ert", "standard-colors.frag")

        withProgram(theProgram) { offsetUniform = "offset".location }
    }

    fun initializeVertexBuffer(gl: GL3) = gl.initArrayBuffer(vertexBufferObject) { data(vertexData, GL_STATIC_DRAW) }

    override fun display(gl: GL3) = with(gl) {

        clear { color(0) }

        usingProgram(theProgram) {

            glUniform2f(offsetUniform, 0.5f, 0.25f)

            val colorData = vertexData.size / 2

            withVertexLayout(vertexBufferObject, glf.pos4_col4, 0, colorData) { glDrawArrays(36) }
        }
    }

    override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
        glViewport(w, h)
    }

    override fun end(gl: GL3) = with(gl) {

        glDeleteProgram(theProgram)
        glDeleteBuffer(vertexBufferObject)
        glDeleteVertexArray(vao)

        destroyBuffers(vao, vertexBufferObject, vertexData)
    }

    override fun keyPressed(keyEvent: KeyEvent) {

        when (keyEvent.keyCode) {
            KeyEvent.VK_ESCAPE -> quit()
        }
    }

    val vertexData = floatBufferOf(
            +0.25f, +0.25f, +0.75f, 1.0f,
            +0.25f, -0.25f, +0.75f, 1.0f,
            -0.25f, +0.25f, +0.75f, 1.0f,

            +0.25f, -0.25f, +0.75f, 1.0f,
            -0.25f, -0.25f, +0.75f, 1.0f,
            -0.25f, +0.25f, +0.75f, 1.0f,

            +0.25f, +0.25f, -0.75f, 1.0f,
            -0.25f, +0.25f, -0.75f, 1.0f,
            +0.25f, -0.25f, -0.75f, 1.0f,

            +0.25f, -0.25f, -0.75f, 1.0f,
            -0.25f, +0.25f, -0.75f, 1.0f,
            -0.25f, -0.25f, -0.75f, 1.0f,

            -0.25f, +0.25f, +0.75f, 1.0f,
            -0.25f, -0.25f, +0.75f, 1.0f,
            -0.25f, -0.25f, -0.75f, 1.0f,

            -0.25f, +0.25f, +0.75f, 1.0f,
            -0.25f, -0.25f, -0.75f, 1.0f,
            -0.25f, +0.25f, -0.75f, 1.0f,

            +0.25f, +0.25f, +0.75f, 1.0f,
            +0.25f, -0.25f, -0.75f, 1.0f,
            +0.25f, -0.25f, +0.75f, 1.0f,

            +0.25f, +0.25f, +0.75f, 1.0f,
            +0.25f, +0.25f, -0.75f, 1.0f,
            +0.25f, -0.25f, -0.75f, 1.0f,

            +0.25f, +0.25f, -0.75f, 1.0f,
            +0.25f, +0.25f, +0.75f, 1.0f,
            -0.25f, +0.25f, +0.75f, 1.0f,

            +0.25f, +0.25f, -0.75f, 1.0f,
            -0.25f, +0.25f, +0.75f, 1.0f,
            -0.25f, +0.25f, -0.75f, 1.0f,

            +0.25f, -0.25f, -0.75f, 1.0f,
            -0.25f, -0.25f, +0.75f, 1.0f,
            +0.25f, -0.25f, +0.75f, 1.0f,

            +0.25f, -0.25f, -0.75f, 1.0f,
            -0.25f, -0.25f, -0.75f, 1.0f,


ry.core.metadata.EntityMetadata;
import com.easy.query.core.metadata.NavigateMetadata;
import com.easy.query.core.util.EasyClassUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create time 2025/3/29 21:12
 * 文件说明
 *
 * @author xuejiaming
 */
public class EqualsDirectToOneGetter implements RelationIncludeGetter {
    private final QueryRuntimeContext runtimeContext;
    private final RelationValueColumnMetadataFactory relationValueColumnMetadataFactory;
    private final NavigateMetadata navigateMetadata;
    private final EntityMetadata targetEntityMetadata;
    private final Map<RelationValue, Object> targetToManyMap;

    public EqualsDirectToOneGetter(QueryRuntimeContext runtimeContext, NavigateMetadata navigateMetadata, List<RelationExtraEntity> includes, List<Object> mappingRow) {
        this.runtimeContext = runtimeContext;
        this.relationValueColumnMetadataFactory = runtimeContext.getRelationValueColumnMetadataFactory();
        this.navigateMetadata = navigateMetadata;
        this.targetEntityMetadata = runtimeContext.getEntityMetadataManager().getEntityMetadata(navigateMetadata.getNavigatePropertyType());
        this.targetToManyMap = getTargetDirectMap(includes,mappingRow);
    }

    protected Map<RelationValue, Object> getTargetDirectMap(List<RelationExtraEntity> includes, List<Object> mappingRows) {

        Map<RelationValue, Object> resultMap = new HashMap<>();

        EntityMetadata entityMetadata = runtimeContext.getEntityMetadataManager().getEntityMetadata(navigateMetadata.getDirectMappingClass(runtimeContext));
        RelationValueColumnMetadata selfRelationColumn = relationValueColumnMetadataFactory.create(entityMetadata, navigateMetadata.getDirectMappingSelfPropertiesOrPrimary(runtimeContext));
        //优化多级RelationValueColumnMetadata
        RelationValueColumnMetadata targetRelationColumn = relationValueColumnMetadataFactory.createDirect(navigateMetadata, navigateMetadata.getDirectMappingTargetPropertiesOrPrimary(runtimeContext));

        Map<RelationValue, Object> targetDirectMap = getTargetDirectMap(includes);
        for (Object mappingRow : mappingRows) {
            RelationValue selfRelationId = selfRelationColumn.getRelationValue(mappingRow);
            if (selfRelationId.isNull()) {
                continue;
            }
            RelationValue targetRelationId = targetRelationColumn.getRelationValue(mappingRow);
            if (targetRelationId.isNull()) {
                continue;
            }
            Object value = targetDirectMap.get(targetRelationId);
            Object oldVal = resultMap.put(selfRelationId, value);
            if (oldVal != null) {
                //如果你存在NotNull的列这一列的数据可能存在空值,空值之间会互相关联也会导致当前错误,还有一种就是ToOne或者ToMany配置错误
                throw new EasyQueryInvalidOperationException("The relationship property '{" + targetRelationColumn.getPropertyNames() + "}' value ‘" + selfRelationId + "’ appears to have duplicates: ["+EasyClassUtil.getSimpleName(navigateMetadata.getEntityMetadata().getEntityClass())+"." + EasyClassUtil.getInstanceSimpleName(oldVal) + "]. Please confirm whether the data represents a One or Many relationship.");
            }

        }
        return resultMap;
    }

    protected Map<RelationValue, Object> getTargetDirectMap(List<RelationExtraEntity> includes) {
        Map<RelationValue, Object> resultMap = new HashMap<>();
        String[] directTargetPropertiesOrPrimary = navigateMetadata.getDirectTargetPropertiesOrPrimary(runtimeContext);
        for (RelationExtraEntity target : includes) {
            RelationValue targetRelationId = target.getRelationExtraColumns(directTargetPropertiesOrPrimary);
            if (targetRelationId.isNull()) {
                continue;
            }
            resultMap.putIfAbsent(targetRelationId, target.getEntity());
        }
        return resultMap;
    }

    @Override
    public boolean include() {
        return !targetToManyMap.isEmpty();


   Args:
            x_transitions (numpy.array): positions where transitions are placed
            start (str): How the binary code starts:'down' (starts in 0) or 'up' (starts in 1)
            has_draw (bool): If True, draws the code

        """

        x_transitions = np.sort(x_transitions)
        x_transitions = np.hstack((self.x[0], x_transitions, self.x[-1]))
        x_transitions = np.unique(x_transitions)

        t = np.ones_like(self.x)

        i_transitions, _, _ = nearest2(self.x, x_transitions)

        i_transitions = i_transitions.astype(int)

        for i in range(0, len(i_transitions) - 1, 2):
            i0 = i_transitions[i]
            i1 = i_transitions[i + 1]
            t[i0:i1] = 0

        if start == 'up':
            t = 1 - t

        self.u = t

        if has_draw:
            plt.figure(figsize=(18, 5))
            plt.plot(self.x, t)
            plt.plot(x_transitions, np.ones_like(x_transitions), 'ko')
            plt.xlim(self.x[0], self.x[-1])

        return t

    def binary_code(self, x0: float = 0*um, kind: str = 'standard',
                    code: tuple[int] = [1, 1, 0, 0, 1, 0, 1], bit_width: float = 20*um):
        """Binary code in form of 1's and 0's.

        Args:
            kind (str): there are serveral types of codes
                'standard' - normal
                'abs_fag' -  used in some abs encoders
            code (numpy.array): array with values of code
            bit_width (float): size of each data of code
            x0 (float): Initial position
        """

        if kind == 'abs_fag':
            i0_ones = np.ones_like(code)
            i0_zeros = np.zeros_like(code)
            code = np.vstack((i0_zeros, i0_ones, code, i0_ones)).reshape(
                (-1, ), order='F')
            bit_width = bit_width/2

        t = Scalar_mask_X(self.x, self.wavelength)
        t2 = Scalar_mask_X(self.x, self.wavelength)
        t.u = np.zeros(self.x.shape)

        for i0j, j in zip(code, list(range(len(code)))):
            t2.slit(x0 + (j + 0.5) * bit_width, bit_width)
            t.u = t.u + i0j * t2.u

        self.u[-1] = self.u[-2]
        self.u = t.u

        return t.u


@Test
    fun `adding nanoseconds doesn't affect the offset`() {
        assertEquals(
            Time(1, 2, 3, 5) at UtcOffset.MAX,
            time1234 + 1.nanoseconds
        )
    }
}
package io.islandtime

import io.islandtime.format.TimeZoneTextStyle
import io.islandtime.locale.toLocale
import io.islandtime.measures.hours
import io.islandtime.test.AbstractIslandTimeTest
import io.islandtime.zone.TimeZoneRulesException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class TimeZoneTest : AbstractIslandTimeTest() {
    @Test
    fun `can be created from an id of 'Z'`() {
        val zone = TimeZone("Z")
        assertEquals(UtcOffset.ZERO, (zone as TimeZone.FixedOffset).offset)
    }

    @Test
    fun `can be created from a fixed offset id`() {
        assertEquals(UtcOffset(18.hours).asTimeZone(), TimeZone("+18:00"))
        assertEquals(UtcOffset.ZERO.asTimeZone(), TimeZone("-00:00"))
        assertEquals(UtcOffset.ZERO.asTimeZone(), TimeZone("+00:00"))
        assertEquals(UtcOffset((-18).hours).asTimeZone(), TimeZone("-18:00"))
    }

    @Test
    fun `throws an exception when created with an improperly formatted offset id`() {
        listOf(
            "+1800",
            "-1800",
            "-18",
            "+18",
            "+1",
            "-1",
            "-",
            "+",
            "- ",
            "+ "
        ).forEach {
            assertFailsWith<DateTimeException> { TimeZone(it) }
            assertFailsWith<DateTimeException> { TimeZone.FixedOffset(it) }
        }
    }

    @Test
    fun `throws an exception when created with an offset that's outside the valid range`() {
        listOf(
            "+18:00:01",
            "-18:00:01",
            "-18:01",
            "+18:01"
        ).forEach {
            assertFailsWith<DateTimeException> { TimeZone(it) }
            assertFailsWith<DateTimeException> { TimeZone.FixedOffset(it) }
        }
    }

    @Test
    fun `throws an exception when region identifier has less than 2 characters`() {
        listOf("U", "G", "").forEach {
            assertFailsWith<DateTimeException> { TimeZone(it) }
        }
    }

    @Test
    fun `can be created from a region id regardless of validity`() {
        listOf("Etc/UTC", "America/New_York", "America/Boston").forEach {
            assertEquals(TimeZone.Region(it), TimeZone(it))
        }
    }

    @Test
    fun `validated throws an exception if a region-based time zone has an invalid ID`() {
        assertFailsWith<TimeZoneRulesException> { TimeZone("America/Boston").validated() }
    }

    @Test
    fun `validated does nothing if the time zone is valid`() {
        listOf(
            "America/New_York",
            "+18:00",
            "Z"
        ).forEach {
            val zone = TimeZone(it)
            assertEquals(zone, zone.validated())
        }
    }

    @Test
    fun `localizedName and displayName get localized text from the provider`() {
        assertEquals(
            "Greenwich Mean Time",
            TimeZone("Europe/London").localizedName(TimeZoneTextStyle.STANDARD, "en-GB".toLocale())
        )
        assertEquals(
            "Greenwich Mean Time",
            TimeZone("Europe/London").displayName(TimeZoneTextStyle.STANDARD, "en-GB".toLocale())
        )
    }

    @Test
    fun `displayName returns the ID on a fixed offset zone`() {
        as


GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUI.enabled = _materialIndex > 1;
            if (GUILayout.Button("<<", EditorStyles.miniButton))
            {
                _materialIndex = 1;
            }
            if (GUILayout.Button("<", EditorStyles.miniButton))
            {
                _materialIndex -= 1;
            }
            GUI.enabled = true;
            GUILayout.Label($"{_materialIndex}/{_materialTotalIndex}");
            GUI.enabled = _materialIndex < _materialTotalIndex;
            if (GUILayout.Button(">", EditorStyles.miniButton))
            {
                _materialIndex += 1;
            }
            if (GUILayout.Button(">>", EditorStyles.miniButton))
            {
                _materialIndex = _materialTotalIndex;
            }
            GUI.enabled = true;
            if (GUILayout.Button("Amount", EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm = new GenericMenu();
                gm.AddItem(new GUIContent("10"), _pageAmount == 10, () =>
                {
                    _pageAmount = 10;
                    ApplyIndex();
                });
                gm.AddItem(new GUIContent("20"), _pageAmount == 20, () =>
                {
                    _pageAmount = 20;
                    ApplyIndex();
                });
                gm.AddItem(new GUIContent("30"), _pageAmount == 30, () =>
                {
                    _pageAmount = 30;
                    ApplyIndex();
                });
                gm.AddItem(new GUIContent("40"), _pageAmount == 40, () =>
                {
                    _pageAmount = 40;
                    ApplyIndex();
                });
                gm.AddItem(new GUIContent("50"), _pageAmount == 50, () =>
                {
                    _pageAmount = 50;
                    ApplyIndex();
                });
                gm.ShowAsContext();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }
        /// <summary>
        /// 贴图列表GUI
        /// </summary>
        private void OnTextureGUI()
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(10);
            GUILayout.Label(_texturesDisplay.Count.ToString(), GUILayout.Width(_previewWidth));
            if (GUILayout.Button(_sortGC, EditorGlobalTools.Styles.IconButton, GUILayout.Width(20), GUILayout.Height(20)))
            {
                GenericMenu gm = new GenericMenu();
                gm.AddItem(new GUIContent("Ascending"), false, () =>
                {
                    _texturesDisplay.Sort((a, b) => { return string.Compare(a.name, b.name); });
                });
                gm.AddItem(new GUIContent("Descending"), false, () =>
                {
                    _texturesDisplay.Sort((a, b) => { return string.Compare(b.name, a.name); });
                });
                gm.AddSeparator("");
                gm.AddItem(new GUIContent("Alarm Value"), false, () =>
                {
                    _texturesDisplay.Sort((a, b) => { return _textures[b].AlarmLevel - _textures[a].AlarmLevel; });
                });
                gm.ShowAsContext();
            }
            GUILayout.Label("Name", GUILayout.Width(175));
            if (GUILayout.Button(_sortGC, EditorGlobalTools.Styles.IconButton, GUILayout.Width(20), GUILayout.Height(20)))
            {
                GenericMenu gm = new GenericMenu();
                gm.AddItem(new GUIContent("Ascending"), false, () =>
                {
                    _texturesDisplay.Sort((a, b) => { return _textures[a].Size - _textures[b].Size; });


 2024 The KubeStellar Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package metrics

import (
	"testing"
	"time"

	k8smetrics "k8s.io/component-base/metrics"
)

func TestClientMetrics(t *testing.T) {
	reg := k8smetrics.NewKubeRegistry()
	msc := NewMultiSpaceClientMetrics()
	MustRegister(reg.Register, msc)
	cm := msc.MetricsForSpace("outer")
	cm.Record("widgets", "frob", nil, 42*time.Millisecond)
	gathered, err := reg.Gather()
	if err != nil {
		t.Error(err)
	}
	if len(gathered) != 1 {
		t.Fatalf("Got wrong number of MetricFamily: expected 1, got %d", len(gathered))
	}
}
/*
Copyright 2024 The KubeStellar Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package abstract

// PrimitiveMap is a MutableMap implemented by a Go primitve map.
type PrimitiveMap[Key comparable, Val any] map[Key]Val

// Assert that PrimitiveMap implements MutableMap
var _ MutableMap[int, func()] = PrimitiveMap[int, func()]{}

// AsPrimitiveMap makes a primitive map look like a PrimitiveMap.
func AsPrimitiveMap[Key comparable, Val any](pm map[Key]Val) PrimitiveMap[Key, Val] {
	return PrimitiveMap[Key, Val](pm)
}

func (pm PrimitiveMap[Key, Val]) Length() int { return len(pm) }

func (pm PrimitiveMap[Key, Val]) Get(key Key) (Val, bool) {
	val, have := pm[key]
	return val, have
}

func (pm PrimitiveMap[Key, Val]) ContGet(key Key, cont func(Val)) {
	val, have := pm[key]
	if have {
		cont(val)
	}
}

func (pm PrimitiveMap[Key, Val]) Iterate2(yield func(Key, Val) error) error {
	for key, val := range pm {
		err := yield(key, val)
		if err != nil {
			return err
		}
	}
	return nil
}

func (pm PrimitiveMap[Key, Val]) Put(key Key, val Val) (Val, bool) {
	old, had := pm[key]
	pm[key] = val
	return old, had
}

func (pm PrimitiveMap[Key, Val]) Delete(key Key) (Val, bool) {
	old, had := pm[key]
	delete(pm, key)
	return old, had
}
/*
Copyright 2024 The KubeStellar Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package abstract

// Map abstracts reading from a map from Ke


C;限定哪些呢？一句话总结就是：只能读，不能写，但能删能清。</e,v></e,v></e,v>

不信？我们可以看源码。

首先来看values方法：

public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

可以看到values其实是返回了一个Values类的，这是个内部类，就在它后面：

final class Values extends AbstractCollection<V> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<V> iterator()     { return new ValueIterator(); }
        public final boolean contains(Object o) { return containsValue(o); }
        public final Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

看到没有，完全没有提供新数据，完全是操作那个table，或者调用hashMap自己的方法。我之前傻呵呵的找源码是怎么为values（HashMap除了有values这个方法，还有一个属性也叫values，坑爹不？）赋值的，现在才知道自己是这么傻&#


;

  return (

{title}

{category}

{description}

            Price -
            <Currency quantity={price} currency="INR" />

          <button
            className={`button py-2 xxs:px-10 px-8 ${disabled ? "opacity-50" : ""
              }`}
            onClick={() => router.push(`/admin/update-product/${_id}`)}
            disabled={disabled}
          >
            Update
          </button>
          <button
            className={`button-red py-2 xxs:px-10 px-8 ${disabled ? "opacity-50" : ""
              }`}
            onClick={() => deleteProduct(_id)}
            disabled={disabled}
          >
            Delete
          </button>

        <Image
          src={image}
          width={120}
          height={120}
          alt=""
          objectFit="contain"
        />

  );
}

export default ProductInfo;
import Image from "next/image";
import Currency from "react-currency-formatter";
import { useDispatch } from "react-redux";
import { addToCart } from "../../slices/cartSlice";
import Fade from "react-reveal/Fade";
import { useRouter } from "next/router";
import Link from "next/link";
import { ShoppingCartIcon } from "@heroicons/react/solid";

function Product({ _id, title, price, description, category, image }) {
  const dispatch = useDispatch();
  const router = useRouter();
  const addItemToCart = () => {
    //Sending the product as an action to the REDUX store... the cart slice
    dispatch(
      addToCart({
        _id,
        title,
        price,
        description,
        category,
        image,
        qty: 1,
        toast: true,
      })
    );
  };

  return (
    <Fade bottom>

          {category}

        <Image
          src={image}
          height={200}
          width={200}
          alt=""
          objectFit="contain"
          className="cursor-pointer"
          onClick={() => router.push(`/product-details/${_id}`)}
        />

          <Link href={`/product-details/${_id}`}>{title}</Link>

          <Link href={`/product-details/${_id}`}>{description}</Link>

          <Currency quantity={price} currency="INR" />

        <button
          className="mt-auto button flex items-center justify-center"


`ascending`、`descending`、`limit`、`objectId`、`equalTo`、`exists`、`greaterThan`、`greaterThanOrEqualTo`、`lessThan`、`lessThanOrEqualTo`、`containedIn`、`containsAll`。

### 反向关系

在实现一对多关系时，我们经常会在「多」上面保存一个到「一」的指针，leancloud-graphql 会自动在「多」上面创建一个属性，用来表示反向关系。例如因为 Todo 的 owner 是一个指向 \_User 的 Pointer，所以 \_User 上会自动出现一个 `ownerOfTodo`：

```graphql
query {
  _User {
    username, ownerOfTodo {
      title
    }
  }
}
```

这样我们便可以查到每个用户的 Todo：

```javascript
{
  _User: [{
    username: "someone",
    ownerOfTodo: [
      {title: "紧急 Bug 修复"},
      {title: "打电话给 Peter"},
      {title: "还信用卡账单"},
      {title: "买酸奶"}
    ]
  }]
}
```

你也可以在 Relation 上进行反向查询，例如查询每个 Todo 所属的 TodoFolder：

```graphql
query {
  Todo {
    title, containedTodosOfTodoFolder {
      name
    }
  }
}
```

结果（省略了一部分）：

```javascript
{
  Todo: [{
    title: "紧急 Bug 修复",
    containedTodosOfTodoFolder: [
      {name: "工作"},
      {name: "someone"}
    ]
  }, {
    title: "买酸奶",
    containedTodosOfTodoFolder: [
      {name: "购物清单"},
      {name: "someone"}
    ]
  }, {
    title: "团队会议",
    containedTodosOfTodoFolder: [
      {name: "工作"}
    ]
  }]
}
```

### 多级关系

在 GraphQL 中你甚至可以进行多层级的关系查询：

```graphql
query {
  TodoFolder {
    name,
    containedTodos {
      title, owner {
        username, email
      }
    }
  }
}
```

结果（省略了一部分）：

```javascript
{
  TodoFolder: [{
    name: "工作",
    containedTodos: [{
      title: "紧急 Bug 修复",
      owner: {
        username: "someone",
        email: "test@example.com"
      }
    }, // ...
    ]
  }, // ...
  ]
}
```

## 修改对象

GraphQL 毕竟是一个数据查询语言，因此我们仅提供了非常有限的创建和更新对象的功能。

### 创建对象

你可以这样创建一个对象，并要求服务器返回 objectId、标题和优先级：

```graphql
mutation {
  Todo(title: "思考巨石阵是如何修建的") {
    objectId, title, priority
  }
}
```

结果：

```javascript
{
  Todo: {
    objectId: "5853adb7b123db006562f83b",
    title: "思考巨石阵是如何修建的",
    priority: 10
  }
}
```

### 更新对象

然后你可以用非常相似的�


        //adjusting positions to keep same relationship
        adjustPosition(p, player);
        aliens.forEach(alien => {adjustPosition(p, alien)})
    }

    // DRAWING
    p.draw = () => {
        p.background("Navy");

        handleKeyDown(p);
        p.keyPressed = () => {
            handleKeyPress(p);
        }

        player.render(p);

        for (let projectile of projectiles) {
            cleanFromArray(projectile, projectiles, p);
            projectile.render(p);
            projectile.move(p);

        }

        for(let alien of aliens)
        {
            cleanFromArray(alien, aliens, p);
            alien.render(p);

            // check if they are hit
            projectiles.map(projectile =>
            {
                if(isRectColliding(
                    {
                        left: alien.position.x - alien.size.x,
                        right: alien.position.x,
                        top  : alien.position.y - alien.size.y,
                        bottom : alien.position.y
                    },
                    {
                        left : projectile.position.x - alien.size.y,
                        right: projectile.position.x,
                        top  : projectile.position.y - projectile.size.y,
                        bottom : projectile.position.y
                    }
                ))
                {
                    // do womething
                    const indexOfProjectile = projectiles.indexOf(projectile);
                    const indexOfAlien = aliens.indexOf(alien);
                    projectiles.splice(indexOfProjectile, 1);
                    aliens.splice(indexOfAlien, 1);
                }
            }
            // move them
            if(p.frameCount % 120 === 0)
            {
                const num = p.floor(p.random(1, 5));
                switch (num) {
                    case 1:
                        alien.move.up();
                        break;
                    case 2:
                        alien.move.down();
                        break;
                    case 3:
                        alien.move.right();
                        break;
                    case 4:
                        alien.move.left();
                        break;
                }
            }
        }
    }

    /**
     * Returns two-dimensional array of aliens
     */
    let createAliens = (columns : number, rows : number) =>
    {
        /**
         * I imagine splicing the space into "parts".
         * Each alien is placed in a part
         */
        let parts = {
            x : p.windowWidth / columns,
            y : p.windowHeight / rows
        };

        for(let i = 0; i < columns; i++)
        {
            for(let j = 0; j < rows; j++)
            {
                // adjusted for screensize;
                let actualX = parts.x * i;
                let actualY = parts.y * j;

                aliens.push(new Alien(p, {x : actualX, y: actualY}, {x : 30, y:45}, 100));
            }
        }
        return aliens;
    }

}

var sketchP = new p5(sketch);

import {
  ContainerWithImmerAndGlobAccessAndDispatch,
  TContainer,
  TContainerWithStore,
} from './Container';
import {
  eventEmitter,
  IEventEmitter,
  TContainerWithEventEmitter,
} from './decorator/eventEmitter';
import {IPipe, pipe, TContainerWithPipe} from './decorator/pipe';
import {ISaga, saga} from './decorator/saga';

export interface Mediator<U extends TContainer<V>, V extends


= bookUrl,
            index = down_chapters_index,
            v = os.time()
        })
    end, nil, {
        timeouts = {18, 25}
    }, 'GetChapterContent')
end

function M:saveBookProgress(chapter)

    if not (H.is_str(chapter.name) and H.is_str(chapter.bookUrl)) then
        return wrap_response(nil, '参数错误')
    end
    local chapters_index = chapter.chapters_index

    return self:legadoSporeApi(function()
        return self.apiClient:saveBookProgress({
            name = chapter.name,
            author = chapter.author or '',
            durChapterPos = 0,
            durChapterIndex = chapters_index,
            durChapterTime = time.to_ms(time.now()),
            durChapterTitle = chapter.title or '',
            index = chapters_index,
            url = chapter.bookUrl,
            v = os.time()
        })
    end, nil, {
        timeouts = {3, 5}
    }, 'saveBookProgress')

end

function M:getAvailableBookSource(bookinfo)
    if not (H.is_tbl(bookinfo) and H.is_str(bookinfo.bookUrl)) then
        return wrap_response(nil, '获取可用书源参数错误')
    end

    local bookUrl = bookinfo.bookUrl
    local name = bookinfo.name
    local author = bookinfo.author
    if self:_isLegadoApp() then
        return self:searchBookSocket(name, {
            name = name,
            author = author
        })
    end
    return self:legadoSporeApi(function()
        -- data=bookinfos
        return self.apiClient:getAvailableBookSource({
            refresh = 0,
            url = bookUrl,
            v = os.time()
        })
    end, nil, {
        timeouts = {30, 50},
        isServerOnly = true
    }, 'getAvailableBookSource')

end

function M:getBookSourcesList()
    return self:legadoSporeApi(function()
        return self.apiClient:getBookSources({
            simple = 1,
            v = os.time()
        })
    end, nil, {
        timeouts = {15, 20},
        isServerOnly = true
    }, 'getBookSourcesList')
end

function M:setBookSource(newBookSource)
    -- origin = bookSourceUrl
    -- return bookinfo
    if not H.is_tbl(newBookSource) or not H.is_str(newBookSource.bookUrl) or not H.is_str(newBookSource.newUrl) or
        not H.is_str(newBookSource.bookSourceUrl) then
        return wrap_response(nil, '更换书源参数错误')
    end

    return self:legadoSporeApi(function()
        -- data=bookinfo
        return self.apiClient:setBookSource({
            bookUrl = newBookSource.bookUrl,
            bookSourceUrl = newBookSource.bookSourceUrl,
            newUrl = newBookSource.newUrl,
            v = os.time()
        })
    end, function(response)
        if H.is_str(response.data.name) and H.is_str(response.data.bookUrl) and H.is_str(response.data.origin) then
            local bookShelfId = self:getServerPathCode()
            local response = {response.data}
            local status, err = pcall(function()
                return self.dbManager:upsertBooks(bookShelfId, response, true)
            end)

            if not status then
                dbg.log('setBookSource数据写入', tostring(err))
                return wrap_response(nil, '数据写入出错，请重试')
            end
            return wrap_response(true)
        else
            return w


d,this.cwd)||vt.dot;let e=this.manifest.name?this.manifest.name:Da(null,`${this.computeCandidateName()}-${cs(this.relativeCwd).substring(0,6)}`);this.anchoredDescriptor=On(e,`${Ei.protocol}${this.relativeCwd}`),this.anchoredLocator=Ws(e,`${Ei.protocol}${this.relativeCwd}`);let r=this.manifest.workspaceDefinitions.map(({pattern:a})=>a);if(r.length===0)return;let s=await(0,ude.default)(r,{cwd:fe.fromPortablePath(this.cwd),onlyDirectories:!0,ignore:["**/node_modules","**/.git","**/.yarn"]});s.sort(),await s.reduce(async(a,n)=>{let c=J.resolve(this.cwd,fe.toPortablePath(n)),f=await ce.existsPromise(J.join(c,"package.json"));await a,f&&this.workspacesCwds.add(c)},Promise.resolve())}get anchoredPackage(){let e=this.project.storedPackages.get(this.anchoredLocator.locatorHash);if(!e)throw new Error(`Assertion failed: Expected workspace ${HB(this.project.configuration,this)} (${_t(this.project.configuration,J.join(this.cwd,Er.manifest),ht.PATH)}) to have been resolved. Run "yarn install" to update the lockfile`);return e}accepts(e){let r=e.indexOf(":"),s=r!==-1?e.slice(0,r+1):null,a=r!==-1?e.slice(r+1):e;if(s===Ei.protocol&&J.normalize(a)===this.relativeCwd||s===Ei.protocol&&(a==="*"||a==="^"||a==="~"))return!0;let n=cl(a);return n?s===Ei.protocol?n.test(this.manifest.version??"0.0.0"):this.project.configuration.get("enableTransparentWorkspaces")&&this.manifest.version!==null?n.test(this.manifest.version):!1:!1}computeCandidateName(){return this.cwd===this.project.cwd?"root-workspace":`${J.basename(this.cwd)}`||"unnamed-workspace"}getRecursiveWorkspaceDependencies({dependencies:e=Ht.hardDependencies}={}){let r=new Set,s=a=>{for(let n of e)for(let c of a.manifest[n].values()){let f=this.project.tryWorkspaceByDescriptor(c);f===null||r.has(f)||(r.add(f),s(f))}};return s(this),r}getRecursiveWorkspaceDependents({dependencies:e=Ht.hardDependencies}={}){let r=new Set,s=a=>{for(let n of this.project.workspaces)e.some(f=>[...n.manifest[f].values()].some(p=>{let h=this.project.tryWorkspaceByDescriptor(p);return h!==null&&MB(h.anchoredLocator,a.anchoredLocator)}))&&!r.has(n)&&(r.add(n),s(n))};return s(this),r}getRecursiveWorkspaceChildren(){let e=new Set([this]);for(let r of e)for(let s of r.workspacesCwds){let a=this.project.workspacesByCwd.get(s);a&&e.add(a)}return e.delete(this),Array.from(e)}async persistManifest(){let e={};this.manifest.exportTo(e);let r=J.join(this.cwd,Ht.fileName),s=`${JSON.stringify(e,null,this.manifest.indent)}
`;await ce.changeFilePromise(r,s,{automaticNewlines:!0}),this.manifest.raw=e}}});function nat({project


0moPUNrGDFlsaaCsF9FAqO2"
            + "uhir6Du+RxZvZG93i7QaCoGs0gpgOo5uJgOmmWM8FID2HDF5tB+btPtKi7G2al06"
            + "ziIjie9YJBVYOVFgDUEAAl/6b0DYyCT8x+BC1ZrYrhDpxueVSK68fHg85ytzakV6"
            + "h73jWRnuy7BrqvVOSrHcl/RieJNAc9F1XvjRdqA/cADOzaM8xPZzjeLsw1k0tdSq"
            + "eL330FvAmLpMuTWRhokJ+Ia5HdhH7ei+bBQU5FRW/AejnulDOzdU+D2IurQeLL6q"
            + "pWs1uOvpPESokJ1sRDax9nmZU/2UEsVEAoXUcEFlnDZ/U1QzFUf3Hh4WbsIuMHMz"
            + "CteTcZR6VunSzWP1VtdNO+YjmCP45yK8QwnIOYTMJQY0EjSgzmilT2cebCsjSZwB"
            + "u8PonZTQ4WNrC4FzaPfCmoG9sAyBhRYUDelQ0lW0BOaTpc72EsLACIbVnw+CKmz6"
            + "G1W4bTrhjJN0bF0jowQxIpPuI7EDRoCacyq8uC+u3zgvn9OLU3VSOLdjbjliUXqK"
            + "uVQw2UW+DzIblxGw+Lt0vMe69YJrYRgz7F2rYlNhcj60digs1141BkjmTQhxnpqs"
            + "uF/KzORJifzpeNDf0IywkATt4Cuw/5fjZfardIDuo/oW0FxxO1Aj1himj9yyw82O"
            + "WyZnnE19XwHppfLxTuNb5KQHanmJsgCg3M/veOsMKHgT+DcYz0pOcJO6+yrAEtE3"
            + "CqOWoAABO0wPRe11aeNafwDUP39twaeaXDaY9XH6dDjxDyshABOO1XQPkC0XKgL1"
            + "IJEEtF8vM2ng6ix70JvAb0Acpd6t33QpabGVWz6/tHL6D7teRG+WEzTutaOaAFNm"
            + "3/CBis6C4aIQi+u5UOhnA7r6syvNaHk9OBbp2jbfecGi7v0EAfeNX9DpMiOhN88Z"
            + "FP0u0+lyc11QOVZsc+zcypooWKRK4+ZuWuO/F6wOMoT1PEcv8ND1How9QKre6xi4"
            + "UA+OUOvgqDnANcNO+lRJhEuK30Z+gZczLXgUiumvtIiAyuSsdJikmTV1TnIRUiem"
            + "bECk0VOUgbslH58KdWHuPG6xA7Nc9C7+NNOYhnahoWVp23CCoMgDBGsvcBx1k9TM"
            + "H8gdOf03molq9+DR6Z7GYDmOWesqwvnqZDB177TJgFnnj5HtvHgqsSbh0d8WYzrR"
            + "jfiNK6Ynh9MJLOe+7Y/Uimnl1fsWE4SbmmYVHdPY55BEMr4


                  /* "{{"  */
  YYSYMBOL_OPEN_BRACE = 163,               /* "new scope"  */
  YYSYMBOL_CLOSE_BRACE = 164,              /* "close scope"  */
  YYSYMBOL_SEMICOLON = 165,                /* "end of line"  */
  YYSYMBOL_INTEGER = 166,                  /* "integer constant"  */
  YYSYMBOL_LONG_INTEGER = 167,             /* "long integer constant"  */
  YYSYMBOL_UNSIGNED_INTEGER = 168,         /* "unsigned integer constant"  */
  YYSYMBOL_UNSIGNED_LONG_INTEGER = 169,    /* "unsigned long integer constant"  */
  YYSYMBOL_UNSIGNED_INT8 = 170,            /* "unsigned int8 constant"  */
  YYSYMBOL_DAS_FLOAT = 171,                /* "floating point constant"  */
  YYSYMBOL_DOUBLE = 172,                   /* "double constant"  */
  YYSYMBOL_NAME = 173,                     /* "name"  */
  YYSYMBOL_KEYWORD = 174,                  /* "keyword"  */
  YYSYMBOL_TYPE_FUNCTION = 175,            /* "type function"  */
  YYSYMBOL_BEGIN_STRING = 176,             /* "start of the string"  */
  YYSYMBOL_STRING_CHARACTER = 177,         /* STRING_CHARACTER  */
  YYSYMBOL_STRING_CHARACTER_ESC = 178,     /* STRING_CHARACTER_ESC  */
  YYSYMBOL_END_STRING = 179,               /* "end of the string"  */
  YYSYMBOL_BEGIN_STRING_EXPR = 180,        /* "{"  */
  YYSYMBOL_END_STRING_EXPR = 181,          /* "}"  */
  YYSYMBOL_END_OF_READ = 182,              /* "end of failed eader macro"  */
  YYSYMBOL_183_begin_of_code_block_ = 183, /* "begin of code block"  */
  YYSYMBOL_184_end_of_code_block_ = 184,   /* "end of code block"  */
  YYSYMBOL_185_end_of_expression_ = 185,   /* "end of expression"  */
  YYSYMBOL_SEMICOLON_CUR_CUR = 186,        /* ";}}"  */
  YYSYMBOL_SEMICOLON_CUR_SQR = 187,        /* ";}]"  */
  YYSYMBOL_SEMICOLON_SQR_SQR = 188,        /* ";]]"  */
  YYSYMBOL_COMMA_SQR_SQR = 189,            /* ",]]"  */
  YYSYMBOL_COMMA_CUR_SQR = 190,            /* ",}]"  */
  YYSYMBOL_191_ = 191,                     /* ','  */
  YYSYMBOL_192_ = 192,                     /* '='  */
  YYSYMBOL_193_ = 193,                     /* '?'  */
  YYSYMBOL_194_ = 194,                     /* ':'  */
  YYSYMBOL_195_ = 195,                     /* '|'  */
  YYSYMBOL_196_ = 196,                     /* '^'  */
  YYSYMBOL_197_ = 197,                     /* '&'  */
  YYSYMBOL_198_ = 198,                     /* '<'  */
  YYSYMBOL_199_ = 199,                     /* '>'  */
  YYSYMBOL_200_ = 200,                     /* '-'  */
  YYSYMBOL_201_ = 201,                     /* '+'  */
  YYSYMBOL_202_ = 202,                     /* '*'  */
  YYSYMBOL_203_ = 203,                     /* '/'  */
  YYSYMBOL_204_ = 204,                     /* '%'  */
  YYSYMBOL_UNARY_MINUS = 205,              /* UNARY_MINUS  */
  YYSYMBOL_UNARY_PLUS = 206,               /* UNARY_PLUS  */
  YYSYMBOL_207_ = 207,                     /* '~'  */
  YYSYMBOL_208_ = 208,                     /* '!'  */
  YYSYMBOL_PRE_INC = 209,


 "../stores/mocks";
import * as _ from "../helpers/underscore";
import * as ditto from "../helpers/ditto";

export const basket = (state: Array<Purchase> = Mocks.initialBasket(), action: IPurchaseAction): Array<Purchase> => {

	switch (action.type) {
		case "ADD_PURCHASE":
			// return state.push( Purchase.CreatePurchase(action.sku, action.quantity, action.price) );
			let mockPurchase: Purchase = Purchase.CreatePurchase(action.sku, action.quantity, action.price);
			return ditto.append(state, mockPurchase);

		case "REMOVE_PURCHASE":
			// TODO: Decrement version
			// return List<Purchase>( state.filter((p: Purchase) => p.sku !== action.sku) );
			return ditto.deleteItems(state, (p:Purchase) => p.sku !== action.sku);

		default:
			return state;
	}

}

// IMMUTABLE JS version
// export const basket = (state: List<Purchase> = Mocks.initialBasket(), action: IPurchaseAction) => {

// 	function indexOf(sku: string): number {
// 		return state.findIndex((p: Purchase) => p.sku === action.sku);
// 	}
// 	function bySku(sku: string): Purchase {
// 		let hits = state.filter((p: Purchase) => p.sku === action.sku);
// 		if (hits.count() > 0) {
// 			return hits.first();
// 		}
// 		return null;
// 	}

// 	switch (action.type) {
// 		case "ADD_PURCHASE":
// 			return state.push( Purchase.CreatePurchase(action.sku, action.quantity, action.price) );

// 		case "REMOVE_PURCHASE":
// 			// TODO: Decrement version
// 			return List<Purchase>( state.filter((p: Purchase) => p.sku !== action.sku) );

// 		default:
// 			return state;
// 	}

// }import { existsSync } from "fs"
import { getTaroVersion } from "./util"
import { AppConfig } from "@tarojs/taro"
import { isEmptyObject } from "@tarojs/helper"
import { appConfigCachePath } from "../constants"
import {
  getAppConfig as getAppConfigV3,
  ErrorMessage as ErrorMessageV3,
} from "./version3"
import {
  getAppConfig as getAppConfigV1_2,
  ErrorMessage as ErrorMessageV1_2,
} from "./version1_2"

export enum PageType {
  MAIN_PAGE,
  SUBPACKAGE_ROOT,
  SUBPACKAGE_ITEM,
}

export interface MainPageType {
  value: string
  type: PageType.MAIN_PAGE
}

export interface SubpackageRoot {
  value: Taro.SubPackage
  type: PageType.SUBPACKAGE_ROOT
}

export interface SubpackageItem {
  value: string
  root: Taro.SubPackage
  type: PageType.SUBPACKAGE_ITEM
}

export type PageValue = MainPageType | SubpackageRoot | SubpackageItem
export interface PageItem {
  name: string
  value: PageValue
}

export type PageList = PageItem[]

// 判断是否有 app.config.js 的缓存
export function hasAppConfigCache() {
  return existsSync(appConfigCachePath)
}

// 获取 appConfig 内容
export function getAppConfig(): AppConfig {
  const version = getTaroVersion()
  if (version >= 3) {
    return getAppConfigV3()
  } else {
    return getAppConfigV1_2()
  }
}

// 获取 app.config.js 中 pages 字段的列表
export function getApp


 &str, handler: H)
where
    H: 'static + Fn(P) -> Pin<Box<dyn Future<Output = Result<R, E>>>>,
    P: 'static + for<'de> Deserialize<'de>,
    R: Serialize,
    E: RpcErrorCode + std::error::Error,
{
    let name = CString::new(name).unwrap();
    let handler_ptr = Box::into_raw(Box::new(handler)) as *mut c_void;

    unsafe {
        spdk_rpc_register_method(
            name.as_ptr(),
            Some(jsonrpc_handler::<H, P, R, E>),
            handler_ptr,
            SPDK_RPC_RUNTIME,
        );
    }
}
<reponame>gwihlidal/hindranch
extern crate ggez;
extern crate rand;
extern crate toml;
#[macro_use]
extern crate serde_derive;

use ggez::audio;
use ggez::conf::{WindowMode, WindowSetup};
use ggez::event::{self, MouseButton};
use ggez::graphics;
use ggez::graphics::{spritebatch::SpriteBatch, Color, DrawParam, Image, Rect};
use ggez::input::keyboard::{KeyCode, KeyMods};
use ggez::timer;
use ggez::{Context, GameResult};
use nalgebra as na;
use std::cell::RefCell;
use std::env;
use std::path::{self, Path};
use std::rc::Rc;

mod ai;
mod characters;
mod consts;
mod enemy;
mod music;
mod player;
mod settings;
mod sounds;
mod tile_util;
mod types;
mod voice;
mod weapon;

mod dead;
mod intro;
mod menu;
mod outro;
mod prepare;
mod round;

use self::ai::*;
use self::characters::*;
use self::consts::*;
use self::enemy::*;
use self::music::*;
use self::player::*;
use self::settings::*;
use self::sounds::*;
use self::tile_util::*;
use self::types::*;
use self::voice::*;
use self::weapon::*;

use self::dead::*;
use self::intro::*;
use self::menu::*;
use self::outro::*;
use self::prepare::*;
use self::round::*;

use na::Isometry2;
use ncollide2d::shape::{Ball, Cuboid, ShapeHandle};
use ncollide2d::world::CollisionGroups;
use nphysics2d::algebra::Force2;
use nphysics2d::force_generator::{ForceGeneratorHandle, Spring};
use nphysics2d::object::{BodyHandle, Material};
use nphysics2d::volumetric::Volumetric;
use nphysics2d::world::World;

pub const DESIRED_FPS: u32 = 60;
pub const TIME_STEP: f32 = 1.0 / 60.0;

enum Phase {
    Dead(DeadPhase),
    Intro(IntroPhase),
    Menu(MenuPhase),
    Outro(OutroPhase),
    Prepare(PreparePhase),
    Round(RoundPhase),
}

pub struct WorldData {
    world_to_screen: Matrix4,
    screen_to_world: Matrix4,
    map: tiled::Map,
    map_tile_image: graphics::Image,
    map_spritebatch: graphics::spritebatch::SpriteBatch,
    bullets: Vec<Bullet>,
    bullet_batch: SingleImageSpriteBatch,
    wall_pieces: Vec<WallPiece>,
    world: World<f32>,
    engine_data: audio::SoundData,
    font: graphics::Font,
    sounds: Sounds,
    characters: Characters,
    player: Player,
    player_input: PlayerInput,
    splash: graphics::Image,
    dozer_image: Rc<graphics::Image>,
    enemies: Vec<Box<dyn Enemy>>,
    camera_pos: Point2,
    strategic_view: bool,
    character_spritebatch: Rc<RefCell<graphics::spritebatch::SpriteBatch>>,
}

impl WorldData {
    pub fn new(_settings: settings::Settings, ctx: &mut Context) -> Self {
        let map = tiled::parse_file(&Path::new("resources/map.tmx")).unwrap();
        let map_tile_image =
            Image::new(ctx, &map.tilesets[0].images[0].source).expect("opening the tileset image");
        let map_spritebatch = graphics::spritebatch::SpriteBatch::new(map_tile_image.clone());


get("dst"))
    return None

def test_trash_sandbox_logs_dst(monkeypatch, caplog):
    # Enable sandbox mode and sane root
    monkeypatch.setenv("INSPECT_AGENTS_FS_MODE", "sandbox")
    monkeypatch.setenv("INSPECT_AGENTS_FS_ROOT", "/repo")
    monkeypatch.setenv("INSPECT_SANDBOX_PREFLIGHT", "auto")

    _install_tool_decorator_stub(monkeypatch)
    fs: dict[str, str] = {}
    _install_editor_bash_stubs(monkeypatch, fs)

    tool = files_tool()

    async def _roundtrip():
        await tool(params=FilesParams(root=WriteParams(command="write", file_path="docs/a.txt", content="hello")))
        # Trash the file
        return await tool(params=FilesParams(root=TrashParams(command="trash", file_path="/repo/docs/a.txt")))

    caplog.set_level(logging.INFO, logger="inspect_agents.tools")
    asyncio.run(_roundtrip())

    # Verify logs contain destination under /.trash/<ts>/docs/a.txt
    dst = _extract_trash_dst(caplog.records)
    assert dst is not None
    assert "/.trash/" in dst and dst.endswith("/docs/a.txt"), dst

    # Stat the destination path to ensure adapter wrote something
    async def _stat():
        return await tool(params=FilesParams(root=StatParams(command="stat", path=dst)))

    res = asyncio.run(_stat())
    assert hasattr(res, "exists") or isinstance(str(res), str)

def test_trash_sandbox_policy_denied(monkeypatch, caplog):
    monkeypatch.setenv("INSPECT_AGENTS_FS_MODE", "sandbox")
    monkeypatch.setenv("INSPECT_AGENTS_FS_ROOT", "/repo")
    monkeypatch.setenv("INSPECT_SANDBOX_PREFLIGHT", "auto")
    # We'll deny docs/* only for the trash step to allow initial write

    _install_tool_decorator_stub(monkeypatch)
    fs: dict[str, str] = {}
    _install_editor_bash_stubs(monkeypatch, fs)

    tool = files_tool()
    caplog.set_level(logging.INFO, logger="inspect_agents.tools")

    async def _do_trash():
        # Allow write
        monkeypatch.delenv("INSPECT_FS_DENY", raising=False)
        await tool(params=FilesParams(root=WriteParams(command="write", file_path="docs/a.txt", content="hello")))
        # Deny subsequent destructive op (trash)
        monkeypatch.setenv("INSPECT_FS_DENY", "docs/*")
        return await tool(params=FilesParams(root=TrashParams(command="trash", file_path="/repo/docs/a.txt")))

    # Expect ToolException bubbling due to policy denial
    with pytest.raises(Exception):
        asyncio.run(_do_trash())

    # Logs should include PolicyDenied error for files:trash
    msgs = [
        r.getMessage()
        for r in caplog.records
        if isinstance(r.getMessage(), str) and r.getMessage().startswith("tool_event ")
    ]
    joined = "\n".join(msgs)
    assert '"tool": "files:trash"' in joined and '"PolicyDenied"' in joined


 code for the add annotation default response
func (o *AddAnnotationDefault) Code() int {
	return o._statusCode
}

func (o *AddAnnotationDefault) Error() string {
	payload, _ := json.Marshal(o.Payload)
	return fmt.Sprintf("[POST /v1/management/annotations][%d] AddAnnotation default %s", o._statusCode, payload)
}

func (o *AddAnnotationDefault) String() string {
	payload, _ := json.Marshal(o.Payload)
	return fmt.Sprintf("[POST /v1/management/annotations][%d] AddAnnotation default %s", o._statusCode, payload)
}

func (o *AddAnnotationDefault) GetPayload() *AddAnnotationDefaultBody {
	return o.Payload
}

func (o *AddAnnotationDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
	o.Payload = new(AddAnnotationDefaultBody)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

/*
AddAnnotationBody AddAnnotationRequest is a params to add new annotation.
swagger:model AddAnnotationBody
*/
type AddAnnotationBody struct {
	// An annotation description. Required.
	Text string `json:"text,omitempty"`

	// Tags are used to filter annotations.
	Tags []string `json:"tags"`

	// Used for annotating a node.
	NodeName string `json:"node_name,omitempty"`

	// Used for annotating services.
	ServiceNames []string `json:"service_names"`
}

// Validate validates this add annotation body
func (o *AddAnnotationBody) Validate(formats strfmt.Registry) error {
	return nil
}

// ContextValidate validates this add annotation body based on context it is used
func (o *AddAnnotationBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	return nil
}

// MarshalBinary interface implementation
func (o *AddAnnotationBody) MarshalBinary() ([]byte, error) {
	if o == nil {
		return nil, nil
	}
	return swag.WriteJSON(o)
}

// UnmarshalBinary interface implementation
func (o *AddAnnotationBody) UnmarshalBinary(b []byte) error {
	var res AddAnnotationBody
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*o = res
	return nil
}

/*
AddAnnotationDefaultBody add annotation default body
swagger:model AddAnnotationDefaultBody
*/
type AddAnnotationDefaultBody struct {
	// code
	Code int32 `json:"code,omitempty"`

	// message
	Message string `json:"message,omitempty"`

	// details
	Details []*AddAnnotationDefaultBodyDetailsItems0 `json:"details"`
}

// Validate validates this add annotation default body
func (o *AddAnnotationDefaultBody) Validate(formats strfmt.Registry) error {
	var res []error

	if err := o.validateDetails(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (o *AddAnnotationDefaultBody) validateDetails(formats strfmt.Registry) error {
	if swag.IsZero(o.Details) { // not required
		return nil
	}

	for i := 0; i < len(o.Details); i++ {
		if swag.IsZero(o.Details[i]) { // not required
			continue
		}

		if o.Details[i] != nil {
			if err := o.Details[i].Validate(formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName("AddAnnotation default" + "." + "details" + "." + strconv.Itoa(i))
				} else if ce, ok


), this->size()), QColor(130, 40, 90));
    for (auto button : m_buttons) {
        p.setPen(!button.pressed ? QColor(240, 240, 240) : QColor(140, 140, 140));
        p.drawRect(button.geometry);
        p.drawText(button.geometry.adjusted(10, 0, 0, 0), button.text);
    }
}

void QMUIWindow::mousePressEvent(QMouseEvent *event)
{
    // Find button under mouse and set down-presseed state
    for (auto &button : m_buttons) {
        if (button.geometry.contains(event->pos())) {
            button.pressed = true;
            m_pressedButton = &button;
            update();
        }
    }
}

void QMUIWindow::mouseMoveEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    // Check if the mouse cursor is still over any down-pressed button
    if (m_pressedButton) {
        bool nowPressed = m_pressedButton->geometry.contains(event->pos());
        if (nowPressed != m_pressedButton->pressed) {
            m_pressedButton->pressed = nowPressed;
            update();
        }
    }
}

void QMUIWindow::mouseReleaseEvent(QMouseEvent *event)
{
    // Activate button if released on button interior
    if (m_pressedButton) {
        if (m_pressedButton->geometry.contains(event->pos())) {
            m_pressedButton->onActivate();
        }
        m_pressedButton->pressed = false;
        m_pressedButton = nullptr;
        update();
    }
}

void stackOverflow() {
    static volatile int number = 0;
    stackOverflow();
    ++number;
    stackOverflow();
}

volatile void *ptr;
void heapOverflow() {
    for(int i = 0; i < 10000000; ++i) {
        ptr = malloc(100000);
    }
}

int main(int argc, char **argv)
{
    QGuiApplication app(argc, argv);

    QMUIWindow window;

#ifdef Q_OS_WASM
    window.addButton("exit(0)", [](){
        emscripten_force_exit(0);
    });

    window.addButton("exit(1)", [](){
        emscripten_force_exit(1);
    });

    window.addButton("Module.abort()", [](){
        EM_ASM(Module.abort("Abort button pressed"););
    });
#endif

    window.addButton("Stack Overflow", [](){
        stackOverflow();
    });

    window.addButton("Heap Owerflow", [](){
        heapOverflow();
    });

    window.addButton("*((volatile int *)(0)) = 42;", [](){
        *((volatile int *)(0)) = 42;
    });

    window.addButton("memset(100, 1, 1M)", [](){
        int *ptr = (int *)100;
        memset(ptr, 1, 1024 * 1024);
    });

    window.showFullScreen();

    return app.exec();
}

#include "main.moc"
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names o


tions[] = init__JSON_actions_0();

private static byte[] init__JSON_key_offsets_0()
{
	return new byte [] {
	    0,    0,    7,    9,   10,   12,   13,   15,   16,   18,   19
	};
}

private static final byte _JSON_key_offsets[] = init__JSON_key_offsets_0();

private static char[] init__JSON_trans_keys_0()
{
	return new char [] {
	   13,   32,   47,   91,  123,    9,   10,   42,   47,   42,   42,   47,
	   10,   42,   47,   42,   42,   47,   10,   13,   32,   47,    9,   10,
	    0
	};
}

private static final char _JSON_trans_keys[] = init__JSON_trans_keys_0();

private static byte[] init__JSON_single_lengths_0()
{
	return new byte [] {
	    0,    5,    2,    1,    2,    1,    2,    1,    2,    1,    3
	};
}

private static final byte _JSON_single_lengths[] = init__JSON_single_lengths_0();

private static byte[] init__JSON_range_lengths_0()
{
	return new byte [] {
	    0,    1,    0,    0,    0,    0,    0,    0,    0,    0,    1
	};
}

private static final byte _JSON_range_lengths[] = init__JSON_range_lengths_0();

private static byte[] init__JSON_index_offsets_0()
{
	return new byte [] {
	    0,    0,    7,   10,   12,   15,   17,   20,   22,   25,   27
	};
}

private static final byte _JSON_index_offsets[] = init__JSON_index_offsets_0();

private static byte[] init__JSON_indicies_0()
{
	return new byte [] {
	    0,    0,    2,    3,    4,    0,    1,    5,    6,    1,    7,    5,
	    7,    0,    5,    0,    6,    8,    9,    1,   10,    8,   10,   11,
	    8,   11,    9,   11,   11,   12,   11,    1,    0
	};
}

private static final byte _JSON_indicies[] = init__JSON_indicies_0();

private static byte[] init__JSON_trans_targs_0()
{
	return new byte [] {
	    1,    0,    2,   10,   10,    3,    5,    4,    7,    9,    8,   10,
	    6
	};
}

private static final byte _JSON_trans_targs[] = init__JSON_trans_targs_0();

private static byte[] init__JSON_trans_actions_0()
{
	return new byte [] {
	    0,    0,    0,    3,    1,    0,    0,    0,    0,    0,    0,    0,
	    0
	};
}

private static final byte _JSON_trans_actions[] = init__JSON_trans_actions_0();

static final int JSON_start = 1;
static final int JSON_first_final = 10;
static final int JSON_error = 0;

static final int JSON_en_main = 1;

// line 866 "Parser.rl"

        public IRubyObject parseStrict() {
            int cs = EVIL;
            int p, pe;
            IRubyObject result = null;
            ParserResult res = new ParserResult();

// line 2212 "Parser.java"
	{
	cs = JSON_start;
	}

// line 875 "Parser.rl"
            p = byteList.begin();
            pe = p + byteList.length();

// line 2221 "Parser.java"
	{
	int _klen;
	int _trans = 0;
	int _acts;
	int _nacts;
	int _keys;
	int _goto_targ = 0;

	_goto: while (true) {
	switch ( _goto_targ ) {
	case 0:
	if ( p == pe ) {
		_goto_targ = 4;
		continue _goto;
	}
	if ( cs == 0 ) {
		_goto_targ = 5;
		continue _goto;
	}
case 1:
	_match: do {
	_keys = _JSON_key_offsets[cs];


xb0, 0x2c, 0xc8, 0x27, 0x2a, 0x9a, 0x2, 0xf, 0x42, 0x0, 0xe3, 0x46, 0xe2, 0x76, 0xae, 0x66, 0x4e, 0x45, 0xee, 0x80, 0x74, 0x55, 0x74, 0xe2, 0xf5, 0xab, 0x81}\n",
			"        \t            \tactual  : hash.Hash{0x36, 0xf0, 0x28, 0x58, 0xb, 0xb0, 0x2c, 0xc8, 0x27, 0x2a, 0x9a, 0x2, 0xf, 0x42, 0x0, 0xe3, 0x46, 0xe2, 0x76, 0xae, 0x66, 0x4e, 0x45, 0xee, 0x80, 0x74, 0x55, 0x74, 0xe2, 0xf5, 0xab, 0x80}\n",
			"        \t            \t\n",
			"        \t            \tDiff:\n",
			"        \t            \t--- Expected\n",
			"        \t            \t+++ Actual\n",
			"        \t            \t@@ -1,2 +1,2 @@\n",
			"        \t            \t-(hash.Hash) (len=32) 0x36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab81\n",
			"        \t            \t+(hash.Hash) (len=32) 0x36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\n",
			"        \t            \t \n",
			"        \tTest:       \tTestSanitySha3_256\n",
			"--- FAIL: TestSanitySha3_256 (0.00s)\n",
		},
	}
}

func getExceptionTest_TestEncodableRandomBeaconPrivKeyMsgPack() common.Level1TestResult {
	return common.Level1TestResult{
		CommitSha:  COMMIT_SHA,
		RunID:      RUN_ID,
		CommitDate: getCommitDate(),
		JobRunDate: getJobRunDate(),
		Test:       "TestEncodableRandomBeaconPrivKeyMsgPack",
		Package:    "github.com/onflow/flow-go/model/encodable",
		Pass:       0,
		Exception:  1,
		Elapsed:    0,
		Output: []string{
			"=== RUN   TestEncodableRandomBeaconPrivKeyMsgPack\n",
			"bytes: 194--- PASS: TestEncodableRandomBeaconPrivKeyMsgPack (0.00s)\n",
		},
	}
}

// **********************************************************
// ************** Level 1 Summaries Testing *****************
// **********************************************************

// The following GetTestData_Level1_*() functions are used by level 1 unit tests for constructing expected level 1 summaries.
// These expected level 1 summaries will be compared with the generated level 1 summaries created by the level 1 parser.
// Instead of having to represent these level 1 summaries as JSON files, they are represented as structs
// to make them easier to maintain.

// GetTestData_Level1_1CountSingleExceptionTest represents a level 1 summary (as exptected output from level 1 parser)
// with a single no result test and no other tests, count=1.
func GetTestData_Level1_1CountSingleExceptionTest() common.Level1Summary {
	return []common.Level1TestResult{
		getExceptionTest_TestEncodableRandomBeaconPrivKeyMsgPack(),
	}
}

// GetTestData_Level1_1CountPass represents a level 1 summary (as exptected output from level 1 parser)
// with multiple passed tests, count=1.
func GetTestData_Level1_1CountPass() common.Level1Summary


    );
    const wrapperClasses = this.classes(
      ...classy.keys(CSS, {disabled}),
      ...classy.valueKeys(CSS, {floated})
    );
    const labeledClasses = this.classes(
      ...classy.generic(CSS, {labeled: labelPosition || !!label}),
    );
    const ElementType = getElementType(Button, this.properties, this.computeElementType);
    const tabIndex = this.computeTabIndex(ElementType);

    if (!!children.length) {
      const classes = {...uiClass, ...baseClasses, ...wrapperClasses, ...labeledClasses, ...btnClass};
      return v(ElementType, {
        ...rest,
        classes: classes.fixed(...this.fixed),
        tabIndex: tabIndex,
        onClick: this.handleClick
      }, children)
    }
    const _children = [Icon.create(icon), content];
    if (!!label) {
      const labelElement = Label.create(label, {
        basic: true,
        pointing: labelPosition === 'left' ? 'right' : 'left'
      });
      if (labelElement) {
        const classes = {...uiClass, ...baseClasses, ...btnClass};
        const containerClasses = {...uiClass, ...labeledClasses, ...btnClass, ...wrapperClasses};
        children.push(
          v('button', {classes: classes.fixed(), tabIndex}, _children),
          (labelPosition === 'right' || !labelPosition) ? labelElement : null
        );
        return v(ElementType, {
          ...rest,
          tabIndex: 0,
          classes: containerClasses.fixed(...this.fixed),
          onClick: this.handleClick
        }, children)
      }
    }
    const classes = {...uiClass, ...labeledClasses, ...baseClasses, ...btnClass, ...wrapperClasses};
    return v(ElementType, {
      ...rest,
      classes: classes.fixed(...this.fixed),
      tabIndex,
      onClick: this.handleClick
    }, (!!icon) ? _children : [content])
	}
}
import { isDefined } from '../isDefined';

describe('utility function isDefined', () => {
  test('returns "false" when "undefined" argument is passed to function', () => {
    let value: undefined;
    expect(isDefined(value)).toBe(false);
    expect(isDefined(undefined)).toBe(false);
  });

  test('returns "false" when "null" argument is passed to function', () => {
    const value = null;
    expect(isDefined(value)).toBe(false);
    expect(isDefined(null)).toBe(false);
  });

  test('returns "true" for all cases where supplied argument is not "undefined" or "null"', () => {
    expect(isDefined(function () {})).toBe(true);
    expect(isDefined({})).toBe(true);
    expect(isDefined('')).toBe(true);
    expect(isDefined(0)).toBe(true);
    expect(isDefined([])).toBe(true);
  });
});
import { Resolver, Mutation, Args, Query } from '@nestjs/graphql';
import { AdminProfile, Admin } from '@contact/entity/index';
import { CreateAdminProfileInput, UpdateAdminProfileInput } from '@contact/dto/index';
import { NotFoundException, ConflictException } from '@nestjs/common';

@Resolver(AdminProfile)
export class AdminProfileResolver {

  @Query(() => AdminProfile)
  async adminProfile(@Args("adminId") adminId: string): Promise<AdminProfile> {
    return await AdminProfile.findOne({ where: { adminId } });
  }

  @Mutation(() => AdminProfile)
  async createAdminProfile(@Args("adminId") adminId: string, @Args("data") data: CreateAdminProfileInput): Promise<AdminProfile> {
    const adminExist = await Admin.findOne({ where: { id: adminId } });
    if (!adminExist) throw new NotFoundException("You are not an admin")
    const profile = AdminProfile.create({ ...data })
    profile


로틀 처리 |
| useInterval | 주기적 실행 |
| useBatteryStatus | 배터리 상태 감지 |
| useGeolocation | 위치 정보 추적 |
| useMediaQuery | 미디어 쿼리 상태 관리 |
| useClipboard | 클립보드 관리 |
| useKeyPress | 키 입력 감지 |
| useMousePosition | 마우스 위치 추적 |
| useCountdown | 카운트다운 타이머 |
| useCountUp | 카운트업 애니메이션 |
| useFetch | 데이터 페칭 |
| useWebSocket | 웹소켓 통신 |
| useFavicon | 파비콘 변경 |
| useTitle | 페이지 제목 변경 |
| useLocalization | 다국어 지원 |
| useConfirmExit | 페이지 이탈 확인 |
| useWindowScroll | 윈도우 스크롤 위치 추적 |
| useScript | 외부 스크립트 로드 |
| useToggle | boolean 상태 토글 |
| useTimeout | 타이머 관리 |
| useTabNotification | 브라우저 탭 알림 |
| useStorage | 스토리지 통합 관리 |
| useStack | 스택 자료구조 관리 |
| useSpeech | 웹 스피치 API 관리 |
| useSize | DOM 요소 크기 추적 |
| useSessionStorage | 세션 스토리지 관리 |
| useScrollPosition | 스크롤 위치 추적 |
| useSanitizer | HTML 문자열 정제 |
| useQueue | 큐 자료구조 관리 |
| usePrevious | 이전 값 추적 |
| usePreventBodyScroll | body 스크롤 방지 |
| usePrefersTheme | 시스템 테마 감지 |
| usePermissions | 브라우저 권한 관리 |
| useOrientation | 디바이스 방향 감지 |
| useOnlineStatus | 온라인 상태 감지 |
| useNetworkStatus | 네트워크 상태 모니터링 |
| useMutationObserver | DOM 변경 감지 |
| useMediaDevices | 미디어 장치 접근 |
| useIntersectionObserver | 요소 가시성 감지 |
| useFirstRender | 첫 렌더링 감지 |
| useEventListner | 이벤트 리스너 관리 |
| useDeviceOS | 운영체제 감지 |
| useSingleEffect | 단일 실행 이펙트 |
| useWorker | 웹 워커 통신 |
| useViewportSize | 뷰포트 크기 추적 |
| useUrgentUpdate | 긴급 업데이트 트리거 |
| useUpdateEffect |


m(0, 8);
			if (Item)
			{
				ULONG_PTR Addr = GetItemValue(Item, CV_ADDR);
				OpenOpRefList(Addr);
			}
		}
		return true;
	}
	bool CCodeView::OnEventSearchTrRef(WISP_MSG *pMsg)
	{
		if (gpSyser->m_SyserUI.m_SyserCodeDoc.m_bOpen)
		{
			CListStringItem *Item = FindItem(0, 8);
			if (Item)
			{
				ULONG_PTR Addr = GetItemValue(Item, CV_ADDR);
				OpenTRefList(Addr);
			}
		}
		return true;
	}

	bool CCodeView::GetOpRefList(ULONG_PTR Address, TList<ULONG_PTR> & Addrs, ULONG_PTR & Return)
	{
		if (!m_pSyserCodeDoc)
			return false;

		if (!m_pSyserCodeDoc->m_bOpen)
			return false;

		ULONG_PTR Ret;
		if (!m_pSyserCodeDoc->GetAddrValue(Address, &Ret))
			return false;

		Return = Ret;
		CDbgModule *pDbgMod = gpSyser->m_pDebugger->m_DbgModuleList.FindModule(Address);
		if (!pDbgMod)
		{
	#ifdef _RING0_
			pDbgMod = gpSyser->m_pSysDebugger->GetModule(Address);
			if (!pDbgMod)
	#endif
				return false;
		}

		if (Ret < pDbgMod->m_ImageBase)
			return false;

		if (Ret >= pDbgMod->m_ImageBase + pDbgMod->m_ImageSize)
			return false;

	gpSyser->m_MainFrame.CreateProgress(WSTR(""), pDbgMod->m_ImageSize-3);
	unsigned long Progress = (pDbgMod->m_ImageSize-3)/100;

		for (unsigned long i = 0; i < pDbgMod->m_ImageSize-3; ++i)
		{
			ULONG_PTR Op;
			ULONG_PTR Offset = pDbgMod->m_ImageBase+i;

			if (m_pSyserCodeDoc->ReadMemory(Offset, &Op, sizeof(Op)) == sizeof(Op) && Op == Ret)
			{
				Addrs.Append(&Offset);
			}

	if (Progress && !(i%Progress))
	gpSyser->m_MainFrame.UpdateProgress(i);

		}
	gpSyser->m_MainFrame.DestroyProgress();
		return Addrs.Size();
	}

	bool CCodeView::OpenOpRefList(ULONG_PTR Address)
	{
		TList<ULONG_PTR> Addrs;
		if (GetOpRefList(Address, Addrs, Address))
		{
			if (gpSyser->m_MainFrame.m_CrossReferenceForm.IsWindow())
				gpSyser->m_MainFrame.m_CrossReferenceForm.Show(WISP_SH_MINSIZE);
			else	gpSyser->m_MainFrame.m_CrossReferenceForm.Create(0, WISP_SH_MINSIZE);
			gpSyser->m_MainFrame.m_CrossReferenceForm.OpenOpRefList(Addrs, Address);
		} else
		{
			gpSyser->m_MainFrame.m_SystemExplorer.m_TerminalWnd.Printf(WSTR("Can't find Operand Reference\n"));
		}
		return true;
	}

	unsigned long CCodeView::GetTRefList(ULONG_PTR Address, TList<ULONG_PTR> & Addrs)
	{
		CDbgModule *pDbgMod = gpSyser->m_pDebugger->m_DbgModuleList.FindModule(Address);
		if (!pDbgMod)
		{
			if (gpSyser->m_pSysDebugger != gpSyser->m_pDebugger)
				pDbg


1),
h1:where(.root_reset.h1),
:where(.root_reset .__wab_expr_html_text) h1,
:where(.root_reset_tags) h1,
h1:where(.root_reset_tags) {
  font-family: var(--mixin-8j3XoZ4uT_font-family);
  color: var(--mixin-8j3XoZ4uT_color);
  font-size: var(--mixin-8j3XoZ4uT_font-size);
  font-weight: var(--mixin-8j3XoZ4uT_font-weight);
  letter-spacing: var(--mixin-8j3XoZ4uT_letter-spacing);
  line-height: var(--mixin-8j3XoZ4uT_line-height);
}

:where(.root_reset) h2:where(.h2),
h2:where(.root_reset.h2),
:where(.root_reset .__wab_expr_html_text) h2,
:where(.root_reset_tags) h2,
h2:where(.root_reset_tags) {
  font-family: var(--mixin-5aXL6aZTBD_font-family);
  color: var(--mixin-5aXL6aZTBD_color);
  font-size: var(--mixin-5aXL6aZTBD_font-size);
  font-weight: var(--mixin-5aXL6aZTBD_font-weight);
  letter-spacing: var(--mixin-5aXL6aZTBD_letter-spacing);
  line-height: var(--mixin-5aXL6aZTBD_line-height);
}

:where(.root_reset) h3:where(.h3),
h3:where(.root_reset.h3),
:where(.root_reset .__wab_expr_html_text) h3,
:where(.root_reset_tags) h3,
h3:where(.root_reset_tags) {
  font-family: var(--mixin-Axc4TAIqRn_font-family);
  color: var(--mixin-Axc4TAIqRn_color);
  font-size: var(--mixin-Axc4TAIqRn_font-size);
  font-weight: var(--mixin-Axc4TAIqRn_font-weight);
  letter-spacing: var(--mixin-Axc4TAIqRn_letter-spacing);
  line-height: var(--mixin-Axc4TAIqRn_line-height);
}

:where(.root_reset) h4:where(.h4),
h4:where(.root_reset.h4),
:where(.root_reset .__wab_expr_html_text) h4,
:where(.root_reset_tags) h4,
h4:where(.root_reset_tags) {
  font-family: var(--mixin-L6FpGFmlSf_font-family);
  color: var(--mixin-L6FpGFmlSf_color);
  font-size: var(--mixin-L6FpGFmlSf_font-size);
  font-weight: var(--mixin-L6FpGFmlSf_font-weight);
  letter-spacing: var(--mixin-L6FpGFmlSf_letter-spacing);
  line-height: var(--mixin-L6FpGFmlSf_line-height);
}

:where(.root_reset) h5:where(.h5),
h5:where(.root_reset.h5),
:where(.root_reset .__wab_expr_html_text) h5,
:where(.root_reset_tags) h5,
h5:where(.root_reset_tags) {
  font-family: var(--mixin-wdVMhj1zYC_font-family);
  color: var(--mixin-wdVMhj1zYC_color);
  font-size: var(--mixin-wdVMhj1zY


= constraintHandle;
            }
            var reference = solver.GetConstraintReference(constraintHandle);
            Debug.Assert(reference.IndexInTypeBatch >= 0 && reference.IndexInTypeBatch < reference.TypeBatch.ConstraintCount);
            narrowPhase.contactConstraintAccessors[reference.TypeBatch.TypeId].ScatterNewImp


14.0.sdk -mmacosx-version-min=10.15.0  -c ../../flutter/assets/directory_asset_bundle.cc -o  obj/flutter/assets/assets.directory_asset_bundle.o"
  },
]
''', flush: true);
      final Build targetBuild = buildConfig.builds[0];
      final BuildRunner buildRunner = BuildRunner(
        platform: FakePlatform(operatingSystem: Platform.linux, numberOfProcessors: 32),
        processRunner: ProcessRunner(
          // dryRun should not try to spawn any processes.
          processManager: _fakeProcessManager(),
        ),
        abi: ffi.Abi.linuxX64,
        engineSrcDir: srcDir,
        build: targetBuild,
      );
      final List<RunnerEvent> events = <RunnerEvent>[];
      void handler(RunnerEvent event) => events.add(event);
      await buildRunner.run(handler);
      expect(file.readAsStringSync(), r'''
[
  {
    "file": "../../flutter/assets/asset_manager.cc",
    "directory": "/Users/flutter/src/engine/src/out/host_debug_unopt_arm64",
    "command": "../../flutter/buildtools/mac-x64/clang/bin/clang++ -MMD -MF  obj/flutter/assets/assets.asset_manager.o.d  -DUSE_OPENSSL=1 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D_FORTIFY_SOURCE=2 -D_LIBCPP_DISABLE_AVAILABILITY=1 -D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS -D_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS -D_DEBUG -DFLUTTER_RUNTIME_MODE_DEBUG=1 -DFLUTTER_RUNTIME_MODE_PROFILE=2 -DFLUTTER_RUNTIME_MODE_RELEASE=3 -DFLUTTER_RUNTIME_MODE_JIT_RELEASE=4 \"-DDART_LEGACY_API=[[deprecated]]\" -DFLUTTER_RUNTIME_MODE=1 -DFLUTTER_JIT_RUNTIME=1  -I../.. -Igen -I../../flutter/third_party/libcxx/include -I../../flutter/third_party/libcxxabi/include -I../../flutter/build/secondary/flutter/third_party/libcxx/config -I../../flutter  -fno-strict-aliasing -fstack-protector-all --target=arm64-apple-macos -arch arm64 -fcolor-diagnostics -Wall -Wextra -Wendif-labels -Werror -Wno-missing-field-initializers -Wno-unused-parameter -Wno-unused-but-set-parameter -Wno-unused-but-set-variable -Wno-implicit-int-float-conversion -Wno-deprecated-copy -Wno-psabi -Wno-deprecated-literal-operator -Wno-unqualified-std-cast-call -Wno-non-c-typedef-for-linkage -Wno-range-loop-construct -Wunguarded-availability -Wno-deprecated-declarations -no-canonical-prefixes -fvisibility=hidden -Wstring-conversion -Wnewline-eof -O0 -g2 -Wunreachable-code  -fvisibility-inlines-hidden -std=c++17 -fno-rtti -nostdinc++ -nostdinc++ -fvisibility=hidden -fno-exceptions -stdlib=libc++ -isysroot ../../flutter/prebuilts/SDKs/MacOSX14.0.sdk -mmacosx-version-min=10.15.0  -c ../../flutter/assets/asset_manager.cc -o  obj/flutter/assets/assets.asset_manager.o"
  },
  {
    "file": "../../flutter/assets/directory_asset_bundle.cc",
    "directory": "/Users/flutter/src/engine/src/out/host_debug_unopt_arm64",
    "command": "../../flutter/buildtools/mac-x64/cl


################################# bld_linux_connector_oddbc ################################
def build_src_connector_odbc(name, kvm_image):
    f_src_connector_odbc= BuildFactory()
    args= ["--port="+getport(), "--user=buildbot", "--smp=4", "--cpu=qemu64"]
    f_src_connector_odbc.addStep(ShellCommand(
        description=["cleaning", "build", "dir"],
        descriptionDone=["clean", "build", "dir"],
        command=["sh", "-c", "rm -Rf ../build/*"]))
    f_src_connector_odbc.addStep(ShellCommand(
        description=["rsyncing", "VMs"],
        descriptionDone=["rsync", "VMs"],
        doStepIf=(lambda(step): step.getProperty("slavename") != "bb01"),
        haltOnFailure=True,
        command=["rsync", "-a", "-v", "-L",
                 "bb01.mariadb.net::kvm/vms/"+kvm_image+"-build.qcow2",
                 "/kvm/vms/"]))
    f_src_connector_odbc.addStep(Compile(
        description=["building", "linux-connctor_odbc"],
        descriptionDone=["build", "linux-connector_odbc"],
        timeout=3600,
        env={"TERM": "vt102"},
        command=["runvm", "--base-image=/kvm/vms/"+kvm_image+"-build.qcow2"] + args +["vm-tmp-"+getport()+".qcow2",
        "rm -Rf buildbot && mkdir buildbot",
        WithProperties("""
set -ex
git --version
rm -Rf build
rm -Rf cc

CCINSTDIR="${PWD}/cc"
time git clone --depth 1 -b %(branch)s "https://github.com/MariaDB-Corporation/mariadb-connector-odbc.git" build
cd build
git reset --hard %(revision)s
rm -rf ./test

# Building and installing C/C to test build from source and against C/C installation
# Directory for C/C installtaion
mkdir ../cc
git submodule init
git submodule update
cd libmariadb
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DWITH_SSL=OPENSSL -DWITH_UNIT_TESTS=Off -DCMAKE_INSTALL_PREFIX=$CCINSTDIR .
make
make install
cd ..
ls $CCINSTDIR
echo $LIBRARY_PATH
echo $CPATH
export LIBRARY_PATH="${LIBRARY_PATH}:${CCINSTDIR}/lib:${CCINSTDIR}/lib/mariadb"
export CPATH="${CPATH}:${CCINSTDIR}/include:${CCINSTDIR}/include/mariadb"
# We need it deleted for source package generation
rm -rf ./libmariadb
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DWITH_OPENSSL=OFF -DGIT_BUILD_SRCPKG=1 .
ls -l ./mariadb*odbc*src*tar.gz ./mariadb*odbc*src*.zip
SRC_PACK_NAME=`ls ./mariadb*src*tar.gz`
tar ztf $SRC_PACK_NAME
cd ..
tar zxf build/$SRC_PACK_NAME
ls
cd mariadb*src*
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DWITH_OPENSSL=OFF -DCONC_WITH_UNIT_TESTS=Off -DWITH_UNIT_TESTS=Off -DMARIADB_LINK_DYNAMIC=1 .
make
"""),
        "= scp -r -P "+getport()+" "+kvm_scpopt+" buildbot@localhost:/home/buildbot/build/mariadb*odbc*src*.* .",
        ]))
#make package_source
    f_src_connector_odbc.addStep(SetPropertyFromCommand(
        property="src_pack_name",
        command=["sh", "-c", WithProperties("basename `ls mariadb*odbc*src*tar.gz`")],
        ))
    addPackageUploadStep(f_src_connector_odbc, '"%(src_pack_name)s"')
    f_src_connector_odbc.addStep(SetPropertyFromCommand(
        property="src_pack_name",
        command=["sh", "-c", WithProperties("basename `ls mariadb*odbc*src*.zip`")],
        ))
    addPackageUploadStep(f_src_connector_odbc, '"%(src_pack_name)s"')
    return {'name': name, 'builddir': name,
            'factory': f_src_connector_odbc,
            "slavenames": connector_slaves,
            "category": "connectors"}

bld_codbc_src= build_src_connector_odbc("codbc-source-package", "vm-buster-amd64");
#sudo apt-get update
#sudo sh -c "DEBIAN_FRONTEND=noninteractive apt-get install --allow-unauthenticated -y --force-yes -m unixodbc-dev"


}>	\n[]	\n-	\n
\n
\ndefault-index	\n\u9ED8\u8BA4\u9009\u4E2D\u9879	\nBoolean	\n0	\n-	\n
\n
\ninvalid-index	\n\u7981\u7528\u9009\u62E9\u9879\u7D22\u5F15	\nNumber	\n-1	\n-	\n
\n
\ncancel-text	\n\u53D6\u6D88\u6309\u94AE\u6587\u6848	\nString	\n-	\n-	\n
\n
\nlarge-radius 2.4.0+	\n\u5927\u5706\u89D2\u6A21\u5F0F	\nBoolean	\nfalse	\n-	\n
\n

\n
ActionSheet Events#

@selected(item)#

\u9009\u62E9\u4E8B\u4EF6
\n
\n
\n
\n\u5C5E\u6027	\n\u8BF4\u660E	\n\u7C7B\u578B	\n
\n
\n

\nitem	\n\u9009\u4E2D\u9879\u7684\u503C	\nObject: {text, value}	\n
\n

\n
@cancel()#

\u53D6\u6D88\u9009\u62E9\u4E8B\u4EF6
\n
@show()#

\u9762\u677F\u5C55\u793A\u4E8B\u4EF6
\n
@hide()#

\u9762\u677F\u9690\u85CF\u4E8B\u4EF6
\n
ActionSheet Static Methods<a href=\"javascript:jumpAnchor('Act


driverClearDao.save(driverClear);
			} else {
				driverClearDao.save(driverClear);
				cargoReceiptDao.updateStateByCode("已结合同", driverClear.getBackBillCode());
			}
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println("司机结算 插入失败！");
			return false;
		}
	}

	@Override
	public List<CustomerBillClear> selectCusclear(String eventName) {
		List<CustomerBillClear> customerBillCleareds = new ArrayList(); // 已结
		List<CustomerBillClear> customerBillUnClears = new ArrayList(); // 未结

		if (eventName.equals("已结运单")) {
			List<GoodsBillEvent> goodsBillEvents = goodsBillEventDao.findByEventName("已结运单");
			for (GoodsBillEvent goodsBillEvent : goodsBillEvents) {
				CustomerBillClear customerBillClear = customerBillClearDao
						.findByGoodsBillCode(goodsBillEvent.getGoodsBillId());
				customerBillCleareds.add(customerBillClear);
			}
			return customerBillCleareds;
		} else {
			List<GoodsBillEvent> goodsBillEvents = goodsBillEventDao.findByEventName("未结");
			for (GoodsBillEvent goodsBillEvent : goodsBillEvents) {
				GoodsBill goodsBill = goodsBillDao.findByGoodsBillCode(goodsBillEvent.getGoodsBillId());
				CustomerBillClear temp = customerBillClearDao.findByGoodsBillCode(goodsBillEvent.getGoodsBillId());
				if (temp == null) {
					CustomerBillClear customerBillClear = new CustomerBillClear();
					customerBillClear.setCustomerCode(goodsBill.getSendGoodsCustomerNo()); // 客户编号
					customerBillClear.setGoodsBillCode(goodsBillEvent.getGoodsBillId()); // 货运单编号
					customerBillClear.setCarriageReduceFund(goodsBill.getReduceFund()); // 减款
					customerBillClear.setInsurance(goodsBill.getInsurance()); // 保险费
					customerBillClear.setPayKickback(goodsBill.getPayKickback()); // 付回扣
					customerBillClear.setCarryGoodsFee(goodsBill.getCarryGoodsFee());// 送货费
					customerBillClear.setBalanceType("结入"); // 结算类型

					customerBillClearDao.save(customerBillClear);
					customerBillUnClears.add(customerBillClear);
				} else {
					customerBillUnClears.add(temp);
				}

			}
			return customerBillUnClears;
		}
	}

	@Override
	public CustomerBillClear selectByBillCode(String goodsBillCode) {
		// TODO Auto-generated method stub
		return customerBillClearDao.findByGoodsBillCode(goodsBillCode);
	}

	@Override
	public boolean cusClear(CustomerBillClear customerBillClear) {
		System.out.println(customerBillClear);
		try {
			double billMoney = customerBillClear.getBillMoney(); // 本单
			double insurance = customerBillClear.getInsurance(); // 保险费
			double carriageReduceFund = customerBillClear.getCarriageReduceFund(); // 减款
			double prepayMoney = customerBillClear.getPrepayMoney(); // 预付金额
			double receivedMoney = customerBillClear.getReceivedMoney(); // 已收

			double moneyReceivable = billMoney + insurance - carriageReduceFund - prepayMoney; // 应收

			customerBillClear.setMoneyReceivable(moneyReceivable);

			do


INT Height;
    DXGI_RATIONAL RefreshRate;
    DXGI_FORMAT Format;
    DXGI_MODE_SCANLINE_ORDER ScanlineOrdering;
    DXGI_MODE_SCALING Scaling;
} DXGI_MODE_DESC;
typedef struct DXGI_GAMMA_CONTROL_CAPABILITIES {
    BOOL ScaleAndOffsetSupported;
    float MaxConvertedValue;
    float MinConvertedValue;
    UINT NumGammaControlPoints;
    float ControlPointPositions[1025];
} DXGI_GAMMA_CONTROL_CAPABILITIES;
typedef struct DXGI_RGB {
    float Red;
    float Green;
    float Blue;
} DXGI_RGB;
typedef struct DXGI_GAMMA_CONTROL {
    DXGI_RGB Scale;
    DXGI_RGB Offset;
    DXGI_RGB GammaCurve[1025];
} DXGI_GAMMA_CONTROL;
/* Begin additional prototypes for all interfaces */

/* End additional prototypes */

#ifdef __cplusplus
}
#endif

#endif /* __WIDL_DXGITYPE_H */


/* Copyright (c) 2007-2008 CSIRO
   Copyright (c) 2007-2009 Xiph.Org Foundation
   Copyright (c) 2007-2009 Timothy B. Terriberry
   Written by Timothy B. Terriberry and Jean-Marc Valin */
/*
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef CWRS_H
#define CWRS_H

#include "arch.h"
#include "stack_alloc.h"
#include "entenc.h"
#include "entdec.h"

#ifdef CUSTOM_MODES
int log2_frac(opus_uint32 val, int frac);
#endif

void get_required_bits(opus_int16 *bits, int N, int K, int frac);

void encode_pulses(const int *_y, int N, int K, ec_enc *enc);

opus_val32 decode_pulses(int *_y, int N, int K, ec_dec *dec);

#endif /* CWRS_H */


", "2022-12-28 00:00:00.0"));
    validateRow(response, 29, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 30, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 31, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 32, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 33, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 34, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 35, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 36, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 37, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 38, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 39, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 40, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 41, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 42, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 43, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 44, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 45, List.of("", "", "2022-12-28 00:00:00.0"));
    validateRow(response, 46, List.of("", "", "2022-12-27 00:00:00.0"));
    validateRow(response, 47, List.of("", "", "2022-12-27 00:00:00.0"));
    validateRow(response, 48, List.of("", "", "2022-12-27 00:00:00.0"));
    validateRow(response, 49, List.of("", "", "2022-12-27 00:00:00.0"));
  }

  @Test
  public void sortByEventDateWithOffsetsDesc() throws JSONException {
    // Given
    QueryParamsBuilder params =
        new QueryParamsBuilder()
            .add("includeMetadataDetails=true")
            .add("displayProperty=NAME")
            .add("totalPages=false")
            .add("rowContext=true")
            .add("IpHINAT79UW[-1].A03MvHHogjR[-1].occurreddate=LAST_YEAR")
            .add("pageSize=10")
            .add("page=1")
            .add(
                "dimension=ou:USER_ORGUNIT,gHGyrwKPzej,ciq2USN94oJ,cejWyOfXge6,IpHINAT79UW.A03MvHHogjR.bx6fsa0t90x,IpHINAT79UW.A03MvHHogjR.a3kGcGDCuk6")
            .add("desc=lastupdated")
            .add("relativePeriodDate=2018-01-28");

    // When
    ApiResponse response = actions.query().get("nEenWmSyUEp", JSON, JSON, params);

    // Then
    response
        .validate()
        .statusCode(200)
        .body("headers", hasSize(equalTo(45)))
        .body("rows", hasSize(equalTo(10)))
        .body("height


                       else -> {
                            break // 找到了一个未完成的 source, 不再继续判断
                        }
                    }
                }

                // 尝试立即选择 tier 低的数据源 (具体阈值取决于 fastSelectTierThreshold)
                // See MediaSourceTier
                states
                    .mapIndexedNotNull { i, state ->
                        if (state is MediaSourceFetchState.Succeed) {
                            val source = fastSources[i]
                            val tier = source.getTier()
                            if (tier <= instantSelectTierThreshold) {
                                source
                            } else {
                                null
                            }
                        } else {
                            null
                        }
                    }
                    .let { lowTierSources ->
                        // 该数据源查询成功了, 立即选择它
                        val selected: Media? = mediaSelector.trySelectFromMediaSources(
                            lowTierSources.map { it.mediaSourceId },
                            overrideUserSelection = overrideUserSelection,
                            blacklistMediaIds = blacklistMediaIds,
                            allowNonPreferred = allowNonPreferred,
                        )
                        logger.debug { "done trySelectFromMediaSources 2" }

                        if (selected != null) {
                            // selected one
                            return@combine selected // 'returns' to `firstOrNull`
                        }
                    }

                null
            }.filterNotNull()
                .run {
                    try {
                        firstOrNull().also {
                            logger.debug { "fastSources selected: $it" }
                        }
                    } catch (e: CancellationException) {
                        logger.debug { "fastSources cancelled" }
                        throw e
                    }
                }
                .also {
                    backgroundTasks.cancel() // 不可以使用 cancelScope, 否则会取消整个函数, 导致总是 return null.
                }
        }
    }

    /**
     * 自动选择第一个 [MediaSourceKind.LocalCache] [Media].
     *
     * 当成功选择了一个 [Media] 时返回它. 若已经选择了一个别的, 或没有 [MediaSourceKind.LocalCache] 类型的 [Media] 供选择, 返回 `null`.
     */
    suspend fun selectCached(
        mediaFetchSession: MediaFetchSession,
        maxAttempts: Int = Int.MAX_VALUE,
    ): Media? {
        val isSuccess = object {
            @Volatile
            var value: Media? = null

            @Volatile
            var attempted = 0
        }
        combine(
            mediaFetchSession.cumulativeResults,
        ) { _ ->
            if (mediaSelector.selected.value != null) {
                // 用户已经选择了
                isSuccess.value = null
                return@combine STOP
            }

            val selected = mediaSelector.trySelectCached()
            if (selected != null) {
                isSuccess.value = selected
                STOP
            } else {
                if (++isSuccess.attempted >= maxAttempts) {
                    // 尝试次数过多
                    STOP
                } else {
                    // 继续等待
                    !STOP
                }
            }
        }.takeWhile { it == !STOP }.collect()
        return isSuccess.value
    }

    // #355 播放时自动启用上次临时启用选择的数据源
    suspend fun autoEnableLastSelected(mediaFetchSession: MediaFetchSession) {
        val lastSelectedId = mediaSelector.mediaSourceId.finalSelected.first()
        val lastSelected = mediaFetchSession.mediaSourceResults.firstOrNull {
            it.mediaSourceId == lastSelectedId
        } ?: return
        lastSelected.enable()
    }

    companion object {
        /**
         * 如果快速选择数据源功


 ByteArrayInputStream(inputWithCommentsBytes))
}
/*
 * Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package benchmarks.model // NOT A KOTLINX PACKAGE. Otherwise Moshi starts complaining on platform classes

import kotlinx.serialization.*
import kotlinx.serialization.json.*

// For Jackson/Moshi data

@Serializable
data class DefaultPixelEvent(
    val version: Int,
    val dateTime2: String,
    val serverName: String,
    val domain: String,
    val method: String,
    val clientIp: String,
    val queryString: String,
    val userAgent: String,
    val contentType: String,
    val browserLanguage: String,
    val postData: String,
    val cookies: String
)

val pixelEvent = DefaultPixelEvent(
    version = 1,
    dateTime2 = System.currentTimeMillis().toString(),
    serverName = "some-endpoint-qwer",
    domain = "some.domain.com",
    method = "POST",
    clientIp = "127.0.0.1",
    queryString = "anxa=CASCative&anxv=13.901.16.34566&anxe=FoolbarActive&anxt=E7AFBF15-1761-4343-92C1-78167ED19B1C&anxtv=13.901.16.34566&anxp=%5ECQ6%5Expt292%5ES33656%5Eus&anxsi&anxd=2019-10-08T17%3A03%3A57.246Z&f=00400000&anxr=1571945992297&coid=66abafd0d49f42e58dc7536109395306&userSegment&cwsid=opgkcnbminncdgghighmimmphiooeohh",
    userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0",
    contentType = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    browserLanguage = "en-US,en;q=0.5",
    postData = "-",
    cookies = "_ga=GA1.2.971852807.1546968515"
)

val pixelEventJson = Json.encodeToString(pixelEvent)

val pixelEventWithEscapes = DefaultPixelEvent(
    version = 1,
    dateTime2 = System.currentTimeMillis().toString(),
    serverName = "some-endp\"oint-qwer",
    domain = "<a href=\"some.domain.com\">",
    method = "POST",
    clientIp = "127.0.0.1",
    queryString = "anxa=CASCative&anxv=13.901.16.34566&anxe=\"FoolbarActive\"&anxt=E7AFBF15-1761-4343-92C1-78167ED19B1C&anxtv=13.901.16.34566&anxp=%5ECQ6%5Expt292%5ES33656%5Eus&anxsi&anxd=2019-10-08T17%3A03%3A57.246Z&f=00400000&anxr=1571945992297&coid=\"66abafd0d49f42e58dc7536109395306\"&userSegment&cwsid=opgkcnbminncdgghighmimmphiooeohh",
    userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0",
    contentType = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    browserLanguage = "\"en\"-\"US\",en;\\q=0.5",
    postData = "-",
    cookies = "_ga=GA1.2.971852807.1546968515"
)
package sample

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
class EmptyClassB : EmptyBase()

@Serializable
open class Car : Vehicle() {
    var maxSpeed: Int = 100

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Car) return false
        if (name != other.name) return false
        if (color != other.color) re


let list = json!([100, 200, 300]);
  let mut json_handler = JsonHandler { value: list };

  json_handler.apply_key(&DocPath::new_unwrap("$[3]"), &Generator::RandomInt(0, 10), &hashmap!{}, &DefaultVariantMatcher.boxed());

  expect!(json_handler.value).to(be_equal_to(json!([100, 200, 300])));
}

#[test]
fn does_not_apply_the_generator_when_not_a_list() {
  let list = json!(100);
  let mut json_handler = JsonHandler { value: list };

  json_handler.apply_key(&DocPath::new_unwrap("$[3]"), &Generator::RandomInt(0, 10), &hashmap!{}, &DefaultVariantMatcher.boxed());

  expect!(json_handler.value).to(be_equal_to(json!(100)));
}

#[test]
fn applies_the_generator_to_the_root() {
  let value = json!(100);
  let mut json_handler = JsonHandler { value };

  json_handler.apply_key(&DocPath::root(), &Generator::RandomInt(0, 10), &hashmap!{}, &DefaultVariantMatcher.boxed());

  expect!(&json_handler.value).to_not(be_equal_to(&json!(100)));
}

#[test]
fn applies_the_generator_to_the_object_graph() {
  let value = json!({
    "a": ["A", {"a": "A", "b": {"1": "1", "2": "2"}, "c": "C"}, "C"],
    "b": "B",
    "c": "C"
  });
  let mut json_handler = JsonHandler { value };

  json_handler.apply_key(&DocPath::new_unwrap("$.a[1].b['2']"), &Generator::RandomInt(3, 10), &hashmap!{}, &DefaultVariantMatcher.boxed());

  expect!(&json_handler.value["a"][1]["b"]["2"]).to_not(be_equal_to(&json!("2")));
}

#[test]
fn does_not_apply_the_generator_to_the_object_graph_when_the_expression_does_not_match() {
  let value = json!({
    "a": "A",
    "b": "B",
    "c": "C"
  });
  let mut json_handler = JsonHandler { value };

  json_handler.apply_key(&DocPath::new_unwrap("$.a[1].b['2']"), &Generator::RandomInt(0, 10), &hashmap!{}, &DefaultVariantMatcher.boxed());

  expect!(&json_handler.value).to(be_equal_to(&json!({
    "a": "A",
    "b": "B",
    "c": "C"
  })));
}

#[test]
fn applies_the_generator_to_all_map_entries() {
  let value = json!({
    "a": "A",
    "b": "B",
    "c": "C"
  });
  let mut json_handler = JsonHandler { value };

  json_handler.apply_key(&DocPath::new_unwrap("$.*"), &Generator::RandomInt(0, 10), &hashmap!{}, &DefaultVariantMatcher.boxed());

  expect!(&json_handler.value["a"]).to_not(be_equal_to(&json!("A")));
  expect!(&json_handler.value["b"]).to_not(be_equal_to(&json!("B")));
  expect!(&json_handler.value["c"]).to_not(be_equal_to(&json!("C")));
}

#[test]
fn applies_the_generator_to_all_list_items() {
  let value = json!(["A", "B", "C"]);
  let mut json_handler = JsonHandler { value };

  json_handler.apply_key(&DocPath::new_unwrap("$[*]"), &Generator::RandomInt(0, 10), &hashmap!{


trySet() ) {
            String key = entry.getKey();
            ContainerBeanDto value = containerBeanToContainerBeanDto( entry.getValue() );
            map1.put( key, value );
        }

        return map1;
    }
}
/*
 * Copyright MapStruct Authors.
 *
 * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
 */
package org.mapstruct.ap.test.nestedbeans;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2017-05-04T00:00:45+0200",
    comments = "version: , compiler: javac, environment: Java 1.8.0_131 (Oracle Corporation)"
)
public class UserDtoUpdateMapperSmartImpl implements UserDtoUpdateMapperSmart {

    @Override
    public void userToUserDto(UserDto userDto, User user) {
        if ( user == null ) {
            return;
        }

        if ( user.getName() != null ) {
            userDto.setName( user.getName() );
        }
        else {
            userDto.setName( null );
        }
        if ( user.getCar() != null ) {
            if ( userDto.getCar() == null ) {
                userDto.setCar( new CarDto() );
            }
            carToCarDto( user.getCar(), userDto.getCar() );
        }
        else {
            userDto.setCar( null );
        }
        if ( user.getSecondCar() != null ) {
            if ( userDto.getSecondCar() == null ) {
                userDto.setSecondCar( new CarDto() );
            }
            carToCarDto( user.getSecondCar(), userDto.getSecondCar() );
        }
        else {
            userDto.setSecondCar( null );
        }
        if ( user.getHouse() != null ) {
            if ( userDto.getHouse() == null ) {
                userDto.setHouse( new HouseDto() );
            }
            houseToHouseDto( user.getHouse(), userDto.getHouse() );
        }
        else {
            userDto.setHouse( null );
        }
    }

    protected WheelDto wheelToWheelDto(Wheel wheel) {
        if ( wheel == null ) {
            return null;
        }

        WheelDto wheelDto = new WheelDto();

        wheelDto.setFront( wheel.isFront() );
        wheelDto.setRight( wheel.isRight() );

        return wheelDto;
    }

    protected List<WheelDto> wheelListToWheelDtoList(List<Wheel> list) {
        if ( list == null ) {
            return null;
        }

        List<WheelDto> list1 = new ArrayList<WheelDto>( list.size() );
        for ( Wheel wheel : list ) {
            list1.add( wheelToWheelDto( wheel ) );
        }

        return list1;
    }

    protected void carToCarDto(Car car, CarDto mappingTarget) {
        if ( car == null ) {
            return;
        }

        if ( car.getName() != null ) {
            mappingTarget.setName( car.getName() );
        }
        else {
            mappingTarget.setName( null );
        }
        mappingTarget.setYear( car.getYear() );
        if ( mappingTarget.getWheels() != null ) {
            List<WheelDto> list = wheelListToWheelDtoList( car.getWheels() );
            if ( list != null ) {
                mappingTarget.getWheels().clear();
                mappingTarget.getWheels().addAll( list );
            }
        }
        else {
            List<WheelDto> list = wheelListToWheelDtoList( car.getWheels() );
            if ( list != null ) {
                mappingTarget.setWheels( list );
            }
        }
    }

    protected ExternalRoofType roofTypeToExternalRoofType(RoofType roofType) {
        if ( roofType == null ) {
            return