eme.of(context).textTheme.headline6,
                textAlign: TextAlign.left,
              ),
              const SizedBox(height: 10),
              Text(
                languageNameFromCode["de"]! +
                    ", " +
                    languageNameFromCode["en"]! +
                    ", " +
                    languageNameFromCode["fr"]! +
                    ": " +
                    L10n.of(context).imprintPageMyName,
                textAlign: TextAlign.left,
              ),
              Text(
                languageNameFromCode["es"]! + ": Luciano Gardella",
                textAlign: TextAlign.left,
              ),
              Text(
                languageNameFromCode["pl"]! + ": Mateusz Bartczak (matebart)",
                textAlign: TextAlign.left,
              ),
              Text(
                languageNameFromCode["nl"]! + ": Pander (PanderMusubi)",
                textAlign: TextAlign.left,
              ),
              Text(
                languageNameFromCode["ca"]! + ": Maite Guix",
                textAlign: TextAlign.left,
              ),
              const SizedBox(height: 20),
              Text(
                L10n.of(context).imprintPageDataHeadline,
                style: Theme.of(context).textTheme.headline6,
                textAlign: TextAlign.left,
              ),
              const SizedBox(height: 10),
              Text(
                L10n.of(context).imprintPageDataText,
                textAlign: TextAlign.left,
              ),
              const SizedBox(height: 10),
              Text(L10n.of(context).imprintPageDataText2,
                  textAlign: TextAlign.left,
                  style: Theme.of(context)
                      .textTheme
                      .bodyText1
                      ?.copyWith(fontStyle: FontStyle.italic)),
              const SizedBox(height: 20),
              GestureDetector(
                child: Text(
                  L10n.of(context).imprintPageImagesHeadline,
                  style: Theme.of(context).textTheme.headline6?.copyWith(
                      color: Theme.of(context).colorScheme.secondary),
                  textAlign: TextAlign.left,
                ),
                onTap: () =>
                    Navigator.of(context).pushNamed("/etc/imprint/imgs"),
              ),
              const SizedBox(height: 10),
              Text(
                L10n.of(context).imprintPageFontsHeadline,
                style: Theme.of(context).textTheme.headline6,
                textAlign: TextAlign.left,
              ),
              const SizedBox(height: 10),
              Text(
                L10n.of(context).imprintPageFontsText,
                textAlign: TextAlign.left,
              ),
            ],
          ))),
    );
  }
}
// 用于String替换掉Html元素的分类
extension Extension on String {
  String get replaceHtmlElement {
    return replaceAll(RegExp("(<em[^>]*>)|(</em>)"), "")
        .replaceAll(RegExp("\n{2,}"), "\n")
        .replaceAll(RegExp("s{2,}"), " ")
        .replaceAll("–", "–")
        .replaceAll("—", "—")
        .replaceAll("‘", "‘")
        .replaceAll("’", "’")
        .replaceAll("‚", "‚")
        .replaceAll("“", "“")
        .replaceAll("”", "”")
        .replaceAll("„", "„")
        .replaceAll("‰", "‰")
        .replaceAll("‹", "‹")
        .replaceAll("›", "›")


} else {
        $(".items .card").hide();
        $(".items .empty").hide();

        $(".dropzone").remove();

        $.each(results, function (index, item) {
            $("#order" + item.id).show();
            $('

').insertAfter("#order" + item.id);
            $("#operationalTask" + item.id).show();
        });

        if ($("#dashboardKanban #ordersPending").length) {
            $(".items:not(:has(.card.draggable))").append($('

'));
        }
    }
}

function addOrder() {
    QCD.orderDefinitionWizard.init();
}

function addOperationalTask() {
    QCD.operationalTasksDefinitionWizard.init();
}

function goToOrderDetails(id) {
    goToPage("orders/orderDetails.html?context=" + JSON.stringify({
        "form.id": id,
        "form.undefined": null
    }), true);
}

function goToOperationalTaskDetails(id) {
    goToPage("orders/operationalTaskDetails.html?context=" + JSON.stringify({
        "form.id": id,
        "form.undefined": null
    }), true);
}

function goToProductionTrackingTerminal(orderId, operationalTaskId, workstationNumber) {
    let url = "/productionRegistrationTerminal.html";
    if (orderId) {
        url += "?orderId=" + orderId;
    } else if (operationalTaskId) {
        url += "?operationalTaskId=" + operationalTaskId;
        if (workstationNumber) {
            url += '&workstationNumber=' + workstationNumber;
        }
    }
    goToPage(url, false);
}

function printLabel(orderId) {
    let url = "orders/ordersLabelReport.pdf?id=" + orderId;
    window.open(url, '_blank');
}

function showMessage(type, title, content, autoClose) {
    messagesController.addMessage({
        type : type,
        title : title,
        content : content,
        autoClose : autoClose,
        extraLarge : false
    });
}

function logoutIfSessionExpired(data) {
	if ($.trim(data) == "sessionExpired" || $.trim(data).substring(0, 20) == "<![CDATA[ERROR PAGE:") {
		window.location = "/login.html?timeout=true";
	}
}
/*
 * ***************************************************************************
 * Copyright (c) 2010 Qcadoo Limited
 * Project: Qcadoo MES
 * Version: 1.3
 *
 * This file is part of Qcadoo.
 *
 * Qcadoo is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * ***************************************************************************
 */
$(function() {
	$('#fileupload')
			.fileupload(
					{
						pasteZone: null,
						dataType : 'json',
						acceptFileTypes : QCDMultiUpload.acceptFileTypes,

						submit : function(e, data) {
							var locale = window.mainController
							.getComponentByReferenceName(
								"workstationMultiUploadLocale")
									.getValue().content.value;
							var techId = window.mainController
								.getComponentByReferenceName(
									"workstationIdForMultiUpload")
										.getVal


var bottomPaddingTop = parseInt(bottom.getStyle('padding-top'));
      var allDraggables = $$('.xEditableDragXY:not(.xFixed)');
      var maxY = y = 0;
      var windowH = window.getSize().y;
      var windowW = window.getSize().x;
      var bottomH = 0;

      bottom.getChildren().each(function (item) {
        var bottomElH = item.getSize().y;
        if (bottomElH > bottomH) {
          bottomH = bottomElH;
        }
      });

      if (this.isResponsive || (this.isAutoResponsive && bertaGlobalOptions.environment == 'site' && windowW < this.mobileBrekapoint)) {
        maxY = $('allContainer').getSize().y;
        //add h1 margin-top to the height
        var h1 = $$('h1');
        if (h1) {
          maxY = maxY + parseInt(h1.getStyle('margin-top'));
        }
      } else {
        allDraggables.each(function (item) {
          y = parseInt(item.getStyle('top')) + parseInt(item.getSize().y)
          if (maxY < y) {
            maxY = y;
          }
        });
      }

      if (maxY < windowH - bottomH) {
        maxY = windowH - bottomH - bottomPaddingTop;
      }

      bottom.setStyle('top', maxY + 'px');
    }
  },

  editor_saveOrder: function (event) {
    event.stop();

    var target = $(event.target);
    target = target.getParent('.xEntry');
    var entriesList = target.getParent('.xEntriesList');
    var nextEntry = entriesList.getFirst('.xEntry');
    target.inject(entriesList, 'top');

    var entryId = target.getClassStoredValue('xEntryId');
    var value = nextEntry.getClassStoredValue('xEntryId');
    var site = getCurrentSite();

    redux_store.dispatch(Actions.initOrderSectionEntries(
      site,
      bertaEditor.currentSection,
      entryId,
      value
    ));
  },

  firstPageInit: function () {
    this.entriesContainer = $('firstPageMarkedEntries');
    if (this.entriesContainer && bertaGlobalOptions.environment == 'site') {
      this.entriesContainer.getElements('.firstPagePic').each(function (el) {
        el.addEvent('mouseenter', this.onFirstPagePicMouseEnter.bindWithEvent(this));
        el.addEvent('mouseleave', this.onFirstPagePicMouseLeave.bindWithEvent(this));
        el.addEvent('mousemove', this.onFirstPagePicMouseMove.bindWithEvent(this));
        el.store('prevMouseX', 0);
        el.store('prevMouseY', 0);
        el.store('mouseMoveOn', false);
      }.bind(this));
    }
  },

  onFirstPagePicMouseEnter: function (event) {
    var target = $(event.target);
    if (!target.hasClass('firstPagePic')) {
      target = target.getParent('.firstPagePic');
    }

    target.store('mouseMoveOn', true);

    target.store('prevMouseX', event.page.x);
    target.store('prevMouseY', event.page.y);
    target.store('initPosX', target.getStyle('left'));
    target.store('initPosY', target.getStyle('top'));

  },

  onFirstPagePicMouseLeave: function (event) {
    var target = $(event.target);
    if (!target.hasClass('firstPagePic')) {
      target = target.getParent('.firstPagePic');
    }

    target.setStyle('left', target.retrieve('initPosX'));
    target.setStyle('top', target.retrieve('initPosY'));
  },

  onFirstPagePicMouseMove: function (event) {
    var target = $(event.target);
    if (!target.hasClass('firstPagePic')) {
      target = target.getParent('.firstPagePic');
    }
    if (target


CCreateRel::ShowKeyIndex()
{
	IndexManager	ciu;

	ciu.Create(m_hwnd, m_tunnel, m_mysql, (wyChar*)m_db.GetString(), (wyChar*)m_table.GetString());

	return wyTrue;
}

wyBool
CCreateRel::ShowRefIndex()
{
	IndexManager	ciu;
	wyInt32			cursel;
	wyWChar			table[SIZE_512] = {0};
	wyString		tablestr;

	cursel = SendMessage(GetDlgItem(m_hwnd, IDC_TABLELIST), CB_GETCURSEL, 0, 0);

	if(cursel == CB_ERR)
    {
		yog_message(m_hwnd, _(L"Please select a reference table"), pGlobals->m_appname.GetAsWideChar(), MB_OK | MB_ICONINFORMATION | MB_HELP);
		return wyFalse;
	}

	VERIFY(SendMessage(GetDlgItem(m_hwnd, IDC_TABLELIST), CB_GETLBTEXT, cursel, (LPARAM)table));

	tablestr.SetAs(table);

	ciu.Create(m_hwnd, m_tunnel, m_mysql, m_db.GetString(), tablestr.GetString());

	return wyTrue;

}/* Copyright (C) 2013 Webyog Inc

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA

*/

#include "wyIni.h"
#include "wyString.h"
#include "Global.h"
#include "CommonHelper.h"

extern PGLOBALS	pGlobals;

wyBool
wyIni::Initialize(const wyChar* filename, const wyChar* sec, const wyChar* key)
{
    EnterCriticalSection(&pGlobals->m_csiniglobal);
	InitializeContent();

	m_errormsg = NULL;
	m_flag  = REPLACE;
    m_sectionnameonly = wyFalse;
    m_filename.SetAs(filename);

    if(LoadFile(m_filename.GetString(), sec, key) == wyFalse)
		return wyFalse;

	return wyTrue;
}

void
wyIni::SetSectionNameOnly(wyBool issectiononly)
{
    m_sectionnameonly = issectiononly;
}

void
wyIni::Finialize(wyBool iswrite)
{

    if(iswrite == wyTrue)
    SaveFile();

    FreeListData();

    LeaveCriticalSection(&pGlobals->m_csiniglobal);
}

// get value
wyInt32
wyIni::IniGetString(const wyChar *sec,const wyChar *key, const wyChar *defval, wyString *returnedstring, const wyChar *path)
{
    wyIni       inimngr;
    wyInt32     noofchars;

    if(!path)
    {
        returnedstring->SetAs(defval);
        noofchars = strlen(defval);
        return noofchars;
    }


Equal(
			stdlibx509.KeyUsageDigitalSignature|stdlibx509.KeyUsageKeyEncipherment,
			serverCert.KeyUsage,
		)
		suite.Assert().Equal([]stdlibx509.ExtKeyUsage{stdlibx509.ExtKeyUsageServerAuth}, serverCert.ExtKeyUsage)

		return nil
	})
}
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package secrets_test

import (
	stdlibx509 "crypto/x509"
	"fmt"
	"testing"
	"time"

	"github.com/cosi-project/runtime/pkg/resource"
	"github.com/cosi-project/runtime/pkg/resource/rtestutils"
	"github.com/siderolabs/crypto/x509"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"

	"github.com/cozystack/talm/internal/app/machined/pkg/controllers/ctest"
	secretsctrl "github.com/cozystack/talm/internal/app/machined/pkg/controllers/secrets"
	"github.com/siderolabs/talos/pkg/machinery/resources/secrets"
)

func TestMaintenanceSuite(t *testing.T) {
	suite.Run(t, &MaintenanceSuite{
		DefaultSuite: ctest.DefaultSuite{
			Timeout: 2 * time.Second,
			AfterSetup: func(suite *ctest.DefaultSuite) {
				suite.Require().NoError(suite.Runtime().RegisterController(&secretsctrl.MaintenanceController{}))
			},
		},
	})
}

type MaintenanceSuite struct {
	ctest.DefaultSuite
}

func (suite *MaintenanceSuite) TestReconcile() {
	rootSecrets := secrets.NewMaintenanceRoot(secrets.MaintenanceRootID)

	rootCA, err := x509.NewSelfSignedCertificateAuthority(
		x509.Organization("talos"),
	)
	suite.Require().NoError(err)

	rootSecrets.TypedSpec().CA = &x509.PEMEncodedCertificateAndKey{
		Crt: rootCA.CrtPEM,
		Key: rootCA.KeyPEM,
	}
	suite.Require().NoError(suite.State().Create(suite.Ctx(), rootSecrets))

	certSANs := secrets.NewCertSAN(secrets.NamespaceName, secrets.CertSANMaintenanceID)
	certSANs.TypedSpec().Append(
		"example.com",
		"foo",
		"10.2.1.3",
	)

	certSANs.TypedSpec().FQDN = "maintenance-service"
	suite.Require().NoError(suite.State().Create(suite.Ctx(), certSANs))

	rtestutils.AssertResources(suite.Ctx(), suite.T(), suite.State(), []resource.ID{secrets.MaintenanceServiceCertsID},
		func(certs *secrets.MaintenanceServiceCerts, asrt *assert.Assertions) {
			spec := certs.TypedSpec()

			asrt.Equal(rootCA.CrtPEM, spec.CA.Crt)
			asrt.Nil(spec.CA.Key)

			serverCert, err := spec.Server.GetCert()
			asrt.NoError(err)

			if err != nil {
				return
			}

			asrt.Equal([]string{"example.com", "foo"}, serverCert.DNSNames)
			asrt.Equal("[10.2.1.3]", fmt.Sprintf("%v", serverCert.IPAddresses))

			asrt.Equal("maintenance-service", serverCert.Subject.CommonName)
			asrt.Empty(serverCert.Subject.Organization)

			asrt.Equal(
				stdlibx509.KeyUsageDigitalSignature,
				serverCert.KeyUsage,
			)
			asrt.Equal([]stdlibx509.ExtKeyUsage{stdlibx509.ExtKeyUsageServerAuth}, serverCert.ExtKeyUsage)
		})
}
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a


 = stackGroups[stackKey];
					} else if (otherOptions.grouping !== false) { // #1162
						columnIndex = columnCount++;
					}
					otherSeries.columnIndex = columnIndex;
				}
			});
		}

