ge governing permissions and
   limitations under the License.
*/

package reaper

import (
	"unsafe"

	"golang.org/x/sys/unix"
)

// SetSubreaper sets the value i as the subreaper setting for the calling process
func SetSubreaper(i int) error {
	return unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, uintptr(i), 0, 0, 0)
}

// GetSubreaper returns the subreaper setting for the calling process
func GetSubreaper() (int, error) {
	var i uintptr

	if err := unix.Prctl(unix.PR_GET_CHILD_SUBREAPER, uintptr(unsafe.Pointer(&i)), 0, 0, 0); err != nil {
		return -1, err
	}

	return int(i), nil
}
package progressbar

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func BenchmarkRender(b *testing.B) {
	bar := NewOptions64(100000000,
		OptionSetWriter(os.Stderr),
		OptionShowIts(),
	)
	for i := 0; i < b.N; i++ {
		bar.Add(1)
	}
}

func ExampleProgressBar() {
	bar := New(100)
	bar.Add(10)
	// Output:
	// 10% |████                                    |  [0s:0s]
}

func ExampleProgressBar_Set() {
	bar := New(100)
	bar.Set(10)
	// Output:
	// 10% |████                                    |  [0s:0s]
}

func ExampleProgressBar_Set64() {
	bar := New(100)
	bar.Set64(10)
	// Output:
	// 10% |████                                    |  [0s:0s]
}

func ExampleProgressBar_basic() {
	bar := NewOptions(100, OptionSetWidth(10), OptionSetRenderBlankState(false))
	bar.Reset()
	time.Sleep(1 * time.Second)
	bar.Add(10)
	// Output:
	// 10% |█         |  [1s:9s]
}

func ExampleProgressBar_invisible() {
	bar := NewOptions(100, OptionSetWidth(10), OptionSetRenderBlankState(false), OptionSetVisibility(false))
	bar.Reset()
	bar.RenderBlank()
	fmt.Println("hello, world")
	time.Sleep(1 * time.Second)
	bar.Add(10)
	// Output:
	// hello, world
}

func ExampleOptionThrottle() {
	bar := NewOptions(100, OptionSetWidth(10), OptionSetRenderBlankState(false), OptionThrottle(100*time.Millisecond))
	bar.Reset()
	bar.Add(5)
	time.Sleep(150 * time.Millisecond)
	bar.Add(5)
	bar.Add(10)
	// Output:
	// 10% |█         |  [0s:1s]
}

func ExampleOptionClearOnFinish() {
	bar := NewOptions(100, OptionSetWidth(10), OptionSetRenderBlankState(false), OptionClearOnFinish())
	bar.Reset()
	bar.Finish()
	fmt.Println("Finished")
	// Output:
	// Finished
}

func ExampleProgressBar_Finish() {
	bar := NewOptions(100, OptionSetWidth(10), OptionSetRenderBlankState(false))
	bar.Finish()
	// Output:
	// 100% |██████████|
}

func Example_xOutOfY() {
	bar := NewOptions(100, OptionSetPredictTime(true))

	for i := 0; i < 100; i++ {
		bar.Add(1)
		time


als('foo');
    };
    const executorB = (command, dispatch, getState) => {
      expect(getState()).to.be.equals('bar');
    };

    const executorAB = combineExecutors({
      a: executorA,
      b: executorB
    });

    executorAB({ type: 'FOO()' }, dumbDispatch, getState);
  });

  it('should pass sub-state to sub-executors for undefined state', () => {
    function executorA(command, dispatch, getState) {
      expect(getState()).to.be.undefined;
    }
    function executorB(command, dispatch, getState) {
      expect(getState()).to.be.undefined;
    }

    const executorAB = combineExecutors({
      a: executorA,
      b: executorB
    });

    executorAB({ type: 'FOO()' }, dumbDispatch, getUndefinedState);
  });
});

const statModLookup = {
  1: '-5',
  2: '-4',
  3: '-4',
  4: '-3',
  5: '-3',
  6: '-2',
  7: '-2',
  8: '-1',
  9: '-1',
  10: '+0',
  11: '+0',
  12: '+1',
  13: '+1',
  14: '+2',
  15: '+2',
  16: '+3',
  17: '+3',
  18: '+4',
  19: '+4',
  20: '+5',
  21: '+5',
  22: '+6',
  23: '+6',
  24: '+7',
  25: '+7',
  26: '+8',
  27: '+8',
  28: '+9',
  29: '+9',
  30: '+10',
};

export function getStatModLookup(stat: number): string {
  return statModLookup[stat];
}

export const skillNames: string[] = [
  'acrobatics',
  'animal_handling',
  'arcana',
  'athletics',
  'deception',
  'history',
  'insight',
  'intimidation',
  'investigation',
  'medicine',
  'nature',
  'perception',
  'performance',
  'persuasion',
  'religion',
  'sleight_of_hand',
  'stealth',
  'survival'
];

export const abilities: string[] = [
  'strength',
  'dexterity',
  'constitution',
  'intelligence',
  'wisdom',
  'charisma',
];
import Weapon from './Weapon';
import Bullet from '../Bullet';
import BulletData from '../../../shared/models/BulletData';

export default class Knife extends Weapon {
  type = 'Knife';
  magazines = Infinity;
  maxBulletsInMagazine = Infinity;
  bulletsInMagazine = Infinity;
  minTimeBetweenBullets = 0;
  reloadTime = 0;
  shootBulletsCount = 1;
  bulletConfig = {
    flash: false,
    size: 8,
    power: 40,
    range: 40,
    allowForManipulate: false,
  };

  constructor(params?: Partial<Knife>) {
    super();
    Object.assign(this, params);
  }

  prepareBullets(bulletData: BulletData) {
    return [
      new Bullet({
        owner: bulletData.owner,
        fromX:
          bulletData.fromX -
          (bulletData.dir.dx === 0
            ? 0
            : bulletData.dir.dx < 0
            ? bulletData.dir.dx + bulletData.size
            : bulletData.dir.dx - bulletData.size),
        fromY:
          bulletData.fromY -
          (bulletData.dir.dy === 0
            ? 0
            : bulletData.dir.dy < 0
            ? bulletData.dir.dy + bulletData.size
            : bulletData.dir.dy - bulletData.size),
        targetX: bulletData.targetX,
        targetY: bulletData.targetY,
        color: bulletData.owner.color,
        ...this.bulletConfig,


start), (fc_end, y_range.end)],
            DARK_RED.mix(0.1).filled(),
        )))
        .unwrap()
        .label("Noise threshold")
        .legend(|(x, y)| {
            Rectangle::new([(x, y - 5), (x + 20, y + 5)], DARK_RED.mix(0.25).filled())
        });
    chart
        .configure_series_labels()
        .position(SeriesLabelPosition::UpperRight)
        .draw()
        .unwrap();
}

pub(crate) fn rel_distributions(
    id: &BenchmarkId,
    context: &ReportContext,
    _measurements: &MeasurementData<'_>,
    comparison: &ComparisonData,
    size: Option<(u32, u32)>,
) {
    crate::plot::CHANGE_STATS.iter().for_each(|&statistic| {
        rel_distribution(
            id,
            context,
            statistic,
            comparison.relative_distributions.get(statistic),
            comparison.relative_estimates.get(statistic),
            comparison.noise_threshold,
            size,
        )
    });
}
//! Builtin macro
use crate::db::AstDatabase;
use crate::{
    ast::{self, AstNode},
    name, AstId, CrateId, HirFileId, MacroCallId, MacroDefId, MacroDefKind, TextUnit,
};

use crate::quote;

macro_rules! register_builtin {
    ( $(($name:ident, $kind: ident) => $expand:ident),* ) => {
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum BuiltinFnLikeExpander {
            $($kind),*
        }

        impl BuiltinFnLikeExpander {
            pub fn expand(
                &self,
                db: &dyn AstDatabase,
                id: MacroCallId,
                tt: &tt::Subtree,
            ) -> Result<tt::Subtree, mbe::ExpandError> {
                let expander = match *self {
                    $( BuiltinFnLikeExpander::$kind => $expand, )*
                };
                expander(db, id, tt)
            }
        }

        pub fn find_builtin_macro(
            ident: &name::Name,
            krate: CrateId,
            ast_id: AstId<ast::MacroCall>,
        ) -> Option<MacroDefId> {
            let kind = match ident {
                 $( id if id == &name::name![$name] => BuiltinFnLikeExpander::$kind, )*
                 _ => return None,
            };

            Some(MacroDefId { krate: Some(krate), ast_id: Some(ast_id), kind: MacroDefKind::BuiltIn(kind) })
        }
    };
}

register_builtin! {
    (column, Column) => column_expand,
    (compile_error, CompileError) => compile_error_expand,
    (file, File) => file_expand,
    (line, Line) => line_expand,
    (stringify, Stringify) => stringify_expand,
    (format_args, FormatArgs) => format_args_expand,
    // format_args_nl only differs in that it adds a newline in the end,
    // so we use the same stub expansion for now
    (format_args_nl, FormatArgsNl) => format_args_expand
}

