ue,
							name = L["Bars"],
							args = {
								smoothbars = {
									order = 1,
									type = "toggle",
									name = L["Smooth Bars"],
									desc = L["Bars will transition smoothly."],
									set = function(info, value) E.db.unitframe[info[#info]] = value UF:Update_AllFrames() end
								},
								statusbar = {
									order = 3,
									type = "select", dialogControl = "LSM30_Statusbar",
									name = L["StatusBar Texture"],
									desc = L["Main statusbar texture."],
									values = AceGUIWidgetLSMlists.statusbar,
									set = function(info, value) E.db.unitframe[info[#info]] = value UF:Update_StatusBars() end
								}
							}
						},
						fontGroup = {
							order = 8,
							type = "group",
							guiInline = true,
							name = L["Fonts"],
							args = {
								font = {
									order = 4,
									type = "select", dialogControl = "LSM30_Font",
									name = L["Default Font"],
									desc = L["The font that the unitframes will use."],
									values = AceGUIWidgetLSMlists.font,
									set = function(info, value) E.db.unitframe[info[#info]] = value UF:Update_FontStrings() end
								},
								fontSize = {
									order = 5,
									type = "range",
									name = L["FONT_SIZE"],
									desc = L["Set the font size for unitframes."],
									min = 4, max = 32, step = 1,
									set = function(info, value) E.db.unitframe[info[#info]] = value UF:Update_FontStrings() end
								},
								fontOutline = {
									order = 6,
									type = "select",
									name = L["Font Outline"],
									desc = L["Set the font outline."],
									values = C.Values.FontFlags,
									set = function(info, value) E.db.unitframe[info[#info]] = value UF:Update_FontStrings() end
								}
							}
						}
					}
				},
				frameGlowGroup = {
					order = 2,
					type = "group",
					childGroups = "tree",
					name = L["Frame Glow"],
					args = {
						header = {
							order = 1,
							type = "header",
							name = L["Frame Glow"]
						},
						mainGlow = {
							order = 2,
							type = "group",
							guiInline = true,
							name = L["Mouseover Glow"],
							get = function(info)
								local t = E.db.unitframe.colors.frameGlow.mainGlow[info[#info]]
								if type(t) == "boolean" then return t end
								local d = P.unitframe.colors.frameGlow.mainGlow[info[#info]]
								return t.r, t.g, t.b, t.a, d.r, d.g, d.b, d.a
							end,
							set = function(info, r, g, b, a)
								local t = E.db.unitframe.colors.frameGlow.mainGlow[info[#info]]
								if type(t) == "boolean" then
									E.db.unitframe.colors.frameGlow.mainGlow[info[#info]] = r
								else
									t.r, t.g, t.b, t.a = r, g, b, a
								end
								UF:FrameGlow_UpdateFrames()
							end,
							disabled = function() return not E.db.unitframe.colors.frameGlow.mainGlow.enable end,
							args = {
								enable = {
									order = 1,
									type = "toggle",
									name = L["Enable"],
									disabled = false
								},
								spacer = {
									order = 2,
									type = "description",
									name = ""
								},
								class = {
									order = 3,
									type = "toggle",
									name = L["Use


799727,1,0",
	"0,MmS7bQcM6yDKc5UrynFZcN9RxSPiCZLBiFy,10154782410888,1,0",
	"0,MmS7choftdUwZSFLwYVvkr2pyhjjTVMsGTQ,3106991100,1,0",
	"0,MmS8BCLh3FCZcycVnpLF6B5u87EULFxpKpM,3861943743570,1,0",
	"0,MmS8CEnXsxgazqiMN68nUmPoESqzEqyPE5k,1553495550,1,0",
	"0,MmS8m2YujzoS5eg8xcp2pV4zEk1fjwwFaw8,1098855134921,1,0",
	"0,MmS8rFALTEGr7ZrVbJ7Jt7ywE4BmWp4xyTg,224719899412,1,0",
	"0,MmS8rpPvkUtx8MmUbd9fzsZoRZCfwVM8vAk,61012439923,1,0",
	"0,MmS9HwXeaPFg2JiFhmcqMrUgrm1SPWJotpH,1553495550,1,0",
	"0,MmS9LiK1U2jeaS4FQfBRbYaWoMHDFr3NwjD,3106991100,1,0",
	"0,MmS9pPKakhn9FCaAMWNLr7fMxYT1jifffPK,138911811453,1,0",
	"0,MmSaC2ZDSmiyCgtwZz7SMWbeVDHAwoTcBuU,4420595852152,1,0",
	"0,MmSAkMFovWr74w2LYtJfVGd5ENQ2GURZ5WB,125103375078,1,0",
	"0,MmSaKS5EfVdF4GQwU9SCnEvp5w2UEWFrvyg,3106991100,1,0",
	"0,MmSAMsEVacrFV5WP6bcrADU3HxYBnB4ry4j,228254997595,1,0",
	"0,MmSaqhGr4MBBYfyAYDhqEegnDiX6RTVNCAP,2053698463370,1,0",
	"0,MmSatvbMWw4YXywPzXgt3vJbEzaGRUiwm5y,7598047864978,1,0",
	"0,MmSAZ8oBsWy8GCSEuJEVcERnD1M6Q45d5vR,1753727376721,1,0",
	"0,MmSbMv1yQrEeFA2zXEF26mq4VrRWpRsdcfg,1553495550,1,0",
	"0,MmSBNa7iMzYbBZ7fBN8tZuAGFd19kmpWepb,98388051500,1,0",
	"0,MmSbnaLCcux565oZWZe9e91Mcbq6fMys6Ak,1553495550,1,0",
	"0,MmSBoqM7HvHnQDcz25nGhuqbaNbrUKLA5jz,1035663700000,1,0",
	"0,MmSbWvks95yEgpFPsytdNMndByHwosMq8Gy,817144862097,1,0",
	"0,MmSbxZRBCy7Sgen8ivw8EAzWoWHBqXMJ7Ea,179833948398,1,0",
	"0,MmSC7wuBHtE6Unkt99jTCnYKQvttZ48hcys,3106991100,1,


}

        // Calling write_next_segment (without a payload source) again should not send
        // anything else.
        assert!(t.write_next_segment(&mut c, None).unwrap().is_none());

        {
            let payload_len = data.payload_len() as u32;

            // Assuming no one changed the code, the local window size of the connection was 10000,
            // so we should be able to successfully receive 9 more segments with 1000 byte payloads.
            let max = 9;
            for i in 1u32..=max {
                // The 1 we add is because the SYN consumes a sequence number.
                data.set_sequence_number(t.remote_isn.wrapping_add(1 + i * payload_len));
                assert_eq!(
                    t.receive_segment(&mut c, &data).unwrap(),
                    (
                        Some(NonZeroUsize::new(data.payload_len()).unwrap()),
                        RecvStatusFlags::empty()
                    )
                );
            }

            let expected_ack = t.remote_isn.wrapping_add(1 + (max + 1) * payload_len);
            // The connection should send a single cumulative ACK, and no other segment afterward
            // (if we don't also provide a payload source, which we don't).
            {
                {
                    let s = t.write_next_segment(&mut c, None).unwrap().unwrap();
                    check_acks(&s, expected_ack, TcpFlags::empty());
                }

                assert!(t.write_next_segment(&mut c, None).unwrap().is_none());
            }

            // Sending any more new data should be outside of the receive window of the connection.
            data.set_sequence_number(expected_ack);
            assert_eq!(
                t.receive_segment(&mut c, &data).unwrap(),
                (None, RecvStatusFlags::SEGMENT_BEYOND_RWND)
            );
        }

        // Restore connection state to just after ESTABLISHED, and make it send some data.
        c = c_clone.clone();

        // This should send anything, as the payload source does not contain the next sequence
        // number to be sent.

        // Should contain conn_isn + 1 to be fine, but we make it start just after.
        payload_src.as_mut().unwrap().1 = Wrapping(conn_isn) + Wrapping(2);

        assert_eq!(
            t.write_next_segment(&mut c, payload_src).unwrap_err(),
            WriteNextError::PayloadMissingSeq
        );

        // Let's fix it.
        payload_src.as_mut().unwrap().1 = Wrapping(conn_isn) + Wrapping(1);

        // The mss is 1100, and the remote window is 11000, so we can send 10 data packets.
        let max = 10;
        let remote_isn = t.remote_isn;
        let mss = u32::from(t.mss);

        let (payload_buf, mut response_seq) = payload_src.unwrap();
        let mut payload_offset = 0;
        for i in 0..max {
            // Using the expects to get the value of i if there's an error.
            let s = t
                .write_next_segment(&mut c, Some((&payload_buf[payload_offset..], response_seq)))
                .unwrap_or_else(|_| panic!("{}", i))
                .unwrap_or_else(|| panic!("{}", i));

            payload_offset += s.payload_len();
            response_seq += Wrapping(s.payload_len() as u32);

            // Again, the 1 accounts for the sequence number taken up by the SYN.
            assert_eq!(s.sequence_number(), conn_isn.wrapping_add(1 + i * mss));
            assert_eq!(s.ack_number(),


      }

        private async void B_NTP_Click(object sender, EventArgs e)
        {
            try
            {
                await ConnectionWrapper.ResetTimeNTP(Token).ConfigureAwait(false);
                B_Read_Click(sender, e);
            }
            catch (Exception ex)
            {
                await this.DisplayMessageBox(Webhook, $"Could not reset the date: {ex.Message}", Token).ConfigureAwait(false);
            }
        }

        private async void B_Write_Click(object sender, EventArgs e)
        {
            try
            {
                var success = ulong.TryParse(TB_Tick.Text, out var time);
                if (success)
                {
                    await ConnectionWrapper.SetCurrentTime(time, Token).ConfigureAwait(false);
                }
                else
                {
                    await this.DisplayMessageBox(Webhook, $"Could not write the date: {TB_Tick.Text} could not be parsed as a ulong!", Token).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                await this.DisplayMessageBox(Webhook, $"Could not write the date: {ex.Message}", Token).ConfigureAwait(false);
            }
        }
    }
}


cube.y)
    let rz = Math.round(cube.z)

    const xDiff = Math.abs(rx - cube.x)
    const yDiff = Math.abs(ry - cube.y)
    const zDiff= Math.abs(rz - cube.z)

    if ((xDiff > yDiff) && (xDiff > zDiff)) {
      rx = -ry - rz
    }
    else if (yDiff > zDiff) {
      ry = -rx - rz
    }
    else {
      rz = -rx - ry
    }

    return {x: rx, y: ry, z: rz}
  }
}

export class SearchCoordinate extends Coordinate implements BaseCoordinate {
  originRow: number | null
  originColumn: number | null
  movementCostSpent: number
  estimatedMovementCostRemaining: number
  totalMovementCostSpent: number

  constructor(
    row: number,
    column: number,
    originRow: number | null,
    originColumn: number | null,
    movementCostSpent: number,
    estimatedMovementCostRemaining: number,
    totalMovementCostSpent?: number
  ) {
    super(row, column);
    this.originRow = originRow
    this.originColumn = originColumn
    this.movementCostSpent = movementCostSpent
    this.estimatedMovementCostRemaining = estimatedMovementCostRemaining
    this.totalMovementCostSpent = totalMovementCostSpent
  }

  getOriginColumn(): number | null {
    return this.originColumn
  }

  getOriginRow(): number | null {
    return this.originRow
  }

  getOriginLocationKey(): string | null {
    if (this.originRow && this.originColumn) {
      return `${this.getOriginRow()}, ${this.getOriginColumn()}`
    }
    return null
  }

  getMovementCostSpent(): number {
    return this.movementCostSpent
  }

  getEstimatedMovementCostRemaining(): number {
    return this.estimatedMovementCostRemaining
  }

  getTotalMovementCostSpent(): number {
    return this.totalMovementCostSpent
  }

  isOrigin() {
    return (this.getOriginLocationKey() === null)
  }

  clone() {
    return new SearchCoordinate(
      this.getRow(),
      this.getColumn(),
      this.getOriginRow(),
      this.getOriginColumn(),
      this.getMovementCostSpent(),
      this.getEstimatedMovementCostRemaining(),
    )
  }
}

export class Path {
  searchCoordinates: Array<SearchCoordinate>

  constructor(startingCoordinate?: SearchCoordinate) {
    if (startingCoordinate) {
      this.searchCoordinates = new Array<SearchCoordinate>(startingCoordinate)
    }
    else {
      this.searchCoordinates = new Array<SearchCoordinate>()
    }
  }

  getNumberOfCoordinates(): number{
    return this.searchCoordinates.length
  }

  getHeadCoordinate(): SearchCoordinate {
    return this.searchCoordinates[this.searchCoordinates.length - 1]
  }

  getTotalMovementCostSpent(): number {
    return this.searchCoordinates.map(
      searchCoordinate => searchCoordinate.getMovementCostSpent()
    ).reduce(
      (accumulator, currentCost) => {
        return accumulator + currentCost
      },
      0
    )
  }

  addSearchCoordinate(newSearchCoordinate: SearchCoordinate): void {
    this.searchCoordinates.push(newSearchCoordinate)
  }

  clone(): Path {
    const clonedPath = new Path()
    this.searchCoordinates.forEach((newSearchCoordinate) => {
      clonedPath.addSearchCoordinate(newSearchCoordinate.clone())
    })


upportPrimaryKeyGenerator.class, primaryKeyGeneratorClass)) {
//
//                        PrimaryKeyGenerator primaryKeyGenerator = configuration.getPrimaryKeyGenerator(primaryKeyGeneratorClass);
//                        if (primaryKeyGenerator == null) {
//                            throw new EasyQueryException(EasyClassUtil.getSimpleName(entityClass) + "." + property + " primary key generator unknown");
//                        }
//                        columnOption.setPrimaryKeyGenerator(primaryKeyGenerator);
//                        this.hasPrimaryKeyGenerator = true;
//                    }
//                }
//                columnOption.setGeneratedKey(generatedKey);
//
//                columnOption.setLarge(column.large());
////                    columnMetadata.setSelect(column.select());
////                    columnMetadata.setNullable(false);//如果为主键那么之前设置的nullable将无效
//
//
////                Class<? extends ValueUpdateAtomicTrack<?>> trackValueUpdateClass = column.valueUpdateAtomicTrack();
////                if (!Objects.equals(DefaultValueUpdateAtomicTrack.class, trackValueUpdateClass)) {
////                    ValueUpdateAtomicTrack<?> trackValueUpdate = configuration.getValueUpdateAtomicTrack(trackValueUpdateClass);
////                    if (trackValueUpdate == null) {
////                        throw new EasyQueryException(EasyClassUtil.getSimpleName(entityClass) + "." + property + " trackValueUpdate unknown");
////                    }
////                    if(column.concurrent()){
////                        throw new EasyQueryException(EasyClassUtil.getSimpleName(entityClass) + "." + property + "conflict with trackValueUpdate and concurrent");
////                    }
////                    columnOption.setValueUpdateAtomicTrack(EasyObjectUtil.typeCastNullable(trackValueUpdate));
////                }else{
////                    if(column.concurrent()){
////                        ValueUpdateAtomicTrack<?> valueUpdateAtomicTrack = configuration.getValueUpdateAtomicTrack(ConcurrentValueUpdateAtomicTrack.class);
////                        columnOption.setValueUpdateAtomicTrack(EasyObjectUtil.typeCastNullable(valueUpdateAtomicTrack));
////                    }
////                }
////                if(column.concurrent()){
////                    columnOption.setConcurrentUpdateInTrack(true);
////                }
//                Class<? extends ColumnValueSQLConverter> columnValueSQLConverterClass = column.sqlConversion();
//                if (!Objects.equals(DefaultColumnValueSQLConverter.class, columnValueSQLConverterClass)) {
//                    //配置列值数据库转换器
//                    ColumnValueSQLConverter columnValueSQLConverter = configuration.getColumnValueSQLConverter(columnValueSQLConverterClass);
//                    if (columnValueSQLConverter == null) {
//                        throw new EasyQueryException(EasyClassUtil.getSimpleName(entityClass) + "." + property + " column value sql converter unknown");
//                    }
//                    columnOption.setColumnValueSQLConverter(columnValueSQLConverter);
//                    if (columnValueSQLConverter.isMergeSubQuery()) {
//                        this.aliasQuery = true;
//                    }
//                }
//            }
//            InsertIgnore insertIgnore = field.getAnnotation(InsertIgnore.class);
//            if (insertIgnore != null) {
//                columnOption.setInsertIgnore(true);
//            }
//
//            UpdateIgnore updateIgnore = field.getAnnotation(UpdateIgnore.class);
//            if (updateIgnore != null) {
//                columnOption.setUpdateIgnore(true);
//                columnOption.setUpdateSetInTrackDiff(updateIgnore.updateSetInTrackDiff());
//            }
//            Version version = field.getAnnotation(Version.class);
//            if (version != null) {
//
//                Class<? extends VersionStrategy> strategy = version.strategy();
//                VersionStrategy easyVersionStrategy = configuration.getEasyVersionStrategyOrNull(strategy);
//                if (easyVersionStrategy == null) {
//                    throw new EasyQueryException(EasyClassUtil.getSimpleName(entityClass) + "." + property + " Version strategy unknown");
//                }
//                columnOption.setVersion(true);
//
//                if (versionMetadata == null) {
//                    versionMetad


Advertising professional trying for a clean slate!";
      sa[219] = "African Safari Wedding";
      sa[220] = "Aftra Membership";
      sa[221] = "Ahmed";
      sa[222] = "Aid for Credit Card Debt Loan";
      sa[223] = "Air Conditioner Loan";
      sa[224] = "Aircraft Partnership Loan";
      sa[225] = "Ajith's Debt Consoliation Loan";
      sa[226] = "Al's Loan";
      sa[227] = "Alabama Consolidation Loan";
      sa[228] = "Alan's Personal Loan";
      sa[229] = "Albert's loan";
      sa[230] = "Alex";
      sa[231] = "Alex Loan";
      sa[232] = "Alfa";
      sa[233] = "Alfonso Silva";
      sa[234] = "Alfredo's Loan";
      sa[235] = "Ali Pay Off";
      sa[236] = "Alison Braen";
      sa[237] = "All Clear";
      sa[238] = "All Consumer Debt Loan";
      sa[239] = "All Debt Consolidate";
      sa[240] = "All Debts Consolidate";
      sa[241] = "All In One Bill";
      sa[242] = "All bills into One";
      sa[243] = "Allen Loan";
      sa[244] = "Allen's Debt Consolidation Loan";
      sa[245] = "Allen's Granny Flat home project";
      sa[246] = "Allison";
      sa[247] = "Almost There debt consolidation";
      sa[248] = "Almost There!";
      sa[249] = "Almost out of Debt.....";
      sa[250] = "Always on time with payments";
      sa[251] = "Always pays on time";
      sa[252] = "AmEx";
      sa[253] = "Amanda and Tyler's wedding fund";
      sa[254] = "American Dreamcard payoff";
      sa[255] = "American Enterprise";
      sa[256] = "American Express";
      sa[257] = "American Union";
      sa[258] = "Amex";
      sa[259] = "Amex Payoff";
      sa[260] = "Amy";
      sa[261] = "Amy's Wedding";
      sa[262] = "Andrea's Consolidation Loan";
      sa[263] = "Andrew";
      sa[264] = "Andrew's Debt Help";
      sa[265] = "Andy ";
      sa[266] = "Andy's Bailout";
      sa[267] = "Angela Kay Myrick";
      sa[268] = "Angela's Debt Consolidation";
      sa[269] = "Angela- Home imp loan";
      sa[270] = "Anniv. Gift";
      sa[271] = "Another take on Credit Card Reform ";
      sa[272] = "Apartment";
      sa[273] = "Apartment Initiative";
      sa[274] = "Apartment Loan";
      sa[275] = "Appendectomy";
      sa[276] = "Apple Tree";
      sa[277] = "Appreciative Borrower";
      sa[278] = "April 2011 Lending Club";
      sa[279] = "Archie's loan";
      sa[280] = "Ashley's Consolidation";
      sa[281] = "Askerlik";
      sa[282] = "Aspiring CPA";
      sa[283] = "Assist Family Members";
      sa[284] = "Assist in buying used car";
      sa[285] = "Assistance";
      sa[286] = "Astoria";
      sa[287] = "Attic Renovation Project";
      sa[288] = "Attorney Fees";
      sa[289] = "Attorney Fees for Child Custody";
      sa[290] = "Attorney retainer";
      sa[291] = "Audra's Dreamhouse";
      sa[29


i. La differenza di popolarità è così sbalorditiva, che anche `-ms-linear-gradient()`, che non è mai stato necessario (Internet Explorer 10 supportava i gradienti sia con che senza il prefisso `-ms-`), è più popolare di `radial-gradient()`! Il nuovo supporto `conic-gradient()` è ancora più sottoutilizzato, apparendo solo in 652 pagine desktop (0.01%) e 848 pagine mobile (0.01%), il che è previsto, poiché Firefox ha appena spedito la sua implementazione al canale stabile.

Anche i gradienti ripetuti di tutti i tipi sono abbastanza sottoutilizzati, con `repeating-linear-gradient()` che appare solo nel 3% delle pagine e gli altri si trascinano ancora di più (`repeating-conic-gradient()` è usato solo in 21 pagine!).

I gradienti prefissati sono ancora molto popolari, anche se i gradienti non richiedono più un prefisso dal 2013. È da notare che -webkit-gradient() è ancora utilizzato in metà di tutti i siti Web, anche se non è più stato necessario dal 2011. Inoltre `-webkit-linear-gradient()` è ancora la seconda funzione gradiente più utilizzata di tutte, che appare nel 57% dei siti web.

{{ figure_markup(
  image="gradient-functions.png",
  caption="Le funzioni gradiente più popolari come percentuale di pagine.",
  description="Grafico a barre che mostra le funzioni gradiente più popolari come percentuale delle pagine desktop e mobile. Le funzioni gradiente tendono ad essere più popolari sulle pagine mobile. La funzione gradiente più popolare è `linear-gradient`, utilizzata sul 73% delle pagine mobile. Seguito da `-webkit-linear-gradient` sul 57%, `-webkit-gradient` e `-linear-gradient` sul 50%, `-moz-linear-gradient` sul 49%, `-ms-linear-gradient` sul 33%, `radial-gradient` sul 15%, `-webkit-radial-gradient` sul 9%, e `repeating-linear-gradient` e `-moz-radial-gradient` utilizzato sul 3% delle pagine per dispositivi mobile.",
  chart_url="https://docs.google.com/spreadsheets/d/e/2PACX-1vRpe_HsNGpekn6YZV9k6QGmcZPxalqnDrL7DrDY-7X65RZEf_-aGfWuEvhk-yWV83ctIceE1bppCLpj/pubchart?oid=1552177796&format=interactive",
  sheets_gid="397884589",
  sql_file="gradient_functions.sql"
) }}

{{ figure_markup(
  image="gradient-functions-unprefixed.png",
  caption="Le funzioni gradiente più popolari come percentuale di pagine, omettendo i prefissi del fornitore.",
  description="Grafico a barre che mostra le funzioni gradiente più popolari come percentuale delle pagine desktop e mobile, omettendo i prefissi del fornitore. L'adozione da desktop è leggermente inferiore ai dispositivi mobile. Le variazioni di `linear-gradient` sono utilizzate sul 72.57% delle pagine mobile, `radial-gradient` sul 15.13%, `repeating-linear-gradient` su 2.99%, `repeating-radial-gradient` sullo 0.07%, `conic-gradient` sullo 0.01% e `repeating-conic-gradient` su circa lo 0.00% delle pagine per dispositivi mobile",
  chart_url="https:


ommunity Center"
    participants_file = "participants.csv"
    inventory_file = "inventory.csv"
    volunteers_file = "volunteers.csv"

    # Mock all loading functions
    with patch('source.load_csv_participants', return_value=mock_participants_data), \
         patch('source.load_csv_inventory', return_value=mock_inventory_data), \
         patch('source.load_csv_volunteers', return_value=mock_volunteers_data), \
         patch('source.check_scheduling_conflicts', return_value=None), \
         patch('source.assign_volunteers', return_value=[{'volunteer': v, 'assigned_participants': []} for v in mock_volunteers_data]):

        # Execute with no config (should use defaults)
        result = process_bike_repair_workshop(
            workshop_date, location, participants_file, inventory_file,
            volunteers_file
        )

        # Assert
        assert result['status'] == 'success'
        assert result['statistics']['workshop_hours'] == 4  # Default value
        assert result['workshop_info']['is_online'] == False  # Default value

# Test online workshop format
def test_online_workshop_format(mock_participants_data, mock_inventory_data, mock_volunteers_data):
    # Setup
    workshop_date = "2023-06-15"
    location = "Virtual"
    participants_file = "participants.csv"
    inventory_file = "inventory.csv"
    volunteers_file = "volunteers.csv"
    online_config = {
        'max_participants': 30,  # Can handle more participants online
        'required_tools': ['wrench', 'screwdriver', 'pliers', 'pump', 'allen keys'],
        'workshop_hours': 2,
        'is_online': True
    }

    # Mock all loading functions
    with patch('source.load_csv_participants', return_value=mock_participants_data), \
         patch('source.load_csv_inventory', return_value=mock_inventory_data), \
         patch('source.load_csv_volunteers', return_value=mock_volunteers_data), \
         patch('source.check_scheduling_conflicts', return_value=None), \
         patch('source.assign_volunteers', return_value=[{'volunteer': v, 'assigned_participants': []} for v in mock_volunteers_data]):

        # Execute
        result = process_bike_repair_workshop(
            workshop_date, location, participants_file, inventory_file,
            volunteers_file, online_config
        )

        # Assert
        assert result['status'] == 'success'
        assert result['workshop_info']['is_online'] == True
        assert result['workshop_info']['location'] == "Virtual"


/* 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/. */

#ifndef nsCategoryCache_h_
#define nsCategoryCache_h_

#include "mozilla/Attributes.h"

#include "nsICategoryManager.h"
#include "nsIObserver.h"
#include "nsISimpleEnumerator.h"
#include "nsISupportsPrimitives.h"

#include "nsServiceManagerUtils.h"

#include "nsAutoPtr.h"
#include "nsCOMArray.h"
#include "nsInterfaceHashtable.h"

#include "nsXPCOM.h"

class NS_COM_GLUE nsCategoryObserver MOZ_FINAL : public nsIObserver
{
  public:
    nsCategoryObserver(const char* aCategory);
    ~nsCategoryObserver();

    void ListenerDied();
    nsInterfaceHashtable<nsCStringHashKey, nsISupports>& GetHash()
    {
      return mHash;
    }

    NS_DECL_ISUPPORTS
    NS_DECL_NSIOBSERVER
  private:
    void RemoveObservers();

    nsInterfaceHashtable<nsCStringHashKey, nsISupports> mHash;
    nsCString mCategory;
    bool mObserversRemoved;
};

/**
 * This is a helper class that caches services that are registered in a certain
 * category. The intended usage is that a service stores a variable of type
 * nsCategoryCache<nsIFoo> in a member variable, where nsIFoo is the interface
 * that these services should implement. The constructor of this class should
 * then get the name of the category.
 */
template<class T>
class nsCategoryCache MOZ_FINAL
{
  public:
    explicit nsCategoryCache(const char* aCategory)
      : mCategoryName(aCategory)
    {
    }
    ~nsCategoryCache() {
      if (mObserver)
	mObserver->ListenerDied();
    }

    void GetEntries(nsCOMArray<T>& result) {
      // Lazy initialization, so that services in this category can't
      // cause reentrant getService (bug 386376)
      if (!mObserver)
        mObserver = new nsCategoryObserver(mCategoryName.get());

      mObserver->GetHash().EnumerateRead(EntriesToArray, &result);
    }

  private:
    // Not to be implemented
    nsCategoryCache(const nsCategoryCache<T>&);

    static PLDHashOperator EntriesToArray(const nsACString& key,
					  nsISupports* entry, void* arg)
    {
      nsCOMArray<T>& entries = *static_cast<nsCOMArray<T>*>(arg);

      nsCOMPtr<T> service = do_QueryInterface(entry);
      if (service) {
	entries.AppendObject(service);
      }
      return PL_DHASH_NEXT;
    }

    nsCString mCategoryName;
    nsRefPtr<nsCategoryObserver> mObserver;

};

#endif


 {
          // assert(cp.normalImpulse == 0f)
          // System.out.println("contact normal impulse: " + cp.normalImpulse);
          vcp.normalImpulse = step.dtRatio * cp.normalImpulse
          vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse
        } else {
          vcp.normalImpulse = 0f
          vcp.tangentImpulse = 0f
        }
        vcp.rA.setZero()
        vcp.rB.setZero()
        vcp.normalMass = 0f
        vcp.tangentMass = 0f
        vcp.velocityBias = 0f
        pc.localPoints[j].x = cp.localPoint.x
        pc.localPoints[j].y = cp.localPoint.y
      }
    }
  }

  fun warmStart() {
    // Warm start.
    for (i in 0 until count) {
      val vc = velocityConstraints[i]
      val indexA = vc.indexA
      val indexB = vc.indexB
      val mA = vc.invMassA
      val iA = vc.invIA
      val mB = vc.invMassB
      val iB = vc.invIB
      val pointCount = vc.pointCount
      val vA = velocities[indexA].v
      var wA = velocities[indexA].w
      val vB = velocities[indexB].v
      var wB = velocities[indexB].w
      val normal = vc.normal
      val tangentx = 1.0f * normal.y
      val tangenty = -1.0f * normal.x
      for (j in 0 until pointCount) {
        val vcp = vc.points[j]
        val Px = tangentx * vcp.tangentImpulse + normal.x * vcp.normalImpulse
        val Py = tangenty * vcp.tangentImpulse + normal.y * vcp.normalImpulse
        wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px)
        vA.x -= Px * mA
        vA.y -= Py * mA
        wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px)
        vB.x += Px * mB
        vB.y += Py * mB
      }
      velocities[indexA].w = wA
      velocities[indexB].w = wB
    }
  }

  fun initializeVelocityConstraints() {
    // Warm start.
    for (i in 0 until count) {
      val vc = velocityConstraints[i]
      val pc = positionConstraints[i]
      val radiusA = pc.radiusA
      val radiusB = pc.radiusB
      val manifold = contacts[vc.contactIndex]!!.manifold
      val indexA = vc.indexA
      val indexB = vc.indexB
      val mA = vc.invMassA
      val mB = vc.invMassB
      val iA = vc.invIA
      val iB = vc.invIB
      val localCenterA = pc.localCenterA
      val localCenterB = pc.localCenterB
      val cA = positions[indexA].c
      val aA = positions[indexA].a
      val vA = velocities[indexA].v
      val wA = velocities[indexA].w
      val cB = positions[indexB].c
      val aB = positions[indexB].a
      val vB = velocities[indexB].v
      val wB = velocities[i


7c-2.7 7.5-4.1 15.6-4.1 24c0 13.3 10.7 24 24 24l176 0c13.3 0 24-10.7 24-24c0-8.4-1.4-16.5-4.1-24zM464 224a48 48 0 1 0 0-96 48 48 0 1 0 0 96zm-80-32a64 64 0 1 0 -128 0 64 64 0 1 0 128 0zM504 48l88 0 0 88c0 13.3 10.7 24 24 24s24-10.7 24-24l0-104c0-17.7-14.3-32-32-32L504 0c-13.3 0-24 10.7-24 24s10.7 24 24 24zM48 464l0-88c0-13.3-10.7-24-24-24s-24 10.7-24 24L0 480c0 17.7 14.3 32 32 32l104 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-88 0zm456 0c-13.3 0-24 10.7-24 24s10.7 24 24 24l104 0c17.7 0 32-14.3 32-32l0-104c0-13.3-10.7-24-24-24s-24 10.7-24 24l0 88-88 0z"],"file-video":[384,512,[],"f1c8","M64 0C28.7 0 0 28.7 0 64L0 448c0 35.3 28.7 64 64 64l256 0c35.3 0 64-28.7 64-64l0-288-128 0c-17.7 0-32-14.3-32-32L224 0 64 0zM256 0l0 128 128 0L256 0zM64 288c0-17.7 14.3-32 32-32l96 0c17.7 0 32 14.3 32 32l0 96c0 17.7-14.3 32-32 32l-96 0c-17.7 0-32-14.3-32-32l0-96zM300.9 397.9L256 368l0-64 44.9-29.9c2-1.3 4.4-2.1 6.8-2.1c6.8 0 12.3 5.5 12.3 12.3l0 103.4c0 6.8-5.5 12.3-12.3 12.3c-2.4 0-4.8-.7-6.8-2.1z"],"up-right-from-square":[512,512,["external-link-alt"],"f35d","M352 0c-12.9 0-24.6 7.8-29.6 19.8s-2.2 25.7 6.9 34.9L370.7 96 201.4 265.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L416 141.3l41.4 41.4c9.2 9.2 22.9 11.9 34.9 6.9s19.8-16.6 19.8-29.6l0-128c0-17.7-14.3-32-32-32L352 0zM80 32C35.8 32 0 67.8 0 112L0 432c0 44.2 35.8 80 80 80l320 0c44.2 0 80-35.8 80-80l0-112c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 112c0 8.8-7.2 16-16 16L80 448c-8.8 0-16-7.2-16-16l0-320c0-8.8 7.2-16 16-16l112 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L80 32z"],"table-cells":[512,512,["th"],"f00a","M64 32C28.7 32 0 60.


[[译] Instagram 是如何提升 TextView 渲染性能的？ (@archieyang)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fcodethink.me%2F2015%2F04%2F23%2Fimproving-comment-rendering-on-android%2F&aid=2173&nid=68)
[Android 应用内社区 SDK 技术架构浅析 (liubin)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fblog.umeng.com%2F%3Fp%3D4475&aid=2214&nid=69)
[Android 性能优化典范（第 2 季） (@胡凯me)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fhukai.me%2Fandroid-performance-patterns-season-2%2F&aid=2216&nid=69)
[系列译文：Android 的 MVP 模式开发 (shadev)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.jianshu.com%2Fp%2Ff60ce3cae7b5&aid=2217&nid=69)
[一个 Mac 上的 Android 工具 (mortenjust)](http://weekly.manong.io/bounce?url=https%3A%2F%2Fgithub.com%2Fmortenjust%2Fandroidtool-mac&aid=2232&nid=69)
[SquiDB - 一个用于 Android 的 SQLite 数据库框架](http://weekly.manong.io/bounce?url=https%3A%2F%2Fgithub.com%2Fyahoo%2Fsquidb&aid=2233&nid=69)
[系列译文：Android 研发工程师高级进阶 (asce1885)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fasce1885.gitbooks.io%2Fandroid-rd-senior-advanced%2Fcontent%2F&aid=2261&nid=70)
[Android 加载不同 DPI 资源与内存消耗之间的关系 (Will)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.tinylab.org%2Fandroid-loading-a-different-relationship-between-dpi-and-memory-consumption-of-resources%2F&aid=2262&nid=70)
[MaterialViewPager - 一个易于使用的 Material Design ViewPager 库 (florent37)](http://weekly.manong.io/bounce?url=https%3A%2F%2Fgithub.com%2Fflorent37%2FMaterialViewPager&aid=2290&nid=70)
[Android RecyclerView 使用完全解析 (鸿洋_)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fblog.csdn.net%2Flmj623565791%2Farticle%2Fdetails%2F45059587&aid=2318&nid=71)
[Android 中的 MVP (@鄭曉鵬-Rocko)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fzhengxiaopeng.com%2F2015%2F02%2F06%2FAndroid%25E4%2


    z-index: 1030
}

.border-white-color-40 {
    border-color: rgba(233,236,239,.4)!important
}

.border-dashed {
    border: 1px dashed #dfe3e8!important
}

.divider {
    display: flex;
    align-items: center
}

.divider:after,.divider:before {
    flex: 1 1;
    border-top: .0625rem solid #c4cdd5;
    content: "";
    margin-top: .0625rem
}

.divider:before {
    margin-right: 1.5rem
}

.divider:after {
    margin-left: 1.5rem
}

.icon-xxs {
    width: .875rem;
    height: .875rem;
    line-height: .875rem
}

.icon-xs {
    width: 1rem;
    height: 1rem;
    line-height: 1rem
}

.icon-sm {
    width: 1.5rem;
    height: 1.5rem;
    line-height: 1.5rem
}

.icon-md {
    width: 2.5rem;
    height: 2.5rem;
    line-height: 2.5rem
}

.icon-lg {
    width: 3rem;
    height: 3rem;
    line-height: 3rem
}

.icon-xl {
    width: 3.5rem;
    height: 3.5rem;
    line-height: 3.5rem
}

.icon-xxl {
    width: 4rem;
    height: 4rem;
    line-height: 4rem
}

.icon-shape {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    vertical-align: middle
}

.h1,.h2,.h3,.h4,h1,h2,h3,h4 {
    letter-spacing: -.02rem
}

.text-inherit {
    color: #161c24
}

.text-primary-hover:hover {
    color: #624bff!important
}

/*!
 * Bootstrap  v5.2.3 (https://getbootstrap.com/)
 * Copyright 2011-2022 The Bootstrap Authors
 * Copyright 2011-2022 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 */
:root {
    --bs-blue: #0d6efd;
    --bs-indigo: #6610f2;
    --bs-purple: #6f42c1;
    --bs-pink: #d63384;
    --bs-red: #dc3545;
    --bs-orange: #fd7e14;
    --bs-yellow: #f59e0b;
    --bs-green: #198754;
    --bs-teal: #20c997;
    --bs-cyan: #0ea5e9;
    --bs-black: #000;
    --bs-gray: #637381;
    --bs-gray-dark: #212b36;
    --bs-gray-100: #f1f5f9;
    --bs-gray-200: #f4f6f8;
    --bs-gray-300: #dfe3e8;
    --bs-gray-400: #c4cdd5;
    --bs-gray-500: #919eab;
    --bs-gray-600: #637381;
    --bs-gray-700: #454f5b;
    --bs-gray-800: #212b36;
    --bs-gray-900: #161c24;
    --bs-primary: #624bff;
    --bs-secondary: #637381;
    --bs-success: #198754;
    --bs-info: #0ea5e9;
    --bs-warning: #f59e0b;
    --bs-danger: #dc3545;
    --bs-l


                               icon: Icon(
                                      Icons.cloud_upload,
                                      size: ToPx.size(60),
                                      color: Colors.black87.withAlpha(50),
                                    ),
                                    onPressed: () => workorderDetailState.onPickFile(context),
                                  ),
                                  SizedBox(
                                    width: ToPx.size(25),
                                  ),
                                  SizedBox(
                                    width: ToPx.size(145),
                                    height: ToPx.size(65),
                                    child: RaisedButton(
                                        color: themeData.primaryColor,
                                        onPressed: workorderDetailState.reply,
                                        child: Text(
                                          "提交",
                                          style: TextStyle(color: Colors.white),
                                        )),
                                  )
                                ],
                              ),
                            )
                          ],
                        )
                      ],
                    ),
                  )
                ],
              );
            }

            Widget _loading() {
              return Center(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    SizedBox(
                width: ToPx.size(30),
                height: ToPx.size(30),
                child: Platform.isAndroid
                    ? CircularProgressIndicator(
                        strokeWidth: 2.0,
                      )
                    : CupertinoActivityIndicator(
                        radius: 15.0,
                      )),
                      Text("\r\n加载中...", style: themeData.textTheme.caption,)
                ]
              ),
              );
            }

            return Scaffold(
                backgroundColor: Colors.white,
                appBar: customAppBar(
                    title: Text(
                      "工单详情",
                      style: themeData.textTheme.display1,
                    ),
                    actions: [
                      Offstage(
                        offstage: workOrder.status == 3 || workOrder.delete == 1,
                        child: Button(
                        height: ToPx.size(90),
                        useIosStyle: true,
                        color: Colors.transparent,
                        width: ToPx.size(150),
                        child: Text("关闭工单"),
                        onPressed: ()=>workorderDetailState.closeWorkOrder(context)),
                      ),
                      Offstage(
                        offstage: workOrder.status != 3 || workOrder.delete == 1,
                        child: Button(
                        height: ToPx.size(90),
                        useIosStyle: true,
                        color: Colors.transparent,
                        width: ToPx.size(150),
                        child: Text("删除工单"),
                        onPressed: ()=>workorderDetailState.deleteWorkOrder(context)),
                      )
                    ]),
                body: workorderDetailState.isLoading ?
                _loading() :
                Column(
                  children: <Widget>[
                    Expanded(
                        child: RefreshIndicator(
                        color: themeData.primaryColorLight,
                        backgroundColor: themeData.primaryColor,
                        onRefresh: () async{
                         await workOrderDetailProvide.getWorkOrder(_workOrder.id, isLoading: false);
                         await workOrderDetailProvide.getWorkOrderComments(_workOrder.id);
                          return true;
                        },
                        child: CustomScrollView(
                          physics: AlwaysScrollableScrollPhysics(),
                          controller: workorderDetailState.customScrollView,
                      slivers: <Widget>[
                        SliverToBoxAdapter(
                          child: Column(
                            children: <Widget>[
                            SizedBox(height: 10.0),
                            _lineBox(
                              label: "用户：",
                              content: "${workOrder.uNickname}"),
                            _lineBox(
                                label: "标题：",
                                content: "${workOrder.title}"),
                            _lineBox(
                                label: "内容：",
                                content: _html("${workOrder.content}")),
                            _lineBox(
                                label: "电话：",
                                content: "${workOrder.phone}"),
                            _line


="mrcp__server_8h.html#ae2506a09d094aca81e7bc9f2e5d3009b">mrcp_server.h

mrcp_server_rtp_settings_register()
: mrcp_server.h

mrcp_server_session_create()
: mrcp_server_session.h

mrcp_server_session_state_e
: mrcp_server_session.h

mrcp_server_session_t
: mrcp_server_session.h

mrcp_server_shutdown()
: mrcp_server.h

mrcp_server_signaling_agent_get()
: mrcp_server.h

mrcp_server_signaling_agent_register()
: mrcp_server.h

mrcp_server_signaling_message_process()
: mrcp_server_session.h

mrcp_server_start()
: mrcp_server.h

mrcp_server_t
: mrcp_server_types.h

mrcp_session_answer_create()
: mrcp_session_descriptor.h

mrcp_session_create()
: mrcp_session.h

mrcp_session_create_ex()
: mrcp_session.h

mrcp_session_descriptor_create()
: <a


 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 LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
 */
package net.ccbluex.liquidbounce.features.module.modules.movement

import net.ccbluex.liquidbounce.config.types.NamedChoice
import net.ccbluex.liquidbounce.event.events.BlockShapeEvent
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.features.module.Category
import net.ccbluex.liquidbounce.features.module.ClientModule
import net.ccbluex.liquidbounce.utils.block.getBlock
import net.minecraft.block.*
import net.minecraft.fluid.FluidState
import net.minecraft.fluid.Fluids
import net.minecraft.util.math.BlockPos
import net.minecraft.util.shape.VoxelShapes

/**
 * Anti hazards module
 *
 * Prevents you walking into blocks that might be malicious for you.
 */
object ModuleAvoidHazards : ClientModule("AvoidHazards", Category.MOVEMENT) {
    private val avoid by multiEnumChoice("Avoid", Avoid.entries)

    // Conflicts with AvoidHazards
    val cobWebs get() = Avoid.COBWEB in avoid

    @Suppress("MagicNumber")
    private val UNSAFE_BLOCK_CAP = Block.createCuboidShape(
        0.0,
        0.0,
        0.0,
        16.0,
        4.0,
        16.0
    )

    @Suppress("unused")
    val shapeHandler = handler<BlockShapeEvent> { event ->
        avoid.find { it.test(event.state.block, event.state.fluidState, event.pos) }?.let {
            event.shape = if (it.fullCube) VoxelShapes.fullCube() else UNSAFE_BLOCK_CAP
        }
    }

    private enum class Avoid(
        override val choiceName: String,
        val fullCube: Boolean = true,
        val test: (block: Block, fluidState: FluidState, pos: BlockPos) -> Boolean
    ) : NamedChoice {
        CACTI("Cacti", test = { block, _, _ ->
            block is CactusBlock
        }),
        BERRY_BUSH("BerryBush", test = { block, _, _ ->
            block is SweetBerryBushBlock
        }),
        FIRE("Fire", test = { block, _, _, ->
            block is FireBlock
        }),
        COBWEB("Cobwebs", test = { block, _, _, ->
            block is CobwebBlock
        }),
        PRESSURE_PLATES("PressurePlates", fullCube = false, test = { block, _, _ ->
            block is AbstractPressurePlateBlock
        }),
        MAGMA("MagmaBlocks", fullCube = false, test = { _, _, pos ->
            pos.down().getBlock() is MagmaBlock
        }),
        LAVA("Lava", test = { _, fluidState, _ ->
            fluidState.isOf(Fluids.LAVA) || fluidState.isOf(Fluids.FLOWING_LAVA)
        })
    }
}
/*
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
 *
 * Copyright (c) 2015 - 2025 CCBlueX
 *
 * LiquidBounce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LiquidBounce 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 LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
 */
package net.ccbluex.liquidbounce.features.module.modules.world

import net.ccblue


faces.StructExternal).name = [0, 0, 1];
  expect(p1.compare(p2)).toBeGreaterThan(0);
  expect(p2.compare(p1)).toBeLessThan(0);

  p1.set(-1, Person._NAME, 1);
  expect(p1.compare(p2)).toBeLessThan(0);
  expect(p2.compare(p1)).toBeGreaterThan(0);

  // Struct with compare function
  let a: Interfaces.Struct, b: Interfaces.Struct;
  a = new CompareStruct({value: 10});
  b = new CompareStruct({value: 100});
  expect(a.compare(b)).toBeGreaterThan(0);
 });
});

/*

// Test
let Person = Struct([
 {name: 'name', type: Types.Int32, length: 3},
 {name: 'age', type: Types.Uint8},
 {name: 'height', type: Types.Float64}
]);

let p : Interfaces.Struct = new Person({
 name: [1, 2, 3],
 age: 29,
 height: 160
});
console.log(p.get());
console.log(p.name);
p.name = [4, 5, 6];
console.log(p.get());
console.log(p.name);
p.age = 31;
console.log(p.age);
console.log(p.get());

p.set(100, Person._NAME, 2);
console.log(p.get(Person._NAME, 2));
console.log(p.get());
p.set([9, 9], Person._NAME);
console.log(p.get());

let p2: Interfaces.Struct = new Person();
console.log(p2.get());
p2.copyFrom(p);
console.log(p2.get());
p.height = 23.3;
console.log(p.get(), p2.get());

*/import {SqlClient} from 'msnodesqlv8'
import {DT, STAGING} from '../../../../tables'
import {DestinationHandler} from '../../destinationHandler'
import {AddressHandlerProps} from '../address'

const sql: SqlClient = require('msnodesqlv8');

export default class NamesHandler extends DestinationHandler {
  table: string;

  suffixes = [
    "JR", "SR", "II", "IV", "III", "V", "VI", "VII"
  ]

  constructor(props: AddressHandlerProps) {
    super(props);
    this.table = "dbo.DCT_Persons_Staging" // props.table;
  }

  import = (data:STAGING.DCT_PERSONS_STAGING[]) => {
    if (data.length > 0) {
      let query =  `INSERT INTO ${this.table} (${Object.keys(data[0]).map(k => k).join(",")}) VALUES `
      query += data.map(data => `(${Object.values(data).map(k => k).join(",")})`).join(",")

      const response = this.query(query);
      return new Promise((resolve, reject) => {
        response.then(res => resolve({response: res, data}));
        response.catch(err => reject(err));
      });
      // return query;
    }
    return "";
  }

  convert = (data: DT.ATYP | any) => {

    const name = this.splitName(data.ATY_NAME.replace(/\s+/g, " ").replace(/'/g, "''"));
    const timestamp = new Date().toISOString().replace("T", " ").replace("Z", "");

    const response = {
      spn: `'${data.ATY_BAR_NO}'`,
      firstname: `'${name.first}'`,
      middlename: `'${name.middle}'`,
      lastname: `'${name.last}'`,
      displayname: `'${data.ATY_NAME.replace(/\s+/g, " ").replace(/'/g, "''")}'`,
      sealedflag: `'N'`,
      corp: `'N'`,
      is_att


using System;

namespace OpenTK.Compute.OpenCL
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
    public readonly struct CLProgram : IEquatable<CLProgram>
    {
        public readonly IntPtr Handle;

        public CLProgram(IntPtr handle)
        {
            Handle = handle;
        }

        public bool Equals(CLProgram other)
        {
            return Handle.Equals(other.Handle);
        }

        public override bool Equals(object obj)
        {
            return obj is CLProgram other && Equals(other)


		void register() {
			Project proj = frame.getProject();
			proj.addProjectListener(this);
			menubar.setSimulateListener(this);
			menubar.setCircuitState(proj.getSimulator(), proj.getCircuitState());
		}

		@Override
		public void stateChangeRequested(Simulator sim, CircuitState state) {
			if (state != null)
				frame.getProject().setCircuitState(state);
		}
	}

	private Frame frame;
	private LogisimMenuBar menubar;
	private ArrayList<EnabledListener> listeners;
	private FileListener fileListener = new FileListener();
	private EditListener editListener = new EditListener();
	private ProjectMenuListener projectListener = new ProjectMenuListener();
	private SimulateMenuListener simulateListener = new SimulateMenuListener();

	public MenuListener(Frame frame, LogisimMenuBar menubar) {
		this.frame = frame;
		this.menubar = menubar;
		this.listeners = new ArrayList<EnabledListener>();
	}

	public void addEnabledListener(EnabledListener listener) {
		listeners.add(listener);
	}

	public void doAction(LogisimMenuItem item) {
		menubar.doAction(item);
	}

	private void fireEnableChanged() {
		for (EnabledListener listener : listeners) {
			listener.menuEnableChanged(this);
		}
	}

	LogisimMenuBar getMenuBar() {
		return menubar;
	}

	public boolean isEnabled(LogisimMenuItem item) {
		return menubar.isEnabled(item);
	}

	public void register(CardPanel mainPanel) {
		fileListener.register();
		editListener.register();
		projectListener.register();
		simulateListener.register();
	}

	public void removeEnabledListener(EnabledListener listener) {
		listeners.remove(listener);
	}

	public void setEditHandler(EditHandler handler) {
		editListener.setHandler(handler);
	}
}
/* Copyright (c) 2010, Carl Burch. License information is located in the
 * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */

package com.cburch.draw.shapes;

import com.cburch.draw.model.Handle;
import com.cburch.logisim.data.Location;

public class PolyUtil {
	public static class ClosestResult {
		private double dist;
		private Location loc;
		private Handle prevHandle;
		private Handle nextHandle;

		public double getDistanceSq() {
			return dist;
		}

		public Location getLocation() {
			return loc;
		}

		public Handle getNextHandle() {
			return nextHandle;
		}

		public Handle getPreviousHandle() {
			return prevHandle;
		}
	}

	public static ClosestResult getClosestPoint(Location loc, boolean closed, Handle[] hs) {
		int xq = loc.getX();
		int yq = loc.getY();
		ClosestResult ret = new ClosestResult();
		ret.dist = Double.MAX_VALUE;
		if (hs.length > 0) {
			Handle h0 = hs[0];
			int x0 = h0.getX();
			int y0 = h0.getY();
			int stop = closed ? hs.length : (hs.length - 1);
			for (int i = 0; i < stop; i++) {
				Handle h1 = hs[(i + 1) % hs.length];
				int x1 = h1.getX();
				int y1 = h1.getY();
				double d = LineUtil.ptDistSqSegment(x0, y0, x1, y1, xq, yq);
				if (d < ret.dist) {
					ret.dist = d;
					ret.prevHandle = h0;
					ret.nextHandle = h1;
				}
				h0 = h1;
				x0 = x1;
				y0 = y1;
			}
		}
		if (ret.dist == Double.MAX_VALUE


int tidx = an->get_track_count() - 1;
				an->track_set_path(tidx, path);

				Dictionary parent_xform_dict;
				Dictionary xform_dict;

				if (state.bones.has(bone)) {
					xform_dict = state.bones[bone].node;
				}

				Array parent_keyframes;
				if (sk->get_bone_parent(bone_idx) != -1) {
					String parent_name = sk->get_bone_name(sk->get_bone_parent(bone_idx));
					if (state.bones.has(parent_name)) {
						parent_xform_dict = state.bones[parent_name].node;
					}

					print_line("parent for " + bone + "? " + parent_name + " XFD: " + String(Variant(parent_xform_dict)));
					for (int k = 0; k < bone_tracks.size(); k++) {
						Dictionary d = bone_tracks[k];
						if (d["boneId"] == parent_name) {
							parent_keyframes = d["keyframes"];
							print_line("found keyframes");
							break;
						}
					}
				}

				print_line("BONE XFD " + String(Variant(xform_dict)));

				Array keyframes = bone_track["keyframes"];

				for (int k = 0; k < keyframes.size(); k++) {

					Dictionary key = keyframes[k];
					Transform xform = _get_transform_mixed(key, xform_dict);
					float time = key["keytime"];
					time = time / 1000.0;
#if 0
					if (parent_keyframes.size()) {
						//localize
						print_line(itos(k)+" localizate for: "+bone);

						float prev_kt=-1;
						float kt;
						int idx=0;

						for(int l=0;l<parent_keyframes.size();l++) {

							Dictionary d=parent_keyframes[l];
							kt=d["keytime"];
							kt=kt/1000.0;
							if (kt>time)
								break;
							prev_kt=kt;
							idx++;

						}

						Transform t;
						if (idx==0) {
							t=_get_transform_mixed(parent_keyframes[0],parent_xform_dict);
						} else if (idx==parent_keyframes.size()){
							t=_get_transform_mixed(parent_keyframes[idx-1],parent_xform_dict);
						} else {
							t=_get_transform_mixed(parent_keyframes[idx-1],parent_xform_dict);
							float d = (time-prev_kt)/(kt-prev_kt);
							if (d>0) {
								Transform t2=_get_transform_mixed(parent_keyframes[idx],parent_xform_dict);
								t=t.interpolate_with(t2,d);
							} else {
								print_line("exact: "+rtos(kt));
							}
						}

						xform = t.affine_inverse() * xform; //localize
					} else if (!parent_xform_dict.empty()) {
						Transform t = _get_transform(parent_xform_dict);
						xform = t.affine_inverse() * xform; //localize
					}
#endif

					xform = sk->get_bone_rest(bone_idx).affine_inverse() * xform;

					Quat q = xform.basis;
					q.normalize();
					Vector3 s = xform.basis.get_scale();
					Vector3 l = xform.origin;

					an->transform_track_insert_key(tidx, time, l, q, s);
				}
			}
		}

		ap->add_animation(_id(anim["id"]), an);
	}

	retur


 := backUpCronJob.Spec.JobTemplate.Spec.Template.Spec.Volumes[0].PersistentVolumeClaim.ClaimName
		if expectedBackupPvcName != cronJobPvcName {
			log.Println("CronJob '" + backUpCronJob.Name + "' doesn't have the expected PVC with name: '" + expectedBackupPvcName + "'. Waiting...")
			return false
		}

		cronJobVolumeMount := backUpCronJob.Spec.JobTemplate.Spec.Template.Spec.Containers[0].VolumeMounts[0].MountPath
		if expectedBackupVolumeMount != cronJobVolumeMount {
			log.Println("CronJob '" + backUpCronJob.Name + "' doesn't have the expected volume mount: '" + expectedBackupVolumeMount + "'. Waiting...")
			return false
		}

		return true

	}, time.Second*10, time.Second*5).Should(BeTrue())
}

func (r *SpecBackUpTest) thenCronJobSpecShouldHaveAnnotation(annotationKey, annotationValue string) bool {

	return Eventually(func() bool {

		kubegresResources, err := r.resourceRetriever.GetKubegresResources()
		if err != nil && !apierrors.IsNotFound(err) {
			log.Println("ERROR while retrieving Kubegres kubegresResources")
			return false
		}

		backUpCronJob := kubegresResources.BackUpCronJob
		if backUpCronJob.Name == "" {
			return false
		}

		if backUpCronJob.Spec.JobTemplate.Spec.Template.Annotations[annotationKey] == annotationValue {
			log.Println("The container of CronJob'" + backUpCronJob.Name + "' has the expected annotation with " +
				"key: '" + annotationKey + "' and value: '" + annotationValue + "' in its metadata.")
			return true
		}

		log.Println("The container of CronJob'" + backUpCronJob.Name + "' does NOT have the expected annotation with " +
			"key: '" + annotationKey + "' and value: '" + annotationValue + "' in its metadata. Waiting...")
		return false

	}, time.Second*10, time.Second*5).Should(BeTrue())
}

func (r *SpecBackUpTest) thenCronJobSpecShouldHaveEnvVar(envVarName, envVarVal string) bool {

	return Eventually(func() bool {

		kubegresResources, err := r.resourceRetriever.GetKubegresResources()
		if err != nil && !apierrors.IsNotFound(err) {
			log.Println("ERROR while retrieving Kubegres kubegresResources")
			return false
		}

		backUpCronJob := kubegresResources.BackUpCronJob
		if backUpCronJob.Name == "" {
			return false
		}

		for _, envVar := range backUpCronJob.Spec.JobTemplate.Spec.Template.Spec.Containers[0].Env {
			if envVar.Name == envVarName && envVar.Value == envVarVal {
				log.Println("The container of CronJob'" + backUpCronJob.Name + "' has the expected environment variable with " +
					"name: '" + envVarName + "' and value: '" + envVarVal + "' in its Spec.")
				return true
			}
		}

		log.Println("The container of CronJob'" + backUpCronJob.Name + "' does NOT have the expected environment variable with " +
			"name: '" + envVarName + "' and value: '" + envVarVal + "' in its Spec.")
		return false

	}, time.Second*10, time.Second*5).Should(BeTrue())
}
/*
Copyright 2023 Reactive Tech Limited.
"Reactive Tech Limited" is a company located in England, United Kingdom.
https://www.reactive-tech.io

Lead Developer: Alex Arica

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

    http://w


r_CheckTableComment_Error(txnOperator, systemMetricSqlStmtCuComment121, err)
			got := upg_system_metrics_sql_stmt_cu_comment.Upgrade(executor, uint32(0))
			require.Equal(t, err, got)
		},
	)

	// test upg_system_stmt_info_add_column_conn_id, case NotExist
	runtime.RunTest(
		sid,
		func(rt runtime.Runtime) {
			txnOperator := mock_frontend.NewMockTxnOperator(gomock.NewController(t))
			txnOperator.EXPECT().TxnOptions().Return(txn.TxnOptions{CN: sid}).AnyTimes()
			executor := MockExecutor_CheckTableColumn_NotExist(txnOperator)
			got := upg_system_stmt_info_add_column_conn_id.Upgrade(executor, uint32(0))
			require.Equal(t, nil, got)
		},
	)
	// test upg_system_stmt_info_add_column_conn_id, case Exist
	runtime.RunTest(
		sid,
		func(rt runtime.Runtime) {
			txnOperator := mock_frontend.NewMockTxnOperator(gomock.NewController(t))
			txnOperator.EXPECT().TxnOptions().Return(txn.TxnOptions{CN: sid}).AnyTimes()
			executor := MockExecutor_CheckTableColumn_Exist(txnOperator)
			got := upg_system_stmt_info_add_column_conn_id.Upgrade(executor, uint32(0))
			require.Equal(t, nil, got)
		},
	)
	// test upg_system_stmt_info_add_column_conn_id, case Error
	runtime.RunTest(
		sid,
		func(rt runtime.Runtime) {
			txnOperator := mock_frontend.NewMockTxnOperator(gomock.NewController(t))
			txnOperator.EXPECT().TxnOptions().Return(txn.TxnOptions{CN: sid}).AnyTimes()
			err := moerr.GetOkExpectedEOF()
			executor := MockExecutor_CheckTableColumn_Error(txnOperator, err)
			got := upg_system_stmt_info_add_column_conn_id.Upgrade(executor, uint32(0))
			require.Equal(t, err, got)
		},
	)

	// test upg_system_stmt_info_add_column_cu, case NotExist
	runtime.RunTest(
		sid,
		func(rt runtime.Runtime) {
			txnOperator := mock_frontend.NewMockTxnOperator(gomock.NewController(t))
			txnOperator.EXPECT().TxnOptions().Return(txn.TxnOptions{CN: sid}).AnyTimes()
			executor := MockExecutor_CheckTableColumn_NotExist(txnOperator)
			got := upg_system_stmt_info_add_column_cu.Upgrade(executor, uint32(0))
			require.Equal(t, nil, got)
		},
	)
	// test upg_system_stmt_info_add_column_cu, case Error
	runtime.RunTest(
		sid,
		func(rt runtime.Runtime) {
			txnOperator := mock_frontend.NewMockTxnOperator(gomock.NewController(t))
			txnOperator.EXPECT().TxnOptions().Return(txn.TxnOptions{CN: sid}).AnyTimes()
			err := moerr.GetOkExpectedEOF()
			executor := MockExecutor_CheckTableColumn_Error(txnOperator, err)
			got := upg_system_stmt_info_add_column_cu.Upgrade(executor, uint32(0))
			require.Equal(t, err, got)
		},
	)

}

func MockExecutor_CheckTableDefinitionExist(txnOperator *mock_frontend.MockTxnOperator) executor.TxnExecutor {
	const checkTableDefinitionPrefix = "SELECT reldatabase, relname, account_id FROM mo_catalog.mo_tables tbl"

	return executor.NewMemTxn


.storage.HTStorageAccess
import hiiragi283.ragium.api.storage.HTStorageAction
import hiiragi283.ragium.api.storage.capability.RagiumCapabilities
import hiiragi283.ragium.api.storage.energy.HTEnergyBattery
import hiiragi283.ragium.api.storage.holder.HTEnergyStorageHolder
import hiiragi283.ragium.api.storage.holder.HTItemSlotHolder
import hiiragi283.ragium.api.storage.item.HTItemSlot
import hiiragi283.ragium.api.storage.item.HTItemStorageStack
import hiiragi283.ragium.common.storage.energy.HTEnergyBatteryWrapper
import hiiragi283.ragium.common.storage.holder.HTSimpleEnergyStorageHolder
import hiiragi283.ragium.common.storage.holder.HTSimpleItemSlotHolder
import hiiragi283.ragium.common.storage.item.slot.HTItemStackSlot
import hiiragi283.ragium.common.variant.HTDeviceVariant
import hiiragi283.ragium.setup.RagiumMenuTypes
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.InteractionResult
import net.minecraft.world.entity.player.Player
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.phys.BlockHitResult
import net.neoforged.neoforge.common.util.TriState
import kotlin.math.min

sealed class HTEnergyNetworkAccessBlockEntity(variant: HTDeviceVariant, pos: BlockPos, state: BlockState) :
    HTDeviceBlockEntity(variant, pos, state) {
    private lateinit var battery: HTEnergyBattery

    override fun initializeEnergyStorage(listener: HTContentListener): HTEnergyStorageHolder? {
        battery = createEnergyStorage(listener)
        return HTSimpleEnergyStorageHolder.generic(null, battery)
    }

    protected abstract fun createEnergyStorage(listener: HTContentListener): HTEnergyBattery

    private lateinit var extractSlot: HTItemSlot
    private lateinit var insertSlot: HTItemSlot

    override fun initializeItemHandler(listener: HTContentListener): HTItemSlotHolder? {
        // extract
        extractSlot = HTItemStackSlot.create(
            listener,
            HTSlotHelper.getSlotPosX(2),
            HTSlotHelper.getSlotPosY(1),
            filter = { stack: HTItemStorageStack ->
                val battery: HTEnergyBattery = RagiumCapabilities.ENERGY.getCapabilitySlot(stack, 0) ?: return@create false
                !battery.isEmpty()
            },
        )
        // insert
        insertSlot = HTItemStackSlot.create(
            listener,
            HTSlotHelper.getSlotPosX(2),
            HTSlotHelper.getSlotPosY(1),
            filter = { stack: HTItemStorageStack ->
                val battery: HTEnergyBattery = RagiumCapabilities.ENERGY.getCapabilitySlot(stack, 0) ?: return@create false
                battery.getNeededAsInt() > 0
            },
        )
        return HTSimpleItemSlotHolder(null, listOf(extractSlot), listOf(extractSlot))
    }

    override fun onRightClicked(
        state: BlockState,
        level: Level,
        pos: BlockPos,
        player: Player,
        hitResult: BlockHitResult,
    ): InteractionResult = RagiumMenuTypes.ENERGY_NETWORK_ACCESS.openMenu(player, name, this, ::writeExtraContainerData)

    override fun actionServer(level: ServerLevel, pos: BlockPos, state: BlockState): Boolean {
        // 左のスロットから電力を吸い取る
        extractFromItem()
        // 右のスロットに電力を渡す
        receiveToItem()
        return false
    }

    private fun extractFromItem(): TriState {
        val stackIn: HTItemStorageStack = extractSlot.getStack()
        val energyIn: HTEnergyBattery = RagiumCapabilities.ENERGY.getCapabilitySlot(stackIn, 0)
            ?: return TriState.FALSE
        var to


License as published by the Free Software Foundation; either
 *     version 2.1 of the License, or (at your option) any later version.
 *
 *     This library is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *     Lesser General Public License for more details.
 *
 *     You should have received a copy of the GNU Lesser General Public
 *     License along with this library; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
 *     USA
 *
 *     Please contact Rosemoe by email 2073412493@qq.com if you need
 *     additional information or have any questions
 ******************************************************************************/

package io.github.rosemoe.sora.editor.ts.predicate.builtin

import com.itsaky.androidide.treesitter.TSQuery
import com.itsaky.androidide.treesitter.TSQueryMatch
import com.itsaky.androidide.treesitter.TSQueryPredicateStep.Type
import com.itsaky.androidide.treesitter.string.UTF16String
import io.github.rosemoe.sora.editor.ts.predicate.TsClientPredicateStep
import io.github.rosemoe.sora.text.Content

fun parametersMatch(
    predicate: List<TsClientPredicateStep>,
    types: Array<Type>
): Boolean {
    if (predicate.size == types.size) {
        for (i in types.indices) {
            if (predicate[i].predicateType != types[i]) {
                return false
            }
        }
        return true
    }
    return false
}

fun getCaptureContent(
    tsQuery: TSQuery,
    match: TSQueryMatch,
    captureName: String,
    text: CharSequence
) = match.captures.filter { tsQuery.getCaptureNameForId(it.index) == captureName }
    .map {
        val start = it.node.startByte / 2
        val end = it.node.endByte / 2
        when (text) {
            is UTF16String -> {
                text.subseqChars(start, end).use {
                    it.toString()
                }
            }

            is Content -> text.substring(start, end)
            else -> text.substring(start, end)
        }
    }/*******************************************************************************
 *    sora-editor - the awesome code editor for Android
 *    https://github.com/Rosemoe/sora-editor
 *    Copyright (C) 2020-2024  Rosemoe
 *
 *     This library is free software; you can redistribute it and/or
 *     modify it under the terms of the GNU Lesser General Public
 *     License as published by the Free Software Foundation; either
 *     version 2.1 of the License, or (at your option) any later version.
 *
 *     This library is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *     Lesser General Public License for more details.
 *
 *     You should have received a copy of the GNU Lesser General Public
 *     License along with this library; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
 *     USA
 *
 *     Please contact Rosemoe by email 2073412493@qq.com if you need
 *     additional information or have any questions
 ******************************************************************************/

package io.github.rosemoe.sora.utils

import android.content.Context
import android.widget.Toast
import androidx.annotation.StringRes

fun Context.toast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, text, duration).show()
}

fun Context.toast(@StringRes resId: Int, duration: Int = Toast.LENGTH_SHORT) {
    Toas


ror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)
    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)

*/

.cm-s-hopscotch.CodeMirror {background: #322931; color: #d5d3d5;}
.cm-s-hopscotch div.CodeMirror-selected {background: #433b42 !important;}
.cm-s-hopscotch .CodeMirror-gutters {background: #322931; border-right: 0px;}
.cm-s-hopscotch .CodeMirror-linenumber {color: #797379;}
.cm-s-hopscotch .CodeMirror-cursor {border-left: 1px solid #989498 !important;}

.cm-s-hopscotch span.cm-comment {color: #b33508;}
.cm-s-hopscotch span.cm-atom {color: #c85e7c;}
.cm-s-hopscotch span.cm-number {color: #c85e7c;}

.cm-s-hopscotch span.cm-property, .cm-s-hopscotch span.cm-attribute {color: #8fc13e;}
.cm-s-hopscotch span.cm-keyword {color: #dd464c;}
.cm-s-hopscotch span.cm-string {color: #fdcc59;}

.cm-s-hopscotch span.cm-variable {color: #8fc13e;}
.cm-s-hopscotch span.cm-variable-2 {color: #1290bf;}
.cm-s-hopscotch span.cm-def {color: #fd8b19;}
.cm-s-hopscotch span.cm-error {background: #dd464c; color: #989498;}
.cm-s-hopscotch span.cm-bracket {color: #d5d3d5;}
.cm-s-hopscotch span.cm-tag {color: #dd464c;}
.cm-s-hopscotch span.cm-link {color: #c85e7c;}

.cm-s-hopscotch .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
.cm-s-hopscotch .CodeMirror-activeline-background { background: #302020; }
.CodeMirror-merge {
  position: relative;
  border: 1px solid #ddd;
  white-space: pre;
}

.CodeMirror-merge, .CodeMirror-merge .CodeMirror {
  height: 350px;
}

.CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; }
.CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; }
.CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; }
.CodeMirror-merge-


Service(&_Scheduler_serviceDesc, srv)
}

func _Scheduler_Schedule_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(ScheduleRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(SchedulerServer).Schedule(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/stellar.services.scheduler.v1.Scheduler/Schedule",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(SchedulerServer).Schedule(ctx, req.(*ScheduleRequest))
	}
	return interceptor(ctx, in, info, handler)
}

var _Scheduler_serviceDesc = grpc.ServiceDesc{
	ServiceName: "stellar.services.scheduler.v1.Scheduler",
	HandlerType: (*SchedulerServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Schedule",
			Handler:    _Scheduler_Schedule_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "github.com/ehazlett/stellar/api/services/scheduler/v1/scheduler.proto",
}
package network

import (
	"context"
	"errors"
	"fmt"
	"net"
	"strings"

	"github.com/containerd/containerd/errdefs"
	api "github.com/ehazlett/stellar/api/services/network/v1"
	ptypes "github.com/gogo/protobuf/types"
	"github.com/sirupsen/logrus"
)

var (
	ErrNoAvailableIP = errors.New("IP allocation exhausted")
	// format: ips.<node>.<id>
	dsIPsKey = "ips.%s.%s"
)

func (s *service) AllocateIP(ctx context.Context, req *api.AllocateIPRequest) (*api.AllocateIPResponse, error) {
	c, err := s.client(s.agent.Self().Address)
	if err != nil {
		return nil, err
	}
	defer c.Close()

	reservedIPs, err := s.getIPs(ctx, req.Node)
	if err != nil {
		return nil, err
	}

	if ip, exists := reservedIPs[req.ID]; exists {
		return &api.AllocateIPResponse{
			IP:   ip.String(),
			Node: req.Node,
		}, nil
	}

	lookup := map[string]string{}
	for id, ip := range reservedIPs {
		lookup[ip.String()] = id
	}

	logrus.Debugf("allocating ip for %s", req.ID)
	ip, ipnet, err := net.ParseCIDR(req.SubnetCIDR)
	if err != nil {
		return nil, err
	}

	for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); nextIP(ip) {
		// filter out network, gateway and broadcast
		if !validIP(ip) {
			continue
		}
		if _, exists := lookup[ip.String()]; exists {
			// ip already reserved
			continue
		}
		ipKey := fmt.Sprintf(dsIPsKey, req.Node, req.ID)
		logrus.


Merge the new space into a.ranges[i-1].
		a.ranges[i-1].limit = r.limit
	} else if coalescesUp {
		// We have a neighbor at a higher address only and it borders us.
		// Merge the new space into a.ranges[i].
		a.ranges[i].base = r.base
	} else {
		// We may or may not have neighbors which don't border us.
		// Add the new range.
		if len(a.ranges)+1 > cap(a.ranges) {
			// Grow the array. Note that this leaks the old array, but since
			// we're doubling we have at most 2x waste. For a 1 TiB heap and
			// 4 MiB arenas which are all discontiguous (both very conservative
			// assumptions), this would waste at most 4 MiB of memory.
			oldRanges := a.ranges
			ranges := (*notInHeapSlice)(unsafe.Pointer(&a.ranges))
			ranges.len = len(oldRanges) + 1
			ranges.cap = cap(oldRanges) * 2
			ranges.array = (*notInHeap)(persistentalloc(unsafe.Sizeof(addrRange{})*uintptr(ranges.cap), sys.PtrSize, a.sysStat))

			// Copy in the old array, but make space for the new range.
			copy(a.ranges[:i], oldRanges[:i])
			copy(a.ranges[i+1:], oldRanges[i:])
		} else {
			a.ranges = a.ranges[:len(a.ranges)+1]
			copy(a.ranges[i+1:], a.ranges[i:])
		}
		a.ranges[i] = r
	}
	a.totalBytes += r.size()
}

// removeLast removes and returns the highest-addressed contiguous range
// of a, or the last nBytes of that range, whichever is smaller. If a is
// empty, it returns an empty range.
func (a *addrRanges) removeLast(nBytes uintptr) addrRange {
	if len(a.ranges) == 0 {
		return addrRange{}
	}
	r := a.ranges[len(a.ranges)-1]
	size := r.size()
	if size > nBytes {
		newEnd := r.limit.sub(nBytes)
		a.ranges[len(a.ranges)-1].limit = newEnd
		a.totalBytes -= nBytes
		return addrRange{newEnd, r.limit}
	}
	a.ranges = a.ranges[:len(a.ranges)-1]
	a.totalBytes -= size
	return r
}

// removeGreaterEqual removes the ranges of a which are above addr, and additionally
// splits any range containing addr.
func (a *addrRanges) removeGreaterEqual(addr uintptr) {
	pivot := a.findSucc(addr)
	if pivot == 0 {
		// addr is before all ranges in a.
		a.totalBytes = 0
		a.ranges = a.ranges[:0]
		return
	}
	removed := uintptr(0)
	for _, r := range a.ranges[pivot:] {
		removed += r.size()
	}
	if r := a.ranges[pivot-1]; r.contains(addr) {
		removed += r.size()
		r = r.removeGreaterEqual(addr)
		if r.size() == 0 {
			pivot--
		} else {
			removed -= r.size()
			a.ranges[pivot-1] = r
		}
	}
	a.ranges = a.ranges[:pivot]
	a.totalBytes -= removed
}

// cloneInto makes a deep clone of a's state into b, re-using
// b's ranges if able.
func (a *addrRanges) cloneInto(b *addrRanges) {
	if len(a.ranges) > cap(b.ranges) {
		// Grow the array.
		ranges := (*notInHeapSlice)(unsafe.Pointer(&b.ranges))
		ranges.len = 0
		ranges.cap = cap(a.ranges)
		ranges.array = (*notInHeap)(persistentalloc(unsafe.Sizeof(addrRange


* @param {Number} value 标记位
     */
    setFlags(value?: number): void;
    /**
     * 清除所有刷新标记
     */
    clearFlags(): void;
    /**
     * 设置/取消标志位
     * @param {Number} flags 标记位
     * @param {Boolean} enable 是否设置标记位
     */
    enableFlags(flags: number, enable: boolean): void;
    /**
     * 查询刷新标记
     * @param {Number} flags 标记位
     * @return {Boolean} 是否需要刷新
     */
    hasFlags(flags: number): boolean;
    /**
     * 是否存在任一标记
     * @return {Boolean}
     */
    hasAnyFlags(): boolean;
}
import * as nodemailer from 'nodemailer';
import Email = require('email-templates');

const env = process.env.NODE_ENV || 'development';

export interface EmailOptions {
    destinationEmail: string;
    template: string;
    localValues: { [key: string]: string };
    attachments?: { name: string, content: string }[];
}

const createTransporter = () => {
    return nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: process.env.EMAIL_USERNAME,
            pass: process.env.EMAIL_PASSWORD
        }
    });
};

export const sendEmail = (emailOptions: EmailOptions) => {
    const transporter = createTransporter();

    const email = new Email({
        message: {
            from: process.env.EMAIL_USERNAME,
            attachments: emailOptions.attachments
        },
        send: true,
        transport: transporter,
        subjectPrefix: env === 'production' ? false : `[${env.toUpperCase()}] `
    });

    email
        .send({
            template: emailOptions.template,
            message: {
                to: emailOptions.destinationEmail
            },
            locals: emailOptions.localValues
        })
        .then((result) => {
            console.log('Email sent to ', emailOptions.destinationEmail);
        })
        .catch((err) => {
            console.error('Email not sent', err);
        });
};
import { GameCoreService } from '../../core/GameCore';
import { CellState, GameState } from '../../models/Game';

describe("MATRIX", ()=>{
  test('Create new Game and Win', () => {
    // const mockFn = (amountOfMines: number, rows: number, columns: number) => ;
    const game = new GameCoreService();
    jest.spyOn(game, "generateRandomMineCells").mockReturnValue([{ x: 2, y: 3 }]);
    const newGame = game.createNewGame(1, 4, 4, "aa");
    console.log(game.generateRandomMineCells(1,2,3))
    game.clickCell(newGame, 0, 0);
    game.clickCell(newGame, 1, 0);
    game.clickCell(newGame, 3, 3);
    expect(newGame.state).toEqual(GameState.Won);
  });
  test('Create new Game and lose', () => {
    // const mockFn = (amountOfMines: number, rows: number, columns: number) => ;
    const game = new GameCoreService();
    jest.spyOn(game, "generateRandomMineCells").mockReturnValue([{ x: 2, y: 3 }]);
    const newGame = game.createNewGame(1, 4, 4, "aa");
    console.log(game.generateRandomMineCells(1,2,3))
    game.clickCell(newGame, 2, 3);
    expect(newGame.state).toEqual(GameState.Lost);
  });
  test('Create new Game and flag one cell, in progress. Cell flagged not checked.', () => {
    // const mockFn = (amountOfMines: number, rows: number, columns: number) => ;
    const game = new GameCoreService();
    jest.spyOn(game, "generateRandomMineCells").mockReturnValue([{ x: 2, y: 3 }]);
    const


function replacetext()
  scale = tonumber(SKIN:GetVariable('Scale'))
  text= string.upper(SKIN:GetMeasure('MeasureWeekDay'):GetStringValue())
  font = SELF:GetOption('FontFace')
  fontsize = SKIN:ParseFormula('('..SELF:GetOption('FontSize')..')')
  realFontSize = math.ceil(fontsize*100/70)
  X = 55*scale
  Y = 190*scale
  file = io.open(SKIN:MakePathAbsolute(SELF:GetOption("SVGfile")), "w")
  template={
    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
    "<svg",
    "xmlns:dc=\"http://purl.org/dc/elements/1.1/\"",
    "xmlns:cc=\"http://creativecommons.org/ns#\"",
    "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"",
    "xmlns:svg=\"http://www.w3.org/2000/svg\"",
    "xmlns=\"http://www.w3.org/2000/svg\"",
    "version=\"1.1\"",
    "width=\"1920\"",
    "height=\"10


.)
	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(payload.TokenId), zt.TokenBitWidth)...)
	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(payload.ProxyId), zt.AccountBitWidth)...)
	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(payload.TargetId), zt.AccountBitWidth)...)

	copy(binaryData, pubData)

	return &zt.ZkMsg{
		First:  setBeBitsToVal(binaryData[:zt.MsgFirstWidth]),
		Second: setBeBitsToVal(binaryData[zt.MsgFirstWidth : zt.MsgFirstWidth+zt.MsgSecondWidth]),
		Third:  setBeBitsToVal(binaryData[zt.MsgFirstWidth+zt.MsgSecondWidth:]),
	}

}

func GetSetPubKeyMsg(payload *zt.ZkSetPubKey) *zt.ZkMsg {
	var pubData []uint

	binaryData := make([]uint, zt.MsgWidth)

	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(zt.TySetPubKeyAction), zt.TxTypeBitWidth)...)
	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(payload.AccountId), zt.AccountBitWidth)...)
	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(payload.PubKeyTy), zt.TxTypeBitWidth)...)

	pubKeyX, _ := new(big.Int).SetString(payload.PubKey.X, 10)
	pubData = append(pubData, getBigEndBitsWithFixLen(pubKeyX, zt.PubKeyBitWidth)...)
	pubKeyY, _ := new(big.Int).SetString(payload.PubKey.Y, 10)
	pubData = append(pubData, getBigEndBitsWithFixLen(pubKeyY, zt.PubKeyBitWidth)...)

	copy(binaryData, pubData)

	return &zt.ZkMsg{
		First:  setBeBitsToVal(binaryData[:zt.MsgFirstWidth]),
		Second: setBeBitsToVal(binaryData[zt.MsgFirstWidth : zt.MsgFirstWidth+zt.MsgSecondWidth]),
		Third:  setBeBitsToVal(binaryData[zt.MsgFirstWidth+zt.MsgSecondWidth:]),
	}

}

func GetFullExitMsg(payload *zt.ZkFullExit) *zt.ZkMsg {
	var pubData []uint

	binaryData := make([]uint, zt.MsgWidth)

	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(zt.TyFullExitAction), zt.TxTypeBitWidth)...)
	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(payload.TokenId), zt.TokenBitWidth)...)
	pubData = append(pubData, getBigEndBitsWithFixLen(new(big.Int).SetUint64(payload.AccountId), zt.AccountBitWidth)...)

	copy(binaryData, pubData)

	return &zt.ZkMsg{
		First:  setBeBitsToVal(binaryData[:zt.MsgFirstWidth]),
		Second: setBeBitsToVal(binaryData[zt.MsgFirstWidth : zt.MsgFirstWidth+zt.MsgSecondWidth]),
		Third:  setBeBitsToVal(binaryData[zt.MsgFirstWidth+zt.MsgSecondWidth:]),
	}

}

func GetMintNFTMsg(payload *zt.ZkMintNFT) *zt.ZkMsg {
	var pubData []uint

	binaryData := make([]uint, zt.MsgWidth)

	part1, part2, _, err := zt.SplitNFTContent(payload.ContentHash)
	if err != nil {
		fmt.Println(fmt.Sprintf("split content hash=%s wrong", payload.ContentHash))
		panic(err)
	}


using TorchSharp;
using TorchSharp.Modules;
using static TorchSharp.torch;
using static TorchSharp.torch.nn;

namespace NeuralCodecs.Torch.Modules.DAC;

public class WNConv2d : Module<Tensor, Tensor>
{
    /// <summary>
    /// Stride for the convolution operation
    /// </summary>
    private readonly (long, long) _stride;

    /// <summary>
    /// Padding applied to input before convolution
    /// </summary>
    private readonly (long, long) _padding;

    /// <summary>
    /// Dilation factor for the convolution
    /// </summary>
    private readonly long _dilation;

    /// <summary>
    /// Number of groups for grouped convolution
    /// </summary>
    private readonly long _groups;

    public WNConv2d(
        long inChannels,
        long outChannels,
        (long, long) kernelSize,
        (long, long) stride = default,
        (long, long) padding = default,
        long dilation = 1,
        long groups = 1,
        bool useBias = true,
        Device device = null) : base($"WNConv2d_{inChannels}_{outChannels}")
    {
        if (stride == default)
        {
            stride = (1, 1);
        }

        if (padding == default)
        {
            padding = (0, 0);
        }

        device ??= torch.CPU;

        _stride = stride;
        _padding = padding;
        _dilation = dilation;
        _groups = groups;

        weight_g = Parameter(
            ones([1, outChannels / groups, 1, 1],
                 dtype: float32,
                 device: device));

        weight_v = Parameter(
            empty([outChannels, inChannels / groups, kernelSize.Item1, kernelSize.Item2],
                  dtype: float32,
                  device: device));

        if (useBias)
        {
            bias = new Parameter(empty(outChannels, dtype: float32));
        }

        RegisterComponents();
        ResetParameters(useBias);
    }

    /// <summary>
    /// The learnable bias parameter for the convolution layer.
    /// Only available when useBias is set to true during initialization.
    /// </summary>
    public readonly Parameter bias;

    /// <summary>
    /// The gain parameter (g) used in weight normalization.
    /// Represents the magnitude/scale of the normalized weight vectors.
    /// </summary>
    public readonly Parameter weight_g;

    /// <summary>
    /// The directional weight parameter (v) used in weight normalization.
    /// Represents the direction of the weight vectors bef


/*!
 * Copyright 2021 Cognite AS
 */

import * as THREE from 'three';
import { ParsePrimitiveAttribute } from '@cognite/reveal-parser-worker';

import {
  filterPrimitivesOutsideClipBoxByBaseBoundsAndInstanceMatrix,
  filterPrimitivesOutsideClipBoxByCenterAndRadius,
  filterPrimitivesOutsideClipBoxByEllipse,
  filterPrimitivesOutsideClipBoxByVertices
} from './filterPrimitives';

describe('filterPrimitivesOutsideClipBoxByCenterAndRadius', () => {
  let attributes: Map<string, ParsePrimitiveAttribute>;

  beforeEach(() => {
    attributes = new Map<string, ParsePrimitiveAttribute>([
      ['centerA', { offset: 0, size: 3 * 4 }],
      ['radiusA', { offset: 12, size: 4 }],
      ['centerB', { offset: 16, size: 3 * 4 }],
      ['radiusB', { offset: 28, size: 4 }]
    ]);
  });

  test('no clipbox, returns original', () => {
    const original = new Uint8Array(32);
    const filtered = filterPrimitivesOutsideClipBoxByCenterAndRadius(original, attributes, null);
    expect(filtered).toBe(original);
  });

  test('one accepted, one reject - returns filtered', () => {
    // Arrange
    const original = new Float32Array([
      // Element 1
      ...createElement([0, 0, 0], 1),
      ...createElement([2, 2, 2], 1),
      // Element 2
      ...createElement([10, 10, 10], 1),
      ...createElement([11, 11, 11], 1)
    ]);
    const bytes = new Uint8Array(original.buffer);
    const clipBox = new THREE.Box3(new THREE.Vector3(0, 0, 0), new THREE.Vector3(2, 2, 2));

    const filtered = filterPrimitivesOutsideClipBoxByCenterAndRadius(bytes, attributes, clipBox);
    const filteredFloats = new Float32Array(filtered.buffer);
    expect(filteredFloats).toEqual(original.subarray(0, original.length / 2));
  });

  function createElement(center: [number, number, number], radius: number): [number, number, number, number] {
    return [...center, radius];
  }
});

describe('filterPrimitivesOutsideClipBoxByVertices', () => {
  let attributes: Map<string, ParsePrimitiveAttribute>;

  beforeEach(() => {
    attributes = new Map<string, ParsePrimitiveAttribute>([
      ['vertex1', { offset: 0, size: 3 * 4 }],
      ['vertex2', { offset: 12, size: 3 * 4 }],
      ['vertex3', { offset: 24, size: 3 * 4 }],
      ['vertex4', { offset: 36, size: 3 * 4 }]
    ]);
  });

  test('no clipbox, returns original', () => {
    const original = new Uint8Array(48);
    const filtered = filterPrimitivesOutsideClipBoxByVertices(original, attributes, null);
    expect(filtered).toBe(original);
  });

  test('one accepted, one reject - returns filtered', () => {
    // Arrange
    const original = new Float32Array([
      // Element 1
      ...[1, 1, 1],
      ...[2, 2, 2],
      ...[3, 3, 3],
      ...[4, 4, 4],
      // Element 2
      ...[11, 11, 11],
      ...[12, 12, 12],
      ...[13, 13, 13],
      ...[14, 14, 14]
    ]);
    const bytes = new Uint8Array(original.buffer);
    const clipBox = new THREE.Box3(new THREE.Vector3(0, 0, 0), new THREE.Vector3(2, 2, 2));

    const filtered = filterPrimitivesOutsideClipBoxByVertices(bytes, attributes, clipBox);
    const filteredFloats = new Float32Array(filtered.buffer);
    expect(filteredFloats).toEqual(original.subarray(0, original.length / 2));


ns true if the image has a format that respects the alpha channel, otherwise returns false.

See also Image Information.
*/
func (this *QImage) HasAlphaChannel() bool {
	rv, err := qtrt.InvokeQtFunc6("_ZNK6QImage15hasAlphaChannelEv", qtrt.FFI_TYPE_POINTER, this.GetCthis())
	qtrt.ErrPrint(err, rv)
	return rv != 0
}

// /usr/include/qt/QtGui/qimage.h:266
// index:0
// Public Visibility=Default Availability=Available
// [-2] void setAlphaChannel(const QImage &)

/*

 */
func (this *QImage) SetAlphaChannel(alphaChannel QImage_ITF) {
	var convArg0 unsafe.Pointer
	if alphaChannel != nil && alphaChannel.QImage_PTR() != nil {
		convArg0 = alphaChannel.QImage_PTR().GetCthis()
	}
	rv, err := qtrt.InvokeQtFunc6("_ZN6QImage15setAlphaChannelERKS_", qtrt.FFI_TYPE_POINTER, this.GetCthis(), convArg0)
	qtrt.ErrPrint(err, rv)
}

// /usr/include/qt/QtGui/qimage.h:267
// index:0
// Public Visibility=Default Availability=Available
// [32] QImage alphaChannel() const

/*

 */
func (this *QImage) AlphaChannel() *QImage /*123*/ {
	rv, err := qtrt.InvokeQtFunc6("_ZNK6QImage12alphaChannelEv", qtrt.FFI_TYPE_POINTER, this.GetCthis())
	qtrt.ErrPrint(err, rv)
	rv2 := /*==*/ NewQImageFromPointer(unsafe.Pointer(uintptr(rv))) // 333
	qtrt.SetFinalizer(rv2 /*==*/, DeleteQImage)
	return rv2
}

// /usr/include/qt/QtGui/qimage.h:268
// index:0
// Public Visibility=Default Availability=Available
// [32] QImage createAlphaMask(Qt::ImageConversionFlags) const

/*
Builds and returns a 1-bpp mask from the alpha buffer in this image. Returns a null image if the image's format is QImage::Format_RGB32.

The flags argument is a bitwise-OR of the Qt::ImageConversionFlags, and controls the conversion process. Passing 0 for flags sets all the default options.

The returned image has little-endian bit order (i.e. the image's format is QImage::Format_MonoLSB), which you can convert to big-endian (QImage::Format_Mono) using the convertToFormat() function.

See also createHeuristicMask() and Image Transformations.
*/
func (this *QImage) CreateAlphaMask(flags int) *QImage /*123*/ {
	rv, err := qtrt.InvokeQtFunc6("_ZNK6QImage15createAlphaMaskE6QFlagsIN2Qt19ImageConversionFlagEE", qtrt.FFI_TYPE_POINTER, this.GetCthis(), flags)
	qtrt.ErrPrint(err, rv)
	rv2 := /*==*/ NewQImageFromPointer(unsafe.Pointer(uintptr(rv))) // 333
	qtrt.SetFinalizer(rv2 /*==*/, DeleteQImage)
	return rv2
}

// /usr/include/qt/QtGui/qimage.h:268
// index:0
// Public Visibility=Default Availability=Available
// [32] QImage createAlphaMask(Qt::ImageConversionFlags) const

/*
Builds and returns a 1-bpp mask from the alpha buffer in this image. Returns a null image if the image's format is QImage::Format_RGB32.

The flags argument is a bitwise-OR of the Qt::ImageConversionFlags, and controls the conversion process. Passing 0 for flags sets all the default options.

The returned image has little-endian bit order (i.e. the image's format is QImage::Format_MonoLSB), which you can convert to big-endian (QImage::Format_Mono) using the convertToFormat() function.

See also createHeuristicMask() and Image Transformations.
*/
func (this *


ocument">Indicates whether the entity set is advertised in the service document.</param>
        public EdmEntitySet(IEdmEntityContainer container, string name, IEdmEntityType elementType, bool includeInServiceDocument)
            : base(name, elementType)
        {
            EdmUtil.CheckArgumentNull(container, "container");

            this.container = container;
            this.type = new EdmCollectionType(new EdmEntityTypeReference(elementType, false));
            this.path = new EdmPathExpression(name);
            this.includeInServiceDocument = includeInServiceDocument;
        }

        /// <summary>
        /// Gets the kind of element of this container element.
        /// </summary>
        public EdmContainerElementKind ContainerElementKind
        {
            get { return EdmContainerElementKind.EntitySet; }
        }

        /// <summary>
        /// Gets the container of this entity set.
        /// </summary>
        public IEdmEntityContainer Container
        {
            get { return this.container; }
        }

        /// <summary>
        /// Gets the type of this entity set.
        /// </summary>
        public override IEdmType Type
        {
            get { return this.type; }
        }

        /// <summary>
        /// Gets the path that a navigation property targets.
        /// </summary>
        public override IEdmPathExpression Path
        {
            get { return this.path; }
        }

        /// <summary>
        /// Gets a value indicating whether the entity set is included in the service document.
        /// </summary>
        public bool IncludeInServiceDocument
        {
            get { return includeInServiceDocument; }
        }
    }
}


_GENA_ACTCMPAU_ZERO => 2,
            PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_ONE => 3,
        }
    }
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline(always)]
    pub fn _from(value: u8) -> PWM_1_GENA_ACTCMPAUR {
        match value {
            0 => PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_NONE,
            1 => PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_INV,
            2 => PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_ZERO,
            3 => PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_ONE,
            _ => unreachable!(),
        }
    }
    #[doc = "Checks if the value of the field is `PWM_1_GENA_ACTCMPAU_NONE`"]
    #[inline(always)]
    pub fn is_pwm_1_gena_actcmpau_none(&self) -> bool {
        *self == PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_NONE
    }
    #[doc = "Checks if the value of the field is `PWM_1_GENA_ACTCMPAU_INV`"]
    #[inline(always)]
    pub fn is_pwm_1_gena_actcmpau_inv(&self) -> bool {
        *self == PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_INV
    }
    #[doc = "Checks if the value of the field is `PWM_1_GENA_ACTCMPAU_ZERO`"]
    #[inline(always)]
    pub fn is_pwm_1_gena_actcmpau_zero(&self) -> bool {
        *self == PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_ZERO
    }
    #[doc = "Checks if the value of the field is `PWM_1_GENA_ACTCMPAU_ONE`"]
    #[inline(always)]
    pub fn is_pwm_1_gena_actcmpau_one(&self) -> bool {
        *self == PWM_1_GENA_ACTCMPAUR::PWM_1_GENA_ACTCMPAU_ONE
    }
}
#[doc = "Values that can be written to the field `PWM_1_GENA_ACTCMPAU`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_1_GENA_ACTCMPAUW {
    #[doc = "Do nothing"]
    PWM_1_GENA_ACTCMPAU_NONE,
    #[doc = "Invert pwmA"]
    PWM_1_GENA_ACTCMPAU_INV,
    #[doc = "Drive pwmA Low"]
    PWM_1_GENA_ACTCMPAU_ZERO,
    #[doc = "Drive pwmA High"]
    PWM_1_GENA_ACTCMPAU_ONE,
}
impl PWM_1_GENA_ACTCMPAUW {
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline(always)]
    pub fn _bits(&self) -> u8 {
        match *self {
            PWM_1_GENA_ACTCMPAUW::PWM_1_GENA_ACTCMPAU_NONE => 0,
            PWM_1_GENA_ACTCMPAUW::PWM_1_GENA_ACTCMPAU_INV => 1,
            PWM_1_GENA_ACTCMP


# coding=utf-8
# Copyright 2024 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

import torch

from diffusers import DDIMScheduler, DDPMScheduler, UNet2DModel
from diffusers.training_utils import set_seed
from diffusers.utils.testing_utils import slow

torch.backends.cuda.matmul.allow_tf32 = False

class TrainingTests(unittest.TestCase):
    def get_model_optimizer(self, resolution=32):
        set_seed(0)
        model = UNet2DModel(sample_size=resolution, in_channels=3, out_channels=3)
        optimizer = torch.optim.SGD(model.parameters(), lr=0.0001)
        return model, optimizer

    @slow
    def test_training_step_equality(self):
        device = "cpu"  # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable
        ddpm_scheduler = DDPMScheduler(
            num_train_timesteps=1000,
            beta_start=0.0001,
            beta_end=0.02,
            beta_schedule="linear",
            clip_sample=True,
        )
        ddim_scheduler = DDIMScheduler(
            num_train_timesteps=1000,
            beta_start=0.0001,
            beta_end=0.02,
            beta_schedule="linear",
            clip_sample=True,
        )

        assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps

        # shared batches for DDPM and DDIM
        set_seed(0)
        clean_images = [torch.randn((4, 3, 32, 32)).clip(-1, 1).to(device) for _ in range(4)]
        noise = [torch.randn((4, 3, 32, 32)).to(device) for _ in range(4)]
        timesteps = [torch.randint(0, 1000, (4,)).long().to(device) for _ in range(4)]

        # train with a DDPM scheduler
        model, optimizer = self.get_model_optimizer(resolution=32)
        model.train().to(device)
        for i in range(4):
            optimizer.zero_grad()
            ddpm_noisy_images = ddpm_scheduler.add_noise(clean_images[i], noise[i], timesteps[i])
            ddpm_noise_pred = model(ddpm_noisy_images, timesteps[i]).sample
            loss = torch.nn.functional.mse_loss(ddpm_noise_pred, noise[i])
            loss.backward()
            optimizer.step()
        del model, optimizer

        # recreate the model and optimizer, and retry with DDIM
        model, optimizer = self.get_model_optimizer(resolution=32)
        model.train().to(device)
        for i in range(4):
            optimizer.zero_grad()
            ddim_noisy_images = ddim_scheduler.add_noise(clean_images[i], noise[i], timesteps[i])
            ddim_noise_pred = model(ddim_noisy_images, timesteps[i]).sample
            loss = torch.nn.functional.mse_loss(ddim_noise_pred, noise[i])
            loss.backward()
            optimizer.step()
        del model, optimizer

        self.assertTrue(torch.allclose(ddpm_noisy_images, ddim_noisy_images, atol=1e-5))
        self.assertTrue(torch.allclose(ddpm_noise_pred, ddim_noise_pred, atol=1e-5))


, 0.1, 0.8), make_vec3(0.6, 0.7, 0.8),  125.
    );
    Material red_rubber = make_Material(
       1.0, make_vec4(0.9,  0.1, 0.0, 0.0), make_vec3(0.3, 0.1, 0.1),   10.
    );
    Material mirror = make_Material(
       1.0, make_vec4(0.0, 10.0, 0.8, 0.0), make_vec3(1.0, 1.0, 1.0),  142.
    );

    spheres[0] = make_Sphere(make_vec3(-3,    0,   -16), 2,      ivory);
    spheres[1] = make_Sphere(make_vec3(-1.0, -1.5, -12), 2,      glass);
    spheres[2] = make_Sphere(make_vec3( 1.5, -0.5, -18), 3, red_rubber);
    spheres[3] = make_Sphere(make_vec3( 7,    5,   -18), 4,     mirror);

    lights[0] = make_Light(make_vec3(-20, 20,  20), 1.5);
    lights[1] = make_Light(make_vec3( 30, 50, -25), 1.8);
    lights[2] = make_Light(make_vec3( 30, 20,  30), 1.7);
}

static void run_tinyraytracer(void) {
    printf("===== TINYRAYTRACER ====\n");
    init_scene();
    graphics_init();
    render(spheres, nb_spheres, lights, nb_lights);
    graphics_terminate();
}

int main(int argc, char** argv) {
   benchmark = 0;
   small = 0;
   if(argc == 2 && !strcmp(argv[1],"-benchmark")) {
      benchmark = 1;
   }
   if(argc == 2 && !strcmp(argv[1],"-small")) {
      small = 1;
   }
   run_tinyraytracer();
   return 0;
}