ng_count_entry.following_count if following_count_entry else 0

    # 获取用户的粉丝数量
    follower_count_entry = UserFollowerCount.query.filter_by(
        user_user_uid=user_uid
    ).first()
    follower_count = follower_count_entry.follower_count if follower_count_entry else 0

    # 调试输出
    print(f"Current User UID: {g.user.user_uid if g.user else None}")
    print(f"Target User UID: {user_uid}")
    print(f"Is Following: {is_following}")

    return render_template(
        'user/user_profile.html',
        user=user_data['user'],
        activities=user_data['activities'],
        likes=user_data['likes'],
        posts=user_data['posts'],
        is_following=is_following,
        following_count=following_count,
        follower_count=follower_count,
        current_user=g.user
    )

@user_bp.route('/user/<int:user_uid>/activity')
def activity(user_uid):
    user_data = get_user_data(user_uid)
    if not user_data:
        return jsonify({'error': '用户不存在'}), 404

    return render_template('user/user_activity.html', user=user_data['user'], activities=user_data['activities'])

@user_bp.route('/user/<int:user_uid>/activity-feed')
def activity_feed(user_uid):
    user_data = get_user_data(user_uid)
    if not user_data:
        return jsonify({'error': '用户不存在'}), 404

    return render_template('user/user_activity_feed.html', user=user_data['user'], activities=user_data['activities'])

@user_bp.route('/user/<int:user_uid>/posts')
def user_posts(user_uid):
    user_data = get_user_data(user_uid)
    if not user_data:
        return jsonify({'error': '用户不存在'}), 404

    return render_template('user/user_posts.html', user=user_data['user'], posts=user_data['posts'])

@user_bp.route('/user/<int:user_uid>/contributions')
def get_user_contributions(user_uid):
    # 获取用户过去70天的贡献数据
    end_date = datetime.now().date()
    start_date = end_date - timedelta(days=69)

    contributions = UserContribution.query.filter(
        UserContribution.user_uid == user_uid,
        UserContribution.date.between(start_date, end_date)
    ).all()

    # 格式化数据
    contributions_data = {}
    for contribution in contributions:
        contributions_data[contribution.date.isoformat()] = contribution.contribution_value

    # 补全缺失的日期（贡献值为0）
    current_date = start_date
    while current_date <= end_date:
        if current_date.isoformat() not in contributions_data:
            contributions_data[current_date.isoformat()] = 0
        current_date += timedelta(days=1)

    return jsonify(contributions_data)

def calculate_contributions(user_uid):
    user = User.query.filter_by(user_uid=user_uid).first()
    if not user:
        return None

    # 获取用户过去70天的活动数据
    end_date = datetime.now().date()
    start_date = end_date - timedelta(days=69)

    # 删除旧的贡献记录（保留最近70天）
    UserContribution.query.filter(
        UserContribution.user_uid == user_uid,
        UserContribution.date < start_date
    ).delete()
    db.session.commit()

    current_date = start_date
    while current_date <= end_date:
        # 计算当天的活动数（帖子、评论、回复、点赞、举报）
        posts_count = Post.query.filter(
            Post.author_id == user.id,
            func.date(Post.created_at) == current_date
        ).count()

        comments_count = Comment.query.filter(
            Comment.author_id == user.id,
            func.date(Comment.created_at) == current_date
        ).count()

        reply_count = ReplyComment.query.filter(
            func.date(ReplyComment.reply_at) == current_date
        ).count()

        like_count = Like.query.filter(
            Like.user_id == user.id,
            func.date(Like.created_at) == current_date
        ).count()

        report_count = Report.query.filter(
            Report.user_id == user.id,
            func.date(Report.created_at) == current_date
        ).count()

        # 总贡献值（每个活动算1点）
        total_contribution = posts_count + comments_count + reply_count + like_count + report_count

        # 新用户注册当天贡献为20
        if current_date == user.created_at.date():
            total_contribution = 20

        # 添加或更新贡献记录
        existing_contribution = UserContribution.query.filter_by(
            user_uid=user_uid,
            date=current_date
        ).first()

        if existing_contribution:
            existing_contribution.contribution_value = total_contribution
        else:
            new_contribution = UserContribution(
                user_uid=user_uid,
                date=current_date,
                contribution_valu


e_a_few();
   _update_item(0, efl_add(EFL_UI_GRID_DEFAULT_ITEM_CLASS, win), EINA_SIZE2D(20, 20));
   _iterate_a_few();
}
EFL_END_TEST

static void
_content_size_cb(void *data, const Efl_Event *ev)
{
   Eina_Size2D *size = data;
   *size = *((Eina_Size2D*)ev->info);
}

EFL_START_TEST(viewport_newsize_event_result)
{
   Eina_Size2D size = EINA_SIZE2D(-2, -2), min_size = EINA_SIZE2D(-2, -2);
   efl_event_callback_add(position_manager,
      EFL_UI_POSITION_MANAGER_ENTITY_EVENT_CONTENT_SIZE_CHANGED, _content_size_cb, &size);
   efl_event_callback_add(position_manager,
      EFL_UI_POSITION_MANAGER_ENTITY_EVENT_CONTENT_MIN_SIZE_CHANGED, _content_size_cb, &min_size);
   _initial_setup();
   _add_item(efl_add(EFL_UI_GRID_DEFAULT_ITEM_CLASS, win), EINA_SIZE2D(20, 20));
   _add_item(efl_add(EFL_UI_GRID_DEFAULT_ITEM_CLASS, win), EINA_SIZE2D(20, 30));

   efl_ui_position_manager_entity_viewport_set(position_manager, EINA_RECT(0, 0, 200, 200));
   _iterate_a_few();

   ck_assert_int_ne(size.w, -2);
   ck_assert_int_ne(size.h, -2);
   ck_assert_int_ne(min_size.w, -2);
   ck_assert_int_ne(min_size.h, -2);
}
EFL_END_TEST

void efl_ui_test_position_manager_common_add(TCase *tc)
{
   tcase_add_checked_fixture(tc, item_container_setup, item_container_teardown);
   tcase_add_test(tc, no_crash1);
   tcase_add_test(tc, no_crash2);
   tcase_add_test(tc, viewport_newsize_event_result);
}


 String {
        return Json.encodeToString(this)
    }

    fun getPrompt(): String {
        val prompt = this.getTypedNode<PromptInputs>(PROMPT)
        return prompt!!.inputs.text
    }
}

@Serializable
data class Node<T>(
    val inputs: T,
    @SerialName("class_type")
    val classType: String,
    @SerialName("_meta")
    val meta: Meta
)

@Serializable
data class Meta(
    val title: String
)

@Serializable
data class SizeInputs(
    val width: Int,
    val height: Int,
    @SerialName("batch_size")
    val batchSize: Int
)

@Serializable
data class PromptInputs(
    val text: String,
    val clip: JsonElement
)

fun Workflow.updateSizeAndBatch(width: Int, height: Int, batchSize: Int) {
    this.updateTypedNode<SizeInputs>(Workflow.SIZE) { node ->
        node.copy(
            inputs = node.inputs.copy(
                width = width,
                height = height,
                batchSize = batchSize
            )
        )
    }
}

fun Workflow.updatePrompt(prompt: String) {
    this.updateTypedNode<PromptInputs>(Workflow.PROMPT) { node ->
        node.copy(
            inputs = node.inputs.copy(
                text = prompt
            )
        )
    }
}

fun updateSeed(node: Node<JsonElement>, seedKey: String, newSeed: Long): Node<JsonElement> {
    val currentInputs = node.inputs.jsonObject
    val updatedInputs = buildJsonObject {
        currentInputs.forEach { (key, value) ->
            if (key == seedKey) {
                put(key, JsonPrimitive(newSeed))
            } else {
                put(key, value)
            }
        }
    }
    return node.copy(inputs = updatedInputs)
}

fun Workflow.updateSeed(seed: Long) {
    this.updateNode(Workflow.KSAMPLER) { node ->
        updateSeed(node, "seed", seed)
    }
    this.updateNode(Workflow.RANDOMNOISE) { node ->
        updateSeed(node, "noise_seed", seed)
    }
}
package com.github.eltonvs.obd.command

import java.util.regex.Pattern

object RegexPatterns {
    val WHITESPACE_PATTERN: Pattern = Pattern.compile("\\s")
    val BUS_INIT_PATTERN: Pattern = Pattern.compile("(BUS INIT)|(BUSINIT)|(\\.)")
    val SEARCHING_PATTERN: Pattern = Pattern.compile("SEARCHING")
    val CARRIAGE_PATTERN: Pattern = Pattern.compile("[\r\n]")
    val CARRIAGE_COLON_PATTERN: Pattern = Pattern.compile("[\r\n].:")
    val COLON_PATTERN: Pattern = Pattern.compile(":")
    val DIGITS_LETTERS_PATTERN: Pattern = Pattern.compile("([0-9A-F:])+")
    val STARTS_WITH_ALPHANUM_PATTERN: Pattern = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE)

    // Error patterns
    const val BUSINIT_ERROR_MESSAGE_PATTERN = "BUS INIT... ERROR"
    const val MISUNDERSTOOD_COMMAND_MESSAGE_PATTERN = "?"
    const val NO_DATE_MESSAGE_PATTERN = "NO DATA"
    const val STOPPED_MESSAGE_PATERN = "STOPPED"
    const val UNABLE_TO_CONNECT_MESSAGE_PATTERN = "UNABLE TO CONNECT"
    const val ERROR_MESSAGE_PATTERN = "ERROR"
    const val UNSUPPORTED_COMMAND_MESSAGE_PATTERN = "7F 0[0-A] 1[1-2]"
}

fun removeAll(pattern: Pattern, input: String): String {
    return pattern.matcher(input).replaceAll("")
}

fun r


aext_sext
sext_remw_aext_sext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl sext_remw_aext_zext
sext_remw_aext_zext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl sext_remw_sext_aext
sext_remw_sext_aext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl sext_remw_sext_sext
sext_remw_sext_sext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl sext_remw_sext_sext_i16
sext_remw_sext_sext_i16:
	sll $t0, $a0, 16
	sra $t0, $t0, 16
	sll $t1, $a1, 16
	sra $t1, $t1, 16
	div $zero, $t0, $t1
	mfhi $t0
	andi $v0, $t0, 65535
	jr $ra
	nop
.p2align 2
.globl sext_remw_sext_sext_i8
sext_remw_sext_sext_i8:
	sll $t0, $a0, 24
	sra $t0, $t0, 24
	sll $t1, $a1, 24
	sra $t1, $t1, 24
	div $zero, $t0, $t1
	mfhi $t0
	andi $v0, $t0, 255
	jr $ra
	nop
.p2align 2
.globl sext_remw_sext_zext
sext_remw_sext_zext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl sext_remw_zext_aext
sext_remw_zext_aext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl sext_remw_zext_sext
sext_remw_zext_sext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl sext_remw_zext_zext
sext_remw_zext_zext:
	div $zero, $a0, $a1
	mfhi $v0
	jr $ra
	nop
.p2align 2
.globl zext_divuw_aext_aext
zext_divuw_aext_aext:
	divu $zero, $a0, $a1
	mflo $v0
	jr $ra
	nop
.p2align 2
.globl zext_divuw_aext_sext
zext_divuw_aext_sext:
	divu $zero, $a0, $a1
	mflo $v0
	jr $ra
	nop
.p2align 2
.globl zext_divuw_aext_zext
zext_divuw_aext_zext:
	divu $zero, $a0, $a1
	mflo $v0
	jr $ra
	nop
.p2align 2
.globl zext_divuw_sext_aext
zext_divuw_sext_aext:
	divu $zero, $a0, $a1
	mflo $v0
	jr $ra
	nop
.