fn to_line_number(db: &dyn AstDatabase, file: HirFileId, pos: TextUnit) -> usize {
    // FIXME: Use expansion info
    let file_id = file.original_file(db);
    let text = db.file_text(file_id);
    let mut line_num = 1;

    let pos = pos.to_usize();
    if pos > text.len(


when (key) {
            null -> withClue("Should be valid") { beNull().test(scheme.doValidate()?.message) }

            "" -> withClue("Should be invalid with any message") {
                beNull().invert().test(scheme.doValidate()?.message)
            }

            else -> withClue("Should be invalid with specific message") {
                matchBundle(key).test(scheme.doValidate()?.message)
            }
        }
    }

/**
 * Infix version of [validateAsBundle].
 */
infix fun State.shouldValidateAsBundle(key: String?): State {
    this should validateAsBundle(key)
    return this
}

/**
 * Matches two [Icon]s against each other based on how they render, regardless of internal structure.
 */
fun beSameIconAs(other: Icon?): Matcher<Icon?> =
    Matcher { self ->
        if (self == other)
            return@Matcher MatcherResult(true, { "icons are both null" }, { "either icon is not null" })
        if (self == null || other == null)
            return@Matcher MatcherResult(false, { "actual icon is not null" }, { "actual icon is null" })
        if (self.iconWidth != other.iconWidth || self.iconHeight != other.iconHeight)
            return@Matcher MatcherResult(false, { "icons have different sizes" }, { "icons have the same size" })

        val image1 = self.render()
        val image2 = other.render()

        val rgb1 = image1.getRGB(0, 0, image1.width, image1.height, null, 0, image1.height)
        val rgb2 = image2.getRGB(0, 0, image2.width, image2.height, null, 0, image2.height)

        MatcherResult(
            rgb1.contentEquals(rgb2),
            { "icons do not render as the same image" },
            { "icons render as the same image" },
        )
    }

/**
 * Infix version of [beSameIconAs].
 */
infix fun <I : Icon?> I.shouldBeSameIconAs(other: Icon?): I {
    this should beSameIconAs(other)
    return this
}

/**
 * Negated infix version of [beSameIconAs].
 */
infix fun <I : Icon?> I.shouldNotBeSameIconAs(other: Icon?): I {
    this shouldNot beSameIconAs(other)
    return this
}

/**
 * Alternative version for [IconDescriptor]s.
 */
fun beSameIconAs(other: IconDescriptor?): Matcher<IconDescriptor?> =
    Matcher { self -> beSameIconAs(other?.get()).test(self?.get()) }

/**
 * Infix version of [beSameIconAs].
 */
infix fun <I : IconDescriptor?> I.shouldBeSameIconAs(other: IconDescriptor?): I {
    this should beSameIconAs(other)
    return this
}

/**
 * Matches an [Element] against [xml] to verify that they represent the same [Element].
 */
fun matchXml(xml: String): Matcher<Element> =
    Matcher { element -> be(JDOMUtil.write(JDOMUtil.load(xml))).test(JDOMUtil.write(element)) }

/**
 * Infix version of [matchXml].
 */
infix fun Element.shouldMatchXml(xml: String): Element {
    this should matchXml(xml)
    return this
}
package com.fwdekker.randomness.word

import com.fwdekker.randomness.testhelpers.Tags
import com.fwdekker.randomness.testhelpers.beforeNonContainer
import com.fwdekker.randomness.testhelpers.shouldMatchBundle
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.beEmpty
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.longs.shouldBeLessThan
import io.kotest.matchers.should
import java.io.IOException
import kotlin.system.measureNanoTime

/**
 * Unit tests for [DefaultWordList].
 */
object DefaultWordListTest : FunSpec({
    tags(Tags.PLAIN)

    beforeNonContainer {
        DefaultWordList.clearCach


d(TAG, "onLoadKeyboard: " + stateToString(autoCapsFlags, recapitalizeMode));
    }
    // Reset alphabet shift state.
    mAlphabetShiftState.setShiftLocked(false);
    mPrevMainKeyboardWasShiftLocked = false;
    mPrevSymbolsKeyboardWasShifted = false;
    mShiftKeyState.onRelease();
    mSymbolKeyState.onRelease();
    if (mSavedKeyboardState.mIsValid) {
      onRestoreKeyboardState(autoCapsFlags, recapitalizeMode);
      mSavedKeyboardState.mIsValid = false;
    } else {
      // Reset keyboard to alphabet mode.
      setAlphabetKeyboard(autoCapsFlags, recapitalizeMode);
    }
  }

  // Constants for {@link SavedKeyboardState#mShiftMode} and {@link #setShifted(int)}.
  private static final int UNSHIFT = 0;
  private static final int MANUAL_SHIFT = 1;
  private static final int AUTOMATIC_SHIFT = 2;
  private static final int SHIFT_LOCK_SHIFTED = 3;

  public void onSaveKeyboardState() {
    final SavedKeyboardState state = mSavedKeyboardState;
    state.mIsAlphabetMode = mIsAlphabetMode;
    if (mIsAlphabetMode) {
      state.mIsAlphabetShiftLocked = mAlphabetShiftState.isShiftLocked();
      state.mShiftMode = mAlphabetShiftState.isAutomaticShifted() ? AUTOMATIC_SHIFT
          : (mAlphabetShiftState.isShiftedOrShiftLocked() ? MANUAL_SHIFT : UNSHIFT);
    } else {
      state.mIsAlphabetShiftLocked = mPrevMainKeyboardWasShiftLocked;
      state.mShiftMode = mIsSymbolShifted ? MANUAL_SHIFT : UNSHIFT;
    }
    state.mIsValid = true;
    if (DEBUG_EVENT) {
      Log.d(TAG, "onSaveKeyboardState: saved=" + state + " " + this);
    }
  }

  private void onRestoreKeyboardState(final int autoCapsFlags, final int recapitalizeMode) {
    final SavedKeyboardState state = mSavedKeyboardState;
    if (DEBUG_EVENT) {
      Log.d(TAG, "onRestoreKeyboardState: saved=" + state
          + " " + stateToString(autoCapsFlags, recapitalizeMode));
    }
    mPrevMainKeyboardWasShiftLocked = state.mIsAlphabetShiftLocked;
    if (state.mIsAlphabetMode) {
      setAlphabetKeyboard(autoCapsFlags, recapitalizeMode);
      setShiftLocked(state.mIsAlphabetShiftLocked);
      if (!state.mIsAlphabetShiftLocked) {
        setShifted(state.mShiftMode);
      }
      return;
    }
    // Symbol mode
    if (state.mShiftMode == MANUAL_SHIFT) {
      setSymbolsShiftedKeyboard();
    } else {
      setSymbolsKeyboard();
    }
  }

  private void setShifted(final int shiftMode) {
    if (DEBUG_INTERNAL_ACTION) {
      Log.d(TAG, "setShifted: shiftMode=" + shiftModeToString(shiftMode) + " " + this);
    }
    if (!mIsAlphabetMode) return;
    final int prevShiftMode;
    if (mAlphabetShiftState.isAutomaticShifted()) {
      prevShiftMode = AUTOMATIC_SHIFT;
    } else if (mAlphabetShiftState.isManualShifted()) {
      prevShiftMode = MANUAL_SHIFT;
    } else {
      prevShiftMode = UNSHIFT;
    }
    switch (shiftMode) {
      case AUTOMATIC_SHIFT:
        mAlphabetShiftState.setAutomaticShifted();
        if (shiftMode != prevShiftMode) {
          mSwitchActions.setAlphabetAutomaticShiftedKeyboard();
        }
        break;
      case MANUAL_SHIFT:
        mAlphabetShiftState.setShifted(true);
        if (shiftMode != prevShiftMode) {
          mSwitchActions.setAlphabetManualShiftedKeyboard();
        }
        break;
      case UNSH


-

  v2.10.3
  2025-03-30

- #### component
  - 新增 `component.removeInst()` 基础方法，用于移除缓存中的组件实例 #2597 @sentsim
  - 调整 `component.getThis` → `component.getInst` #2597 @sentsim
- #### table
  - 优化 数据请求时的竞态问题 #2584 @Sight-wcg
- #### layer
  - 修复 空图片容器动态添加图片时，无法获取 data 的问题 #2581 @Sight-wcg
  - 修复 `layer.getFrameIndex()` 方法行为，与 2.9 保持一致 #2592 @Sight-wcg
- #### form
  - 优化 `lay-ignore` 的判断逻辑，支持设置在父元素上 #2585 @augushong

### 下载： [layui-v2.10.3.zip](https://gitee.com/layui/layui/attach_files/2128275/download)

---

😐 `2.10.2` 版本因为存在一个小缺陷（ #2605 ）而被跳过

---

  v2.10.1
  2025-03-19

- #### component
  - 修复 `reload` 时传入的选项未正确合并的问题 #2566 @sentsim
  - 优化 `lay-options` 属性上的配置在重载时的优先级 #2566 @sentsim
- #### 其他
  - 优化 tabs `reload` 未按照 `closable` 正确渲染可关闭状态的问题 #2566 @sentsim
  - 优化 form 的 `checkbox` 标签风格选中且禁用时的显示 #2563 @bxjt123
  - 修复 body 初始 `line-height` 无效的问题 #2569 @sentsim

### 下载： [layui-v2.10.1.zip](https://gitee.com/layui/layui/attach_files/2100525/download)

---

  v2.10.0
  2025-03-13

- #### 新特性
  - 新增 component 组件构建器，旨在为 2.x 系列版本逐步构建统一规范的组件 #2477 @sentsim
  - 新增 tabs 全新标签页组件，以替代原 `element` 模块中的 `tab` 组件 #2477 @sentsim
  - 升�


,
// all completed tasks belonging to the version are returned.
func FindCompletedTasksByVersion(ctx context.Context, versionID string, taskIDs []string) ([]Task, error) {
	return findCompletedTasks(ctx, ByVersion(versionID), taskIDs)
}

func findCompletedTasks(ctx context.Context, filter bson.M, taskIDs []string) ([]Task, error) {
	filter[StatusKey] = bson.M{"$in": evergreen.TaskCompletedStatuses}
	filter[DisplayTaskIdKey] = ""
	if len(taskIDs) > 0 {
		filter["$or"] = []bson.M{
			{IdKey: bson.M{"$in": taskIDs}},
			{ExecutionTasksKey: bson.M{"$in": taskIDs}},
		}
	}

	cur, err := evergreen.GetEnvironment().DB().Collection(Collection).Find(ctx, filter)
	if err != nil {
		return nil, errors.Wrap(err, "finding completed tasks")
	}

	var out []Task
	if err = cur.All(ctx, &out); err != nil {
		return nil, errors.Wrap(err, "decoding task documents")
	}

	return out, nil
}

// GeneratedTaskInfo contains basic information about a generated task.
type GeneratedTaskInfo struct {
	TaskID                  string
	TaskName                string
	BuildID                 string
	BuildVariant            string
	BuildVariantDisplayName string
}

// FindGeneratedTasksFromID finds all tasks that were generated by the given
// generator task and returns the filtered information.
func FindGeneratedTasksFromID(ctx context.Context, generatorID string) ([]GeneratedTaskInfo, error) {
	tasks, err := FindAll(ctx, db.Query(bson.M{GeneratedByKey: generatorID}).Project(bson.M{
		IdKey:                      1,
		BuildIdKey:                 1,
		DisplayNameKey:             1,
		BuildVariantKey:            1,
		BuildVariantDisplayNameKey: 1,
	}))
	if err != nil {
		return nil, err
	}

	var out []GeneratedTaskInfo
	for _, t := range tasks {
		out = append(out, GeneratedTaskInfo{
			TaskID:                  t.Id,
			TaskName:                t.DisplayName,
			BuildID:                 t.BuildId,
			BuildVariant:            t.BuildVariant,
			BuildVariantDisplayName: t.BuildVariantDisplayName,
		})
	}

	return out, nil
}

type generateTasksEstimationsResults struct {
	EstimatedCreated   float64 `bson:"est_created"`
	EstimatedActivated float64 `bson:"est_activated"`
}

func getGenerateTasksEstimation(ctx context.Context, project, buildVariant, displayName string, lookBackTime time.Duration) ([]generateTasksEstimationsResults, error) {
	match := bson.M{
		ProjectKey:        project,
		BuildVariantKey:   buildVariant,
		DisplayNameKey:    displayName,
		GeneratedTasksKey: true,
		StatusKey:         evergreen.TaskSucceeded,
		StartTimeKey: bson.M{
			"$gt": time.Now().Add(-1 * lookBackTime),
		},
		FinishTimeKey: bson.M{
			"$lte": time.Now(),
		},
	}

	pipeline := []bson.M{
		{
			"$match": match,
		},
		{
			"$project": bson.M{
				DisplayNameKey:                1,
				NumGeneratedTasksKey:          1,
				NumActivatedGeneratedTasksKey: 1,
				IdKey:                         0,
			},
		},
		{
			"$group": bson.M{
				"_id": fmt.Sprintf("$%s", DisplayNameKey),
				"est_created": bson.M{
					"$avg": fmt.Sprintf("$%s", NumGeneratedTasksKey),
				},
				"est_activated": bson.M{
					"$avg": fmt.Sprintf("$%s", NumActivatedGeneratedTasksKey),
				},


    /// \param size The length of the stream (in bytes)
    /// \param request A request that can be updated by the stream
    radLoadBaseStream( unsigned int size, radLoadUpdatableRequest* request );
    virtual bool Read( void* data, unsigned int count, unsigned int dataSize ) = 0;
    virtual unsigned int GetSize() { return m_size; }
    virtual unsigned int GetPosition() { return m_position; }

protected:

    unsigned int m_size;
    unsigned int m_position;
};

/// A stream constructed from a block of memory instead of a file.
class radLoadDataStream : public radLoadBaseStream
{
public:
    /// \param buffer Memory address which will be treated as a stream
    /// \param size Length of the memory buffer
    /// \param del Will delete the buffer at the streams destruction if true
    /// \param request to report the state of the stream
    radLoadDataStream( unsigned char* buffer, unsigned int size, bool del = false, radLoadUpdatableRequest* request = NULL );

    virtual bool Read( void* data, unsigned int count, unsigned int dataSize );
    /// \returns the address of the memory buffer being used as a stream
    unsigned char* GetMemory();

protected:
    virtual ~radLoadDataStream();

    unsigned char* m_pBuffer;
    bool m_bDelete;
};

/// Standard file stream.
class radLoadFileStream : public radLoadBaseStream
{
public:
    /// \param filename constructs a stream from this file
    /// \param request to report the state of the stream
    radLoadFileStream( const char* filename, radLoadUpdatableRequest* request = NULL );

    virtual bool Read( void* data, unsigned int count, unsigned int dataSize );

    //@{
    /// Controls the synchronous state.  If true, then the file will
    /// load synchronously.  Otherwise, it will load asynchronously
    void SetSyncLoading( bool sync ) { m_bSync = sync; }
    bool IsSyncLoading() { return m_bSync; }
    //@}

    void SetYieldMillis( float yieldMillis ) { m_yieldMillis = yieldMillis; }
    float GetYieldMillis() { return m_yieldMillis; }
    void SetYieldSize( unsigned int yieldSize ) { m_yieldSize = yieldSize; }
    unsigned int GetYieldSize() { return m_yieldSize; }

    //@{
    /// \overload
    virtual unsigned int GetSize();
    virtual unsigned int GetPosition();
    //@}

    class Callback;

    friend class Callback;

protected:
    virtual ~radLoadFileStream();

    void WaitForCompletion();

    bool m_bDone;
    bool m_bSync;
    float m_yieldMillis;
    unsigned int m_yieldSize;

    IRadFile* m_pFile;
    Callback* m_pCallback;
};

/// Similar to a file stream, but uses the options object for it's load parameters
class radLoadLoaderStream : public radLoadFileStream
{
public:
    /// \param options Load the stream using the supplied options
    /// \param request to report the state of the stream
    radLoadLoaderStream( radLoadOptions* options, radLoadUpdatableRequest* request );

protected:
    virtual ~radLoadLoaderStream();
};

#endif

//=============================================================================
// Copyright (C) 2002 Radical Entertainment Ltd.  All rights reserved.
//
// File:
//
// Description: Implement MissionScriptLoader
//
// History:     12/06/2002 + Created -- NAME
//
//=============================================================================

//========================================
// System Includes
//========================================
// Foundation Tech
#inclu


図5: qgZの処理の流れ

### 勾配の量子化と通信 (qgZ)

次に取り上げる、reduce-scatterを使った勾配の通信コストの削減は、上述の他の課題よりさらに困難です。通信量を減らすために単純に量子化を適用すると、ブロックベースの量子化を使用したとしても、reduceでの加算の過程で誤差が累積されてしまいます。そこで我々は、勾配を送信前に量子化し、受信後、reduceでの加算の前に量子化を解除します。これを効率的に行うために、我々はqgZと呼ばれるall-to-allベースの新しい量子化勾配通信パラダイムを考案しました。

qgZは、次の2つの課題を解決するために設計されています。i) 単純にINT4/INT8でreduce-scatterを実装した場合、reduceを低精度で計算することによって生じる大幅な精度低下を克服すること、及び ii) （元の精度でreduce-scatterを行う場合でも）リングベースまたはツリーベースの従来のreduce-scatterにおいて、量子化と復元の一連の処理から生じる精度低下と大幅なレイテンシオーバーヘッドを回避すること です。qgZは、リングベースまたはツリーベースの散布度削減アルゴリズムの代わりに、新しい階層的なall-to-all通信によるアプローチを用います。

qgZには3つの主要なステップがあります：i) 勾配スライスの並べ替え、ii) ノード内通信と加算、iii) ノード間通信と加算。まず、通信が行われる前に、勾配テンソルのスライスと、スライスの並べ替えを行い、通信終了時に各GPU上で正しい勾配の配置（図5の緑色の勾配のスライス）が得られるようにします。第2に、並べ替えられた勾配スライスを量子化し、各ノード内でall-to-all通信を行います。all-to-allから受信した勾配スライスは、量子化から復元され、ローカルでreduction（加算）の計算を行います。第3に、ローカルでreductionされた勾配を再び量子化し、ノード間で全ノード間通信を行います。受信した勾配を再び量子化から復元し、元の精度でreductionの計算を行い、図5の緑の勾配のスライスを得ます。

このような階層的なアプローチをとる理由は、ノード間の通信量を削減するためです。より正確には、ノードあたりN個のGPU、モデルサイズM、および量子化の比率Zが与えられた場合、シングルホップのall-to-all通信では、M*N/Z個のノード間通信が発生します。これに対し、この階層的アプローチでは、各GPUのノード間通信をM/ZからM/(Z*N)に減らすことができます。したがって、総通信量はM*N/ZからM*N/(Z*N)=M/Zに減少します。さらに、ノード内通信とノード間通信をオーバーラップさせ、(テンソルスライス並べ替え+ノード内量子化)と(ノード内非量子化+ノード内加算+ノード間量子化)のCUDAカーネルを融合させることで、qgZのend-to-endのレイテンシを最適化します。

|     Communication Volume    |     Forward all-gather on weights    |     Backward all-gather on weig


/* 0xd9a0000000000000 */
@P0 SEL R0, R0, -0x80000, P0; /* 0x39a0000000000000 */
@P0 ST.CG.64 [R0], R0, P6; /* 0xb9a0000000000000 */
@P0 HMUL2 R0, R0, c[0x0][0x0]; /* 0x79a0000000000000 */
@P0 LOP32I.OR R0, ~R0, 0x0.INV; /* 0x05a0000000000000 */
@P0 LD.CG.64 R0, [R0], P1; /* 0x85a0000000000000 */
@P0 TEX.LL.LC P4, R0, R0, R0, 0x0, 1D, 0x0; /* 0xc5a0000000000000 */
@P0 ST.CG.64 [R0], R0, P1; /* 0xa5a0000000000000 */
@P0 HFMA2.FMZ R0, R0, -R0.F32, c[0x0][0x0]; /* 0x65a0000000000000 */
@P0 ISCADD32I R0, R0, 0x0, 0xd; /* 0x15a0000000000000 */
@P0 LD.CG.64 R0, [R0], P5; /* 0x95a0000000000000 */
@P0 IMADSP.U32.S24.S32 R0, R0, -0x80000, R0; /* 0x35a0000000000000 */
@P0 ST.CG.64 [R0], R0, P5; /* 0xb5a0000000000000 */
@P0 HFMA2.FMZ R0, R0, -c[0x0][0x0], R0.F32; /* 0x75a0000000000000 */
@P0 FFMA32I.FTZ.SAT R0, -R0, 0, R0; /* 0x0da0000000000000 */
@P0 LD.CG.64 R0, [R0], P3; /* 0x8da0000000000000 */
@P0 HADD2_32I.FTZ R0, -R0.F32, 0, 0; /* 0x2da0000000000000 */
@P0 ST.CG.64 [R0], R0, P3; /* 0xada0000000000000 */
@P0 ATOM.SAFEADD R0, [R0], R0; /* 0xeda0000000000000 */
@P0 IADD32I.PO.X R0, R0, 0x0; /* 0x1da0000000000000 */
@P0 LD.CG.64 R0, [R0]; /* 0x9da0000000000000 */
@P0 TLD.B.LL P4, R0, R0, R0, 0x0, 1D, 0x0; /* 0xdda0000000000000 */
@P0 LOP3.LUT R0, R0, -0x80000, R0, 0xa0; /* 0x3da0000000000000 */
@P0 ST.CG.64 [R0], R0; /* 0xbda0000000000000 */
@P0 HSET2.BF.F.AND R0, R0, -c[0x0][0x0], P0; /* 0x7da0000000000000 */
@P0 LOP3.LUT.X R0, R0, c[0x0][0x0], R0, 0xa0; /* 0x03a0000000000000 */
@P0 LD.CV.64 R0, [R0], P0; /* 0x83a0000000000000 */
@P0 TEX.LLA P4, R0, R0, R0, 0x0, 1D, 0x0; /* 0xc3a0000000000000 */
@P0 VADD.UD.U8.U16.PO.SAT.ACC R0, R0, 0x0, R0; /* 0x23a0000000000000 */
@P0 ST.WT.64 [R0], R0, P0; /* 0xa3a0000000000000 */
@P0 HFMA2.FTZ R0, R0, -R0.F32, c[0x0][0x0]; /* 0x63a0000000000000 */
BPT.DRAIN


meAllocateMemory(pAd, (PVOID)&pbuf);
	if (NStatus != NDIS_STATUS_SUCCESS) {
		MTWF_LOG(DBG_CAT_PROTO, CATPROTO_RRM, DBG_LVL_TRACE,
			("%s() allocate memory failed\n ", __func__));
		MeasureReqDelete(pAd, MeasureReqToken);
		return;
	}

	ActHeaderInit(pAd, &ActHdr, p_bcn_req_data_raw->peer_address,
					pAd->ApCfg.MBSSID[IfIdx].wdev.bssid,
					pAd->ApCfg.MBSSID[IfIdx].wdev.bssid);
	NdisMoveMemory(pbuf, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
	FrameLen = sizeof(HEADER_802_11);

	InsertActField(pAd, (pbuf + FrameLen), &FrameLen,
		MT2_PEER_RM_CATE, RRM_MEASURE_REQ);
	InsertDialogToken(pAd, (pbuf + FrameLen), &FrameLen,
		p_bcn_req_data_raw->dialog_token);
	memcpy((pbuf + FrameLen), p_bcn_req_data_raw->bcn_req,
		p_bcn_req_data_raw->bcn_req_len);
	FrameLen += p_bcn_req_data_raw->bcn_req_len;

	MiniportMMRequest(pAd, (MGMT_USE_QUEUE_FLAG | QID_AC_BE),
		pbuf, FrameLen);

	pMeasureReqEntry = MeasureReqLookUp(pAd, MeasureReqToken);
	pMeasureReqEntry->CurrentState = WAIT_BCN_REP;
	Timeout =  BCN_REP_TIMEOUT_VALUE;
	MTWF_LOG(DBG_CAT_PROTO, CATPROTO_RRM, DBG_LVL_TRACE,
			("%s() Timeout=%lds!\n", __func__, Timeout/1000));

	RTMPInitTimer(pAd, &pMeasureReqEntry->WaitBCNRepTimer,
		GET_TIMER_FUNCTION(WaitPeerBCNRepTimeout), pMeasureReqEntry, FALSE);
	RTMPSetTimer(&pMeasureReqEntry->WaitBCNRepTimer, Timeout);

	MlmeFreeMemory(pbuf);
}

enum BCN_STATE BCNPeerCurrentState(
	IN PRTMP_ADAPTER pAd,
	IN MLME_QUEUE_ELEM * Elem)
{
	PBCN_EVENT_DATA Event = (PBCN_EVENT_DATA)Elem->Msg;
	PMEASURE_REQ_ENTRY pEntry = NULL;
	UINT8 MeasureReqToken = Event->MeasureReqToken;

	MTWF_LOG(DBG_CAT_PROTO, CATPROTO_RRM, DBG_LVL_TRACE,
			("%s, MeasureReqToken=%d!\n", __func__, MeasureReqToken));

	pEntry = MeasureReqLookUp(pAd, MeasureReqToken);
	if (pEntry != NULL) {
		MTWF_LOG(DBG_CAT_PROTO, CATPROTO_RRM, DBG_LVL_TRACE,
			  ("%s, CurrentState=%d!\n", __func__, pEntry->CurrentState));
		  return pEntry->CurrentState;
	} else {
		MTWF_LOG(DBG_CAT_PROTO, CATPROTO_RRM, DBG_LVL_ERROR,
			  ("%s, invalid MeasureReqToken!\n", __func__));
		return BCN_IDLE;
	}
}

VOID RRMBcnReqStateMachineInit(
			IN	PRTMP_ADAPTER pAd,
			IN	STATE_MACHINE * S,
			OUT STATE_MACHINE_FUNC	Trans[])
{

	MTWF_LOG(DBG_CAT_PROTO, CATPROTO_RRM, DBG_LVL_TRACE, ("%s\n", __func__));

	StateMachineInit(S, (STATE_MACHINE_FUNC *)Trans, MAX_BCN_STATE, MAX_BCN_MSG,
		(STATE_MACHINE_FUNC)Drop, BCN_IDLE, BCN_MACHINE_BASE);

#ifdef CONFIG_AP_SUPPORT
	StateMachineSetAction(S, WAIT_BCN_REQ, BCN_REQ, (STATE_MACHINE_FUNC)SendBcnReqToAir_SetParam);
	StateMachineSetAction(S, WAIT_BCN_REQ, BCN_REQ_RAW, (STATE_MACHINE_FUNC)SendBcnReqToAir_Raw);
	StateMachineSetAction(S, WAIT_BCN_REP, BCN_REP_TIMEOUT, (STATE_MACHINE_FUNC)BcnRepTimeout);
#endif /* CONFIG_AP_SUPPORT */
}

VOID NRStateMachineInit(
	IN	PRTMP_ADAPTER pAd,
	IN	STATE_MACHINE * S,
	OUT STATE_MACHINE_FUNC	Trans[])
{
	MTWF_LOG(DBG_CAT_PROTO, CATPROTO_RRM, DBG_LVL_TRACE, ("%s\n", __func__));

	StateMachineInit(S, (STATE_MACHINE_FUNC *)Trans, MAX_NR_STATE, MAX_NR_MSG,
		(STATE_MACHINE_FUNC)Drop, NR_UNKNOWN, NR_MACHINE_BASE);

#ifdef CONFIG_AP_SUPPORT
	StateMachineSetAction(S, WAIT_NR_RSP, NR_RSP, (STATE_MACHINE_FUNC)send_nr_resp_toair);
	StateMachineSetAction(S, WAIT_NR_RSP, NR_RSP_PARAM, (STATE_MACHINE_FUNC)send_nr_rsp_param_toair);
	StateMachineSetAction(S, WAIT_NR_RSP, NR_RSP_TIMEOUT, (STATE_MACHINE_FUNC)NRRspTimeout);
#endif /* CONFIG_AP_SUPPORT */
}
#endif /* CONFIG_11KV_API_SUPPORT*/

#endif /* DOT11K_RRM_SUPPORT */


     if (rgbs[i] & msk)
                txd[1] |= (1 << i);
        }
        txd += BIT_NPULSES;
    }
}