		var categoryWidth = mathMin(
				mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
				xAxis.len // #1535
			),
			groupPadding = categoryWidth * options.groupPadding,
			groupWidth = categoryWidth - 2 * groupPadding,
			pointOffsetWidth = groupWidth / columnCount,
			optionPointWidth = options.pointWidth,
			pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
				pointOffsetWidth * options.pointPadding,
			pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
			colIndex = (reversedXAxis ?
				columnCount - (series.columnIndex || 0) : // #1251
				series.columnIndex) || 0,
			pointXOffset = pointPadding + (groupPadding + colIndex *
				pointOffsetWidth - (categoryWidth / 2)) *
				(reversedXAxis ? -1 : 1);

		// Save it for reading in linked series (Error bars particularly)
		return (series.columnMetrics = {
			width: pointWidth,
			offset: pointXOffset
		});

	},

	/**
	 * Translate each point to the plot area coordinate system and find shape positions
	 */
	translate: function () {
		var series = this,
			chart = series.chart,
			options = series.options,
			borderWidth = options.borderWidth,
			yAxis = series.yAxis,
			threshold = options.threshold,
			translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
			minPointLength = pick(options.minPointLength, 5),
			metrics = series.getColumnMetrics(),
			pointWidth = metrics.width,
			seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width
			pointXOffset = series.pointXOffset = metrics.offset,
			xCrisp = -(borderWidth % 2 ? 0.5 : 0),
			yCrisp = borderWidth % 2 ? 0.5 : 1;

		if (chart.renderer.isVML && chart.inverted) {
			yCrisp += 1;
		}

		Series.prototype.translate.apply(series);

		// record the new values
		each(series.points, function (point) {
			var yBottom = pick(point.yBottom, translatedThreshold),
				plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
				barX = point.plotX + pointXOffset,
				barW = seriesBarW,
				barY = mathMin(plotY, yBottom),
				right,
				bottom,
				fromTop,
				fromLeft,
				barH = mathMax(plotY, yBottom) - barY;

			// Handle options.minPointLength
			if (mathAbs(barH) < minPointLength) {
				if (minPointLength) {
					barH = minPointLength;
					barY =
						mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
							yBottom - minPointLength : // keep position
							translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
				}
			}

			// Cache for access in polar
			point.barX = barX;
			point.pointWidth = pointWidth;

			// Round off to obtain crisp edges
			fromLeft = mathAbs(barX) < 0.5;
			right = mathRound(barX + barW) + xCrisp;
			barX = mathRound(barX) +


  }

  @Test
  fun `should work with identical elements`() {
    val peerHeads = listOf(500UL, 500UL, 500UL, 500UL)
    val result = selector.selectBestSyncTarget(peerHeads)
    assertEquals(500UL, result)
  }

  @Test
  fun `should handle mixed frequency scenario`() {
    val peerHeads =
      listOf(
        100UL, // appears 1 time
        200UL,
        200UL, // appears 2 times
        300UL,
        300UL,
        300UL, // appears 3 times (most frequent)
        400UL,
        400UL, // appears 2 times
      )
    val result = selector.selectBestSyncTarget(peerHeads)
    assertEquals(300UL, result)
  }
}
/*
 * Copyright Consensys Software Inc.
 *
 * This file is dual-licensed under either the MIT license or Apache License 2.0.
 * See the LICENSE-MIT and LICENSE-APACHE files in the repository root for details.
 *
 * SPDX-License-Identifier: MIT OR Apache-2.0
 */
package maru.syncing.beaconchain.pipeline

import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeoutException
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import maru.core.SealedBeaconBlock
import maru.core.ext.DataGenerators.randomSealedBeaconBlock
import maru.core.ext.DataGenerators.randomStatus
import maru.p2p.MaruPeer
import maru.p2p.PeerLookup
import maru.p2p.messages.BeaconBlocksByRangeResponse
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.catchThrowable
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.kotlin.any
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import tech.pegasys.teku.infrastructure.async.SafeFuture
import tech.pegasys.teku.infrastructure.async.SafeFuture.completedFuture
import tech.pegasys.teku.networking.p2p.peer.NodeId
import tech.pegasys.teku.networking.p2p.reputation.ReputationAdjustment

class DownloadBlocksTest {
  private val defaultEndBlock = 11UL
  private val defaultBackoffDelay = 15.milliseconds

  private val defaultConfig =
    DownloadBlocksStep.Config(
      maxRetries = 5u,
      blockRangeRequestTimeout = 5.seconds,
      backoffDelay = defaultBackoffDelay,
    )

  @Test
  fun `downloads blocks successfully from peer`() {
    val peer = mock<MaruPeer>()
    val peerLookup = mock<PeerLookup>()
    val blocks = listOf(randomSealedBeaconBlock(10u), randomSealedBeaconBlock(defaultEndBlock))
    whenever(peer.sendBeaconBlocksByRange(10uL, 2uL)).thenReturn(completedFuture(BeaconBlocksByRangeResponse(blocks)))
    whenever(peerLookup.getPeers()).thenReturn(listOf(peer))
    whenever(peer.getStatus()).thenReturn(randomStatus(defaultEndBlock))

    val task =
      DownloadBlocksStep(
        downloadPeerProvider = DownloadPeerProviderImpl(peerLookup, false),
        config = defaultConfig,
      )
    val range = SyncTargetRange(10uL, defaultEndBlock)
    val result = task.apply(range).get()

    assertThat(result.size).isEqualTo(2)
    assertThat(result.stream().map({ it.sealedBeaconBlock }).toList()).containsAll(blocks)
  }

  @Test
  fun `downloads blocks in multiple requests when peer returns partial results`() {
    val endBlock = 12UL
    val peer = mock<MaruPeer>()
    val pee


)
      // order by activated tier, then count, then in alphabetical order
      .sort((a, b) => {
        if (a.tier !== b.tier) {
          return b.tier - a.tier;
        }
        if (b.count !== a.count) {
          return b.count - a.count;
        }
        return b.category > a.category ? -1 : 1;
      });

    // hide all synergy markers
    Object.values(this.synergyMarkers).forEach(marker => {
      marker.setVisible(false).setActive(false);
    });

    if (!this.visible) {
      // if this is hidden, don't bother rendering synergies.
      return;
    }

    // then show and reposition the active ones
    this.synergies.slice(0, 12).forEach((synergy, index) => {
      if (!this.synergyMarkers[synergy.category]) {
        // if we haven't created the marker yet, create it now
        this.synergyMarkers[synergy.category] = this.scene.add.existing(
          new SynergyMarker(this.scene, 0, 0, synergy.category, synergy.count)
        );
      }
      this.synergyMarkers[synergy.category]
        ?.setActive(true)
        .setVisible(true)
        .setPosition(40, 150 + index * SynergyMarker.height)
        .setCount(synergy.count);
    });
  }

  canAddPokemonToMainboard() {
    return flatten(this.mainboard).filter(v => !!v).length < this.level;
  }

  canAddPokemonToSideboard() {
    return this.sideboard.includes(undefined);
  }

  takeEnemyTurn() {
    console.log(`${this.playerName}'s turn: ${this.aiStrategy.name}`);

    this.currentShop = this.pool.reroll(this, this.currentShop);

    this.decideEnemyBuys();
    while (this.aiStrategy.decideReroll(this)) {
      this.currentShop = this.pool.reroll(this, this.currentShop);
      this.gold -= 2;
      this.decideEnemyBuys();
    }
  }

  decideEnemyBuys() {
    this.aiStrategy.decideBuys(this).forEach(pokemon => {
      if (this.buyPokemon(pokemon)) {
        delete this.currentShop[this.currentShop.indexOf(pokemon)];
      }
    });

    // after each shop, reorder the board so we can decide what to sell
    const boardOrder = this.aiStrategy.prioritiseBoard(this);
    // we position them by "removing" all the Pokemon from the board first,
    // then manually putting them in the right places using `setPokemonAtLocation`
    for (let x = 0; x < BOARD_WIDTH; x++) {
      for (let y = 0; y < BOARD_WIDTH; y++) {
        this.mainboard[x][y] = undefined;
      }
    }
    for (let i = 0; i < this.sideboard.length; i++) {
      this.sideboard[i] = undefined;
    }

    // the index of the first free space in a given row
    const spaceInRow = [0, 0, 0, 0, 0, 0];
    boardOrder.forEach((selectedPokemon, index) => {
      if (index < this.level) {
        // if index < level, we have room on the board

        // pick a spot for them based on their range.
        // ranged units go in back row, melee in front
        const y =
          selectedPokemon.basePokemon.basicAttack.range


import asyncio
import logging
import sys
from pathlib import Path

from examples.flow_builder.text_extraction.tools.text_extraction_flow import build_docproc_flow

logger = logging.getLogger(__name__)

flow_run = None

doc_ref= None
def on_flow_end(result):
    """
    Callback function to be called when the flow is completed.
    """
    print(f"Custom Handler: flow `{flow_run.name}` completed with result: {result}")

def on_flow_error(error):
    """
    Callback function to be called when the flow fails.
    """
    print(f"Custom Handler: flow `{flow_run.name}` failed: {error}")

async def main():

    '''A function demonstrating how to build a flow and save it to a file.'''
    my_flow_definition = await build_docproc_flow().compile_deploy()
    generated_folder = f"{Path(__file__).resolve().parent}/generated"
    my_flow_definition.dump_spec(f"{generated_folder}/docproc_flow.json")
    global flow_run
    flow_run = await my_flow_definition.invoke({"document_ref": doc_ref}, on_flow_end_handler=on_flow_end, on_flow_error_handler=on_flow_error, debug=True)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Missing required input. Please follow README to test the flow")
        exit(1)
    doc_ref = sys.argv[1]
    asyncio.run(main())


import torch
import os
import random
import glob
from torch.utils.data import Dataset
import numpy as np

class StateMeasurementResultData(Dataset):

    def __init__(self,num_observables=242,num_states=50):
        observables = []
        for i in range(0,num_observables):
            tmp = np.load('/home/haoyu/5qubit/float_observable5_'+str(i)+'.npy')
            observables.append(np.array(tmp))
        self.observables = np.array(observables)
        values = []
        for k in range(0,9):
            base_path = '/home/haoyu/Data6/qubits=5/layers=30/t_gate=' + str(k)
            file_pattern = base_path + '/circuit_seed=*/measuredQubits=01234/*.npy'
            file_paths = glob.glob(file_pattern)
            for file_path in file_paths:
                tmp = np.load(file_path)
                tmp = tmp.reshape(-1, 2**5)
                values.append(np.array(tmp, dtype=np.float32))
        self.expectation_values = np.array(values)
    def __getitem__(self, idx):
        assert idx < len(self.expectation_values)
        return self.observables, self.expectation_values[idx]

    def __len__(self):
        return len(self.expectation_values)
class TestStateMeasurementResultData(Dataset):
    def __init__(self,num_observables=27,num_states=10):
        observables = []
        for i in range(0,num_observables):
            tmp = np.load('/home/haoyu/5qubit/float_observable5_'+str(i)+'.npy')
            observables.append(np.array(tmp))
        self.observables = np.array(observables)

        ratio_space = np.linspace(-2,2,41)
        values = []
        for k in range(0,0):
            base_path = '/home/haoyu/Data6/qubits=5/layers=30/t_gate=' + str(k)
            file_pattern = base_path + '/circuit_seed=*/measuredQubits=01234/*.npy'
            file_paths = glob.glob(file_pattern)
            for file_path in file_paths:
                tmp = np.load(file_path)
                tmp = tmp.reshape(-1, 2**5)
                values.append(np.array(tmp, dtype=np.float32))
        self.expectation_values = np.array(values)

    def __getitem__(self, idx):
        assert idx < len(self.expectation_values)
        return self.observables, self.expectation_values[idx]

    def __len__(self):
        return len(self.expectation_values)


# -*- coding: utf-8 -*-
# Copyright (C) 2024 BIRU
#
# This file is part of Tenzu.
#
# Tenzu is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# You can contact BIRU at ask@biru.sh

import pytest

from base.utils import emails

@pytest.mark.parametrize(
    "first_email, second_email, expected",
    [
        # True
        ("test@email.com", "test@email.com", True),
        ("TEST@EMAIL.COM", "test@email.com", True),
        ("test@email.com", "TEST@EMAIL.COM", True),
        ("test@email.com", "teST@EMail.com", True),
        ("test@emaIL.COm", "test@email.com", True),
        ("te+st@email.com", "te+st@email.com", True),
        ("test@subdomain.email.com", "test@subdomain.email.com", True),
        # False
        ("test1@email.com", "test@email.com", False),
        ("test@email.com", "other@email.com", False),
        ("test@email.com", "test@bemail.es", False),
        ("test@email.com", "tes.t@email.com", False),
        ("tes+t@email.com", "test@email.com", False),
    ],
)
async def test_emails_are_the_same(first_email, second_email, expected):
    assert emails.are_the_same(first_email, second_email) == expected

@pytest.mark.parametrize(
    "value, expected",
    [
        # True
        ("test@email.com", True),
        ("test+something@email.com", True),
        ("test.123@email.com", True),
        ("test@emaIL.comm", True),
        ("test@subdomain.email.com", True),
        # False
        ("test1@com", False),
        ("test@", False),
        ("test", False),
        ("test@.com", False),
        ("test@email.", False),
        ("@email.", False),
    ],
)
async def test_is_email(value, expected):
    assert emails.is_email(value) == expected


[f>>2]}function qQe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&yt(s)}function L5(s){s=s|0,WQe(s)}function jQe(s){s=s|0,GQe(s+24|0)}function GQe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),yt(c))}function WQe(s){s=s|0;var l=0;l=zr()|0,Jr(s,1,15,l,XG()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function YQe(s){return s=s|0,VQe(n[(KQe(s)|0)>>2]|0)|0}function KQe(s){return s=s|0,(n[(OR()|0)+24>>2]|0)+(s<<3)|0}function VQe(s){return s=s|0,FD(KD[s&7]()|0)|0}function zQe(){var s=0;return o[7832]|0||(nFe(10052),pr(25,10052,U|0)|0,s=7832,n[s>>2]=1,n[s+4>>2]=0),10052}function JQe(s,l){s=s|0,l=l|0,n[s>>2]=XQe()|0,n[s+4>>2]=ZQe()|0,n[s+12>>2]=l,n[s+8>>2]=$Qe()|0,n[s+32>>2]=2}function XQe(){return 11709}function ZQe(){return 1188}function $Qe(){return TD()|0}function eFe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Qp(f,896)|0)==512?c|0&&(tFe(c),yt(c)):l|0&&(Hd(l),yt(l))}function Qp(s,l){return s=s|0,l=l|0,l&s|0}function tFe(s){s=s|0,s=n[s+4>>2]|0,s|0&&Rp(s)}function TD(){var s=0;return o[7824]|0||(n[2511]=rFe()|0,n[2512]=0,s=7824,n[s>>2]=1,n[s+4>>2]=0),10044}function rFe(){return 0}function nFe(s){s=s|0,Sp(s)}function iFe(s){s=s|0;var l=0,c=0,f=0,d=0,m=0;l=C,C=C+32|0,c=l+24|0,m=l+16|0,d=l+8|0,f=l,sFe(s,4827),oFe(s,4834,3)|0,aFe(


     */
    next(): Type;
    /**
     * @function get prev element in iterable
     * @throws EmptyCollectionException if there are no elements in iterable
     * @throws OutOfBoundsException if there is no prev element available
     * @returns {Type} prev element in the iterable
     */
    prev(): Type;
    /**
     * @function reset the iterable to first position
     */
    reset(): void;
    /**
     * @function move to end of collection
     */
    end(): void;
    /**
     * @function move to beginning of collection
     */
    start(): void;
    private _assertNotEmpty;
}
export default Iterator;
import { expect } from 'chai';
import { Visibility } from '../../../src/enums';
import { RootPathItem } from '../../../src/PathTree/RootPathItem';
import { treeToString } from '../../../src/plugins/tree/utilities';
import { SpreadPathItem } from '../../../src/PathTree/SpreadPathItem';
import { StaticPathItem } from '../../../src/PathTree/StaticPathItem';
import { SwitchPathItem } from '../../../src/PathTree/SwitchPathItem';
import { DynamicPathItem } from '../../../src/PathTree/DynamicPathItem';

describe('treeToString', () => {
  it('treeToString for single RootPathItem', () => {
    const rootPathItem = new RootPathItem();

    const output = treeToString(rootPathItem);
    expect(output).contain('/')
    expect(output).not.contain('│');
    expect(output).not.contain('─');
    expect(output).not.contain('├');
    expect(output).not.contain('└');

    const linesNumbers = output.split('\n').length - 1;
    expect(linesNumbers).equal(1);
  });

  it('treeToString for single StaticPathItem', () => {
    const staticPathItem = new StaticPathItem('static1', null);

    const output = treeToString(staticPathItem);
    expect(output).contain('static1');
    expect(output).not.contain('│');
    expect(output).not.contain('─');
    expect(output).not.contain('├');
    expect(output).not.contain('└');

    const linesNumbers = output.split('\n').length - 1;
    expect(linesNumbers).equal(1);
  });

  it('treeToString for single DynamicPathItem', () => {
    const dynamicPathItem = new DynamicPathItem('dynamic1', null);

    const output = treeToString(dynamicPathItem);
    expect(output).contain(':dynamic1');
    expect(output).not.contain('│');
    expect(output).not.contain('─');
    expect(output).not.contain('├');
    expect(output).not.contain('└');

    const linesNumbers = output.split('\n').length - 1;
    expect(linesNumbers).equal(1);
  });

  it('treeToString for single SpreadPathItem', () => {
    const dynamicPathItem = new SpreadPathItem('spread1', null);

    const output = treeToString(dynamicPathItem);
    expect(output).contain('...spread1');
    expect(output).not.contain('│');
    expect(output).not.contain('─');
    expect(output).not.contain('├');
    expect(output).not.contain('└');

    const linesNumbers = output.split('\n').length - 1;
    expect(linesNumbers).equal(1);
  });

  it('treeToString for single SwitchPathItem', () => {
    const switchPathItem = new SwitchPathItem(`[a][b=1][cc][dd=2][e="3 4"][f='5 6']`, null);

    const output = treeToString(switchPathItem);
    expect(output).contain(`[a][b=1][cc][dd=2][e='3 4'][f='5 6']`);
    expect(output).not.contain('│');
    expect(output).not.contain('─');
    expect(output).not.contain('├');
    expect(output).not.contain('└');

    const linesNumbers = output


� 사항은 부록 B.1에서 논의된다.\n' +
      '\n' +
      '### Experiment Details\n' +
      '\n' +
      '**Benchmark.** 우리 연구에서 우리는 처음에 사전 처리된 **APPS+** 데이터 세트에 대한 방법과 기준을 평가했다. 또한 코드 생성에서 널리 사용되는 벤치마크, 즉 **MBPP**(대부분 기본 프로그래밍 문제) [2] 및 **HumanEval**[3]에 대해서도 이러한 방법을 평가한다. 우리는 이전 접근법[14; 33]과 동일한 제로샷 학습 설정에서 MBPP와 HumanEval 벤치마크를 평가한다. 이 설정에서 우리는 APPS+ 데이터셋에서만 모델을 미세 조정하고 MBPP와 HumanEval에서 코드 생성 성능을 평가한다. 벤치마크에 대한 자세한 설명은 부록 B.1에서 확인할 수 있다.\n' +
      '\n' +
      '**Baselines.** Step-Coder의 효과를 검증하고 APPS+ 데이터셋에서 LLMs의 성능을 평가하기 위해 StarCoder[15], WizardCoder[23], DeepSeek-Coder[8], CodeLlama(Base, Python, Instruct)[27]의 세 가지 버전을 포함하여 광범위한 베이스라인을 고려한다. 또한, 우리는 또한 바닐라 PPO와 PPOCoder[33] 및 RLTF[20]를 포함한 두 가지 최첨단 RL 기반 접근법을 고려한다. 공정한 비교를 보장하기 위해 APPS+ 데이터 세트에서 동일한 백본(즉, DeepSeek-Coder-Instruct[8])을 사용하여 이러한 방법을 적용하는 실험을 수행했다. 우리의 방법의 필요성과 효과를 입증하는 것 외에도, 우리는 훈련 데이터의 효과를 배제하기 위해 APPS+ 데이터 세트에 대해 미세 조정 DeepSeek-Coder-Instruct [8]을 감독했다. 이러한 기준선에 대한 자세한 설명은


ntity);

//     }
// }
//}

fn action_system(
    keyboard_input: Res<Input<KeyCode>>,
    mut state: ResMut<State<EditorState>>,
) {
    if keyboard_input.just_pressed(KeyCode::F12) {
        match state.current() {
            EditorState::Playing => state.pop().unwrap(),
            EditorState::Disabled => state.push(EditorState::Playing).unwrap(),
        };
    }
}

#[allow(dead_code)]
pub fn run_if_editor(state: Res<State<EditorState>>) -> ShouldRun {
    match state.current() {
        EditorState::Playing => ShouldRun::Yes,
        EditorState::Disabled => ShouldRun::No,
    }
}
use crate::{Rng, Uncertain};

pub struct Not<U>
where
    U: Uncertain,
    U::Value: Into<bool>,
{
    uncertain: U,
}

impl<U> Not<U>
where
    U: Uncertain,
    U::Value: Into<bool>,
{
    pub fn new(uncertain: U) -> Self {
        Self { uncertain }
    }
}

impl<U> Uncertain for Not<U>
where
    U: Uncertain,
    U::Value: Into<bool>,
{
    type Value = bool;

    fn sample(&self, rng: &mut Rng, epoch: usize) -> Self::Value {
        !self.uncertain.sample(rng, epoch).into()
    }
}

macro_rules! logic_op {
    ($name: ident, $op: tt) => {
        pub struct $name<A, B>
        where
            A: Uncertain,
            B: Uncertain,
            A::Value: Into<bool>,
            B::Value: Into<bool>,
        {
            a: A,
            b: B,
        }

        impl<A, B> $name<A, B>
        where
            A: Uncertain,
            B: Uncertain,
            A::Value: Into<bool>,
            B::Value: Into<bool>,
        {
            pub fn new(a: A, b: B) -> Self {
                Self { a, b }
            }
        }

        impl<A, B> Uncertain for $name<A, B>
        where
            A: Uncertain,
            B: Uncertain,
            A::Value: Into<bool>,
            B::Value: Into<bool>,
        {
            type Value = bool;

            fn sample(&self, rng: &mut Rng, epoch: usize) -> Self::Value {
                self.a.sample(rng, epoch).into() $op self.b.sample(rng, epoch).into()
            }
        }
    };
}

macro_rules! binary_op {
    ($name:ident, $op:tt, $trait:tt) => {
        pub struct $name<A, B>
        where
            A: Uncertain,
            B: Uncertain,
            A::Value: std::ops::$trait<B::Value>,
        {
            a: A,
            b: B,
        }

        impl<A, B> $name<A, B>
        where
            A: Uncertain,
            B: Uncertain,
            A::Value: std::ops::$trait<B::Value>,
        {
            pub fn new(a: A, b: B) -> Self {
                Self { a, b }
            }
        }

        impl<A, B> Uncertain for $name<A, B>
        where
            A: Uncertain,
            B: Uncertain,
            A::Value: std::ops::$trait<B::Value>,
        {
            type Value = <A::Value as std::ops::$trait<B::Value>>::Output;

            fn sample(&self, rng: &mut Rng, epoch: usize) -> Self::Value {
                self.a.sample(rng, epoch) $op self.b.sample(rng, epoch)
            }
        }
    };
}

logic_op!(And, &&);
logic_op!(Or, ||);


function bufferWithTimeOrCount<V>(src: EventStream<V>, delay?: number | DelayFunction, count?: number): EventStream<V[]>;
declare class Buffer<V> {
    constructor(onFlush: BufferHandler<V>, onInput: BufferHandler<V>);
    delay?: DelayFunction;
    onInput: BufferHandler<V>;
    onFlush: BufferHandler<V>;
    push: EventSink<V[]>;
    scheduled: number | null;
    end: End | undefined;
    values: V[];
    flush(): any;
    schedule(delay: DelayFunction): any;
}
declare type BufferHandler<V> = (buffer: Buffer<V>) => any;
/** @hidden */
export declare function buffer<V>(src: EventStream<V>, onInput?: BufferHandler<V>, onFlush?: BufferHandler<V>): EventStream<V[]>;
export {};

import Field from "./Logic/field";
import DrawField from "./UI/drawField";

class Game
{
    score : number;
    speed : number;
    field : Field;
    drawer:DrawField;
    playerPos:number;
    crash=false;
    constructor() {
        this.score=0;
        this.playerPos=1;
        this.field=new Field(this.playerPos);
        this.drawer=new DrawField(this.field.getRepresentative(this.playerPos));
        this.speed=1000;
        document.addEventListener('keydown', (event) => {
            if(event.key=="ArrowLeft"||event.key=="a"||event.key=="A")this.playerPos=0;
            else if(event.key=="ArrowRight"||event.key=="d"||event.key=="D")this.playerPos=1;
            else if(event.key==" "){this.field=new Field(this.playerPos);
            this.crash=true;
            this.speed=1000;
                this.score=0;
                this.playerPos=1;
                this.drawer.update(this.field.getRepresentative(this.playerPos),this.score,Math.floor(this.speed/1000));
                 this.game();
            }
        });
    }

     async game(){

        let crash=false;
        let field=this.field;
         await this.delay( 500);
        while((!crash)&&(field==this.field)) {

         await this.delay(1000 / (this.speed/1000));
         this.speed+=23;
         let res=field.gonext(this.playerPos)
            crash=res[1];
         this.score++;
         await this.drawer.update(res[0],this.score,Math.floor(this.speed/1000));
     }
     if(crash)
     for(let i=0;i<4;i++){
         await this.delay(1000 / (this.speed/1000));
         await this.drawer.update(field.goCrash(i),this.score,Math.floor(this.speed/1000));
     }
     }

     delay(delay: number) {
    return new Promise(r => {
        setTimeout(r, delay);
    })
}
}

new Game();

import { Container, Graphics, Rectangle } from "pixi.js";
import { ScrollBarContents } from "../src/scrollBar/ScrollBarContents";

export class ScrollBarContentsGenerator {
  /**
   * スクロールバーのコンテンツおよびコンテンツマスクを生成する
   * @param contentsW
   * @param scrollBarH
   * @param contentsScale
   */
  public static generate(
    contentsW: number,
    scrollBarH: number,
    contentsScale: number
  ): ScrollBarContents {
    const container = new Container();
    const targetContents = this.getScrollBarContents(
      0xff00ff,
      contentsW,
      scrollBarH * contentsScale
    );
    const contentsMask = this.getScrollBarContents(
      0x0000ff,
      contentsW,
      scrollBarH
    );
    return new ScrollBarContents(targetContents, contentsMask, container);
  }


q(value1, value2)

            Operator.AND -> and(value1, value2)
            Operator.OR -> or(value1, value2)

            else -> throw OperationIsNotSupportedException(operation, value1.type(), value2.type())
        }

    // Если у классов реализованы операторы, то вернуть результат. Иначе null
    private fun overridedOperation(value1: LzrValue, value2: LzrValue): LzrValue? {
        if (value1.type() == Types.CLASS) {
            value1 as ClassInstanceValue
            if (value1.has("$operation")) {
                return value1.callMethod("$operation", value2)
            }
        }
        if (value2.type() == Types.CLASS) {
            value2 as ClassInstanceValue
            if (value2.has("r$operation")) {
                return value2.callMethod("r$operation", value1)
            }
        }

        return null
    }

    private fun equals(value1: LzrValue, value2: LzrValue): LzrValue =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean(value1 == value2)

    private fun notEquals(value1: LzrValue, value2: LzrValue) =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean(value1 != value2)

    private fun lt(value1: LzrValue, value2: LzrValue) =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean(value1 < value2)

    private fun lteq(value1: LzrValue, value2: LzrValue) =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean(value1 <= value2)

    private fun gt(value1: LzrValue, value2: LzrValue) =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean(value1 > value2)

    private fun gteq(value1: LzrValue, value2: LzrValue) =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean(value1 >= value2)

    private fun and(value1: LzrValue, value2: LzrValue) =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean((value1.asInt() != 0) && (value1.asInt() != 0))

    private fun or(value1: LzrValue, value2: LzrValue) =
        overridedOperation(value1, value2)
            ?: LzrNumber.fromBoolean((value1.asInt() != 0) || (value2.asInt() != 0))

    private fun nullCoalesce(): LzrValue =
        try {
            expr1.eval()
        } catch (npe: NullPointerException) {
            expr2.eval()
        }

    // end

    override fun accept(visitor: Visitor) =
        visitor.visit(this)

    override fun <R, T> accept(visitor: ResultVisitor<R, T>, t: T): R =
        visitor.visit(this, t)

    override fun toString(): String =
        String.format("%s %s %s", expr1, operation.text, expr2)

    enum class Operator(val text: String) {
        EQUALS("=="),
        NOT_EQUALS("!="),

        LT("<"),
        LTEQ("<="),
        GT(">"),
        GTEQ(">="),

        AND("&&"),
        OR("||"),

        NULL_COALESCE("??");

        override fun toString(): String =
            this.text
    }
}package com.kingmang.lazurite.parser.ast.statements

import com.kingmang.lazurite.exceptions.LzrException
import com.kingmang.lazurite.libraries.Library
import com.kingmang.lazurite.parser.IParser
import com.kingmang.lazurite.parser.ast.InterruptableNode
import com.kingmang.lazurite.parser.ast.expressions.Expression
import com.kingmang.lazurite.parser.impl.LexerImplementation
import com.kingmang.lazurite.parser.impl.ParserImplementation
import com.kingmang.lazurite.patterns.visitor.FunctionAdder
import com.kingmang.la


[] {
  const hours: string[] = [
    '06',
    '07',
    '08',
    '09',
    '10',
    '11',
    '12',
    '13',
    '14',
    '15',
    '16',
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
  ];
  const minutes = ['00', '15', '30', '45'];
  const result: string[] = [];

  for (const hour of hours) {
    for (const minute of minutes) {
      result.push(`${hour}:${minute}`);
    }
  }

  result.push('23:00');
  return result;
}

function getTime(date: Date): string {
  return `${String(date.getHours()).padStart(2, '0')}:${String(
    date.getMinutes()
  ).padStart(2, '0')}`;
}

function createCheckinsCache(
  group: Map<string, ParsedItem[]>
): Record<string, number> {
  const result: Record<string, number> = {};

  for (const [label, items] of group.entries()) {
    for (const item of items) {
      result[`${label} ${getTime(item.timestamp)}`] = item.checkins;
    }
  }

  return result;
}
import * as md5 from 'md5';

import BaseModel from './BaseModel';

// Системные сервисы
import MainRequest from '../../System/MainRequest';

// Классы репозиториев
import UserR from '../../Infrastructure/Repository/UserR';

/**
 * Бизнес модель пользователя
 */
export default class UserM extends BaseModel {

    /* репозиторий пользователя */
    public userR: UserR;

    constructor(req: MainRequest) {
        super(req);
        this.userR = new UserR(req);
    }

    /* выдает ключ по логину паролю */
    public async getUserTokenByLoginAndPass(body: {
        login: string;
        pass: string;
    }): Promise<string> {

        let token;
        let ok = true;

        // Декларирование ошибок
        this.errorSys.declare([
            'login', /* если нет логина */
            'pass', /* если нет пароля */
            'reg', /* если нету такого юзера  */
        ]);

        try {

            if (!body) {
                this.errorSys.error('login', 'Не заполнено поле логин');
                this.errorSys.error('pass', 'Не заполнено поле пароль');
                throw "erro body";
            }

            /* если нету телефона */
            if (!body.login) {
                this.errorSys.error('login', 'Не заполнено поле логин');
                ok = false;
            }
            /* если нету sms */
            if (!body.pass) {
                this.errorSys.error('pass', 'Не заполнено поле пароль');
                ok = false;
            }

            if (ok) {
                /* пытаемся получить token */
                token = await this.userR.getUserTokenByLoginAndPass(body.login, md5(body.pass));
                console.log(token);
            }

            /* если нету такого юзера  */
            if (!token) {
                this.errorSys.error('reg', 'Такой пользователь отсутствует');
                ok = false;
            }

            if (!ok) {
                throw "erro body";
            }

        } catch (e) {
            /* что-то не так */
             console.log(e) ;

        }

        return t


le(scale),
        tint = colorScheme.primary
    )
}fun main() {

    /*
    * Reto #46 27/11/2023  LA CARRERA DE COCHES
    *
    * Crea un programa que simule la competición de dos coches en una pista.
    * - Los dos coches estarán representados por 🚙 y 🚗. Y la meta por 🏁.
    * - Cada pista tendrá entre 1 y 3 árboles 🌲 colocados de forma aleatoria.
    * - Las dos pistas tendrán una longitud configurable de guiones bajos "_".
    * - Los coches comenzarán en la parte derecha de las pistas. Ejemplo:
    *   🏁____🌲_____🚙
    *   🏁_🌲____🌲___🚗
    *
    * El juego se desarrolla por turnos de forma automática, y cada segundo
    * se realiza una acción sobre los coches (moviéndose a la vez), hasta que
    * uno de ellos (o los dos a la vez) llega a la meta.
    * - Acciones:
    *   - Avanzar entre 1 a 3 posiciones hacia la meta.
    *   - Si al avanzar, el coche finaliza en la posición de un árbol,
    *     se muestra 💥 y no avanza durante un turno.
    *   - Cada turno se imprimen las pistas y sus elementos.
    *   - Cuando la carrera finalice, se muestra el coche ganador o el empate.
    *
    */

    CarreraDeCoches(30)

}

class CarreraDeCoches(longitud: Int = 10) {

    private val circuito1 : Carretera
    private val circuito2 : Carretera

    init {
        circuito1 = Carretera(longitud = longitud, "🚙" )
        circuito2 = Carretera(longitud = longitud, "🚗" )
        loopGame()

        println("------------------")
        if (circuito1.enMeta && circuito2.enMeta){
            println("¡¡¡ EMPATE !!!")
        } else if (circuito1.enMeta){
            println("¡¡¡ GANADOR 🚙 !!!")
        } else if (circuito2.enMeta){
            println("¡¡¡ GANADOR 🚗 !!!")
        }
        println("------------------")
    }

    private fun loopGame() {

        // Inicio carrera
        circuito1.pintar()
        circuito2.pintar()
        retardo()

        var finCarrera = false
        while ( !finCarrera ) {

            val posiciones = (1..3).random()
            circuito1.avanzar(posiciones)
            circuito2.avanzar(posiciones)
            circuito1.pintar()
            circuito2.pintar()
            retardo()
            if (circuito1.enMeta || circuito2.enMeta){
                finCarrera = true
            }

        }

    }

    private fun retardo(segundos:Long = 1){

        Thread.sleep(segundos *1000)
    }

}

class Carretera(val longitud: Int, cocheInicial: String){

    private val carretera: MutableList<String> = mutableListOf()
    private val meta = "🏁"
    private val arbol = "🌲"
    private val accidente = "💥"

    var enMeta = false

    init{
        carretera.add(meta)
        (1..longitud).forEach(){
            carretera.add("_")
        }

        // Ponemos los árboles
        var numArboles : Int = (1..3).random()
        while (numArboles>0) {
            val posicion = (1..longitud).random()
            if (carretera[posicion] != arbol) {
                carretera[posicion] = arbol
                numArboles--
            }

        }

        // Finalmente, ponemos el coche en la salida
        carretera.add(cocheInicial)

    }

    fun avanzar(movimiento:Int){

        var mov = movimiento
        var posicion = carretera.lastIndex //Posicion actual del coche

        while (mov>0){

            when (carretera[posicion-1]) {
                meta -> {
                    enMeta = true
                    mov = 0
                }

                arbol -> {
                    carretera[posicion-1] = accidente
                    mov = 0
                }

                else -> {
                    carretera[posicion-1] = carretera[posicion]
                    carretera.removeLast()

                    posicion--
                    mov--

                }

            }


:after {
  display: table;
  clear: both;
  content: "";
}

h1,
h2,
h3,
h4,
h5,
h6 {
  margin-top: 15px;
  margin-bottom: 15px;
  line-height: 1.1;
}

h1 {
  font-size: 30px;
}

h2 {
  font-size: 21px;
}

h3 {
  font-size: 16px;
}

h4 {
  font-size: 14px;
}

h5 {
  font-size: 12px;
}

h6 {
  font-size: 11px;
}

blockquote {
  margin: 0;
}

ul,
ol {
  padding: 0;
  margin-top: 0;
  margin-bottom: 0;
}

ol ol,
ul ol {
  list-style-type: lower-roman;
}

ul ul ol,
ul ol ol,
ol ul ol,
ol ol ol {
  list-style-type: lower-alpha;
}

dd {
  margin-left: 0;
}

code {
  font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
  font-size: 12px;
}

pre {
  margin-top: 0;
  margin-bottom: 0;
  font: 12px Consolas, "Liberation Mono", Menlo, Courier, monospace;
}

.select::-ms-expand {
  opacity: 0;
}

.octicon {
  font: normal normal normal 16px/1 octicons-anchor;
  display: inline-block;
  text-decoration: none;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.octicon-link:before {
  content: '\f05c';
}

.markdown-body:before {
  display: table;
  content: "";
}

.markdown-body:after {
  display: table;
  clear: both;
  content: "";
}

.markdown-body>*:first-child {
  margin-top: 0 !important;
}

.markdown-body>*:last-child {
  margin-bottom: 0 !important;
}

a:not([href]) {
  color: inherit;
  text-decoration: none;
}

.anchor {
  display: inline-block;
  padding-right: 2px;
  margin-left: -18px;
}

.anchor:focus {
  outline: none;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  margin-top: 1em;
  margin-bottom: 16px;
  font-weight: bold;
  line-height: 1.4;
}

h1 .octicon-link,
h2 .octicon-link,
h3 .octicon-link,
h4 .octicon-link,
h5 .octicon-link,
h6 .octicon-link {
  color: #000;
  vertical-align: middle;
  visibility: hidden;
}

h1:hover .anchor,
h2:hover .anchor,
h3:hover .anchor,
h4:hover .anchor,
h5:hover .anchor,
h6:hover .anchor {
  text-decoration: none;
}

h1:hover .anchor .octicon-link,
h2:hover .anchor .octicon-link,
h3:hover .anchor .octicon-link,
h4:hover .anchor .octicon-link,
h5:hover .anchor .octicon-link,
h6:hove


//
//  XHLaunchAdDownload.h
//  XHLaunchAdExample
//
//  Created by zhuxiaohui on 2016/6/26.
//  Copyright © 2016年 it7090.com. All rights reserved.
//  代码地址:https://github.com/CoderZhuXH/XHLaunchAd

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

typedef void(^XHLaunchAdDownloadProgressBlock)(unsigned long long total, unsigned long long current);

@protocol XHLaunchAdDownloadDelegate <NSObject>

- (void)downloadFinishWithURL:(nonnull NSURL *)url;

@end

@interface XHLaunchAdDownload : NSObject

@property (assign, nonatomic ,nonnull)id<XHLaunchAdDownloadDelegate> delegate;

@end

#pragma mark - XHLaunchAdImageDownload

typedef void(^XHLaunchAdDownloadImageCompletedBlock)(UIImage *_Nullable image, NSData * _Nullable data, NSError * _Nullable error);

@interface XHLaunchAdImageDownload : XHLaunchAdDownload

-(nonnull instancetype)initWithURL:(nonnull NSURL *)url delegateQueue:(nonnull NSOperationQueue *)queue progress:(nullable XHLaunchAdDownloadProgressBlock)progressBlock completed:(nullable XHLaunchAdDownloadImageCompletedBlock)completedBlock;

@end

#pragma mark - XHLaunchAdVideoDownload
typedef void(^XHLaunchAdDownloadVideoCompletedBlock)(NSURL * _Nullable location, NSError * _Nullable error);

@interface XHLaunchAdVideoDownload : XHLaunchAdDownload

-(nonnull instancetype)initWithURL:(nonnull NSURL *)url delegateQueue:(nonnull NSOperationQueue *)queue progress:(nullable XHLaunchAdDownloadProgressBlock)progressBlock completed:(nullable XHLaunchAdDownloadVideoCompletedBlock)completedBlock;

@end


, heartbeatInterval, heartbeatTimeout)
{
	override val channelId: UUID? get() = channel.id

	override fun scheduleNextHeartbeatAction(action: () -> Unit)
		: ScheduledFuture<*> =
			channel.adapter.millisTimer(heartbeatInterval, action)

	override fun sendHeartbeat ()
	{
		if (heartbeatCancelled) { return }
		val byteArray = ByteArray(10)
		Random().nextBytes(byteArray)
		WebSocketAdapter.sendPing(
			channel,
			byteArray,
			{
				startHeartbeatTimer()
			},
			{
				startHeartbeatTimer()
			})
	}

	override fun heartbeatFailureThresholdReached()
	{
		channel.adapter.sendClose(channel, HeartbeatFailureDisconnect)
	}
}

/**
 * A `NoHeartbeat` is a deactivated [Heartbeat]. This is used when no
 * `Heartbeat` is desired for the underlying transport mechanism.
 *
 * @author Richard Arriaga <rich@availlang.org>
 */
object NoHeartbeat: Heartbeat
{
	// Do nothing
	override fun sendHeartbeat() = Unit

	// Do nothing
	override fun receiveHeartbeat() = Unit

	// Do nothing
	override fun cancel() = Unit

	override val channelId: UUID? = null
}
/*
 * SocketChannel.kt
 * Copyright © 1993-2022, The Avail Foundation, LLC.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of the copyright holder nor the names of the contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package avail.server.io

import avail.server.messages.Message
import avail.utility.IO

import java.nio.channels.AsynchronousSocketChannel

/**
 * A `SocketChannel` encapsulates an [AsynchronousSocketChannel] created by a
 * `SocketAdapter`.
 *
 * @property adapter
 *   The [SocketAdapter] that created this [channel][SocketChannel].
 * @property transport
 *   The [channel][AsynchronousSocketChannel] used by the associated
 *   [SocketAdapter].
 * @author Todd L Smith <todd@availlang.org>
 *
 * @constructor
 *
 * Construct a new `SocketChannel`.
 *
 * @param adapter
 *   The [SocketAdapter].
 * @param transport
 *   The [channel][AsynchronousSocketChannel].
 * @param closeAction
 *   The custom action that is to be called when the this channel is closed in
 *   order to support implementation-specific requirements during the closing of
 *   a channel.
 */
internal class SocketChannel constructor(
	override val adapter: SocketAdapter,
	override val transport: AsynchronousSocketChannel,
	closeAction: (DisconnectReason, AvailServerChannel) -> Unit = {_,_->})
: AbstractTransportChannel<AsynchronousSocketChannel>(closeAction)
{
	override val isOpen get() = transport.isOpen
	override val maximumSendQueueDepth get() =


/* { dg-do compile } */
/* { dg-options "-mavx512vl -O2" } */
/* { dg-final { scan-assembler-times "vfmsub...pd\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)"  2 } } */
/* { dg-final { scan-assembler-times "vfmsub...pd\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)"  2 } } */
/* { dg-final { scan-assembler-times "vfmsub231pd\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */
/* { dg-final { scan-assembler-times "vfmsub231pd\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */
/* { dg-final { scan-assembler-times "vfmsub...pd\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\{%k\[1-7\]\}\{z\}(?:\n|\[ \\t\]+#)" 1 } } */
/* { dg-final { scan-assembler-times "vfmsub...pd\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\{%k\[1-7\]\}\{z\}(?:\n|\[ \\t\]+#)" 1 } } */

#include <immintrin.h>

volatile __m256d yy, y2, y3;
volatile __m128d xx, x2, x3;
volatile __mmask8 m;

void extern
avx512vl_test (void)
{
  yy = _mm256_mask_fmsub_pd (yy, m, y2, y3);
  xx = _mm_mask_fmsub_pd (xx, m, x2, x3);

  y3 = _mm256_mask3_fmsub_pd (yy, y2, y3, m);
  x3 = _mm_mask3_fmsub_pd (xx, x2, x3, m);

  yy = _mm256_maskz_fmsub_pd (m, yy, y2, y3);
  xx = _mm_maskz_fmsub_pd (m, xx, x2, x3);
}


 }}`},
				{"messages", `[INST] {{ if .System }}{{ .System }}

{{ end }}
{{- range .Messages }}
{{- if eq .Role "user" }}{{ .Content }}[/INST] {{ else if eq .Role "assistant" }}{{ .Content }}[INST] {{ end }}
{{- end }}`},
			},
			Values{
				Messages: []api.Message{
					{Role: "system", Content: "You are a helpful assistant!"},
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
					{Role: "user", Content: "What is your name?"},
				},
			},
			`[INST] You are a helpful assistant!

Hello friend![/INST] Hello human![INST] What is your name?[/INST] `,
		},
		{
			"mistral assistant",
			[]template{
				{"no response", `[INST] {{ .Prompt }}[/INST] `},
				{"response", `[INST] {{ .Prompt }}[/INST] {{ .Response }}`},
				{"messages", `
{{- range $i, $m := .Messages }}
{{- if eq .Role "user" }}[INST] {{ .Content }}[/INST] {{ else if eq .Role "assistant" }}{{ .Content }}{{ end }}
{{- end }}`},
			},
			Values{
				Messages: []api.Message{
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
					{Role: "user", Content: "What is your name?"},
					{Role: "assistant", Content: "My name is Ollama and I"},
				},
			},
			`[INST] Hello friend![/INST] Hello human![INST] What is your name?[/INST] My name is Ollama and I`,
		},
		{
			"chatml",
			[]template{
				// this does not have a "no response" test because it's impossible to render the same output
				{"response", `{{ if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{ end }}{{ if .Prompt }}<|im_start|>user
{{ .Prompt }}<|im_end|>
{{ end }}<|im_start|>assistant
{{ .Response }}<|im_end|>
`},
				{"messages", `
{{- range $index, $_ := .Messages }}<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{ end }}<|im_start|>assistant
`},
			},
			Values{
				Messages: []api.Message{
					{Role: "system", Content: "You are a helpful assistant!"},
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
					{Role: "user", Content: "What is your name?"},
				},
			},
			`<|im_start|>system
You are a helpful assistant!<|im_end|>
<|im_start|>user
Hello friend!<|im_end|>
<|im_start|>assistant
Hello human!<|im_end|>
<|im_start|>user
What is your name?<|im_end|>
<|im_start|>assistant
`,
		},
	}

	for _, tt := range cases {
		t.Run(tt.name, func(t *testing.T) {
			for _, ttt := range tt.templates {
				t.Run(ttt.name, func(t *testing.T) {
					tmpl, err := Parse(ttt.template)
					if err != nil {
						t.Fatal(err)
					}

					var b bytes.Buffer
					if err := tmpl.Execute(&b, tt.values); err != nil {
						t.Fatal(err)
					}

					if diff := cmp.Diff(b.String(), tt.expected); diff != "" {
						t.Errorf("mismatch (


+0DAF SINHALA DAYANNA */,
        Sinh_dhha = 0x1000db0 /* U+0DB0 SINHALA MAHA. DAYANNA */,
        Sinh_na = 0x1000db1 /* U+0DB1 SINHALA DANTAJA NAYANNA */,
        Sinh_ndha = 0x1000db3 /* U+0DB3 SINHALA SANYAKA DAYANNA */,
        Sinh_pa = 0x1000db4 /* U+0DB4 SINHALA PAYANNA */,
        Sinh_pha = 0x1000db5 /* U+0DB5 SINHALA MAHA. PAYANNA */,
        Sinh_ba = 0x1000db6 /* U+0DB6 SINHALA BAYANNA */,
        Sinh_bha = 0x1000db7 /* U+0DB7 SINHALA MAHA. BAYANNA */,
        Sinh_ma = 0x1000db8 /* U+0DB8 SINHALA MAYANNA */,
        Sinh_mba = 0x1000db9 /* U+0DB9 SINHALA AMBA BAYANNA */,
        Sinh_ya = 0x1000dba /* U+0DBA SINHALA YAYANNA */,
        Sinh_ra = 0x1000dbb /* U+0DBB SINHALA RAYANNA */,
        Sinh_la = 0x1000dbd /* U+0DBD SINHALA DANTAJA LAYANNA */,
        Sinh_va = 0x1000dc0 /* U+0DC0 SINHALA VAYANNA */,
        Sinh_sha = 0x1000dc1 /* U+0DC1 SINHALA TAALUJA SAYANNA */,
        Sinh_ssha = 0x1000dc2 /* U+0DC2 SINHALA MUURDHAJA SAYANNA */,
        Sinh_sa = 0x1000dc3 /* U+0DC3 SINHALA DANTAJA SAYANNA */,
        Sinh_ha = 0x1000dc4 /* U+0DC4 SINHALA HAYANNA */,
        Sinh_lla = 0x1000dc5 /* U+0DC5 SINHALA MUURDHAJA LAYANNA */,
        Sinh_fa = 0x1000dc6 /* U+0DC6 SINHALA FAYANNA */,
        Sinh_al


g(config.settingcommand, 'HUD Settings', 'keyboard', config.keybinds['hudsetting'])
	return
end)

RegisterNUICallback('setrefreshrate', function(data)
	if tonumber(data.val) then
		config.Rpm_sleep = data.val
	end
end)

RegisterNUICallback('setcarui', function(data)
	if config.carui ~= data.val or config.enable_carui_perclass then
		Hud.customcarui = true
		config.carui = data.val
	else
		Hud.customcarui = false
	end
end)

settingbool = false
RegisterNUICallback('hidecarlock', function(data, cb)
    SetNuiFocus(false,false)
	SendNUIMessage({
		type = "SettingHud",
		content = {config = config.userconfig, bool = false}
	})
	settingbool = false
	cb(true)
end)


mlSyntaxSummary" onclick="toggleMXMLOnly();">Show MXML Syntax
Hide MXML Syntax

The <s:View> tag inherits all of the tag
  attributes of its superclass and adds the following tag attributes:

  <s:View
   Properties
    actionBarVisible="true"
    actionContent="null"
    actionLayout="null"
    data="null"
    destructionPolicy="auto"
    navigationContent="null"
    navigationLayout="null"
    overlayControls="false"
    tabBarVisible="true"
    title=""
    titleContent="null"
    titleLayout="null"
    viewMenuItems="null"

   Events
    backKeyPressed="No default"
    dataChange="No default"
    menuKeyPressed="No default"
    removing="No default"
    viewActivate="No default"
    viewDeactivate="No default"

  >

Default MXML PropertymxmlContentFactory

View the examples

More examples

Use pushView() to change views
Pass data to a view
Return data from a view
Apply a transition
Use an easing class with a transition

Learn more

Use views and sections to lay out
a mobile application
Lay out a simple mobile application
Navigate the views of a mobile application
<a href="http://help.adobe.com/en_US/Flex/4.6/mobileapps/WSa122979b4619725672e48c412a3e152164-7fff.html"


IGN="top" ALIGN="left">

		<IMG


,1 --1/1 Speak to Forsaken Dreadmage for a teleport
    .skipgossip
    .target Forsaken Dreadmage
step
    .goto 2070,60.83,51.98,10,0
    .goto 2070,60.80,51.37
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Calia Menethil|r
    .turnin 65656 >>Turn in Call to Lordaeron
    .target Calia Menethil
    .accept 65657 >>Accept Assemble the Forsaken
step
    .goto 2070,61.97,50.51
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Dark Ranger Velonara|r
    .accept 65658 >>Accept This Land is Ours
    .complete 65657,1 --1/1 Speak to Dark Ranger Velonara
    .skipgossip
    .target Dark Ranger Velonara
step
    .goto 2070,63.47,49.21
    >>Kill |cRXP_ENEMY_Blighted Soldiers and Shadowmages|r
    .complete 65658,1 --8/8 Blighted Soldiers and Shadowmages slain
    .mob Blighted Soldiers
    .mob Blighted Shadowmages
step
    .goto 2070,63.23,55.52
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Master Apothecary Faranell|r
    .complete 65657,3 --1/1 Speak to Master Apothecary Faranell
    .skipgossip 185794,1
    .target Master Apothecary Faranell
step
    .goto 2070,57.57,49.20
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Lilian Voss|r
    .complete 65657,2 --1/1 Speak to Lilian Voss
    .target Lilian Voss
    .skipgossip 185793,1
step
    .goto 2070,60.84,51.96,10,0
    .goto 2070,60.80,51.56
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Dark Ranger Velonara|r
    .turnin 65658 >>Turn in This Land is Ours
    .target Dark Ranger Velonara
step
    .goto 2070,60.90,51.34
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Lilian Voss|r
    .turnin 65657 >>Turn in Assemble the Forsaken
    .target Lilian Voss
    .accept 65659 >>Accept The Blight Congress
step
    #completewith next
    .gossipoption 54673 >>Talk to |cRXP_FRIENDLY_Lilian Voss|r
    .timer 50,RP
    .target Lilian Voss
step
    .goto 2070,60.79,51.36
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Calia|r
    .complete 65659,3 --1/1 Speak to Calia
    .skipgossip 185512,1
    .target Calia
step
    .goto 2070,61.97,55.67
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Calia Menethil|r
    .turnin 65659 >>Turn in The Blight Congress
    .target Calia Menethil
    .accept 65660 >>Accept Walk of Faith
step
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Calia|r
    .co


FOW extends ffi.Opaque {}

final class PTOUCHPREDICTIONPARAMETERS extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Uint32()
  external int dwLatency;

  @ffi.Uint32()
  external int dwSampleTime;

  @ffi.Uint32()
  external int bUseHWTimeStamp;
}

abstract class PHANDEDNESS {
  static const int HANDEDNESS_LEFT = 0;
  static const int HANDEDNESS_RIGHT = 1;
}

final class LPNONCLIENTMETRICSA extends ffi.Opaque {}

final class LPNONCLIENTMETRICSW extends ffi.Opaque {}

final class LPMINIMIZEDMETRICS extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Int32()
  external int iWidth;

  @ffi.Int32()
  external int iHorzGap;

  @ffi.Int32()
  external int iVertGap;

  @ffi.Int32()
  external int iArrange;
}

final class LPICONMETRICSA extends ffi.Opaque {}

final class LPICONMETRICSW extends ffi.Opaque {}

final class LPANIMATIONINFO extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Int32()
  external int iMinAnimate;
}

final class LPSERIALKEYSA extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Uint64()
  external int dwFlags;

  external ffi.Pointer<ffi.Int8> lpszActivePort;

  external ffi.Pointer<ffi.Int8> lpszPort;

  @ffi.Uint32()
  external int iBaudRate;

  @ffi.Uint32()
  external int iPortState;

  @ffi.Uint32()
  external int iActive;
}

final class LPSERIALKEYSW extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Uint64()
  external int dwFlags;

  external ffi.Pointer<ffi.Uint16> lpszActivePort;

  external ffi.Pointer<ffi.Uint16> lpszPort;

  @ffi.Uint32()
  external int iBaudRate;

  @ffi.Uint32()
  external int iPortState;

  @ffi.Uint32()
  external int iActive;
}

final class LPHIGHCONTRASTA extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Uint64()
  external int dwFlags;

  external ffi.Pointer<ffi.Int8> lpszDefaultScheme;
}

final class LPHIGHCONTRASTW extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Uint64()
  external int dwFlags;

  external ffi.Pointer<ffi.Uint16> lpszDefaultScheme;
}

final class LPVIDEOPARAMETERS extends ffi.Opaque {}

final class LPFILTERKEYS extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Uint64()
  external int dwFlags;

  @ffi.Uint64()
  external int iWaitMSec;

  @ffi.Uint64()
  external int iDelayMSec;

  @ffi.Uint64()
  external int iRepeatMSec;

  @ffi.Uint64()
  external int iBounceMSec;
}

final class LPSTICKYKEYS extends ffi.Struct {
  @ffi.Uint32()
  external int cbSize;

  @ffi.Uint64()
  external int dwFlags;
}

final class LPMOUSEKEYS extends ffi.Struct {


g_ItemPrecache = {
  "item_angels_halo",
  "item_blood_sword",
  "item_bubble_orb_1",
  "item_butterfly_oaa",
  "item_craggy_coat_oaa",
  "item_dagger_of_moriah_1",
  "item_dagon_oaa_1",
  "item_demon_stone",
  "item_devastator_oaa_2",
  "item_dispel_orb_1",
  --"item_dragon_scale_oaa",
  "item_elixier_burst",
  "item_elixier_hybrid",
  "item_elixier_sustain",
  "item_enrage_crystal_1",
  --"item_eternal_shroud_oaa",
  "item_far_sight",
  "item_giant_form",
  "item_greater_phase_boots",
  "item_heart_oaa_1",
  "item_heart_transplant",
  "item_lucience",
  "item_martyrs_mail_1",
  --"item_meteor_hammer_1",
  --"item_pull_staff",
  --"item_reduction_orb_1",
  "item_reflection_shard_1",
  --"item_reflex_core",
  --"item_rune_breaker_oaa",
  --"item_sacred_skull",
  --"item_satanic_core_1",
  "item_shade_staff_1",
  "item_shield_staff",
  "item_siege_mode",
  --"item_silver_staff",
  "item_sonic",
  "item_stoneskin",
  "item_trumps_fists_1",
  --"item_travel_boots_oaa",
  "item_vampire",
}

g_UnitPrecache = {
  "dota_fountain",
  "npc_dota_demon_stone_demon",
  "npc_dota_eul_tornado",
  "npc_dota_eul_wildkin",
  "npc_dota_monkey_clone_oaa",
  "npc_dota_tinkerer_keen_node",
  --"npc_dota_visage_familiar", -- should be precached together with Visage
  --"npc_dota_witch_doctor_death_ward_oaa", -- should be precached together with Witch Doctor
  "npc_dota_hero_sohei",
  "npc_dota_hero_electrician",
  --"npc_azazel_tower_watch",
  "npc_dota_boss_simple_1", -- Skeleton boss
  "npc_dota_boss_simple_5", -- Cleave boss
  "npc_dota_boss_simple_7", -- Dire Creep boss
  --"npc_dota_boss_tier_1", -- Roshan (precached with normal dota)
  "npc_dota_boss_twin",
  "npc_dota_boss_twin_dumb",
  "npc_dota_boss_simple_2", -- Bear boss
  "npc_dota_boss_shielder",
  "npc_dota_boss_charger",
  "npc_dota_boss_pillar_charger_oaa",
  "npc_dota_boss_carapace", -- Weaver boss
  "npc_dota_boss_slime",
  "npc_dota_boss_swiper",  -- Sven boss
  "npc_dota_boss_spiders", -- Alchemist boss
  "npc_dota_creature_dire_tower_boss",
  "npc_dota_creature_magma_boss",
  "npc_dota_magma_boss_volcano",
  "npc_dota_creature_ogre_tank_boss",
  "npc_dota_creature_ogre_seer",
  "npc_dota_creature_lycan_boss",
  "npc_dota_creat


 it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "net/manaserv/messagein.h"

#include <cstring>
#include <enet/enet.h>

namespace ManaServ {

MessageIn::MessageIn(const char *data, unsigned int length):
    mData(data),
    mLength(length),
    mDebugMode(false),
    mPos(0)
{
    // Read the message ID
    mId = readInt16();

    // Read and clear the debug flag
    mDebugMode = mId & ManaServ::XXMSG_DEBUG_FLAG;
    mId &= ~ManaServ::XXMSG_DEBUG_FLAG;
}

uint8_t MessageIn::readInt8()
{
    uint8_t value = 0;

    if (!readValueType(ManaServ::Int8))
        return value;

    if (mPos < mLength)
    {
        value = mData[mPos];
    }
    mPos++;
    return value;
}

uint16_t MessageIn::readInt16()
{
    uint16_t value = 0;

    if (!readValueType(ManaServ::Int16))
        return value;

    if (mPos + 2 <= mLength)
    {
        uint16_t t;
        memcpy(&t, mData + mPos, 2);
        value = (unsigned short) ENET_NET_TO_HOST_16(t);
    }
    mPos += 2;
    return value;
}

uint32_t MessageIn::readInt32()
{
    uint32_t value = 0;

    if (!readValueType(ManaServ::Int32))
        return value;

    if (mPos + 4 <= mLength)
    {
        uint32_t t;
        memcpy(&t, mData + mPos, 4);
        value = ENET_NET_TO_HOST_32(t);
    }
    mPos += 4;
    return value;
}

std::string MessageIn::readString(int length)
{
    if (!readValueType(ManaServ::String))
        return std::string();

    if (mDebugMode)
    {
        int fixedLength = (int16_t) readInt16();
        if (fixedLength != length)
        {
            // String does not have the expected length
            mPos = mLength + 1;
            return std::string();
        }
    }

    // Get string length
    if (length < 0)
    {
        length = readInt16();
    }

    // Make sure the string isn't erroneous
    if (length < 0 || mPos + length > mLength)
    {
        mPos = mLength + 1;
        return std::string();
    }

    // Read the string
    const char *stringBeg = mData + mPos;
    const char *stringEnd = (const char *)memchr(stringBeg, '\0', length);
    std::string readString(stringBeg,
                           stringEnd ? stringEnd - stringBeg : length);
    mPos += length;

    return readString;
}

bool MessageIn::readValueType(ManaServ::ValueType type)
{
    if (!mDebugMode) // Verification not possible
        return true;

    if (mPos >= mLength)
        return false;

    uint8_t t = mData[mPos];
    ++mPos;

    return t == type;
}

} // ManaServ
/*
 *  The Mana Client
 *  Copyright (C) 2004-2009  The Mana World Development Team
 *  Copyright (C) 2009-2012  The Mana Developers
 *
 *  This file is part of The Mana Client.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later


 Int): Byte {
      val result = str.substring(start, end)
      return if (result.isEmpty())
        -1
      else
        result.toByteOrNull(10) ?: -1
    }

    /**
     * Try to read a number from a String in specified bounds
     *
     * @param str   String to be read from
     * @param start Start index (inclusive)
     * @param end   End index (exclusive)
     * @return The byte represented by the digits read from the string
     */
    fun readHexNumber(str: String, start: Int, end: Int): Int {
      val result = str.substring(start, end)
      return if (result.isEmpty())
        -1
      else
        result.toIntOrNull(16) ?: -1
    }

    /**
     * @param str   String to be searched in
     * @param start Start position (inclusive)
     * @return Index of first character that is not a digit
     */
    private fun findEndOfNumber(str: String, start: Int): Int {
      val searchFrame = str.substring(start)
      var i = 0
      loop@ while (i < 2 && i < searchFrame.length) {
        when (searchFrame[i]) {
          '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
            // Do nothing
          }
          else                                             -> break@loop
        }
        i++
      }
      return start + i
    }

    /**
     * @param str   String to be searched in
     * @param start Start position (inclusive)
     * @return Index of first character that is not a digit
     */
    private fun findEndOfHexNumber(str: String, start: Int): Int {
      val searchFrame = str.substring(start)
      var i = 0
      loop@ while (i < 6 && i < searchFrame.length) {
        when (searchFrame[i]) {
          '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b',
          'c', 'd', 'e', 'f' -> {
            // Do nothing
          }
          else               -> break@loop
        }
        i++
      }
      return start + i
    }
  }
}
/*
 * Quasseldroid - Quassel client for Android
 *
 * Copyright (c) 2020 Janne Mareike Koschinski
 * Copyright (c) 2020 The Quassel Project
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3 as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package de.kuschku.libquassel.session

import de.kuschku.libquassel.protocol.BufferId
import de.kuschku.libquassel.protocol.Message
import de.kuschku.libquassel.protocol.MsgId

interface NotificationManager {
  fun init(session: ISession)
  fun processMessages(session: ISession, show: Boolean, vararg messages: Message)
  fun clear(buffer: BufferId, lastRead: MsgId = MsgId.MAX_VALUE)
}
/*
 * Quasseldroid - Quassel client for Android
 *
 * Copyright (c) 2020 Janne Mareike Koschinski
 * Copyright (c) 2020 The Quassel Project
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3 as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANT


import argparse
import json
import os
from utils import extract_audio_from_video, transcribe_audio_file, is_video_file

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Transcribe an audio or video file using OpenAI Whisper."
    )
    parser.add_argument(
        "--input", required=True, help="Path to the input audio or video file."
    )
    parser.add_argument(
        "--output",
        default="transcript.json",
        help="Path to save the output JSON transcription.",
    )
    parser.add_argument(
        "--model_size",
        default="base",
        choices=[
            "tiny",
            "base",
            "small",
            "medium",
            "large",
            "large-v1",
            "large-v2",
            "large-v3",
        ],
        help="Whisper model size to use (default: base).",
    )

    args = parser.parse_args()

    if not os.path.exists(args.input):
        print(f"Error: Input file not found at {args.input}")
        exit(1)

    temp_audio_path = None
    input_for_transcription = args.input

    try:
        if is_video_file(args.input):
            print(f"Input file {args.input} appears to be a video. Extracting audio...")
            temp_audio_path = extract_audio_from_video(args.input)
            input_for_transcription = temp_audio_path
        else:
            print(f"Input file {args.input} appears to be an audio file.")

        if not input_for_transcription:
            print(f"Error: Could not prepare audio for transcription from {args.input}")
            exit(1)

        transcript_result = transcribe_audio_file(
            input_for_transcription, args.model_size
        )

        with open(args.output, "w", encoding="utf-8") as f:
            json.dump(transcript_result, f, indent=2, ensure_ascii=False)

        print(f"[✓] Transcription saved to {args.output}")

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        if temp_audio_path and os.path.exists(temp_audio_path):
            print(f"Cleaning up temporary audio file: {temp_audio_path}")
            os.remove(temp_audio_path)


[tAtom.ID],
            atomCode = atomBaseInfoRecord[tAtom.ATOM_CODE],
            atomName = atomBaseInfoRecord[tAtom.NAME],
            atomStatus = AtomStatusEnum.getAtomStatus(status.toInt()),
            creator = atomBaseInfoRecord[tAtom.CREATOR],
            version = atomBaseInfoRecord[tAtom.VERSION],
            publicFlag = atomBaseInfoRecord[tAtom.DEFAULT_FLAG] as Boolean,
            summary = atomBaseInfoRecord[tAtom.SUMMARY],
            docsLink = atomBaseInfoRecord[tAtom.DOCS_LINK],
            props = atomBaseInfoRecord[tAtom.PROPS]?.let {
                storeI18nMessageService.parseJsonStrI18nInfo(
                    jsonStr = it,
                    keyPrefix = StoreUtils.getStoreFieldKeyPrefix(
                        storeType = StoreTypeEnum.ATOM,
                        storeCode = atomCode,
                        version = atomBaseInfoRecord[tAtom.VERSION]
                    )
                )
            },
            buildLessRunFlag = atomBaseInfoRecord[tAtom.BUILD_LESS_RUN_FLAG],
            createTime = createTime.timestampmilli(),
            updateTime = updateTime.timestampmilli(),
            projectCode = initProjectCode,
            pkgPath = atomEnvInfoRecord?.pkgPath,
            language = atomEnvInfoRecord?.language,
            minVersion = atomEnvInfoRecord?.minVersion,
            target = atomEnvInfoRecord?.target,
            shaContent = atomEnvInfoRecord?.shaContent,
            preCmd = atomEnvInfoRecord?.preCmd,
            jobType = if (jobType == null) null else JobTypeEnum.valueOf(jobType),
            atomPostInfo = atomPostInfo,
            classifyCode = classifyRecord?.classifyCode,
            classifyName = classifyRecord?.classifyName,
            runtimeVersion = atomEnvInfoRecord?.runtimeVersion,
            finishKillFlag = atomEnvInfoRecord?.finishKillFlag,
            authFlag = atomBaseInfoRecord[tAtom.VISIBILITY_LEVEL] != VisibilityLevelEnum.LOGIN_PUBLIC.level
        )
        return Result(atomEnv)
    }

    private fun getAtomEnvInfoRecord(
        atomId: String,
        osName: String?,
        osArch: String?,
        convertOsFlag: Boolean?
    ): TAtomEnvInfoRecord? {
        var finalOsName = osName
        var finalOsArch = osArch
        var defaultAtomEnvInfoRecord: TAtomEnvInfoRecord? = null
        if (convertOsFlag == true) {
            defaultAtomEnvInfoRecord = marketAtomEnvInfoDao.getDefaultAtomEnvInfo(dslContext, atomId)
            // 把操作系统名称和cpu架构转换成开发语言对应的格式
            defaultAtomEnvInfoRecord?.language?.let {
                val atomBusHandleService = AtomBusHandleFactory.createAtomBusHandleService(it)
                osName?.let {
                    finalOsName = atomBusHandleService.handleOsName(osName)
                    finalOsArch = osArch?.let { atomBusHandleService.handleOsArch(osName, osArch) }
                }
            }
        }
        return marketAtomEnvInfoDao.getAtomEnvInfo(
            dslContext = dslContext,
            atomId = atomId,
            osName = finalOsName,
            osArch = finalOsArch
        ) ?: marketAtomEnvInfoDao.getDefaultAtomEnvInfo(dslContext, atomId, osName)
        ?: if (convertOsFlag == true) {
            defaultAtomEnvInfoRecord
        } else {
            marketAtomEnvInfoDao.getDefaultAtomEnvInfo(dslContext, atomId)
        }
    }

    private fun getAtomStatusList(
        atomStatus: Byte?,
        version: String,
        normalStatusList: List<Byte>,
        atomCode: String,
        projectCode: String,
        queryTestFlag: Boolean
    ): List<Byte> {
        return if (atomStatus != null) {
            mutableListOf(atomStatus)
        } else {
            normalStatusList.toMutableList().apply {


        int i=0;
-=--(DOS)----F1  fraction.c     Top L2     (C/l A

34/**display/*
#include <stdio.h>

#include <stdlib.h>
#include <ctype.h>
#include <string.h>

display(int count,char in[])
{
        int charCount = strlen(in);
        int i=0;
Thisprogramisusedtogetthefractionofa\

#include <stdio.h>
givenString.i   gbygivingthes Stringthenthen        [space[1


# master
# Another best method to do this

n = map(list(int, input().split()))
odd_list = list(i for i in n if i % 2 != 0)
print(odd_list)
exit()

# CALCULATE NUMBER OF ODD NUMBERS

# CALCULATE NUMBER OF ODD NUMBERS WITHIN A GIVEN LIMIT
# master

n = int(input("Enter the limit : "))  # user input

if n <= 0:
    print("Invalid number, please enter a number greater than zero!")
else:
    odd_list = [i for i in range(1, n + 1, 2)]  # creating string with number "i"
    print(odd_list)  # in range from 1 till "n".

#     printing odd and even number in same program
n = map(list(int, input().split()))
even = []
odd = []
for i in range(n):
    if i % 2 == 0:
        even.append(i)
    else:
        odd.append(i)


AS CLI flag present, but unable to get value");
        alias = cli_alias.into();
    } else {
        alias = match iridium::cluster::alias::read_node_id(NODE_ID_FILENAME) {
            Ok(read_alias) => read_alias,
            Err(_) => {
                let new_alias = uuid::Uuid::new_v4().to_hyphenated().to_string();
                if let Err(_) = iridium::cluster::alias::write_node_id(NODE_ID_FILENAME, &new_alias) {
                    std::process::exit(1);
                }
                new_alias
            }
        };
    }
    info!("Node ID is: {}", alias);

    let server_addr = matches.value_of("SERVER_LISTEN_HOST").unwrap_or("127.0.0.1");
    let server_port = matches.value_of("SERVER_LISTEN_PORT").unwrap_or(DEFAULT_NODE_LISTEN_PORT);

    let num_threads = match matches.value_of("THREADS") {
        Some(number) => match number.parse::<usize>() {
            Ok(v) => v,
            Err(_e) => {
                println!("Invalid argument for number of threads: {}. Using default.", number);
                num_cpus::get()
            }
        },
        None => num_cpus::get(),
    };

    if daemon_mode == "true" {
        // TODO: Fill this in
    } else {
        let target_file = matches.value_of("INPUT_FILE");
        match target_file {
            Some(filename) => {
                let program = read_file(filename);
                let mut asm = Assembler::new();
                let mut vm = VM::new()
                    .with_alias(alias.to_string())
                    .with_cluster_bind(server_addr.into(), server_port.into());
                vm.logical_cores = num_threads;
                let program = asm.assemble(&program);
                match program {
                    Ok(p) => {
                        vm.add_bytes(p);
                        let _events = vm.run();
                        println!("{:#?}", vm.registers);
                        std::process::exit(0);
                    }
                    Err(_e) => {}
                }
            }
            None => {
                debug!("Spawning REPL with alias {}", alias);
                let mut vm = VM::new()
                    .with_alias(alias.to_string())
                    .with_cluster_bind(server_addr.into(), server_port.into());
                let mut repl = REPL::new(vm);
                let mut rx = repl.rx_pipe.take();
                thread::spawn(move || {
                    let chan = rx.unwrap();
                    loop {
                        match chan.recv() {
                            Ok(msg) => {
                                println!("{}", msg);
                            }
                            Err(_e) => {}
                        }
                    }
                });
                repl.run();
            }
        }
    }
}

fn read_file(tmp: &str) -> String {
    let filename = Path::new(tmp);
    match File::open(Path::new(&filename)) {
        Ok(mut fh) => {
            let mut contents = String::new();
            match fh.read_to_string(&mut contents) {
                Ok(_) => contents,
                Err(e) => {
                    println!("There was an error reading file: {:?}", e);
                    std::process::exit(1);
                }
            }
        }
        Err(e) => {
            println!("File not found: {:?}", e);
            std::process::exit(1)


pt		   = inet_csk_accept,
	.get_port	   = inet_csk_get_port,
	.shutdown	   = dccp_shutdown,
	.destroy	   = dccp_v6_destroy_sock,
	.orphan_count	   = &dccp_orphan_count,
	.max_header	   = MAX_DCCP_HEADER,
	.obj_size	   = sizeof(struct dccp6_sock),
	.slab_flags	   = SLAB_TYPESAFE_BY_RCU,
	.rsk_prot	   = &dccp6_request_sock_ops,
	.twsk_prot	   = &dccp6_timewait_sock_ops,
	.h.hashinfo	   = &dccp_hashinfo,
#ifdef CONFIG_COMPAT
	.compat_setsockopt = compat_dccp_setsockopt,
	.compat_getsockopt = compat_dccp_getsockopt,
#endif
};

static const struct inet6_protocol dccp_v6_protocol = {
	.handler	= dccp_v6_rcv,
	.err_handler	= dccp_v6_err,
	.flags		= INET6_PROTO_NOPOLICY | INET6_PROTO_FINAL,
};

static const struct proto_ops inet6_dccp_ops = {
	.family		   = PF_INET6,
	.owner		   = THIS_MODULE,
	.release	   = inet6_release,
	.bind		   = inet6_bind,
	.connect	   = inet_stream_connect,
	.socketpair	   = sock_no_socketpair,
	.accept		   = inet_accept,
	.getname	   = inet6_getname,
	.poll		   = dccp_poll,
	.ioctl		   = inet6_ioctl,
	.listen		   = inet_dccp_listen,
	.shutdown	   = inet_shutdown,
	.setsockopt	   = sock_common_setsockopt,
	.getsockopt	   = sock_common_getsockopt,
	.sendmsg	   = inet_sendmsg,
	.recvmsg	   = sock_common_recvmsg,
	.mmap		   = sock_no_mmap,
	.sendpage	   = sock_no_sendpage,
#ifdef CONFIG_COMPAT
	.compat_setsockopt = compat_sock_common_setsockopt,
	.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};

static struct inet_protosw dccp_v6_protosw = {
	.type		= SOCK_DCCP,
	.protocol	= IPPROTO_DCCP,
	.prot		= &dccp_v6_prot,
	.ops		= &inet6_dccp_ops,
	.flags		= INET_PROTOSW_ICSK,
};

static int __net_init dccp_v6_init_net(struct net *net)
{
	if (dccp_hashinfo.bhash == NULL)
		return -ESOCKTNOSUPPORT;

	return inet_ctl_sock_create(&net->dccp.v6_ctl_sk, PF_INET6,
				    SOCK_DCCP, IPPROTO_DCCP, net);
}

static void __net_exit dccp_v6_exit_net(struct net *net)
{
	inet_ctl_sock_destroy(net->dccp.v6_ctl_sk);
}

static struct pernet_operations dccp_v6_ops = {
	.init   = dccp_v6_init_net,
	.exit   = dccp_v6_exit_net,
};

static int __init dccp_v6_init(void)
{
	int err = proto_register(&dccp_v6_prot, 1);

	if (err != 0)
		goto out;

	err = inet6_add_protocol(&dccp_v6_protocol, IPPROTO_DCCP);
	if (err != 0)
		goto out_unregister_proto;

	inet6_register_protosw(&dccp_v6_protosw);

	err = register_pernet_subsys(&dccp_v6_ops);
	if (err != 0)
		goto out_destroy_ctl_sock;
out:
	return err;

out_destroy_ctl_sock:
	inet6_del_protocol(&dccp_v6_protocol, IPPROTO_DCCP);
	inet6_unregister_protosw(&dccp_v6_protosw);
out_unregister_proto:
	proto_unregister(&dccp_v6_prot);
	goto out;
}

static void __exit dccp_v6_exit(void)
{
	unregister_pernet_subsys(&dccp_v6_ops);
	inet6_del_protocol(&dccp_v6_protocol, IPPROTO_DCCP);
	inet6_unregister_protosw(&dccp_v6_protosw);
	proto_unregister(&dccp_v6_prot);
}

module_init(dccp_v6_init);
module_exit(dccp_v6_exit);

/*
 * __stringify doesn't likes enums, so use SOCK_DCCP (6) and IPPROTO_DCCP (33)
 * values directly, Also cover the case where the protocol is not specified,
 * i.e. net-pf-PF_INET6-proto-0-type-SOCK_DCCP
 */
MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 33, 6);
MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 0, 6);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Arnaldo Carvalho de Melo <acme@mandriva.com>");
MODULE_DESCRIPTION("DCCPv6 - Datagram Congestion Controlled Protocol");


x / m;
        rateOfChangeVals[idx + OFFSET_POSITION_Y] = P.y / m;
        rateOfChangeVals[idx + OFFSET_POSITION_Z] = P.z / m;
        const uom = Unit.div(P.uom, M.uom);
        rateOfChangeUoms[idx + OFFSET_POSITION_X] = uom;
        rateOfChangeUoms[idx + OFFSET_POSITION_Y] = uom;
        rateOfChangeUoms[idx + OFFSET_POSITION_Z] = uom;
    }
    setAttitudeRateOfChangeVars(rateOfChangeVals: number[], rateOfChangeUoms: Unit[], idx: number, body: ForceBody<Geometric3>): void {
        // The rate of change of attitude is given by: dR/dt = -(1/2) Ω R,
        // requiring the geometric product of Ω and R.
        // Ω and R are auxiliary and primary variables that have already been computed.
        const R = body.R;
        const Ω = body.Ω;
        rateOfChangeVals[idx + OFFSET_ATTITUDE_A] = +0.5 * (Ω.xy * R.xy + Ω.yz * R.yz + Ω.zx * R.zx);
        rateOfChangeVals[idx + OFFSET_ATTITUDE_YZ] = -0.5 * (Ω.yz * R.a + Ω.xy * R.zx - Ω.zx * R.xy);
        rateOfChangeVals[idx + OFFSET_ATTITUDE_ZX] = -0.5 * (Ω.zx * R.a + Ω.yz * R.xy - Ω.xy * R.yz);
        rateOfChangeVals[idx + OFFSET_ATTITUDE_XY] = -0.5 * (Ω.xy * R.a + Ω.zx * R.yz - Ω.yz * R.zx);
        const uom = Unit.mul(Ω.uom, R.uom);
        rateOfChangeUoms[idx + OFFSET_ATTITUDE_A] = uom;
        rateOfChangeUoms[idx + OFFSET_ATTITUDE_YZ] = uom;
        rateOfChangeUoms[idx + OFFSET_ATTITUDE_ZX] = uom;
        rateOfChangeUoms[idx + OFFSET_ATTITUDE_XY] = uom;
    }
    zeroLinearMomentumVars(rateOfChangeVals: number[], rateOfChangeUoms: Unit[], idx: number, body: ForceBody<Geometric3>, uomTime: Unit): void {
        const P = body.P;
        const uom = Unit.div(P.uom, uomTime);
        rateOfChangeVals[idx + OFFSET_LINEAR_MOMENTUM_X] = 0;
        rateOfChangeUoms[idx + OFFSET_LINEAR_MOMENTUM_X] = uom;
        rateOfChangeVals[idx + OFFSET_LINEAR_MOMENTUM_Y] = 0;
        rateOfChangeUoms[idx + OFFSET_LINEAR_MOMENTUM_Y] = uom;
        rateOfChangeVals[idx + OFFSET_LINEAR_MOMENTUM_Z] = 0;
        rateOfChangeUoms[idx + OFFSET_LINEAR_MOMENTUM_Z] = uom;
    }
    zeroAngularMomentumVars(rateOfChangeVals: number[], rateOfChangeUoms: Unit[], idx: number, body: ForceBody<Geometric3>, uomTime: Unit): void {
        const L = body.L;
        const uom = Unit.div(L.uom, uomTime);
        rateOfChangeVals[idx + OFFSET_ANGULAR_MOMENTUM_XY] = 0;
        rateOfChangeUoms[idx + OFFSET_ANGULAR_MOMENTUM_XY] = uom;
        rateOfChangeVals[idx + OFFSET_ANGULAR_MOMENTUM_YZ] = 0;
        rateOfChangeUoms[idx + OFFSET_ANGULAR_MOMENTUM_YZ] =