0 - _4bz * q2) * (_2bx * (q0q2 + q1q3) + _2bz * (0.5f - q1q1 - q2q2) - mz);
            s3 = _2q1 * (2.0f * q1q3 - _2q0q2 - ax) + _2q2 * (2.0f * q0q1 + _2q2q3 - ay) + (-_4bx * q3 + _2bz * q1) * (_2bx * (0.5f - q2q2 - q3q3) + _2bz * (q1q3 - q0q2) - mx) + (-_2bx * q0 + _2bz * q2) * (_2bx * (q1q2 - q0q3) + _2bz * (q0q1 + q2q3) - my) + _2bx * q1 * (_2bx * (q0q2 + q1q3) + _2bz * (0.5f - q1q1 - q2q2) - mz);
            recipNorm = invSqrt(s0 * s0 + s1 * s1 + s2 * s2 + s3 * s3); // normalise step magnitude
            s0 *= recipNorm;
            s1 *= recipNorm;
            s2 *= recipNorm;
            s3 *= recipNorm;

            // Apply feedback step
            qDot1 -= beta * s0;
            qDot2 -= beta * s1;
            qDot3 -= beta * s2;
            qDot4 -= beta * s3;
        }

        // Integrate rate of change of quaternion to yield quaternion
        q0 += qDot1 * timeDelta;
        q1 += qDot2 * timeDelta;
        q2 += qDot3 * timeDelta;
        q3 += qDot4 * timeDelta;

        // Normalise quaternion
        recipNorm = invSqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
        q0 *= recipNorm;
        q1 *= recipNorm;
        q2 *= recipNorm;
        q3 *= recipNorm;
    }
    static void MadgwickAHRSupdateIMU(float gx, float gy, float gz, float ax, float ay, float az) {
        float recipNorm;
        float s0, s1, s2, s3;
        float qDot1, qDot2, qDot3, qDot4;
        float _2q0, _2q1, _2q2, _2q3, _4q0, _4q1, _4q2 ,_8q1, _8q2, q0q0, q1q1, q2q2, q3q3;

        // Rate of change of quaternion from gyroscope
        qDot1 = 0.5f * (-q1 * gx - q2 * gy - q3 * gz);
        qDot2 = 0.5f * (q0 * gx + q2 * gz - q3 * gy);
        qDot3 = 0.5f * (q0 * gy - q1 * gz + q3 * gx);
        qDot4 = 0.5f * (q0 * gz + q1 * gy - q2 * gx);

        // Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation)
        if(!((ax == 0.0f) && (ay == 0.0f) && (az == 0.0f))) {

            // Normalise accelerometer measurement
            recipNorm = inv


 80094D6C 000909CC  3C A0 21 0A */	lis r5, 0x210A0C00@ha
/* 80094D70 000909D0  38 A5 0C 00 */	addi r5, r5, 0x210A0C00@l
/* 80094D74 000909D4  4B FF F2 60 */	b lbl_80093FD4
lbl_80094D78:
/* 80094D78 000909D8  4C 82 00 20 */	bnelr
/* 80094D7C 000909DC  2C 05 00 00 */	cmpwi r5, 0
/* 80094D80 000909E0  41 82 00 10 */	beq lbl_80094D90
/* 80094D84 000909E4  3C A0 21 0F */	lis r5, 0x210F0C00@ha
/* 80094D88 000909E8  38 A5 0C 00 */	addi r5, r5, 0x210F0C00@l
/* 80094D8C 000909EC  4B FF F2 48 */	b lbl_80093FD4
lbl_80094D90:
/* 80094D90 000909F0  3C A0 21 0E */	lis r5, 0x210E0C00@ha
/* 80094D94 000909F4  38 A5 0C 00 */	addi r5, r5, 0x210E0C00@l
/* 80094D98 000909F8  4B FF F2 3C */	b lbl_80093FD4
/* 80094D9C 000909FC  4E 80 00 20 */	blr

.global func_80094DA0
func_80094DA0:
/* 80094DA0 00090A00  38 A0 00 01 */	li r5, 1
/* 80094DA4 00090A04  38 6D 9B 98 */	addi r3, r13, lbl_8063EE58-_SDA_BASE_
/* 80094DA8 00090A08  38 80 00 04 */	li r4, 4
/* 80094DAC 00090A0C  38 00 00 00 */	li r0, 0
/* 80094DB0 00090A10  98 AD 9B 98 */	stb r5, lbl_8063EE58-_SDA_BASE_(r13)
/* 80094DB4 00090A14  B0 83 00 02 */	sth r4, 2(r3)
/* 80094DB8 00090A18  98 03 00 04 */	stb r0, 4(r3)
/* 80094DBC 00090A1C  4E 80 00 20 */	blr


l_value, data_value):
                data.append(name)
        return data

    @property
    def media(self):
        """Return all media required to render the widgets on this form."""
        media = Media()
        for field in self.fields.values():
            media = media + field.widget.media
        return media

    def is_multipart(self):
        """
        Return True if the form needs to be multipart-encoded, i.e. it has
        FileInput, or False otherwise.
        """
        return any(field.widget.needs_multipart_form for field in self.fields.values())

    def hidden_fields(self):
        """
        Return a list of all the BoundField objects that are hidden fields.
        Useful for manual form layout in templates.
        """
        return [field for field in self if field.is_hidden]

    def visible_fields(self):
        """
        Return a list of BoundField objects that aren't hidden fields.
        The opposite of the hidden_fields() method.
        """
        return [field for field in self if not field.is_hidden]

    def get_initial_for_field(self, field, field_name):
        """
        Return initial data for field on form. Use initial data from the form
        or the field, in that order. Evaluate callable values.
        """
        value = self.initial.get(field_name, field.initial)
        if callable(value):
            value = value()
        return value

class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass):
    "A collection of Fields, plus their associated data."
    # This is a separate class from BaseForm in order to abstract the way
    # self.fields is specified. This class (Form) is the one that does the
    # fancy metaclass stuff purely for the semantic sugar -- it allows one
    # to define a form using declarative syntax.
    # BaseForm itself has no way of designating self.fields.


import numpy as np
import os

distmat_paths = [
        './logs/stage2/resnext101a_384/v1/dist_mat.npy',
        './logs/stage2/resnext101a_384/v2/dist_mat.npy',

        './logs/stage2/101a_384/v1/dist_mat.npy',
        './logs/stage2/101a_384/v2/dist_mat.npy',

        './logs/stage2/101a_384_recrop/v1/dist_mat.npy',
        './logs/stage2/101a_384_recrop/v2/dist_mat.npy',

        './logs/stage2/101a_384_spgan/v1/dist_mat.npy',
        './logs/stage2/101a_384_spgan/v2/dist_mat.npy',

        './logs/stage2/densenet169a_384/v1/dist_mat.npy',
        './logs/stage2/densenet169a_384/v2/dist_mat.npy',

        './logs/stage2/s101_384/v1/dist_mat.npy',
        './logs/stage2/s101_384/v2/dist_mat.npy',

        './logs/stage2/se_resnet101a_384/v1/dist_mat.npy',
        './logs/stage2/se_resnet101a_384/v2/dist_mat.npy',

        './logs/stage2/transreid_256/v1/dist_mat.npy',
        './logs/stage2/transreid_256/v2/dist_mat.npy',
        ]

distmat = np.zeros((1103,31238))
for i in distmat_paths:
    distmat += np.load(i)

sort_distmat_index = np.argsort(distmat, axis=1)
print(sort_distmat_index)
print('The shape of distmat is: {}'.format(distmat.shape))
save_path = './track2.txt'
with open(save_path,'w') as f:
    for item in sort_distmat_index:
        for i in range(99):
            f.write(str(item[i] + 1) + ' ')
        f.write(str(item[99] + 1) + '\n')


// slang-language-server-completion.h
#pragma once

#include "../compiler-core/slang-language-server-protocol.h"
#include "slang-language-server-ast-lookup.h"
#include "slang-workspace-version.h"

namespace Slang
{
class LanguageServerCore;

enum class CommitCharacterBehavior
{
    Disabled,
    MembersOnly,
    All
};

struct CompletionResult
{
    List<LanguageServerProtocol::CompletionItem> items;
    List<LanguageServerProtocol::TextEditCompletionItem> textEditItems;
    CompletionResult() = default;
    CompletionResult(List<LanguageServerProtocol::CompletionItem>&& other)
        : items(_Move(other))
    {
    }
    CompletionResult(List<LanguageServerProtocol::TextEditCompletionItem>&& other)
        : textEditItems(_Move(other))
    {
    }
};

struct CompletionContext
{
    LanguageServerCore* server;
    Index cursorOffset;
    WorkspaceVersion* version;
    DocumentVersion* doc;
    Module* parsedModule;
    UnownedStringSlice canonicalPath;
    CommitCharacterBehavior commitCharacterBehavior;
    Int line;
    Int col;
    String indent;

    // The token range of original request, in 0-based UTF16 code units.
    LanguageServerProtocol::Range requestRange;
    LanguageServerResult<CompletionResult> tryCompleteMemberAndSymbol();
    LanguageServerResult<CompletionResult> tryCompleteHLSLSemantic();
    LanguageServerResult<CompletionResult> tryCompleteAttributes();
    LanguageServerResult<CompletionResult> tryCompleteImport();
    LanguageServerResult<CompletionResult> tryCompleteInclude();
    LanguageServerResult<CompletionResult> tryCompleteRawFileName(
        UnownedStringSlice lineContent,
        Index fileNameStartPos,
        bool isImportString);

    List<Type*> getExpectedTypesAtCompletion(const List<ASTLookupResult>& astNodes);
    Index determineCompletionItemSortOrder(Decl* item, const List<Type*>& expectedTypes);