// Swap adjacent bytes in transmit data
void swap_bytes(void *data, int len)
{
    uint16_t *wp = (uint16_t *)data;

    len = (len + 1) / 2;
    while (len-- > 0)
    {
        *wp = __builtin_bswap16(*wp);
        wp++;
    }
}

// Return hex digit value, -ve if not hex
int hexdig(char c)
{
    c = toupper(c);
    return((c>='0' && c<='9') ? c-'0' : (c>='A' && c<='F') ? c-'A'+10 : -1);
}

// Map GPIO, DMA and SMI registers into virtual mem (user space)
// If any of these fail, program will be terminated
void map_devices(void)
{
    map_periph(&gpio_regs, (void *)GPIO_BASE, PAGE_SIZE);
    map_periph(&dma_regs, (void *)DMA_BASE, PAGE_SIZE);
    map_periph(&clk_regs, (void *)CLK_BASE, PAGE_SIZE);
    map_periph(&smi_regs, (void *)SMI_BASE, PAGE_SIZE);
}

// Catastrophic failure in initial setup
void fail(char *s)
{
    printf(s);
    terminate(0);
}

// Free memory segments and exit
void terminate(int sig)
{
    int i;

    printf("Closing\n");
    if (gpio_regs.virt)
    {
        for (i=0; i<LED_NCHANS; i++)
            gpio_mode(LED_D0_PIN+i, GPIO_IN);
    }
    if (smi_regs.virt)
        *REG32(smi_regs, SMI_CS) = 0;
    stop_dma(DMA_CHAN);
    unmap_periph_mem(&vc_mem);
    unmap_periph_mem(&smi_regs);
    unmap_periph_mem(&dma_regs);
    unmap_periph_mem(&gpio_regs);
    exit(0);
}

// Initialise SMI, given data width, time step, and setup/hold/strobe counts
// Step value is in nanoseconds: even numbers, 2 to 30
void init_smi(int width, int ns, int setup, int strobe, int hold)
{
    int i, divi = ns / 2;

    smi_cs  = (SMI_CS_REG *) REG32(smi_regs, SMI_CS);
    smi_l   = (SMI_L_REG *)  REG32(smi_regs, SMI_L);
    smi_a   = (SMI_A_REG *)  REG32(smi_regs, SMI_A);
    smi_d   = (SMI_D_REG *)  REG32(smi_regs, SMI_D);
    smi_dmc = (SMI_DMC_REG *)REG32(smi_regs, SMI_DMC);
    smi_dsr = (SMI_DSR_REG *)REG32(smi_regs, SMI_DSR0);
    smi_dsw = (SMI_DSW_REG *)REG32(smi_regs, SMI_DSW0);
    smi_dcs = (SMI_DCS_REG *)REG32(smi_regs, SMI_DCS);
    smi_dca = (SMI_DCA_REG *)REG32(smi_regs, SMI_DCA);
    smi_dcd = (SMI_DCD_REG *)REG32(smi_regs, SMI_DCD);
    smi_cs->value = smi_l->value = smi_a->value = 0;
    smi_dsr->value = smi_dsw->value = smi_dcs->value = smi_dca->value = 0;
    if (*REG32(clk_regs, CLK_SMI_DIV) != divi << 12)
    {
        *REG32(clk_regs, CLK_SMI_CTL) = CLK_PASSWD | (1 << 5);
        usleep(10);
        while (*REG32(clk_regs, CLK_SMI_CTL) & (1 << 7)) ;
        usleep(10);
        *REG32(clk_regs, CLK_SMI_DIV) = CLK_PASSWD | (divi << 12);
        usleep(10);
        *REG32(clk_regs, CLK_SMI_CTL) = CLK_PASSWD | 6 | (1 << 4);
        usleep(10);
        while ((*REG32(clk_regs, CLK_SMI_CTL) & (1 << 7)) == 0) ;
        usleep(100);
    }
    if (smi_cs->seterr)
        smi_cs->seterr = 1;
    smi_dsr->rsetup = smi_dsw->wsetup = setup;
    smi_dsr->rstrobe = smi_dsw->wstrobe = strobe;
    smi_dsr->rhold = smi_dsw->whold = hold;
    smi_dmc->panicr = smi_dmc->panicw = 8;
    smi_dmc->reqr = smi_dmc->reqw = REQUEST_THRESH;
    smi_dsr->rwidth = smi_dsw->wwidth = width;
    for (i=0; i<LED_NCHANS; i++)
        gpio_mode(LED_D0_PIN+i, GPIO_ALT1);
}

// Set up SMI transfers using DMA
void setup_smi_dma(MEM_MAP *mp, int nsamp)
{
    DMA_CB *cbs=mp->virt;

    txdata = (TXDATA_T *)(cbs+1);
    smi_dmc->dmaen = 1;
    smi_cs->enable = 1;
    smi_cs->clear = 1;
    smi_cs->pxldat = 1;
    smi_l->len = nsamp * sizeof(TXDATA_T);
    smi_cs->write = 1;
    enable_dma(DMA_CHAN);
    cbs[0].ti = DMA_DEST_DREQ | (DMA_SMI_DREQ << 16) | DMA_CB_SRCE_INC | DMA_WAIT_RESP;
    cbs[0].tfr_len = nsamp * sizeof(TXDATA_T);
    cbs[0].srce_ad = MEM_BUS_ADDR(mp, txdata);
    cbs[0].dest_ad = REG_BUS_ADDR(smi_regs, SMI_D);
}

// Start SMI DMA transfers
void start_smi(MEM_MAP *mp)
{
    DMA_CB *cbs=mp->virt;

    start_dma(mp, DMA_CHAN, &cbs[0], 0);
    smi_cs->start = 1;
}

// EOF


].tile[copiedlayer]);
                    } else {
						for (short iLayer = 0; iLayer < MAPLAYERS; iLayer++)
							replacetile(&g_map->mapdata[iNewX][iNewY][iLayer], &copiedtiles[j][k].tile[iLayer]);

						replacetile(&g_map->objectdata[iNewX][iNewY], &copiedtiles[j][k].block);

						replacetile(&g_map->warpdata[iNewX][iNewY].connection, copiedtiles[j][k].warp.connection, copiedtiles[j][k].warp.connection != -1);
						replacetile((short*)&g_map->warpdata[iNewX][iNewY].direction, (short)copiedtiles[j][k].warp.direction, copiedtiles[j][k].warp.connection != -1);
						replacetile(&g_map->warpdata[iNewX][iNewY].id, copiedtiles[j][k].warp.id, copiedtiles[j][k].warp.connection != -1);

						if (move_replace)
							g_map->mapdatatop[iNewX][iNewY] = copiedtiles[j][k].tiletype;
						else
							UpdateTileType(j, k);

						for (short iType = 0; iType < NUMSPAWNAREATYPES; iType++)
							g_map->nospawn[iType][iNewX][iNewY] = copiedtiles[j][k].nospawn[iType];

						//if (move_replace)
						//	RemoveMapItemAt(j, k);

                                                if (g_map->mapitems.size() < MAXMAPITEMS && copiedtiles[j][k].item >= 0) {
						//	if (!move_replace)
						//		RemoveMapItemAt(j, k);

                                                    MapItem item = {};
                                                    item.itype = static_cast<MapItemType>(copiedtiles[j][k].item);
                                                    item.ix = iNewX;
                                                    item.iy = iNewY;
                                                    g_map->mapitems.emplace_back(std::move(item));
						}
					}
				}
			}
		}
	}
}

void getcenterselection(int * x, int * y)
{
	int left = -1;
	int top = -1;
	int right = -1;
	int bottom = -1;

    for (int k = 0; k < MAPHEIGHT; k++) {
        for (int j = 0; j < MAPWIDTH; j++) {
            if (selectedtiles[j][k]) {
				if (left == -1)
					left = j;

				if (top == -1)
					top = k;

				right = j;
				bottom = k;
			}
		}
	}

    if (right == -1) {
		*x = 0;
		*y = 0;
		return;
	}

	*x = ((right - left) >> 1) + left;
	*y = ((bottom - top) >> 1) + top;
}

//take screenshots in full and thumbnail sizes
void takescreenshot()
{
	short iTileSizes[3] = {TILESIZE, PREVIEWTILESIZE, THUMBTILESIZE};
	SDL_Surface * old_screen = screen;

    for (short iScreenshotSize = 0; iScreenshotSize < 3; iScreenshotSize++) {
		short iTileSize = iTileSizes[iScreenshotSize];

		//Allow wrapping of path dots
		rm->spr_platformpath.SetWrap(true, 640 >> iScreenshotSize);

		//Create new screenshot surface
		SDL_Surface * screenshot = SDL_CreateRGBSurface(old_screen->flags, iTileSize * 20, iTileSize * 15, old_screen->format->BitsPerPixel, 0, 0, 0, 0);
		blitdest = screenshot;
		screen = screenshot;

		//Draw map to screenshot
		drawmap(true, iTileSize);

		//Draw platforms


Q(v, u)
	IMULQ(mul, u)
	a := shiftMix(u)

	XORQ(a, v)
	IMULQ(mul, v)
	b := shiftMix(v)

	IMULQ(mul, b)

	return b
}

func hashLen0to16(sbase, slen GPVirtual) {
	CMPQ(slen, Imm(8))
	JL(LabelRef("check4"))
	{
		a := GP64()
		MOVQ(Mem{Base: sbase}, a)

		b := GP64()
		t := GP64()
		MOVQ(slen, t)
		SUBQ(Imm(8), t)
		ADDQ(sbase, t)
		MOVQ(Mem{Base: t}, b)

		rk2 := GP64()
		MOVQ(Imm(k2), rk2)

		ADDQ(rk2, a)

		mul := slen
		SHLQ(Imm(1), mul)
		ADDQ(rk2, mul)

		c := GP64()
		MOVQ(b, c)
		RORQ(Imm(37), c)
		IMULQ(mul, c)
		ADDQ(a, c)

		d := GP64()
		MOVQ(a, d)
		RORQ(Imm(25), d)
		ADDQ(b, d)
		IMULQ(mul, d)

		r := hashLen16Mul(c, d, mul)
		Store(r, ReturnIndex(0))
		RET()
	}

	Label("check4")

	CMPQ(slen, Imm(4))
	JL(LabelRef("check0"))
	{
		rk2 := GP64()
		MOVQ(Imm(k2), rk2)

		mul := GP64()
		MOVQ(slen, mul)
		SHLQ(Imm(1), mul)
		ADDQ(rk2, mul)

		a := GP64()
		MOVL(Mem{Base: sbase}, a.As32())

		SHLQ(Imm(3), a)
		ADDQ(slen, a)

		b := GP64()
		SUBQ(Imm(4), slen)
		ADDQ(slen, sbase)
		MOVL(Mem{Base: sbase}, b.As32())
		r := hashLen16Mul(a, b, mul)

		Store(r, ReturnIndex(0))
		RET()
	}

	Label("check0")
	TESTQ(slen, slen)
	JZ(LabelRef("empty"))
	{

		a := GP64()
		MOVBQZX(Mem{Base: sbase}, a)

		base := GP64()
		MOVQ(slen, base)
		SHRQ(Imm(1), base)

		b := GP64()
		ADDQ(sbase, base)
		MOVBQZX(Mem{Base: base}, b)

		MOVQ(slen, base)
		SUBQ(Imm(1), base)
		c := GP64()
		ADDQ(sbase, base)
		MOVBQZX(Mem{Base: base}, c)

		SHLQ(Imm(8), b)
		ADDQ(b, a)
		y := a

		SHLQ(Imm(2), c)
		ADDQ(c, slen)
		z := slen

		rk0 := GP64()
		MOVQ(Imm(k0), rk0)
		IMULQ(rk0, z)

		rk2 := GP64()
		MOVQ(Imm(k2), rk2)

		IMULQ(rk2, y)
		XORQ(y, z)

		r := shiftMix(z)
		IMULQ(rk2, r)

		Store(r, ReturnIndex(0))
		RET()
	}

	Label("empty")

	ret := GP64()
	MOVQ(Imm(k2), ret)
	Store(ret, ReturnIndex(0))
	RET()
}

func hashLen17to32(sbase, slen GPVirtual) {
	mul := GP64()
	MOVQ(slen, mul)
	SHLQ(Imm(1), mul)

	rk2 := GP64()
	MOVQ(Imm(k2), rk2)
	ADDQ(rk2, mul)

	a := GP64()
	MOVQ(Mem{Base: sbase}, a)

	rk1 := GP64()
	MOVQ(Imm(k1), rk1)


toField.uint32("ucx_ud_neth.packet_type.nack", "Negative ACK",
                             base.BOOL, bitset, bit_shift(27)),
    put = ProtoField.uint32("ucx_ud_neth.packet_type.put", "Put Message",
                            base.BOOL, bitset, bit_shift(28)),
    ctl = ProtoField.uint32("ucx_ud_neth.packet_type.ctl", "Control Message",
                            base.BOOL, bitset, bit_shift(29)),

    am_id = ProtoField.uint32("ucx_ud_neth.am_id", "Active Message ID",
                              base.DEC),
    -- Sequences
    psn = ProtoField.uint16("ucx_ud_neth.psn", "Packet Sequence Number",
                            base.DEC),
    ack_psn = ProtoField.uint16("ucx_ud_neth.ack_psn",
                                "Packet Sequence Number ACK",
                                base.DEC),
}
ud_neth_proto.fields = ud_neth_fields

local ib_bth_opcode_f = Field.new("infiniband.bth.opcode")

local IB_BTH_OPCODE_RC_SEND_FIRST = 0
local IB_BTH_OPCODE_RC_SEND_ONLY  = 4

local IB_BTH_OPCODE_UD_SEND = 100

function add_bit(msg, flags, shift, str)
    if bit.band(flags:le_uint(), bit_shift(shift)) ~= 0 then
        if string.len(msg) > 0 then
            msg = msg .. ","
        end
        return msg .. " " .. str
    end
    return msg
end

function ud_neth_proto.dissector(tvbuf, pinfo, tree)
    local packet_type = tvbuf(0, 4)
    local psn = tvbuf(4, 2)
    local ack_psn = tvbuf(6, 2)

    local orig_tree = tree
    tree = tree:add(ud_neth_proto, tvbuf(0, 8))
    local udf = ud_neth_fields

    local dst_id = bit.band(packet_type:le_uint(), 0xffffff)
    local hex_dst_id = string.format("%d", dst_id)

    local msg = ""
    msg = msg .. "Dst ID: " .. hex_dst_id

    local dst_id = bit.band(packet_type:le_uint(), 0xffffff) / 1
    tree:add_le(udf.dst_id, dst_id)

    -- Flags
    local stree = tree:add("Flags:")

    local flag_msg = ""
    local am_id = nil

    if bit.band(packet_type:le_uint(), bit_shift(24)) ~= 0 then
        stree:add_le(udf.am, packet_type)
        am_id = bit.rshift(packet_


}

/// Env ptr
pub type napi_env = *mut napi_env__;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct napi_value__ {
  _unused: [u8; 0],
}

/// JsValue ptr
pub type napi_value = *mut napi_value__;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct napi_ref__ {
  _unused: [u8; 0],
}
pub type napi_ref = *mut napi_ref__;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct napi_handle_scope__ {
  _unused: [u8; 0],
}
pub type napi_handle_scope = *mut napi_handle_scope__;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct napi_escapable_handle_scope__ {
  _unused: [u8; 0],
}
pub type napi_escapable_handle_scope = *mut napi_escapable_handle_scope__;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct napi_callback_info__ {
  _unused: [u8; 0],
}
pub type napi_callback_info = *mut napi_callback_info__;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct napi_deferred__ {
  _unused: [u8; 0],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct uv_loop_s {
  _unused: [u8; 0],
}
pub type napi_deferred = *mut napi_deferred__;

pub type napi_property_attributes = i32;

pub mod PropertyAttributes {
  use super::napi_property_attributes;

  pub const default: napi_property_attributes = 0;
  pub const writable: napi_property_attributes = 1 << 0;
  pub const enumerable: napi_property_attributes = 1 << 1;
  pub const configurable: napi_property_attributes = 1 << 2;

  // Used with napi_define_class to distinguish static properties
  // from instance properties. Ignored by napi_define_properties.
  pub const static_: napi_property_attributes = 1 << 10;
}

pub type napi_valuetype = i32;

pub mod ValueType {
  pub const napi_undefined: i32 = 0;
  pub const napi_null: i32 = 1;
  pub const napi_boolean: i32 = 2;
  pub const napi_number: i32 = 3;
  pub const napi_string: i32 = 4;
  pub const napi_symbol: i32 = 5;
  pub const napi_object: i32 = 6;
  pub const napi_function: i32 = 7;
  pub const napi_external: i32 = 8;
  #[cfg(feature = "napi6")]
  pub const napi_bigint: i32 = 9;
}

pub type napi_typedarray_type = i32;

pub mod TypedarrayType {
  pub const int8_array: i32 = 0;
  pub const uint8_array: i32 = 1;
  pub const uint8_clamped_array: i32 = 2;
  pub const int16_array: i32 = 3;
  pub const uint16_array: i32 = 4;
  pub const int32_array: i32 = 5;
  pub const uint32_array: i32 = 6;
  pub const float32_array: i32 = 7;
  pub const float64_array: i32 = 8;
  #[cfg(feature = "napi6")]
  pub const bigint64_array: i32 = 9;
  #[cfg(feature = "napi6")]
  pub const biguint64_array: i32 = 10;
}

pub type napi_status = i32;

pub mod Status {
  pub const napi_ok: i32 = 0;
  pub c


', () {
    var frame = Frame.parseFirefox(
        'g@http://localhost:8080/test.wasm:wasm-function[796]:0x143b4');
    expect(frame.uri, Uri.parse('http://localhost:8080/test.wasm'));
    expect(frame.line, 1);
    expect(frame.column, 0x143b4 + 1);
    expect(frame.member, 'g');
  });

  test('parses a Firefox Wasm frame with a name with spaces', () {
    var frame = Frame.parseFirefox(
        'main tear-off trampoline@http://localhost:8080/test.wasm:wasm-function[794]:0x14387');
    expect(frame.uri, Uri.parse('http://localhost:8080/test.wasm'));
    expect(frame.line, 1);
    expect(frame.column, 0x14387 + 1);
    expect(frame.member, 'main tear-off trampoline');
  });

  test('parses a Firefox Wasm frame without a name', () {
    var frame = Frame.parseFirefox(
        '@http://localhost:8080/test.wasm:wasm-function[796]:0x143b4');
    expect(frame.uri, Uri.parse('http://localhost:8080/test.wasm'));
    expect(frame.line, 1);
    expect(frame.column, 0x143b4 + 1);
    expect(frame.member, '796');
  });

  test('parses a Safari Wasm frame with a name', () {
    var frame = Frame.parseSafari('<?>.wasm-function[g]@[wasm code]');
    expect(frame.uri, Uri.parse('wasm code'));
    expect(frame.line, null);
    expect(frame.column, null);
    expect(frame.member, 'g');
  });

  test('parses a Safari Wasm frame with a name', () {
    var frame = Frame.parseSafari(
        '<?>.wasm-function[main tear-off trampoline]@[wasm code]');
    expect(frame.uri, Uri.parse('wasm code'));
    expect(frame.line, null);
    expect(frame.column, null);
    expect(frame.member, 'main tear-off trampoline');
  });

  test('parses a Safari Wasm frame without a name', () {
    var frame = Frame.parseSafari('<?>.wasm-function[796]@[wasm code]');
    expect(frame.uri, Uri.parse('wasm code'));
    expect(frame.line, null);
    expect(frame.column, null);
    expect(frame.member, '796');
  });
}

void expectIsUnparsed(Frame Function(String) constructor, String text) {
  var frame = constructor(text);
  expect(frame, isA<UnparsedFrame>());
  expect(frame.toString(), equals(text));
}
// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:collection';

import 'package:async/async.dart';
import 'package:stack_trace/stack_trace.dart';

/// Manages an abstract pool of resources with a limit on how many may be in use
/// at once.
///
/// When a resource is needed, the user should call [request]. When the returned
/// future completes with a [PoolResource], the resource may be allocated. Once
/// the resource has been released, the user should call [PoolResource.release].
/// The pool will ensure that only a certain number of [PoolResource]s may be
/// allocated at once.
class Pool {
  /// Completers for requests beyond the first [_maxAllocatedResources].
  ///
  /// When an item is released, the next element


ype === 'antiprism') {
    return true;
  }

  if (baseType === 'prism' && Cap.getAll(polyhedron).length === 0) {
    return true;
  }

  if (baseType !== 'truncated' && _.isNil(gyrate)) {
    throw new Error(`Must define 'gyrate' for augmenting ${baseType} `);
  }

  const adjFace =
    baseType === 'prism' ? getOppositePrismFace(base) : base.adjacentFaces()[0];
  const alignedFace = getCyclic(underside.adjacentFaces(), -1);

  if (baseType === 'rhombicosidodecahedron') {
    const isOrtho = (adjFace.numSides !== 4) === (alignedFace.numSides !== 4);
    return isOrtho === (gyrate === 'ortho');
  }

  // It's orthogonal if triangle faces are aligned or non-triangle faces are aligned
  const isOrtho = (adjFace.numSides !== 3) === (alignedFace.numSides !== 3);

  if (baseType === 'truncated') {
    return !isOrtho;
  }

  // "ortho" or "gyro" is actually determined by whether the *tops* are aligned, not the bottoms
  // So for a cupola-rotunda, it's actually the opposite of everything else
  if (isCupolaRotunda(Cap.getAll(polyhedron)[0].type, augmentType)) {
    return isOrtho !== (gyrate === 'ortho');
  }

  return isOrtho === (gyrate === 'ortho');
}