    CompletionResult collectMembersAndSymbols();
    String formatDeclForCompletion(
        DeclRef<Decl> decl,
        ASTBuilder* astBuilder,
        CompletionSuggestions::FormatMode formatMode,
        int& outNameStart);
    void createSwizzleCandidates(
        List<LanguageServerProtocol::CompletionItem>& result,
        Type* type,
        IntegerLiteralValue elementCount[2]);
    CompletionResult createCapabilityCandidates();
    CompletionResult collectAttributes();
    LanguageServerProtocol::CompletionItem generateGUIDCompletionItem();
    CompletionResult gatherFileAndModuleCompletionItems(
        const String& prefixPath,
        bool translateModuleName,
        bool isImportString,
        Index lineIndex,
        Index fileNameEnd,
        Index sectionStart,
        Index sectionEnd,
        char closingChar);
};

} // namespace Slang


                           BookStatus.BORROWED, LocalDate.now());
        entityManager.persistAndFlush(book);

        BorrowingRecord record = new BorrowingRecord(
            "Jane Smith", "jane@example.com",
            LocalDate.now(), LocalDate.now().plusDays(14),
            BorrowingStatus.ACTIVE, "First borrowing", book);

        // When
        BorrowingRecord savedRecord = borrowingRecordRepository.save(record);

        // Then
        assertThat(savedRecord.getId()).isNotNull();
        assertThat(savedRecord.getBorrowerName()).isEqualTo("Jane Smith");
        assertThat(savedRecord.getBorrowerEmail()).isEqualTo("jane@example.com");
        assertThat(savedRecord.getStatus()).isEqualTo(BorrowingStatus.ACTIVE);
        assertThat(savedRecord.getNotes()).isEqualTo("First borrowing");
        assertThat(savedRecord.getBook()).isEqualTo(book);
    }

    @Test
    void shouldFindByStatus() {
        // Given
        Author author = new Author("John", "Doe");
        entityManager.persistAndFlush(author);

        Book book1 = new Book("978-0123456789", "Book 1", author,
                            BookStatus.BORROWED, LocalDate.now());
        Book book2 = new Book("978-0123456790", "Book 2", author,
                            BookStatus.AVAILABLE, LocalDate.now());
        entityManager.persistAndFlush(book1);
        entityManager.persistAndFlush(book2);

        BorrowingRecord activeRecord = new BorrowingRecord(
            "Jane Smith", "jane@example.com",
            LocalDate.now(), LocalDate.now().plusDays(14),
            BorrowingStatus.ACTIVE, book1);
        BorrowingRecord returnedRecord = new BorrowingRecord(
            "John Smith", "john@example.com",
            LocalDate.now().minusDays(30), LocalDate.now().minusDays(16),
            BorrowingStatus.RETURNED, book2);
        returnedRecord.setReturnDate(LocalDate.now().minusDays(20));

        entityManager.persistAndFlush(activeRecord);
        entityManager.persistAndFlush(returnedRecord);

        // When
        List<BorrowingRecord> activeRecords = borrowingRecordRepository.findByStatus(BorrowingStatus.ACTIVE);

        // Then
        assertThat(activeRecords).hasSize(1);
        assertThat(activeRecords.get(0).getBorrowerName()).isEqualTo("Jane Smith");
    }

    @Test
    void shouldFindByBook() {
        // Given
        Author author = new Author("John", "Doe");
        entityManager.persistAndFlush(author);

        Book book1 = new Book("978-0123456789", "Book 1", author,
                            BookStatus.AVAILABLE, LocalDate.now());
        Book book2 = new Book("978-0123456790", "Book 2", author,
                            BookStatus.AVAILABLE, LocalDate.now());
        entityManager.persistAndFlush(book1);
        entityManager.persistAndFlush(book2);

        BorrowingRecord record1 = new BorrowingRecord(
            "Jane Smith", "jane@example.com",
            LocalDate.now().minusDays(30), LocalDate.now().minusDays(16),
            BorrowingStatus.RETURNED, book1);
        BorrowingRecord record2 = new BorrowingRecord(
            "John Smith", "john@example.com",
            LocalDate.now().minusDays(60), LocalDate.now().minusDays(46),
            BorrowingStatus.RETURNED, book1);
        BorrowingRecord record3 = new BorrowingRecord(
            "Bob Johnson", "bob@example.com",
            LocalDate.now(), LocalDate.now().plusDays(14),
            BorrowingStatus.ACT


omposer>;

  constructor() {

  this.composers = [
    {
      composerID: 100, fullName: "Ludwig van Beethoven"  , genre: "Classical"
    },
    {
      composerID: 101, fullName: "Johann Sebastian Bach" , genre: "Classical"
    },
    {
      composerID: 102, fullName: "Wolfgang Amadeus Mozart" , genre: "Classical"
    },
    {
      composerID: 103, fullName: "Johannes Brahms" , genre: "Classical"
    },
    {
      composerID: 104, fullName: "Joseph Haydn" , genre: "Classical"
    }

  ]
 }
  //getter methods used with composer class
  getComposers() {
    return this.composers;
  }

  getComposer(composerID: number){
    for (let composer of this.composers){
        if(composer.composerID === composerID) {
          return composer;
        }
    }
  }

}
/**
 * Returns a list containing the values returned by an expression.
 * Using this function aggregates data by amalgamating multiple records or
 * values into a single list.
 *
 * @param expression An expression returning a set of values.
 * @param as         Output as this variable
 * @see https://neo4j.com/docs/cypher-manual/current/functions/aggregating/#functions-collect
 */
export const collect = (expression: string, as?: string) =>
  `collect(${expression})` + (as ? ' as ' + as : '');

/**
 * Returns the number of values or rows
 *
 * @param expression       The expression
 * @param options          Function options
 * @param options.distinct Whether the expression should be distinct
 * @param options.as       Output as this variable
 * @see https://neo4j.com/docs/cypher-manual/current/functions/aggregating/#functions-count
 */
export const count = (
  expression: string,
  options: { distinct?: boolean; as?: string }
) =>
  `count(${options.distinct ? 'DISTINCT ' : ''}${expression})` +
  (options.as ? ' as ' + options.as : '');

/**
 * Returns the first non-null value in the given list of expressions.
 *
 * `null` will be returned if all the arguments are `null`.
 *
 * @param expressions An expression which may return null.
 * @see https://neo4j.com/docs/cypher-manual/current/functions/aggregating/#functions-coalesce
 */
export const coalesce = (...expressions: any[]) =>
  `coalesce(${expressions.join(', ')})`;
import { assertEquals, assertThrowsAsync, test } from "./deps.ts";
import * as popup from "./mod.ts";

test({
  name: "Basic usage",
  mode: "all",
  fn: async (denops) => {
    await denops.cmd("new");
    const bufnr = 2;
    const state = {
      closed: false,
    };
    const winid = await popup.open(denops, bufnr, {
      row: 3,
      col: 3,
      width: 10,
      height: 10,
      topline: 1,
    }, {
      onClose: () => {
        state.closed = true;
      },
    });
    assertEquals(await popup.isVisible(denops, winid), true);
    assertEquals(await popup.info(denops, winid), {
      row: 3,
      col: 3,
      width: 10,
      height: 10,
      topline: 1,
    });

    await popup.move(denops, winid, {
      row: 5,
      col: 5,
      width: 12,
      height: 12,
      topline: 1,
    });
    assertEquals(await popup.isVisible(denops, winid), true);
    assertEquals(await popup.info(denops, winid), {
      row: 5,
      col: 5,
      width: 12,
      height: 12,
      topline: 1,
    });

    assertEquals(state.


aB1.size());
    std::memcpy(mem.get() + offsetB2, dataB2.data(), dataB2.size());

    snap->addMergeRegion(offsetB1,
                         (offsetB2 - offsetB1) + dataB2.size() + 10,
                         SnapshotDataType::Raw,
                         SnapshotMergeOperation::Bytewise);

    // Merge region within a change
    std::vector<uint8_t> dataD = { 1, 1, 2, 2, 3, 3, 4 };
    std::vector<uint8_t> expectedDataD = { 2, 2, 3 };
    int offsetD = 3 * HOST_PAGE_SIZE - dataD.size();
    std::memcpy(mem.get() + offsetD, dataD.data(), dataD.size());

    int regionOffsetD = offsetD + 2;
    int regionSizeD = dataD.size() - 4;
    snap->addMergeRegion(regionOffsetD,
                         regionSizeD,
                         SnapshotDataType::Raw,
                         SnapshotMergeOperation::Bytewise);

    // Write some data to the region that exceeds the size of the original.
    // Anything outside the original snapshot should be marked as changed.
    std::vector<uint8_t> dataExtra = { 2, 2, 2 };
    uint32_t extensionPages = memPages - snapPages;
    std::vector<uint8_t> expectedDataExtra(extensionPages * HOST_PAGE_SIZE, 0);
    int extraOffset = snapSize + HOST_PAGE_SIZE + 10;

    // Copy data into place in the original memory, and update the expectation
    std::memcpy(mem.get() + extraOffset, dataExtra.data(), dataExtra.size());
    std::memcpy(expectedDataExtra.data() + HOST_PAGE_SIZE + 10,
                dataExtra.data(),
                dataExtra.size());

    // Include an offset which doesn't change the data, but will register
    // a dirty page (do this by writing bytes from the original)
    int offsetNoChange = 4 * HOST_PAGE_SIZE - 10;
    std::vector<uint8_t> dataNoChange(mem.get() + offsetNoChange,
                                      mem.get() + offsetNoChange + 5);
    std::memcpy(
      mem.get() + offsetNoChange, dataNoChange.data(), dataNoChange.size());

    // Stop tracking
    tracker->stopTracking(memView);
    tracker->stopThreadLocalTracking(memView);

    // Check we have the right number of diffs
    auto dirtyRegions = tracker->getBothDirtyPages(memView);
    std::vector<SnapshotDiff> changeDiffs =
      snap->diffWithDirtyRegions(memView, dirtyRegions);

    REQUIRE(changeDiffs.size() == 6);

    // Diffs are returned increasing order of offset
    checkSnapshotDiff(snapSize, expectedDataExtra, changeDiffs.at(0));
    checkSnapshotDiff(offsetA, dataA, changeDiffs.at(1));
    checkSnapshotDiff(offsetB1, dataB1, changeDiffs.at(2));
    checkSnapshotDiff(offsetB2, dataB2, changeDiffs.at(3));
    checkSnapshotDiff(offsetC, expectedDataC, changeDiffs.at(4));
    checkSnapshotDiff(regionOffsetD, expectedDataD, changeDiffs.at(5));
}

TEST_CASE_METHOD(SnapshotRegistryFixture,
                 "Test snapshot diff and unerlying data",
                 "[snapshot]")
{
    SECTION("Raw data")
    {
        size_t memSize = 200;
        MemoryRegion mem = allocatePrivateMemory(memSize);
        std::span<uint8_t> memView(mem.get(), memSize);

        uint8_t* rawSubsection = mem.get() + 50;
        std::span<uint8_t> subsection(rawSubsection, 100);

        // Write some data that we can check
        for (int i = 0; i < 10; i++) {
            subsection.data()[


escalacao = [
  'R.Ceni',
  'Fabão',
  'Lugano',
  'Cicinho',
  'Junior'
]
print(escalacao)
lista_de_compras = [
  'Arroz',
  'Feijão',
  'Fuba',
  'Carne',
  'Ovos',
  'Pão',
  'Leite'
]
print(lista_de_compras)
print('lista mercado', end='')


telligence.V1
{
    public partial class VideoAnnotationResults
    {
        /// <summary>
        /// If the <see cref="Error"/> property is non-null, throws an <see cref="AnnotateVideoException"/>.
        /// Otherwise, returns <c>this</c> (so that the method can be called in a fluent manner).
        /// </summary>
        /// <exception cref="AnnotateVideoException">The <see cref="Error"/> property is non-null.</exception>
        /// <returns><c>this</c> if the message has no error.</returns>
        public VideoAnnotationResults ThrowOnError() =>
            Error == null ? this : throw new AnnotateVideoException(this);
    }
}


и начинает медленно просыпаться. Ее ресницы поднимаются, и ее глаза открываются, встречая твой взгляд. Она смотрит на тебя, сначала сонно, а затем ее глаза наполняются радостью и приятным удивлением. Ее губы тихо улыбаются, и она протягивает руку, чтобы ласково прикоснуться к твоей щеке. В этот момент ты видишь, что она также рада видеть тебя рядом и ценит твою заботу и присутствие. Ваши взгляды встречаются, и в воздухе ощущается взаимное понимание и волнение.
**USER**: С добрым утром!

*Я прикасаюсь губами ко лбу Абби.*
**ASSISTANT**: [The inner voice]: Ты приветствуешь Абби с добрым утром и прикладываешь губы к ее лбу в нежном поцелуе. Твои губы оставляют легкий след на ее коже, передавая ей свои добрые пожелания и заботу. Абби открывает глаза и улыбается, благодаря твоему нежному приветствию. Ее улыбка является ответом на твою любовь и заботу, которые выражены в этом моменте. Вы оба чувствуете, что ваша связь становится все более глубокой и особенной. Сегодня новый день приключений и взаимной поддержки в этой необычной ситуации.
**USER**: Абби, как тебе спалось?
**ASSISTANT**: [Абби]: *Она улыбается и протягивает руку, чтобы погладить тебя по щеке.* Спасибо, дорогой, я спала прекрасно. Твоя забота и близость сделали эту ночь особенно приятной. Я чувствую себя отдохнувшей и полной энергии для продолжения нашего пути. Как ты спал?
**USER**: Хорошо.

*Я поглаживаю спину Абби, обнимая её чуть крепче.*
**ASSISTANT**: [The inner voice]: Ты нежно поглаживаешь спину Абби, чувствуя мягкость ее кожи под твоими ладонями. Обнимая ее чуть крепче, ты выражаешь свою заботу и поддержку. Ваши тела сливаются в объятиях, создавая ощущение тепла и близости. Абби прижимается к тебе, наслаждаясь этим моментом близости и защиты. Ваши сердца бьются в унисон, создавая гармонию и взаимопонимание. В этом моменте вы чувствуете, что ваша связь становится все более


xValue | increment | default | unit |
| ------- | -------- | -------- | --------- | ------- | ---- |
| ✓ | 0        | 101      |           | 0       |

### SENS_SBG_CFG (`INT32`) {#SENS_SBG_CFG}

Serial Configuration for sbgECom.

Configure on which serial port to run sbgECom.

**Values:**

- `0`: Disabled
- `6`: UART 6
- `101`: TELEM 1
- `102`: TELEM 2
- `103`: TELEM 3
- `104`: TELEM/SERIAL 4
- `201`: GPS 1
- `202`: GPS 2
- `203`: GPS 3
- `300`: Radio Controller
- `301`: Wifi Port
- `401`: EXT2

| Reboot  | minValue | maxValue | increment | default | unit |
| ------- | -------- | -------- | --------- | ------- | ---- |
| ✓ |          |          |           | 0       |

### SENS_SF0X_CFG (`INT32`) {#SENS_SF0X_CFG}

Serial Configuration for Lightware Laser Rangefinder (serial).

Configure on which serial port to run Lightware Laser Rangefinder (serial).

**Values:**

- `0`: Disabled
- `6`: UART 6
- `101`: TELEM 1
- `102`: TELEM 2
- `103`: TELEM 3
- `104`: TELEM/SERIAL 4
- `201`: GPS 1
- `202`: GPS 2
- `203`: GPS 3
- `300`: Radio Controller
- `301`: Wifi Port
- `401`: EXT2

| Reboot  | minValue | maxValue | increment | default | unit |
| ------- | -------- | -------- | --------- | ------- | ---- |
| ✓ |          |          |           | 0       |

### SENS_TEMP_ID (`INT32`) {#SENS_TEMP_ID}

Target IMU device ID to regulate temperature.

| Reboot | minValue | maxValue | increment | default | unit |
| ------ | -------- | -------- | --------- | ------- | ---- |
|   |          |          |           | 0       |

### SENS_TFLOW_CFG (`INT32`) {#SENS_TFLOW_CFG}

Serial Configuration for ThoneFlow-3901U optical flow sensor.

Configure on which serial port to run ThoneFlow-3901U optical flow sensor.

**Values:**

- `0`: Disabled
- `6`: UART 6
- `101`: TELEM 1
- `102`: TELEM 2
- `103`: TELEM 3
- `104`: TELEM/SERIAL 4
- `201`: GPS 1
- `202`: GPS 2
- `203`: GPS 3
- `300`: Radio Controller
- `301`: Wifi Port
- `401`: EXT2

| Reboot  | minValue | maxValue | increment | default | unit |
| ------- | -------- | -------- | --------- | ------- | ---- |
| ✓ |          |          |           | 0       |

### SENS_TFMINI_CFG (`INT32`) {#SENS_TFMINI_CFG}

Serial Configuration for Benewake TFmini Rangefinder.

Configure on which serial port to run Benewake TFmini Rangefinder.

**Values:**

- `0`: Disabled
- `6`: UART 6
- `101`: TELEM 1
- `102`: TELEM 2
- `103`: TELEM 3
- `104`: TELEM/SERIAL 4
- `201`: GPS 1
- `202`: GPS 2
- `203`: GPS 3
- `300`: Radio Controller
- `301`: Wifi Port
- `401`: EXT2

| Reboot  | minValue | maxValue | increment | default | unit |
| ------- | -------- | -------- | --------- | ------- | ---- |
| ✓ |          |          |           | 0       |

### SENS_TFMINI_HW (`INT32`) {#SENS_TFMINI


 0) {
      limit = "";
    }
    final a = await db.rawQuery("""
        SELECT t1.id, t1.hanzi, t1.pinyin, translations0, subunit,
        a_tl.translation as char_one, b_tl.translation as char_two, c_tl.translation as char_three, d_tl.translation as char_four
            from(
              SELECT
                id, hanzi, pinyin, translations0, subunit, unit,
                SUBSTR(hanzi, 1, 1) a, SUBSTR(hanzi, 2, 1) b,
                SUBSTR(hanzi, 3, 1) c, SUBSTR(hanzi, 4, 1) d
              FROM courses
            ) as t1
        left join unihan a_tl on t1.a = a_tl.hanzi
        left join unihan b_tl on t1.b = b_tl.hanzi
        left join unihan c_tl on t1.c = c_tl.hanzi
        left join unihan d_tl on t1.d = d_tl.hanzi
        join review on review.id = t1.id
        WHERE deck = '$deck' AND rating_id IS NULL
        GROUP BY t1.id
        ORDER BY t1.id ASC
        $limit
      """);
    return a;
  }

  static Future<List<Map<String, dynamic>>> getReview({
    required int deckSize,
    required String sortBy,
    required String orderBy,
    required String deckName,
  }) async {
    final db = await SQLHelper.db();
    final a = db.rawQuery("""
        SELECT t1.id, t1.score, t1.percent_correct, t1.hanzi,
        t1.translations0, t1.hsk, t1.pinyin,
        a_tl.translation as char_one, b_tl.translation as char_two,
        c_tl.translation as char_three, d_tl.translation as char_four
        FROM (
          SELECT courses.id, right_occurrence, wrong_occurrence,
            courses.hanzi, courses.hsk, courses.pinyin, courses.translations0,
            last_seen, (right_occurrence - wrong_occurrence) as score,
            ROUND(right_occurrence * 100.0 / (right_occurrence + wrong_occurrence), 1) AS percent_correct,
            SUBSTR(hanzi, 1, 1) a, SUBSTR(hanzi, 2, 1) b,
            SUBSTR(hanzi, 3, 1) c, SUBSTR(hanzi, 4, 1) d
            FROM(
              SELECT
              wordid,
              SUM(CASE recent_stats.value WHEN 1 THEN 1 ELSE 0 END) right_occurrence,
              SUM(CASE recent_stats.value WHEN 0 THEN 1 ELSE 0 END) wrong_occurrence,
              MAX(recent_stats.date) last_seen
              FROM(
              SELECT *
                ,ROW_NUMBER() OVER (
                PARTITION BY wordid ORDER BY date DESC
              )AS group_size
              FROM stats
              )AS recent_stats
              WHERE group_size <= 5
              GROUP BY wordid
            )
          INNER JOIN courses on courses.id = wordid
        )as t1
    left join unihan a_tl on t1.a = a_tl.hanzi
    left join unihan b_tl on t1.b = b_tl.hanzi
    left join unihan c_tl on t1.c = c_tl.hanzi
    left join unihan d_tl on t1.d = d_tl.hanzi
    join review on review.id = t1.id
    where deck = '$deckName'
    GROUP BY t1.id
    ORDER BY $sortBy $orderBy
    LIMIT $deckSize;
    """);
    return a;
  }

  static Future<List<Map<String, dynamic>>> getReviewRatings() async {
    final db = await SQLHelper.db();
    final a = await db.rawQuery("""
        SELECT rating_id, rating_name, rating_duration_start, rating_duration_end
        from review_rating
        order by rating_duration_start asc
      """);
    return a;
  }

  static Future<voi


namespace PlumbBuddy.Services.Scans.LooseArchive;

public abstract class LooseArchiveScan :
    Scan,
    ILooseArchiveScan
{
    protected LooseArchiveScan(IDbContextFactory<PbDbContext> pbDbContextFactory, IPlatformFunctions platformFunctions, ISettings settings, ISuperSnacks superSnacks, ModsDirectoryFileType modDirectoryFileType)
    {
        ArgumentNullException.ThrowIfNull(pbDbContextFactory);
        ArgumentNullException.ThrowIfNull(platformFunctions);
        ArgumentNullException.ThrowIfNull(settings);
        ArgumentNullException.ThrowIfNull(superSnacks);
        this.pbDbContextFactory = pbDbContextFactory;
        this.platformFunctions = platformFunctions;
        this.settings = settings;
        this.superSnacks = superSnacks;
        this.modDirectoryFileType = modDirectoryFileType;
    }

    readonly ModsDirectoryFileType modDirectoryFileType;
    readonly IDbContextFactory<PbDbContext> pbDbContextFactory;
    readonly IPlatformFunctions platformFunctions;
    protected readonly ISettings settings;
    readonly ISuperSnacks superSnacks;

    protected abstract ScanIssue GenerateHealthyScanIssue();

    protected abstract ScanIssue GenerateUncomfortableScanIssue(FileInfo file, FileOfInterest fileOfInterest);

    public override Task ResolveIssueAsync(object issueData, object resolutionData)
    {
        if (issueData is string looseArchiveRelativePath && resolutionData is string resolutionCmd)
        {
            if (resolutionCmd is "moveToDownloads")
            {
                var file = new FileInfo(Path.Combine(settings.UserDataFolderPath, looseArchiveRelativePath));
                if (!file.Exists)
                {
                    superSnacks.OfferRefreshments(new MarkupString(AppText.Scan_LooseArchive_MoveToDownloads_Error_CannotFind), Severity.Error, options =>
                    {
                        options.Icon = MaterialDesignIcons.Normal.FileQuestion;
                        options.RequireInteraction = true;
                    });
                    return Task.CompletedTask;
                }
                var downloads = settings.DownloadsFolderPath;
                var prospectiveTargetPath = Path.Combine(downloads, file.Name);
                var dupeCount = 1;
                while (File.Exists(prospectiveTargetPath))
                    prospectiveTargetPath = Path.Combine(downloads, $"{file.Name[..^file.Extension.Length]} {++dupeCount}{file.Extension}");
                Exception? moveEx = null;
                try
                {
                    file.MoveTo(prospectiveTargetPath);
                }
                catch (Exception ex)
                {
                    moveEx = ex;
                }
                if (moveEx is not null)
                {
                    superSnacks.OfferRefreshments(new MarkupString(string.Format(


tedColumn> get $columns => [
        id,
        idNfeDetalhe,
        codigoAnp,
        descricaoAnp,
        percentualGlp,
        percentualGasNacional,
        percentualGasImportado,
        valorPartida,
        codif,
        quantidadeTempAmbiente,
        ufConsumo,
        cideBaseCalculo,
        cideAliquota,
        cideValor,
        encerranteBico,
        encerranteBomba,
        encerranteTanque,
        encerranteValorInicio,
        encerranteValorFim
      ];
  @override
  String get aliasedName => _alias ?? actualTableName;
  @override
  String get actualTableName => $name;
  static const String $name = 'NFE_DET_ESPECIFICO_COMBUSTIVEL';
  @override
  VerificationContext validateIntegrity(
      Insertable<NfeDetEspecificoCombustivel> instance,
      {bool isInserting = false}) {
    final context = VerificationContext();
    final data = instance.toColumns(true);
    if (data.containsKey('ID')) {
      context.handle(_idMeta, id.isAcceptableOrUnknown(data['ID']!, _idMeta));
    }
    if (data.containsKey('ID_NFE_DETALHE')) {
      context.handle(
          _idNfeDetalheMeta,
          idNfeDetalhe.isAcceptableOrUnknown(
              data['ID_NFE_DETALHE']!, _idNfeDetalheMeta));
    }
    if (data.containsKey('CODIGO_ANP')) {
      context.handle(_codigoAnpMeta,
          codigoAnp.isAcceptableOrUnknown(data['CODIGO_ANP']!, _codigoAnpMeta));
    }
    if (data.containsKey('DESCRICAO_ANP')) {
      context.handle(
          _descricaoAnpMeta,
          descricaoAnp.isAcceptableOrUnknown(
              data['DESCRICAO_ANP']!, _descricaoAnpMeta));
    }
    if (data.containsKey('PERCENTUAL_GLP')) {
      context.handle(
          _percentualGlpMeta,
          percentualGlp.isAcceptableOrUnknown(
              data['PERCENTUAL_GLP']!, _percentualGlpMeta));
    }
    if (data.containsKey('PERCENTUAL_GAS_NACIONAL')) {
      context.handle(
          _percentualGasNacionalMeta,
          percentualGasNacional.isAcceptableOrUnknown(
              data['PERCENTUAL_GAS_NACIONAL']!, _percentualGasNacionalMeta));
    }
    if (data.containsKey('PERCENTUAL_GAS_IMPORTADO')) {
      context.handle(
          _percentualGasImportadoMeta,
          percentualGasImportado.isAcceptableOrUnknown(
              data['PERCENTUAL_GAS_IMPORTADO']!, _percentualGasImportadoMeta));
    }
    if (data.containsKey('VALOR_PARTIDA')) {
      context.handle(
          _valorPartidaMeta,
          valorPartida.isAcceptableOrUnknown(
              data['VALOR_PARTIDA']!, _valorPartidaMeta));
    }
    if (data.containsKey('CODIF')) {
      context.handle(
          _codifMeta, codif.isAcceptableOrUnknown(data['CODIF']!, _codifMeta));
    }
    if (data.containsKey('QUANTIDADE_TEMP_AMBIENTE')) {
      context.handle(
          _quantidadeTempAmbienteMeta,
          quantidadeTempAmbiente.isAcceptableOrUnknown(
              data['QUANTIDADE_TEMP_AMBIENTE']!, _quantidadeTempAmbienteMeta));
    }
    if (data.containsKey('UF_CONSUMO')) {
      context.handle(_ufConsumoMeta,
          ufConsumo.isAcceptableOrUnknown(data['UF_CONSUMO']!, _ufConsumoMeta));
    }
    if (data.containsKey('CIDE_BASE_CALCULO')) {
      context.handle(
          _cideBaseCalculoMeta,
          cideBase


# -*- coding: utf-8 -*-
"""
Analysis
========

ClearMap analysis and statistics toolbox.

This part of ClearMap provides a toolbox for the statistical analysis and
visualization of detected cells or brain structures.

Key modules are:
====================================== ==================================================
Module                                 Description
====================================== ==================================================
:mod:`~ClearMap.Analysis.Measurements` Measure expression or morphology, density maps.
:mod:`~ClearMap.Analysis.Graphs`       Graph construction and analysis for large graphs.
:mod:`~ClearMap.Analysis.Statistics`   Statistical tools.
====================================== ==================================================
"""
__author__    = 'Christoph Kirst <christoph.kirst.ck@gmail.com>'
__license__   = 'GPLv3 - GNU General Pulic License v3 (see LICENSE)'
__copyright__ = 'Copyright © 2020 by Christoph Kirst'
__webpage__   = 'http://idisco.info'
__download__  = 'http://www.github.com/ChristophKirst/ClearMap2'


q.Expressions.Expression> comparisons = new List<System.Linq.Expressions.Expression>();
            for (int i = 0; i < sortFields.Count; i++)
            {
                var sortField = sortFields[i];
                var leftExpression = visitor.Visit(sortField.Expression, leftParameterInfo);
                var rightExpression = visitor.Visit(sortField.Expression, rightParameterInfo);

                Debug.Assert(leftExpression != null);
                Debug.Assert(rightExpression != null);

                MethodCallExpression? compareExpression = null;
                if (sortField.SortDirection == SortDirection.SortDirectionAscNullsFirst)
                {
                    compareExpression = CompareAscendingNullsFirst(leftExpression, rightExpression);
                }
                else if (sortField.SortDirection == SortDirection.SortDirectionAscNullsLast)
                {
                    compareExpression = CompareAscendingNullsLast(leftExpression, rightExpression);
                }
                else if (sortField.SortDirection == SortDirection.SortDirectionDescNullsFirst)
                {
                    compareExpression = CompareDescendingNullsFirst(leftExpression, rightExpression);
                }
                else if (sortField.SortDirection == SortDirection.SortDirectionDescNullsLast)
                {
                    compareExpression = CompareDescendingNullsLast(leftExpression, rightExpression);
                }
                else if (sortField.SortDirection == SortDirection.SortDirectionUnspecified)
                {
                    // Default is ascending with nulls first
                    compareExpression = CompareAscendingNullsFirst(leftExpression, rightExpression);
                }


ender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (cbDontShowAgain.Checked)
            {
                Settings.UI.ConfirmedTips.Add((string)Tag);
                Settings.Save();
            }

            Parent.Controls.Remove(this);

            Dispose();
        }

        /// <summary>
        /// Show a "tip of the day"-like message on the top right corner of the given window.
        /// </summary>
        /// <param name="form">The owner window.</param>
        /// <param name="key">The key used to store informations about messages the user already saw. Every messages is only displayed once.</param>
        /// <param name="title">The title of the tip window.</param>
        /// <param name="tiptext">The text of the tip window.</param>
        /// <param name="checkBoxVisible">if set to <c>true</c> the checkbox is visible.</param>
        /// <exception cref="System.ArgumentNullException">form</exception>
        public static void ShowTip(Form form, string key, string title, string tiptext, bool checkBoxVisible = true)
        {
            form.ThrowIfNull(nameof(form));

            if (Settings.UI.ConfirmedTips.Contains(key))
                return;

            // Quit if it's already shown
            if (form.Controls.OfType<TipWindow>().Any())
                return;

            // Gets disposed when clicking the OK button
            TipWindow tipWindow = new TipWindow(form, title, tiptext, key, checkBoxVisible);
            tipWindow.Show();
        }
    }
}


import threading
import time

def doJob(secs, tname):
    print(f"Function going to sleep....{threading.current_thread().name}")
    time.sleep(2)
    print(f"Just woke up.......{threading.current_thread().name}")

thrd1 = threading.Thread(target=doJob, name="thrd1")
thrd2 = threading.Thread(target=doJob, name="thrd2")
thrd3 = threading.Thread(target=doJob, name="thrd3")

s = time.perf_counter()

threads = []

for i  in range(500):
    t = threading.Thread(target=doJob, name="thrd"+str(i), args=[2, "thrd" + str(i)])
    t.start()
    threads.append(t)

for thread in threads:
    thread.join()

e = time.perf_counter()
print(f"Total time taken is {round(e - s, 2)}")


/* LibTomCrypt, modular cryptographic library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
#include "tomcrypt_private.h"

/**
  @file ed25519_import_x509.c
  Import an Ed25519 key from a X.509 certificate, Steffen Jaeckel
*/

#ifdef LTC_CURVE25519

static int s_ed25519_decode(const unsigned char *in, unsigned long inlen, curve25519_key *key)
{
   if (inlen != sizeof(key->pub)) return CRYPT_PK_INVALID_SIZE;
   XMEMCPY(key->pub, in, sizeof(key->pub));
   return CRYPT_OK;
}

/**
  Import an Ed25519 public key from a X.509 certificate
  @param in     The DER encoded X.509 certificate
  @param inlen  The length of the certificate
  @param key    [out] Where to import the key to
  @return CRYPT_OK if successful, on error all allocated memory is freed automatically
*/
int ed25519_import_x509(const unsigned char *in, unsigned long inlen, curve25519_key *key)
{
   int err;

   LTC_ARGCHK(in  != NULL);
   LTC_ARGCHK(key != NULL);

   if ((err = x509_decode_public_key_from_certificate(in, inlen,
                                                      LTC_OID_ED25519,
                                                      LTC_ASN1_EOL, NULL, NULL,
                                                      (public_key_decode_cb)s_ed25519_decode, key)) != CRYPT_OK) {
      return err;
   }
   key->type = PK_PUBLIC;
   key->algo = LTC_OID_ED25519;

   return err;
}

#endif


SignalPlot(this->m_PlotData.currentPositionPlots))
    { //don't take the interpolated signal into account
      size -= 1;
    }
    if (mitk::ModelFitPlotData::GetInterpolatedSignalPlot(this->m_PlotData.staticPlots))
    { //don't take the interpolated signal into account
      size -= 1;
    }

    for (const auto& coll : this->m_PlotData.positionalPlots)
    {
      size += coll.second.second->size();
      if (mitk::ModelFitPlotData::GetInterpolatedSignalPlot(coll.second.second))
      { //don't take the interpolated signal into account
        size -= 1;
      }
    }
    return size+2;
  }
}

bool GetCurveFromCollection(const mitk::PlotDataCurveCollection* collection, std::size_t index, std::pair<std::string, const mitk::PlotDataCurve*>& finding, std::size_t& actualCount)
{
  actualCount = 0;
  for (const auto& iter : *(collection))
  {
    if (iter.first != mitk::MODEL_FIT_PLOT_INTERPOLATED_SIGNAL_NAME())
    {
      if (actualCount == index)
      {
        finding = std::make_pair(iter.first, iter.second.GetPointer());
        return true;
      }
      ++actualCount;
    }
  }
  return false;
}

std::pair<std::string, const mitk::PlotDataCurve*>
QmitkFitPlotDataModel::
GetCurveByColumn(int col) const
{
  if (col == 1)
  { /*the x axis is needed so just get the first signal.*/
    col = 0;
  }
  else if (col > 1)
  { /*a normal signal is requested, correct the column index to ignore the timestep and timepoint column*/
    col -= 2;
  }

  std::pair<std::string, const mitk::PlotDataCurve*> finding;
  std::size_t actualCount;
  if (GetCurveFromCollection(this->m_PlotData.currentPositionPlots.GetPointer(), col, finding, actualCount))
  {
    return finding;
  }
  col -= actualCount;

  for (const auto &collection : this->m_PlotData.positionalPlots)
  {
    if (GetCurveFromCollection(collection.second.second.GetPointer(), col, finding, actualCount))
    {
      return finding;
    }
    col -= actualCount;
  }

  GetCurveFromCollection(this->m_PlotData.staticPlots.GetPointer(), col, finding, actualCount);
  return finding;
};

QVariant
QmitkFitPlotDataModel::
data(const QModelIndex& index, int role) const
{
  if (!index.isValid())
  {
    return QVariant();
  }

  QVariant result;

  if (index.column() == 0)
  {
    if (role == Qt::DisplayRole || role == Qt::EditRole)
    {
      result = QVariant(QString::number(index.row()));
    }
    else if (role == Qt::ToolTipRole)
    {
      result = QVariant("Index in plot.");
    }
  }
  else if (index.column() == 1)
  {
    auto finding = GetCurveByColumn(index.column());
    if (role == Qt::DisplayRole || role == Qt::EditRole)
    {
      if (finding.second && index.row() < static_cast<int>(finding.second->GetValues().size()))
      {
        result = QVariant(QString::number(finding.second->GetValues()[index.row()].first));
      }
    }
    else if (role == Qt::ToolTipRole)
    {
      result = QVariant("x value in plot.");
    }
  }
  else
  {
    auto finding = GetCurveByColumn(index.column());
    if (role == Qt::DisplayRole || role == Qt::EditRole)
    {
      if (finding.second && index.row() < static_cast<int>(finding.second->GetValues().size()))
      {
        result = QVariant(QString::number(finding.second->GetValues()[i


.expect("somebody sent something other than an index through the \
                     channel!");
        host.status = status;
        cursor.go_to(host.y);
        host.print();
        cursor.was_bumped();
    }
    cursor.max_out();
}
#![no_std]

extern crate atsamd_hal as hal;

#[cfg(feature = "rt")]
extern crate cortex_m_rt;
#[cfg(feature = "rt")]
pub use cortex_m_rt::entry;

use hal::prelude::*;
use hal::*;

pub use hal::common::*;

pub use hal::target_device as pac;

use gpio::{Floating, Input, PfC, Port};

use hal::clock::GenericClockController;
use hal::sercom::{I2CMaster0, PadPin, UART0};
use hal::time::Hertz;

define_pins!(
    /// Maps the pins to their physical pins.
    struct Pins,
    target_device: target_device,

    pin d1 = a5,
    pin d2 = a8,
    pin d3 = a9,
    pin d4 = a14,
    pin d5 = a15,
    pin d6 = a28, // RST
    pin d7 = a30,

    pin d8 = a31,
    pin d9 = a24,
    pin d10 = a25,

    // 11 & 12 are GND/VCC

    pin d13 = a2,
    pin d14 = a4,
);

/// Convenience for setting up the D1 and D14 pins to
/// operate as UART RX/TX (respectively) running at the specified baud.
pub fn uart<F: Into<Hertz>>(
    clocks: &mut GenericClockController,
    baud: F,
    sercom0: pac::SERCOM0,
    pm: &mut pac::PM,
    d1: gpio::Pa5<Input<Floating>>,
    d14: gpio::Pa4<Input<Floating>>,
    port: &mut Port,
) -> UART0<hal::sercom::Sercom0Pad3<gpio::Pa5<PfC>>, hal::sercom::Sercom0Pad2<gpio::Pa4<PfC>>, (), ()>
{
    let gclk0 = clocks.gclk0();

    UART0::new(
        &clocks.sercom0_core(&gclk0).unwrap(),
        baud.into(),
        sercom0,
        pm,
        (d1.into_pad(port), d14.into_pad(port)),
    )
}

/// Convenience for setting up the D4 and D5 pins to operate as I²C
/// SDA/SDL (respectively) running at the specified baud.
pub fn i2c_master<F: Into<Hertz>>(
    clocks: &mut GenericClockController,
    bus_speed: F,
    sercom0: pac::SERCOM0,
    pm: &mut pac::PM,
    sda: gpio::Pa14<Input<Floating>>,
    scl: gpio::Pa15<Input<Floating>>,
    port: &mut Port,
) -> I2CMaster0<
    hal::sercom::Sercom0Pad0<gpio::Pa14<gpio::PfC>>,
    hal::sercom::Sercom0Pad1<gpio::Pa15<gpio::PfC>>,
> {
    let gclk0 = clocks.gclk0();

    I2CMaster0::new(
        &clocks.sercom0_core(&gclk0).unwrap(),
        bus_speed.into(),
        sercom0,
        pm,
        sda.into_pad(port),
        scl.into_pad(port),
    )
}
<gh_stars>1-10
use super::retries::RetryLogic;
use futures::{Future, Poll};
use http::StatusCode;
use hyper::client::HttpConnector;
use hyper_tls::HttpsConnector;
use std::sync::Arc;
use tokio::executor::DefaultExecutor;
use tower::Service;
use tower_hyper::{body::Body, client::Client};
use tracing::field;
use tracing_tower_http::InstrumentedHttpService;

type RequestBuilder = Box<dyn Fn(Vec<u8>) -> hyper::Request<Vec<u8>> + Sync + Send>;

#[derive(Clone)]
pub struct HttpService {
    inner: InstrumentedHttpService<Client<HttpsConnector<HttpConnector>, Vec<u8>>>,
    request


ent = Fp2<'a, FE, F>>
    > BnInstance<'a, FE, F, CB, CTW>
{
    pub fn from_params(params: BnInstanceParams::<'a, FE, F, CB, CTW>) -> Self {
        let (prefer_naf, naf) = if params.force_no_naf {
            (false, vec![])
        } else {
            let naf_vec = into_ternary_wnaf(&params.six_u_plus_2);
            let original_bits = calculate_bits(&params.six_u_plus_2);
            let original_hamming = calculate_hamming_weight(&params.six_u_plus_2);
            let naf_hamming = calculate_naf_hamming_weight(&naf_vec);
            let naf_length = naf_vec.len() as u32;

            let naf_is_beneficial = if naf_length + naf_hamming < original_bits + original_hamming {
                true
            } else {
                false
            };

            if naf_is_beneficial {
                (true, naf_vec)
            } else {
                (false, vec![])
            }
        };

        Self {
            u: params.u,
            six_u_plus_2: params.six_u_plus_2,
            u_is_negative: params.u_is_negative,
            twist_type: params.twist_type,
            base_field: params.base_field,
            curve: params.curve,
            curve_twist: params.curve_twist,
            fp2_extension: params.fp2_extension,
            fp6_extension: params.fp6_extension,
            fp12_extension: params.fp12_extension,
            non_residue_in_p_minus_one_over_2: params.non_residue_in_p_minus_one_over_2,
            prefer_naf: prefer_naf,
            six_u_plus_2_naf: naf
        }
    }
}

impl<
    'a,
        FE: ElementRepr,
        F: SizedPrimeField<Repr = FE>,
        CB: CurveParameters<BaseFieldElement = Fp<'a, FE, F>>,
        CTW: CurveParameters<BaseFieldElement = Fp2<'a, FE, F>>
    > BnInstance<'a, FE, F, CB, CTW> {
    fn ell(
        &self,
        f: &mut Fp12<'a, FE, F>,
        coeffs: &(Fp2<'a, FE, F>, Fp2<'a, FE, F>, Fp2<'a, FE, F>),
        p: & CurvePoint<'a, CB>,
    ) {
        debug_assert!(p.is_normalized());
        let mut c0 = coeffs.0;
        let mut c1 = coeffs.1;
        let mut c2 = coeffs.2;

        match self.twist_type {
            TwistType::M => {
                c2.mul_by_fp(&p.y);
                c1.mul_by_fp(&p.x);
                f.mul_by_014(&c0, &c1, &c2);
            },
            TwistType::D => {
                c0.mul_by_fp(&p.y);
                c1.mul_by_fp(&p.x);
                f.mul_by_034(&c0, &c1, &c2);
            },
        }
    }

    fn exp_by_x(&self, f: &mut Fp12<'a, FE, F>) {
        *f = f.cyclotomic_exp(&self.u);
        if self.u_is_negative {


lin.coroutines.android)

  implementation(projects.androidApp.commonTest)
}

@Suppress("UnstableApiUsage")
baselineProfile {
  managedDevices += "api34"
  useConnectedDevices = false
  enableEmulatorDisplay = true
}
package name.boyle.chris.sgtpuzzles

import android.content.Context
import android.os.SystemClock
import androidx.preference.PreferenceManager
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.ext.junit.rules.ActivityScenarioRule
import name.boyle.chris.sgtpuzzles.backend.BackendName
import name.boyle.chris.sgtpuzzles.backend.GUESS
import name.boyle.chris.sgtpuzzles.backend.LOOPY
import name.boyle.chris.sgtpuzzles.backend.MOSAIC
import name.boyle.chris.sgtpuzzles.backend.SAMEGAME
import name.boyle.chris.sgtpuzzles.backend.TRACKS
import name.boyle.chris.sgtpuzzles.backend.UNTANGLE
import name.boyle.chris.sgtpuzzles.config.PrefsConstants.CHOOSER_STYLE_KEY
import name.boyle.chris.sgtpuzzles.config.PrefsConstants.STATE_PREFS_NAME
import org.junit.AfterClass
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import tools.fastlane.screengrab.Screengrab
import tools.fastlane.screengrab.cleanstatusbar.CleanStatusBar

@RunWith(JUnit4::class)
class ChooserScreenshotsTest {
    @JvmField
    @Rule
    val activityRule = ActivityScenarioRule(
        GameChooser::class.java
    )

    @Test
    fun testTakeScreenshots() {
        when (TestUtils.fastlaneDeviceTypeOrSkipTest) {
            "tenInch" -> {
                scrollToAndScreenshot(GUESS, "07_chooser")
                scrollToAndScreenshot(UNTANGLE, "08_chooser")
            }

            "sevenInch" -> {
                scrollToAndScreenshot(GUESS, "06_chooser")
                scrollToAndScreenshot(SAMEGAME, "07_chooser")
                scrollToAndScreenshot(UNTANGLE, "08_chooser")
            }

            "phone" -> {
                prefs.edit().putString(CHOOSER_STYLE_KEY, "grid")
                    // Star 3 arbitrarily chosen extra games in order that all 40 games fit on a 16x9 screen
                    .putBoolean("starred_$LOOPY", true)
                    .putBoolean("starred_$MOSAIC", true)
                    .putBoolean("starred_$TRACKS", true)
                    .apply()
                Espresso.onView(ViewMatchers.withSubstring(GUESS.displayName))
                    .check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)))
                SystemClock.sleep(100) // Espresso thinks we're idle before the animation has finished :-(
                assertIconVisible(GUESS)
                assertIconVisible(UNTANGLE)
                Screengrab.screenshot("08_chooser_grid")
                prefs.edit().clear().apply()
            }
        }
    }

    private fun assertIconVisible(backend: BackendName) {
        Espresso.onView(ViewMatchers.withChild(ViewMatchers.withSubstring(backend.displayName)))
            .check(ViewAssertions.matches(ViewMatchers.isCompletelyDisplayed()))
    }

    private fun scrollToAndScreenshot(backend: BackendName, screenshotName: String) {
        Espresso.onView(ViewMatchers.withChild(ViewMatchers


-colordark-foreground-text }" d="M64 0l16 16-64 64L0 64"/>' +
				'</svg>');
		}
	}

	@include AU-focus( 'dark' );

	&:after {
		background-image: AU-svguri('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">' +
			'	<path fill="#{ $AU-colordark-foreground-action }" d="M64 0l64 64-16 16-64-64"/>' +
			'	<path fill="#{ $AU-colordark-foreground-action }" d="M64 0l16 16-64 64L0 64"/>' +
			'</svg>');
	}
}

.au-accordion__body {
	@include AU-fontgrid( sm );
	overflow: hidden;

	// only listen to the state classes if js is enabled
	.js & {
		&.au-accordion--open {
			display: block;
			height: auto;
		}

		&.au-accordion--closed {
			display: none;
			height: 0;
		}
	}
}

.au-accordion__body-wrapper {
	@include AU-space( padding, 1unit );
	border-top: 1px solid $AU-color-foreground-border;

	.au-accordion--dark & {
		border-top: 1px solid $AU-colordark-foreground-border;
	}
}

.au-accordion-group {
	list-style: none;
	padding: 0;
}

/*! PANCAKE v1.4.1 PANCAKE-SASS v2.3.7 */

/*
 * THIS FILE IS AUTOGENERATED EVERY TIME YOU INSTALL A PANCAKE MODULE.
 * DO NOT EDIT THIS FILE AND AVOID COMMITTING IT TO VERSION CONTROL.
 */

/* @gov.au/select v2.0.11 */

@import "_index.scss";

@import "core.scss";

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// select module
// The form select element for multiple options
//
// Content:
// - sass-versioning
// - globals
//--------------------------------------------------------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// SASS VERSIONING
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
$name: "@gov.au/select";
$version: "2.0.11";
$dependencies: (
	("@gov.au/core", "3.0.0"),
);

@media print {
	.au-select {
		border-color: #000 !important;
		background-image: AU-svguri('<svg fill="#000" width="1.5em" height="auto" viewBox="0 0 28 12" xmlns="http://www.w3.org/2000/svg">' +
			'<path d="M1.9 1.1L8 7.2l6.1-6.1L16 2.9l-8 8-8-8 1.9-1.8z"/>' +
			'<path fill="none" d="M2-5.8h24v24H2v-24z"/>' +
		'</svg>') !important;
	}
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// select style
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
.au-select {
	@include AU-fontgrid( sm );
	@include AU-space( padding, 0.5unit 2.25unit 0.5unit 0.75unit );

	// 2.875unit = 46px = 40px heig


Housemarque Oy 2002

 Copyright Paul Mensonides 2002

Distributed under the Boost Software License, Version 1.0. (See
		accompanying file LICENSE_1_0.txt or
		copy at www.boost.org/LICENSE_1_0.txt)

		<title>BOOST_PP_SEQ_FOR_EACH_I_R</title>
		<link rel="stylesheet" type="text/css" href="../styles.css">

			The BOOST_PP_SEQ_FOR_EACH_I_R macro repeats a macro for each element in
			a seq.  It reenters BOOST_PP_FOR with maximum efficiency.

			Usage

			BOOST_PP_SEQ_FOR_EACH_I_R(r, macro, data, seq)

			Arguments

r

				The next available BOOST_PP_FOR repetition.

macro

				A macro of the form macro(r, data, i, elem).
				This macro is expanded by BOOST_PP_SEQ_FOR_EACH_I with each element in seq.
				It is expanded with the next available BOOST_PP_FOR repetition, the
				auxiliary data, the index of the current element, and the current
				element.

data

				Auxiliary data passed to macro.

seq

				The seq for which macro will be invoked on each element.

			Remarks

			This macro is a repetition construct.  If seq is (a)(b)(c),
			it expands to the sequence:

				macro(r, data, 0, a) macro(r, data,
				1, b) macro(r, data, 2, c)

			See Also

				BOOST_PP_SEQ_FOR_EACH_I

			Requirements

			Header:  <boost/preprocessor/seq/for_each_i.hpp>

	<hr


fullcalendar_common_main.html#Identity" class="tsd-signature-type" data-tsd-kind="Type alias">Identity<((this: CalendarApi, error: any) => void)>

Inherited from BuiltInBaseOptionRefiners.eventSourceFailure

event<wbr/>Source<wbr/>Success<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-link" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M10 14a3.5 3.5 0 0 0 5 0l4 -4a3.5 3.5 0 0 0 -5 -5l-.5 .5"></path><path d="M14 10a3.5 3.5 0 0 0 -5 0l-4 4a3.5 3.5 0 0 0 5 5l.5 -.5"></path></svg>

event<wbr/>Source<wbr/>Success: Identity<((this: CalendarApi, eventsInput: EventInput[], xhr?: XMLHttpRequest) => void | EventInput[]<span class="tsd-signatur


 }

  private BufferedSink newJournalWriter() throws FileNotFoundException {
    Sink fileSink = fileSystem.appendingSink(journalFile);
    Sink faultHidingSink = new FaultHidingSink(fileSink) {
      @Override protected void onException(IOException e) {
        assert (Thread.holdsLock(DiskLruCache.this));
        hasJournalErrors = true;
      }
    };
    return Okio.buffer(faultHidingSink);
  }

  private void readJournalLine(String line) throws IOException {
    int firstSpace = line.indexOf(' ');
    if (firstSpace == -1) {
      throw new IOException("unexpected journal line: " + line);
    }

    int keyBegin = firstSpace + 1;
    int secondSpace = line.indexOf(' ', keyBegin);
    final String key;
    if (secondSpace == -1) {
      key = line.substring(keyBegin);
      if (firstSpace == REMOVE.length() && line.startsWith(REMOVE)) {
        lruEntries.remove(key);
        return;
      }
    } else {
      key = line.substring(keyBegin, secondSpace);
    }

    Entry entry = lruEntries.get(key);
    if (entry == null) {
      entry = new Entry(key);
      lruEntries.put(key, entry);
    }

    if (secondSpace != -1 && firstSpace == CLEAN.length() && line.startsWith(CLEAN)) {
      String[] parts = line.substring(secondSpace + 1).split(" ");
      entry.readable = true;
      entry.currentEditor = null;
      entry.setLengths(parts);
    } else if (secondSpace == -1 && firstSpace == DIRTY.length() && line.startsWith(DIRTY)) {
      entry.currentEditor = new Editor(entry);
    } else if (secondSpace == -1 && firstSpace == READ.length() && line.startsWith(READ)) {
      // This work was already done by calling lruEntries.get().
    } else {
      throw new IOException("unexpected journal line: " + line);
    }
  }

  /**
   * Computes the initial size and collects garbage as a part of opening the cache. Dirty entries
   * are assumed to be inconsistent and will be deleted.
   */
  private void processJournal() throws IOException {
    fileSystem.delete(journalFileTmp);
    for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
      Entry entry = i.next();
      if (entry.currentEditor == null) {
        for (int t = 0; t < valueCount; t++) {
          size += entry.lengths[t];
        }
      } else {
        entry.currentEditor = null;
        for (int t = 0; t < valueCount; t++) {
          fileSystem.delete(entry.cleanFiles[t]);
          fileSystem.delete(entry.dirtyFiles[t]);
        }
        i.remove();
      }
    }
  }

  /**
   * Creates a new journal that omits redundant information. This replaces the current journal if it
   * exists.
   */
  synchronized void rebuildJournal() throws IOException {
    if (journalWriter != null) {
      journalWriter.close();
    }

    BufferedSink writer = Okio.buffer(fileSystem.sink(journalFileTmp));
    try {
      writer.writeUtf8(MAGIC).writeByte('\n');
      writer.writeUtf8(VERSION_1).writeByte('\n');
      writer.writeDecimalLong(appVersion).writeByte('\n');
      writer.writeDecimalLong(valueCount).writeByte('\n');
      writer.writeByte('\n');

      for (Entry entry : lruEntries.values()) {
        if (entry.currentEditor != null) {
          writer.writeUtf8(DIRTY).writeByte(' ');
          writer.writeUtf8(entry.key);
          writer.writeByte('\n');
        } else {
          writer.writeUtf8(CLEAN).writeByte(' ');
          writer.writeUtf8(entry.key);
          entry.writeLengths(writer);
          writer.writeByte('\n');
        }
      }
    } finally {
      writer


, `vllm`, `no`，默认为`pt`，采样模型的推理引擎。
- output_dir：输出目录，默认为`sample_output`。
- output_file：输出文件名称，默认为`None`使用时间戳作为文件名。传入时不需要传入目录，仅支持jsonl格式。
- override_exist_file：如`output_file`存在，是否覆盖。
- num_sampling_per_gpu_batch_size：每次采样的batch_size。
- num_sampling_per_gpu_batches：共采样多少batch。
- n_best_to_keep：返回多少最佳sequences。
- data_range：本采样处理数据集的分片。传入格式为`2 3`，代表数据集分为3份处理（这意味着通常有三个`swift sample`在并行处理），本实例正在处理第3个分片。
- temperature：在这里默认为1.0。
- prm_threshold：PRM阈值，低于该阈值的结果会被过滤掉，默认值为`0`。
- easy_query_threshold：单个query的所有采样中，ORM评估如果正确，大于该比例的query会被丢弃，防止过于简单的query出现在结果中，默认为`None`，代表不过滤。
- engine_kwargs：传入sampler_engine的额外参数，以json string传入，例如`{"cache_max_entry_count":0.7}`。
- num_return_sequences：采样返回的原始sequence数量。默认为64，本参数对`sample`采样有效。
- cache_files：为避免同时加载prm和generator造成显存OOM，可以分两步进行采样，第一步将prm和orm置为`None`，则所有结果都会输出到文件中，第二次运行采样将sampler_engine置为`no`并传入`--cache_files`为上次采样的输出文件，则会使用上次输出的结果进行prm和orm评估并输出最终结果。
  - 注意：使用cache_files时，`--dataset`仍然需要传入，这是因为cache_files的id是由原始数据计算的md5，需要把两部分信息结合使用。

#### MCTS
- rollout_depth：rollout 时的最大深度，默认为 `5`。
- rollout_start_depth：开始 rollout 时的深度，低于此深度的节点只会进行 expand 操作，默认为 `3`。
- max_iterations：mcts 的最大迭代次数，默认为 `100`。
- process_reward_rate：select 中计算 value 时 process reward 占的比例，默认为 `0.0`，即不使用 PRM。
- exploration_rate：UCT 算法中的探索参数，值越大越照顾探索次数较小的节点，默认为 `0.5`。
- api_key：使用 client 作为推理引擎时需要，默认为 `EMPTY`。
- base_url：使用 client 作为推理引擎时需要，默认为 'https://dashscope.aliyuncs.com/compatible-mode/v1'

## 特定模型参数
特定模型参数可以


158.cn/tags-t-g65b3b7e3781ff.html" target="_blank" class="relatedlink">提供了良好的市场基础。

宠物店的前景和利润是相对较好的。随着人们生活水平的提高，越来越多的人开始养宠物，而宠物店则提供了许多需要的服务和商品，比如宠物食品、宠物用具、宠物医疗服务等等。因此，宠物店在市场上有着广阔的发展空间。

当然利润这东西是看自己经营。我身边好几个朋友都赚了，我也打算开个宠物店。好比宠物店卖的宠物的利润就是一半，比如犬舍供应的一只狗500，你就可以卖1000-1300左右。美容就是纯利润。
<h2 id='开一家宠物店利润大不大啊?'>开一家宠物店利润大不大啊?

开一家宠物店的利润大小取决于多个因素。首先，宠物店的地理位置非常重要。如果位于繁华地段或者宠物密集区域，客源会更多，利润也相对较高。其次，宠物店的经营<a href="http://www.to3158.cn/tags-g-m65b


om[{$sub.type_id}][3]" value="3" lay-skin="primary" title="{:lang('admin/group/popedom_play')}" {if condition="!empty($info['group_popedom'][$sub.type_id][3])"}checked {/if}>
                            <input type="checkbox" name="group_popedom[{$sub.type_id}][4]" value="4" lay-skin="primary" title="{:lang('admin/group/popedom_down')}" {if condition="!empty($info['group_popedom'][$sub.type_id][4])"}checked {/if}>
                            <input type="checkbox" name="group_popedom[{$sub.type_id}][5]" value="5" lay-skin="primary" title="{:lang('admin/group/popedom_trysee')}" {if condition="!empty($info['group_popedom'][$sub.type_id][5])"}checked {/if}>
                            {/if}

                    {/volist}
                {/volist}

                <button type="button" class="layui-btn layui-btn-normal formCheckAll" lay-filter="formCheckAll" >{:lang('check_all')}</button>
                <button type="button" class="layui-btn layui-btn-normal formCheckOther" lay-filter="formCheckOther">{:lang('check_other')}</button>
                <button type="submit" class="layui-btn" lay-submit="" lay-filter="formSubmit" data-child="true">{:lang('btn_save')}</button>
                <button class="layui-btn layui-btn-primary" type="reset">{:lang('btn_reset')}</button>

    </form>

{include file="../../../application/admin/view_new/public/foot" /}

{include file="../../../application/admin/view_new/public/head" /}

{include file="../../../application/admin/view_new/public/editor" flag="vod_editor"/}

    <form class="layui-form layui-form-pane" method="post" action="">
        <input type="hidden" name="vod_id" value="{$info.vod_id}">
        <input


.getComputedStyle(el);

/**
 * Check if an element has visibility:hidden
 * @param {HTMLElement} el
 * @returns {boolean}
 */
export const isVisibilityHidden = el => windowStyle(el).visibility === 'hidden';

/**
 * Check if an element has display:none
 * @param {HTMLElement} el
 * @returns {boolean}
 */
export const isDisplayNone = el => windowStyle(el).display === 'none';

/**
 * Turn an HTML string into HTMLElement
 * @param {string} html
 * @returns {HTMLElement}
 */
export const htmlToDom = html => new DOMParser().parseFromString(html, 'text/html').body; //.firstChild;

/**
 * Get a string and turn it into template literal
 * @param {string} tpl
 * @returns {function}
 *
 * x = parseLit(string)
 * x(state) // to update
 */
export const parseLit = tpl => state => new Function(`return \`${tpl}\``).call(state);

/**
 * Convert a string that contains {...} to ${...}
 * @param {string} str
 * @returns {string}
 */
export const toStrLit = str => str.replace(/\$?\{([^\;\{]+)\}/g, (_, expression) => `\${${expression}}`);

/**
 * Create a function that receive data to create computed state
 * @param {string} key
 * @param {function} fn
 * myCs = computeState(('fullName', (state) => return state.name) => )
 * myCs({name: 'Mardix'})
 * myCs.fullName -> Mardix
 */
export const computeState = (key, fn) => state => (state[key] = fn({ ...state }));

/**
 *
 * @param {function} callback
 * @param {number} time
 * @param {any} interval
 * @returns {any}
 */
export const debounce = (callback, time = 250, interval) => (...args) =>
  clearTimeout(interval, (interval = setTimeout(callback, time, ...args)));

/**
 * @type {array}
 */
const decodeHTMLList = [
  ['<', '<'],
  ['>', '>'],
  ['&', '&'],
];

/**
 * To decode html string for directive
 * change < + >  to < + > respectively
 * @param {string} str
 * @returns {string}
 */
export const decodeHTMLStringForDirective = str =>
  decodeHTMLList.reduce((pV, cK) => pV.replace(new RegExp(cK[0], 'g'), cK[1]), str);

/**
 * Returns all attributes into an object
 * @param {HTMLElement} el
 * @param {boolean} camelCaseIt
 * @returns {object}
 */
export const getAttrs = (el, camelCaseIt = false) =>
  Object.freeze(
    Array.from(el.attributes)
      .map(e => ({ [camelCaseIt ? camelCase(e.name) : e.name]: e.value }))
      .reduce((pV, cK) => ({ ...pV, ...cK }), {})
  );

const proxyTarget = '#';
const isPrimitive = value => value === null || !['function', 'object'].includes(typeof value);

/**
 * Generate random chars. Mainly to use in webcomponent without name
 * @param {number} l the length
 * @return {string}
 */
export const randomChars = (l = 7) =>
  Math.random()
    .toString(36)
    .substr(2, l)
    .toLowerCase();

/**
 * objectOnChange
 * Observe an object change, and run onChange()
 * @param {*} object
 * @param {*} onChange
 */
export const objectOnChange = (object, onChange) => {
  let inApply = false;
  let changed = false;
  const propCache = new WeakMap();

  const handleChange = () => {
    if (!inApply) onChange();
    else if (!changed) changed = true;
  };

  const getOwnPropertyDescriptor = (target, property) => {
    let props = propCache.get(target);
    if (props) return


10.26l25.78-63.26c3.02-7.39.2-15.85-6.68-20.07l-39.28-24.1C98.51-3.87 80.09-.5 68.95 11.97c-92.57 103.6-92 259.55 2.1 362.49 9.87 10.8 29.12 12.48 41.65 4.8l39.41-24.18c6.89-4.22 9.7-12.67 6.69-20.07zM480 384H192c-35.35 0-64 28.65-64 64v32c0 17.67 14.33 32 32 32h352c17.67 0 32-14.33 32-32v-32c0-35.35-28.65-64-64-64zm-144 96c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32z"],blind:[384,512,[],"f29d","M380.15 510.837a8 8 0 0 1-10.989-2.687l-125.33-206.427a31.923 31.923 0 0 0 12.958-9.485l126.048 207.608a8 8 0 0 1-2.687 10.991zM142.803 314.338l-32.54 89.485 36.12 88.285c6.693 16.36 25.377 24.192 41.733 17.501 16.357-6.692 24.193-25.376 17.501-41.734l-62.814-153.537zM96 88c24.301 0 44-19.699 44-44S120.301 0 96 0 52 19.699 52 44s19.699 44 44 44zm154.837 169.128l-120-152c-4.733-5.995-11.75-9.108-18.837-9.112V96H80v.026c-7.146.003-14.217 3.161-18.944 9.24L0 183.766v95.694c0 13.455 11.011 24.791 24.464 24.536C37.505 303.748 48 293.1 48 280v-79.766l16-20.571v140.698L9.927 469.055c-6.04 16.609 2.528 34.969 19.138 41.009 16.602 6.039 34.968-2.524 41.009-19.138L136 309.638V202.441l-31.406-39.816a4 4 0 1 1 6.269-4.971l102.3 129.217c9.145 11.584 24.368 11.339 33.708 3.965 10.41-8.216 12.159-23.334 3.966-33.708z"],blog:[512,512,[],"f781","M172.2 226.8c-14.6-2.9-28.2 8.9-28.2 23.8V301c0 10.2 7.1 18.4 16.7 22 18.2 6.8 31.3 24.4 31.3 45 0 26.5-21.5 48-48 48s-48-21.5-48-48V120c0-13.3-10.7-24-24-24H24c-13.3 0-24 10.7-24 24v248c0 89.5 82.1 160.2 175 140.7 54.4-11.4 98.3-55.4 109.7-109.7 17.4-82.9-37-157.2-112.5-172.2zM209 0c-9.2-.5-17 6.8-17 16v31.6c0 8.5 6.6 15.5 15 15.9 129.4 7 233.4 112 240.9 241.5.5 8.4 7.5 15 15.9 15h32.1c9.2 0 16.5-7.8 16-17C503.4 139.8 372.2 8.6 209 0zm.3 96c


Op::create(b, nestedLoc, mulType, args[1]);
          mul = arith::MulIOp::create(b, nestedLoc, args[0], ext1);
        } else {
          Value ext0 = arith::ExtSIOp::create(b, nestedLoc, mulType, args[0]);
          Value ext1 = arith::ExtUIOp::create(b, nestedLoc, mulType, args[1]);
          mul = arith::MulIOp::create(b, nestedLoc, ext0, ext1);
        }
        Value sum;
        if (mulType == accType) {
          sum = arith::AddIOp::create(b, nestedLoc, mul, args[2]);
        } else {
          Value extMul = arith::ExtSIOp::create(b, nestedLoc, accType, mul);
          sum = arith::AddIOp::create(b, nestedLoc, extMul, args[2]);
        }
        linalg::YieldOp::create(b, nestedLoc, sum);
      });
  LLVM_DEBUG(DBGS() << "integerMatmulOp:   " << integerMatmulOp << "\n");
  return integerMatmulOp;
}

// Creates a generic that does the reassociated dequantization math, and does
// the final reduction along the number of groups dimension.
linalg::GenericOp
QuantizedMatmulRewriter::generateReassociatedDequantizationGeneric(
    SmallVector<Value> quantizeResults, Value quantizedIntegerMatmul) {
  assert(quantizeResults.size() == 4 &&
         "expected 4 ops from quantization step");
  Value scales = ins[2]->get();
  Value zps = ins[3]->get();
  Value newScales = quantizeResults[1];
  Value groupSums = quantizeResults[2];

  SmallVector<utils::IteratorType> iterators =
      getParallelAndReductionIterators(matmul.getNumLoops() - 1, 1);
  SmallVector<AffineMap> maps;
  AffineMap quantizedIntegerMatmulMap =
      rewriter.getMultiDimIdentityMap(iterators.size());
  maps.push_back(quantizedIntegerMatmulMap);

  {
    OpOperand *matmulUnquantizedOperand = ins[1];
    auto exprs =
        matmul.getMatchingIndexingMap(matmulUnquantizedOperand).getResults();
    exprs = exprs.slice(0, exprs.size() - 1);
    auto newScalesAndSumsMap =
        AffineMap::get(iterators.size(), 0, exprs, exprs.front().getContext());
    maps.push_back(newScalesAndSumsMap);
    maps.push_back(newScalesAndSumsMap);
  }

  {
    OpOperand *matmulDequantizedOperand = ins[4];
    auto exprsRef =
        matmul.getMatchingIndexingMap(matmulDequantizedOperand).getResults();
    SmallVector<AffineExpr> exprs(exprsRef.slice(0, exprsRef.size() - 1));
    RankedTensorType scalesType =
        llvm::cast<RankedTensorType>(scales.getType());
    RankedTensorType zpsType = llvm::cast<RankedTensorType>(zps.getType());
    if (exprs.size() < scalesType.getShape().size() &&
        scalesType.getShape().back() == 1 && zpsType.getShape().back() == 1) {
      exprs.push_back(rewriter.getAffineConstantExpr(0));
    }
    assert(exprs.size() == scalesType.getShape().size() &&
           "unexpected rank for scales");
    assert(exprs.size() == zpsType.getShape().size() &&
           "unexpected rank for zero points");
    auto scalesAndZpsMap =
        AffineMap::get(iterators.size(), 0, exprs, exprs.front().getContext());
    maps.push_back(scalesAndZpsMap);
    maps.push_back(scalesAndZpsMap);
  }

  OpOperand *matmulOutputOperand = matmul.getDpsInitOperand(0);
  SmallVector<AffineExpr> outputExprs(
      matmul.


primary_fungible_store_primary_store">

## Function `primary_store`

Get the primary store object for the given account.

#[view]
public fun primary_store<T: key>(owner: address, metadata: object::Object<T>): object::Object<fungible_asset::FungibleStore>

Implementation

public fun primary_store<T: key>(owner: address, metadata: Object<T>): Object<FungibleStore> {
    let store = primary_store_address(owner, metadata);
    object::address_to_object<FungibleStore>(store)
}

## Function `primary_store_exists`

Return whether the given account's primary store exists.

#[view]
public fun primary_store_exists<T: key>(account: address, metadata: object::Object<T>): bool

Implementation

public fun primary_store_exists<T: key>(account: address, metadata: Object<T>): bool {
    fungible_asset::store_exists(primary_store_address(account, metadata))
}

## Function `primary_store_address_inlined`

Get the address of the primary store for the given account.
Use instead of the corresponding view functions for dispatchable hooks to avoid circular dependencies of modules.

public fun primary_store_address_inlined<T: key>(owner: address


#!/usr/bin/python3
"""A python module that determines if all boxes can be opened
   from a list of lists
"""

def canUnlockAll(boxes=[]):
    """A function that returns True of all box in
    boxes can be opend
    """
    if not boxes:
        return False

    keys = set([0])
    for box_id, box in enumerate(boxes):
        for key in box:
            if key < len(boxes) and key != box_id:
                keys.add(key)

    if len(keys) != len(boxes):
        return False

    return True

if __name__ == '__main__':
    boxes = [
                [1, 3],
                [2],
                [3, 0],
                [1, 2, 3],
            ]
    print(unlockBoxes(boxes))

    boxes = [[1], [2], [3], [4], []]
    print(canUnlockAll(boxes))

    boxes = [[1, 4, 6], [2], [0, 4, 1], [5, 6, 2], [3], [4, 1], [6]]
    print(unlockBoxes(boxes))

    boxes = [[1, 4], [2], [0, 4, 1], [3], [], [4, 1], [5, 6]]
    print(unlockBoxes(boxes))


Library_SetGravity, KawaiiPhysics) == 0x000000, "Member 'KawaiiPhysicsLibrary_SetGravity::KawaiiPhysics' has a wrong offset!");
static_assert(offsetof(KawaiiPhysicsLibrary_SetGravity, Gravity) == 0x000010, "Member 'KawaiiPhysicsLibrary_SetGravity::Gravity' has a wrong offset!");
static_assert(offsetof(KawaiiPhysicsLibrary_SetGravity, ReturnValue) == 0x000028, "Member 'KawaiiPhysicsLibrary_SetGravity::ReturnValue' has a wrong offset!");

// Function KawaiiPhysics.KawaiiPhysicsLibrary.SetNeedWarmUp
// 0x0028 (0x0028 - 0x0000)
struct KawaiiPhysicsLibrary_SetNeedWarmUp final
{
public:
	struct FKawaiiPhysicsReference                KawaiiPhysics;                                     // 0x0000(0x0010)(ConstParm, Parm, OutParm, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic)
	bool                                          NeedWarmUp;                                        // 0x0010(0x0001)(Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
	uint8                                         Pad_11[0x7];                                       // 0x0011(0x0007)(Fixing Size After Last Property [ Dumper-7 ])
	struct FKawaiiPhysicsReference                ReturnValue;                                       // 0x0018(0x0010)(Parm, OutParm, ReturnParm, NoDestructor, NativeAccessSpecifierPublic)
};
static_assert(alignof(KawaiiPhysicsLibrary_SetNeedWarmUp) == 0x000008, "Wrong alignment on KawaiiPhysicsLibrary_SetNeedWarmUp");
static_assert(sizeof(KawaiiPhysicsLibrary_SetNeedWarmUp) == 0x000028, "Wrong size on KawaiiPhysicsLibrary_SetNeedWarmUp");
static_assert(offsetof(KawaiiPhysicsLibrary_SetNeedWarmUp, KawaiiPhysics) == 0x000000, "Member 'KawaiiPhysicsLibrary_SetNeedWarmUp::KawaiiPhysics' has a wrong offset!");
static_assert(offsetof(KawaiiPhysicsLibrary_SetNeedWarmUp, NeedWarmUp) == 0x000010, "Member 'KawaiiPhysicsLibrary_SetNeedWarmUp::NeedWarmUp' has a wrong offset!");
static_assert(offsetof(KawaiiPhysicsLibrary_SetNeedWarmUp, ReturnValue) == 0x000018, "Member 'KawaiiPhysicsLibrary_SetNeedWarmUp::ReturnValue' has a wrong offset!");

// Function KawaiiPhysics.KawaiiPhysicsLibrary.SetPhysicsSettings
// 0x0040 (0x0040 - 0x0000)
struct KawaiiPhysicsLibrary_SetPhysicsSettings final
{
public:
	struct FKawaiiPhysicsReference                KawaiiPhysics;                                     // 0x0000(0x0010)(ConstParm, Parm, OutParm, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic)
	struct FKawaiiPhysicsSettings                 PhysicsSettings;                                   // 0x0010(0x0020)(Parm, OutParm, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic)
	struct FKawaiiPhysicsReference                ReturnValue;                                       // 0x0030(0x0010)(Parm, OutParm, ReturnParm, NoDestructor, NativeAccessSpecifierPublic)
};
static_assert(alignof(KawaiiPhysicsLibrary_SetPhysicsSettings) == 0x000008, "Wrong alignment on KawaiiPhysicsLibrary_SetPhysicsSettings");
static_assert(sizeof(KawaiiPhysicsLibrary_SetPhysicsSettings) == 0x000040, "Wrong size on KawaiiPhysicsLibrary_SetPhysicsSettings");
static_assert(offsetof(KawaiiPhysicsLibrary_SetPhysicsSettings, KawaiiPhysics) == 0x000000, "Member 'KawaiiPhysicsLibrary_SetPhysicsSettings::KawaiiPhysics' has a wrong offset!");
static_assert(offsetof(KawaiiPhysicsLibrary_SetPhysicsSettings, PhysicsSettings) == 0x000010, "Member 'KawaiiPhysicsLibrary_SetP


te that sqlite will repeat the type you tell it, but in many cases, it's ignored.  So you can initialize a column as CHAR(3) but it's really TEXT.  See https://www.sqlite.org/datatype3.html
//
// This info may additionally conflict with the reality that your data is being JSON encoded/decoded.
func (qr *QueryResult) Types() []string {
	return qr.types
}
package cdc

import (
	"expvar"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sync"
	"sync/atomic"
	"time"

	cdcjson "github.com/rqlite/rqlite/v9/cdc/json"
	"github.com/rqlite/rqlite/v9/command/proto"
	"github.com/rqlite/rqlite/v9/internal/rarchive/flate"
	"github.com/rqlite/rqlite/v9/internal/rsync"
	"github.com/rqlite/rqlite/v9/queue"
)

const (
	cdcDB         = "fifo.db"
	leaderChanLen = 5   // Support any fast back-to-back leadership changes.
	inChanLen     = 100 // Size of the input channel for CDC events.

	retryForever = -1
)

const (
	numDroppedFailedToSend = "dropped_failed_to_send"
	numRetries             = "retries"
	numEventsTxOK          = "num_events_tx_ok"
	numEventTxFailed       = "num_events_tx_failed"
	numBytesTx             = "num_bytes_tx"
	numSnapshotSync        = "snapshot_sync"
	numBatcherWrites       = "batcher_writes"
	numBatcherEventsWrite  = "batcher_events_write"
	numBatcherReads        = "batcher_reads"
	numBatcherWriteIgnored = "batcher_write_ignored"
	numFIFOEnqueueIgnored  = "fifo_enqueue_ignored"
	numHWMIgnored          = "hwm_ignored"
	fifoSize               = "fifo_size"
)

// stats captures stats for the CDC Service.
var stats *expvar.Map

func init() {
	stats = expvar.NewMap("cdc-service")
	ResetStats()
}

// ResetStats resets the expvar stats for this module. Mostly for test purposes.
func ResetStats() {
	stats.Init()
	stats.Add(numDroppedFailedToSend, 0)
	stats.Add(numRetries, 0)
	stats.Add(numEventsTxOK, 0)
	stats.Add(numEventTxFailed, 0)
	stats.Add(numBytesTx, 0)
	stats.Add(numSnapshotSync, 0)
	stats.Add(numBatcherWrites, 0)
	stats.Add(numBatcherEventsWrite, 0)
	stats.Add(numBatcherReads, 0)
	stats.Add(numBatcherWriteIgnored, 0)
	stats.Add(numFIFOEnqueueIgnored, 0)
	stats.Add(numHWMIgnored, 0)
	stats.Add(fifoSize, 0)
}

// Cluster is an interface that defines methods for cluster management and communication.
type Cluster interface {
	// RegisterLeaderChange registers the given channel which will receive
	// a signal when the node detects that the Leader changes.
	RegisterLeaderChange(c chan<- bool)

	// RegisterSnapshotSync registers a channel to allow synchronization with
	// Snapshotting.
	RegisterSnapshotSync(ch chan<- chan struct{})

	// RegisterHWMUpdate registers a channel to receive highwater mark updates.
	RegisterHWMUpdate(c chan<- uint64)

	// BroadcastHighWatermark sets the high watermark across the cluster.
	BroadcastHighWatermark(value uint64) error
}

// Service is a CDC service that reads events from


rence.CreateFromDiscriminatorValue); } },
                { "startDateTime", n => { StartDateTime = n.GetObjectValue<global::Microsoft.Graph.Beta.Models.DateTimeTimeZone>(global::Microsoft.Graph.Beta.Models.DateTimeTimeZone.CreateFromDiscriminatorValue); } },
                { "type", n => { Type = n.GetEnumValue<global::Microsoft.Graph.Beta.Models.EventType>(); } },
            };
        }
        /// <summary>
        /// Serializes information the current object
        /// </summary>
        /// <param name="writer">Serialization writer to use to serialize this model</param>
        public override void Serialize(ISerializationWriter writer)
        {
            if(ReferenceEquals(writer, null)) throw new ArgumentNullException(nameof(writer));
            base.Serialize(writer);
            writer.WriteObjectValue<global::Microsoft.Graph.Beta.Models.DateTimeTimeZone>("endDateTime", EndDateTime);
            writer.WriteObjectValue<global::Microsoft.Graph.Beta.Models.Event>("event", Event);
            writer.WriteBoolValue("isAllDay", IsAllDay);
            writer.WriteBoolValue("isDelegated", IsDelegated);
            writer.WriteBoolValue("isOutOfDate", IsOutOfDate);
            writer.WriteObjectValue<global::Microsoft.Graph.Beta.Models.Location>("location", Location);
            writer.WriteEnumValue<global::Microsoft.Graph.Beta.Models.MeetingMessageType>("meetingMessageType", MeetingMessageType);
            writer.WriteObjectValue<global::Microsoft.Graph.Beta.Models.PatternedRecurrence>("recurrence", Recurrence);
            writer.WriteObjectValue<global::Microsoft.Graph.Beta.Models.DateTimeTimeZone>("startDateTime", StartDateTime);
            writer.WriteEnumValue<global::Microsoft.Graph.Beta.Models.EventType>("type", Type);
        }
    }
}
#pragma warning restore CS0618


    /**
     * Sets the marker size (in px).
     * Default: 6.
     */
    public var size: Number by numberGreaterThan(0)

    /**
     * Array of numbers greater than or equal to 0.
     * Sets the markers size. Default: 6.
     */
    public var sizesList: List<Number> by numberList(key = "size".asName())

    /**
     * Sets the marker opacity.
     */
    public var opacity: Number by numberInRange(0.0..1.0)

    /**
     * Sets the markers opacity.
     */
    public var opacitiesList: List<Number> by numberList(key = "opacity".asName())

    /**
     * Sets a maximum number of points to be drawn on the graph.
     * "0" corresponds to no limit.
     * Default: 0.
     */
    public var maxdisplayed: Int by intGreaterThan(0)

    /**
     * Has an effect only if `size` is set to a numerical array.
     * Sets the scale factor used to determine the rendered size
     * of marker points. Use with `sizemin` and `sizemode`.
     * Default: 1.
     */
    public var sizeref: Number? by number()

    /**
     * Has an effect only if `marker.size` is set to a numerical array.
     * Sets the minimum size (in px) of the rendered marker points.
     * Default: 0.
     */
    public var sizemin: Number by numberGreaterThan(0)

    /**
     * Enumerated , one of ( "diameter" | "area" )
     * Has an effect only if `marker.size` is set to a numerical array.
     * Sets the rule for which the data in `size` is converted to pixels.
     * Default: "diameter".
     */
    public var sizemode: SizeMode by enum(SizeMode.diameter)

    public var line: MarkerLine by scheme(MarkerLine)

    /**
     * Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale
     * relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set.
     */
    public val color: Color by color()

    /**
     * Sets the color of each sector. If not specified, the default trace color set is used to pick the sector colors.
     */
    public var pieColors: List<Value> by listOfValues(key = "colors".asName())

    public var colorbar: ColorBar by scheme(ColorBar)

    public var gradient: Gradient by scheme(Gradient)

    /**
     * Sets the color of the outlier sample points. Default: rgba(0, 0, 0, 0).
     */
    public val outliercolor: Color by color()

    public fun colors(colors: Iterable<Any>) {
        color.value = colors.map { Value.of(it) }.asValue()
    }

    public fun line(block: MarkerLine.() -> Unit) {
        line = MarkerLine(block)
    }

    public fun colorbar(block: ColorBar.() -> Unit) {
        colorbar = ColorBar(block)
    }

    public fun gradient(block: Gradient.() -> Unit) {
        gradient = Gradient(block)
    }

    public companion object : SchemeSpec<Marker>(::Marker)
}

/*
 * Copyright 2018-2024 KMath contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package space.kscience.kmath.nd4j

import org.nd4j.linalg.api.ndarray.INDArray
import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.nd.*
import space.kscience.kmath.structures.Float64

/**
 * Represents a [StructureND] wrapping an [INDArray] object.
 *
 * @param T the type of items.
 */
public sealed class Nd4jArrayStructure<T> : MutableStructureND<T