function getAugmentee(augmentType: string, numSides: number) {
  const index = _.includes(['cupola', 'rotunda'], augmentType)
    ? numSides / 2
    : numSides;
  return augmentData[augmentType][index];
}

function isFastigium(augmentType: string, numSides: number) {
  return augmentType === 'cupola' && numSides === 4;
}

// Augment the following
function doAugment(
  polyhedron: Polyhedron,
  base: Face,
  augmentType: string,
  gyrate?: string,
) {
  const numSides = base.numSides;
  const augmentee = getAugmentee(augmentType, numSides);
  const underside = augmentee.faceWithNumSides(base.numSides);

  // Determine the orientations of the underside and the base
  const undersideRadius = underside.vertices[0].vec
    .sub(underside.centroid())
    .getNormalized();

  const baseIsAligned = isAligned(
    polyhedron,
    base,
    underside,
    isFastigium(augmentType, numSides) ? 'gyro' : gyrate,
    augmentType,
  );
  const offset = baseIsAligned ? 0 : 1;
  const baseRadius = base.vertices[offset].vec
    .sub(base.centroid())
    .getNormalized();

  // https://math.stackexchange.com/questions/624348/finding-rotation-axis-and-angle-to-align-two-oriented-vectors
  // Determine the transformation that rotates the underside orientation to the base orientation
  // TODO we probably want this as some sort of generic method
  const transformMatrix = getOrthonormalTransform(
    undersideRadius,
    underside.normal().getInverted(),
    baseRadius,
    base.normal(),
  );
  const transform = withOrigin(base.centroid(), u =>
    transformMatrix.applyTo(u),
  );

  // Scale and position the augmentee so that it lines up with the base
  const alignedVertices = augmentee.vertices.map(v => {
    return v.vec
      .sub(underside.centroid())
      .scale(base.sideLength() / augmentee.edgeLength())
      .add(base


.createElement('input');
  attachmentCheckbox.setAttribute('type', 'checkbox');

  attachmentCheckbox.setAttribute('data-text', attachment.text);
  attachmentCheckbox.setAttribute('data-download', attachment.download);
  attachmentCheckbox.setAttribute('data-href', attachment.href);

  if (attachment.missingCorsHeader) {
    attachmentCheckbox.disabled = true;
    attachmentCheckbox.setAttribute('title', 'The domain where this attachment is hosted does not send proper CORS headers, so it is not eligible for bulk download.')
  }
  else {
    attachmentCheckbox.checked = true;
  }

  container.appendChild(attachmentCheckbox);

  var attachmentLink = createAnchorTag(attachment.text, null);
  attachmentLink.setAttribute('data-href', attachment.href);
  attachmentLink.classList.add('attachment');

  attachmentLink.onclick = function(e) {
    attachment.element.click();
  };

  var attachmentWrapper = document.createElement('span');
  attachmentWrapper.appendChild(attachmentLink);

  container.appendChild(attachmentWrapper);
}

/**
 * Generate a zip file containing all attachments for the specified ticket.
 */

function createAttachmentZip(
  ticketId: string,
  ticketInfo: TicketMetadata
) : void {

  var instance = <HTMLAnchorElement> this;

  var attachmentLinks = <Array<HTMLInputElement>> Array.from(document.querySelectorAll('div[data-side-conversations-anchor-id="' + ticketId + '"] .lesa-ui-attachment-info input[type="checkbox"]'));

  var attachmentCount = 0;

  for (var i = 0; i < attachmentLinks.length; i++) {
    attachmentLinks[i].disabled = true;

    if (attachmentLinks[i].checked) {
      ++attachmentCount;
    }
  }

  if (attachmentCount == 0) {
    return;
  }

  instance.classList.add('downloading');

  var downloadCount = 0;

  var zip = new JSZip();

  for (var i = 0; i < attachmentLinks.length; i++) {
    if (!attachmentLinks[i].checked) {
      continue;
    }

    downloadAttachment(
      attachmentLinks[i],
      function(fileName: string, blob: Blob) : void {
        if (blob) {
          zip.file(fileName, blob);
        }

        if (++downloadCount < attachmentCount) {
          return;
        }

        instance.classList.remove('downloading');
        instance.classList.add('generating');

        zip.generateAsync({
          type: 'blob'
        }).then(function(blob: Blob) {
          var accountCode = getAccountCode(ticketId, ticketInfo) || 'UNKNOWN';
          var zipFileName = accountCode + '.zendesk-' + ticketId + '.zip';

          var downloadLink = createAnchorTag('Download ' + zipFileName, URL.createObjectURL(blob), zipFileName);
          downloadLink.classList.add('.lesa-ui-attachments-download-blob');

          var parentElement = <HTMLElement>instance.parentElement;
          parentElement.replaceChild(downloadLink, instance);
        });
      })
  }
}

/**
 * Function to check if this is a large attachment, since those cannot be automatically
 * included in attachment .zip files due to CORS policies.
 */

function isLiferayLargeAttachment(anchor: HTMLAnchorElement) : boolean {
  return anchor.href.indexOf('ticketAttachmentId') != -1;
}

/**
 * Create a container to hold all of the attachments in the ticket, and a convenience
 * link which allows the user to download all of the selected attachments at once.
 */

function createAttachmentsContainer(
  ticketId: string,
  ticketInfo: TicketMetadata,
  conversation: HTMLDivElement
) : HTMLDivElement | null {

  var attachmen


/*
 *  Copyright 2019-2023 Diligent Graphics LLC
 *
 *  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.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

#pragma once

/// \file
/// Definition of the Diligent::IPipelineStateCacheMtl interface

#include "../../GraphicsEngine/interface/PipelineStateCache.h"

DILIGENT_BEGIN_NAMESPACE(Diligent)

// {03CF61A7-BBAF-47E6-8E09-A9BCAD701A27}
static DILIGENT_CONSTEXPR INTERFACE_ID IID_PipelineStateCacheMtl =
    {0x3cf61a7, 0xbbaf, 0x47e6, {0x8e, 0x9, 0xa9, 0xbc, 0xad, 0x70, 0x1a, 0x27}};

#define DILIGENT_INTERFACE_NAME IPipelineStateCacheMtl
#include "../../../Primitives/interface/DefineInterfaceHelperMacros.h"

#define IPipelineStateCacheMtlInclusiveMethods \
    IPipelineStateCacheInclusiveMethods;       \
    IPipelineStateCacheMtlMethods PipelineStateCacheMtl

// clang-format off

/// Exposes Metal-specific functionality of a pipeline state cache object.
DILIGENT_BEGIN_INTERFACE(IPipelineStateCacheMtl, IPipelineStateCache)
{
};
DILIGENT_END_INTERFACE

#include "../../../Primitives/interface/UndefInterfaceHelperMacros.h"

#if DILIGENT_C_INTERFACE

#endif

DILIGENT_END_NAMESPACE // namespace Diligent


0x7e,0xfa,0x01,0x20]
// W32-ERR: :[[@LINE-2]]:{{[0-9]+}}: error: invalid operand for instruction

v_cmp_u_f64_e64 s[10:11], null, 0.5
// W64: encoding: [0x0a,0x00,0x28,0xd4,0x7c,0xe0,0x01,0x00]
// W32-ERR: :[[@LINE-2]]:{{[0-9]+}}: error: invalid operand for instruction

v_cmp_u_f64_e64 s[104:105], -1, -1
// W64: encoding: [0x68,0x00,0x28,0xd4,0xc1,0x82,0x01,0x00]
// W32-ERR: :[[@LINE-2]]:{{[0-9]+}}: error: invalid operand for instruction

v_cmp_u_f64_e64 vcc, 0.5, null
// W64: encoding: [0x6a,0x00,0x28,0xd4,0xf0,0xf8,0x00,0x00]
// W32-ERR: :[[@LINE-2]]:{{[0-9]+}}: error: invalid operand for instruction

v_cmp_u_f64_e64 ttmp[14:15], -|src_scc|, -|exec|
// W64: encoding: [0x7a,0x03,0x28,0xd4,0xfd,0xfc,0x00,0x60]
// W32-ERR: :[[@LINE-2]]:{{[0-9]+}}: error: invalid operand for instruction

v_cmp_u_f64_e64 null, 0xaf123456, -|vcc| clamp
// GFX11: encoding: [0x7c,0x82,0x28,0xd4,0xff,0xd4,0x00,0x40,0x56,0x34,0x12,0xaf]


:1  @P1 RED.E.ADD.F32.FTZ.RN [Out + 4x<5*$Q*$N + 1*$N>], s51;
--:-:-:-:1  @P2 RED.E.ADD.F32.FTZ.RN [Out + 4x<5*$Q*$N + 2*$N>], s52;
--:-:-:-:1  @P3 RED.E.ADD.F32.FTZ.RN [Out + 4x<5*$Q*$N + 3*$N>], s53;
--:-:-:-:1  @P4 RED.E.ADD.F32.FTZ.RN [Out + 4x<5*$Q*$N + 4*$N>], s54;
--:1:-:-:1  @P5 RED.E.ADD.F32.FTZ.RN [Out + 4x<5*$Q*$N + 5*$N>], s55;
    };
+]
</SCHEDULE_BLOCK>

[+
    our $type;
    return $type eq 'h' ? q{
--:-:-:-:1      LDS.U.32 s00, [readCs + 4x<(0*6+0)*32>];
--:-:-:-:1      LDS.U.32 s01, [readCs + 4x<(0*6+1)*32>];
--:-:-:-:1      LDS.U.32 s02, [readCs + 4x<(0*6+2)*32>];
--:-:-:-:1      LDS.U.32 s03, [readCs + 4x<(0*6+3)*32>];
--:-:-:-:1      LDS.U.32 s04, [readCs + 4x<(0*6+4)*32>];
--:-:1:-:1      LDS.U.32 s05, [readCs + 4x<(0*6+5)*32>];

--:-:-:-:1      LDS.U.32 s10, [readCs + 4x<(1*6+0)*32>];
--:-:-:-:1      LDS.U.32 s11, [readCs + 4x<(1*6+1)*32>];
--:-:-:-:1      LDS.U.32 s12, [readCs + 4x<(1*6+2)*32>];
--:-:-:-:1      LDS.U.32 s13, [readCs + 4x<(1*6+3)*32>];
--:-:-:-:1      LDS.U.32 s14, [readCs + 4x<(1*6+4)*32>];
--:-:2:-:1      LDS.U.32 s15, [readCs + 4x<(1*6+5)*32>];

--:-:-:-:1      LDS.U.32 s20, [readCs + 4x<(2*6+0)*32>];
--:-:-:-:1      LDS.U.32 s21, [readCs + 4x<(2*6+1)*32>];
--:-:-:-:1      LDS.U.32 s22, [readCs + 4x<(2*6+2)*32>];
--:-:-:-:1      LDS.U.32 s23, [readCs + 4x<(2*6+3)*32>];
--:-:-:-:1      LDS.U.32 s24, [readCs + 4x<(2*6+4)*32>];
--:-:3:-:1      LDS.U.32 s25, [readCs + 4x<(2*6+5)*32>];

<SCHEDULE_BLOCK>
<ORDERED>
01:-:-:-:1  @P0 RED.E.ADD.F16x2.FTZ.RN [Out + 2x<0*$Q*$N + 0*$N>], s00;
--:-:-:-:1      LDS.U.32 s30, [readCs + 4x<(3*6+0)*32>];


-- LuaTools需要PROJECT和VERSION这两个信息
PROJECT = "otademo"
VERSION = "1.0.0"

log.info("main", PROJECT, VERSION)

-- sys库是标配
_G.sys = require("sys")

if wdt then
    --添加硬狗防止程序卡死，在支持的设备上启用这个功能
    wdt.init(15000)--初始化watchdog设置为15s
    sys.timerLoopStart(wdt.feed, 10000)--10s喂一次狗
end

local bin_path = "/luadb/"
local bin_name = "update.bin"
local tar_path = "/spiffs/"

--[[
ota流程就是把update.bin放在根目录(esp为"/spiffs/" 其余为"/")，重启后会自动升级.
update.bin制作方法:luatools中点击生成量产文件,将 SOC量产及远程升级文件 目录中的XXX.ota文件更名为update.bin即可
]]

sys.taskInit(function()
    log.info("-----------------old-----------------


dom().nextInt(10000)
    val range = 1..limit
    val components = range.map { "country:$it" }

    // when
    val formatted = components.toPipedString()

    // then
    assertLastCharacterIsNotPipe(formatted!!)
    assertThat(formatted.split("|").size, `is`(limit))
    assertThat(formatted.split("|").last(), `is`("country:$limit"))
  }

  @Test
  fun formatWithComma_shouldPutFirstCommaAndSecond() {
    // given
    val location = 10.0 to -20.0

    // when
    val formatted = location.formatWithComma()

    // then
    assertThat(formatted, `is`("10.0,-20.0"))
  }

  private fun assertLastCharacterIsNotPipe(formatted: String) {
    assertThat(formatted.last().toString(), not(`is`("|")))
  }
}package com.a99.rxplaces

import com.a99.rxplaces.GoogleMapsApi.Companion.INVALID_REQUEST
import com.a99.rxplaces.GoogleMapsApi.Companion.OK
import com.a99.rxplaces.GoogleMapsApi.Companion.OVER_QUERY_LIMIT
import com.a99.rxplaces.GoogleMapsApi.Companion.REQUEST_DENIED
import com.a99.rxplaces.GoogleMapsApi.Companion.UNKNOWN_ERROR
import com.a99.rxplaces.GoogleMapsApi.Companion.ZERO_RESULTS
import com.a99.rxplaces.options.AutocompleteOptions
import rx.Single

internal class PlacesAutocompleteRepositoryImpl
constructor(val apiKey: String, val googleMapsApi: GoogleMapsApi) : PlacesAutocompleteRepository {

  override fun query(
      input: String,
      options: AutocompleteOptions): Single<List<Prediction>> {

    val single = createAutocompleteQuerySingle(input, options)
        .flatMap { flattenPredictions(it) }

    return single
  }

  private fun createAutocompleteQuerySingle(
      input: String,
      options: AutocompleteOptions): Single<PlaceAutocompleteResponse> {

    return googleMapsApi.getPlaceAutocomplete(
        key = apiKey,
        input = input,
        offset = options.offset,
        location = options.location?.formatWithComma(),
        radius = options.radius,
        language = options.language,
        types = options.types.toPipedString(),
        components = options.components.toPipedString(),
        strictBounds = options.strictBounds
    )
  }

  private fun flattenPredictions(response: PlaceAutocompleteResponse): Single<List<Prediction>> {
    return when (response.status) {
      OK -> Single.fromCallable { response.predictions }
      ZERO_RESULTS -> Single.fromCallable { emptyList<Prediction>() }
      OVER_QUERY_LIMIT -> Single.error(OverQueryLimitException(FAILURE_MESSAGE))
      REQUEST_DENIED -> Single.error(RequestDeniedException(FAILURE_MESSAGE))
      INVALID_REQUEST -> Single.error(InvalidRequestException(FAILURE_MESSAGE))
      UNKNOWN_ERROR -> Single.error(UnknownErrorException(FAILURE_MESSAGE))
      else -> Single.error(Exception(FAILURE_MESSAGE.plus("Status: ${response.status


on training  : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus

package main

import (
	s "github.com/inancgumus/prettyslice"
)

func main() {
	s.PrintBacking = true

	// ----------------------------------------------------
	// #1 nil slice
	var games []string // nil slice
	s.Show("games", games)

	// ----------------------------------------------------
	// #2 empty slice
	games = []string{} // empty slice
	s.Show("games", games)
	// s.Show("another empty", []int{})

	// ----------------------------------------------------
	// #3 non-empty slice
	games = []string{"pacman", "mario", "tetris", "doom"}
	s.Show("games", games)

	// ----------------------------------------------------
	// #4 reset the part using the games slice
	//    part is empty but its cap is still 4
	part := games
	s.Show("part", part)

	part = games[:0]
	s.Show("part[:0]", part)
	s.Show("part[:cap]", part[:cap(part)])

	for cap(part) != 0 {
		part = part[1:cap(part)]
		s.Show("part", part)
	}

	// #6 backing array's elements become inaccessible
	// games = games[len(games):]

	// ----------------------------------------------------
	// #5 part doesn't have any more capacity
	//    games slice is still intact
	s.Show("part", part)
	s.Show("games", games)
}
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials  : https://learngoprogramming.com
// In-person training  : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus

package main

import "fmt"

type printer interface {
	print()

	// use type assertion when you cannot change the interface.
	// discount(ratio float64)
}

type list []printer

func (l list) print() {
	if len(l) == 0 {
		fmt.Println("Sorry. We're waiting for delivery 🚚.")
		return
	}

	for _, it := range l {
		it.print()
	}
}

// type assertion can extract the wrapped value.
// or: it can put the value into another interface.
func (l list) discount(ratio float64) {
	// you can declare an interface in a function/method as well.
	// interface is just a type.
	type discounter interface {
		discount(float64)
	}

	for _, it := range l {
		// you can assert to an interface.
		// and extract another interface.
		if it, ok := it.(discounter); ok {
			it.discount(ratio)
		}
	}
}

// ----

// func (l list) discount(ratio float64) {
// 	for _, it := range l {
// 		// you can inline-assert interfaces
// 		// interface is just a type.
// 		g, ok := it.(interface{ discount(float64) })
// 		if !ok {
// 			continue
// 		}

// 		g.discount(ratio)
// 	}
// }

// ----

// // type assertion can pull out the real value behind an interface value.
// // it can also check whether the value convertable to a given type.
// func (l list) discount(ratio float64) {
// 	for _, it := range l {
// 		g, ok := it.(*game)
//


r,7" error-holder="mifStudentOutreach1Error"
           ng-class="{'required-error': !(mifStudentCoverage.outreachTetanus1.value.hasValue() ||
           mifStudentCoverage.outreachTetanus1.notRecorded)}"/>

    <input id="outreach1Nr_3" type="checkbox"
           ng-model="mifStudentCoverage.outreachTetanus1.notRecorded" not-recorded/>

    <input id="outreach2To5_3" class="right-justified" type="number" min="0" max="9999999" step="1"
           ng-model="mifStudentCoverage.outreachTetanus2To5.value" ng-trim="false"
           name="outreach2To5Nr_3"
           numeric-validator="positiveInteger,7" error-holder="mifStudentOutreachTetanus2To5Error"
           ng-class="{'required-error': !(mifStudentCoverage.outreachTetanus2To5.value.hasValue() ||
           mifStudentCoverage.outreachTetanus2To5.notRecorded)}"/>

    <input id="outreach2To5Nr_3" type="checkbox"
           ng-model="mifStudentCoverage.outreachTetanus2To5.notRecorded" not-recorded/>

    <input id="outreach1_4" class="right-justified" type="number" min="0" max="9999999" step="1"
           ng-model="mifWorkerCoverage.outreachTetanus1.value" ng-trim="false"
           name="outreach1Nr_4"
           numeric-validator="positiveInteger,7" error-holder="mifWorkerOutreach1Error"
           ng-class="{'required-error': !(mifWorkerCoverage.outreachTetanus1.value.hasValue() ||
           mifWorkerCoverage.outreachTetanus1.notRecorded)}"/>
    <


#include "TestMacros.h"

#include "MRMeshC/MRMesh.h"
#include "MRMeshC/MRMeshExtrude.h"
#include "MRMeshC/MRBitSet.h"
#include "MRMeshC/MRTorus.h"
#include <stdlib.h>

// Test for the case when the region contains selected faces
void testDegenerateBandNonEmpty(void) {
    // Create a torus mesh
    MRMakeTorusParameters params = { 1.1f, 0.5f, 16, 16 };
    MRMesh* mesh = mrMakeTorus(&params);
    TEST_ASSERT(mesh != NULL);

    // Record the number of vertices before calling the function
    size_t vCountBefore = mrMeshPointsNum(mesh);

    // Create a face bit set and select a few faces (for example, faces 0 and 1)
    MRFaceBitSet* region = mrFaceBitSetNew(0, false);
    mrBitSetAutoResizeSet((MRBitSet*)region, 0, true);
    mrBitSetAutoResizeSet((MRBitSet*)region, 1, true);

    // Call the function to create a band of degenerate faces along the region boundary
    mrMakeDegenerateBandAroundRegion(mesh, region);

    // Invalidate caches
    mrMeshInvalidateCaches(mesh, true);

    // Get the number of vertices after the function call
    size_t vCountAfter = mrMeshPointsNum(mesh);

    // Expect the number of vertices to increase due to vertex duplication along the boundary
    TEST_ASSERT( vCountBefore - vCountAfter != 0);

    mrFaceBitSetFree(region);
    mrMeshFree(mesh);
}

// Test for the case when the region is empty (no selected faces)
void testDegenerateBandEmpty(void) {
    // Create a torus mesh
    MRMakeTorusParameters params = { 1.1f, 0.5f, 16, 16 };
    MRMesh* mesh = mrMakeTorus(&params);
    TEST_ASSERT(mesh != NULL);

    // Record the number of vertices before calling the function
    size_t vCountBefore = mrMeshPointsNum(mesh);

    // Create an empty face bit set
    MRFaceBitSet* region = mrFaceBitSetNew(0, false);

    // Call the function with an empty region, no changes should occur
    mrMakeDegenerateBandAroundRegion(mesh, region);
    mrMeshInvalidateCaches(mesh, true);

    // The number of vertices should remain the same
    size_t vCountAfter = mrMeshPointsNum(mesh);
    TEST_ASSERT(vCountAfter == vCountBefore);

    mrFaceBitSetFree(region);
    mrMeshFree(mesh);
}


client?.getBatchHistory(args: {
  //       "0": [
  //         "f0c86f888f2aca0efaf1705247dbd1ebc02347c183e197310c9062ea2c9d2e34"
  //       ]
  //     })).called(1);
  //     verify(client?.getBatchHistory(args: {
  //       "0": [
  //         "ff7f0d2a4b8e2805706ece77f4e672550fe4c505a150c781639814338eda1734"
  //       ]
  //     })).called(1);
  //     verify(client?.getBatchHistory(args: {
  //       "0": [
  //         "1c2336c32dc62f00862ee6a75643e01017c86edece10b5a9d7defbd5f66b0a80"
  //       ]
  //     })).called(1);
  //
  //     verify(client?.getBlockHeadTip()).called(1);
  //     verify(client?.getHistory(scripthash: anyNamed("scripthash"))).called(1);
  //
  //     expect(secureStore.interactions, 10);
  //     expect(secureStore.writes, 5);
  //     expect(secureStore.reads, 5);
  //     expect(secureStore.deletes, 0);
  //
  //     verifyNoMoreInteractions(client);
  //     verifyNoMoreInteractions(cachedClient);
  //     verifyNoMoreInteractions(tracker);
  //   });
  //
  //   test("refresh wallet normally", () async {
  //     when(client?.getBlockHeadTip()).thenAnswer((realInvocation) async =>
  //         {"height": 520481, "hex": "some block hex"});
  //     when(client?.getServerFeatures()).thenAnswer((_) async => {
  //           "hosts": <dynamic, dynamic>{},
  //           "pruning": null,
  //           "server_version": "Unit tests",
  //           "protocol_min": "1.4",
  //           "protocol_max": "1.4.2",
  //           "genesis_hash": GENESIS_HASH_MAINNET,
  //           "hash_function": "sha256",
  //           "services": <dynamic>[]
  //         });
  //     when(client?.getBatchHistory(args: historyBatchArgs0))
  //         .thenAnswer((_) async => historyBatchResponse);
  //     when(client?.getBatchHistory(args: historyBatchArgs1))
  //         .thenAnswer((_) async => historyBatchResponse);
  //     when(client?.getHistory(scripthash: anyNamed("scripthash")))
  //         .thenAnswer((_) async => []);
  //     when(client?.estimateFee(blocks: anyNamed("blocks")))
  //         .thenAnswer((_) async => Decimal.one);
  //     // when(priceAPI?.getPricesAnd24hChange(baseCurrency: "USD"))
  //     //     .thenAnswer((_) async => Decimal.one);
  //
  //     await Hive.openBox<dynamic>(testWalletId);
  //     await Hive.openBox<dynamic>(DB.boxNamePrefs);
  //
  //     // recover to fill data
  //     await bch?.recoverFromMnemonic(
  //         mnemonic: TEST_MNEMONIC,
  //         maxUnusedAddressGap: 2,
  //         maxNumberOfIndexesToCheck: 1000,
  //         height: 4000);
  //
  //     when(client?.getBatchHistory(args: anyNamed("args")))
  //         .thenAnswer((_) async => {});
  //     when(client?.getBatchUTXOs(args: anyNamed("args")))
  //         .thenAnswer((_) async => emptyHistoryBatchResponse);
  //
  //     await bch?.refresh();
  //
  //     verify(client?.getServerFeatures()).called(1);
  //     verify(client?.getBatchHistory(args: historyBatchArgs0)).cal


{
    let str:string = '';
    while (l>0) {
        str += 'test ';
        l--;
    }

    return str;
}

let data_source:Array<string> = [];
for (let i = 0; i < 170; i++) {
    let l:number = (Math.random() * 100) + 1;
    let str:any = '<strong>' + (i+1) + '</strong>' + ' - ' + craeteString(l);
    data_source.push(str);
}

///////////////////////////////////////////////////////////
//////////////////// INIT LIST OPTIONS ////////////////////
///////////////////////////////////////////////////////////

let scroll_comp:YAIS;

scroll_comp = new YAIS(true);

scroll_comp.setOptionHTMLElement(Settings.CONTAINER, document.getElementById("infinite-scroll-cont"));
scroll_comp.setOptionArray<string>(Settings.DATA, data_source);
scroll_comp.setOptionNumber(Settings.ITEMS_PER_PAGE, 30);
scroll_comp.setOptionBoolean(Settings.LOOP, false);
scroll_comp.setOptionNumber(Settings.BOTTOM_REACHED, 600);
scroll_comp.setOptionNumber(Settings.TOP_REACHED, 600);

//////////////////////////////////////////////////////////////////
//////////////////// SET LISTENERS / HANDLERS ////////////////////
//////////////////////////////////////////////////////////////////

class OnScrollListener extends AbsScrollListener {
    public topReached(evt:any, yais:YAIS):void {
        super.topReached(evt);
        yais.addElemsToTop();
        console.log("topReached!!!");
    }
    public bottomReached(evt:any, yais:YAIS):void {
        super.bottomReached(evt);
        yais.addElemsToBottom();
        console.log("SCROLLDOWN!!!!!")
    }
}

scroll_comp.setOnScrollListener(new OnScrollListener());
//scroll_comp.setOnScrollListener(null);

scroll_comp.onScrollStartGoingDown.add(() => {
    console.log("onScrollStartGoingDown");
}, this);

scroll_comp.onScrollStartGoingUp.add(() => {
    console.log("onScrollStartGoingUp");
}, this);

scroll_comp.onScrollFinishGoingDown.add(() => {
    console.log("onScrollFinishGoingDown");
}, this);

scroll_comp.onScrollFinishGoingUp.add(() => {
    console.log("onScrollFinishGoingUp");
}, this);

scroll_comp.onOutOfData.add(() => {
    console.log("onOutOfData");
}, this);

//////////////////////////////////////////////////////////
//////////////////// START ENGINES ON ////////////////////
//////////////////////////////////////////////////////////

scroll_comp.init();

window['yais'] = scroll_comp;import '../iterablehelpers';
import { empty, minBy, sequenceEqual } from 'ix/iterable';

test('Iterable#minBy', () => {
  const source = [3, 5, 7, 6, 4, 2];

  const res = minBy(source, { selector: (x) => Math.floor(x / 2) });
  expect(sequenceEqual(res, [3, 2])).toBeTruthy();
});

test('Iterable#minBy empty throws', () => {
  const source = empty();

  expect(() => minBy(source, { selector: (x) => Math.floor(x / 2) })).toThrow();
});
export const Login = (username:string, id:number) => {
  return {
    type: 'LOGIN_USER',
    id,
    username
  }
};

export const Logout = () => {
  return {type: 'LOGOUT_USER'}
}

export const Loader = (value: boolean) => {
  return {
    type: "LOADER",
    value
  }
}

/* ASYNC */
export const GetMatch = () => {
  return (dispatch: any) => {
    // Run page loader
    dispatch(Loader(true));

    // Run async request
    fetch("https://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(users => {
      dispatch(GetMatchSuccess(users));
      dispatch(


 cmp    al, byte [rdx + 16]
	LONG $0x2454930f; BYTE $0x0d   // setae    byte [rsp + 13]
	LONG $0x1146b60f               // movzx    eax, byte [rsi + 17]
	WORD $0x423a; BYTE $0x11       // cmp    al, byte [rdx + 17]
	LONG $0xd4930f41               // setae    r12b
	LONG $0x1246b60f               // movzx    eax, byte [rsi + 18]
	WORD $0x423a; BYTE $0x12       // cmp    al, byte [rdx + 18]
	LONG $0xd5930f41               // setae    r13b
	LONG $0x1346b60f               // movzx    eax, byte [rsi + 19]
	WORD $0x423a; BYTE $0x13       // cmp    al, byte [rdx + 19]
	LONG $0x2454930f; BYTE $0x08   // setae    byte [rsp + 8]
	LONG $0x1446b60f               // movzx    eax, byte [rsi + 20]
	WORD $0x423a; BYTE $0x14       // cmp    al, byte [rdx + 20]
	LONG $0x2454930f; BYTE $0x09   // setae    byte [rsp + 9]
	LONG $0x1546b60f               // movzx    eax, byte [rsi + 21]
	WORD $0x423a; BYTE $0x15       // cmp    al, byte [rdx + 21]
	LONG $0x2454930f; BYTE $0x0a   // setae    byte [rsp + 10]
	LONG $0x1646b60f               // movzx    eax, byte [rsi + 22]
	WORD $0x423a; BYTE $0x16       // cmp    al, byte [rdx + 22]
	LONG $0x2454930f; BYTE $0x0b   // setae    byte [rsp + 11]
	LONG $0x1746b60f               // movzx    eax, byte [rsi + 23]
	WORD $0x423a; BYTE $0x17       // cmp    al, byte [rdx + 23]
	LONG $0xd1930f41               // setae    r9b
	LONG $0x1846b60f               // movzx    eax, byte [rsi + 24]
	WORD $0x423a; BYTE $0x18       // cmp    al, byte [rdx + 24]
	LONG $0x2454930f; BYTE $0x13   // setae    byte [rsp + 19]
	LONG $0x1946b60f               // movzx    eax, byte [rsi + 25]
	WORD $0x423a; BYTE $0x19       // cmp    al, byte [rdx + 25]
	LONG $0x2454930f; BYTE $0x0c   // setae    byte [rsp + 12]
	LONG $0x1a46b60f               // movzx    eax, byte [rsi + 26]
	WORD $0x423a; BYTE $0x1a       // cmp    al, byte [rdx + 26]
	LONG $0x2454930f; BYTE $0x0e   // setae    byte [rsp + 14]
	LONG $0x1b46b60f               // movzx    eax, byte [rsi + 27]
	WORD $0x423a; BYTE $0x1b       // cmp    al, byte [rdx + 27]
	LONG $0x2454930f; BYTE $0x0f   // setae    byte [rsp + 15]
	LONG $0x1c46b60f               // movzx    eax, byte [rsi + 28]
	WORD $0x423a; BYTE $0x1c       // cmp    al, byte [rdx + 28]
	LONG $0x2454930


/*=============================================================================

  Library: CTK

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  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.

=============================================================================*/

#ifndef CTKCMDLINEMODULEEXPLORERDIRECTORYSETTINGS_H
#define CTKCMDLINEMODULEEXPLORERDIRECTORYSETTINGS_H

#include <ctkSettingsPanel.h>

#include "ui_ctkCmdLineModuleExplorerDirectorySettings.h"

class ctkCmdLineModuleDirectoryWatcher;

/**
 * \class ctkCmdLineModuleExplorerDirectorySettings
 * \brief Example application settings panel.
 */
class ctkCmdLineModuleExplorerDirectorySettings : public ctkSettingsPanel, public Ui::ctkCmdLineModuleExplorerDirectorySettings
{
  Q_OBJECT

public:
  ctkCmdLineModuleExplorerDirectorySettings(ctkCmdLineModuleDirectoryWatcher* directoryWatcher);

  void applySettings();

private:

  ctkCmdLineModuleDirectoryWatcher* DirectoryWatcher;

};

#endif // CTKCMDLINEMODULEEXPLORERDIRECTORYSETTINGS_H


ER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY;
pub const KSAUDIO_SPEAKER_QUAD: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT;
pub const KSAUDIO_SPEAKER_SURROUND: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER;
pub const KSAUDIO_SPEAKER_5POINT0: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_SIDE_LEFT  | SPEAKER_SIDE_RIGHT;
pub const KSAUDIO_SPEAKER_5POINT1: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT  | SPEAKER_BACK_RIGHT;
pub const KSAUDIO_SPEAKER_7POINT0: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT
    | SPEAKER_SIDE_RIGHT;
pub const KSAUDIO_SPEAKER_7POINT1: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
    | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER;
pub const KSAUDIO_SPEAKER_5POINT1_SURROUND: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT  | SPEAKER_SIDE_RIGHT;
pub const KSAUDIO_SPEAKER_7POINT1_SURROUND: DWORD = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
    | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
    | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT;
<filename>src/test/run-pass/unwind-resource.rs
// xfail-win32
use std;
import task;
import comm;

class complainer {
  let c: comm::chan<bool>;
  new(c: comm::chan<bool>) {
    #error("Hello!");
    self.c = c; }
  drop { #error("About to send!");
    comm::send(self.c, true);
    #error("Sent!"); }
}

fn f(c: comm::chan<bool>) {
    let _c <- complainer(c);
    fail;
}

fn main() {
    let p = comm::port();
    let c = comm::chan(p);
    task::spawn_unlinked(|| f(c) );
    #error("hiiiiiiiii");
    assert comm::recv(p);
}
#![recursion_limit="128"]
#[macro_use] extern crate helix;
#[macro_use] extern crate serde_json;
extern crate indyrs as indy;

use indy::pool;
use indy::wallet;
use std::string::String;

use indy::future::Future;

use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;

ruby! {
    class IndyWallet {
        struct {
            name: String,
            handle: i32
        }

        def initialize(helix, name: String) {
            let handle = 0;
            IndyWallet { helix, name, handle }
        }

        def create(&self) {
            let config = format!("{{\"id\":\"wallet{}\"}}", self.name);


          if ( File.Exists( expectedProgramOutputFilePath ) )
            {
                expectedProgramOutput = await File.ReadAllTextAsync( expectedProgramOutputFilePath );
            }

            return new TemplateTest
            {
                Input = TestInput.Factory.Default.FromSource( projectProperties, testSource, filePath ),
                ExpectedTransformedCode = expectedTransformedCode,
                ExpectedProgramOutput = expectedProgramOutput
            };
        }

        public static async Task SaveToFileAsync( TemplateTest test, string filePath )
        {
            if ( test.Input == null )
            {
                throw new InvalidOperationException( "Test input not set." );
            }

            await File.WriteAllTextAsync( filePath, test.Input.SourceCode );

            var expectedTransformedCodeFilePath = GetExpectedTransformedCodeFilePath( filePath );
            await File.WriteAllTextAsync( expectedTransformedCodeFilePath, test.ExpectedTransformedCode );

            var expectedProgramOutputFilePath = GetExpectedProgramOutputFilePath( filePath );

            if ( !string.IsNullOrWhiteSpace( test.ExpectedProgramOutput ) )
            {
                await File.WriteAllTextAsync( expectedProgramOutputFilePath, test.ExpectedProgramOutput );
            }
            else if ( File.Exists( expectedProgramOutputFilePath ) )
            {
                File.Delete( expectedProgramOutputFilePath );
            }
        }
    }
}


}{{if isSlice $value}}{{ range $value }}--{{$name}}="{{.}}" {{end}}{{else}}--{{$name}}="{{$value}}" {{end}}{{ end }}{{ end }}{{ index .Options "_"}}`

		tpl, err := template.New("").Option("missingkey=zero").Funcs(funcMap).Parse(p.opt.OptionsCompositionTpl)
		if err != nil {
			return err
		}
		p.flagsTpl = tpl
	}

	switch p.opt.Kind {
	case "php":
		if strings.HasPrefix(p.opt.Code, "<?php") {
			p.opt.Code = p.opt.Code[5:]
		}
		p.opt.Command = "php"
		p.opt.Args = []string{"-d", "display_errors=stderr", "-r", p.opt.Code, "--"}
	case "python":
		p.opt.Command = "python"
		p.opt.Args = []string{"-u", "-c", p.opt.Code}
	case "golang":
		tmpGoFile := filepath.Join(p.DataLocation, "main.go")

		err := ioutil.WriteFile(tmpGoFile, []byte(p.opt.Code), 0644)
		if err != nil {
			return err
		}

		p.opt.Command = "go"
		p.opt.Args = []string{"run", tmpGoFile}
	}

	return err
}

func (p *processor) buildCommandArgs(e processors.IPacket) []string {
	finalArgs := []string{}
	for _, v := range p.opt.Args {
		v := strings.TrimSpace(v)
		if v == "" {
			continue
		}
		finalArgs = append(finalArgs, v)
	}
	if p.flagsTpl == nil {
		for k, v := range p.opt.Flags {
			if k == "_" {
				continue
			}
			switch vt := v.(type) {
			case string:
				if v == "" {
					finalArgs = append(finalArgs, "--"+k)
				} else {
					if e != nil {
						processors.Dynamic(&vt, e.Fields())
					}
					finalArgs = append(finalArgs, "--"+k+"="+vt)
				}
			case int64:
				finalArgs = append(finalArgs, fmt.Sprintf("--%s=%d", k, vt))
			case bool:
				if vt == true {
					finalArgs = append(finalArgs, fmt.Sprintf("--%s", k))
				}
			case []interface{}:
				for _, l := range vt {
					switch lt := l.(type) {
					case string:
						if e != nil {
							processors.Dynamic(&lt, e.Fields())
						}
						finalArgs = append(finalArgs, fmt.Sprintf("--%s=%s", k, lt))
					case int64:
						finalArgs = append(finalArgs, fmt.Sprintf("--%s=%d", k, lt))
					default:
						p.Logger.Errorf("not handled slice type : %s=>%v", k, v)
					}
				}
			case map[string]interface{}:
				for key, value := range vt {
					switch valuet := value.(type) {
					case string:
						finalArgs = append(finalArgs, fmt.Sprintf("--%s=%s:%s", k, key, valuet))
					default:
						p.Logger.Errorf("not handled map value type : %s=>%s", key, value)
					}
				}

			default:
				p.Logger.Errorf("not handled type : %s=>%v", k, v)
			}

		}
		if v, ok := p.opt.Flags["_"]; ok {
			switch vt := v.(type) {
			case string:
				finalArgs = append(finalArgs, vt)
			default:
				p.Logger.Errorf("not handled type : _ =>%v", v)
			}

		}
	} else { // use template
		buff := bytes.NewBufferString("")
		err := p.flagsTpl.Execute(buff, struct{ Options map[string]interface{} }{p.opt.Flags})
		if err != nil {
			p.Logger.Errorf("template error : %v", err)
			return finalArgs


nt_pattern="test-pattern",
    )
    mock_put_target.assert_called_once_with(
        rule_name="test-rule",
        target_pipeline="test-target-pipeline",
        target_pipeline_parameters=None,
        role_arn=SCHEDULE_ROLE_ARN,
    )
    mock_add_tags.assert_called_once_with(rule_arn=EVENT_BRIDGE_RULE_ARN, tags=TAGS)
    mock_create_trigger_lineage.assert_called_once_with(
        pipeline_name="test-target-pipeline",
        trigger_arn=EVENT_BRIDGE_RULE_ARN,
        state="Enabled",
        tags=TAGS,
        event_pattern="test-pattern",
    )

@patch(
    "sagemaker.feature_store.feature_processor._event_bridge_rule_helper.EventBridgeRuleHelper.enable_rule"
)
def test_enable_trigger(mock_enable_rule):
    session = Mock(Session, sagemaker_client=Mock(), boto_session=Mock())
    enable_trigger(pipeline_name="test-pipeline", sagemaker_session=session)
    mock_enable_rule.assert_called_once_with(rule_name="test-pipeline")

@patch(
    "sagemaker.feature_store.feature_processor._event_bridge_rule_helper.EventBridgeRuleHelper.disable_rule"
)
def test_disable_trigger(mock_disable_rule):
    session = Mock(Session, sagemaker_client=Mock(), boto_session=Mock())
    disable_trigger(pipeline_name="test-pipeline", sagemaker_session=session)
    mock_disable_rule.assert_called_once_with(rule_name="test-pipeline")

@patch(
    "sagemaker.feature_store.feature_processor._event_bridge_rule_helper.EventBridgeRuleHelper.list_targets_by_rule",
    return_value=[{"Targets": [{"Id": "target_pipeline"}]}],
)
@patch(
    "sagemaker.feature_store.feature_processor._event_bridge_rule_helper.EventBridgeRuleHelper.remove_targets"
)
@patch(
    "sagemaker.feature_store.feature_processor._event_bridge_rule_helper.EventBridgeRuleHelper.delete_rule"
)
def test_delete_trigger(mock_delete_rule, mock_remove_targets, mock_list_targets_by_rule):
    session = Mock(Session, sagemaker_client=Mock(), boto_session=Mock())
    delete_trigger(pipeline_name="test-pipeline", sagemaker_session=session)
    mock_delete_rule.assert_called_once_with("test-pipeline")
    mock_list_targets_by_rule.assert_called_once_with("test-pipeline")
    mock_remove_targets.assert_called_once_with(rule_name="test-pipeline", ids=["target_pipeline"])


}

    setGuessedLetters = (guessedLetter) => {
        this.game.guessedLetters.push(guessedLetter);
    }

    getGame = () => {
        return this.game;
    }
}import * as fs from 'fs';
import * as express from 'express';
import { Response as FetchResponse } from 'node-fetch';
import {
  Express,
  RequestHandler,
  Request,
  Response,
  NextFunction,
} from 'express';
import { getOTP, isSetupYet } from '../setup';
import { isBotRunning } from '../bot/bot';

/** @internal */
export function newExpressApp(): Express {
  return express();
}
/**
 * This middleware ensures only the admin with the correct token can access the resource.
 * It also sets the cookie, in case there is none
 * @internal
 * */
export function hasValidToken(medium: 'query' | 'cookies'): RequestHandler {
  return function (req: Request, res: Response, next: NextFunction): void {
    const { token } = req[medium];

    if (!token || token !== getOTP()) {
      res.status(401);
      res.render('error', {
        heading: '401 - Unauthorized',
        message: 'Token invalid or not provided',
      });
    } else {
      res.cookie('token', token, { httpOnly: true });
      next();
    }
  };
}

/** @internal */
export function onlyWhenSetup(
  _req: Request,
  res: Response,
  next: NextFunction,
): void {
  if (isSetupYet() && isBotRunning()) {
    next();
    return;
  }
  res.status(503);
  res.render('error', {
    heading: '503 - Not set up yet',
    message: 'The owner did not finish the setup yet. Please be patient.',
  });
}

/**
 * Makes sure the code query parameter is set
 * @internal
 * */
export function hasCodeQuery(
  req: Request,
  res: Response,
  next: NextFunction,
): void {
  const { code } = req.query;
  if (!code) {
    res.status(400);
    res.render('error', {
      heading: 'Invalid response',
      message: 'Code not provided',
    });
    return;
  }
  next();
}

/** @internal */
export async function ensureFetchIsOk(
  resp: FetchResponse,
): Promise<FetchResponse> {
  if (resp.ok) {
    return resp;
  }

  const errorMessage =
    'An error has occurred while reaching out to the TwitchAPI';

  return resp
    .json()
    .catch(() => null)
    .then((j) => {
      throw new Error(
        `${errorMessage}${
          j !== null ? ': ' + extractFetchErrorMessage(j) : ''
        }`,
      );
    });
}

/** @internal */
export function extractFetchErrorMessage(json: {
  status?: number;
  message?: string;
}): string {
  if (json.message) {
    return json.message;
  }
  if (json.status) {
    return json.status + '';
  }
  return JSON.stringify(json);
}

/** @internal */
export function verifyFilesExist(): void {
  const files = [
    'views/add.ejs',
    'views/add_success.ejs',
    'views/error.ejs',
    'views/ok.ejs',
    'views/remove.ejs',
    'views/remove_success.ejs',
  ];

  const missing = [];

  for (const file of files) {
    if (!fs.existsSync(file)) {
      missing.push(file);
    }
  }

  if (missing.length !== 0) {
    throw new Error(
      "Can't start server, the following files are missing: " +
        JSON.stringify(missing) +
        '\n' +
        'In case you are using the npm package, read the setup guide!',
    );
  }
}
import { Observable } from 'rxjs';
import { l


9: "dai4", // 𣫹
	0x23afb: "lou2", // 𣫻
	0x23b02: "guan4", // 𣬂
	0x23b06: "pei2", // 𣬆
	0x23b09: "pi2", // 𣬉
	0x23b0b: "juan4", // 𣬋
	0x23b0d: "bei1", // 𣬍
	0x23b0e: "jue2", // 𣬎
	0x23b0f: "juan4", // 𣬏
	0x23b10: "shi4", // 𣬐
	0x23b15: "xie3", // 𣬕
	0x23b18: "rui2", // 𣬘
	0x23b19: "jing4", // 𣬙
	0x23b1a: "po4", // 𣬚
	0x23b1b: "san1", // 𣬛
	0x23b20: "ji1", // 𣬠
	0x23b29: "fen1", // 𣬩
	0x23b2a: "bei4", // 𣬪
	0x23b2b: "jie4", // 𣬫
	0x23b2c: "sa1", // 𣬬
	0x23b2e: "pi1", // 𣬮
	0x23b34: "di4", // 𣬴
	0x23b35: "mao2", // 𣬵
	0x23b36: "ba5", // 𣬶
	0x23b37: "ba5", // 𣬷
	0x23b38: "tiao2", // 𣬸
	0x23b39: "ling2", // 𣬹
	0x23b3a: "sheng1", // 𣬺
	0x23b3b: "zhen3", // 𣬻
	0x23b3c: "pi1", // 𣬼
	0x23b3d: "wu4", // 𣬽
	0x23b3f: "ze4", // 𣬿
	0x23b40: "bao4", // 𣭀
	0x23b47: "lv3", // 𣭇
	0x23b56: "hao1", // 𣭖
	0x23b57: "dou3", // 𣭗
	0x23b58: "fu2", // 𣭘
	0x23b59: "ni2", // 𣭙
	0x23b5d: "ge2", // 𣭝
	0x23b60: "ru2", // 𣭠
	0x23b61: "xian3", // 𣭡
	0x23b64: "bi4", // 𣭤
	0x23b6e: "mao2", // 𣭮
	0x23b72: "rong3", // 𣭲
	0x23b73: "qiu2", // 𣭳
	0x23b77: "bo2", // 𣭷
	0x23b79: "hao1", // 𣭹
	0x23b7a: "nao3", // 𣭺
	0x23b7b: "yan2", // 𣭻
	0x23b83: "pao2", // 𣮃
	0x23b84: "sui1", // 𣮄
	0x23b86: "tuo4", // 𣮆
	0x23b88: "qu1", // 𣮈
	0x23b89: "li2", // 𣮉


 Pilzer", "jan.pilzer@gmx.de")
	addPerson("Jan Ziak", "0xe2.0x9a.0x9b@gmail.com", "@atomsymbol")
	addPerson("Janne Snabb", "snabb@epipe.com", "@snabb")
	addPerson("Jason A. Donenfeld", "jason@zx2c4.com", "@zx2c4")
	addPerson("Jason Barnett", "jason.w.barnett@gmail.com", "@jasonwbarnett")
	addPerson("Jason Buberel", "jbuberel@google.com", "8445@62eb7196-b449-3ce5-99f1-c037f21e1705")
	addPerson("Jason Buberel", "jbuberel@google.com", "jason@buberel.org", "@jbuberel")
	addPerson("Jason Chu", "jasonchujc@gmail.com", "@1lann")
	addPerson("Jason Cwik", "jason@cwik.org")
	addPerson("Jason Del Ponte", "delpontej@gmail.com", "@jasdel")
	addPerson("Jason Donenfeld", "jason.donenfeld@gmail.com", "20556@62eb7196-b449-3ce5-99f1-c037f21e1705")
	addPerson("Jason E. Aten", "j.e.aten@gmail.com")
	addPerson("Jason Hall", "imjasonh@gmail.com")
	addPerson("Jason Hall", "jasonhall@google.com")
	addPerson("Jason Hewes", "jasonhewes5@gmail.com")
	addPerson("Jason Keene", "jasonkeene@gmail.com")
	addPerson("Jason Keene", "jasonkeene@gmail.com", "@jasonkeene")
	addPerson("Jason LeBrun", "jblebrun@gmail.com", "@jblebrun")
	addPerson("Jason McVetta", "jason.mcvetta@gmail.com", "@jmcvetta")
	addPerson("Jason Murray", "jason@chaosaffe.io")
	addPerson("Jason Smale", "jsmale@zendesk.com")
	addPerson("Jason Travis", "infomaniac7@gmail.com", "@corburn")
	addPerson("Jason Wangsadinata", "jwangsadinata@gmail.com", "@jwangsadinata")
	addPerson("Jason Wilder", "mail@jasonwilder.com")
	addPerson("Javier Kohen", "jkohen@google.com", "@jkohen")
	addPerson("Javier Segura", "javism@gmail.com", "@jsegura")
	addPerson("Jay Conrod", "jayconrod@google.com", "17092@62eb7196-b449-3ce5-99f1-c037f21e1705")
	addPerson("Jay Conrod", "jayconrod@google.com", "@jayconrod")
	addPerson("Jay Satiro", "raysatiro@yahoo.com")
	addPerson("Jay Stramel", "js@ionactual.com")
	addPerson("Jay Weisskopf", "jay@jayschwa.net", "@jayschwa")
	addPerson("Jayabaskar Rajagopal", "jayabaskar.rajagopal@gmail.com")
	addPerson("Jean de Klerk", "deklerk@google.com", "26615@62eb7196-b449-3ce5-99f1-c037f21e1705")
	addPerson("Jean de Klerk", "deklerk@google.com", "@jadekler")
	addPerson("Jean de Klerk", "jadekler@gmail.com")
	addPerson("Jean-André Santoni", "jean.andre.santoni@gmail.com")
	addPerson("Jean-Francois Cantin", "jfcantin@gmail.com", "@jfcantin")
	addPerson("Jean-Marc Eurin", "jmeurin@google.com", "@jmeurin")
	addPerson("Jean-Nicolas Moal", "jn.moal@gmail.com",


 (p_width == 0) {
		p_width = m_videoParam.GetRect().GetWidth();
	}
	if (p_height == 0) {
		p_height = m_videoParam.GetRect().GetHeight();
	}

	if (!m_paused) {
		m_3dManager->GetLego3DView()->GetView()->ForceUpdate(p_x, p_y, p_width, p_height);
	}
}

// FUNCTION: LEGO1 0x1007c520
void LegoVideoManager::FUN_1007c520()
{
	m_unk0xe5 = TRUE;
	m_render3d = FALSE;
	m_videoParam.GetPalette()->SetOverrideSkyColor(FALSE);

	m_displaySurface->ClearScreen();
	InputManager()->EnableInputProcessing();
	InputManager()->SetUnknown335(TRUE);
}

extern void ViewportDestroyCallback(IDirect3DRMObject*, void*);

// FUNCTION: LEGO1 0x1007c560
int LegoVideoManager::EnableRMDevice()
{
	IDirect3DRMViewport* viewport;

	if (!m_paused) {
		return -1;
	}

	TglImpl::DeviceImpl* deviceImpl = (TglImpl::DeviceImpl*) m_3dManager->GetLego3DView()->GetDevice();
	IDirect3DRMDevice2* d3drmDev2 = NULL;
	IDirect3D2* d3d2 = m_direct3d->Direct3D();
	IDirect3DDevice2* d3dDev2 = m_direct3d->Direct3DDevice();

	int result = -1;
	IDirect3DRM2* d3drm2 = ((TglImpl::RendererImpl*) m_renderer)->ImplementationData();

	m_direct3d->RestoreSurfaces();

	if (d3drm2->CreateDeviceFromD3D(d3d2, d3dDev2, &d3drmDev2) == D3DRM_OK) {
		viewport = NULL;
		deviceImpl->SetImplementationData(d3drmDev2);

		if (d3drm2->CreateViewport(d3drmDev2, m_camera, 0, 0, m_cameraWidth, m_cameraHeight, &viewport) == D3DRM_OK) {
			viewport->SetBack(m_back);
			viewport->SetFront(m_front);
			viewport->SetField(m_fov);
			viewport->SetCamera(m_camera);
			viewport->SetProjection(m_projection);
			viewport->SetAppData((LPD3DRM_APPDATA) m_appdata);
			d3drmDev2->SetQuality(m_quality);
			d3drmDev2->SetShades(m_shades);
			d3drmDev2->SetTextureQuality(m_textureQuality);
			d3drmDev2->SetRenderMode(m_rendermode);
			d3drmDev2->SetDither(m_dither);
			d3drmDev2->SetBufferCount(m_bufferCount);
			m_camera->Release();

			if (viewport->AddDestroyCallback(ViewportDestroyCallback, m_appdata) == D3DRM_OK) {
				((TglImpl::ViewImpl*) m_3dManager->GetLego3DView()->GetView())->SetImplementationData(viewport);
				m_paused = 0;
				result = 0;
			}
		}
	}

	return result;
}

// FUNCTION: LEGO1 0x1007c740
int LegoVideoManager::DisableRMDevice()
{
	if (m_paused) {
		return -1;
	}

	IDirect3DRMDevice2* d3drmDev2 =
		((TglImpl::DeviceImpl*) m_3dManager->GetLego3DView()->GetDevice())->ImplementationData();

	if (d3drmDev2 != NULL) {
		IDirect3DRMViewportArray* viewportArray = NULL;

		if (d3drmDev2->GetViewports(&viewportArray) == D3DRM_OK && viewportArray != NULL) {
			if (viewportArray->GetSize() == 1) {
				IDirect3DRMViewport*


tracker/tracker/Context;)V\n"
            + "// end ArrayStore.instrument\n"
            + "RETURN\n"
            + "MAXSTACK = 6\n"
            + "MAXLOCALS = 7\n");
  }

  static char[] myCharArray;
  static byte[] myByteArray;
  static boolean myBoolean;
  static InputStream inputStream;
  static OutputStream outputStream;

  @Test
  public void testFramesLoop() {
    testTransform(new Object() {
                    @SuppressWarnings("unused")
                    void t() {
                      while (myBoolean) {
                        myCharArray[0] = myCharArray[1];
                      }
                    }
                  },
        // original code
        "L0\n"
            + "FRAME FULL [$THIS$] []\n"
            + "GETSTATIC $THISTEST$.myBoolean : Z\n"
            + "IFEQ L1\n"
            + "GETSTATIC $THISTEST$.myCharArray : [C\n"
            + "ICONST_0\n"
            + "GETSTATIC $THISTEST$.myCharArray : [C\n"
            + "ICONST_1\n"
            + "CALOAD\n"
            + "CASTORE\n"
            + "GOTO L0\n"
            + "L1\n"
            + "FRAME FULL [$THIS$] []\n"
            + "RETURN\n"
            + "MAXSTACK = 4\n"
            + "MAXLOCALS = 1\n",
        // transformed code
        "// Initialize newLocal ArrayLoadValue PointTracker\n"
            + "ACONST_NULL\n"
            + "ASTORE 1\n"
            + "// Initialize newLocal ContextLoader context\n"
            + "INVOKESTATIC com/coekie/flowtracker/tracker/Context.context ()Lcom/coekie/flowtracker/tracker/Context;\n"
            + "ASTORE 2\n"
            + "L0\n"
            + "FRAME FULL [$THIS$ com/coekie/flowtracker/tracker/TrackerPoint com/coekie/flowtracker/tracker/Context] []\n"
            + "GETSTATIC $THISTEST$.myBoolean : Z\n"
            + "IFEQ L1\n"
            + "GETSTATIC $THISTEST$.myCharArray : [C\n"
            + "ICONST_0\n"
            + "GETSTATIC $THISTEST$.myCharArray : [C\n"
            + "ICONST_1\n"
            + "// begin ArrayLoadValue.insertTrackStatements\n"
            + "DUP2\n"
            + "ALOAD 2\n"
            + "INVOKESTATIC com/coekie/flowtracker/hook/ArrayLoadHook.getElementTracker (Ljava/lang/Object;ILcom/coekie/flowtracker/tracker/Context;)Lcom/coekie/flowtracker/tracker/TrackerPoint;\n"
            + "ASTORE 1\n"
            + "// end ArrayLoadValue.insertTrackStatements\n"
            + "CALOAD\n"
            + "// begin ArrayStore.instrument: ArrayHook.set*(array, arrayIndex, value [already on stack], sourcePoint)\n"
            + "// ArrayLoadValue.loadSourcePoint\n"
            + "ALOAD 1\n"
            + "ALOAD 2\n"
            + "INVOKESTATIC com/coekie/flowtracker/hook/ArrayHook.setChar ([CICLcom/coekie/flowtracker/tracker/TrackerPoint;Lcom/coekie/flowtracker/tracker/Context;)V\n"
            + "// end ArrayStore.instrument\n"
            + "GOTO L0\n"
            + "L1\n"
            + "FRAME FULL [$THIS$ com/coekie/flowtracker/t