text
stringlengths
184
4.48M
'use client'; import React, { useEffect, useState } from 'react'; import { Formik, Form, Field } from 'formik'; import formatTime from '@/app/helpers/time'; import { loadState, saveState } from '@/app/helpers/presist'; interface Props { questionsData: Question[]; currentQuestionId: number; remainingTime: number; } export default function Quiz({ questionsData, currentQuestionId, remainingTime }: Props) { const [currentQuestion, setCurrentQuestion] = useState(currentQuestionId); const [time, setTime] = useState(remainingTime); useEffect(() => { saveState('currentQuestionId', currentQuestion); }, [currentQuestion]); useEffect(() => saveState('remainingTime', time), [time]); useEffect(() => { const intervalId = setInterval(() => { setTime(prevTime => prevTime - 1); }, 1000); return () => clearInterval(intervalId); }, []); const handleNextQuestion = (values: any) => { console.log('Answered:', values); setCurrentQuestion(prevQuestion => { saveState('currentQuestionId', prevQuestion + 1); saveState('userAnswersData', values); return prevQuestion + 1; }); }; const handleSubmit = (values: string[]) => { console.log('Submitted:', values); }; return ( <Formik initialValues={loadState('userAnswersData') || {}} onSubmit={values => { console.log('Submitted:', values); }} > {formik => ( <Form className="form-container"> <> <div className="quiz-header"> <h1 className="font-size-25 bold">Тестирование</h1> <div className="timer">{formatTime(time)}</div> </div> <QuestionsProgress count={questionsData.length} currentId={currentQuestion} /> <div> <h3 className="bold">{questionsData[currentQuestion].question}</h3> {questionsData[currentQuestion].variants ? ( questionsData[currentQuestion].variants.map((variant, index) => ( <label className="custom-radio" key={index}> <Field type={questionsData[currentQuestion].type === 'single' ? 'radio' : 'checkbox'} name={`question-${currentQuestion}`} value={variant} /> {variant && variant} </label> )) ) : ( <Field as={questionsData[currentQuestion].type === 'largetext' ? 'textarea' : 'input'} type={questionsData[currentQuestion].type === 'text' ? 'text' : 'textarea'} name={`question-${currentQuestion}`} /> )} </div> {currentQuestion === questionsData.length - 1 && ( <button type="submit" className="button"> Отправить ответы </button> )} {currentQuestion !== questionsData.length - 1 && ( <button type="button" onClick={() => handleNextQuestion(formik.values)} className="button" > Ответить </button> )} </> </Form> )} </Formik> ); } interface Question { question: string; variants: string[]; type: string; } const QuestionsProgress = ({ count, currentId }) => { const progressBar = []; for (let i = 0; i < count; i++) { const variant = i === currentId ? 'active' : i < currentId && 'passed'; progressBar.push(<div key={i} className={`question-mark ${variant}`}></div>); } return <div>{progressBar}</div>; };
import React, { useState, useEffect } from "react"; import { useQuery } from "react-query"; import axios from "axios"; const retrievePosts = async () => { const response = await axios.get("https://jsonplaceholder.typicode.com/posts"); return response.data; }; const AxiosUseQuery = () => { const [startTime, setStartTime] = useState(null); const [endTime, setEndTime] = useState(null); const { data: posts, error, isLoading, } = useQuery("postsData", async () => { setStartTime(performance.now()); const data = await retrievePosts(); setEndTime(performance.now()); return data; }); const fetchDuration = endTime ? `${(endTime - startTime).toFixed(2)} ms` : null; if (isLoading) return <div>Fetching projects ...</div>; if (error) return <div>An error occurred: {error.message}</div>; return ( <div> <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> {fetchDuration && <p>Fetch duration: {fetchDuration}</p>} </div> ); }; export default AxiosUseQuery;
// BinarySearch.jsx import React, { useState } from "react"; import VisualizeHeader from "../../../../Components/VisualizeHeader"; import "../../../../index.css"; import Description from "../../../../Components/Description"; import VisualizePageReplacement from "../../../Visualizations/VisualizePageReplacement"; const PageReplacement = () => { const [array, setArray] = useState("1 2 3 4 5"); const [inVisualize, setInVisualize] = useState(false); const [arrayValues, setArrayValues] = useState([]); const [message, setMessage] = useState(''); const [type,setType] = useState('fifo'); const [frameSize,setFrameSize] = useState(3); const handleArrayChange = (event) => { setArray(event.target.value); }; function getMessage(message){ setMessage(message); } const setArrayRight = () => { const arrayValues = array.split(" ").map(Number); if (arrayValues[arrayValues.length - 1] === 0) arrayValues.pop(-1); setArrayValues(arrayValues); setInVisualize(true); }; return ( <div className="bg-color h-screen"> <div className="max-w-[1200px] m-auto h-full"> <VisualizeHeader routePath="/dataStructure/linkedList" setInVisualize={setInVisualize} /> {inVisualize ? ( <div className="flex justify-around items-center h-[80%]"> <div className="border bg-input p-4 flex h-[80%] flex-col justify-between"> <div>Array : {arrayValues}</div> </div> <div className="w-[70%]"> <div className="w-full min-h-[350px] flex justify-center items-center bg-input p-4"> <VisualizePageReplacement arrayValues={arrayValues} getMessage={getMessage} type={type} setArrayValues = {setArrayValues} frameSize={frameSize} /> </div> <Description message={message}/> </div> </div> ) : ( <div className="mt-24 bg-input w-fit m-auto p-5"> <h1 className="card-heading text-3xl font-bold mb-4 flex flex-col items-center text-red-500 py-4"> Page Replacement Visualization </h1> <form className="mb-8 flex justify-center items-center flex-col space-y-4"> <div className="flex items-center space-x-2"> <label className="min-w-[170px] text-blue-500 card-heading"> Enter Elements: </label> <input type="text" value={array} onChange={handleArrayChange} className="bg-input border border-blue-500 rounded py-2 px-3 text-red-500" /> </div> <div className="flex items-center space-x-2"> <label className="min-w-[170px] text-blue-500 card-heading"> Enter Number Of Frames: </label> <input type="number" value={frameSize} onChange={(event)=>{setFrameSize(event.target.value)}} className="bg-input border border-blue-500 rounded py-2 px-3 text-red-500" /> </div> <div className="mb-8 flex items-center justify-center"> <label htmlFor="type" className="min-w-[170px] text-blue-500 card-heading">Type:</label> <select name="type" id="type" onChange={(event)=>setType(event.target.value)} className="border bg-input border-blue-500 rounded py-2 px-3 text-red-500"> <option value="fifo">FiFo</option> <option value="lru">Lru</option> <option value="optimal">Optimal</option> </select> </div> <div className="flex gap-2 py-4"> <button type="button" onClick={setArrayRight} className="bg-input hover:scale-110 hover:card-heading hover:shadow-[0_10px_20px_rgba(240,_46,_170,_0.7)] bg-blue-500 text-white py-2 px-4 rounded" > Visualize </button> </div> </form> </div> )} </div> </div> ); }; export default PageReplacement;
# Homeopathy Clinic Management System This project is a comprehensive management system for homeopathy clinics, developed using the Laravel framework. It streamlines various administrative and clinical processes, including patient registration, appointment scheduling, treatment history tracking, billing, and inventory management. The system features a user-friendly interface and robust backend, ensuring efficient and secure handling of patient data and clinic operations. With this tool, homeopathy clinics can enhance their service delivery, improve patient care, and optimize their workflow. ## Admin Module To-Do List ### User Management - **Create Admin Dashboard** - Overview of clinic statistics (appointments, patients, revenue, etc.) - **User Roles and Permissions** - Define roles (admin, doctor, receptionist, etc.) - Assign permissions based on roles - **Staff Management** - Add/edit/delete staff members - Assign roles and permissions ### Patient Management - **Patient Records** - Add/edit/delete patient details - View patient history and treatment records - **Appointment Management** - Schedule new appointments - Modify or cancel appointments - View appointment calendar ### Treatment Management - **Treatment Plans** - Create and manage treatment plans - Assign treatments to patients - Track treatment progress - **Medical Records** - Store and manage patient medical records - Ensure secure access to sensitive information ### Financial Management - **Billing and Invoicing** - Generate and manage invoices - Track payments and outstanding balances - **Expense Management** - Record clinic expenses - Generate expense reports ### Inventory Management - **Inventory Tracking** - Manage homeopathy medicines and supplies - Track stock levels and expiry dates - **Order Management** - Place and track orders for supplies - Manage suppliers and vendors ### Reporting and Analytics - **Generate Reports** - Patient reports - Financial reports - Inventory reports - **Data Analytics** - Analyze clinic performance metrics - Identify trends and make data-driven decisions ### System Configuration - **Settings and Configurations** - Manage clinic details (name, address, contact information) - Configure system settings (working hours, appointment durations, etc.) - **Notification Management** - Set up email/SMS notifications for appointments, payments, etc. - Configure reminders for patients and staff ### Security and Compliance - **Data Security** - Implement user authentication and authorization - Ensure data encryption and secure storage - **Compliance Management** - Ensure the system complies with relevant health regulations and data protection laws (e.g., HIPAA) ### Backup and Recovery - **Data Backup** - Implement regular data backup processes - Set up backup storage and recovery procedures ### User Support and Documentation - **Help and Support** - Provide user manuals and documentation - Set up a support ticket system for staff queries - **Training and Onboarding** - Create training materials for new staff - Conduct training sessions ### Continuous Improvement - **Feedback System** - Collect feedback from staff and patients - Implement improvements based on feedback - **System Updates** - Regularly update the system with new features and bug fixes - Ensure minimal disruption during updates --- By following this to-do list, you can develop a robust and efficient admin module for a homeopathy clinic management system.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # """evohome-async - validate the handling of vendor APIs (URLs).""" from __future__ import annotations import logging from http import HTTPMethod, HTTPStatus import pytest import pytest_asyncio import evohomeasync as evohome from evohomeasync.broker import URL_HOST # FIXME: need v1 schemas from evohomeasync2.schema import vol # type: ignore[import-untyped] from . import _DEBUG_DISABLE_STRICT_ASSERTS, _DEBUG_USE_REAL_AIOHTTP from .helpers import ( aiohttp, # aiohttp may be mocked client_session as _client_session, user_credentials as _user_credentials, ) URL_BASE = f"{URL_HOST}/WebAPI/api" _LOGGER = logging.getLogger(__name__) _global_user_data: str = None # session_id @pytest.fixture(autouse=True) def patches_for_tests(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("evohomeasync.base.aiohttp", aiohttp) monkeypatch.setattr("evohomeasync.broker.aiohttp", aiohttp) @pytest.fixture() def user_credentials(): return _user_credentials() @pytest_asyncio.fixture async def session(): client_session = _client_session() try: yield client_session finally: await client_session.close() async def instantiate_client( username: str, password: str, session: aiohttp.ClientSession | None = None, ): """Instantiate a client, and logon to the vendor API.""" global _global_user_data # Instantiation, NOTE: No API calls invoked during instantiation evo = evohome.EvohomeClient( username, password, session=session, session_id=_global_user_data, ) # Authentication await evo._populate_user_data() _global_user_data = evo.broker.session_id return evo async def should_work( # type: ignore[no-any-unimported] evo: evohome.EvohomeClient, method: HTTPMethod, url: str, json: dict | None = None, content_type: str | None = "application/json", schema: vol.Schema | None = None, ) -> dict | list: """Make a request that is expected to succeed.""" response: aiohttp.ClientResponse response = await evo._do_request(method, f"{URL_BASE}/{url}", data=json) response.raise_for_status() assert True or response.content_type == content_type if response.content_type == "application/json": content = await response.json() else: content = await response.text() if schema: return schema(content) return content async def should_fail( evo: evohome.EvohomeClient, method: HTTPMethod, url: str, json: dict | None = None, content_type: str | None = "application/json", status: HTTPStatus | None = None, ) -> aiohttp.ClientResponse: """Make a request that is expected to fail.""" response: aiohttp.ClientResponse response = await evo._do_request(method, f"{URL_BASE}/{url}", data=json) try: response.raise_for_status() except aiohttp.ClientResponseError as exc: assert exc.status == status else: assert False, response.status if _DEBUG_DISABLE_STRICT_ASSERTS: return response assert True or response.content_type == content_type if response.content_type == "application/json": content = await response.json() else: content = await response.text() if isinstance(content, dict): assert True or "message" in content elif isinstance(content, list): assert True or "message" in content[0] return content async def _test_client_apis( username: str, password: str, session: aiohttp.ClientSession | None = None, ): """Instantiate a client, and logon to the vendor API.""" global _global_user_data # Instantiation, NOTE: No API calls invoked during instantiation evo = evohome.EvohomeClient( username, password, session=session, session_id=_global_user_data, ) user_data = await evo._populate_user_data() assert user_data == evo.user_info _global_user_data = evo.broker.session_id full_data = await evo._populate_locn_data() assert full_data == evo.location_data temps = await evo.get_temperatures() assert temps # for _ in range(3): # await asyncio.sleep(5) # _ = await evo.get_temperatures() # _LOGGER.warning("get_temperatures() OK") @pytest.mark.asyncio async def test_client_apis( user_credentials: tuple[str, str], session: aiohttp.ClientSession ) -> None: """Test _populate_user_data() & _populate_full_data()""" if not _DEBUG_USE_REAL_AIOHTTP: pytest.skip("Mocked server not implemented") try: await _test_client_apis(*user_credentials, session=session) except evohome.AuthenticationFailed: pytest.skip("Unable to authenticate")
--- permalink: online-help/reference-health-all-nodes-view.html sidebar: sidebar keywords: summary: 'The Health/Nodes inventory page enables you to view detailed information about the nodes in a selected cluster.' --- = Health/Nodes inventory page :icons: font :imagesdir: ../media/ [.lead] The Health/Nodes inventory page enables you to view detailed information about the nodes in a selected cluster. == Command button * *Export* + Enables you to export the details of all the monitored nodes to a comma-separated values (`.csv`) file. == Nodes list The Nodes list displays the properties of all the discovered nodes in a cluster. You can use the column filters to customize the data that is displayed. * *Status* + An icon that identifies the current status of the node. The status can be Critical (image:../media/sev-critical-um60.png[Icon for event severity – critical]), Error (image:../media/sev-error-um60.png[Icon for event severity – error]), Warning (image:../media/sev-warning-um60.png[Icon for event severity – warning]), or Normal (image:../media/sev-normal-um60.png[Icon for event severity – normal]). + You can position your cursor over the icon to view more information about the event or events generated for the node. * *Node* + The name of the node. * *State* + The state of the node. The state can be Up or Down. * *HA State* + The state of the HA pair. The state can be Error, Warning, Normal, or Not applicable. * *Down Time* + The time that has elapsed or the timestamp since the node is offline. If the time elapsed exceeds a week, the timestamp when the node went offline is displayed. * *Cluster* + The name of the cluster to which the node belongs. * *Model* + The model of the node. * *OS version* + The ONTAP software version that the node is running. * *All Flash Optimized* + Whether the node is optimized to support only solid-state drives (SSDs). * *Serial Number* + The serial number of the node. * *Firmware Version* + The firmware version number of the node. * *Owner* + The name of the node's owner. * *Location* + The location of the node. * *Aggregate Used Capacity* + The amount of space used for data in the node's aggregates. * *Aggregate Total Capacity* + The total space available for data in the node's aggregates. * *Usable Spare Capacity* + The amount of available space in the node that can be used to enhance the aggregate capacity. * *Usable Raw Capacity* + The amount of space that is usable in the node. * *Total Raw Capacity* + The capacity of every unformatted disk in the node before right-sizing and RAID configuration. * *SVM Count* + The number of SVMs contained by the cluster. * *FC Port Count* + The number of FC ports contained by the node. * *FCoE Port Count* + The number of FCoE ports contained by the node. * *Ethernet Port Count* + The number of ethernet ports contained by the node. * *Flash Card Size* + The size of the flash cards installed on the node. * *Flash Card Count* + The number of flash cards installed on the node. * *Disk Shelves Count* + The number of disk shelves contained by the node. * *Disk Count* + The number of disks in the node. == Filters pane The Filters pane enables you to set filters to customize the way information is displayed in the nodes list. You can select filters related to the Status, State, and HA State columns. [NOTE] ==== The filters that are specified in the Filters pane override the filters that are specified for the columns in the Nodes list. ====
import { useFirestoreCollection } from "hooks"; import React, { useState } from "react"; import { createAndPostTweet } from "./utils/createAndPostTweet"; import { Tweet } from "types"; type TProps = { author: string; }; const TweetCreator = ({ author }: TProps) => { const [, , tweetsCollectionReferece] = useFirestoreCollection<Tweet>("tweets"); const [content, setContent] = useState(""); const [postingTweet, setPostingTweet] = useState(false); const handleTweetCreation = async () => { setPostingTweet(true); await createAndPostTweet(author, content, tweetsCollectionReferece); setContent(""); setPostingTweet(false); }; return ( <div> <input type="text" value={content} onChange={(e) => setContent(e.target.value)} disabled={postingTweet} /> <button onClick={handleTweetCreation} disabled={postingTweet}> {postingTweet ? "Posting tweet..." : "Post tweet"} </button> </div> ); }; export default React.memo(TweetCreator);
// SPDX-License-Identifier: AGPL-3.0-or-later /* solhint-disable one-contract-per-file */ pragma solidity ^0.8.8; import {PermissionLib} from "../../permission/PermissionLib.sol"; import {IPluginSetup} from "../../plugin/setup/IPluginSetup.sol"; import {PluginSetup} from "../../plugin/setup/PluginSetup.sol"; import {ProxyLib} from "../../utils/deployment/ProxyLib.sol"; import {IDAO} from "../../dao/IDAO.sol"; import {mockPermissions, mockHelpers} from "./PluginSetupMockData.sol"; import {PluginCloneableMockBuild1, PluginCloneableMockBuild2} from "./PluginCloneableMock.sol"; /// @notice A mock plugin setup of a cloneable plugin to be deployed via the minimal proxy pattern. /// v1.1 (Release 1, Build 1) /// @dev DO NOT USE IN PRODUCTION! contract PluginCloneableSetupMockBuild1 is PluginSetup { using ProxyLib for address; uint16 internal constant THIS_BUILD = 1; constructor() PluginSetup(address(new PluginCloneableMockBuild1())) {} /// @inheritdoc IPluginSetup function prepareInstallation( address _dao, bytes memory ) external returns (address plugin, PreparedSetupData memory preparedSetupData) { bytes memory initData = abi.encodeCall(PluginCloneableMockBuild1.initialize, (IDAO(_dao))); plugin = implementation().deployMinimalProxy(initData); preparedSetupData.helpers = mockHelpers(THIS_BUILD); preparedSetupData.permissions = mockPermissions( 0, THIS_BUILD, PermissionLib.Operation.Grant ); } /// @inheritdoc IPluginSetup function prepareUninstallation( address _dao, SetupPayload calldata _payload ) external pure returns (PermissionLib.MultiTargetPermission[] memory permissions) { (_dao, _payload); permissions = mockPermissions(0, THIS_BUILD, PermissionLib.Operation.Revoke); } } /// @notice A mock plugin setup of a cloneable plugin to be deployed via the minimal proxy pattern. /// v1.2 (Release 1, Build 2) /// @dev DO NOT USE IN PRODUCTION! contract PluginCloneableSetupMockBuild2 is PluginSetup { using ProxyLib for address; uint16 internal constant THIS_BUILD = 2; constructor() PluginSetup(address(new PluginCloneableMockBuild2())) {} /// @inheritdoc IPluginSetup function prepareInstallation( address _dao, bytes memory ) external returns (address plugin, PreparedSetupData memory preparedSetupData) { bytes memory initData = abi.encodeCall(PluginCloneableMockBuild2.initialize, (IDAO(_dao))); plugin = implementation().deployMinimalProxy(initData); preparedSetupData.helpers = mockHelpers(THIS_BUILD); preparedSetupData.permissions = mockPermissions( 0, THIS_BUILD, PermissionLib.Operation.Grant ); } /// @inheritdoc IPluginSetup function prepareUninstallation( address _dao, SetupPayload calldata _payload ) external pure returns (PermissionLib.MultiTargetPermission[] memory permissions) { (_dao, _payload); permissions = mockPermissions(0, THIS_BUILD, PermissionLib.Operation.Revoke); } }
import 'dart:async'; import 'dart:io' as io; import 'package:android_intent_plus/android_intent.dart'; import 'package:android_intent_plus/flag.dart'; import 'package:extended_image/extended_image.dart'; import 'package:file_picker/file_picker.dart'; import 'package:file_saver/file_saver.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:kavita_api/kavita_api.dart'; import 'package:log/log.dart'; import 'package:open_filex/open_filex.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; import 'package:skeletonizer/skeletonizer.dart'; import 'package:subete/src/features/download/application/download_service.dart'; import 'package:subete/src/features/download/presentation/draggable_cloud_widget.dart'; import 'package:subete/src/features/kavita/application/kavita_auth_provider.dart'; import 'package:subete/src/features/kavita/application/kavita_data_providers.dart'; import 'package:subete/utils/utils.dart'; import 'package:super_sliver_list/super_sliver_list.dart'; class SeriesDetailsScreen extends ConsumerWidget { const SeriesDetailsScreen({ required this.seriesId, super.key, }); final int seriesId; @override Widget build(BuildContext context, WidgetRef ref) { final kavita = ref.watch(kavitaProvider); final series = ref.watch(findSeriesProvider(seriesId)); final seriesDetailsAsync = ref.watch(findSeriesDetailProvider(seriesId)); return Material( child: AnimatedSwitcher( duration: const Duration(milliseconds: 650), switchInCurve: Curves.easeInOut, switchOutCurve: Curves.easeInOut, child: seriesDetailsAsync.when( data: (seriesDetails) { final List<VolumeDto> volumes = seriesDetails.volumes ?? []; final List<ChapterDto> specials = seriesDetails.specials ?? []; return KeyedSubtree( key: const ValueKey('SeriesDetailsScreen-list'), child: Scrollbar( child: ScrollConfiguration( behavior: ScrollConfiguration.of(context).copyWith( scrollbars: false, ), child: CustomScrollView( slivers: <Widget>[ SuperSliverList( delegate: SliverChildBuilderDelegate( childCount: specials.length + 1, (context, index) { if (specials.isEmpty) return null; if (index == 0) { return const ListTile( title: Text('Specials'), ); } final ChapterDto specialItem = specials[index - 1]; final (:headers, :url) = kavita.image.url .getChapterCover(id: specialItem.id ?? -1); return Card( child: ListTile( leading: ExtendedImage.network( url.toString(), headers: headers, width: 40, fit: BoxFit.cover, filterQuality: FilterQuality.medium, shape: BoxShape.rectangle, handleLoadingProgress: true, borderRadius: // ignore: avoid_using_api const BorderRadius.all( Radius.circular(8.0), ), ), title: Text(specialItem.title ?? 'Special'), subtitle: Text( '${specialItem.minHoursToRead} hours', ), onTap: () { // TODO: Support downloading specials context.showSnackBar( 'Downloads are not currently supported for specials', ); }, ), ); }, ), ), SuperSliverList( delegate: SliverChildBuilderDelegate( childCount: volumes.length + 1, (context, index) { if (volumes.isEmpty) return null; if (index == 0) { return const ListTile( title: Text('Volumes'), ); } final VolumeDto volumeItem = volumes[index - 1]; return Builder(builder: (context) { return _VolumeWidget( key: ValueKey( volumeItem.id ?? 'volume-item-$index'), volumeItem: volumeItem, seriesName: series.valueOrNull?.name ?? '', ); }); }, ), ), ], ), ), ), ); }, error: (error, stackTrace) { return Center( key: ValueKey(error), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text('Error: $error'), const SizedBox(height: 16), ElevatedButton( onPressed: () => ref.invalidate(librariesProvider), child: const Text('Retry'), ) ], ), ); }, loading: () { return Skeletonizer( key: const ValueKey('SeriesDetailsScreen-loading'), child: ListView.builder( itemCount: 10, itemBuilder: (context, index) { return const Card( child: ListTile( leading: Icon(Icons.library_books), minLeadingWidth: 40, title: Text('Loading...'), subtitle: Text('Hours...'), ), ); }, ), ); }, ), ), ); } } class _VolumeWidget extends ConsumerStatefulWidget { const _VolumeWidget({ required this.volumeItem, required this.seriesName, super.key, }); final VolumeDto volumeItem; final String seriesName; @override ConsumerState<_VolumeWidget> createState() => _VolumeWidgetState(); } class _VolumeWidgetState extends ConsumerState<_VolumeWidget> { static final _log = Logger('_VolumeWidget'); bool _isDownloading = false; @override Widget build(BuildContext context) { final kavita = ref.watch(kavitaProvider); final downloadService = ref.watch(downloadServiceProvider.notifier); final (headers: coverHeaders, url: coverUrl) = kavita.image.url.getVolumeCover(id: widget.volumeItem.id ?? -1); final (headers: fileHeaders, url: fileUrl) = kavita.download.url.getDownloadVolume(id: widget.volumeItem.id ?? -1); final String volumeName = widget.volumeItem.name ?? widget.seriesName; final String volumeNameFallback = volumeName.isEmpty ? '${widget.seriesName} Volume ${widget.volumeItem.minNumber ?? widget.volumeItem.maxNumber}' : volumeName; final filename = downloadService.sanitizeFilename( '$volumeNameFallback.epub', replacement: '_', ); final coverImage = ExtendedImage.network( coverUrl.toString(), headers: coverHeaders, width: 40, fit: BoxFit.cover, filterQuality: FilterQuality.medium, shape: BoxShape.rectangle, handleLoadingProgress: true, borderRadius: // ignore: avoid_using_api const BorderRadius.all( Radius.circular(8.0), ), ); return Material( child: DraggableCloudWidget( suggestedName: filename, downloadUrl: fileUrl, thumbnailUrl: coverUrl, downloadHeaders: fileHeaders, thumbnailHeaders: coverHeaders, child: Card( child: Stack( alignment: Alignment.bottomCenter, children: [ ListTile( minLeadingWidth: 40, leading: coverImage, title: Text(volumeNameFallback), subtitle: Text( '${widget.volumeItem.avgHoursToRead} hours', ), onTap: () async { final id = widget.volumeItem.id; if (id == null) { return; } setState(() { _isDownloading = true; }); final download = await ref .read(downloadVolumeProvider(volumeId: id).future); if (!context.mounted) return; setState(() { _isDownloading = false; }); if (!kIsWeb) { final file = XFile.fromData( download, mimeType: MimeType.epub.type, name: filename, lastModified: widget.volumeItem.lastModifiedUtc, ); if (io.Platform.isMacOS || io.Platform.isWindows || io.Platform.isLinux) { // TODO: Show dialog with "open", "open with", and "save as" options await _openFile(file, filename, fallback: () async { await _saveFileAs(filename, file, context); }); } else if (io.Platform.isIOS) { if (context.mounted) { await _shareFile(context, file, filename); } } else if (io.Platform.isAndroid) { // TODO: Show dialog with "open with" and "save as" options await _openFileAndroid(filename, file, download, context, fallback: () async { await _saveFileAs(filename, file, context); }); } } else { await _saveFile(download, filename); } }, ), if (_isDownloading) const Center( child: LinearProgressIndicator(), ), ], ), ), ), ); } /// Opens a file with the default app if available. Only supported on Android Future<void> _openFileAndroid( String filename, XFile file, Uint8List download, BuildContext context, { required FutureOr<void> Function() fallback, }) async { if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) return; try { final tempDir = await getApplicationCacheDirectory(); final savedFilePath = p.join(tempDir.path, filename); await file.saveTo(savedFilePath); final intent = AndroidIntent( action: 'action_view', data: Uri.encodeFull( 'content://com.getboolean.subete.subete_fileprovider/cache/$filename'), type: MimeType.epub.type, flags: <int>[ Flag.FLAG_ACTIVITY_NEW_TASK, Flag.FLAG_GRANT_READ_URI_PERMISSION ], // open in app ); await intent.launch(); } on Exception catch (_, __) { final result = fallback(); if (result is Future) { await result; } } } /// Opens a save file dialog. Not supported on web Future<void> _saveFileAs( String filename, XFile file, BuildContext context, ) async { if (kIsWeb) return; final String? outputFile = await FilePicker.platform.saveFile( dialogTitle: 'Please select a file save location:', fileName: filename, type: FileType.custom, allowedExtensions: ['epub'], ); if (outputFile != null) { await file.saveTo(outputFile); if (context.mounted) { context.showAccessibilitySnackBar('Saved file successfully'); } } } /// Saves a file to the user's Downloads folder. Future<void> _saveFile(Uint8List file, String filename) async { await FileSaver.instance.saveFile( name: filename, bytes: file, mimeType: MimeType.epub, ); if (!mounted) return; if (kIsWeb) { context.showAccessibilitySnackBar('Opened save file dialog'); } else { context.showSnackBar('Saved to Downloads Folder'); } } /// Opens a file with the default app if available. Not supported on web Future<void> _openFile( XFile file, String filename, { required FutureOr<void> Function() fallback, }) async { if (kIsWeb) { final result = fallback(); if (result is Future) { await result; } return; } final tempDir = await getAppTemporaryDirectory(); final savedFilePath = p.join(tempDir, filename); await file.saveTo(savedFilePath); final openResult = await OpenFilex.open( savedFilePath, type: MimeType.epub.type, uti: 'org.idpf.epub-container', ); final ioFile = io.File(savedFilePath); if (!mounted) return; switch (openResult.type) { case ResultType.done: try { if (ioFile.existsSync()) { await Future<void>.delayed(const Duration(seconds: 15)); if (ioFile.existsSync()) { await ioFile.delete(); } } } on io.FileSystemException catch (e, st) { _log.severe(e.message, e, st); } case ResultType.error: case ResultType.permissionDenied: case ResultType.fileNotFound: case ResultType.noAppToOpen: final result = fallback(); if (result is Future) { await result; } } await clearAppTemporaryDirectory(tempDir); } /// Open share dialog. Not supported on Linux. Future<void> _shareFile( BuildContext context, XFile file, String filename, { FutureOr<void> Function()? fallback, }) async { if (!kIsWeb && defaultTargetPlatform == TargetPlatform.linux) { final result = fallback?.call(); if (result is Future) { await result; } return; } final box = context.findRenderObject() as RenderBox?; try { final result = await Share.shareXFiles( [file], sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size, ); if (!context.mounted) return; switch (result.status) { case ShareResultStatus.success: case ShareResultStatus.dismissed: break; case ShareResultStatus.unavailable: await fallback?.call(); } } on PlatformException catch (e, st) { _log.severe(e.message, e, st); final result = fallback?.call(); if (result is Future) { await result; } return; } } }
/****************************************************************************** START Glitch hello-app default styles The styles in this section do some minimal CSS resets, set default fonts and colors, and handle the layout for our footer and "Remix on Glitch" button. If you're new to CSS they may seem a little complicated, but you can scroll down to this section's matching END comment to see page-specific styles. ******************************************************************************/ /* The style rules specify elements by type and by attributes such as class and ID Each section indicates an element or elements, then lists the style properties to apply See if you can cross-reference the rules in this file with the elements in index.html */ /* Our default values set as CSS variables */ :root { --color-bg: #111111; --color-text-main: #FFFFFF; --color-primary: #FFFFFF; --wrapper-height: 87vh; --image-max-width: 300px; --image-margin: 3rem; --font-family: "HK Grotesk"; --font-family-header: "HK Grotesk"; } * { box-sizing: border-box; color: #FFFFFF; } [hidden] { display: none !important; } .footer { display: flex; justify-content: space-between; margin: 1rem auto 0; padding: 1rem 0 0.75rem 0; width: 100%; flex-wrap: wrap; border-top: 4px solid #333333; } .footer .links { padding: 0.5rem 1rem 1.5rem; white-space: nowrap; } html, body { font-family: sans-serif; background-color: var(--color-bg); margin: 0; padding: 0; } body { display: flex; flex-direction: column; align-items: center; } .navbar { width: 100vw; height: 70px; color: white; position: fixed; display: flex; justify-content: center; align-items: center; background-color: rgba(0, 0, 0, 0.2); -webkit-backdrop-filter: blur(25px); backdrop-filter: blur(25px); z-index: 1; } .videoWrapper { position: relative; padding-bottom: 56.25%; /* 16:9 */ padding-top: 25px; height: 0; } .video { position: absolute; top: 0; left: 0; width: 75%; height: 75%; } .banner { width: 100%; mask-image: linear-gradient(transparent, rgba(0, 0, 0, 1) 50%, transparent); -webkit-mask-image: linear-gradient(transparent, rgba(0, 0, 0, 1) 50%, transparent); -o-mask-image: linear-gradient(transparent, rgba(0, 0, 0, 1) 50%, transparent); -moz-mask-image: linear-gradient(transparent, rgba(0, 0, 0, 1) 50%, transparent); -ms-mask-image: linear-gradient(transparent, rgba(0, 0, 0, 1) 50%, transparent); }
import React, {useState} from "react"; import {useNavigate} from "react-router"; import s from "../Heroes.module.css"; import ImageSlider from "../../ImagesSlider/ImagesSlider"; //deck import card1 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/epic-poem.png' import card2 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/fatal-struggle.png' import card3 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/feint.png' import card4 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/golden-drinking-horn.png' import card5 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/hot-for-battle.png' import card6 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/no-contest-expecteth.png' import card7 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/remnant-of-valor.png' import card8 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/skirmish (1).png' import card9 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/the-ancient-heirloom.png' import card10 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/the-equal-of-grendel.png' import card11 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/the-war-king.png' import card12 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-deck/vigor-and-courage.png' //hero images import avatar from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-images/beowulf-art.jpg' import image1 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-images/beowulf-grendel.jpg' import image2 from '../../../images/heroes/beowulf-and-red-hood/beowulf/beowulf-images/beowulf-minifigure.jpg' const Beowulf = ({state}) => { const [showCards, setShowCards] = useState(false) const handleToggleCards = () => { setShowCards(!showCards); window.scrollTo({top: 50000, behavior: 'smooth'}) } let imgUrls = [avatar, image1, image2] const myStyleBackground = { backgroundColor: state.backgroundColor, height: '100%' }; const headersBackground = { backgroundColor: state.headersBackgroundColor, color: state.fontColor } const navigate = useNavigate() function handleClick() { navigate(`/${state.companionRoute}`); } return (<div style={myStyleBackground} className={s.content}> <div style={headersBackground}> <h1>{state.heroName}</h1> </div> <div className={s.wrapper}> <div className={s.middleSide}> <p><span className={s.firstWord}>Companion:</span></p> <p><span className={s.firstWord}>Name:</span> {state.companionName}</p> <p><span className={s.firstWord}>Range:</span> {state.companionRange}</p> <p><span className={s.firstWord}>Start health:</span> {state.companionHealth}</p> {/*Companion button will be later*/} {/*<button className={s.companionButton} onClick={handleClick}>More about companion*/} {/*</button>*/} </div> {/*left and right gaps for big displays*/} <div className={s.leftSideGap}> {/*<img src="" alt=""></img>*/} </div> <div className={s.rightSideGap}> {/*<img src="" alt=""></img>*/} </div> <div className={s.leftSidePartOne}> <p><span className={s.firstWord}>Name:</span> {state.heroName}</p> <p><span className={s.firstWord}>Range:</span> {state.heroRange}</p> <p><span className={s.firstWord}>Start health:</span> {state.heroHealth}</p> <p><span className={s.firstWord}>Movement:</span> {state.movement}</p> <p><span className={s.firstWord}>Origin:</span> {state.origin}</p> </div> <div className={s.leftSidePartTwo}> <div style={headersBackground} className={s.fanStatsHeader}><h3>Non official stats:</h3></div> <div className={s.fanStatsContainer}> <p><span className={s.firstWord}>Tier:</span> {state.tier}</p> <p><span className={s.firstWord}>Difficulty:</span> {state.difficulty}</p> <p><span className={s.firstWord}>Overall power:</span> {state.overallPower}</p> </div> </div> <div className={s.rightSide}> <div className={s.imageSlider}> <ImageSlider headersBackground={headersBackground} imgUrls={imgUrls}/> </div> <div> <blockquote className={s.quote}>{state.heroQuote}</blockquote> </div> </div> <div className={s.downSide}> <div style={headersBackground}> <h2>Hero's traits</h2> </div> <p>{state.heroTrait}</p> <div style={headersBackground}> <h2>Tactics</h2> </div> <p>{state.tactics} </p> <div style={headersBackground}> <h2>Description</h2> </div> <p> {state.description} </p> </div> </div> <div> <div style={headersBackground}> <h2>Hero's cards</h2> </div> <div className={s.showCardsButton} onClick={handleToggleCards}> <h3>Click to show</h3> </div> </div> <br/> <div className={`cards-wrapper ${showCards ? 'active' : ''}`}> <div className={s.cards}> <img src={card1} alt="none"/> <img src={card2} alt="none"/> <img src={card3} alt="none"/> <img src={card4} alt="none"/> <img src={card5} alt="none"/> <img src={card6} alt="none"/> <img src={card7} alt="none"/> <img src={card8} alt="none"/> <img src={card9} alt="none"/> <img src={card10} alt="none"/> <img src={card11} alt="none"/> <img src={card12} alt="none"/> </div> </div> </div> ) } export default Beowulf
import Game from "./Game"; import LocalStorageWrapper from "../utils/LocalStorageWrapper"; import GameUtils from "./GameUtils"; import soundOnSrc from "/volume_up.svg"; import soundOffSrc from "/volume_mute.svg"; import { GAME_DIFFICULTY, GAME_MODE, PADDLE_POSITION, } from "../utils/constants"; import { BoxSize, GameDifficulty, GameMode, PaddlePosition, } from "../utils/types"; const soundOnImage = new Image(); soundOnImage.src = soundOnSrc; const soundOffImage = new Image(); soundOffImage.src = soundOffSrc; class Menu { public isOpen = false; private optionVisible = { isGameMode: true, isSingleGameMode: false, isDoubleGameMode: false, isDifficulty: false, isPosition: false, }; constructor(private game: Game) { window.addEventListener("keydown", (event) => { if (this.game.state.isOver) return; const key = event.key.toLowerCase(); if (key === "m") { this.toggleMenuVisibility(); } }); } setVisibleOption(option: keyof typeof this.optionVisible | null) { (Object.keys(this.optionVisible) as typeof option[]).forEach((key) => { this.optionVisible[key!] = option === key; }); } private toggleMenuVisibility() { this.isOpen = !this.isOpen; this.game.state.isPaused = this.isOpen; this.setVisibleOption(this.isOpen ? "isGameMode" : null); } update() {} draw(ctx: CanvasRenderingContext2D) { const canvasSize = { x: 0, y: 0, w: ctx.canvas.width, h: ctx.canvas.height, }; // draw burga-nav btnm { const burgaNav: BoxSize = { x: canvasSize.w * 0.955, y: canvasSize.h * 0.02, w: 50, h: 40, }; GameUtils.createButton( ctx, { data: burgaNav, hasBackground: true }, this.game.cursors, { pointerDownHandler: () => { this.toggleMenuVisibility(); }, drawHandler: () => { if (this.isOpen) { ctx.lineWidth = 10; ctx.strokeStyle = "white"; ctx.beginPath(); ctx.moveTo(burgaNav.x, burgaNav.y); ctx.lineTo(burgaNav.x + burgaNav.w, burgaNav.y + burgaNav.h); ctx.moveTo(burgaNav.x, burgaNav.y + burgaNav.h); ctx.lineTo(burgaNav.x + burgaNav.w, burgaNav.y); ctx.stroke(); } else { ctx.fillRect(burgaNav.x, burgaNav.y, burgaNav.w, 10); ctx.fillRect(burgaNav.x, burgaNav.y + 15, burgaNav.w, 10); ctx.fillRect(burgaNav.x, burgaNav.y + 30, burgaNav.w, 10); // ctx.fillRect(menu.x, menu.y, menu.w, menu.h); } }, } ); } if (this.isOpen) { // Draw First Question if (this.optionVisible.isGameMode) { const GAME_TITLE = "PONG"; let fontSize = 150; this.game.Utils.saveAndRestore(ctx, () => { ctx.globalAlpha = 1; ctx.font = `${fontSize}px Blomberg`; ctx.fillText( GAME_TITLE, canvasSize.w * 0.5 - ctx.measureText(GAME_TITLE).width * 0.5, canvasSize.h * 0.1 ); // Draw Middle Line this.drawMiddleLine(ctx, { isFull: false }); }); // Options fontSize = 80; ctx.font = `${fontSize}px Blomberg`; ctx.textBaseline = "hanging"; [ { text: "1 Player" as const, value: "Single" as const, x: canvasSize.w * 0.25 - ctx.measureText("1 Player").width * 0.5, y: canvasSize.h * 0.7, w: ctx.measureText("1 Player").width, h: ctx.measureText("1 Player").actualBoundingBoxDescent, }, { text: "2 Players" as const, value: "Double" as const, x: canvasSize.w * 0.75 - ctx.measureText("2 Players").width * 0.5, y: canvasSize.h * 0.7, w: ctx.measureText("2 Players").width, h: ctx.measureText("2 Players").actualBoundingBoxDescent, }, ].forEach((option) => { this.game.Utils.createButton( ctx, { data: option }, this.game.cursors, { drawHandler() { ctx.fillText(option.text, option.x, option.y); }, pointerDownHandler: () => { if (option.value === "Single") { LocalStorageWrapper.set<GameMode>(GAME_MODE, option.value); this.setVisibleOption("isSingleGameMode"); } else if (option.value === "Double") { location.href = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"; } }, } ); }); } // MULTI-PLAYER QUESTIONS BEGIN // MULTI-PLAYER QUESTIONS END // SINGLE PLAYER QUESTIONS BEGIN // Draw "Single Player" Option Titles if (this.optionVisible.isSingleGameMode) { const GAME_TITLE = "PONG"; let fontSize = 150; this.game.Utils.saveAndRestore(ctx, () => { ctx.globalAlpha = 1; ctx.font = `${fontSize}px Blomberg`; ctx.fillText( GAME_TITLE, canvasSize.w * 0.5 - ctx.measureText(GAME_TITLE).width * 0.5, canvasSize.h * 0.1 ); // Draw Middle Line this.drawMiddleLine(ctx, { isFull: false }); }); // Options fontSize = 80; ctx.font = `${fontSize}px Blomberg`; ctx.textBaseline = "hanging"; [ { text: "Difficulty" as const, x: canvasSize.w * 0.25 - ctx.measureText("Difficulty").width * 0.5, y: canvasSize.h * 0.7, w: ctx.measureText("Difficulty").width, h: ctx.measureText("Difficulty").actualBoundingBoxDescent, }, { text: "Position" as const, x: canvasSize.w * 0.75 - ctx.measureText("Position").width * 0.5, y: canvasSize.h * 0.7, w: ctx.measureText("Position").width, h: ctx.measureText("Position").actualBoundingBoxDescent, }, ].forEach((option) => { this.game.Utils.createButton( ctx, { data: option }, this.game.cursors, { drawHandler() { ctx.fillText(option.text, option.x, option.y); }, pointerDownHandler: () => { if (option.text === "Difficulty") { this.setVisibleOption("isDifficulty"); } else { this.setVisibleOption("isPosition"); } }, } ); }); } // Draw "Single Player" Difficulty Configs if (this.optionVisible.isDifficulty) { const fontSize = 100; ctx.font = `${fontSize}px Blomberg`; [ { value: "EASY" as const, x: canvasSize.w * 0.5 - ctx.measureText("EASY").width * 0.5, y: (canvasSize.h - ctx.measureText("EASY").actualBoundingBoxDescent) / 4, w: ctx.measureText("EASY").width, h: ctx.measureText("EASY").actualBoundingBoxDescent, }, { value: "MEDIUM" as const, x: canvasSize.w * 0.5 - ctx.measureText("MEDIUM").width * 0.5, y: ((canvasSize.h - ctx.measureText("MEDIUM").actualBoundingBoxDescent) / 4) * 2, w: ctx.measureText("MEDIUM").width, h: ctx.measureText("MEDIUM").actualBoundingBoxDescent, }, { value: "HARD" as const, x: canvasSize.w * 0.5 - ctx.measureText("HARD").width * 0.5, y: ((canvasSize.h - ctx.measureText("HARD").actualBoundingBoxDescent) / 4) * 3, w: ctx.measureText("HARD").width, h: ctx.measureText("HARD").actualBoundingBoxDescent, }, ].forEach((option) => { this.game.Utils.createButton( ctx, { data: option }, this.game.cursors, { drawHandler() { ctx.fillText(option.value, option.x, option.y); }, pointerDownHandler: () => { LocalStorageWrapper.set<GameDifficulty>( GAME_DIFFICULTY, option.value ); this.setVisibleOption("isSingleGameMode"); }, } ); }); } // Draw "Single Player" Position Configs if (this.optionVisible.isPosition) { const fontSize = 130; ctx.font = `${fontSize}px Blomberg`; this.game.Utils.saveAndRestore(ctx, () => { [ { value: "LEFT" as const, x: canvasSize.w * 0.25 - ctx.measureText("LEFT").width * 0.5, y: canvasSize.h * 0.5, w: ctx.measureText("LEFT").width, h: ctx.measureText("LEFT").actualBoundingBoxDescent, }, { value: "RIGHT" as const, x: canvasSize.w * 0.75 - ctx.measureText("RIGHT").width * 0.5, y: canvasSize.h * 0.5, w: ctx.measureText("RIGHT").width, h: ctx.measureText("RIGHT").actualBoundingBoxDescent, }, ].forEach((option) => { this.game.Utils.createButton( ctx, { data: option }, this.game.cursors, { drawHandler() { ctx.fillText(option.value, option.x, option.y); }, pointerDownHandler: () => { this.setVisibleOption("isSingleGameMode"); LocalStorageWrapper.set<PaddlePosition>( PADDLE_POSITION, option.value ); }, } ); }); // Draw Middle Line this.drawMiddleLine(ctx, { isFull: true }); this.game.state.isStartNewGame = true; }); } // SINGLE PLAYER QUESTIONS END // Draw A Back Arrow // Will show in some scenarios // if (!this.optionVisible.isGameMode) { if (!this.optionVisible.isGameMode) { const backArrowBoxSize: BoxSize = { h: 100, w: 70, x: 15, y: canvasSize.h / 2, }; this.game.Utils.createButton( ctx, { data: { ...backArrowBoxSize, y: backArrowBoxSize.y - backArrowBoxSize.h * 0.5, }, }, this.game.cursors, { drawHandler: () => { for (let count = 0; count < 4; count++) { ctx.strokeStyle = "#fff"; ctx.fillStyle = "#fff"; ctx.beginPath(); ctx.moveTo(backArrowBoxSize.x, backArrowBoxSize.y); ctx.lineTo( backArrowBoxSize.x + backArrowBoxSize.w, backArrowBoxSize.y - backArrowBoxSize.h * 0.5 ); ctx.lineTo( backArrowBoxSize.x + backArrowBoxSize.w, backArrowBoxSize.y + backArrowBoxSize.h * 0.5 ); ctx.closePath(); ctx.stroke(); // backArrowBoxSize backArrowBoxSize.h -= 14; backArrowBoxSize.w -= 10; backArrowBoxSize.x += 6; } ctx.fill(); }, pointerDownHandler: () => { if (this.optionVisible.isSingleGameMode) { this.setVisibleOption("isGameMode"); } else if ( this.optionVisible.isDifficulty || this.optionVisible.isPosition ) { this.setVisibleOption("isSingleGameMode"); } }, } ); } // Draw Sound Control Button const soundImageBoxSize: BoxSize = { h: 45, w: 45, x: 10, y: 5, }; this.game.Utils.createButton( ctx, { data: soundImageBoxSize }, this.game.cursors, { drawHandler: () => { ctx.drawImage( this.game.isSoundOn ? soundOnImage : soundOffImage, soundImageBoxSize.x, soundImageBoxSize.y, soundImageBoxSize.w, soundImageBoxSize.h ); }, pointerDownHandler: () => { this.game.isSoundOn = !this.game.isSoundOn; }, } ); } } private drawMiddleLine( ctx: CanvasRenderingContext2D, options = { isFull: true } ) { const canvasSize = { x: 0, y: 0, w: ctx.canvas.width, h: ctx.canvas.height, }; // Draw Middle Line ctx.beginPath(); ctx.moveTo( canvasSize.w * 0.497, canvasSize.h * (options.isFull ? 0 : 0.45) ); ctx.lineTo(canvasSize.w * 0.497, canvasSize.h - (options.isFull ? 0 : 20)); ctx.stroke(); ctx.beginPath(); ctx.moveTo( canvasSize.w * 0.502, canvasSize.h * (options.isFull ? 0 : 0.45) ); ctx.lineTo(canvasSize.w * 0.502, canvasSize.h - (options.isFull ? 0 : 20)); ctx.stroke(); } } export default Menu;
<?php namespace Modules\Stats\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Database\Eloquent\Factory; use Route; class StatsServiceProvider extends ServiceProvider { protected $defer = false; protected $moduleSvc; /** * Boot the application events. */ public function boot() { $this->moduleSvc = app('App\Services\ModuleService'); $this->registerRoutes(); $this->registerTranslations(); $this->registerConfig(); $this->registerViews(); $this->registerLinks(); $this->registerFactories(); $this->loadMigrationsFrom(__DIR__ . '/../Database/migrations'); } /** * Add module links here */ public function registerLinks() { // Show this link if logged in $this->moduleSvc->addFrontendLink('Stats', '/stats', '', $logged_in=true); // Admin links: $this->moduleSvc->addAdminLink('Stats', '/admin/stats'); } /** * Register the routes */ protected function registerRoutes() { /** * Routes for the frontend */ Route::group([ 'as' => 'stats.', 'prefix' => 'stats', // If you want a RESTful module, change this to 'api' 'middleware' => ['web'], 'namespace' => 'Modules\Stats\Http\Controllers' ], function() { $this->loadRoutesFrom(__DIR__ . '/../Http/Routes/web.php'); }); /** * Routes for the admin */ Route::group([ 'as' => 'stats.', 'prefix' => 'admin/stats', // If you want a RESTful module, change this to 'api' 'middleware' => ['web', 'role:admin'], 'namespace' => 'Modules\Stats\Http\Controllers\Admin' ], function() { $this->loadRoutesFrom(__DIR__ . '/../Http/Routes/admin.php'); }); /** * Routes for an API */ Route::group([ 'as' => 'stats.', 'prefix' => 'api/stats', // If you want a RESTful module, change this to 'api' 'middleware' => ['api'], 'namespace' => 'Modules\Stats\Http\Controllers\Api' ], function() { $this->loadRoutesFrom(__DIR__ . '/../Http/Routes/api.php'); }); } /** * Register config. */ protected function registerConfig() { $this->publishes([ __DIR__.'/../Config/config.php' => config_path('stats.php'), ], 'stats'); $this->mergeConfigFrom( __DIR__.'/../Config/config.php', 'stats' ); } /** * Register views. */ public function registerViews() { $viewPath = resource_path('views/modules/stats'); $sourcePath = __DIR__.'/../Resources/views'; $this->publishes([ $sourcePath => $viewPath ],'views'); $this->loadViewsFrom(array_merge(array_map(function ($path) { return $path . '/modules/stats'; }, \Config::get('view.paths')), [$sourcePath]), 'stats'); } /** * Register translations. */ public function registerTranslations() { $langPath = resource_path('lang/modules/stats'); if (is_dir($langPath)) { $this->loadTranslationsFrom($langPath, 'stats'); } else { $this->loadTranslationsFrom(__DIR__ .'/../Resources/lang', 'stats'); } } /** * Register an additional directory of factories. * @source https://github.com/sebastiaanluca/laravel-resource-flow/blob/develop/src/Modules/ModuleServiceProvider.php#L66 */ public function registerFactories() { if (! app()->environment('production')) { app(Factory::class)->load(__DIR__ . '/../Database/factories'); } } /** * Get the services provided by the provider. */ public function provides() { return []; } }
/** * \file * \author Aznam Yacoub ([email protected]) * \date Sept. 9 2020 * \version 1.0 * \brief This file provides an implementation of the application. * \details This file implements the main application. */ /* Project Includes */ #include "../../../include/missionplanner/robot.hpp" #include "../../../include/missionplanner/application/application.hpp" #include "../../../include/missionplanner/globals.hpp" /* Code */ namespace lis::pecase::productive40::missionplanner::application { #pragma region Constructors / Destructor Application::Application ( int argc, char ** argv ) : QApplication(argc, argv), m_networkManager(network::NetworkManager::instance()) { virtual_network_ = new environment::VirtualNetwork; // Setup the network manager for the Fake Communication this->m_networkManager.addNetworkDelegate( new network::delegate::FakeCommunicationImpl ); // Setup the network manager for ROS Communication //#if !defined(_DEBUG) this->m_networkManager.addNetworkDelegate( new network::delegate::ROSCommunicationImpl(argc, argv) ); //#endif // Setup the network manager for INET Communication //this->m_networkManager.addNetworkDelegate( // new network::delegate::InetCommunicationImpl //); // Setup view subscriber //this->m_networkManager.subscribe(&this->m_mainWindow); // Configure the main window QObject::connect( &this->m_mainWindow, &ui::MainWindow::exitApplication, this, &Application::exit, Qt::QueuedConnection ); QObject::connect( &missionplanner::robot::RobotManager::instance(), &missionplanner::robot::RobotManager::displayRobot, &this->m_mainWindow, &ui::MainWindow::displayRobot ); // Parse arguments for(unsigned i = 1; i < argc; i++) { // Simulated robots if(strcmp(argv[i], "--robot") == 0 && i + 1 < argc) { unsigned int nb_robots = atoi(argv[i + 1]); for(unsigned r = 1; r <= nb_robots; r++) { this->createRobot(r); } } } this->m_mainWindow.show(); } Application::~Application ( void ) { QObject::disconnect( &missionplanner::robot::RobotManager::instance(), &missionplanner::robot::RobotManager::displayRobot, &this->m_mainWindow, &ui::MainWindow::displayRobot ); for(unsigned r = 0; r < this->m_simubots.size(); r++) { this->m_simubots[r]->exit(0); } QObject::disconnect(this); delete virtual_network_; } #pragma endregion #pragma region Methods Definitions and Implementations #pragma region Application Management void Application::exit ( unsigned int exit_code ) { QCoreApplication::exit(exit_code); } #pragma endregion #pragma region Simubot Functions Simubot * Application::createRobot ( unsigned int robot_idx ) { Simubot * robot = new Simubot(this, robot_idx); QObject::connect(robot, &Simubot::finished, this, &Application::robotTerminated); this->m_simubots.append(robot); robot->start(); missionplanner::robot::RobotManager::instance().robotConnected(&robot->m_robotInterface); return robot; } void Application::robotTerminated ( void ) { Simubot* robot = (Simubot*)QObject::sender(); QObject::disconnect(robot, nullptr, this, nullptr); delete robot; } #pragma endregion #pragma endregion }; // namespace lis::pecase::productive40::missionplanner::application
#ifndef __outputstream_h #define __outputstream_h #include <stdarg.h> #include "dmapiexport.h" /** * Simple interface that allows output to be written to the implementing object. */ class DMAPI_API IOutputStream { public: virtual void writeToStdOut(const char *fmt, ...) = 0; virtual void writevToStdOut(long threadId, const char *buffer) = 0; virtual void writeBufferToStdOut(long threadId, const char *buffer, int len) = 0; virtual void writeToStdErr(const char *fmt, ...) = 0; virtual void writevToStdErr(long threadId, const char *buffer) = 0; virtual void writeBufferToStdErr(long threadId, const char *buffer, int len) = 0; }; /** * Concrete class that implements the OutputStream interface and writes the * output to a buffer which can be later printed into another OutputStream. */ class DMAPI_API OutputStream : public /*virtual*/ IOutputStream { private: char *m_buffer; long m_len; int m_refCount; bool m_autoNewline; public: OutputStream(); OutputStream(bool autoNewline); ~OutputStream(); void addRef(); void releaseRef(); void writeToStdOut(const char *fmt, ...); void writevToStdOut(long threadId, const char *buffer); void writeBufferToStdOut(long threadId, const char *buffer, int len); void writeToStdErr(const char *fmt, ...); void writevToStdErr(long threadId, const char *buffer); void writeBufferToStdErr(long threadId, const char *buffer, int len); void readFromStdIn(); const char *buffer(); long size(); void truncate(); }; #endif /*__outputstream_h*/
import React, { Component } from "react"; import { ImageSearch } from "./Searchbar"; import { ImageCard } from "./ImageGallery"; import { fetchImages } from "../services/api"; import { ImageModal } from "./Modal"; const ERROR_MSG = `Something went wrong, please reload the page`; export class App extends Component{ // Initialize the state with empty gallery, loading flag, and error state = { gallery:[], isLoading: false, error: null, selectedImg: null, } //Function to handle search submission handleSearchSubmit = async (searchText, page) => { try{ //Set loading state and clear previous error this.setState({isLoading:true, error:null}) // Fetch images based on search text and page number const fetchedImages = await fetchImages(searchText, page) //Update the gallery state with fetched images this.setState({ gallery: fetchedImages.hits, }) }catch(error){ this.setState({error: error.message || 'Something went wrong'}); }finally{ this.setState({isLoading: false}); } }; setSelectedImg = () => { this.setState({selectedImg: this.largeImageURL}) } closeModal = () => { this.setState({selectedImg: null}) } render(){ const {gallery, isLoading, error, selectedImg} = this.state; return( <div> {/* render the Searchbar component */} <ImageSearch onSearchSubmit={this.handleSearchSubmit} /> {/* Render loading message, error message, or ImageCard */} { isLoading?( <p>Loading...</p> ) : error ? ( <p>{ERROR_MSG}</p> ) : ( gallery.length > 0 && <ImageCard gallery={gallery}/> ) } <ImageModal isOpen={selectedImg !== null} onClose={this.closeModal} image={selectedImg} /> </div> ) } }
"use client"; import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, } from "@/components/ui/dropdown-menu"; import { supabaseBrowser } from "@/lib/supabase/browser"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useEffect } from "react"; import { User } from "@supabase/supabase-js"; import { archive } from "@/lib/supabase/queries"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { MoreHorizontal, Trash } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; interface MenuProps { documentId: string; } export const Menu = ({ documentId }: MenuProps) => { const supabase = supabaseBrowser(); const router = useRouter(); const [user, setUser] = useState<User | null>(); const onArchive = () => { if (!documentId) return; async function archiveDocument(documentId: string) { try { await archive(documentId); toast.success("Note moved to trash!"); } catch (error) { console.log(error); toast.error("Failed to archive note."); } } archiveDocument(documentId).then(() => router.push("/documents")); }; useEffect(() => { async function getUser() { const { data, error } = await supabase.auth.getUser(); setUser(data.user); } getUser(); }, [supabase.auth]); return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button size="sm" variant="ghost"> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent className="w-60" align="end" alignOffset={8} forceMount > <DropdownMenuItem onClick={onArchive}> <Trash className="w-4 h-4 mr-2" /> Delete </DropdownMenuItem> <DropdownMenuSeparator /> <div className="text-xs text-muted-foreground p-2"> Last edited by : {user?.user_metadata.full_name} </div> </DropdownMenuContent> </DropdownMenu> ); }; Menu.Sketeton = function MenuSketeton() { return <Skeleton className="h-8 w-10" />; };
/** * * Wrapper for props functions validating that they exist * and are actual functions before calling them. * * @param {Function} propFct Function to be tested / called * @param {String} fctName Name of the function (for logging purposes) * @param {String} compName Name of the component (for logging purposes) * @param {Array<Object>=} args Arguments of the function * @param {Function=} cb Callback if the function was called */ const handlePropsFct = ( propFct, fctName = "UNSPECIFIED_FUNCTION", compName = "UNSPECIFIED_COMPONENT", args = undefined, cb = undefined ) => { if (propFct) { if (propFct instanceof Function) { args && args.length > 0 ? propFct(...args) : propFct(); if (cb && cb instanceof Function) { cb(); } } else { let err = `${compName}'s '${fctName}' isn't a function.`; console.error(err); if (cb) { cb(err); } } } else { let err = `${compName}'s '${fctName}' isn't set.`; console.warn(err); if (cb) { cb(err); } } }; module.exports = { handlePropsFct, };
package org.ylan.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.collect.Queues; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.ylan.mapper.GatewayLogMapper; import org.ylan.model.entity.GatewayLogDO; import org.ylan.service.GatewayLogService; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * 网关日志接口实现层 * * @author ylan */ @Slf4j @Service @RequiredArgsConstructor public class GatewayLogServiceImpl extends ServiceImpl<GatewayLogMapper, GatewayLogDO> implements GatewayLogService { /** * 网关日志持久层 */ private final GatewayLogMapper gatewayLogMapper; /** * 是否运行 保证可见行+禁止指令重排 */ volatile boolean isRunning = true; /** * 最大缓存日志数量 条 */ private static final int GatewayLogQueueSize = 1000; /** * 最大缓存日志时间 秒 */ private static final int GatewayLogQueueTime = 60 * 5; /** * 使用LinkedBlockingQueue缓存数据 */ volatile BlockingQueue<GatewayLogDO> gatewayLogQueue = new LinkedBlockingQueue<GatewayLogDO>(); @PostConstruct public void postConstruct() { new Thread(() -> { while (isRunning) { try { List<GatewayLogDO> gatewayLogList = new ArrayList<>(GatewayLogQueueSize + 5); Queues.drain(gatewayLogQueue, gatewayLogList, GatewayLogQueueSize, GatewayLogQueueTime , TimeUnit.SECONDS); batchSaveGatewayLog(gatewayLogList); } catch (Throwable e) { log.error("GatewayLog-Queues error", e); } } }).start(); log.info("GatewayLog-Queues init success"); } @PreDestroy public void destroy() { isRunning = false; List<GatewayLogDO> gatewayLogList = new ArrayList<>(GatewayLogQueueSize + 5); gatewayLogQueue.drainTo(gatewayLogList); batchSaveGatewayLog(gatewayLogList); } @Override @Transactional(rollbackFor = Exception.class) public boolean batchSaveGatewayLog(List<GatewayLogDO> gatewayLogList) { if (gatewayLogList.isEmpty()) return false; return gatewayLogMapper.batchSaveGatewayLog(gatewayLogList) > 0; } @Override public boolean addGatewayLog(GatewayLogDO gatewayLog) { return gatewayLogQueue.add(gatewayLog); } }
package com.example.admin.arouterdemo.dialog; import android.app.Activity; import android.graphics.drawable.ColorDrawable; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.PopupWindow; import com.example.admin.arouterdemo.R; import com.example.admin.arouterdemo.adapter.MyViewPagerAdapter; import java.util.ArrayList; /** * @author bobo * <p> * function:图片展示 * <p> * create_time:2018/8/9 17:21 * update_by: * update_time: */ public class PopuWindowShowPhoto extends PopupWindow implements PopupWindow.OnDismissListener, MyViewPagerAdapter.ViewPagerInter { private static PopupWindow popupWindow; private View contentView; private MyViewPagerAdapter adapter; private ViewPager viewPager; private Activity context; /** * 图片展示 * @param context 上下文对象 * @param urls 图片集合 * @param pos 当前图片位置 */ public void showWindow(final Activity context, ArrayList<String> urls, int pos) { this.context = context; // 用于PopupWindow的View contentView = LayoutInflater.from(context) .inflate(R.layout.popu_window_show_photo, null, false); popupWindow = new PopupWindow( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setContentView(contentView); popupWindow.setAnimationStyle(R.style.alpha_anim); popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000)); popupWindow.setOutsideTouchable(true); popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0); WindowManager.LayoutParams lp = context.getWindow().getAttributes(); lp.alpha = 0.3f; context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); context.getWindow().setAttributes(lp); viewPager = contentView.findViewById(R.id.view_pager); adapter = new MyViewPagerAdapter(context, urls, this); viewPager.setAdapter(adapter); viewPager.setCurrentItem(pos); } @Override public void onDismiss() { WindowManager.LayoutParams lp = context.getWindow().getAttributes(); lp.alpha = 1.0f; context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); context.getWindow().setAttributes(lp); popupWindow.dismiss(); } @Override public void viewPagerClick() { onDismiss(); } }
<template lang="pug"> .curso-main-container.pb-3 BannerInterno .container.tarjeta.tarjeta--blanca.p-4.p-md-5 .titulo-principal.color-acento-botones(data-aos="flip-up") .titulo-principal__numero span 2 h1 Compositor p.mb-4 Los nodos de composición (figura1) permiten mejorar las imágenes, los videos o las secuencias de imágenes. Además, se pueden unificar varios elementos en una misma secuencia, alterando sus colores, brillos, crear máscaras, entre muchos más. Así mismo, se pueden crear composiciones estáticas, las cuales serán homogéneas, y composiciones dinámicas, que a medida que avanza el clip, pueden tener parámetros diferentes, con los nodos se puede cambiar el estado de ánimo que genera la imagen, por ejemplo, una imagen colorida, puede tornarse gris, lo que genera dramatismo; una imagen con tonos azules puede ser fría, o para transmitir rabia o enojo, se puede entintar de color rojo, con el amarillo se puede transmitir alegría, felicidad. .BG04.p-4.mb-4 .row.justify-content-center .titulo-sexto.color-primario(data-aos="fade-right") h5 Figura 1 p Compositor .col-11 figure(data-aos="flip-up") img(src='@/assets/curso/tema2/img01.png') figcaption Nota. Tomado de https://docs.blender.org/manual/es/2.93/compositing/introduction.html .row.mb-4 .col-8 .BG02.p-3 p.text-bold.mb-0 Se podrá revisar este tema con mayor detalle, consultando los videos que encuentra a continuación: LineaTiempoD.color-primario.mb-5(data-aos="fade-down") .row(numero="1" titulo="Herramienta Compositing de <em>Blender</em>") .col-12.tarjeta.BG03.p-4 figure .video iframe(width="560" height="315" src="https://www.youtube.com/embed/_s-iSyC6qYI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen) .row(numero="2" titulo="Nodos Compositing") .col-12.tarjeta.BG03.p-4 figure .video iframe(width="560" height="315" src="https://www.youtube.com/embed/DC3o39Xjoqs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen) h4 Composición multipase p.mb-4 Es la composición con múltiples imágenes, esta información es extraída durante el proceso del #[i render], adquiriendo así datos de la iluminación, colores, #[i shaders], texturas, rugosidades, alfas, profundidades, reflejos, normales, Z-Depht; esto permite que, al combinar toda la información, en el programa de composición, se puedan manipular individualmente cada uno de estos elementos, dependiendo de lo que se necesite reforzar. En la siguiente figura 2, se pueden observar algunos pases: .BG04.p-4.mb-4 .row.justify-content-center .titulo-sexto.color-primario(data-aos="fade-right") h5 Figura 2 p Ejemplo de composición #[i multipase] .col-11 figure(data-aos="flip-up") img(src='@/assets/curso/tema2/img02.png') figcaption Nota. Tomado de https://www.notodoanimacion.es/tecnicas-de-composicion-digital/ </template> <script> export default { name: 'Tema2', data: () => ({ // variables de vue }), mounted() { this.$nextTick(() => { this.$aosRefresh() }) }, updated() { this.$aosRefresh() }, } </script> <style lang="sass"></style>
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head th:replace="fragments/commons::head"> </head> <body> <header th:replace="fragments/commons::navigation"></header> <main role="main"> <div class="jumbotron"> <div class="d-flex justify-content-center h-100"> <div class="card"> <div class="card-header container"> <h3>Add Guide</h3> </div> <div class="card-body"> <form th:object="${guideAddBindingModel}" th:method="POST" th:action="@{/games/guides/{id}/add/(id=${id})}" enctype="multipart/form-data"> <div class="input-group form-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <input th:field="*{guideTitle}" th:errorclass="is-invalid" type="text" minlength="3" maxlength="35" class="form-control" id="gameTitle" name="gameTitle" aria-describedby="gameTitleHelpInline" placeholder="Guide Title"> <small th:if="${#fields.hasErrors('guideTitle')}" th:errors="*{guideTitle}" id="gameTitleHelpInline" class="invalid-feedback bg-danger text-light rounded text-center"> Game title must be between 3 and 35 characters. </small> </div> <div class="input-group form-group"> <div class="input-group form-group"> <textarea th:field="*{description}" th:errorclass="is-invalid" class="form-control z-depth-1" id="exampleFormControlTextarea6" rows="3" minlength="15" placeholder="Add Game Description here..."></textarea> <small id="gameDescriptionHelpInline" class="invalid-feedback bg-danger text-light rounded text-center"> Game description must be more than 15 characters. </small> </div> </div> <div class="form-group log_btn"> <input type="submit" value="Add Guide" class="btn add_game_btn"> </div> </form> </div> </div> </div> </div> </main> <footer th:replace="fragments/commons::footer"></footer> </body> </html>
package com.shobhit97.filmflicks.feature_movie.presentation.util import com.shobhit97.filmflicks.feature_movie.data.dto.movie_details.ProductionCompanyModel import com.shobhit97.filmflicks.feature_movie.domain.model.movie_details.GenreModel import java.text.SimpleDateFormat import java.util.Locale fun String.toLanguageName(): String { return when (this) { "en" -> "English" "es" -> "Spanish" "fr" -> "French" "de" -> "German" "hi" -> "Hindi" else -> this } } fun String.toChangeDateFormat():String { val inputFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val outputFormat = SimpleDateFormat("dd MMM yyyy", Locale.getDefault()) return try { // Parse the input date string into a Date object val date = inputFormat.parse(this) // Format the Date object into the desired output format outputFormat.format(date) } catch (e: Exception) { // Handle parsing or formatting errors here "Invalid Date" } } fun List<ProductionCompanyModel>.getProductionName():String { var productionName = "" if(this.isNotEmpty()) { this.forEachIndexed { index, productionCompanyModel -> productionName += if(index == this.size-1) { productionCompanyModel.name } else { productionCompanyModel.name + " | " } } } return productionName } fun List<GenreModel>.getCategories():String{ var categories = "" if(this.isNotEmpty()) { this.forEachIndexed { index, genreModel -> categories += if(index == this.size-1) { genreModel.name } else { genreModel.name + " | " } } } return categories }
"use client"; import { LoadingSpinner } from "@/app/_components"; import Modal from "@/app/_components/Modal"; import dynamic from "next/dynamic"; import NotFound from "./not-found"; import { useSingleCategoryHook } from "@/app/_category/[id]/SingleCategoriesHook"; import SingleCategoryRenderCandidate from "@/app/_components/SingleCategoryRenderCandidate"; import { SingleCategoryBtn } from "@/app/_components/SingelCategoryBtn"; import { DisplayImage } from "@/app/_components/DisplayImage"; const ClientJs = dynamic(() => import("@/lib/utils/ClientFingerPrint"), { ssr: false, }); const CategoryDetail = ({ params }: { params: { id: number } }) => { const { id } = params; const { setSelected, setImageUrl, setShowModal, setFingerPrint, setCountItem, setVote, selected, imageUrl, showModal, countItem, loading, status, categoryDetail, categoryError, ip, finger_print, voteCandidate, } = useSingleCategoryHook(id); if (categoryError) { return <NotFound />; } if (status === "loading") { return ( <div className="py-20"> <LoadingSpinner /> </div> ); } return ( <> <ClientJs setFingerprint={setFingerPrint} /> <Modal show={showModal} onClose={() => setShowModal(false)}> <div className="justify-center items-center text-2xl font-thin text-center mb-4"> Already voted for this category please vote for other categories <div className="mt-4"> <div className="border-[1px] border-opacity-30 border-t-slate-800"></div> <p className="p-4">{countItem.candidateName}</p> <p>Total Count {countItem.count}</p> </div> </div> </Modal> <div className="flex justify-center text-center gap-16 pt-2 text-black text-[2vh] md:text-[3vh]"> <p>ሐምሌ 1 2013 - ሰኔ 30 2015</p> </div> <div className="flex justify-center text-center gap-6 mx-2 md:mx-10 "> <p className="font-[500] text-[20px] md:text-[40px]"> {categoryDetail.category_name} </p> </div> {/* // */} <div className=" mx-2 md:mx-16 "> <div className="flex flex-col md:flex-row items-center justify-evenly py-10"> <div className="pb-8"> <DisplayImage artistName={countItem.candidateName} imageUrl={imageUrl} className={`md:hidden rounded-[14px] ${ imageUrl === "" ? "" : "shadow-2xl transition-all duration-300 hover:scale-105" } aspect-square object-cover`} /> </div> <SingleCategoryRenderCandidate selected={selected} setSelected={setSelected} setImageUrl={setImageUrl} setVote={setVote} setCountItem={setCountItem} categoryDetail={categoryDetail} ip={ip} finger_print={finger_print} /> <> <div> <DisplayImage artistName={countItem.candidateName} imageUrl={imageUrl} className={`hidden md:block rounded-[14px] ${ selected === 0 ? "" : "shadow-2xl transition-all duration-300 hover:scale-105" } aspect-square object-cover`} /> <SingleCategoryBtn loading={loading} selected={selected} ipv4={ip} finger_print={finger_print} voteCandidate={voteCandidate} /> </div> </> </div> </div> </> ); }; export default CategoryDetail;
import React from "react"; import { useDispatch } from "react-redux"; import { Route } from "react-router-dom"; import { MortuaryUIProvider } from "./CoffinUIContext"; import { CoffinEditDialog } from "./coffin-edit-dialog/CoffinEditDialog"; import { CoffinDeleteDialog } from "./coffin-delete-dialog/CoffinDeleteDialog"; import { CoffinActiveDialog } from "./coffin-active-dialog/CoffinActiveDialog"; import { CoffinCard } from "./coffin-card/CoffinCard"; import { ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import * as actions from "../../_redux/coffin/reduxActions"; import { fetchUserStatusTypes } from "../../../UserMangement/_redux/usersActions"; export function CoffinPage({ history }) { const dispatch = useDispatch(); const moduleUIEvents = { addNewButtonClick: () => { dispatch(fetchUserStatusTypes({ filter: { cf: true } })); history.push("/ibs/read-all-coffinforms/new"); }, openEditDialog: (id) => { dispatch(actions.fetchInfoById(id)); dispatch(fetchUserStatusTypes({ filter: { cf: true } })); history.push(`/ibs/read-all-coffinforms/${id}/edit`); }, openDeleteDialog: (id, status) => { history.push(`/ibs/read-all-coffinforms/${id}/${status}/delete`); }, openActiveDialog: (id) => { history.push(`/ibs/read-all-coffinforms/${id}/active`); }, openReadDialog: (id, isUserRead) => { dispatch(actions.fetchInfoById(id)); dispatch(fetchUserStatusTypes({ filter: { cf: true } })); history.push(`/ibs/read-all-coffinforms/${id}/read`); }, }; return ( <MortuaryUIProvider moduleUIEvents={moduleUIEvents}> <Route exact path="/ibs/read-all-coffinforms/new"> {({ history, match }) => ( <CoffinEditDialog show={match != null} onHide={() => { history.push("/ibs/read-all-coffinforms"); }} isNew={true} /> )} </Route> <Route path="/ibs/read-all-coffinforms/:id/edit"> {({ history, match }) => ( <CoffinEditDialog show={match != null} onHide={() => { history.push("/ibs/read-all-coffinforms"); }} /> )} </Route> <Route path="/ibs/read-all-coffinforms/:id/read"> {({ history, match }) => ( <CoffinEditDialog show={match != null} id={match && match.params.id} userForRead={true} onHide={() => { history.push("/ibs/read-all-coffinforms"); }} /> )} </Route> <Route path="/ibs/read-all-coffinforms/:id/:status/delete"> {({ history, match }) => ( <CoffinDeleteDialog show={match != null} id={match && match.params.id} status={match && match.params.status} onHide={() => { history.push("/ibs/read-all-coffinforms"); }} /> )} </Route> <Route path="/ibs/read-all-coffinforms/:id/active"> {({ history, match }) => ( <CoffinActiveDialog show={match != null} id={match && match.params.id} //status={match && match.params.status} onHide={() => { history.push("/ibs/read-all-coffinforms"); }} /> )} </Route> <CoffinCard /> <ToastContainer position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover /> </MortuaryUIProvider> ); }
#include<iostream> #include"Vehiculo.h" using namespace std; class Furgoneta : protected Vehiculo{ private: string carga; public: Furgoneta(string marca,string color,string modelo,string carga) : Vehiculo(marca,color,modelo){ this->carga = carga; } string getCarga(){ return carga; } string mostrarMarca(){ //mensaje = getMarca(); return getMarca(); } string mostrarColor(){ return getColor(); } string mostrarModelo(){ return getModelo(); } };
import { useState, useRef, useEffect } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import { useLogout } from '../../features/authentication/useLogout'; import Hamburger from 'hamburger-react'; import useOutsideClick from '../../hooks/useOutsideClickforNav'; import Button from '../Button'; import SpinnerMini from '../SpinnerMini'; import logo from '../../assets/logo.png'; import styles from './NotLoggedInNav.module.css'; const AdminNav = () => { const [isHambugerOpen, setHamburgerOpen] = useState(false); const hamburgerRef = useRef(null); const dropdownRef = useRef(null); const { logout, isLoading } = useLogout(); const navigate = useNavigate(); const handleClick = () => { logout(); navigate('/'); }; // Close dropdown when user lands on a new page const closeMenu = () => { setHamburgerOpen(false); }; // Close dropdown when user clicks outside of dropdown useOutsideClick(hamburgerRef, dropdownRef, closeMenu); // Close dropdown when the window is resized to a larger size useEffect(() => { const handleResize = () => { if (window.innerWidth > 950) { setHamburgerOpen(false); } }; window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return ( <div className={styles.navBarContainer}> <Link to="/"> <img src={logo} alt="my student wellbeing logo" /> </Link> <Link to="/"> <h2>Event Hub</h2> </Link> <ul ref={dropdownRef} className={isHambugerOpen ? styles.navMenuDropdown : styles.navMenu} > <div className={styles.menuWrapper}> <li> <Link to="/admin/dashboard" onClick={closeMenu}> DASHBOARD </Link> </li> <li> <Link to="/admin/events" onClick={closeMenu}> EVENT MANAGEMENT </Link> </li> <li> <Link to="/submitevents" onClick={closeMenu}> SUBMIT EVENTS </Link> </li> <li> <Link to="/viewmyevents" onClick={closeMenu}> VIEW MY EVENTS </Link> </li> <li> <Link to="/setting" onClick={closeMenu}> SETTING </Link> </li> </div> <div className={styles.btnWarapper}> <li> <Link to="/" className={styles.btnLink} onClick={closeMenu}> <Button type="navBtn" onClick={handleClick}> {!isLoading ? 'Log Out' : <SpinnerMini />} </Button> </Link> </li> </div> </ul> <div ref={hamburgerRef} className={styles.hamburgerWrapper}> <Hamburger toggled={isHambugerOpen} toggle={() => setHamburgerOpen((prev) => !prev)} label="Show menu" color="#02057b" size={22} /> </div> </div> ); }; export default AdminNav;
import 'package:flutter/material.dart'; class MyTextField extends StatelessWidget { final TextEditingController controller; final String hintText; final bool obscureText; final Widget? suffixIcon; // Nuevo parámetro para el icono al final del TextField const MyTextField({ Key? key, required this.controller, required this.hintText, required this.obscureText, this.suffixIcon, }) : super(key: key); @override Widget build(BuildContext context) { return TextField( controller: controller, obscureText: obscureText, decoration: InputDecoration( enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Color.fromARGB(255, 8, 8, 8)), ), focusedBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.white), ), fillColor: Colors.grey[100], filled: true, hintText: hintText, hintStyle: const TextStyle(color: Color.fromARGB(255, 93, 92, 92)), suffixIcon: suffixIcon, // Usa el nuevo parámetro para el ícono al final ), ); } }
// implement MovieLibrary component here import React from 'react'; import PropTypes from 'prop-types'; import './components.css'; import AddMovie from './AddMovie'; import SearchBar from './SearchBar'; import MovieList from './MovieList'; class MovieLibrary extends React.Component { constructor(props) { super(props); /* Chama o construtor do React.Component */ this.handleChange = this.handleChange.bind(this); this.addNewMovie = this.addNewMovie.bind(this); this.filterMovies = this.filterMovies.bind(this); this.filteredGenreFuncion = this.filteredGenreFuncion.bind(this); this.filteredBookMarkedFunction = this.filteredBookMarkedFunction.bind(this); this.filteredTextFunction = this.filteredTextFunction.bind(this); this.state = { searchText: '', bookmarkedOnly: false, selectedGenre: '', movies: props.movies, }; } filteredGenreFuncion(chosenGenre, moviesArray) { if (chosenGenre !== '') { return moviesArray.filter((movie) => movie.genre === chosenGenre); } return moviesArray; } filteredBookMarkedFunction(filteredGenre, isBookMarked) { if (isBookMarked !== false) { return filteredGenre.filter((movie) => movie.bookmarked === true); } return filteredGenre; } filteredTextFunction(filteredBookMarked, chosenText) { if (chosenText !== '') { return filteredBookMarked.filter((movie) => movie.title.toLowerCase().includes(chosenText.toLowerCase()) === true || movie.subtitle.toLowerCase().includes(chosenText.toLowerCase()) === true || movie.storyline.toLowerCase().includes(chosenText.toLowerCase()) === true); } return filteredBookMarked; } handleChange({ target }) { const { name, type, checked, value } = target; const valueType = type === 'checkbox' ? checked : value; this.setState({ [name]: valueType }, () => this.filterMovies()); } filterMovies() { const moviesArray = this.state.movies; const chosenGenre = this.state.selectedGenre; const isBookMarked = this.state.bookmarkedOnly; const chosenText = this.state.searchText; const filteredGenre = this.filteredGenreFuncion(chosenGenre, moviesArray); const filteredBookMarked = this.filteredBookMarkedFunction(filteredGenre, isBookMarked); const filteredText = this.filteredTextFunction(filteredBookMarked, chosenText); return filteredText; } addNewMovie(newMovie) { const movies = this.state.movies; this.setState({ movies: [...movies, newMovie] }); } render() { return ( <div> <div className="form-section"> <SearchBar searchText={this.state.searchText} onSearchTextChange={this.handleChange} bookmarkedOnly={this.state.bookmarkedOnly} onBookmarkedChange={this.handleChange} selectedGenre={this.state.selectedGenre} onSelectedGenreChange={this.handleChange} /> <AddMovie onClick={this.addNewMovie} /> </div> <MovieList movies={this.filterMovies()} /> </div> ); } } MovieLibrary.propTypes = { movies: PropTypes.arrayOf(PropTypes.object).isRequired }; export default MovieLibrary;
#include <stdio.h> #include <string.h> #include "3-calc.h" /** * get_op_func - check operator and select function * @s: operator char * Return: selected function or NULL */ int (*get_op_func(char *s))(int, int) { op_t ops[] = { {"+", op_add}, {"-", op_sub}, {"*", op_mul}, {"/", op_div}, {"%", op_mod}, {NULL, NULL} }; int i = 0; while (ops[i].op) { if (*s == *ops[i].op && strlen(s) == 1) return (ops[i].f); i++; } return (NULL); }
// Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause pragma ComponentBehavior: Bound import QtQuick //! [0] Window { id: window //! [0] width: 360 height: 640 visible: true Item { id: statesItem visible: false state: "loading" states: [ State { name: "loading" PropertyChanges { main.opacity: 0 } PropertyChanges { wait.opacity: 1 } }, State { name: "ready" PropertyChanges { main.opacity: 1 } PropertyChanges { wait.opacity: 0 } } ] } //! [1] AppModel { id: appModel onReadyChanged: { if (appModel.ready) statesItem.state = "ready" else statesItem.state = "loading" } } //! [1] Item { id: wait anchors.fill: parent Text { text: "Loading weather data..." anchors.centerIn: parent font.pointSize: 18 } } Item { id: main anchors.fill: parent Column { spacing: 6 anchors { fill: parent topMargin: 6; bottomMargin: 6; leftMargin: 6; rightMargin: 6 } Rectangle { width: parent.width height: 25 color: "lightgrey" Text { text: (appModel.hasValidCity ? appModel.city : "Unknown location") + (appModel.useGps ? " (GPS)" : "") anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter } MouseArea { anchors.fill: parent onClicked: { if (appModel.useGps) { appModel.useGps = false appModel.city = "Brisbane" } else { switch (appModel.city) { case "Brisbane": appModel.city = "Oslo" break case "Oslo": appModel.city = "Helsinki" break case "Helsinki": appModel.city = "New York" break case "New York": appModel.useGps = true break } } } } } //! [3] BigForecastIcon { id: current width: main.width -12 height: 2 * (main.height - 25 - 12) / 3 weatherIcon: (appModel.hasValidWeather ? appModel.weather.weatherIcon : "sunny") //! [3] topText: (appModel.hasValidWeather ? appModel.weather.temperature : "??") bottomText: (appModel.hasValidWeather ? appModel.weather.weatherDescription : "No weather data") MouseArea { anchors.fill: parent onClicked: { appModel.refreshWeather() } } //! [4] } //! [4] Row { id: iconRow spacing: 6 width: main.width - 12 height: (main.height - 25 - 24) / 3 property int daysCount: appModel.forecast.length property real iconWidth: (daysCount > 0) ? (iconRow.width / daysCount) - 10 : iconRow.width property real iconHeight: iconRow.height Repeater { model: appModel.forecast ForecastIcon { required property string dayOfWeek required property string temperature required property string weatherIcon id: forecast1 width: iconRow.iconWidth height: iconRow.iconHeight topText: (appModel.hasValidWeather ? dayOfWeek : "??") bottomText: (appModel.hasValidWeather ? temperature : ("??" + "/??")) weatherIcon: (appModel.hasValidWeather ? weatherIcon : "sunny") } } } } } //! [2] } //! [2]
//fazer entrada de dados notas de alunos cadastrar alunos e notas, exibir relatório de notas e alunos.exibir aprovado ou nao usando array e switch case.usar for e while. //biblioteca de entrada de dados. const prompt = require("prompt-sync")({ sigint: true }); let alunos = []; // array vazio. // menu para melhorar a usabilidade do código. while (true) { console.log("Menu:"); console.log("1 - Cadastrar aluno"); console.log("2 - Exibir relatório"); console.log("3 - Sair"); const opcao = prompt("Escolha uma opção: "); // entrada de dados pelo usuário. switch (opcao) { case "1": let nome = prompt("Digite o nome do aluno: "); let nota1 = +prompt("Digite a primeira nota do aluno: "); let nota2 = +prompt("Digite a segunda nota do aluno: "); if (nota1 <= 10 && nota2 <= 10 && !isNaN(nota1) && !isNaN(nota2) && typeof nome === 'string') { alunos.push(cadastro(nome, nota1, nota2)); console.log("Aluno cadastrado com sucesso!\n"); } else if (isNaN(nota1) || isNaN(nota2)) { console.log("Digite notas válidas (0 a 10)!\n"); } else if (typeof nome !== 'string') { console.log('Digite apenas letras!'); } break; case "2": console.log("Relatório de notas:\n"); // percorrendo a entrada de dados do aluno no array. for (let i = 0; i < alunos.length; i++) { relatorio(alunos[i]); status(media(alunos[i].notas)); console.log(""); } break; case "3": console.log("Saindo..."); return; default: console.log("Opção inválida!"); break; } } // função para cadastrar aluno. function cadastro(nome, nota1, nota2) { return { nome: nome, notas: [nota1, nota2], }; } // retornar os dados do aluno cadastrado. function relatorio(aluno) { console.log( `Aluno: ${aluno.nome} - Nota 1: ${aluno.notas[0]} - Nota 2: ${ aluno.notas[1] } - Média: ${media(aluno.notas)}` ); } // função para calcular médias. function media(notas) { return (Math.round(notas[0]) + Math.round(notas[1])) / 2; } // função para retornar se o aluno passou por média. function status(studentMedia) { if (studentMedia >= 7) { console.log("Aluno aprovado."); } else if (studentMedia >= 5 && studentMedia < 7) { console.log("Aluno em recuperação."); } else if (studentMedia < 5) { console.log("Aluno reprovado."); } else { console.log("Erro!"); } }
import { WebSocketGateway, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect, SubscribeMessage, WebSocketServer, } from '@nestjs/websockets'; import { Logger, Controller } from '@nestjs/common'; import { Server } from 'socket.io'; import * as os from 'os'; import * as diskinfo from 'diskinfo'; @Controller('system') @WebSocketGateway(5000, { transports: ['websocket'], }) export class SystemGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { private logger: Logger = new Logger('SystemGateway'); @WebSocketServer() server: Server; afterInit(server: any) { this.logger.log('Initialized!'); this.logger.log(server); } handleConnection(client: any, ...args: any[]) { this.logger.log(`Client connected: ${client}`); this.logger.log(args); } handleDisconnect(client: any) { this.logger.log(`Client disconnected: ${client.id}`); } @SubscribeMessage('getstatus') async onMessage() { // 获取CPU利用率 只在Linux环境下有效 const cpuUsage = Math.round( (os.loadavg().reduce((a, b) => a + b) * 100) / 3, ); console.log('CPU利用率:', cpuUsage); // 获取内存信息 const totalMemory = os.totalmem(); const freeMemory = os.freemem(); const usedMemory = totalMemory - freeMemory; console.log('总内存:', totalMemory); console.log('可用内存:', freeMemory); console.log('已使用内存:', usedMemory); const disk = await new Promise((resolve) => { diskinfo.getDrives((err: any, aDrives: Array<any>) => { // 筛选根目录,Linux下根目录为/ const root = aDrives.find((v) => v.mounted == '/'); console.log('磁盘:' + root.mounted); console.log('磁盘总内存:' + root.blocks); console.log('磁盘已用内存:' + root.used); console.log('磁盘可用内存:' + root.available); console.log('磁盘已用内存百分比: ' + root.capacity); console.log('-----------------------------------------'); resolve({ total: root.blocks, used: root.used }); }); }); return { memory: { totalMemory, freeMemory, }, cpuUsage, disk, }; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./CSS/style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css"/> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" /> <title>Fashi</title> </head> <body> <div class="container"> <div class="nav"> <div class="logo"> <img src="./assests/logo.png.webp" alt=""> </div> <div class="search-bar"> <div class="button-nav"> <div class="button"> All Categories <span class="material-symbols-outlined">arrow_drop_down</span> </div> </div> <div class="search-nav"> <input type="text" placeholder="What do You Need ?"> </div> <div class="search-icon"> <span class="material-symbols-outlined search-icon">search</span> </div> </div> <div class="nav-right"> <span class="material-symbols-outlined" style="cursor: pointer;">favorite</span> <div class="shopping-bag"> <span class="material-symbols-outlined" style="cursor: pointer;">shopping_bag</span> <div class="cart-hover" style="z-index: 3;"> <div class="cart-item"> <img src="./assests/select-product-1.jpg.webp" alt=""> <div class="item-details"> <p>$60.00 x 1</p> <h5>Kabino Bedside Table</h5> </div> </div> <div class="cart-item"> <img src="./assests/select-product-2.jpg.webp" alt=""> <div class="item-details"> <p>$120.00 x 2</p> <h5>Kabino Bedside Table</h5> </div> </div> <button>VIEW CARD</button> <br> <button style="background-color: black;">CHECK OUT</button> </div> </div> <span>$500</span> </div> </div> </div> <div class="nav-container"> <div class="nav-bar"> <div class="nav-buttons"> <div class="department-button"> <button style="display: flex; align-items: center;justify-content: space-around;"> <span class="material-symbols-outlined">menu</span> ALL DEPARTMENTS <span class="material-symbols-outlined">arrow_drop_down</span> </button> <div class="nav-button-content" style="z-index: 3;"> <ul style="text-decoration: none;"> <p>Womens Clothing</p> <p>Men's Clothing</p> <p>Underwear</p> <p>Kid's Clothing</p> <p>Brand Fashion</p> <p>Accessories</p> <p>Luxury Brands</p> <p>Brand Outdoor Apparel</p> </ul> </div> </div> <div class="nav-main"> <ul> <li id="home"><a href="">HOME</a></li> <li id="shop"><a href="shop.html">SHOP</a></li> <li id="collection"><a href="">COLLECTION</a></li> <li id="blog"><a href="">BLOG</a></li> <li id="contact"><a href="">CONTACT</a></li> <li id="pages"><a href="">PAGES</a></li> </ul> </div> </div> <div class="nav-menu"> <button> <span class="material-symbols-outlined">menu</span> menu </button> </div> </div> </div> <div class="swiper" style="margin: 0;padding: 0;"> <!-- Additional required wrapper --> <div class="swiper-wrapper" style="margin: 0;padding: 0;"> <!-- Slides --> <div class="swiper-slide slide-1" style="background-image: url(/assests/swiper\ 1.avif);margin: 0;padding: 0;"> <div class="content"> <div class="heading"> <h1>BLACK FRIDAY</h1> </div> <div class="details"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore minus excepturi ipsa praesentium, tempora placeat qui mollitia, esse dicta quas optio cupiditate, sapiente quos earum sint possimus accusamus error voluptatum? </div> </div> <div class="btn"> <button>SHOP NOW</button> </div> </div> <div class="swiper-slide slide-2" style="background-image: url(/assests/swiper\ 1\ pics.jpg);margin: 0;padding: 0;" > <div class="content"> <div class="heading"> <h1>BLACK FRIDAY</h1> </div> <div class="details"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore minus excepturi ipsa praesentium, tempora placeat qui mollitia, esse dicta quas optio cupiditate, sapiente quos earum sint possimus accusamus error voluptatum? </div> </div> <div class="btn"> <button>SHOP NOW</button> </div> </div> <div class="swiper-slide slide-3" style="background-image: url(/assests/swiper\ 3.avif);margin: 0;padding: 0;"> <div class="content"> <div class="heading"> <h1>BLACK FRIDAY</h1> </div> <div class="details"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore minus excepturi ipsa praesentium, tempora placeat qui mollitia, esse dicta quas optio cupiditate, sapiente quos earum sint possimus accusamus error voluptatum? </div> </div> <div class="btn"> <button>SHOP NOW</button> </div> </div> </div> <!-- If we need pagination --> <div class="swiper-pagination"></div> <!-- If we need navigation buttons --> <div class="swiper-button-prev" style="color:orange"></div> <div class="swiper-button-next" style="color: orange;"></div> <!-- If we need scrollbar --> <div class="swiper-scrollbar" style="color: orange;"></div> </div> <div class="gender-section"> <div class="men"> <img src="/assests/men.webp" alt=""> <span>Men's</span> </div> <div class="women"> <img src="/assests/women.avif" alt=""> <span>Women's</span> </div> <div class="kid"> <img src="/assests/kids.avif" alt=""> <span>Kids's</span> </div> </div> <div class="women-section"> <div class="aside-1"> <h1 style="font-size: 70px;">Women's</h1> <h2 style="text-decoration: underline;">Discover More</h2> </div> <div class="main"> <div class="top-section"> <ul> <li style="text-decoration: underline;">Clothing</li> <li style="opacity: 0.5;">Handbag</li> <li style="opacity: 0.5;">Shoes</li> <li style="opacity: 0.5;">Accessories</li> </ul> </div> <div class="swiper mySwiper" style="background-color: white;"> <div class="swiper-wrapper"> <div class="swiper-slide slide-1" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-2" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-3" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-4" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-1" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-2" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-3" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-4" style="background-color: red;cursor: pointer;"> <span class="material-symbols-outlined fav-btn">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> </div> </div> </div> </div> <div class="deal-container"> <div class="deal-details"> <h1 style="text-decoration: underline;">Deal Of The Week</h1> <p style="width: 75%;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem odio explicabo dicta atque cupiditate saepe architecto harum! Iusto,</p> <p style="color: gray;"><span style="color: orange;font-size: 25px;font-weight: bolder;">$35.00</span>/Combo Offer</p> <div class="deal-timer"> <div class="deal-timer-display"> <h1 id="days">06</h1> <h1 id="hours">10</h1> <h1 id="minutes">50</h1> <h1 id="seconds">60</h1> </div> <div class="deal-date-display"> <p>DAYS</p> <p>HOURS</p> <p>MINUTES</p> <p>SECONDS</p> </div> </div> <button>SHOP NOW</button> </div> <div class="deal-img"> <img src="/assests/deal img.avif" alt=""> </div> </div> <div class="women-section"> <div class="aside-1" style="background-image: url(/assests/men\ section\ img.avif);"> <h1 style="font-size: 70px;">Men's</h1> <h2 style="text-decoration: underline;">Discover More</h2> </div> <div class="main"> <div class="top-section"> <ul> <li style="text-decoration: underline;">Clothing</li> <li style="opacity: 0.5;">Belts</li> <li style="opacity: 0.5;">Shoes</li> <li style="opacity: 0.5;">Accessories</li> </ul> </div> <div class="swiper mySwiper" style="background-color: white"> <div class="swiper-wrapper"> <div class="swiper-slide slide-1" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 1.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-2" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 2.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-3" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 3.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-4" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 4.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-1" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 1.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-2" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 2.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-3" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 3.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> <div class="swiper-slide slide-4" style="background-color: red;cursor: pointer;background-image: url(/assests/men\ shirt\ 4.avif);"> <span class="material-symbols-outlined fav-btn" style="color: white;">favorite</span> <div class="swiper-hover-btn"> <span class="material-symbols-outlined" style="background-color: orange; padding:5px;margin: 5px;">bookmark_add</span> <p style="background-color: white;font-size: 20px;padding:5px;">Quick Details</p> <span class="material-symbols-outlined" style="margin: 5px;background-color: white;padding:5px">share</span> </div> </div> </div> </div> </div> </div> <footer> <div class="left"> <img src="/assests/logo light.webp" alt=""> <p>Address: 60-49 Road 11378 New</p> <p>York</p> <p>Phone: +65 11.188.888</p> <p>Email: [email protected]</p> </div> <div class="main"> <div class="main-left"> <h2>Information</h2> <p>About Us</p> <p>Checkout</p> <p>Contact</p> <p>Service</p> </div> <div class="main-right"> <h2>My Account</h2> <p>My Account</p> <p>Contact</p> <p>Shopping Cart</p> <p>Shop</p> </div> </div> <div class="right"> <p>Join Our Newsletter</p> <div class="news-btn"> <input type="text" style="width: 250px;background-color: gray;"> <button style="position: relative;right: 34px;">Submit</button> </div> <p>Get E-mail updates about our latest shop and special offers.</p> </div> </footer> <script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script> <script src="script.js"></script> </body> </html>
package com.xili.loinfo.blog.controller; import com.xili.loinfo.blog.domain.Authority; import com.xili.loinfo.blog.domain.User; import com.xili.loinfo.blog.service.AuthorityService; import com.xili.loinfo.blog.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import java.util.ArrayList; import java.util.List; /** * 主页控制器 * @author xili * @since 2020/1/8 18:57 **/ @Controller public class MainController { private static final Long ROLE_USER_AUTHORITY_ID = 2L; @Autowired private UserService userService; @Autowired private AuthorityService authorityService; @GetMapping("/") public String root() { return "redirect:/index"; } /** * 获取登录页面 * @return */ @GetMapping("/login") public String login(){ return "login"; } public String loginError(Model model) { model.addAttribute("loginError", true); model.addAttribute("errorMsg", "登陆失败,账号或者密码错误!"); return "lgoin"; } @GetMapping("/register") public String register(){ return "register"; } /** * 注册用户 * @param user * @return */ @PostMapping("/register") public String registerUser(User user) { List<Authority> authorities = new ArrayList<>(); authorities.add(authorityService.getAuthorityById(ROLE_USER_AUTHORITY_ID)); user.setAuthorities(authorities); userService.saveOrUpdateUser(user); return "redirect:/login"; } @GetMapping("/search") public String serach() { return "search"; } }
import React, { useContext } from "react"; import "./Card.css"; import { themeContext } from "../../Context"; const Card = ({ emoji, heading, detail, color }) => { const theme = useContext(themeContext); const darkMode = theme.state.darkMode; return ( <div className="card" style={{ borderColor: { color }, background: !darkMode ? "rgba(255, 255, 255, 0.26)" : "rgba(255, 255, 255, 0.95)", }} > <img src={emoji} alt="" /> <span style={{ color: darkMode && "black" }}>{heading}</span> <span style={{ color: darkMode && "black" }}>{detail}</span> <button className="c-button">LEARN MORE</button> </div> ); }; export default Card;
const LEVA_STRELICA = 37; const DESNA_STRELICA = 39; const SPACE = 32; const IGRA_SIRINA = 800; const IGRA_VISINA = 600; const IGRAC_SIRINA = 40; const IGRAC_MAX_BRZINA = 500; const LASER_MAX_BRZINA = 300; const LASER_COOLDOWN = 0.5; const NEPRIJATELJI_PO_REDU = 10; const NEPRIJATELJ_HORIZONTAL_PADDING = 80; const NEPRIJATELJ_VERTICAL_PADDING = 70; const NEPRIJATELJ_VERTICAL_SPACING = 80; const NEPRIJATELJ_COOLDOWN = 10; var poeni=0; const STANJE_IGRE = { vreme: Date.now(), levaStr: false, desnaStr: false, spacePr: false, igracX: 0, igracY: 0, igracCooldown: 0, laseri: [], neprijatelji: [], neprijateljLaseri: [], krajIgre: false }; function presecanje(r1, r2) { return !( r2.left > r1.right || r2.right < r1.left || r2.top > r1.bottom || r2.bottom < r1.top ); } function pozicija(el, x, y) { el.style.transform = `translate(${x}px, ${y}px)`; } function granica(v, min, max) { if (v < min) { return min; } else if (v > max) { return max; } else { return v; } } function rand(min, max) { if (min === undefined) min = 0; if (max === undefined) max = 1; return min + Math.random() * (max - min); } function napraviIgraca(container) { STANJE_IGRE.igracX = IGRA_SIRINA / 2; STANJE_IGRE.igracY = IGRA_VISINA - 50; const igrac = document.createElement("img"); igrac.src = "slike/player-red-1.png"; igrac.className = "igrac"; container.appendChild(igrac); pozicija(igrac, STANJE_IGRE.igracX, STANJE_IGRE.igracY); } function unistiIgraca(container, igrac) { container.removeChild(igrac); STANJE_IGRE.krajIgre = true; const audio = new Audio("audio/loser.ogg"); audio.play(); } function updateIgrac(vr,container) { if (STANJE_IGRE.levaStr) { STANJE_IGRE.igracX -= vr * IGRAC_MAX_BRZINA; } if (STANJE_IGRE.desnaStr) { STANJE_IGRE.igracX += vr * IGRAC_MAX_BRZINA; } STANJE_IGRE.igracX = granica(STANJE_IGRE.igracX, IGRAC_SIRINA, IGRA_SIRINA - IGRAC_SIRINA); if (STANJE_IGRE.spacePr && STANJE_IGRE.igracCooldown <= 0) { napraviLaser(container, STANJE_IGRE.igracX, STANJE_IGRE.igracY); STANJE_IGRE.igracCooldown = LASER_COOLDOWN; } if (STANJE_IGRE.igracCooldown > 0) { STANJE_IGRE.igracCooldown -= vr; } const igrac = document.querySelector(".igrac"); pozicija(igrac, STANJE_IGRE.igracX, STANJE_IGRE.igracY); } function napraviLaser(container, x, y) { const element = document.createElement("img"); element.src = "slike/laser-red-5.png"; element.className = "laser"; container.appendChild(element); const laser = { x, y, element }; STANJE_IGRE.laseri.push(laser); const audio = new Audio("audio/laser9.ogg"); audio.play(); pozicija(element, x, y); } function updateLaser(vr, container) { const laseri = STANJE_IGRE.laseri; for (let i = 0; i < laseri.length; i++) { const laser = laseri[i]; laser.y -= vr * LASER_MAX_BRZINA; if (laser.y < 0) { unistiLaser(container, laser); } pozicija(laser.element, laser.x, laser.y); const r1 = laser.element.getBoundingClientRect(); const neprijatelji = STANJE_IGRE.neprijatelji; for (let j = 0; j < neprijatelji.length; j++) { const neprijatelj = neprijatelji[j]; if (neprijatelj.jeUnisten) continue; const r2 = neprijatelj.element.getBoundingClientRect(); if (presecanje(r1, r2)) { unistiNeprijatelja(container, neprijatelj); unistiLaser(container, laser); break; } } } STANJE_IGRE.laseri = STANJE_IGRE.laseri.filter(e => !e.jeUnisten); } function unistiLaser(container, laser) { container.removeChild(laser.element); laser.jeUnisten = true; } function napraviNeprijatelja(container, x, y) { const element = document.createElement("img"); element.src = "slike/plavo.png"; element.className = "neprijatelj"; container.appendChild(element); const neprijatelj = {x, y, cooldown: rand(0.5, NEPRIJATELJ_COOLDOWN),element}; STANJE_IGRE.neprijatelji.push(neprijatelj); pozicija(element, x, y); } function updateNeprijatelj(vr, container) { const dx = Math.sin(STANJE_IGRE.vreme / 1000.0) * 50; const dy = Math.cos(STANJE_IGRE.vreme / 1000.0) * 10; const neprijatelji = STANJE_IGRE.neprijatelji; for (let i = 0; i < neprijatelji.length; i++) { const neprijatelj = neprijatelji[i]; const x = neprijatelj.x + dx; const y = neprijatelj.y + dy; pozicija(neprijatelj.element, x, y); neprijatelj.cooldown -= vr; if (neprijatelj.cooldown <= 0) { napraviNLaser(container, x, y); neprijatelj.cooldown = NEPRIJATELJ_COOLDOWN; } } STANJE_IGRE.neprijatelji = STANJE_IGRE.neprijatelji.filter(e => !e.jeUnisten); } function unistiNeprijatelja(container, neprijatelj) { container.removeChild(neprijatelj.element); neprijatelj.jeUnisten = true; updatePoeni(); } function napraviNLaser(container, x, y) { const element = document.createElement("img"); element.src = "slike/laser-blue-7.png"; element.className = "n-laser"; container.appendChild(element); const laser = { x, y, element }; STANJE_IGRE.neprijateljLaseri.push(laser); pozicija(element, x, y); } function updateNLaser(vr, container) { const laseri = STANJE_IGRE.neprijateljLaseri; for (let i = 0; i < laseri.length; i++) { const laser = laseri[i]; laser.y += vr * LASER_MAX_BRZINA; if (laser.y > IGRA_VISINA) { unistiLaser(container, laser); } pozicija(laser.element, laser.x, laser.y); const r1 = laser.element.getBoundingClientRect(); const igrac = document.querySelector(".igrac"); const r2 = igrac.getBoundingClientRect(); if (presecanje(r1, r2)) { unistiIgraca(container, igrac); break; } } STANJE_IGRE.neprijateljLaseri = STANJE_IGRE.neprijateljLaseri.filter(e => !e.jeUnisten); } function inicijalizacija() { const container = document.querySelector(".igra"); napraviIgraca(container); const razmak = (IGRA_SIRINA - NEPRIJATELJ_HORIZONTAL_PADDING * 2) / (NEPRIJATELJI_PO_REDU - 1); for (let j = 0; j < 3; j++) { const y = NEPRIJATELJ_VERTICAL_PADDING + j * NEPRIJATELJ_VERTICAL_SPACING; for (let i = 0; i < NEPRIJATELJI_PO_REDU; i++) { const x = i * razmak + NEPRIJATELJ_HORIZONTAL_PADDING; napraviNeprijatelja(container, x, y); } } } function pobeda() { return STANJE_IGRE.neprijatelji.length === 0; } function updatePoeni(){ poeni=poeni+100; var a=document.getElementById('abc'); a.innerHTML=poeni; } function update(e) { const trenutnoVreme = Date.now(); const vr = (trenutnoVreme - STANJE_IGRE.vreme) / 1000; if (STANJE_IGRE.krajIgre) { document.querySelector(".kraj-igre").style.display = "block"; return; } if (pobeda()) { document.querySelector(".pobeda").style.display = "block"; return; } const container = document.querySelector(".igra"); updateIgrac(vr, container); updateLaser(vr, container); updateNeprijatelj(vr, container); updateNLaser(vr, container); STANJE_IGRE.vreme = trenutnoVreme; window.requestAnimationFrame(update); } function onKeyDown(e) { if (e.keyCode === LEVA_STRELICA) { STANJE_IGRE.levaStr = true; } else if (e.keyCode === DESNA_STRELICA) { STANJE_IGRE.desnaStr = true; } else if (e.keyCode === SPACE) { STANJE_IGRE.spacePr= true; } } function onKeyUp(e) { if (e.keyCode === LEVA_STRELICA) { STANJE_IGRE.levaStr = false; } else if (e.keyCode === DESNA_STRELICA) { STANJE_IGRE.desnaStr = false; } else if (e.keyCode === SPACE) { STANJE_IGRE.spacePr = false; } } inicijalizacija(); window.addEventListener("keydown", onKeyDown); window.addEventListener("keyup",onKeyUp); window.requestAnimationFrame(update);
import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar'; import { ActivatedRoute, Router } from '@angular/router'; import { LoanApi } from 'src/app/api/loan-api'; import { LoanModel } from 'src/app/model/loan-model'; import { QuestionsModel } from 'src/app/model/questions-model'; import { Subscription } from 'src/app/model/subscription'; import { LoanService } from 'src/app/service/loan.service'; import { SubscriptionService } from 'src/app/service/subscription.service'; @Component({ selector: 'app-apply-loan', templateUrl: './apply-loan.component.html', styleUrls: ['./apply-loan.component.scss'], }) export class ApplyLoanComponent implements OnInit { payments: number = 0; loanAmount: number = 0; interest: number = 0; selectedValue!: Subscription; amount: number = 0; subscriptions!: Subscription[]; durationInSeconds = 5; danger: boolean = true; loading: boolean = false; submitted: boolean = false; answerId!: string; constructor( private routerAcive: ActivatedRoute, private _snackBar: MatSnackBar, private router: Router, private loanService: LoanService, private subscriptionService: SubscriptionService ) {} ngOnInit(): void { this.getSubscription(); this.routerAcive.params.subscribe((params) => { this.answerId = params.id; }); } openSnackBar(message: string) { const configureSnackBar = new MatSnackBarConfig(); configureSnackBar.duration = 5000; configureSnackBar.horizontalPosition = 'center'; configureSnackBar.verticalPosition = 'bottom'; configureSnackBar.panelClass = this.danger ? 'snackbar-danger' : 'snackbar-success'; this._snackBar.open(message, undefined, configureSnackBar); } getSubscription() { this.subscriptionService.getSubscriptions().subscribe((response) => { console.log(response); this.subscriptions = response; }); } applyLoan() { const loan = new LoanModel(); loan.interest = this.interest; loan.payments = this.payments; loan.totalAmount = this.loanAmount; loan.loanAmount = this.amount loan.subscriptionModel = this.selectedValue; const que = new QuestionsModel(); que.id = parseInt(this.answerId); loan.question = que; this.loanService.requestLoan(loan).subscribe( (response) => { console.log(response); this.loading = false; this.danger = false; this.openSnackBar(response.message); }, (error: HttpErrorResponse) => { this.loading = false; this.openSnackBar(error.message); } ); } calculateLoan() { console.log(this.amount); console.log(this.selectedValue); this.interest = (this.amount * Number.parseInt(this.selectedValue.interest)) / 100; this.loanAmount = Number.parseInt(this.amount.toString()) + Number.parseInt(this.interest.toString()); this.payments = this.loanAmount / Number.parseInt(this.selectedValue.period); } }
package router import ( "fmt" "go-networking/ginh/file" "go-networking/ginh/global" "go-networking/ginh/helloworld" "go-networking/ginh/user" "go-networking/log" "time" "github.com/gin-gonic/gin" ) func InitRouter(r *gin.Engine) { log.Info("Init router") r.Use(gin.CustomRecovery(global.ErrorHandler)) r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { // your custom format return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n", param.ClientIP, param.TimeStamp.Format(time.RFC1123), param.Method, param.Path, param.Request.Proto, param.StatusCode, param.Latency, param.Request.UserAgent(), param.ErrorMessage, ) })) r.Use(func(c *gin.Context) { if c.FullPath() == "/login" { log.Info("Passing through the exact URI filter.") c.Next() } else { c.Next() } }) // order is very import since auth protection will not work if the middleware is not registered. // user.InitAuthMiddleware(r) log.Info("Init auth middleware completed") v1 := r.Group("/api/v1") publicGroup := v1.Group("/") protectGroup := v1.Group("/") protectGroup.Use(user.AuthMiddleware()) user.InitRouter(publicGroup, protectGroup) file.InitRouter(protectGroup) helloworld.InitRouter(r) log.Info("Init router completed") }
const express = require ('express'); const app = express (); //captura de datos// app.use(express.urlencoded({extended:false})); app.use(express.json()); //invoco a dotenv// const dotenv = require ('dotenv'); dotenv.config({path: './env/.env'}); //directorio public// app.use('/resources', express.static('public')); app.use('/resources', express.static(__dirname + '/public')); //ejs// app.set('view engine', 'ejs'); //motor bcrypts// const bcryptsjs = require('bcryptjs'); //var de session// const session = require ('express-session'); app.use(session({ secret: 'secret', resave: true, saveUninitialized: true })); //BD// const connection = require('./db/db'); //Rutas// app.get('/', (req, res) => { res.render('index'); }); app.get('/login', (req, res) => { res.render('login'); }); app.get('/disney', (req, res) => { res.render('disney'); }); app.get('/register', (req, res) => { res.render('register'); }); app.listen(3000, (req, res)=>{ console.log('fiumbaa'); }); // Registro // app.post('/register', async (req, res)=>{ const id_mail = req.body.email; const contraseña = req.body.contraseña; let contraseñaHaash = await bcryptsjs.hash(contraseña, 8); connection.query('INSERT INTO personas SET ?', {id_mail:id_mail, contraseña:contraseñaHaash}, async(error, results)=>{ if(error){ console.log(error); }else { res.redirect('/'); } }); }); //login// app.post('/login', async (req, res)=>{ const id_mail = req.body.email; const contraseña = req.body.contraseña; let contraseñaHaash = await bcryptsjs.hash(contraseña, 8); if(id_mail && contraseña){ connection.query('SELECT * FROM personas WHERE id_mail = ?', [id_mail] , async(error, results)=>{ if(results.length == 0 || ! (await bcryptsjs.compare(contraseña, results[0].contraseña))){ res.redirect('/login'); console.log(results); console.log(contraseña) } else { res.redirect('/disney'); console.log(results); console.log(contraseña) } }) } })
/* LibISDB Copyright(c) 2017-2020 DBCTRADO This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** @file EventInfo.cpp @brief 番組情報 @author DBCTRADO */ #include "../LibISDBPrivate.hpp" #include "EventInfo.hpp" #include "../Utilities/Sort.hpp" #include "../Base/DebugDef.hpp" namespace LibISDB { bool EventInfo::operator == (const EventInfo &rhs) const noexcept { return IsEqual(rhs) && (Type == rhs.Type) && (UpdatedTime == rhs.UpdatedTime) && (SourceID == rhs.SourceID); } bool EventInfo::IsEqual(const EventInfo &Op) const noexcept { return (NetworkID == Op.NetworkID) && (TransportStreamID == Op.TransportStreamID) && (ServiceID == Op.ServiceID) && (EventID == Op.EventID) && (StartTime.IsValid() == Op.StartTime.IsValid()) && ((!StartTime.IsValid() || (StartTime == Op.StartTime))) && (Duration == Op.Duration) && (RunningStatus == Op.RunningStatus) && (FreeCAMode == Op.FreeCAMode) && (EventName == Op.EventName) && (EventText == Op.EventText) && (ExtendedText == Op.ExtendedText) && (VideoList == Op.VideoList) && (AudioList == Op.AudioList) && (ContentNibble == Op.ContentNibble) && (EventGroupList == Op.EventGroupList) && (IsCommonEvent == Op.IsCommonEvent) && ((!IsCommonEvent || (CommonEvent == Op.CommonEvent))); } bool EventInfo::HasBasic() const noexcept { return !!(Type & TypeFlag::Basic); } bool EventInfo::HasExtended() const noexcept { return !!(Type & TypeFlag::Extended); } bool EventInfo::IsPresent() const noexcept { return !!(Type & TypeFlag::Present); } bool EventInfo::IsFollowing() const noexcept { return !!(Type & TypeFlag::Following); } bool EventInfo::IsPresentFollowing() const noexcept { return !!(Type & (TypeFlag::Present | TypeFlag::Following)); } bool EventInfo::IsDatabase() const noexcept { return !!(Type & TypeFlag::Database); } bool EventInfo::GetStartTime(ReturnArg<DateTime> Time) const { if (!Time) return false; Time = StartTime; return Time->IsValid(); } bool EventInfo::GetEndTime(ReturnArg<DateTime> Time) const { if (!Time) return false; if (StartTime.IsValid()) { Time = StartTime; if (Time->OffsetSeconds(Duration)) return true; } Time->Reset(); return false; } bool EventInfo::GetStartTimeUTC(ReturnArg<DateTime> Time) const { if (!Time) return false; if (StartTime.IsValid()) { if (EPGTimeToUTCTime(StartTime, Time)) return true; } Time->Reset(); return false; } bool EventInfo::GetEndTimeUTC(ReturnArg<DateTime> Time) const { if (!Time) return false; if (StartTime.IsValid()) { Time = StartTime; if (Time->OffsetSeconds((-9 * 60 * 60) + Duration)) return true; } Time->Reset(); return false; } bool EventInfo::GetStartTimeLocal(ReturnArg<DateTime> Time) const { if (!Time) return false; if (StartTime.IsValid()) { if (EPGTimeToLocalTime(StartTime, Time)) return true; } Time->Reset(); return false; } bool EventInfo::GetEndTimeLocal(ReturnArg<DateTime> Time) const { if (!Time) return false; DateTime EndTime; if (GetEndTime(&EndTime) && EPGTimeToLocalTime(EndTime, Time)) return true; Time->Reset(); return false; } bool EventInfo::GetConcatenatedExtendedText(ReturnArg<String> Text) const { if (!Text) return false; Text->clear(); for (auto it = ExtendedText.begin(); it != ExtendedText.end(); ++it) { if (!it->Description.empty()) { *Text += it->Description; *Text += LIBISDB_STR(LIBISDB_NEWLINE); } if (!it->Text.empty()) { *Text += it->Text; if (it + 1 != ExtendedText.end()) *Text += LIBISDB_STR(LIBISDB_NEWLINE); } } return true; } size_t EventInfo::GetConcatenatedExtendedTextLength() const { static const size_t NewLineLength = std::size(LIBISDB_STR(LIBISDB_NEWLINE)) - 1; size_t Length = 0; for (auto it = ExtendedText.begin(); it != ExtendedText.end(); ++it) { if (!it->Description.empty()) { Length += it->Description.length(); Length += NewLineLength; } if (!it->Text.empty()) { Length += it->Text.length(); if (it + 1 != ExtendedText.end()) Length += NewLineLength; } } return Length; } int EventInfo::GetMainAudioIndex() const { for (size_t i = 0; i < AudioList.size(); i++) { if (AudioList[i].MainComponentFlag) return (int)i; } return -1; } const EventInfo::AudioInfo * EventInfo::GetMainAudioInfo() const { if (AudioList.empty()) return nullptr; const int MainAudioIndex = GetMainAudioIndex(); if (MainAudioIndex >= 0) return &AudioList[MainAudioIndex]; return &AudioList[0]; } // EPGの日時(UTC+9)からUTCに変換する bool EPGTimeToUTCTime(const DateTime &EPGTime, ReturnArg<DateTime> UTCTime) { if (!UTCTime) return false; UTCTime = EPGTime; if (UTCTime->OffsetSeconds(-9 * 60 * 60)) return true; UTCTime->Reset(); return false; } // UTCからEPGの日時(UTC+9)に変換する bool UTCTimeToEPGTime(const DateTime &UTCTime, ReturnArg<DateTime> EPGTime) { if (!EPGTime) return false; EPGTime = UTCTime; if (EPGTime->OffsetSeconds(9 * 60 * 60)) return true; EPGTime->Reset(); return false; } // EPGの日時(UTC+9)からローカル日時に変換する bool EPGTimeToLocalTime(const DateTime &EPGTime, ReturnArg<DateTime> LocalTime) { if (!LocalTime) return false; if (EPGTimeToUTCTime(EPGTime, LocalTime) && LocalTime->ToLocal()) return true; LocalTime->Reset(); return false; } // 現在の日時をEPGの日時(UTC+9)で取得する bool GetCurrentEPGTime(ReturnArg<DateTime> Time) { if (!Time) return false; Time->NowUTC(); if (Time->OffsetSeconds(9 * 60 * 60)) return true; Time->Reset(); return false; } // 拡張テキストを取得する bool GetEventExtendedTextList(const DescriptorBlock *pDescBlock, ReturnArg<EventExtendedTextList> List) { if (!List) return false; List->clear(); if (pDescBlock == nullptr) return false; std::vector<const ExtendedEventDescriptor *> DescList; pDescBlock->EnumDescriptors<ExtendedEventDescriptor>( [&](const ExtendedEventDescriptor *pDesc) { DescList.push_back(pDesc); }); if (DescList.empty()) return false; // descriptor_number 順にソートする InsertionSort(DescList, [](const ExtendedEventDescriptor *pDesc1, const ExtendedEventDescriptor *pDesc2) { return pDesc1->GetDescriptorNumber() < pDesc2->GetDescriptorNumber(); }); struct ItemInfo { uint8_t DescriptorNumber; const ARIBString *pDescription; const ARIBString *pData1; const ARIBString *pData2; }; std::vector<ItemInfo> ItemList; for (auto e : DescList) { for (int j = 0; j < e->GetItemCount(); j++) { const ExtendedEventDescriptor::ItemInfo *pItem = e->GetItem(j); if (pItem == nullptr) continue; if (!pItem->Description.empty()) { // 新規項目 ItemInfo Item; Item.DescriptorNumber = e->GetDescriptorNumber(); Item.pDescription = &pItem->Description; Item.pData1 = &pItem->ItemChar; Item.pData2 = nullptr; ItemList.push_back(Item); } else if (!ItemList.empty()) { // 前の項目の続き ItemInfo &Item = ItemList[ItemList.size() - 1]; if ((Item.DescriptorNumber == e->GetDescriptorNumber() - 1) && (Item.pData2 == nullptr)) { Item.pData2 = &pItem->ItemChar; } } } } List->resize(ItemList.size()); for (size_t i = 0; i < ItemList.size(); i++) { EventExtendedTextItem &Item = (*List)[i]; Item.Description = *ItemList[i].pDescription; Item.Text = *ItemList[i].pData1; if (ItemList[i].pData2 != nullptr) Item.Text += *ItemList[i].pData2; } return true; } static void CanonicalizeExtendedText(const String &Src, ReturnArg<String> Dst) { for (auto it = Src.begin(); it != Src.end();) { if (*it == LIBISDB_CHAR('\r')) { *Dst += LIBISDB_STR(LIBISDB_NEWLINE); ++it; if (it == Src.end()) break; if (*it == LIBISDB_CHAR('\n')) ++it; } else { Dst->push_back(*it); ++it; } } } bool GetEventExtendedTextList( const DescriptorBlock *pDescBlock, ARIBStringDecoder &StringDecoder, ARIBStringDecoder::DecodeFlag DecodeFlags, ReturnArg<EventInfo::ExtendedTextInfoList> List) { EventExtendedTextList TextList; if (!GetEventExtendedTextList(pDescBlock, &TextList)) return false; List->clear(); List->reserve(TextList.size()); String Buffer; for (auto const &e : TextList) { EventInfo::ExtendedTextInfo &Text = List->emplace_back(); StringDecoder.Decode(e.Description, &Text.Description, DecodeFlags); if (StringDecoder.Decode(e.Text, &Buffer, DecodeFlags)) CanonicalizeExtendedText(Buffer, &Text.Text); } return true; } bool GetConcatenatedEventExtendedText( const EventExtendedTextList &List, ARIBStringDecoder &StringDecoder, ARIBStringDecoder::DecodeFlag DecodeFlags, ReturnArg<String> Text) { if (!Text) return false; Text->clear(); String Buffer; for (auto &e : List) { if (StringDecoder.Decode(e.Description, &Buffer, DecodeFlags)) { *Text += Buffer; *Text += LIBISDB_STR(LIBISDB_NEWLINE); } if (StringDecoder.Decode(e.Text, &Buffer, DecodeFlags)) { CanonicalizeExtendedText(Buffer, Text); *Text += LIBISDB_STR(LIBISDB_NEWLINE); } } return true; } bool GetEventExtendedText( const DescriptorBlock *pDescBlock, ARIBStringDecoder &StringDecoder, ARIBStringDecoder::DecodeFlag DecodeFlags, ReturnArg<String> Text) { EventExtendedTextList List; if (!GetEventExtendedTextList(pDescBlock, &List)) return false; return GetConcatenatedEventExtendedText(List, StringDecoder, DecodeFlags, Text); } } // namespace LibISDB
from pydantic import BaseModel, Field from typing import List, Dict, Any, Union class AddSource(BaseModel): file_link: str = Field(description="The link to the data source you wish to add") file_type: str = Field( description="The type of data source you wish to add. Currently the choices are Doc, Pdf or Website" ) title: Union[str, None] = Field( description="A 4 word or less sparse summary of what this data is and what it can be used for, easy to remember for the user. If the file_type is Csv this is very useful and you should ask the user for the title before continuing.", default=None, ) class Datasource(BaseModel): id: Union[str, None] = Field( description="The mongo ObjectId from this document in the collection", default=None, alias="_id", ) ai_agent: str = Field( description="The name of the AI Agent who added (and has implied access to) this datasource" ) file_link: str = Field(description="The link to the data source you wish to add") file_type: str = Field( description="The type of data source you wish to add. Currently the choices are Doc, Pdf or Website" ) title: Union[str, None] = Field( description="A 4 word or less sparse summary of what this data is and what it can be used for, easy to remember for the user. If the file_type is Csv this is very useful and you should ask the user for the title before continuing.", default=None, ) created_at_utc: Union[str, None] = Field( description="UTC created time", default=None ) updated_at_utc: Union[str, None] = Field( description="UTC updated time", default=None ) created_by: Union[str, None] = Field( description="The username who requested to have the source added", default=None ) updated_by: Union[str, None] = Field( description="username of updator", default=None ) sparse_summary: Union[str, None] = Field( description="A 40 word or less sparse summary of what this data is and what it can be used for", default=None, ) s3_key: Union[str, None] = Field(description="The link to the file in AWS s3 in s3://filename style", default=None) class UserMessage(BaseModel): context: Any contextType: str username: str message: str class BotMessage(BaseModel): username: str context: Any contextType: str message: Any sources: List[Dict] | None class ChatQuestion(BaseModel): username: str question: str class ChatAnswer(BaseModel): username: str answer: str sources: List[Dict] | None class WebsiteQuestion(BaseModel): website_urls: list[str] = Field( description="A list of website urls to use as sources for question and answer" ) question: str = Field( description="The question the user to research in the webiste data" ) class UserNoteQuestion(BaseModel): query: str | None = Field( description="Words or topic to search for in the notes", default=None ) title: str | None = Field( description="A 12 word or less title based on a sparse summary of the note.", default=None, ) context: str = Field( description="The id or unique name of the entity for which the 'context_type' of the note is associated with. For example, when the context_type is 'Bill' the context will be the bill_slug" ) context_type: str = Field( description="The entity the note is about, for example a Bill" ) username: str = Field( description="The name of the user(politician) whoose note it is" ) note_id: str | None = Field( description="The note_id is the unique id for the note in the database, this is the most accurate means of retreiving a specific note when possible.", default=None, ) class UserNote(BaseModel): note: str = Field( description="The content the user has asked you to save, escaped it a json format for inserting into a mongo document" ) title: str = Field( description="A 12 word or less title based on a sparse summary of the note." ) context: str = Field( description="The id or unique name of the entity for which the 'context_type' of the note is associated with. For example, when the context_type is 'Bill' the context will be the bill_slug" ) context_type: str = Field( description="The entity the note is about, for example a Bill" ) username: str = Field( description="The name of the user(politician) who asks for the note" ) note_id: str | None = Field( description="If the user wants to edit an existing note, then the note_id will already exist and be available somewhere in the context, otherwise omitt this parameter (Default is None)", default=None, )
<template> <div class="toolbar-container"> <div class="title" v-if="props.title">{{ props.title }}</div> <div class="button"> <el-space wrap> <el-button type="primary" v-if="state.refresh" @click="emits('refresh')"> <iconify-icon icon="ci:refresh" /> </el-button> <el-button type="primary" v-if="state.add" @click="emits('add')">新增</el-button> <el-button v-if="state.edit" @click="emits('edit', props.selectRow)" :disabled="isEmpty(props.selectRow)" > 编辑 </el-button> <el-button type="danger" v-if="state.remove" @click="emits('remove', props.selectRow)" :disabled="isEmpty(props.selectRow)" > 删除</el-button > </el-space> </div> <div class="search"> <el-input placeholder="请输入搜索关键字" @input="(val) => (keywords = val)" :model-value="keywords" clearable @clear="onClickClear" @keyup.enter="onChangKeywords" v-if="state.search" /> <el-button-group v-if="state.search || state.column"> <el-button @click="onChangKeywords" type="primary" :disabled="isEmpty(keywords)"> <iconify-icon icon="ant-design:search-outlined" v-if="state.search" /> </el-button> <el-popover placement="bottom" v-if="state.column"> <template #reference> <el-button> <iconify-icon icon="ci:table" /> </el-button> </template> <el-checkbox-group :model-value="showFields" @change="onChangField"> <el-checkbox v-for="(field, index) in props.fields" :key="index" :label="field.label" /> </el-checkbox-group> </el-popover> </el-button-group> </div> </div> </template> <script setup lang="ts"> import _, { isEmpty } from 'lodash'; import { DataTableFieldConfig, OperateType } from '..'; const props = defineProps<{ selectRow?: Recordable<any> | undefined; title?: string; fields: DataTableFieldConfig[]; // 字段 toolbar?: OperateType[]; // 工具栏选项 }>(); const keywords = ref(''); const showFields = ref(props.fields.filter((t) => !t.hide).map((t) => t.label)); const emits = defineEmits<{ (event: 'refresh'): void; (event: 'add'): void; (event: 'edit', value: Recordable<any>): void; (event: 'remove', value: Recordable<any>): void; (event: 'changKeywords', value: string): void; (event: 'clearKeywords'): void; (event: 'changField', value: any): void; }>(); const state = computed(() => { return { refresh: props.toolbar?.includes('refresh'), add: props.toolbar?.includes('edit'), edit: props.toolbar?.includes('edit'), remove: props.toolbar?.includes('remove'), search: props.toolbar?.includes('search'), column: props.toolbar?.includes('column') }; }); const onClickClear = () => { keywords.value = ''; emits('clearKeywords'); }; const onChangKeywords = () => { if (!isEmpty(keywords.value)) { emits('changKeywords', keywords.value); } }; const onChangField = (value) => { showFields.value = value; emits('changField', value); }; </script> <style lang="scss" scoped> .toolbar-container { display: flex; justify-content: space-between; align-items: center; padding: 16px 0; .title { margin: 0px 20px; font-size: large; font-weight: 500; } .button { margin-right: auto; } .search { display: flex; .el-input { margin-right: 20px; } .el-button-group { display: flex; } } } </style>
package common import ( "net/http" "net/url" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "a.yandex-team.ru/portal/avocado/libs/utils/base/models" "a.yandex-team.ru/portal/avocado/libs/utils/staticparams" ) func TestHTTPRequestWrapper_isInternal(t *testing.T) { testCases := []struct { headers map[string]string expected bool caseName string }{ { headers: map[string]string{ "X-Yandex-Internal-Request": "1", }, expected: true, caseName: "regular_case", }, { headers: map[string]string{ "X-YANDEX-INTERNAL-REQUEST": "1", }, expected: true, caseName: "upper_case", }, { headers: map[string]string{ "X-NOT-YANDEX-INTERNAL-REQUEST": "1", }, expected: false, caseName: "upper_case", }, { headers: nil, expected: false, caseName: "no_headers", }, { headers: map[string]string{ "X-Yandex-Internal-Request": "yes", }, expected: false, caseName: "incorrect_value", }, } for _, testCase := range testCases { t.Run(testCase.caseName, func(t *testing.T) { headers := http.Header{} for k, v := range testCase.headers { headers.Add(k, v) } ctrl := gomock.NewController(t) originRequestMock := NewMockoriginRequestKeeper(ctrl) originRequestMock.EXPECT().GetOriginRequest().Return(&models.OriginRequest{Headers: headers}, nil).AnyTimes() wrapper := NewHTTPRequestWrapper(originRequestMock, url.Values{}) require.NotNil(t, wrapper) assert.Equal(t, testCase.expected, wrapper.IsInternalRequest()) }) } } func TestHTTPRequestWrapper_getUSaaSHeaderFromTHttpRequest(t *testing.T) { type answer struct { flags string boxes string } testCases := []struct { headers map[string]string location staticparams.Location expected answer caseName string }{ { headers: map[string]string{ "X-Yandex-ExpFlags": "AAA", "X-Yandex-ExpBoxes": "BBB", "X-Yandex-ExpFlags-Pre": "CCC", "X-Yandex-ExpBoxes-Pre": "DDD", }, location: "vla", expected: answer{ flags: "CCC", boxes: "DDD", }, caseName: "prestable headers in VLA", }, { headers: map[string]string{ "X-Yandex-ExpFlags": "AAA", "X-Yandex-ExpBoxes": "BBB", "X-Yandex-ExpFlags-Pre": "CCC", "X-Yandex-ExpBoxes-Pre": "DDD", }, location: "sas", expected: answer{ flags: "AAA", boxes: "BBB", }, caseName: "stable headers not in VLA", }, { headers: map[string]string{ "X-Yandex-ExpFlags": "AAA", "X-Yandex-ExpBoxes": "BBB", "X-Yandex-ExpFlags-Pre": "CCC", "X-Yandex-ExpBoxes-Pre": "DDD", }, location: "", expected: answer{ flags: "AAA", boxes: "BBB", }, caseName: "stable headers by default", }, { headers: map[string]string{ "X-Yandex-ExpFlags-Pre": "CCC", "X-Yandex-ExpBoxes-Pre": "DDD", }, location: "vla", expected: answer{ flags: "CCC", boxes: "DDD", }, caseName: "only prestable, VLA location", }, { headers: map[string]string{ "X-Yandex-ExpFlags-Pre": "CCC", "X-Yandex-ExpBoxes-Pre": "DDD", }, location: "sas", expected: answer{ flags: "", boxes: "", }, caseName: "only prestable, not VLA location", }, { headers: map[string]string{ "X-Yandex-ExpFlags": "AAA", "X-Yandex-ExpBoxes": "BBB", }, location: "", expected: answer{ flags: "AAA", boxes: "BBB", }, caseName: "only stable", }, { headers: map[string]string{ "X-Yandex-ExpFlags": "AAA", "X-Yandex-ExpBoxes": "BBB", }, location: "vla", expected: answer{ flags: "AAA", boxes: "BBB", }, caseName: "only stable in VLA", }, { headers: map[string]string{ "x-yandex-expflags": "AAA", "x-yandex-expboxes": "BBB", "x-yandex-expflags-pre": "CCC", "x-yandex-expBoxes-pre": "DDD", }, location: "vla", expected: answer{ flags: "CCC", boxes: "DDD", }, caseName: "lower_case in VLA", }, { headers: map[string]string{ "X-Yandex-ExpFlags": "AAA", "X-Yandex-ExpBoxes": "BBB", "X-Yandex-ExpFlags-Pre": "", "X-Yandex-ExpBoxes-Pre": "", }, location: "vla", expected: answer{ flags: "AAA", boxes: "BBB", }, caseName: "empty_prestable_headers in VLA", }, } for _, testCase := range testCases { t.Run(testCase.caseName, func(t *testing.T) { headers := http.Header{} for k, v := range testCase.headers { headers.Add(k, v) } ctrl := gomock.NewController(t) originRequestMock := NewMockoriginRequestKeeper(ctrl) originRequestMock.EXPECT().GetOriginRequest().Return(&models.OriginRequest{Headers: headers}, nil).AnyTimes() wrapper := NewHTTPRequestWrapper(originRequestMock, url.Values{}) require.NotNil(t, wrapper) assert.Equal(t, testCase.expected.flags, wrapper.GetExpFlags(testCase.location)) assert.Equal(t, testCase.expected.boxes, wrapper.GetExpBoxes(testCase.location)) }) } }
package rs.etf.sab.student; import rs.etf.sab.operations.TransactionOperations; import java.math.BigDecimal; import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class TransactionOperationsImpl implements TransactionOperations { private static final Connection connection = DB.getInstance().getConnection(); @Override public BigDecimal getBuyerTransactionsAmmount(int buyerId) { String selectQuery = "SELECT COALESCE(SUM(amount), 0) FROM TransactionT WHERE buyerId = ? AND type = 'buyer'"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, buyerId); ResultSet rs = ps.executeQuery(); return rs.next() ? rs.getBigDecimal(1) : BigDecimal.valueOf(-1); } catch (SQLException ex) { return BigDecimal.valueOf(-1); } } @Override public BigDecimal getShopTransactionsAmmount(int shopId) { String selectQuery = "SELECT COALESCE(SUM(amount), 0) FROM TransactionT WHERE shopId = ? AND type = 'shop'"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, shopId); ResultSet rs = ps.executeQuery(); return rs.next() ? rs.getBigDecimal(1) : BigDecimal.valueOf(-1); } catch (SQLException ex) { return BigDecimal.valueOf(-1); } } @Override public List<Integer> getTransationsForBuyer(int buyerId) { String selectQuery = "SELECT transactionId FROM TransactionT WHERE buyerId = ? AND type = 'buyer'"; List<Integer> transactions = new ArrayList<>(); try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, buyerId); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { transactions.add(resultSet.getInt(1)); } return transactions.isEmpty() ? null : transactions; } catch (SQLException ex) { return null; } } @Override public int getTransactionForBuyersOrder(int orderId) { String selectQuery = "SELECT transactionId FROM TransactionT WHERE orderId = ? AND type = 'buyer'"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, orderId); ResultSet rs = ps.executeQuery(); return rs.next() ? rs.getInt(1) : -1; } catch (SQLException ex) { return -1; } } @Override public int getTransactionForShopAndOrder(int orderId, int shopId) { String selectQuery = "SELECT transactionId FROM TransactionT WHERE orderId = ? AND shopId = ? AND type = 'shop'"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, orderId); ps.setInt(2, shopId); ResultSet rs = ps.executeQuery(); return rs.next() ? rs.getInt(1) : -1; } catch (SQLException ex) { return -1; } } @Override public List<Integer> getTransationsForShop(int shopId) { String selectQuery = "SELECT transactionId FROM TransactionT WHERE shopId = ? AND type = 'shop'"; List<Integer> transactions = new ArrayList<>(); try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, shopId); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { transactions.add(resultSet.getInt(1)); } return transactions.isEmpty() ? null : transactions; } catch (SQLException ex) { return null; } } @Override public Calendar getTimeOfExecution(int transactionId) { String selectQuery = "SELECT executionTime FROM TransactionT WHERE transactionId = ?"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, transactionId); ResultSet rs = ps.executeQuery(); rs.next(); Date executionTime = rs.getDate(1); if (executionTime == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(executionTime); return calendar; } catch (SQLException ex) { return null; } } @Override public BigDecimal getAmmountThatBuyerPayedForOrder(int orderId) { String selectQuery = "SELECT amount FROM TransactionT WHERE orderId = ? AND type = 'buyer'"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, orderId); ResultSet rs = ps.executeQuery(); return rs.next() ? rs.getBigDecimal(1) : null; } catch (SQLException ex) { return null; } } @Override public BigDecimal getAmmountThatShopRecievedForOrder(int shopId, int orderId) { String selectQuery = "SELECT amount FROM TransactionT WHERE shopId = ? AND orderId = ? AND type = 'shop'"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, orderId); ResultSet rs = ps.executeQuery(); return rs.next() ? rs.getBigDecimal(1) : null; } catch (SQLException ex) { return null; } } @Override public BigDecimal getTransactionAmount(int transactionId) { String selectQuery = "SELECT amount FROM TransactionT WHERE transactionId = ?"; try (PreparedStatement ps = connection.prepareStatement(selectQuery)) { ps.setInt(1, transactionId); ResultSet rs = ps.executeQuery(); return rs.next() ? rs.getBigDecimal(1) : null; } catch (SQLException ex) { return null; } } @Override public BigDecimal getSystemProfit() { String selectQuery = "SELECT COALESCE(SUM(amount), 0) FROM TransactionT WHERE type = 'system'"; try (Statement stm = connection.createStatement()) { ResultSet rs = stm.executeQuery(selectQuery); return rs.next() ? rs.getBigDecimal(1) : null; } catch (SQLException ex) { return null; } } }
package main import "fmt" // Define a struct named Book to represent book information. type Book struct { Title string Author string Year int } func main() { // Create a map to store information about books. library := make(map[string]Book) // Add books to the library. library["001"] = Book{"The Great Gatsby", "F. Scott Fitzgerald", 1925} library["002"] = Book{"To Kill a Mockingbird", "Harper Lee", 1960} library["003"] = Book{"1984", "George Orwell", 1949} // Display information about each book in the library. for key, book := range library { fmt.Printf("Book ID: %s\n", key) fmt.Printf("Title: %s\n", book.Title) fmt.Printf("Author: %s\n", book.Author) fmt.Printf("Year: %d\n\n", book.Year) } }
### # @format # ----- # Project: grand_theft_auto # File: install.py # Path: /install.py # Created Date: Sunday, December 3rd 2023 # Author: Jonathan Stevens (Email: [email protected], Github: https://github.com/TGTGamer) # ----- # Contributing: Please read through our contributing guidelines. Included are directions for opening # issues, coding standards, and notes on development. These can be found at https://github.com/grand_theft_auto/blob/develop/CONTRIBUTING.md # # Code of Conduct: This project abides by the Contributor Covenant, version 2.0. Please interact in ways that contribute to an open, # welcoming, diverse, inclusive, and healthy community. Our Code of Conduct can be found at https://github.com/grand_theft_auto/blob/develop/CODE_OF_CONDUCT.md # ----- # Copyright (c) 2023 Resnovas - All Rights Reserved # LICENSE: Creative Commons Zero v1.0 Universal (CC0-1.0) # ----- # This program has been provided under confidence of the copyright holder and is # licensed for copying, distribution and modification under the terms of # the Creative Commons Zero v1.0 Universal (CC0-1.0) published as the License, # or (at your option) any later version of this license. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # Creative Commons Zero v1.0 Universal for more details. # # You should have received a copy of the Creative Commons Zero v1.0 Universal # along with this program. If not, please write to: [email protected], # or see https://creativecommons.org/publicdomain/zero/1.0/legalcode # # DELETING THIS NOTICE AUTOMATICALLY VOIDS YOUR LICENSE - PLEASE SEE THE LICENSE FILE FOR DETAILS # ----- # Last Modified: 03-12-2023 # By: Jonathan Stevens (Email: [email protected], Github: https://github.com/TGTGamer) # Current Version: <<projectversion>> ### import frappe # This function creates the default content for Grand Theft Auto usage with Eventiva Gaming module # This is called after the app is installed and is only called once def after_install(): if not frappe.db.exists("Company", "Gaming Community"): createParent() companies = ["Police Constabulary", "Fire Rescue Service", "Ambulance Service"] for company in companies: if not frappe.db.exists("Company", company): createChild(company) pass def createParent(): # check to see if the the company exists parent = frappe.new_doc("Company") parent.set("company_name", "Gaming Community") parent.set("abbr", "GC") parent.set("default_currency", "GBP") parent.set("country", "United Kingdom") parent.set("is_group", True) parent.set("create_chart_of_accounts_based_on", "Standard Template") parent.set("chart_of_accounts", "Standard with Numbers") parent.insert() pass def createChild(company: str): child = frappe.new_doc("Company") child.set("company_name", company) ## get a letter from each word in the company name abbr = "" for word in company.split(): abbr += word[0] child.set("abbr", abbr) child.set("default_currency", "GBP") child.set("country", "United Kingdom") child.set("parent_company", "Gaming Community") child.set("create_chart_of_accounts_based_on", "Existing Company") child.set("existing_company", "Gaming Community") child.set("allow_account_creation_against_child_company", True) child.insert() pass
<?php namespace App\Models\Models; use App\Traits\AttributeTrait; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use GuzzleHttp\Client; class Mercadolivre extends Model { use HasFactory, AttributeTrait; protected $fillable = [ 'access_token', 'token_type', 'expires_in', 'scope', 'user_id', 'refresh_token', ]; private $access_token, $content_type, $user_id; public function sync_product($product_id) { $product = Product::find($product_id); $headers = $this->header_uri(); $body = array_merge($this->body_base($product_id)); $body = array_merge($body, $this->list_attributes($product_id)); if ($product->mercado_livre_id) { $url = "https://api.mercadolibre.com/items/$product->mercado_livre_id"; $method = "PUT"; } else { $url = "https://api.mercadolibre.com/items"; $method = "POST"; } $client = new Client(); $res = $client->request($method, $url, [ 'headers' => $headers, 'body' => json_encode($body) ]); $res->getStatusCode(); $body = $res->getBody(); $contents = $body->getContents(); $product->update(['mercado_livre_id' => json_decode($contents)->id]); return 'Sincronização efetuada com sucesso!'; } }
import { rest } from 'msw'; import { IBoard } from '@interfaces/boards'; import { IJob } from '@interfaces/jobs'; const baseUrl = 'http://localhost:3001'; const boardsData: IBoard[] = [ { id: 1, name: "Lorna's Board", created: '2023-02-07T15:58:11.689Z', lastModified: '2023-03-10T12:41:14.930Z', }, { id: 2, name: 'Party Board', created: '2023-02-07T15:58:11.689Z', lastModified: '2023-03-10T12:41:14.930Z', }, ]; const jobsData: IJob[] = [ { id: 1, boardId: 1, typeId: 1, title: 'test', description: '<p>test</p>', status: 'Not Started', completionDate: '2023-02-27T00:00:00.000Z', lastModified: '2023-03-02T10:53:23.663Z', created: '2023-02-27T18:33:18.476Z', jobType: { id: 1, description: 'tick' }, }, { id: 2, boardId: 1, typeId: 2, title: 'test2', description: '<p>test2</p>', status: 'Done', completionDate: '2023-02-27T00:00:00.000Z', lastModified: '2023-03-02T10:53:23.663Z', created: '2023-02-27T18:33:18.476Z', jobType: { id: 2, description: 'task' }, }, ]; export const handlers = [ rest.get(baseUrl + '/api/authenticate/refresh', (req, res, ctx) => res( ctx.status(200), ctx.json({ accessToken: 'new-access-token', refreshToken: 'new-refresh-token', }) ) ), rest.post(baseUrl + '/api/authenticate', async (req, res, ctx) => { const requestData = await req.json(); if ( requestData.email === '[email protected]' && requestData.password === 'password1!' ) { return res(ctx.status(200)); } else { return res(ctx.status(500)); } }), rest.get(baseUrl + '/boards', (req, res, ctx) => { return res(ctx.json(boardsData)); }), rest.get(baseUrl + '/jobs', (req, res, ctx) => { return res(ctx.json(jobsData)); }), rest.post(baseUrl + '/boards', (req, res, ctx) => { return res(ctx.json(boardsData)); }), rest.post(baseUrl + '/jobs', (req, res, ctx) => { return res(ctx.json(jobsData)); }), rest.put(baseUrl + '/boards', (req, res, ctx) => { return res(ctx.json(boardsData)); }), rest.put(baseUrl + '/jobs', (req, res, ctx) => { return res(ctx.json(jobsData)); }), rest.delete(baseUrl + '/boards', (req, res, ctx) => { return res(ctx.status(204)); }), rest.delete(baseUrl + '/jobs', (req, res, ctx) => { return res(ctx.status(204)); }), ]; export { rest };
--*****PLEASE ENTER YOUR DETAILS BELOW***** --T1-mns-schema.sql --Student ID: 32729286 --Student Name: Daisuke Murakami --Unit Code: FIT2094 --Applied Class No: 2 /* Comments for your marker: */ -- Task 1 Add Create table statements for the white TABLES below -- Ensure all column comments, and constraints (other than FK's) -- are included. FK constraints are to be added at the end of this script -- TABLE: APPOINTMENT CREATE TABLE APPOINTMENT ( appt_no NUMBER(7) NOT NULL, appt_datetime DATE NOT NULL, appt_roomno NUMBER(2) NULL, appt_length CHAR(1) CHECK(appt_length IN ('S', 'T', 'L')), patient_no NUMBER(4) NOT NULL, provider_code CHAR(6) NULL, nurse_no NUMBER(3) NOT NULL, appt_prior_apptno NUMBER(7) NULL ); COMMENT ON COLUMN APPOINTMENT.appt_no IS 'Appointment number (identifier)'; COMMENT ON COLUMN APPOINTMENT.appt_datetime IS 'Date and time of the appointment'; COMMENT ON COLUMN APPOINTMENT.appt_roomno IS 'Room in which appointment is scheduled to take place'; COMMENT ON COLUMN APPOINTMENT.appt_length IS 'Length of appointment - Short, Standard or Long (S, T or L)'; COMMENT ON COLUMN APPOINTMENT.patient_no IS 'Patient who books the appointment'; COMMENT ON COLUMN APPOINTMENT.provider_code IS 'Provider who is assigned to the appointment'; COMMENT ON COLUMN APPOINTMENT.nurse_no IS 'Nurse who is assigned to the appointment'; COMMENT ON COLUMN APPOINTMENT.appt_prior_apptno IS 'Prior appointment number which leads to this appointment (this is required to be unique)'; ALTER TABLE APPOINTMENT ADD CONSTRAINT appointment_pk PRIMARY KEY ( appt_no ); ALTER TABLE APPOINTMENT ADD CONSTRAINT provider_appt_fk FOREIGN KEY ( provider_code ) REFERENCES PROVIDER ( provider_code ); ALTER TABLE APPOINTMENT ADD CONSTRAINT nurse_appt_fk FOREIGN KEY ( nurse_no ) REFERENCES NURSE ( nurse_no ); ALTER TABLE APPOINTMENT ADD CONSTRAINT prior_appt_fk FOREIGN KEY ( appt_prior_apptno ) REFERENCES APPOINTMENT ( appt_no ); -- TABLE: EMERGENCY_CONTACT CREATE TABLE EMERGENCY_CONTACT ( ec_id NUMERIC(4) NOT NULL, ec_fname VARCHAR(30) NOT NULL, ec_lname VARCHAR(30) NOT NULL, ec_phone CHAR(10) NOT NULL ); COMMENT ON COLUMN EMERGENCY_CONTACT.ec_id IS 'Emergency contact identifier'; COMMENT ON COLUMN EMERGENCY_CONTACT.ec_fname IS 'Emergency contact first name'; COMMENT ON COLUMN EMERGENCY_CONTACT.ec_lname IS 'Emergency contact last name'; COMMENT ON COLUMN EMERGENCY_CONTACT.ec_phone IS 'Emergency contact phone number'; ALTER TABLE EMERGENCY_CONTACT ADD CONSTRAINT emergency_pk PRIMARY KEY ( ec_id ); -- TABLE: PATIENT CREATE TABLE PATIENT ( patient_no NUMBER(4) NOT NULL, patient_fname VARCHAR2(30) NOT NULL, patient_lname VARCHAR2(30) NOT NULL, patient_street VARCHAR2(50) NULL, patient_city VARCHAR2(20) NULL, patient_state VARCHAR2(3) CHECK(patient_state IN ('NT', 'QLD', 'NSW', 'ACT', 'VIC', 'TAS', 'SA', 'WA')), patient_postcode CHAR(4) NULL, patient_dob DATE NULL, patient_contactmobile CHAR(10) NULL, patient_contactemail VARCHAR2(25) NULL, ec_id NUMBER(4) NOT NULL ); COMMENT ON COLUMN PATIENT.patient_no IS 'Patient number (unique for each patient)'; COMMENT ON COLUMN PATIENT.patient_fname IS 'Patient first name'; COMMENT ON COLUMN PATIENT.patient_lname IS 'Patient last name'; COMMENT ON COLUMN PATIENT.patient_street IS 'Patient residential street address'; COMMENT ON COLUMN PATIENT.patient_city IS 'Patient residential city'; COMMENT ON COLUMN PATIENT.patient_state IS 'Patient residential state - NT, QLD, NSW, ACT, VIC, TAS, SA, or WA'; COMMENT ON COLUMN PATIENT.patient_postcode IS 'Patient residential postcode'; COMMENT ON COLUMN PATIENT.patient_dob IS 'Patient date of birth'; COMMENT ON COLUMN PATIENT.patient_contactmobile IS 'Patient contact mobile number'; COMMENT ON COLUMN PATIENT.patient_contactemail IS 'Patient contact email address'; COMMENT ON COLUMN PATIENT.ec_id IS 'Patient emergency contact identifier'; ALTER TABLE PATIENT ADD CONSTRAINT patient_pk PRIMARY KEY ( patient_no ); ALTER TABLE PATIENT ADD CONSTRAINT ec_patient_fk FOREIGN KEY ( ec_id ) REFERENCES EMERGENCY_CONTACT ( ec_id ); -- Add all missing FK Constraints below here ALTER TABLE APPOINTMENT ADD CONSTRAINT patient_appt_fk FOREIGN KEY ( patient_no ) REFERENCES PATIENT ( patient_no );
'use client' import { useRouter } from 'next/navigation' import React, { useState } from 'react'; import { Menu, message } from 'antd'; import LoginForm from '../Forms/loginForm'; import PostForm from '../Forms/postForm'; import RegistrationForm from '../Forms/registrationForm'; import { useAuth } from '@/app/auth-context'; import menuItems from './menuItems'; const MainNav = () => { const [current, setCurrent] = useState('home'); const { AuthState, logout } = useAuth(); const [isLoginFormOpen, setLoginFormOpen] = useState(false); const [isRegistrationFormOpen, setRegistrationFormOpen] = useState(false); const [isPostFormOpen, setPostFormOpen] = useState(false); const [messageApi, contextHolder] = message.useMessage(); const router = useRouter(); const onClick = (e) => { if (!AuthState.isLoggedIn) { if (['addpost', 'mypost', 'bookmarks'].includes(e.key)) { messageApi.info('Please Login'); return; } } setCurrent(e.key); if (e.keyPath.includes('genre')) { if (e.keyPath.includes('movie')) { router.push(`/category/movies/${e.key}`); return; } router.push(`/category/animes/${e.key}`); return; } switch (e.key) { case 'user': setLoginFormOpen(true); break; case 'logout': logout(); break; case 'home': router.push('/'); break; case 'mostlikes': router.push('/most-likes'); break; case 'addpost': setPostFormOpen(true); break; case 'mypost': router.push('/myposts'); break; case 'bookmarks': router.push('/bookmarks'); break; default: break; } }; return ( <> {contextHolder} <Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" style={{ marginBottom: '20px', border: '1px solid #e8e8e8' }} items={menuItems(AuthState)} /> {!AuthState.isLoggedIn && <LoginForm isLoginFormOpen={isLoginFormOpen} setLoginFormOpen={setLoginFormOpen} setRegistrationFormOpen={setRegistrationFormOpen} />} {!AuthState.isLoggedIn && <RegistrationForm isRegistrationFormOpen={isRegistrationFormOpen} setRegistrationFormOpen={setRegistrationFormOpen} />} {AuthState.isLoggedIn && <PostForm isPostFormOpen={isPostFormOpen} setPostFormOpen={setPostFormOpen} />} </> ); }; export default MainNav;
import os from 'os' import { promisify } from 'util' import { chmod } from 'fs' import { filesystem, print, system } from 'gluegun' import { INSTALL_DIR, INSTALL_PATH, EXPORTS_FILE_PATH, getProfilePath, XSBUG_LOG_PATH, } from './constants' import upsert from '../patching/upsert' import { execWithSudo } from '../system/exec' import { PlatformSetupArgs } from './types' import { fetchLatestRelease, downloadReleaseTools } from './moddable' const chmodPromise = promisify(chmod) export default async function({ sourceRepo, targetBranch }: PlatformSetupArgs): Promise<void> { print.info('Setting up Linux tools!') const BIN_PATH = filesystem.resolve( INSTALL_PATH, 'build', 'bin', 'lin', 'release' ) const DEBUG_BIN_PATH = filesystem.resolve( INSTALL_PATH, 'build', 'bin', 'lin', 'debug' ) const BUILD_DIR = filesystem.resolve( INSTALL_PATH, 'build', 'makefiles', 'lin' ) const PROFILE_PATH = getProfilePath() const spinner = print.spin() spinner.start('Beginning setup...') // 0. clone moddable repo into ./local/share directory if it does not exist yet filesystem.dir(INSTALL_DIR) await upsert(EXPORTS_FILE_PATH, `# Generated by xs-dev CLI`) // 1. Install or update the packages required to compile: spinner.start('Installing dependencies...') await execWithSudo( 'apt-get install --yes gcc git wget make libncurses-dev flex bison gperf', { stdout: process.stdout } ) spinner.succeed() // 2. Install the development version of the GTK+ 3 library spinner.start('Installing GTK+ 3...') await execWithSudo('apt-get --yes install libgtk-3-dev', { stdout: process.stdout, }) spinner.succeed() // 3. Download the Moddable repository, or use the git command line tool as follows: if (filesystem.exists(INSTALL_PATH) !== false) { spinner.info('Moddable repo already installed') } else { if (targetBranch === 'latest-release') { spinner.start('Getting latest Moddable-OpenSource/moddable release') const release = await fetchLatestRelease() await system.spawn( `git clone ${sourceRepo} ${INSTALL_PATH} --depth 1 --branch ${release.tag_name} --single-branch` ) filesystem.dir(BIN_PATH) filesystem.dir(DEBUG_BIN_PATH) const isArm = os.arch() === 'arm64' const assetName = isArm ? 'moddable-tools-lin64arm.zip' : 'moddable-tools-lin64.zip' spinner.info('Downloading release tools') await downloadReleaseTools({ writePath: BIN_PATH, assetName, release, }) const tools = filesystem.list(BIN_PATH) ?? [] await Promise.all( tools.map(async (tool) => { await chmodPromise(filesystem.resolve(BIN_PATH, tool), 0o751) await filesystem.copyAsync( filesystem.resolve(BIN_PATH, tool), filesystem.resolve(DEBUG_BIN_PATH, tool) ) }) ) } else { spinner.start(`Cloning ${sourceRepo} repo`) await system.spawn( `git clone ${sourceRepo} ${INSTALL_PATH} --depth 1 --branch ${targetBranch} --single-branch` ) } spinner.succeed() } // 4. Setup the MODDABLE environment variable process.env.MODDABLE = INSTALL_PATH process.env.PATH = `${String(process.env.PATH)}:${BIN_PATH}` await upsert(PROFILE_PATH, `source ${EXPORTS_FILE_PATH}`) await upsert(EXPORTS_FILE_PATH, `export MODDABLE=${process.env.MODDABLE}`) await upsert(EXPORTS_FILE_PATH, `export PATH="${BIN_PATH}:$PATH"`) // 5. Build the Moddable command line tools, simulator, and debugger from the command line: if (targetBranch !== 'latest-release') { spinner.start('Building platform tooling') await system.exec('make', { cwd: BUILD_DIR, stdout: process.stdout }) spinner.succeed() } // 6. Install the desktop simulator and xsbug debugger applications spinner.start('Installing simulator') if (targetBranch === 'latest-release') { filesystem.dir( filesystem.resolve( BUILD_DIR, '..', '..', 'tmp', 'lin', 'debug', 'simulator' ) ) await system.exec( `mcconfig -m -p x-lin ${filesystem.resolve( INSTALL_PATH, 'tools', 'xsbug', 'manifest.json' )}`, { process } ) await system.exec( `mcconfig -m -p x-lin ${filesystem.resolve( INSTALL_PATH, 'tools', 'mcsim', 'manifest.json' )}`, { process } ) } await execWithSudo('make install', { cwd: BUILD_DIR, stdout: process.stdout, }) spinner.succeed() if (system.which('npm') !== null) { spinner.start('Installing xsbug-log dependencies') await system.exec('npm install', { cwd: XSBUG_LOG_PATH }) spinner.succeed(); } // 7. Profit? print.success( 'Moddable SDK successfully set up! Start a new terminal session and run the "helloworld example": xs-dev run --example helloworld' ) }
/* * Created on 11-Feb-2004 at 23:30:01. * * Copyright (c) 2004 Robert Virkus / Enough Software * * This file is part of J2ME Polish. * * J2ME Polish is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * J2ME Polish 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 Foobar; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Commercial licenses are also available, please * refer to the accompanying LICENSE.txt or visit * http://www.j2mepolish.org for details. */ package de.enough.polish.ant.requirements; import org.apache.tools.ant.BuildException; import junit.framework.TestCase; /** * <p>Tests the version matcher class.</p> * * <p>copyright Enough Software 2004</p> * <pre> * history * 11-Feb-2004 - rob creation * </pre> * @author Robert Virkus, [email protected] */ public class VersionMatcherTest extends TestCase { public VersionMatcherTest( String name ) { super( name ); } public void testMatches() throws BuildException { String needed = "1.2.5+"; VersionMatcher matcher = new VersionMatcher( needed ); assertFalse( matcher.matches( "1.2.4" ) ); assertFalse( matcher.matches( "1.2" ) ); assertTrue( matcher.matches( "1.2.5" ) ); assertTrue( matcher.matches( "1.2.6" ) ); assertFalse( matcher.matches( "1.3.0" ) ); assertFalse( matcher.matches( "2.2.4" ) ); needed = "1.2.3"; matcher = new VersionMatcher( needed ); assertFalse( matcher.matches( "1.1.9" ) ); assertFalse( matcher.matches( "1.2" ) ); assertTrue( matcher.matches( "1.2.3" ) ); assertFalse( matcher.matches( "1.2.6" ) ); assertFalse( matcher.matches( "1.3.0" ) ); assertFalse( matcher.matches( "2.2.4" ) ); needed = "1.2+"; matcher = new VersionMatcher( needed ); assertFalse( matcher.matches( "1.1.9" ) ); assertTrue( matcher.matches( "1.2" ) ); assertTrue( matcher.matches( "1.2.5" ) ); assertTrue( matcher.matches( "1.2.6" ) ); assertTrue( matcher.matches( "1.3.0" ) ); assertFalse( matcher.matches( "2.2.4" ) ); needed = "1.2+.5+"; matcher = new VersionMatcher( needed ); assertFalse( matcher.matches( "1.2" ) ); assertFalse( matcher.matches( "1.2.4" ) ); assertTrue( matcher.matches( "1.2.5" ) ); assertTrue( matcher.matches( "1.2.6" ) ); assertTrue( matcher.matches( "1.3.0" ) ); assertFalse( matcher.matches( "2.2.4" ) ); needed = "1+.2+.5+"; matcher = new VersionMatcher( needed ); assertFalse( matcher.matches( "1.2" ) ); assertFalse( matcher.matches( "1.2.4" ) ); assertTrue( matcher.matches( "1.2.5" ) ); assertTrue( matcher.matches( "1.2.6" ) ); assertTrue( matcher.matches( "1.3.0" ) ); assertTrue( matcher.matches( "2.0.0" ) ); assertTrue( matcher.matches( "2.2.4" ) ); } }
package org.sopt.mvvmdiaryexample.data.executor import android.os.Handler import android.os.Looper import java.util.concurrent.Executor import java.util.concurrent.Executors class DispatchExecutors( val ioThread: Executor = IoThreadExecutor, val mainThread: Executor = MainThreadExecutor, ) { companion object { private var instance: DispatchExecutors? = null fun getInstance(): DispatchExecutors { return instance ?: synchronized(this) { DispatchExecutors().also { instance = it } } } } } private object MainThreadExecutor : Executor { private val mainThreadHandler = Handler(Looper.getMainLooper()) override fun execute(command: Runnable) { mainThreadHandler.post(command) } } // Main Thread 이외의 Thread 라고 IO로 통상적으로 부름 // Background Thread 에서 코드를 돌릴거다 private object IoThreadExecutor : Executor { private val ioThreadExecutor = Executors.newSingleThreadExecutor() override fun execute(command: Runnable) { ioThreadExecutor.execute(command) } }
#include <iostream> #include <list> int menu(); int* agregarArray(); void mostrarArray(int arrayNums[], int tamano); void continuar(); int busquedaLineal(int arrayNums[], int size, int buscado); int validarNum(); void cambiarLugar(int& a, int&b); int particionar(int arrayNums[], int bajo, int alto); void quickSort(int arrayNums[], int bajo, int alto); void ordenarArray(); int busquedaBinaria(int arrayNums[], int target); int busquedaInterpolacion(int arrayNums[], int target); int* arrayNums = agregarArray(); int buscado = 0; int counter = 0; int arrayOrdenado[10]; int main() { mostrarArray(arrayNums, counter); continuar(); int size = counter; while (true) { validarNum(); int opcion = menu(); switch (opcion) { case 1: { system("cls"); int indice = busquedaLineal(arrayNums, size, buscado); if (indice != -1) { std::cout << "El número " << buscado << " se encuentra en la posición " << indice << " del array.\n"; continuar(); system("cls"); } else { std::cout << "El número " << buscado << " no se encuentra en el array.\n"; continuar(); system("cls"); } } break; case 2: { system("cls"); ordenarArray(); std::cout << "***** ORDENAMIENTO DE ARRAY *****\n\n\n"; std::cout << "Para llevar a cabo la búsqueda binaria es necesario contar con un array ordenado (Khan Academy, 2022)\nPor lo tanto, se procede a ordenar el arreglo capturado:\n\n"; std::cout << "\nArreglo original: \n\n"; for (int i = 0; i < counter; i++) { std::cout << arrayNums[i] << " "; } std::cout << std::endl; std::cout << "\n\n\nArreglo ordenado: \n\n"; for (int i= 0; i < counter; i++) { std::cout << arrayOrdenado[i] << " "; } std::cout << std::endl; continuar(); system("cls"); int indice = busquedaBinaria(arrayOrdenado, buscado); if(indice != -1) { std::cout << "El número " << buscado << " se encuentra en la posición " << indice << " del array.\n\n"; continuar(); system("cls"); } else { std::cout << "El número " << buscado << " no se encuentra en el array.\n"; continuar(); system("cls"); } } break; case 3: { system("cls"); int indice = busquedaInterpolacion(arrayOrdenado, buscado); if(indice != -1) { std::cout << "\nEl número " << buscado << " se encuentra en la posición " << indice << " del array.\n\n"; continuar(); system("cls"); } else { std::cout << "\nEl número " << buscado << " no se encuentra en el array.\n"; continuar(); system("cls"); } } break; case 4: { std::cout << "Saliendo del programa.\n"; return 0; } default: std::cout << "Opción inválida.\n"; break; } } return 0; } int menu() { int opcion; std::cout << "**** MENÚ DE OPCIONES ****\n\n"; std::cout << "MÉTODOS DE BÚSQUEDA: \n"; std::cout << "1. SECUENCIAL\n"; std::cout << "2. BINARIA\n"; std::cout << "3. INTERPOLACIÓN\n"; std::cout << "4. SALIR DEL PROGRAMA\n"; std::cout << "\nElige una opción: "; std::cin >> opcion; std::cin.ignore(); // Descartar el carácter de nueva línea return opcion; } int* agregarArray() { int* arrayNums = new int[10]; counter = 0; std::cout << "\n\n+++++ CREAR ARRAY +++++\n\n\nIngrese valores para agregar al array. Presione 'q' para finalizar.\n"; while (counter < 10) { std::string entrada; std::cout << "Ingrese un número entero positivo par: "; std::getline(std::cin, entrada); if (entrada == "q" || entrada == "Q") { break; } try { int num = std::stoi(entrada); if (num > 0 && num % 2 == 0) { bool numeroRepetido = false; for (int i = 0; i < counter; ++i) { if (arrayNums[i] == num) { numeroRepetido = true; break; } } if (numeroRepetido) { std::cout << "El número " << num << " ya está en el array.\n"; std::cout << "Este valor es inválido, no se ha agregado al array.\n\n"; } else { arrayNums[counter] = num; std::cout << "El valor ingresado para la posición " << counter << " es " << num <<".\n\n"; ++counter; } } else { std::cout << "El número " << num << " es inválido. Debe ser positivo y par.\n\n"; } } catch (const std::invalid_argument&) { std::cout << "Entrada inválida. Intente nuevamente.\n"; } } return arrayNums; } void mostrarArray(int arrayNums[], int tamano) { std::cout << "Los elementos agregados al array son:\n\n"; for (int i = 0; i < tamano; ++i) { std::cout << "Posición [" << i << "]: " << arrayNums[i] << "\n"; } } void continuar() { std::cout << "\n\nPresione ENTER para continuar..."; std::cin.get(); // Capturar el ENTER system("cls"); } int validarNum() { bool valorIncorrecto = true; std::cout << "\n ***** BUSCAR UN NÚMERO EN EL ARRAY *****\n"; do { std::string entrada; std::cout << "\n\nIngrese un número entero positivo par a buscar (o 'q' para salir): "; std::getline(std::cin, entrada); if (entrada == "q" || entrada == "Q") { valorIncorrecto = false; // Exit the loop } else { try { int num = std::stoi(entrada); if (num > 0 && num % 2 == 0) { buscado = num; valorIncorrecto = false; // Exit the loop } else { std::cout << "El número " << num << " es inválido. Debe ser positivo y par.\n\n"; } } catch (const std::invalid_argument&) { std::cout << "Entrada inválida. Intente nuevamente.\n"; } } } while (valorIncorrecto); std::cout << "Se buscará el número: " << buscado; continuar(); return buscado; } int busquedaLineal(int arrayNums[],int size, int value) { for (int i = 0; i < size; i++) { if (arrayNums[i] == value) { std::cout << "\nIteración: " << i + 1 << " se localizó " << value <<"\n"; return i; } else { std::cout << "Iteración: " << i + 1 << " aún sin localizar " << value <<"\n\n"; } } return -1; } void cambiarLugar(int& a, int& b) { int temp = a; a = b; b = temp; } int particionar(int arrayNums[], int bajo, int alto) { int pivote = arrayNums[alto]; int i = bajo - 1; for (int j = bajo; j <= alto - 1; j++) { if (arrayNums[j] < pivote) { i++; cambiarLugar(arrayNums[i], arrayNums[j]); } } cambiarLugar(arrayNums[i + 1], arrayNums[alto]); return (i + 1); } void quickSort(int arrayNums[], int bajo, int alto) { if (bajo < alto) { int p = particionar(arrayNums, bajo, alto); quickSort(arrayNums, bajo, p - 1); quickSort(arrayNums, p + 1, alto); } } void ordenarArray() { for(int i = 0; i < counter; i++) { arrayOrdenado[i] = arrayNums[i]; } quickSort(arrayOrdenado, 0, counter-1); } int busquedaBinaria(int arrayNums[], int target) { int contador = 0; int izquierda = 0; int derecha = counter - 1; while (izquierda <= derecha) { int medio = izquierda + (derecha - izquierda) / 2; if (arrayNums[medio] == target) { std::cout << "\nIteración: " << contador + 1 << " se localizó " << target <<"\n"; return medio; } else if (arrayNums[medio] < target) { izquierda = medio + 1; std::cout << "Iteración: " << contador + 1 << " aún sin localizar " << target <<"\n\n"; contador++; } else { derecha = medio - 1; std::cout << "Iteración: " << contador + 1 << " aún sin localizar " << target <<"\n\n"; contador++; } } return -1; } int busquedaInterpolacion(int arrayNums[], int target) { int bajo = 0; int alto = counter - 1; int contador = 0; while (bajo <= alto && target >= arrayNums[bajo] && target <= arrayNums[alto]) { if (bajo == alto) { if (arrayNums[bajo] == target) return bajo; return -1; } int pos = bajo + ((double)(alto - bajo) / (arrayNums[alto] - arrayNums[bajo])) * (target - arrayNums[bajo]); if (arrayNums[pos] == target) { std::cout << "\nIteración: " << contador + 1 << " se localizó " << target <<"\n"; return pos; } else if (arrayNums[pos] < target) { bajo = pos + 1; std::cout << "Iteración: " << contador + 1 << " aún sin localizar " << target <<"\n\n"; contador++; } else { alto = pos - 1; std::cout << "Iteración: " << contador + 1 << " aún sin localizar " << target <<"\n\n"; contador++; } } return -1; }
package com.simplefinance.feature.news.presentation.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.simplefinance.common.model.ErrorEntity import com.simplefinance.common.ui.BaseUiModel import com.simplefinance.feature.news.data.model.News import com.simplefinance.feature.news.domain.usecase.NewsUseCase import com.simplefinance.feature.news.presentation.mapper.NewsMapper import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class NewsViewModel @Inject constructor(var newsUseCase: NewsUseCase, var dataMapper: NewsMapper) : ViewModel() { private val _uiData: MutableStateFlow<BaseUiModel> = MutableStateFlow<BaseUiModel>(BaseUiModel()) val uiData: MutableStateFlow<BaseUiModel> = _uiData init { insertNews() getData() } fun getData() { viewModelScope.launch(Dispatchers.IO) { val result = newsUseCase.invoke() result.catch { uiData.emit(dataMapper.map(ErrorEntity.getInstance(it.message!!))) }.collect() { uiData.emit(dataMapper.map(it)) } } } fun insertNews() { viewModelScope.launch { newsUseCase.insertNews(News("job", "description")) } } override fun onCleared() { super.onCleared() viewModelScope.cancel() } }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style> td { font: 20px 宋体; width: 80px; background-color: white; } </style> <script type="text/javascript"> window.onload = function () { //为文本框注册一个键盘按下后弹起的事件 document.getElementById('txtPwd').onkeyup = function () { var tds = document.getElementById('tbl1').getElementsByTagName('td'); //初始化颜色 for (var i = 0; i < tds.length; i++) { tds[i].style.backgroundColor = ''; } //1、获取用户输入的内容 var pwd = this.value; if (pwd.length > 0) { //2、根据用户输入的密码,校验长度 var pwdLevel = getPasswordLevel(pwd); //3、根据密码强度,设置显示强度等级 switch (pwdLevel) { case 0: case 1: case 2: //弱 tds[0].style.backgroundColor = 'red'; break; case 3: case 4: //中 tds[0].style.backgroundColor = 'orange'; tds[1].style.backgroundColor = 'orange'; break; case 5: //强 tds[0].style.backgroundColor = 'green'; tds[1].style.backgroundColor = 'green'; tds[2].style.backgroundColor = 'green'; break; } } }; }; //定义函数,计算密码强度 function getPasswordLevel(upwd) { var lvl = 0; //1、如果密码中包含数字,则强度加1 if (upwd.match(/\d+/)) { lvl++; } //2、如果密码中包含小写字母,则强度加1 if (upwd.match(/[a-z]+/)) { lvl++; } //3、如果密码中包含大写字母,则强度加1 if (upwd.match(/[A-Z]+/)) { lvl++; } //4、如果密码中包含特殊符号,则强度加1 if (upwd.match(/^[0-9a-zA-Z]+/)) { lvl++; } //5、如果密码长度超过6位,则强度加1 if (upwd.length > 6) { lvl++; } return lvl;//返回密码强度 计算值 } </script> </head> <body> 请输入密码:<input type="text" name="name" id="txtPwd"> <table id="tbl1" border="1" cellpadding="0" cellspacing="0"> <tr> <td> 弱 </td> <td> 中 </td> <td> 强 </td> </tr> </table> </body> </html>
import React, { useState } from 'react' import { KeyboardAvoidingView, View } from 'react-native' import { Button, HelperText, TextInput, Title } from 'react-native-paper' import { cores } from '../../../globalStyles' import { useHeaderHeight } from '@react-navigation/elements'; import API from '../../api/service' import styles from './styles' export default function Cadastro({navigation}) { const [nome, setNome] = useState(''); const [email, setEmail] = useState(''); const [cargo, setCargo] = useState(''); const [senha, setSenha] = useState(''); const [exibir, setExibir] = useState(0); function criarConta(){ const user = { nome, cargo, email, senha } API.criarConta(user) .then(res => { navigation.navigate('Login') }) .catch(console.log) } const validEmail = () => email && email.includes('@') const validPass = () => senha && senha.length >= 8 function renderSenha(){ return ( <> <TextInput style={styles.input} onChangeText={cargo => setCargo(cargo)} value={cargo} label='Cargo' mode='outlined' selectionColor={cores.azulPrimario} activeOutlineColor={cores.azulPrimario} outlineColor={cores.preto} /> <HelperText visible={false}></HelperText> <TextInput secureTextEntry={true} style={styles.input} onChangeText={senha => setSenha(senha)} value={senha} label='Senha' error={senha && !validPass()} placeholder='*****' mode='outlined' selectionColor={cores.azulPrimario} activeOutlineColor={cores.azulPrimario} outlineColor={cores.preto} /> <HelperText type='error' visible={senha && !validPass()} >A senha deve conter no mínimo 8 caracteres</HelperText> <Button mode='contained' color={cores.azulPrimarioEscuro} style={styles.cadastroBotao} onPress={criarConta} > Criar Conta </Button> </> ) } function renderEmail(){ return ( <> <TextInput style={styles.input} onChangeText={nome => setNome(nome)} value={nome} label='Nome' mode='outlined' selectionColor={cores.azulPrimario} activeOutlineColor={cores.azulPrimario} outlineColor={cores.preto} /> <HelperText visible={false}></HelperText> <TextInput style={styles.input} onChangeText={email => setEmail(email)} value={email} label='Email' mode='outlined' error={email && !validEmail()} selectionColor={cores.azulPrimario} activeOutlineColor={cores.azulPrimario} outlineColor={cores.preto} /> <HelperText type='error' visible={email && !validEmail()} >Email inválido</HelperText> <Button mode='contained' color={cores.azulPrimarioEscuro} style={styles.cadastroBotao} onPress={() => setExibir(exibir + 1)} >Próximo</Button> </> ) } return ( <View style={styles.cadastro}> <Title style={styles.cadastroTitulo}>Cadastro</Title> { exibir === 0 ? renderEmail() : renderSenha() } </View> ) }
/* eslint-disable camelcase */ import { useCallback } from 'react' import { Contract } from '@ethersproject/contracts' import { PoHContractABI, UBIV2ContractABI, PoH_CONTRACT_ADDRESS, UBIv2_CONTRACT_ADDRESS, } from '@constants' import { useWallet } from '@hooks' const GAS_LIMIT = 200 * 21000 // const fetcher = // (library: Web3Provider, abi: any, address: any, method: string) => // (...args: any[]): Promise<any> => { // // it's a contract // if (isAddress(address)) { // const contract = new Contract(address, abi, library.getSigner()) // // if (filterName) { // // const fromMe = contract.filters[filterName](account, null) // // library.on(fromMe, (from, to, amount, event) => { // // console.log('Transfer|sent', { from, to, amount, event }) // // }) // // } // console.log('calling contract', method, args) // const extraParams = account // ? { // from: account, // gasLimit: GAS_LIMIT, // } // : {} // return contract[method](...args, extraParams) // } // console.log('here') // // it's a eth call // return (library as any)[method](...args) // } const UBIv2_CONTRACT_NAME = 'UBIv2' const PoH_CONTRACT_NAME = 'PoH' const ADMITTED_CONTRACTS = [UBIv2_CONTRACT_NAME, PoH_CONTRACT_NAME] as const type ContractType = typeof ADMITTED_CONTRACTS[number] const CONTRACT_INFO = { [UBIv2_CONTRACT_NAME]: { abi: UBIV2ContractABI, address: UBIv2_CONTRACT_ADDRESS, }, [PoH_CONTRACT_NAME]: { abi: PoHContractABI, address: PoH_CONTRACT_ADDRESS, }, } const errorFn = () => { throw new Error('No active wallet') } interface IContractFunctionParams { contractCallArguments?: any[] addOverridaParams?: boolean extraParams?: { gasLimit?: number from?: string gasPrice?: number value?: string blockTag?: string } } const useContractCall = (contractType: ContractType, method: string) => { const { library, active, account } = useWallet() const { abi, address } = CONTRACT_INFO[contractType] const call = useCallback( ({ contractCallArguments = [], addOverridaParams = false, extraParams, }: IContractFunctionParams): Promise<any> => { if (active) { const contract = new Contract(address, abi, library!.getSigner()) const override = addOverridaParams ? { from: account, gasLimit: GAS_LIMIT, ...extraParams, } : null return contract[method](...contractCallArguments, override) } return errorFn() }, [library, active] ) return { call } } export default useContractCall
import { Actions } from "@/types"; import { CommandInteraction, InteractionType, SlashCommandBuilder, } from "discord.js"; import { member, role, server } from "./infos"; export const data = new SlashCommandBuilder() .setName("info") .setDescription("Info related commands") .addSubcommand((subcommand) => subcommand .setName("member") .setDescription("See info regarding a specific member") .addMentionableOption((option) => option .setName("member") .setDescription("Member to look up") .setRequired(false), ), ) .addSubcommand((subcommand) => subcommand .setName("role") .setDescription("See info regarding a specific role") .addMentionableOption((option) => option .setName("role") .setDescription("Role to look up") .setRequired(true), ), ) .addSubcommand((subcommand) => subcommand .setName("server") .setDescription("See info regarding the server"), ) .setDMPermission(false); export const execute = async (interaction: CommandInteraction) => { if ( interaction.type !== InteractionType.ApplicationCommand || !interaction.isChatInputCommand() ) return; const command = interaction.options.getSubcommand(); await interaction.deferReply(); const actions: Actions = { member: member, role: role, server: server, }; return actions[command](interaction); };
from django.shortcuts import render, get_object_or_404, redirect from django.views import View from django.views.generic import CreateView, FormView, ListView, RedirectView from django.urls import reverse_lazy from django.contrib.auth import login, logout from datetime import datetime from django.contrib import messages from .models import User, List_Element, Shopping_List, To_Do_List, To_Do_Element from .forms import ( LoginForm, AddUserForm, EditUserForm, AddShoppingListForm, AddShoppingListElementForm, EditShoppingListElement, AddToDoListForm, AddToDoElementForm, EditToDoElementForm, ) class IndexView(View): """ Straight-forward landing page rendering for the application """ def get(self, request, *args, **kwargs): template_name = "haulistic/index.html" context = { 'now': datetime.now().year, } return render(request, template_name, context) class AddUserView(CreateView): """ New user creation using CreateView and AddUserForm that inherits from UserCreationForm (all authentication of passwords, usernames, emails etc. handled by Django middlewares) - basically, Django does the heavy lifting here if you provide needed resources based on the documentation """ template_name = "haulistic/add_user.html" model = User form_class = AddUserForm extra_context = {'now': datetime.now().year} success_url = reverse_lazy("login") def EditUserView(request): """ Simple user updating view - no password change is allowed """ form = EditUserForm(instance=request.user) if request.method == "POST": form = EditUserForm(request.POST, instance=request.user) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, "Account " + username +" successfully modified!") return redirect('/dashboard/') context = { "form": form, 'now': datetime.now().year, } return render(request, 'haulistic/edit_user.html', context) class UserListView(ListView): """ A basic listing of all created users for staff members that are not super-users """ template_name = "haulistic/user_list.html" model = User extra_context = {'now': datetime.now().year} context_object_name = "users" ordering = ['pk'] class LoginView(FormView): """ Login view that logs you if provided with proper credentials """ template_name = "haulistic/login.html" form_class = LoginForm success_url = reverse_lazy("dashboard") extra_context = {'now': datetime.now().year} def form_valid(self, form): user = form.user login(self.request, user) return super().form_valid(form) class LogoutView(RedirectView): """ Logout view that logs out the user """ url = reverse_lazy("index") def get(self, request, *args, **kwargs): logout(request) return super().get(request, *args, **kwargs) class DashboardView(View): """ Dashboard view that pulls the default lists created for every new account and lists all the elements contained in those default lists """ def get(self, request, *args, **kwargs): messages.info(request, "Welcome " + self.request.user.username +"!") logged_user_id = self.request.user.id default_sh_list = Shopping_List.objects.all().filter(list_owner=logged_user_id)[0] default_td_list = To_Do_List.objects.all().filter(list_owner=logged_user_id)[0] sh_list_elements = List_Element.objects.all().filter(list_pk=default_sh_list.id) td_list_elements = To_Do_Element.objects.all().filter(list_pk=default_td_list.id) context = { "sh_list":default_sh_list, "sh_elements":sh_list_elements, "td_list":default_td_list, "td_elements":td_list_elements, 'now': datetime.now().year, } return render(request, 'haulistic/dashboard.html', context) class AllShoppingListsView(View): """ Listing all shopping lists owned by the logged-in user """ def get(self, request, *args, **kwargs): logged_user_id = self.request.user.id owned_lists = Shopping_List.objects.all().filter(list_owner=logged_user_id) messages.info(request, "Click on the name of the list to see details.") context = { 'lists':owned_lists, 'now': datetime.now().year, } return render(request, 'haulistic/all_shopping_lists.html', context) def AddShoppingListView(request, *args, **kwargs): """ Creation of a new shopping list """ logged_user = request.user form = AddShoppingListForm() if request.method == 'POST': form = AddShoppingListForm(request.POST) if form.is_valid(): new_list = form.save(commit=False) new_list.list_owner = logged_user # assigning the created list to the logged user new_list.save() list_name_msg = form.cleaned_data.get('list_name') messages.success(request, 'Successfully added new list "' + list_name_msg +'"!') return redirect('/list/shop/all/') context = { 'form': form, 'now': datetime.now().year, } return render(request, 'haulistic/add_shopping_list.html', context) class DetailShoppingListView(View): """ A view that shows all elements contained in a given list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ def get(self, request, *args, **kwargs): list_pk = kwargs['list_pk'] chosen_list = get_object_or_404(Shopping_List, pk=list_pk) list_elements = List_Element.objects.all().filter(list_pk=list_pk).order_by('bought') if request.user == chosen_list.list_owner: # checking if the logged user is the owner of the list context = { "list": chosen_list, "elements": list_elements, 'now': datetime.now().year, } return render(request, 'haulistic/shopping_list_details.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year, 'access': 'no_access'}) def EditShoppingListView(request, list_pk): """ A view that lets the owner of the list modify the name or the category of the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ sh_list = Shopping_List.objects.get(id=list_pk) form = AddShoppingListForm(instance=sh_list) if request.user == sh_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': form = AddShoppingListForm(request.POST, instance=sh_list) if form.is_valid(): form.save() list_name_msg = form.cleaned_data.get('list_name') messages.success(request, 'Successfully modified list "' + list_name_msg +'"!') return redirect('/list/shop/all/') context = { 'form': form, 'now': datetime.now().year, } return render(request, 'haulistic/add_shopping_list.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) # if not user sees this page def DeleteShoppingListView(request, list_pk): """ A view that lets the owner of the list delete the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ sh_list = Shopping_List.objects.get(id=list_pk) logged_user_id = request.user.id default_sh_list = Shopping_List.objects.all().filter(list_owner=logged_user_id)[0] if request.user == sh_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': if default_sh_list.pk == list_pk: # cheking if the list is the default one that can't be deleted context = {'now': datetime.now().year, 'list': default_sh_list} return render(request, 'haulistic/big_no_no.html', context) # if it's the default render this page else: sh_list.delete() messages.success(request, "List deleted.") return redirect('/list/shop/all/') context = { 'list': sh_list, 'now': datetime.now().year, } return render(request, 'haulistic/delete.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) # if not user sees this page def AddShoppingListElementView(request, *args, **kwargs): """ A view that allows the user to add new positions to the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ active_list = Shopping_List.objects.get(pk=kwargs['list_pk']) form = AddShoppingListElementForm() if request.user == active_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': form = AddShoppingListElementForm(request.POST) if form.is_valid(): new_list = form.save(commit=False) new_list.list_pk = active_list new_list.save() element_name_msg = form.cleaned_data.get('element_name') messages.success(request, 'Successfully added new product "' + element_name_msg +'" to the list.') form = AddShoppingListElementForm() context = { 'form': form, 'now': datetime.now().year, 'list': active_list, } return render(request, 'haulistic/add_shopping_list_element.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) def EditShoppingListElementView(request, list_pk, element_pk): """ A view that lets the owner of the list modify the elements of the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ sh_list = Shopping_List.objects.get(id=list_pk) sh_element = get_object_or_404(List_Element, pk=element_pk) form = EditShoppingListElement(instance=sh_element) if request.user == sh_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': form = EditShoppingListElement(request.POST, instance=sh_element) if form.is_valid(): form.save() element_name_msg = form.cleaned_data.get('element_name') messages.success(request, 'Successfully modified element "' + element_name_msg +'"!') return redirect(f'/list/shop/{list_pk}/') context = { 'list': sh_list, 'form': form, 'now': datetime.now().year, } return render(request, 'haulistic/add_shopping_list_element.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) def AddToDefaultShoppingListElementView(request, *args, **kwargs): """ This view was strictly needed for the quick-access side panel button 'add to default' to work, so the user can quickly add something to a default list without searching for the proper one """ logged_user_id = request.user.id default_sh_list = Shopping_List.objects.all().filter(list_owner=logged_user_id)[0] form = AddShoppingListElementForm() if request.method == 'POST': form = AddShoppingListElementForm(request.POST) if form.is_valid(): new_list = form.save(commit=False) new_list.list_pk = default_sh_list new_list.save() element_name_msg = form.cleaned_data.get('element_name') messages.success(request, 'Successfully added new product "' + element_name_msg +'" to the list.') form = AddShoppingListElementForm() context = { 'form': form, 'now': datetime.now().year, 'list': default_sh_list, } return render(request, 'haulistic/add_shopping_list_element.html', context) class AllToDoListsView(View): """ Listing all To-Do lists owned by the logged-in user """ def get(self, request, *args, **kwargs): logged_user_id = self.request.user.id owned_lists = To_Do_List.objects.all().filter(list_owner=logged_user_id) messages.info(request, "Click on the name of the list to see details.") context = { 'lists':owned_lists, 'now': datetime.now().year, } return render(request, 'haulistic/all_to_do_lists.html', context) def AddToDoListView(request, *args, **kwargs): """ Creation of a new To-Do list """ logged_user = request.user form = AddToDoListForm() if request.method == 'POST': form = AddToDoListForm(request.POST) if form.is_valid(): new_list = form.save(commit=False) new_list.list_owner = logged_user # assigning the created list to the logged user new_list.save() list_name_msg = form.cleaned_data.get('list_name') messages.success(request, 'Successfully added new list "' + list_name_msg +'"!') return redirect('/list/to-do/all/') context = { 'form': form, 'now': datetime.now().year, } return render(request, 'haulistic/add_to_do_list.html', context) class DetailToDoListView(View): """ A view that shows all elements contained in a given list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ def get(self, request, *args, **kwargs): list_pk = kwargs['list_pk'] chosen_list = get_object_or_404(To_Do_List, pk=list_pk) list_elements = To_Do_Element.objects.all().filter(list_pk=list_pk).order_by('completed') if request.user == chosen_list.list_owner: # checking if the logged user is the owner of the list context = { "list":chosen_list, "elements":list_elements, 'now': datetime.now().year, } return render(request, 'haulistic/to_do_list_details.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) def EditToDoListView(request, list_pk): """ A view that lets the owner of the list modify the name or the category of the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ td_list = To_Do_List.objects.get(id=list_pk) form = AddToDoListForm(instance=td_list) if request.user == td_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': form = AddToDoListForm(request.POST, instance=td_list) if form.is_valid(): form.save() list_name_msg = form.cleaned_data.get('list_name') messages.success(request, 'Successfully modified list "' + list_name_msg +'"!') return redirect('/list/to-do/all/') context = { 'form': form, 'now': datetime.now().year, } return render(request, 'haulistic/add_to_do_list.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) def DeleteToDoListView(request, list_pk): """ A view that lets the owner of the list delete the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ logged_user_id = request.user.id default_td_list = To_Do_List.objects.all().filter(list_owner=logged_user_id)[0] td_list = To_Do_List.objects.get(id=list_pk) if request.user == td_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': if default_td_list.pk == list_pk: context = {'now': datetime.now().year, 'list': default_td_list} return render(request, 'haulistic/big_no_no.html', context) else: td_list.delete() messages.success(request, "List deleted.") return redirect('/list/to-do/all/') context = { 'list': td_list, 'now': datetime.now().year, } return render(request, 'haulistic/delete.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) def AddToDoElementView(request, *args, **kwargs): """ A view that allows the user to add new positions to the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ active_list = To_Do_List.objects.get(pk=kwargs['list_pk']) form = AddToDoElementForm() if request.user == active_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': form = AddToDoElementForm(request.POST) if form.is_valid(): new_list = form.save(commit=False) new_list.list_pk = active_list new_list.save() element_name_msg = form.cleaned_data.get('element_name') messages.success(request, 'Successfully added new task "' + element_name_msg + '" to the list.') form = AddToDoElementForm() context = { 'form': form, 'now': datetime.now().year, 'list': active_list, } return render(request, 'haulistic/add_to_do_list_element.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) def EditToDoListElementView(request, list_pk, element_pk): """ A view that lets the owner of the list modify the elements of the list (as the ID of the list is shown in the url there's a special if statement to check if the logged-in user is the owner of the selected list) """ td_list = To_Do_List.objects.get(id=list_pk) td_element = get_object_or_404(To_Do_Element, pk=element_pk) form = EditToDoElementForm(instance=td_element) if request.user == td_list.list_owner: # checking if the logged user is the owner of the list if request.method == 'POST': form = EditToDoElementForm(request.POST, instance=td_element) if form.is_valid(): form.save() element_name_msg = form.cleaned_data.get('element_name') messages.success(request, 'Successfully modified element "' + element_name_msg +'"!') return redirect(f'/list/to-do/{list_pk}/') context = { 'list': td_list, 'form': form, 'now': datetime.now().year, } return render(request, 'haulistic/add_to_do_list_element.html', context) else: return render(request, 'haulistic/no_access.html', {'now': datetime.now().year}) def AddDefaultToDoElementView(request, *args, **kwargs): """ This view was strictly needed for the quick-access side panel button 'add to default' to work, so the user can quickly add something to a default list without searching for the proper one """ logged_user_id = request.user.id default_td_list = To_Do_List.objects.all().filter(list_owner=logged_user_id)[0] form = AddToDoElementForm() if request.method == 'POST': form = AddToDoElementForm(request.POST) if form.is_valid(): new_list = form.save(commit=False) new_list.list_pk = default_td_list new_list.save() element_name_msg = form.cleaned_data.get('element_name') messages.success(request, 'Successfully added new task "' + element_name_msg + '" to the list.') form = AddToDoElementForm() context = { 'form': form, 'now': datetime.now().year, 'list': default_td_list, } return render(request, 'haulistic/add_to_do_list_element.html', context)
//Modules import _ from "lodash"; import React, { Component, ReactNode } from "react"; import { withRouter, Prompt, RouteComponentProps } from "react-router-dom"; import { Formik, Form, FormikHelpers, FormikProps } from "formik"; import { diff } from "deep-object-diff"; import { ObjectSchema } from "yup"; //Components import { DeleteButtons } from "./fields/DeleteButtons"; //Enums import { FormFieldTypes, IFieldGroup, IFormikValues } from "~/enum/FormFieldTypes"; //Helpers import { extractYupData, renderFieldGroup, getTouchedNestedErrors } from "~/helpers/formHelper"; //Interfaces interface IProps extends RouteComponentProps { alterValuesBeforeSubmit?: (values: IFormikValues) => IFormikValues | void; className?: string; fastFieldByDefault?: boolean; fieldGroups: IFieldGroup[] | ((values?: IFormikValues) => IFieldGroup[]); includeResetButton?: boolean; initialValues: IFormikValues; isInitialValid?: boolean; isNew: boolean; itemType: string; onDelete?: () => {}; onReset?: () => {}; onSubmit: (values: any, formikProps: FormikHelpers<IFormikValues>) => any; promptOnExit?: boolean; redirectOnDelete?: string; redirectOnSubmit?: string | ((values: IFormikValues) => {}); showErrorSummary?: boolean; submitButtonText?: string; testMode?: boolean; useGrid?: boolean; useFormCard?: boolean; validationSchema: ObjectSchema; } interface IState { fieldGroups: IProps["fieldGroups"]; initialValues: IProps["initialValues"]; isNew: IProps["isNew"]; validationSchema: IProps["validationSchema"]; } //Component class _BasicForm extends Component<IProps, IState> { static defaultProps = { className: "", fastFieldByDefault: true, includeResetButton: true, isInitialValid: false, promptOnExit: true, redirectOnDelete: `/admin/`, showErrorSummary: true, testMode: false, useGrid: true, useFormCard: true }; constructor(props: IProps) { super(props); if (props.testMode) { console.info("Form loaded in test mode"); } this.state = _.pick(props, ["fieldGroups", "initialValues", "isNew", "validationSchema"]); } static getDerivedStateFromProps(nextProps: IProps) { return _.pick(nextProps, ["fieldGroups", "initialValues", "isNew", "validationSchema"]); } getFieldGroups(values: IFormikValues): IFieldGroup[] { const { fieldGroups } = this.props; if (typeof fieldGroups === "function") { return fieldGroups(values); } else { return fieldGroups; } } validateFieldGroups(values: IFormikValues): void { const fieldGroups = this.getFieldGroups(values); _.chain(fieldGroups) .filter("fields") .map("fields") .flatten() .each(field => { let error; switch (field.type) { case FormFieldTypes.radio: case FormFieldTypes.select: { if (!field.options) { error = `Field of type ${field.type} must have an options property`; } break; } case FormFieldTypes.asyncSelect: { if (!field.loadOptions) { error = `Field of type ${field.type} must have a loadOptions property`; } break; } } if (error) { console.error(error, field); } }) .value(); } processValues(values: IFormikValues, fields: IFormikValues, parentPath: string[] = [], isArray: boolean = false) { const callback = (val: any, key: string): any => { //First we determine whether there is a field by this name let field; if (isArray) { field = fields[parentPath.join(".")]; } else { field = fields[[...parentPath, key].join(".")]; } //Convert value let newValue; if (Array.isArray(val)) { //For arrays, go recursive, with isArray set to true newValue = this.processValues(val, fields, [...parentPath, key], true); } else if (typeof val === "object") { //For objects, we check for select fields const isSelect = field && [FormFieldTypes.asyncSelect, FormFieldTypes.creatableSelect].indexOf(field.type) > -1; if (isSelect) { //If it's a creatable or async select, we pull off the value newValue = val.value; } else { //Otherwise, we go recursive newValue = this.processValues(val, fields, [...parentPath, key]); } } else { //For any non-object/array fields, simply return the value as is newValue = val; } return newValue == null || newValue.length === 0 ? null : newValue; }; if (isArray) { return _.map(values, callback); } else { return _.mapValues(values, callback); } } async handleSubmit(fValues: IFormikValues, formikProps: FormikHelpers<IFormikValues>) { const { alterValuesBeforeSubmit, history, onSubmit, redirectOnSubmit, testMode } = this.props; const fieldGroups = this.getFieldGroups(fValues); //Get flat field list const fields = _.chain(fieldGroups).map("fields").flatten().keyBy("name").value(); //Process values (pull value from select fields, convert empty strings to null, etc) let values = this.processValues(_.cloneDeep(fValues), fields); //Custom callback to manipulate values before submitting if (alterValuesBeforeSubmit) { const newValues = alterValuesBeforeSubmit(values); //Most of the time we just manipulate the object without //returning anything from this method. //When we do return, we assign the returned value here if (newValues) { values = newValues; } } //Submit if (testMode) { console.info("Test outcome: ", values); } else { const result = await onSubmit(values, formikProps); //Redirect if (typeof redirectOnSubmit === "function" && result && redirectOnSubmit(result)) { history.push(redirectOnSubmit(result)); } else if (typeof redirectOnSubmit === "string") { history.push(redirectOnSubmit); } //Required in case the submit is unsuccessful formikProps.setSubmitting(false); } } async handleDelete() { const { history, onDelete, redirectOnDelete, testMode } = this.props; if (onDelete && !testMode) { const success = await onDelete(); if (success && redirectOnDelete) { history.replace(redirectOnDelete); } } } renderFields(values: IFormikValues, formikProps: FormikProps<IFormikValues>): ReactNode[] { const { fastFieldByDefault, testMode } = this.props; const { validationSchema } = this.state; const fieldGroups = this.getFieldGroups(values); //Validate this.validateFieldGroups(values); //Log in test mode if (testMode) { console.info("Values", values); console.info("Field Groups", fieldGroups); if (Object.keys(formikProps.errors).length) { console.info("Errors", formikProps.errors); } } return _.flatten( fieldGroups.map((fieldGroup: IFieldGroup, i: number) => { const content = []; if (fieldGroup.label) { content.push(<h6 key={`label-${i}`}>{fieldGroup.label}</h6>); } if ("render" in fieldGroup) { //Custom Render content.push(fieldGroup.render(values, formikProps)); } else if (fieldGroup.hasOwnProperty("fields")) { //Standard fields content.push(renderFieldGroup(fieldGroup.fields, validationSchema, fastFieldByDefault)); } return content; }) ); } renderErrors(nestedErrors: IFormikValues, nestedTouched: IFormikValues) { const { showErrorSummary, useFormCard, validationSchema } = this.props; if (showErrorSummary) { const errors = getTouchedNestedErrors(nestedErrors, nestedTouched); if (Object.keys(errors).length) { const errorList = Object.keys(errors).map(name => { const yupField = extractYupData(name, validationSchema); const label = yupField && yupField.label ? yupField.label : name; return <li key={name}>{label}</li>; }); const content = ( <div className="error"> <strong>The following fields have errors:</strong> <ul>{errorList}</ul> </div> ); if (useFormCard) { //If the parent is a form-card, we return as-is return content; } else { //Otherwise, wrap it in in a form-card return <div className="form-card">{content}</div>; } } } } renderSubmitButtons(formHasChanged: boolean, isSubmitting: boolean) { let { includeResetButton, isInitialValid, itemType, submitButtonText, useFormCard } = this.props; const { isNew } = this.state; if (!submitButtonText) { if (isSubmitting) { if (isNew) { submitButtonText = "Adding"; } else { submitButtonText = "Updating"; } } else { if (isNew) { submitButtonText = "Add"; } else { submitButtonText = "Update"; } } submitButtonText += ` ${itemType}`; } const disableButtons = (!formHasChanged && !isInitialValid) || isSubmitting; let resetButton; if (includeResetButton) { resetButton = ( <button type="reset" disabled={disableButtons}> Reset </button> ); } const buttons = ( <div className="buttons"> {resetButton} <button type="submit" className={disableButtons ? "" : "confirm"} disabled={disableButtons}> {submitButtonText} </button> </div> ); if (useFormCard) { //If the parent is a form-card, we return as-is return buttons; } else { //Otherwise, wrap it in in a form-card return <div className="form-card">{buttons}</div>; } } renderDeleteButtons() { const { onDelete } = this.props; if (onDelete) { return ( <div className="form-card"> <DeleteButtons onDelete={() => this.handleDelete()} /> </div> ); } } render() { const { className, isInitialValid, onReset, promptOnExit, useFormCard, useGrid } = this.props; const { initialValues, validationSchema } = this.state; const divClass = [className]; if (useFormCard) { divClass.push("form-card"); if (useGrid) { divClass.push("grid"); } } return ( <Formik enableReinitialize={true} isInitialValid={isInitialValid} initialValues={initialValues} onReset={onReset} onSubmit={(values, formikProps) => this.handleSubmit(values, formikProps)} validationSchema={validationSchema} render={formikProps => { const { errors, initialValues, values, touched, isSubmitting } = formikProps; const formHasChanged = Object.keys(diff(values, initialValues)).length > 0; return ( <Form> <Prompt when={promptOnExit && !isSubmitting && formHasChanged} message="You have unsaved changes. Are you sure you want to navigate away?" /> <div className={divClass.join(" ")}> {this.renderFields(values, formikProps)} {this.renderErrors(errors, touched)} {this.renderSubmitButtons(formHasChanged, isSubmitting)} </div> {this.renderDeleteButtons()} </Form> ); }} /> ); } } export const BasicForm = withRouter(_BasicForm);
import { FC, useState } from "react"; import Cards from "../components/Cards"; import { CustomDrawer } from "../components/Drawer"; import EmptyElement from "../components/EmptyElement"; import Menu from "../components/Menu"; import Modal from "../components/Modal"; import Table from "../components/Table"; import { useProductsContext } from "../hooks/useProductsContext"; import { useWindowSize } from "../hooks/useWindowSize"; import { Product } from "../model/model"; import "./Products.css"; const Products: FC<{}> = () => { const { state } = useProductsContext(); const [width] = useWindowSize(); const [searchValue, setSearchValue] = useState<string>(""); const [selectCode, setCode] = useState<string>(""); const [direction, setDirection] = useState<string>(""); const [columnName, setColumnName] = useState<string>(""); const [open, setOpen] = useState<boolean>(false); const handleOpenModal = (code: string) => { setOpen(!open); setCode(code); }; const handleClose = () => setOpen(!open); const handleSearchValue = (value: string): void => setSearchValue(value); const handleColumnSort = (value: string) => setColumnName(value); const handleColunmDirection = (value: string): void => setDirection(value); let products = searchValue !== "" ? state.products?.filter( (product) => product.code .toLocaleLowerCase() .includes(searchValue.toLocaleLowerCase()) || product .description!.toLocaleLowerCase() .includes(searchValue.toLocaleLowerCase()) ) : (state.products as Product[]); const handleCompare = (productA: Product, productB: Product) => { let comparison = 0; if ( productA[columnName as keyof typeof productA]! < productB[columnName as keyof typeof productB]! ) { comparison = -1; } if ( productA[columnName as keyof typeof productA]! > productB[columnName as keyof typeof productB]! ) { comparison = 1; } return direction !== "desc" ? comparison : comparison * -1; }; const handleSortTable = (): Product[] => products?.sort(handleCompare) as Product[]; return ( <div className="container"> <div className="table__caption"> <h2> Product Table</h2> </div> <Menu handleSearchValue={handleSearchValue} handleColumnSort={handleColumnSort} handleColunmDirection={handleColunmDirection} columnName={columnName} direction={direction} /> {width <= 450 && ( <Cards handleSortTable={handleSortTable} handleOpenModal={handleOpenModal} /> )} {width > 450 && ( <Table handleSortTable={handleSortTable} handleOpenModal={handleOpenModal} /> )} {width > 450 && selectCode && ( <Modal codeProp={selectCode} open={open} handleClose={handleClose} /> )} {width <= 450 && selectCode && ( <CustomDrawer codeProp={selectCode} open={open} handleClose={handleClose} /> )} {!state.products || (products?.length === 0 && <EmptyElement />)} </div> ); }; export default Products;
<?php namespace App\Http\Controllers; use App\Models\Category; use Illuminate\Http\Request; class CategoryController extends Controller { /** * Display a listing of the resource. */ public function index() { $categories = Category::all(); $data = [ 'categories' => $categories, ]; return view('categories.index', $data); } /** * Show the form for creating a new resource. */ public function create() { return view('categories.create'); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|unique:categories|max:255', ]); $category = new Category(); $category->name = $validated['name']; $category->save(); return redirect()->route('categories')->with('success', 'Category created successfully'); } /** * Display the specified resource. */ // public function show(Category $catcategoryegories) // { // // // } /** * Show the form for editing the specified resource. */ public function edit(Category $category) { $data = [ 'category' => $category, ]; return view('categories.edit', $data); } /** * Update the specified resource in storage. */ public function update(Request $request, Category $category) { if ($request->name != $category->name) { $validated = $request->validate([ 'name' => 'required|unique:categories|max:255', ]); $category->name = $validated['name']; $category->save(); } return redirect()->route('categories.edit', $category->id)->with('success', 'Category updated successfully'); } /** * Remove the specified resource from storage. */ public function destroy(Category $category) { $relatedBooks = $category->books; if ($relatedBooks) { return redirect()->route('categories.index')->with('error', 'Cannot delete category, books are associated with this category, please delete books first'); } $category->delete(); return redirect()->route('categories.index')->with('success', 'Category deleted successfully'); } }
import { useRef, useState } from "react"; import React from 'react'; import { useAuth } from "../contexts/AuthContext"; import { Link, useNavigate } from 'react-router-dom' import { Form, Button, Card, Alert } from "react-bootstrap" function Login(){ const emailRef = useRef() const passwordRef = useRef() const { login, logout } = useAuth(); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const navigate = useNavigate(); const [userData, setUserData] = useState({}); async function handleLogin(e){ e.preventDefault(); try{ setError("") setLoading(true) await login(emailRef.current.value, passwordRef.current.value) navigate('/'); } catch{ setError("Failed to log in") } setLoading(false) } async function handleLogout(e){ e.preventDefault(); try{ setError("") setLoading(true) await logout(); navigate('/'); setError("successfully logged out") } catch { setError("Failed to logout") } setLoading(false) } return ( <React.Fragment> <Card> <Card.Body> <h2 className="text-center mb-4">Log In</h2> <Form onSubmit={handleLogin}> <Form.Group id='email'> <Form.Label>Email</Form.Label> <Form.Control type='email' ref={emailRef} required /> </Form.Group> <Form.Group id='password'> <Form.Label>Password</Form.Label> <Form.Control type='password' ref={passwordRef} required /> </Form.Group> <Button disabled={loading} className='w-100 mt-4' type='submit'> Log In</Button> </Form> </Card.Body> </Card> <div className="w-100 text-center mt-2"> Need an Account? <Link to='/sign-up'>Sign Up</Link> </div> <div className="w-100 text-center mt-2"> <Button onClick={handleLogout}>Logout</Button> {error && <Alert variant='danger'>{error}</Alert>} </div> </React.Fragment> ) } export default Login
<html> <head> <title>Snake</title> <style> body{ display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } canvas{ border:1px solid black; } </style> </head> <body> <canvas id="gamecanvas" width="400" height="400" ></canvas> <script> const canvas = document.getElementById('gamecanvas'); const ctx = canvas.getContext('2d'); const GRID_SIZE = 20 const CANVAS_SIZE = 400 const SNAKE_SPEED = 100; const DIRECTIONS = { ArrowUp: {x: 0, y: -1}, ArrowDown: {x: 0, y: 1}, ArrowLeft: {x: -1, y: 0}, ArrowRight: {x: 1, y: 0} }; let snake = [{x: 10, y: 10}]; let food = {x: 5, y: 5}; let direction = DIRECTIONS.ArrowRight; let gameLoop; function draw(){ ctx.fillStyle = 'white'; ctx.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE); ctx.fillStyle = 'green'; snake.forEach(segment => { ctx.fillRect(segment.x * GRID_SIZE, segment.y * GRID_SIZE, GRID_SIZE, GRID_SIZE); }); ctx.fillStyle = 'red'; ctx.fillRect(food.x * GRID_SIZE, food.y * GRID_SIZE, GRID_SIZE, GRID_SIZE); } function update(){ const head = { x : snake[0].x + direction.x, y : snake[0].y + direction.y } if(head.x === food.x && head.y === food.y){ food = { x : Math.floor(Math.random() * CANVAS_SIZE / GRID_SIZE), y : Math.floor(Math.random() * CANVAS_SIZE / GRID_SIZE) } }else{ snake.pop(); } if(head.x < 0 || head.x >= CANVAS_SIZE / GRID_SIZE || head.y >= CANVAS_SIZE / GRID_SIZE || snake.some((segment, index) => index !== 0 && segment.x === head.x && segment.y === head.y) ){ clearInterval(gameLoop); alert('Game Over! Your score: '+ (snake.length - 1)); window.location.reload(); } } function handleKeyDown(event){ const newDirection = DIRECTIONS[event.key]; if(newDirection){ direction = newDirection } } function startGame(){ gameLoop = setInterval(() => { update(); draw(); }, SNAKE_SPEED); // gameLoopw = setInterval(update, SNAKE_SPEED) document.addEventListener('keydown', handleKeyDown); } startGame(); </script> </body> </html>
export interface Forms{ name: string; url: string } export interface Sprites{ back_default: string; back_female: string; back_shiny: string; back_shiny_female: string; front_default: string; front_female: string; front_shiny: string; front_shiny_female: string; } export interface Abilities{ ability: { name: string; url: string; } name: string; url: string is_hidden: boolean; slot: number; } export interface Stats{ base_stat: number; effort: number; stat: { name: string; url: string; } } export interface PokemonDetails{ abilities: Abilities[]; base_experience: number; forms: Forms[]; height: number; id: number; is_default: boolean; location_area_encounters: string; name: string; order: number; past_types: any[]; species: {} sprites: Sprites; stats: Stats[]; weight: number; }
import os import numpy as np from qgis.core import ( QgsProject, QgsPrintLayout, QgsTextFormat, QgsLayoutItemMap, QgsLayoutExporter, QgsStyle, QgsClassificationJenks, QgsGraduatedSymbolRenderer, QgsSymbol, QgsRendererRange, QgsLayoutItemLabel, QgsLayoutItemLegend, QgsMapLayerLegendUtils, QgsRectangle,QgsRasterLayer, QgsCoordinateReferenceSystem ) from qgis.PyQt.QtGui import (QColor, QFont) from qgis.PyQt.QtCore import QRectF import jenkspy # Set CRS for the QGIS project crs = QgsCoordinateReferenceSystem('EPSG:4326') # Replace with your desired EPSG code QgsProject.instance().setCrs(crs) # Setup the output directory output_dir = os.path.join(QgsProject.instance().homePath(), 'figures') if not os.path.exists(output_dir): os.makedirs(output_dir) def calculate_jenks_breaks(values, num_classes): numeric_values = [np.nan if not isinstance(value, (int, float)) else value for value in values] values_array = np.array(numeric_values, dtype=float) finite_values = values_array[np.isfinite(values_array)] if len(finite_values) > 1: return jenkspy.jenks_breaks(finite_values, n_classes=num_classes) else: return [] def apply_graduated_symbology_and_export(layer, field_name, num_classes=5): values = [feature[field_name] for feature in layer.getFeatures() if feature[field_name] is not None] breaks = calculate_jenks_breaks(values, num_classes) if len(breaks) > 1: color_ramp = QgsStyle().defaultStyle().colorRamp('Magma') ranges = [] for i in range(1, len(breaks)): symbol = QgsSymbol.defaultSymbol(layer.geometryType()) color = color_ramp.color(float(i-1) / (len(breaks)-2)) symbol.setColor(color) renderer_range = QgsRendererRange(breaks[i-1], breaks[i], symbol, f"{breaks[i-1]} - {breaks[i]}") ranges.append(renderer_range) renderer = QgsGraduatedSymbolRenderer(field_name, ranges) layer.setRenderer(renderer) layer.triggerRepaint() prepare_layout(layer, field_name) def prepare_layout(layer, field_name): project = QgsProject.instance() layout = QgsPrintLayout(project) layout.initializeDefaults() layout.setName(f"Layout_{field_name}") # Calculate the extent of the GPS points points_extent = calculate_points_extent(layer) aspect_ratio = (points_extent.width() / points_extent.height()) # Example dimensions for A4 size in millimeters layout_width_mm = 297 # A4 width layout_height_mm = 210 # A4 height # Start by setting a maximum width and calculating height based on aspect ratio max_width_mm = layout_width_mm - 20 # Assuming a 10mm margin on each side calculated_height_mm = max_width_mm / aspect_ratio # If the calculated height is too tall for the page, adjust the width instead if calculated_height_mm > (layout_height_mm - 20): # Assuming a 10mm margin top & bottom calculated_height_mm = layout_height_mm - 20 # Adjust height to fit within margins max_width_mm = calculated_height_mm * aspect_ratio # Recalculate width based on adjusted height # Map item map = QgsLayoutItemMap(layout) map_rect = QRectF(0, 0, max_width_mm, calculated_height_mm) # Set the map rectangle size map.setRect(map_rect) map.setExtent(points_extent) # Ensure the map view focuses on your points layout.addLayoutItem(map) # Title item title = QgsLayoutItemLabel(layout) title.setText(f"Mountain Fire {field_name}") title_font = QFont("Arial", 16, QFont.Bold) title.setFont(title_font) # Set text color using QgsTextFormat text_format = QgsTextFormat() text_format.setFont(title_font) text_format.setColor(QColor(255, 255, 255)) # Set text color to white title.setTextFormat(text_format) title_rect = QRectF(10, 10, 277, 30) # Adjust width as needed, leaving space for margins title.setRect(title_rect) layout.addLayoutItem(title) export_layout(layout, field_name) def export_layout(layout, field_name): exporter = QgsLayoutExporter(layout) output_file = os.path.join(output_dir, f"{field_name}.png") exporter.exportToImage(output_file, QgsLayoutExporter.ImageExportSettings()) # Main execution active_layer = iface.activeLayer() if active_layer is None: print("No active layer selected.") else: if active_layer.type() == QgsMapLayer.VectorLayer: print("Active layer is a vector layer.") exclude_columns = ['GPSLon', 'GPSLat', 'GPSAlt'] # Example vector layer processing for field in active_layer.fields(): if field.name().lower() not in exclude_columns: apply_graduated_symbology_and_export(active_layer, field.name()) elif active_layer.type() == QgsMapLayer.RasterLayer: print("Active layer is a raster layer.") # Insert raster-specific logic here if needed
import 'dart:ffi'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:planoclock/brain.dart'; import 'Constants.dart'; import 'package:intl/intl.dart'; class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { final DateFormat _dateFormat = DateFormat('dd/MM/yy'); @override void initState() { timeinput.text = ""; super.initState(); } Future<void> _selectDate(BuildContext context, TextEditingController controller, DateTime selectedDate) async { final DateTime? picked = await showDatePicker( context: context, initialDate: selectedEndDate, firstDate: DateTime(2000), lastDate: DateTime(2101), ); if (picked != null) { setState(() { selectedEndDate = picked; controller.text = _dateFormat.format(selectedStartDate); }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'PlanOClock', style: TextStyle( fontFamily: 'fonts/Pacifico-Regular.ttf', color: Colors.cyan, fontWeight: FontWeight.w500, ), ), centerTitle: true, ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Padding( padding: EdgeInsets.all(p), child: FloatingActionButton( backgroundColor: Color(0xFFb33a6b), child: Icon(Icons.add), onPressed: () { // print('object'); showDialog( context: context, builder: (context) => AlertDialog( title: Text('Are you sure you want to add the note?'), content: IconButton( icon: Icon( Icons.check_circle_outline, color: Colors.green, size: 40, ), onPressed: () { setState(() { addTitle(); }); Navigator.pop(context); }, ), ), ); }, ), ), Container( padding: EdgeInsets.all(p), child: Text( 'Title', style: ksLabelTextStyle(), ), ), Container( padding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0), child: TextField( onChanged: (value) { titleName = value; }, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter title here', ), style: klLabelTextStyle(), ), ), Container( // padding: EdgeInsets.all(p), child: Text( 'Type', style: ksLabelTextStyle(), ), ), Container( padding: EdgeInsets.all(p), child: TextField( decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Solo/Customized or Random Teams', ), style: klLabelTextStyle(), onChanged: (value) { ktitleType = value; }, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Text( 'Start Date', style: ksLabelTextStyle(), ), Text( 'Due Date', style: ksLabelTextStyle(), ), ], ), Row( children: <Widget>[ Expanded( child: GestureDetector( onTap: () async { final DateTime? picked = await showDatePicker( context: context, initialDate: selectedStartDate, firstDate: DateTime(2015, 8), lastDate: DateTime(2101), ); if (picked != null && picked != selectedStartDate) { setState(() { selectedStartDate = picked; }); } }, child: Container( padding: EdgeInsets.all(p), // Replace 'p' with actual padding child: TextField( controller: dateinputStart, decoration: InputDecoration( icon: Icon(Icons.calendar_today_outlined), border: OutlineInputBorder(), labelText: 'yyyy-MM-dd', ), style: klLabelTextStyle(), onTap: () async { DateTime? pickedDate2 = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2000), lastDate: DateTime(2101), ); if (pickedDate2 != null) { print(pickedDate2); String formattedDate = DateFormat('yyyy-MM-dd').format(pickedDate2); setState(() { selectedStartDate = pickedDate2; dateinputStart.text = formattedDate; startDate = pickedDate2; }); } else { print('Date not selected'); } }, ), ), ), ), Expanded( child: GestureDetector( onTap: () async { final DateTime? picked2 = await showDatePicker( context: context, initialDate: selectedEndDate, firstDate: DateTime(2015, 8), lastDate: DateTime(2101)); if (picked2 != null && picked2 != selectedEndDate) { setState(() { selectedEndDate = picked2; }); } }, child: Container( padding: EdgeInsets.all(p), // Replace 'p' with actual padding child: TextField( controller: dateinputEnd, decoration: InputDecoration( icon: Icon(Icons.calendar_today_outlined), border: OutlineInputBorder(), labelText: 'yyyy-MM-dd', ), style: klLabelTextStyle(), onTap: () async { DateTime? pickedDate3 = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2000), lastDate: DateTime(2101), ); DateTime? pickedDate6 = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2000), lastDate: DateTime(2101), ); if (pickedDate3 != null && pickedDate6 != null) { print(pickedDate3); print(pickedDate6); String formattedDate1 = DateFormat('yyyy-MM-dd').format(pickedDate3); String formattedDate2 = DateFormat('yyyy-MM-dd').format(pickedDate6); setState(() { selectedEndDate = pickedDate3; selectedEndDate = pickedDate6; kDdateArray.add(pickedDate3); kSdateArray.add(pickedDate6); dateinputStart.text = formattedDate2; dateinputEnd.text = formattedDate1; startDate = pickedDate6; endDate = pickedDate3; }); } else { print('Date not selected'); } }, ), ), ), ), ], ), Container( padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 0.0), child: Center( child: Text( 'Priority', style: ksLabelTextStyle(), ), ), ), Center( child: DropdownButton( padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 0.0), value: kvalue, icon: const Icon(Icons.keyboard_arrow_down), items: items.map((String item) { return DropdownMenuItem( value: item, child: Text(item), ); }).toList(), onChanged: (String? value4) { setState(() { kvalue = value4!; }); }, ), ), Row( children: <Widget>[ Expanded( child: Container( padding: EdgeInsets.fromLTRB(8.0, p, 8.0, 0.0), child: TextField( onChanged: (value5) { startTime = value5; }, controller: timeinputStart, decoration: InputDecoration( icon: Icon(Icons.timer), labelText: "Enter Start Time", ), // readOnly: true, onTap: () async { TimeOfDay? pickedTime1 = await showTimePicker( initialTime: TimeOfDay.now(), context: context, ); if (pickedTime1 != null) { String formattedTime = pickedTime1.format(context); setState(() { timeinputStart.text = formattedTime; }); } }, style: klLabelTextStyle()), ), ), Expanded( child: Container( padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 0.0), child: TextField( controller: timeinputEnd, decoration: InputDecoration( icon: Icon(Icons.timer), labelText: "Enter End Time", ), onTap: () async { TimeOfDay? pickedTime2 = await showTimePicker( initialTime: TimeOfDay.now(), context: context, ); if (pickedTime2 != null) { String formattedTime = pickedTime2.format(context); setState(() { timeinputEnd.text = formattedTime; }); } }, style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.normal, color: Colors.black, ), ), ), ), ], ), SizedBox( height: h, child: Padding( padding: EdgeInsets.fromLTRB(8.0, 20.0, 8.0, 0.0), child: TextField( onChanged: (value6) { description = value6; }, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Description', ), maxLines: 5, minLines: 1, style: klLabelTextStyle()), ), ), ], ), ), ); } }
class ScatterPlot { constructor(data) { this.data = data; this.setup(); } setup() { this.data.forEach((d) => { d.x = +d.x; d.y = +d.y; }); const parentDiv = document.getElementById("ScatterPlotContainer"); const parentDivRect = parentDiv.getBoundingClientRect(); this.margin = { top: 20, right: 20, bottom: 30, left: 40 }; this.width = parentDivRect.width - this.margin.left - this.margin.right; this.height = parentDivRect.height - this.margin.top - this.margin.bottom; this.scatterPlot = d3 .select("#ScatterPlotContainer") .append("svg") .attr("width", this.width + this.margin.left + this.margin.right) .attr("height", this.height + this.margin.top + this.margin.bottom) .attr("id", "mds") .append("g") .attr("transform", `translate(${this.margin.left},${this.margin.top})`); this.xExtent = d3.extent(this.data, (d) => d.x); this.yExtent = d3.extent(this.data, (d) => d.y); this.maxExtent = [ Math.min(this.xExtent[0], this.yExtent[0]), Math.max(this.xExtent[1], this.yExtent[1]), ]; this.xScale = d3.scaleLinear().domain(this.maxExtent).range([0, this.width]); this.yScale = d3.scaleLinear().domain(this.maxExtent).range([this.height, 0]); this.tooltip = d3 .select("body") .append("div") .attr("class", "tooltip") .style("opacity", 0) .style("position", "absolute"); this.circles = this.scatterPlot .append("g") .selectAll("circle") .data(this.data) .enter() .append("circle") .attr("cx", (d) => this.xScale(d.x)) .attr("cy", (d) => this.yScale(d.y)) .attr("r", 4) .attr("fill", "red"); this.circles.on("mouseover", (event) => { const xPosition = this.xScale(event.x) + 5 + 7 * this.margin.left; const yPosition = this.yScale(event.y) - 10 + 7 * this.margin.top; this.tooltip .transition() .duration(200) .style("opacity", 0.9) .style("left", xPosition + "px") .style("top", yPosition + "px"); this.tooltip.html(`<strong>${event.label}</strong>`); }); this.circles.on("mouseout", () => { this.tooltip.transition().duration(500).style("opacity", 0); }); this.xAxis = d3.axisBottom(this.xScale); this.yAxis = d3.axisLeft(this.yScale); this.scatterPlot .append("g") .attr("transform", `translate(0, ${this.height})`) .call(this.xAxis); this.scatterPlot.append("g").call(this.yAxis); this.scatterPlot .append("g") .attr("transform", `translate(0, ${this.height})`) .call(this.xAxis); this.scatterPlot.append("g").call(this.yAxis); this.setupBrush(); } setupBrush() { const brush = d3 .brush() .extent([ [-20, -20], [this.width + 20, this.height + 20], ]) .on("brush", this.brushedScatterPlot.bind(this)) .on("end", this.brushedEndScatterPlot.bind(this)); this.scatterPlot.call(brush); } brushedScatterPlot() { const event = d3.event; if (event && event.selection) { const selection = event.selection; // handle brush event } } brushedEndScatterPlot() { const event = d3.event; if (event && event.selection) { const selection = event.selection; const selectedData = this.data.filter( (d) => this.xScale(d.x) >= selection[0][0] && this.xScale(d.x) <= selection[1][0] && this.yScale(d.y) >= selection[0][1] && this.yScale(d.y) <= selection[1][1] ); this.colorScatterPlot(selectedData, "black"); } } colorScatterPlot(selectedData, color) { this.circles.attr("fill", (d) => { return selectedData.length > 0 ? this.isPointInsideSelection(d, selectedData) ? color : "red" : "red"; }); } isPointInsideSelection(point, selection) { for (const i in selection) { if (point.x === selection[i].x && point.y === selection[i].y) { return true; } } return false; } }
/** * @file driver * @author jungkwang.lee ([email protected]) * @brief * * @copyright Copyright (c) 2022 NT Template Library Authoers. * */ #pragma once #ifndef _NTDDK_ #include <wdm.h> #endif #ifndef ClearFlag #define ClearFlag(_F, _SF) ((_F) &= ~(_SF)) #endif #include "device" #include "except" #include "status" #include "unicode_string" #include <algorithm> #include <functional> #include <memory> #include <unordered_map> namespace ntl { namespace detail { namespace driver { inline ntl::exception make_exception(NTSTATUS status) { const char *message; switch (status) { case STATUS_INSUFFICIENT_RESOURCES: message = " Insufficient system resources exist to complete the API."; break; case STATUS_OBJECT_NAME_COLLISION: message = "Object Name already exists."; break; default: message = "Unknown error."; break; } return ntl::exception(status, message); } } // namespace driver } // namespace detail class driver { friend class driver_initializer; friend class driver_unload_invoker; friend class device_dispatch_invoker; private: driver(PDRIVER_OBJECT driver) : object_(driver), name_(driver->DriverName.Buffer, driver->DriverName.Length / sizeof(WCHAR)) {} public: using unload_routine = std::function<void()>; template <typename Extension> std::shared_ptr<device<Extension>> create_device(device_options &opts) { PDEVICE_OBJECT dev = NULL; status s = [&dev, &opts, this]() { ULONG extension_size = (ULONG)sizeof(detail::device::extension_data_t<Extension>); if (opts.name_.empty()) { return IoCreateDevice(object_, extension_size, NULL, opts.type_, 0, opts.exclusive_, &dev); } else { unicode_string dev_name(L"\\Device\\" + opts.name_); return IoCreateDevice(object_, extension_size, &*dev_name, opts.type_, 0, opts.exclusive_, &dev); } }(); if (s.is_err()) throw detail::driver::make_exception(s); new (dev->DeviceExtension) detail::device::extension_data_t<Extension>(); auto ptr = std::make_shared<device<Extension>>(device<Extension>(dev, opts)); dispatchers_.insert({dev, &ptr->dispatchers()}); ClearFlag(dev->Flags, DO_DEVICE_INITIALIZING); return ptr; } void on_unload(unload_routine &&f) { unload_routine_ = f; } const std::wstring &name() const { return name_; } protected: detail::device::dispatchers_t *dispatchers(PDEVICE_OBJECT ptr) noexcept { try { return dispatchers_[ptr]; } catch (...) { return nullptr; } } private: PDRIVER_OBJECT object_; std::wstring name_; std::unordered_map<PDEVICE_OBJECT, detail::device::dispatchers_t *> dispatchers_; unload_routine unload_routine_; }; #if _X86_ // warning C4007: 'main' : must be '__cdecl' #pragma warning(disable : 4007) #endif status main(driver &driver, const std::wstring &registry_path); } // namespace ntl
# The Array#zip method takes two arrays, # and combines them into a single array in which each element is a two-element array where the first element is a value from one array, # and the second element is a value from the second array, in order. # For example: [1, 2, 3].zip([4, 5, 6]) == [[1, 4], [2, 5], [3, 6]] # Write your own version of zip that does the same type of operation. # It should take two Arrays as arguments, # and return a new Array (the original Arrays should not be changed). # Do not use the built-in Array#zip method. You may assume that both input arrays have the same number of elements. # Example: def zip(arr1, arr2) arr1.map.with_index{ |el, idx| [el, arr2[idx]] } end p zip([1, 2, 3], [4, 5, 6]) == [[1, 4], [2, 5], [3, 6]]
"use client"; import React, { useState, useRef, useEffect } from "react"; import { Toolbar } from "primereact/toolbar"; import { Button } from "primereact/button"; import { Dialog } from "primereact/dialog"; import { Toast } from "primereact/toast"; import { suspendOutdatedMembers } from "@components/Members/member"; import NewMemberForm from "@components/Members/NewMemberForm"; import MembersList from "@components/Members/MembersList"; import Form1 from "@components/form/Form1"; const Members = () => { const [suspendDialog, setSuspendDialog] = useState(false); const [newDialog, setNewDialog] = useState(false); const [reloadKey, setReloadKey] = useState(0); const [loading, setLoading] = useState(false); const [user_id, setUser_id] = useState(""); function handleReload() { setReloadKey((prevKey) => prevKey + 1); } const toast = useRef(null); useEffect(() => { setUser_id(localStorage.clubUser && JSON.parse(localStorage.clubUser).id); }, []); async function suspend() { setLoading(true); const count = await suspendOutdatedMembers(); setLoading(false); toggleConfirmSuspendDialog(); handleReload(); toast.current.show({ severity: "success", summary: "تم", detail: `${count} عضو تم إنهاء عضويتهم`, life: 3000, }); } const toggleConfirmSuspendDialog = () => { setSuspendDialog(!suspendDialog); }; const toggleNewDialog = () => { setNewDialog(!newDialog); }; const leftToolbarTemplate = () => { return ( <div className="flex flex-wrap gap-2"> <Button label="إضافة عضو جديد" iconPos="right" icon="pi pi-plus" onClick={toggleNewDialog} /> <Button label="تعليق العضويات المنتهية" icon="pi pi-ban" iconPos="right" onClick={toggleConfirmSuspendDialog} /> </div> ); }; const rightToolbarTemplate = () => { return ( <> <h1 className="label_club">قائمة الاعضاء</h1> </> ); }; const suspendDialogFooter = ( <div style={{ textAlign: "left" }}> <Button label="نعم" icon="pi pi-check" iconPos="right" loading={loading} onClick={async () => { await suspend(); }} /> <Button label="لا" icon="pi pi-times" iconPos="right" onClick={toggleConfirmSuspendDialog} /> </div> ); return ( <> <Toast ref={toast} dir="rtl" /> <Toolbar left={leftToolbarTemplate} right={rightToolbarTemplate} ></Toolbar> <MembersList key={reloadKey} /> {user_id && ( <NewMemberForm toggleNewDialog={toggleNewDialog} handleReload={handleReload} newDialog={newDialog} values={{ user_id }} title="إضافة عضو جديد" method="create" /> )} <Dialog visible={suspendDialog} style={{ width: "32rem" }} breakpoints={{ "960px": "75vw", "641px": "90vw" }} header="إنتبه !" headerStyle={{ direction: "rtl" }} rtl={true} contentStyle={{ direction: "rtl" }} modal footer={suspendDialogFooter} onHide={toggleConfirmSuspendDialog} > <div className="confirmation-content"> <i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: "2rem" }} /> <span>هل تريد إيقاف العضويات المنتهية ؟</span> </div> </Dialog> </> ); }; export default Members;
import React, { useContext } from 'react'; import PropTypes from 'prop-types'; import { getFoodFilter, getMealName } from '../../../services/API'; import MyContext from '../../../Context'; export default function Button({ strCategory }) { const { setFood, nome, setNome } = useContext(MyContext); const handleClick = async ({ target: { name } }) => { if (nome !== strCategory) { const data = await getFoodFilter(name); setFood(data.meals); setNome(strCategory); } else { const data = await getMealName(''); setFood(data.meals); setNome(''); } }; return ( <button type="button" key={ strCategory } name={ strCategory } data-testid={ `${strCategory}-category-filter` } onClick={ handleClick } > { strCategory } </button> ); } Button.propTypes = { strCategory: PropTypes.string.isRequired, };
import m3l from dataclasses import dataclass import csdl import numpy as np @dataclass class DampingRatios: damping_long_11 : m3l.Variable damping_long_12 : m3l.Variable damping_long_21 : m3l.Variable damping_long_22 : m3l.Variable damping_lat_11 : m3l.Variable damping_lat_12 : m3l.Variable damping_lat_21 : m3l.Variable damping_lat_22 : m3l.Variable class LinearStabilityAnalysis(m3l.ImplicitOperation): def initialize(self, kwargs): self.parameters.declare('name', types=str, default='linear_stability_model') def assign_attributes(self): self.name = self.parameters['name'] def evaluate(self, A_long, lhs_long, long_stab_state_vec, A_lat, lhs_lat, lat_stab_state_vec, long_accelerations=None, lat_accelerations=None) -> DampingRatios: self.inputs = {} self.arguments = {} self.arguments['A_long'] = A_long self.arguments['A_lat'] = A_lat # self.arguments['lhs_long'] = lhs_long # self.arguments['long_stab_state_vec'] = long_stab_state_vec # if A_lat: # self.arguments['A_lat'] = A_lat # self.arguments['lhs_lat'] = lhs_lat # self.arguments['lat_stab_state_vec'] = lat_stab_state_vec self.inputs['A_long'] = A_long self.inputs['A_lat'] = A_lat # self.inputs['lhs_long'] = lhs_long # self.inputs['long_stab_state_vec'] = long_stab_state_vec # if A_lat: # self.inputs['A_lat'] = A_lat # self.inputs['lhs_lat'] = lhs_lat # self.inputs['lat_stab_state_vec'] = lat_stab_state_vec self.outputs = {} if long_accelerations: self.outputs['long_accelerations'] = long_accelerations if lat_accelerations: self.outputs['lat_accelerations'] = lat_accelerations self.residual_partials = {} self.residual_partials['long_accelerations_jacobian'] = long_accelerations self.residual_partials['lat_accelerations_jacobian'] = long_accelerations self.size = 4 long_residual = m3l.Variable(name='long_stab_residual', shape=(4, ), operation=self) lat_residual = m3l.Variable(name='lat_stab_residual', shape=(4, ), operation=self) return long_residual, lat_residual def compute_residual(self): csdl_model = LinearStabilityCSDL(linear_stability_analysis=self) return csdl_model def compute_derivatives(self): csdl_model = LinearStabilityDerivativeCSDL() return csdl_model class LinearStabilityCSDL(csdl.Model): def define(self): lhs_long = self.declare_variable('lhs_long', shape=(4, )) A_long = self.declare_variable('A_long', shape=(4, 4)) long_stab_state_vec = self.declare_variable('long_stab_state_vec', shape=(4, )) lhs_lat = self.declare_variable('lhs_lat', shape=(4, )) A_lat = self.declare_variable('A_lat', shape=(4, 4)) lat_stab_state_vec = self.declare_variable('lat_stab_state_vec', shape=(4, )) long_stab_residual = csdl.matvec(A_long, long_stab_state_vec) - lhs_long self.register_output('long_stab_residual', long_stab_residual) lat_stab_residual = csdl.matvec(A_lat, lat_stab_state_vec) - lhs_lat self.register_output('lat_stab_residual', lat_stab_residual) class LinearStabilityDerivativeCSDL(csdl.Model): def define(self): A_long = self.declare_variable('A_long', shape=(4, 4)) A_lat = self.declare_variable('A_lat', shape=(4, 4)) self.register_output('long_accelerations_jacobian', A_long*1) self.register_output('lat_accelerations_jacobian', A_lat*1) @dataclass class LongitudinalStability: short_period_real : m3l.Variable = None, short_period_imag : m3l.Variable = None, short_period_natural_frequency : m3l.Variable = None, short_period_damping_ratio : m3l.Variable = None, short_period_time_to_double : m3l.Variable = None, phugoid_real : m3l.Variable = None, phugoid_imag : m3l.Variable = None, phugoid_natural_frequency : m3l.Variable = None, phugoid_damping_ratio : m3l.Variable = None, phugoid_time_to_double : m3l.Variable = None, @dataclass class LateralStability: dutch_roll_real : m3l.Variable = None dutch_roll_imag : m3l.Variable = None dutch_roll_natural_frequency : m3l.Variable = None dutch_roll_damping_ratio : m3l.Variable = None dutch_roll_time_to_double : m3l.Variable = None roll_real : m3l.Variable = None roll_imag : m3l.Variable = None roll_natural_frequency : m3l.Variable = None roll_damping_ratio : m3l.Variable = None roll_time_to_double : m3l.Variable = None spiral_real : m3l.Variable = None spiral_imag : m3l.Variable = None spiral_natural_frequency : m3l.Variable = None spiral_damping_ratio : m3l.Variable = None spiral_time_to_double : m3l.Variable = None class LongitudinalAircraftStability(m3l.ExplicitOperation): def initialize(self, kwargs): self.parameters.declare('name', types=str, default='longitudinal_stability') self.parameters.declare('connect_from', types=list, default=[]) self.parameters.declare('connect_to', types=list, default=[]) self.parameters.declare('design_condition_name', types=str) def assign_attributes(self): self.dc_name = self.parameters['design_condition_name'] self.name = f"{self.dc_name}_{self.parameters['name']}" def compute(self): self.parameters['connect_from'] = [ f"{self.dc_name}_linear_stability_model_long_accelerations_jacobian_eig.e_real", f"{self.dc_name}_linear_stability_model_long_accelerations_jacobian_eig.e_imag", ] self.parameters['connect_to'] = [ f"{self.name}.e_real_long", f"{self.name}.e_imag_long", ] csdl_model = LongitudinalAircraftStabilityCSDL( size=4, ) return csdl_model def evaluate(self) -> LongitudinalStability: self.arguments = {} short_period_real = m3l.Variable(name='short_period_real', shape=(1, ), operation=self) short_period_imag = m3l.Variable(name='short_period_imag', shape=(1, ), operation=self) short_period_natural_frequency = m3l.Variable(name='short_period_natural_frequency', shape=(1, ), operation=self) short_period_damping_ratio = m3l.Variable(name='short_period_damping_ratio', shape=(1, ), operation=self) short_period_time_to_double = m3l.Variable(name='short_period_time_to_double', shape=(1, ), operation=self) phugoid_real = m3l.Variable(name='phugoid_real', shape=(1, ), operation=self) phugoid_imag = m3l.Variable(name='phugoid_imag', shape=(1, ), operation=self) phugoid_natural_frequency = m3l.Variable(name='phugoid_natural_frequency', shape=(1, ), operation=self) phugoid_damping_ratio = m3l.Variable(name='phugoid_damping_ratio', shape=(1, ), operation=self) phugoid_time_to_double = m3l.Variable(name='phugoid_time_to_double', shape=(1, ), operation=self) long_stab = LongitudinalStability( short_period_real=short_period_real, short_period_imag=short_period_imag, short_period_natural_frequency=short_period_natural_frequency, short_period_damping_ratio=short_period_damping_ratio, short_period_time_to_double=short_period_time_to_double, phugoid_real=phugoid_real, phugoid_imag=phugoid_imag, phugoid_natural_frequency=phugoid_natural_frequency, phugoid_damping_ratio=phugoid_damping_ratio, phugoid_time_to_double=phugoid_time_to_double, ) return long_stab class LateralAircraftStability(m3l.ExplicitOperation): def initialize(self, kwargs): self.parameters.declare('name', types=str, default='lateral_stability') self.parameters.declare('connect_from', types=list, default=[]) self.parameters.declare('connect_to', types=list, default=[]) self.parameters.declare('design_condition_name', types=str) def assign_attributes(self): self.dc_name = self.parameters['design_condition_name'] self.name = f"{self.dc_name}_{self.parameters['name']}" def compute(self): self.parameters['connect_from'] = [ f"{self.dc_name}_linear_stability_model_lat_accelerations_jacobian_eig.e_real", f"{self.dc_name}_linear_stability_model_lat_accelerations_jacobian_eig.e_imag", ] self.parameters['connect_to'] = [ f"{self.name}.e_real_lat", f"{self.name}.e_imag_lat", ] csdl_model = LateralAircraftStabilityCSDL( size=4, ) return csdl_model def evaluate(self) -> LateralStability: self.arguments = {} dutch_roll_real = m3l.Variable(name='dutch_roll_real', shape=(1, ), operation=self) dutch_roll_imag = m3l.Variable(name='dutch_roll_imag', shape=(1, ), operation=self) dutch_roll_natural_frequency = m3l.Variable(name='dutch_roll_natural_frequency', shape=(1, ), operation=self) dutch_roll_damping_ratio = m3l.Variable(name='dutch_roll_damping_ratio', shape=(1, ), operation=self) dutch_roll_time_to_double = m3l.Variable(name='dutch_roll_time_to_double', shape=(1, ), operation=self) roll_real = m3l.Variable(name='roll_real', shape=(1, ), operation=self) roll_imag = m3l.Variable(name='roll_imag', shape=(1, ), operation=self) roll_natural_frequency = m3l.Variable(name='roll_natural_frequency', shape=(1, ), operation=self) roll_damping_ratio = m3l.Variable(name='roll_damping_ratio', shape=(1, ), operation=self) roll_time_to_double = m3l.Variable(name='roll_time_to_double', shape=(1, ), operation=self) spiral_real = m3l.Variable(name='spiral_real', shape=(1, ), operation=self) spiral_imag = m3l.Variable(name='spiral_imag', shape=(1, ), operation=self) spiral_natural_frequency = m3l.Variable(name='spiral_natural_frequency', shape=(1, ), operation=self) spiral_damping_ratio = m3l.Variable(name='spiral_damping_ratio', shape=(1, ), operation=self) spiral_time_to_double = m3l.Variable(name='spiral_time_to_double', shape=(1, ), operation=self) lat_stab = LateralStability( dutch_roll_real=dutch_roll_real, dutch_roll_imag=dutch_roll_imag, dutch_roll_natural_frequency=dutch_roll_natural_frequency, dutch_roll_damping_ratio=dutch_roll_damping_ratio, dutch_roll_time_to_double=dutch_roll_time_to_double, roll_real=roll_real, roll_imag=roll_imag, roll_natural_frequency=roll_natural_frequency, roll_damping_ratio=roll_damping_ratio, roll_time_to_double=roll_time_to_double, spiral_real=spiral_real, spiral_imag=spiral_imag, spiral_natural_frequency=spiral_natural_frequency, spiral_damping_ratio=spiral_damping_ratio, spiral_time_to_double=spiral_time_to_double, ) return lat_stab class LongitudinalAircraftStabilityCSDL(csdl.Model): def initialize(self): self.parameters.declare('size') def define(self): size = self.parameters['size'] e_real = self.declare_variable('e_real_long', shape=(1,size)) e_imag = self.declare_variable('e_imag_long', shape=(1,size)) # short period eigenvalue pair sp_e_real = e_real[0,0] sp_e_imag = e_imag[0,0] self.register_output('short_period_real', sp_e_real) self.register_output('short_period_imag', sp_e_imag) # get phugoid eigenvalue pair ph_e_real = e_real[0,2] ph_e_imag = e_imag[0,2] self.register_output('phugoid_real', ph_e_real) self.register_output('phugoid_imag', ph_e_imag) # compute short period natural frequency sp_wn = (sp_e_real**2 + sp_e_imag**2)**0.5 self.register_output('short_period_natural_frequency', sp_wn) # compute phugoid natural frequency ph_wn = (ph_e_real**2 + ph_e_imag**2)**0.5 self.register_output('phugoid_natural_frequency', ph_wn) # compute short period damping ratio sp_z = -1*sp_e_real/sp_wn self.register_output('short_period_damping_ratio', sp_z) # compute phugoid damping ratio ph_z = -1*ph_e_real/ph_wn self.register_output('phugoid_damping_ratio', ph_z) # compute short period time to double sp_z_abs = (sp_z**2)**0.5 sp_t2 = np.log(2)/(sp_z_abs*sp_wn) self.register_output('short_period_time_to_double', sp_t2) # compute phugoid time to double ph_z_abs = (ph_z**2)**0.5 ph_t2 = np.log(2)/(ph_z_abs*ph_wn) self.register_output('phugoid_time_to_double', ph_t2) class LateralAircraftStabilityCSDL(csdl.Model): def initialize(self): self.parameters.declare('size') def define(self): size = self.parameters['size'] e_real = self.declare_variable('e_real_lat', shape=(1,size)) e_imag = self.declare_variable('e_imag_lat', shape=(1,size)) # order: dr, dr, rr, ss # get dutch roll eigenvalue pair dr_e_real = e_real[0,2] dr_e_imag = e_imag[0,2] self.register_output('dutch_roll_real', dr_e_real) self.register_output('dutch_roll_imag', dr_e_imag) # get roll eigenvalue pair rr_e_real = e_real[0,0] rr_e_imag = e_imag[0,0] self.register_output('roll_real', rr_e_real) self.register_output('roll_imag', rr_e_imag) # get spiral eigenvalue pair ss_e_real = e_real[0,3] ss_e_imag = e_imag[0,3] self.register_output('spiral_real', ss_e_real) self.register_output('spiral_imag', ss_e_imag) # compute dutch roll natural frequency dr_wn = (dr_e_real**2 + dr_e_imag**2)**0.5 self.register_output('dutch_roll_natural_frequency', dr_wn) # compute roll natural frequency rr_wn = (rr_e_real**2 + rr_e_imag**2)**0.5 self.register_output('roll_natural_frequency', rr_wn) # compute spiral natural frequency ss_wn = (ss_e_real**2 + ss_e_imag**2)**0.5 self.register_output('spiral_natural_frequency', ss_wn) # compute dutch roll damping ratio dr_z = -1*dr_e_real/dr_wn self.register_output('dutch_roll_damping_ratio', dr_z) # compute roll damping ratio rr_z = -1*rr_e_real/rr_wn self.register_output('roll_damping_ratio', rr_z) # compute spiral damping ratio ss_z = -1*ss_e_real/ss_wn self.register_output('spiral_damping_ratio', ss_z) # compute dutch roll time to double dr_z_abs = (dr_z**2)**0.5 dr_t2 = np.log(2)/(dr_z_abs*dr_wn) self.register_output('dutch_roll_time_to_double', dr_t2) # compute roll time to double rr_z_abs = (rr_z**2)**0.5 rr_t2 = np.log(2)/(rr_z_abs*rr_wn) self.register_output('roll_time_to_double', rr_t2) # compute spiral time to double ss_z_abs = (ss_z**2)**0.5 ss_t2 = np.log(2)/(ss_z_abs*ss_wn) self.register_output('spiral_time_to_double', ss_t2)
package com.justwayward.renren.ui.adapter; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.text.TextUtils; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.justwayward.renren.R; import com.justwayward.renren.bean.CategoryListBean; import com.justwayward.renren.bean.FreeListBean; import java.util.List; /** * Created by gaoyuan on 2018/3/3. */ public class FreeListAdapter extends BaseQuickAdapter<FreeListBean.DataBean, BaseViewHolder> { public FreeListAdapter(@LayoutRes int layoutResId, @Nullable List<FreeListBean.DataBean> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, FreeListBean.DataBean item) { ImageView imgCover = helper.getView(R.id.ivSubCateCover); Glide.with(mContext).load(item.getPic()).error(R.drawable.cover_default).into(imgCover); String percent = "0"; if (item.getCollect_num() != 0 && item.getView_num() != 0) { double d = (item.getCollect_num() * 100 / item.getView_num()); percent = String.format("%.0f", d); } helper.setText(R.id.tvSubCateTitle, item.getTitle()) .setText(R.id.tvSubCateAuthor, (item.getAuthor() == null ? "未知" : item.getAuthor()) + " | " + (TextUtils.isEmpty(item.getLabels()) ? "未知" : item.getCategory_name())) .setText(R.id.tvSubCateShort, item.getDesc() .replaceAll("<p>", "") .replaceAll("<br/>", "") .replaceAll("</p>", "")) .setText(R.id.tvSubCateMsg, String.format(mContext.getResources().getString(R.string.category_book_msg), item.getCollect_num(), TextUtils.isEmpty(item.getCollect_num() + "") ? "0" : percent)); } }
const express = require("express"); const app = express(); const http = require("http"); const { Server } = require("socket.io"); const ACTIONS = require("./action"); const server = http.createServer(app); const io = new Server(server); const userScoketMap = {}; function getAllClients(roomId) { return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map( (socketId) => { return { socketId, userName: userScoketMap[socketId], }; } ); } io.on("connection", (socket) => { socket.on(ACTIONS.JOIN, ({ roomId, userName }) => { socket.join(roomId); userScoketMap[socket.id] = userName; const allClients = getAllClients(roomId); allClients.forEach(({ socketId }) => { io.to(socketId).emit(ACTIONS.JOINED, { allClients, userName, socketId: socket.id, }); }); }); socket.on(ACTIONS.SYNC_CODE, ({ code, socketId }) => { io.to(socketId).emit(ACTIONS.CODE_CHANGE, { code }); }); socket.on(ACTIONS.CODE_CHANGE, ({ roomId, code }) => { socket.in(roomId).emit(ACTIONS.CODE_CHANGE, { code }); }); socket.on("disconnecting", () => { const rooms = [...socket.rooms]; rooms.forEach((roomId) => { socket.in(roomId).emit(ACTIONS.DISCONNECTED, { socketId: socket.id, userName: userScoketMap[socket.id], }); }); delete userScoketMap[socket.id]; socket.leave(); }); }); const PORT = process.env.PORT || 5000; server.listen(PORT, () => console.log(`Listening on port ${PORT}`));
<?php namespace Magpie\Queues\Providers; use Exception; use Magpie\Commands\CommandRegistry; use Magpie\Exceptions\ClassNotOfTypeException; use Magpie\Exceptions\NotOfTypeException; use Magpie\Exceptions\SafetyCommonException; use Magpie\General\Factories\ClassFactory; use Magpie\Queues\QueueConfig; use Magpie\System\Concepts\DefaultProviderRegistrable; use Magpie\System\Concepts\SystemBootable; use Magpie\System\Kernel\BootContext; use Magpie\System\Kernel\Kernel; /** * Queue creator */ abstract class QueueCreator implements DefaultProviderRegistrable, SystemBootable { /** * Get queue with given name * @param string|null $name * @return Queue */ public abstract function getQueue(?string $name) : Queue; /** * @inheritDoc */ public final function registerAsDefaultProvider() : void { Kernel::current()->registerProvider(self::class, $this); } /** * Create from configuration * @param QueueConfig $config * @return static * @throws Exception */ public static function fromConfig(QueueConfig $config) : static { $typeClassName = ClassFactory::resolve($config->getTypeClass(), self::class); if (!is_subclass_of($typeClassName, self::class)) throw new ClassNotOfTypeException($typeClassName, self::class); return $typeClassName::specificFromConfig($config); } /** * Create from configuration for specific type of implementation * @param QueueConfig $config * @return static * @throws Exception */ protected static abstract function specificFromConfig(QueueConfig $config) : static; /** * Get current instance * @return static * @throws SafetyCommonException */ public static function instance() : static { /** @var static|null $instance */ $instance = Kernel::current()->getProvider(self::class); if (!$instance instanceof self) throw new NotOfTypeException($instance, self::class); return $instance; } /** * @inheritDoc */ public static final function systemBoot(BootContext $context) : void { CommandRegistry::includeDirectory(__DIR__ . '/../Commands'); static::onSystemBoot($context); } /** * Specific system boot-up * @param BootContext $context Boot up context * @return void * @throws Exception */ protected static abstract function onSystemBoot(BootContext $context) : void; }
using AutoMapper; using Avancerad.NET_Projekt.Services; using Avancerad.NET_Projekt_ClassLibrary.Models; using Avancerad.NET_Projekt.Methods; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Text; using System.Numerics; namespace Avancerad.NET_Projekt.Controllers { [Route("api/[controller]")] [ApiController] public class CustomerController : ControllerBase { private readonly UserManager<IdentityUser> _userManager; private readonly ICustomerRepo _customerRepo; private readonly IMapper _mapper; public CustomerController(ICustomerRepo customerRepo, IMapper mapper, UserManager<IdentityUser> userManager) { _customerRepo = customerRepo; _mapper = mapper; _userManager = userManager; } [HttpGet, Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "AdminCompanyPolicy")] public async Task<ActionResult<IEnumerable<CustomerDTO>>> GetAllCustomers() { try { var customers = await _customerRepo.GetAllAsync(); var customerDTO = _mapper.Map<IEnumerable<CustomerDTO>>(customers); return Ok(customerDTO); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error to retrive data from database.."); } } [HttpGet("sort-or-filter"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "AdminCompanyPolicy")] public async Task<ActionResult<IEnumerable<CustomerDTO>>> GetAllCustomersQuery(string sortBy = null, string filterBy = null) { try { var customers = await _customerRepo.GetAllAsync(); // Filtrera kunder baserat på filterBy if (!string.IsNullOrEmpty(filterBy)) { customers = customers.Where(c => c.FirstName.ToLower().Contains(filterBy.ToLower())); } // Sortera kunder baserat på sortBy if (!string.IsNullOrEmpty(sortBy)) { switch (sortBy.ToLower()) { case "firstname": customers = customers.OrderBy(c => c.FirstName); break; case "lastname": customers = customers.OrderBy(c => c.LastName); break; // Lägg till fler sorteringsalternativ här default: break; } } var customerDTOs = _mapper.Map<IEnumerable<CustomerDTO>>(customers); return Ok(customerDTOs); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Fel vid hämtning av data från databasen.."); } } [HttpGet("appointments/{id:int}"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "AdminCompanyPolicy")] public async Task<ActionResult<object>> GetCustomerAppointments(int id) { try { var customer = await _customerRepo.GetCustomerWithAppointments(id); if (customer == null) { return NotFound($"Customer with ID {id} does not exist."); } // Filter out appointments where IsDeleted is false var appointments = customer.Appointments/*.Where(a => !a.IsDeleted)*/.ToList(); var customerDTO = _mapper.Map<CustomerDTO>(customer); var appointmentsDTO = _mapper.Map<List<AppointmentDTO>>(appointments); // Create an anonymous object containing customer info and appointments var response = new { Customer = customerDTO, Appointments = appointmentsDTO }; return Ok(response); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database."); } } [HttpGet("{id:int}"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "AdminCompanyPolicy")] public async Task<ActionResult<CustomerDTO>> GetCustomer(int id) { try { var customer = await _customerRepo.GetByIdAsync(id); if (customer == null) { return NotFound($"Customer with ID {id} does not exist."); } var customerDTO = _mapper.Map<CustomerDTO>(customer); return Ok(customerDTO); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from database."); } } [HttpPost] [Route("account/create/customer")] public async Task<IActionResult> CreateCompany(string email, string password, string firstName, string lastName, string phone) { IdentityUser User = await _userManager.FindByEmailAsync(email); if (User != null) return BadRequest(false); IdentityUser user = new() { UserName = email, PasswordHash = password, Email = email, }; IdentityResult result = await _userManager.CreateAsync(user, password); if (!result.Succeeded) return BadRequest(false); Claim[] userClaims = [ new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Role, "company") ]; await _userManager.AddClaimsAsync(user, userClaims); var customer = new Customer { IdentityUser = user, FirstName = firstName, LastName = lastName, Phone = phone, Email = email, }; await _customerRepo.CreateAsync(customer); return Ok(true); } [HttpDelete("{id:int}"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "AdminCompanyCustomerPolicy")] public async Task<ActionResult<CustomerDTO>> DeleteCustomer(int id, [FromServices] UserManager<IdentityUser> userManager) { try { // Fetch the customer to delete var customerToDelete = await _customerRepo.GetByIdAsync(id); // Check if the customer exists if (customerToDelete == null) { return NotFound($"Customer with ID {id} does not exist and therefore cannot be deleted."); } var email = User.FindFirstValue(ClaimTypes.Email); var loggedInUser = await userManager.FindByEmailAsync(email); // Check if the logged-in user exists if (loggedInUser == null) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving the logged-in user."); } // Check if the logged-in user is trying to delete their own account or if they have the admin or company role if (loggedInUser.Id != customerToDelete.IdentityUserId && User != null && (!User.IsInRole("admin") && !User.IsInRole("company"))) { return Forbid(); } // Map the customer to CustomerDTO var customerDTOToReturn = _mapper.Map<CustomerDTO>(customerToDelete); // Perform the deletion await _customerRepo.DeleteAsync(id); // Delete the associated IdentityUser var identityUserToDelete = await userManager.FindByIdAsync(customerToDelete.IdentityUserId); if (identityUserToDelete != null) { var identityResult = await userManager.DeleteAsync(identityUserToDelete); if (!identityResult.Succeeded) { return StatusCode(StatusCodes.Status500InternalServerError, "Error deleting associated IdentityUser from the database."); } } // Return the CustomerDTO with a status code of OK (HTTP 200) return Ok(customerDTOToReturn); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, $"Error deleting data from the database. {ex.Message}"); } } [HttpPut("{id:int}"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "AdminCompanyCustomerPolicy")] public async Task<ActionResult> UpdateCustomer(int id, CustomerUpdateDTO customerDTO, [FromServices] UserManager<IdentityUser> userManager) { try { // Check if CustomerDTO is provided if (customerDTO == null) { return BadRequest(); } // Get the existing customer to update var existingCustomer = await _customerRepo.GetByIdAsync(id); if (existingCustomer == null) { return NotFound($"Customer with ID {id} does not exist."); } var email = User.FindFirstValue(ClaimTypes.Email); var loggedInUser = await userManager.FindByEmailAsync(email); // Check if the logged-in user exists if (loggedInUser == null) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving the logged-in user."); } // Check if the logged-in user is trying to update their own account or if they have the admin or company role if (loggedInUser.Id != existingCustomer.IdentityUserId && User != null && (!User.IsInRole("admin") && !User.IsInRole("company"))) { return Forbid(); } // Map the CustomerDTO to Customer and set the ID var updatedCustomer = _mapper.Map<Customer>(customerDTO); updatedCustomer.CustomerID = id; // Perform the update using the service await _customerRepo.UpdateAsync(updatedCustomer); return NoContent(); // Return 204 No Content after successful update } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, $"Error updating data in the database. {ex.Message}"); } } [HttpGet("customers/{customerId:int}/appointments/week/{year:int}/{weekNumber:int}"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "AdminCompanyPolicy")] public async Task<ActionResult<int>> GetCustomerAppointmentsInWeek(int customerId, int year, int weekNumber) { try { // Retrieve the count of appointments for the specified customer within the specified week int appointmentsCount = await _customerRepo.GetCustomerAppointmentsWeek(customerId, year, weekNumber); return Ok(appointmentsCount); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving customer appointments for week."); } } } }
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## ## --- A comparison of machine learning and statistical species distribution models: --- ## -- when overfitting hurts interpretation -- ## ## --- February 2023 --- ## ## --- Emma Chollet, Andreas Scheidegger, Jonas Wydler and Nele Schuwirth --- ## ## --- [email protected] --- ## ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # PRELIMINARIES #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ getwd() # show working directory, ! set working directory to source file ('main.r') location rm(list=ls()) # free workspace graphics.off() # clean graphics display ## Main options #### BDM <- F # select dataset, "All" or only "BDM" monitoring programs file.prefix <- ifelse(BDM, "BDM_", "All_") CV <- F # train for cross-validation (CV) ODG <- ifelse(CV, F, # if CV = T, no out-of-domain generalization (ODG) F # train for out-of-domain generalization (ODG), set to T for ODG ) # if CV = F and ODG = F, train on whole dataset (FIT) ODG.info <- c(training.ratio = 0.8, # ratio of data used for calibration in ODG variable = "temperature", # factor by which data is split for ODG, can be "random", "temperature", "IAR", etc model = "lme.area.elev") # if variable = 'temperature', choose by which one to split, can be "lme.area.elev", "lm.area.elev", etc train.info <- ifelse(CV, "CV_", ifelse(ODG, paste0(paste(c("ODG_", ODG.info["training.ratio"], ODG.info["variable"]), collapse = ""), "_"), "FIT_")) dl <- F # allow "data leakage" in standardization between training and testing set, if F standardization is done before splitting, else after splitting if(!CV){ dl <- F } # if it's only fitting, no dataleakage models.analysis <- c( # comparison analysis of different models structures: "rf.hyperparam" = F, # RF regularization "ann.hyperparam" = F, # ANN hyperparameter tuning "rf.random" = F, # sensitivity analysis RF randomness "ann.random" = F, # sensitivity analysis ANN randomness "ice.random" = F # analyze random choice of observ. for ICE plots ) case.compar <- c( # comparison analysis of models trained on different datasets: "cv.odg" = ifelse(!CV & !ODG, F, T), # CV vs ODG "dl" = F, # data leakage (dl) vs no data leakage (in data standardization) "temp.model" = F # different temperature models ) server <- F # run the script on the server (changes number of cores) plot.all.ICE <- F # produce ICE/PDP plots for paper ## Libraries #### # Set a checkpoint to use same library versions, which makes the code repeatable over time if ( !require("checkpoint") ) { install.packages("checkpoint"); library("checkpoint") } checkpoint("2022-01-01", r_version = "4.1.1") # replace with desired date and R version if ( !require("parallel") ) { install.packages("parallel"); library("parallel") } # to run things in parallel # Data management if ( !require("dplyr") ) { install.packages("dplyr"); library("dplyr") } # to sort, join, merge data if ( !require("tidyr") ) { install.packages("tidyr"); library("tidyr") } # to sort, join, merge data if ( !require("splitTools") ) { install.packages("splitTools"); library("splitTools") } # to split the data if ( !require("vtable") ) { install.packages("vtable"); library("vtable") } # to make table with summary statistics if ( !require("pROC") ) { install.packages("pROC"); library("pROC") } # to compute AUC # Plots if ( !require("ggplot2") ) { install.packages("ggplot2"); library("ggplot2") } # to do nice plots if ( !require("gridExtra") ) { install.packages("gridExtra"); library("gridExtra") } # to arrange multiple plots on a page if ( !require("plot.matrix") ) { install.packages("plot.matrix"); library("plot.matrix") } # to plot nice tables if ( !require("scales") ) { install.packages("scales"); library("scales") } # to look at colors if ( !require("reshape2") ) { install.packages("reshape2"); library("reshape2") } # to reshape dataframes if ( !require("DiagrammeR")) { install.packages("DiagrammeR"); library("DiagrammeR") } # to plot trees of BCT if ( !require("skimr") ) { install.packages("skimr"); library("skimr") } # to show key descriptive stats if ( !require("corrplot") ) { install.packages("corrplot"); library("corrplot") } # to plot correlation matrix if ( !require("gt") ) { install.packages("gt"); library("gt") } # to make tables if ( !require("sf") ) { install.packages("sf"); library("sf") } # to read layers for plotting maps if ( !require("ggpubr") ) { install.packages("ggpubr"); library("ggpubr") } # to arrange multiple plots on a page if ( !require("svglite") ) { install.packages("svglite"); library("svglite") } # to produce vector images # Statistical models if ( !require("rstan") ) { install.packages("rstan"); library("rstan") } # to run hierarchical models written in Stan # Artificial Neural Networks (ANN) if ( !require("reticulate") ) { install.packages("reticulate"); library("reticulate") } # install_miniconda() # run this the very first time reticulate is installed # install.packages("tensorflow") # installation of tensorflow and keras may make problems library("tensorflow") # depending on R version # install_tensorflow() # run this line only when opening new R session # install.packages("keras") library("keras") # install_keras() # run this line only when opening new R session # use_condaenv() # Machine Learning (ML) models if ( !require("mgcv") ) { install.packages("mgcv"); library("mgcv") } # to run Generalized Additive Model (GAM) algorithm if ( !require("gam") ) { install.packages("gam"); library("gam") } # to run Generalized Additive Model (GAM) algorithm if ( !require("kernlab") ) { install.packages("kernlab"); library("kernlab") } # to run Support Vector Machine (SVM) algorithm if( !require("xgboost") ) { install.packages("xgboost"); library("xgboost") } # to run Boosted Classification Trees (BCT) if ( !require("randomForest")) {install.packages("randomForest"); library("randomForest") } # to run Random Forest (RF) # have to be loaded at the end to not cache function 'train' if ( !require("caret") ) { install.packages("caret"); library("caret") } # comprehensive framework to build machine learning models ## Functions #### source("stat_model_functions.r") source("ml_model_functions.r") source("ann_model_functions.r") source("plot_functions.r") source("utilities.r") ## Data #### # Define directory and files dir.input.data <- "../Input_data/" dir.workspace <- "../Output_data/Tables/" dir.models.output <- "../Output_data/Trained_models/" dir.plots.output <- "../Plots/Models_analysis_plots/" dir.expl.plots.output <- "../Plots/Explorative_plots/" file.input.data <- "All_2729samples_9envfact_lme.area.elev_ModelInputs.csv" file.prev.taxa <- "All_2729samples_9envfact_lme.area.elev_PrevalenceTaxa.csv" # Load input datasets data <- read.csv(paste0(dir.input.data, file.input.data), header = T, sep = ",", stringsAsFactors = F) prev.inv <- read.csv(paste0(dir.input.data, file.prev.taxa), header = T, sep = ",", stringsAsFactors = F) # Prepare inputs for geographic plots inputs <- map.inputs(directory = paste0(dir.input.data,"Swiss.map.gdb"), data = data) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DATA WRANGLING #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Select env. factors and taxa #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Select temperature of interest print(colnames(data)[which(grepl("temperature", colnames(data)))]) select.temp <- "lme.area.elev" # select.temp <- "lm.area.elev" # data$temperature <- data[,which(colnames(data) == paste0("temperature.", select.temp))] # Add quadratic terms for temperature and flow velocity # data$temperature2 <- data$temperature^2 # data$velocity2 <- data$velocity^2 # Select environmental factors env.fact <- c("Temperature" = "temperature", # Temp "Flow velocity" = "velocity", # FV "Riparian agriculture" = "A10m", # A10m "Livestock unit density" = "cow.density", # LUD "Insecticide application rate" = "IAR", # IAR "Urban area" = "urban.area", # Urban "Forest-river intersection" = "FRI", # FRI "Forest-river intersection buffer" = "bFRI", # bFRI "Width variability" = "width.variability") # WV env.fact.full <- c(env.fact, "Temperature2" = "temperature2", "Velocity2" = "velocity2") no.env.fact <- length(env.fact) # Select sites (categorical) information to keep for analysis vect.info <- c("Region", "RiverBasin", "BIOGEO") # ~~~~~~~~~~~~~~~~~~~~~ ## Preprocess data #### # ~~~~~~~~~~~~~~~~~~~~~ # Select list of taxa list.taxa <- colnames(data)[which(grepl("Occurrence.", colnames(data)))] names.taxa <- gsub("Occurrence.", "", list.taxa) no.taxa <- length(list.taxa) select.taxa <- c("Occurrence.Gammaridae", "Occurrence.Psychodidae", "Occurrence.Nemouridae") # select taxa for further analysis list.taxa.int <- prev.inv[which(prev.inv[, "Prevalence"] < 0.75 & prev.inv[,"Prevalence"] > 0.25), # list taxa with intermediate prevalence "Occurrence.taxa"] no.taxa.int <- length(list.taxa.int) cat("\nSummary information of input dataset:\n", length(unique(data$SampId)), "samples,\n", length(unique(data$SiteId)), "sites,\n", length(list.taxa), "taxa.") print(summary(as.factor(prev.inv[which(prev.inv$Occurrence.taxa %in% list.taxa), "Taxonomic.level"]))) # Write info for files name info.file.name.data <- paste0(file.prefix, dim(data)[1], "samples_", no.env.fact, "envfact_", select.temp) info.file.name.models <- paste0(file.prefix, no.taxa, "taxa_", train.info, ifelse(dl, "DL_", "no_DL_"), select.temp) cat("\nMain info: ", info.file.name.models, "\n\n") # Split data if(CV|ODG){ splits <- split.data(data = data, list.taxa = list.taxa, dir.workspace = dir.workspace, info.file.name.data = info.file.name.data, select.temp = select.temp, CV = CV, ODG = ODG, ODG.info = ODG.info, bottom = T) } else { splits <- list("Entire dataset" = data) } list.splits <- names(splits) no.splits <- length(list.splits) n.cores.splits <- ifelse(server, no.splits, 1) # to use one core per split on the server # Standardize data stand.norm.data <- standardize.data(data = data, splits = splits, env.fact.full = env.fact.full, dl = dl, CV = CV, ODG = ODG) standardized.data <- stand.norm.data$standardized.data standardized.data.factors <- stand.norm.data$standardized.data.factors normalization.data <- stand.norm.data$normalization.data remove(stand.norm.data) # ~~~~~~~~~~~~~~~~~~~~~~~~~ ## Plots data analysis #### # ~~~~~~~~~~~~~~~~~~~~~~~~~ # Fig. SI A 2, 4-6: analysis splits #### file.name <- paste0("_AnalysisSplits_", train.info, ifelse(ODG, paste0("_by", ODG.info["model"],""), "")) if(!file.exists(paste0(dir.expl.plots.output, info.file.name.data, file.name, ".pdf"))){ list.plots <- analysis.splits(inputs = inputs, splits = splits, env.fact = env.fact, vect.info = vect.info) cat("Printing PDF and PNG\n") print.pdf.plots(list.plots = list.plots, width = 15, height = 8, dir.output = dir.expl.plots.output, info.file.name = info.file.name.data, file.name = file.name, png = T, png.ratio = 0.8) } # Fig. SI A 3: correlation matrix #### file.name <- paste0(dir.expl.plots.output, info.file.name.data, "_CorrelationMatrix") if(!file.exists(paste0(file.name,".pdf"))){ pdf.corr.mat.env.fact(data = data, env.fact = env.fact, file.name = file.name) } # Fig. SI A 7-15: maps env. fact #### file.name <- "_MapsEnvFact" list.env.fact <- mapply(c, env.fact, names(env.fact), SIMPLIFY = FALSE) if(!file.exists(paste0(dir.expl.plots.output, info.file.name.data, file.name, ".pdf"))){ list.plots <- maps.env.fact(inputs = inputs, list.env.fact = list.env.fact, data = data) cat("Printing PDF\n") print.pdf.plots(list.plots = list.plots, width = 15, height = 8, dir.output = dir.expl.plots.output, info.file.name = info.file.name.data, file.name = file.name, png = T, png.ratio = 0.8) } # Fig. SI A 18: prevalence analysis #### file.name <- paste0("_AnalysisPrevalence_", train.info, ifelse(ODG, paste0("_by", ODG.info["model"],""), "")) if(!file.exists(paste0(dir.expl.plots.output, info.file.name.data, file.name, ".pdf")) & !CV){ list.plots <- analysis.prevalence(prev.inv = prev.inv, splits = splits, ODG = ODG) cat("Printing PDF\n") print.pdf.plots(list.plots = list.plots, width = 15, height = 15, dir.output = dir.expl.plots.output, info.file.name = info.file.name.data, file.name = file.name, png = T,png.vertical = T, png.ratio = 1) } # ~~~~~~~~~~~~~~~~~~~ ## Select models #### # ~~~~~~~~~~~~~~~~~~~ # Already select the colors assigned to each model for the plots # Statistical models list.stat.mod <- c( "#256801" = "hGLM", "#59AB2D" = "chGLM" ) stat.iterations <- 10000 # set iterations for stat models training (needs to be an even number) n.chain <- 2 # number of sample chains ran in parallel n.cores.stat.models <- ifelse(server, length(list.stat.mod), 1) # to use one core per model on the server comm.corr.options <- c(F,T) # flags for correlation matrix names(comm.corr.options) <- list.stat.mod # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Machine learning algorithms (! their packages have to be installed first) list.algo <- c( "deepskyblue4" = 'glm', # Generalized Linear Model "deepskyblue" = 'gamLoess', # Generalized Additive Model "#7B1359" = 'svmRadial', # Support Vector Machine "hotpink1" = "ada" , # Boosted Classification Tree "hotpink3" = 'rf' # Random Forest ) no.algo <- length(list.algo) list.ml <- c( "iGLM", # Generalized Linear Model "GAM", # Generalized Additive Model "SVM", # Support Vector Machine "BCT", # Boosted Classification Tree "RF" # Random Forest ) names(list.ml) <- names(list.algo) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Artificial Neural Network # Hyperparameters with fixed value learning.rate <- 0.01 # only one value batch.size <- 64 # only one value # Hyperparameters to tune if(models.analysis["ann.hyperparam"]){ grid.hyperparam <- expand.grid( layers = c(3, 5, 10), units = c(4, 8, 32), act.fct = c( "tanh", # "swish", "relu", "leakyrelu"), no.epo = c(50, 100) ) } else { grid.hyperparam <- expand.grid( layers = c(5), units = c(4), act.fct = c("leakyrelu"), no.epo = c(50) ) } grid.hyperparam$act.fct <- as.character(grid.hyperparam$act.fct) no.hyperparam <- nrow(grid.hyperparam) list.hyper.param <- vector("list", no.hyperparam) if(no.hyperparam == 1){ # fixed hyperparameters if(models.analysis["ann.random"]){ no.ann.runs = 5 # number of runs to do randomness sensitivity analysis for (n in 1:no.ann.runs) { list.hyper.param[[n]] <- grid.hyperparam[1,] names(list.hyper.param)[n] <- paste0("ANN_rand", n) } } else { list.hyper.param[[1]] <- grid.hyperparam[1,] names(list.hyper.param) <- c("ANN") } } else { # hyperparameters tuning for (n in 1:no.hyperparam) { list.hyper.param[[n]] <- grid.hyperparam[n,] names(list.hyper.param)[n] <- paste(paste0(grid.hyperparam[n,], c("L", "U_", "", "epo")), collapse = "") } names(list.hyper.param) <- paste("ANN_", names(list.hyper.param), sep = "") } list.ann <- names(list.hyper.param) no.ann <- length(list.ann) if(no.ann == 1){ names(list.ann) <- "#FFB791" } else { names(list.ann) <- hcl.colors(no.ann, palette = "Oranges") } # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Final model list if(models.analysis["ann.hyperparam"]){ list.models <- list.ann } else { list.models <- c(list.ml[1], list.stat.mod, list.ml[2:no.algo], list.ann) list.models.orig <- list.models } no.models <- length(list.models) show_col(names(list.models)) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # APPLY MODELS #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Define null model, outputs taxon prevalence everywhere null.model <- apply.null.model(data = data, list.taxa = list.taxa) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # apply stat and ml only if not doing ann analysis if(!models.analysis["ann.hyperparam"] & !models.analysis["ann.random"] ){ # ~~~~~~~~~~~~~~~~~~~~~~~~ ## Statistical models #### # ~~~~~~~~~~~~~~~~~~~~~~~~ ptm <- proc.time() # to calculate time of simulation stat.outputs <- mclapply(comm.corr.options, mc.cores = n.cores.stat.models, function(comm.corr){ # comm.corr <- comm.corr.options[[1]] model.name <- ifelse(comm.corr, list.stat.mod[2], list.stat.mod[1]) info.file.stat.name <- paste0("Stat_model_", model.name, "_", stat.iterations,"iterations_", info.file.name.models) file.name <- paste0(dir.models.output, info.file.stat.name, ".rds") # cat(file.name) # If the file with the output already exist, just read it if (file.exists(file.name)){ if(!exists("stat.output")){ cat("\nFile with statistical model output already exists, we read it from:\n", file.name, "\nand save it in object 'stat.output'.\n") stat.output <- readRDS(file = file.name) } else{ cat("\nList with statistical model output already exists as object 'stat.output' in this environment.\n") } } else { cat("\nNo statistical model output exist yet, we produce it and save it in", file.name) if(CV|ODG){ stat.output <- mclapply(standardized.data, mc.cores = n.cores.splits, FUN = stat_mod_cv, CV, ODG, model.name, comm.corr, stat.iterations, n.chain, list.taxa, env.fact.full) cat("\nSaving output of statistical models in:\n", file.name) saveRDS(stat.output, file = file.name, version = 2) #version two here is to ensure compatibility across R versions } else { stat.output <- stat_mod_cv(standardized.data, CV, ODG, model.name, comm.corr, stat.iterations, n.chain, list.taxa, env.fact.full) cat("\nSaving output of statistical models in\n", file.name) saveRDS(stat.output, file = file.name, version = 2) } } return(stat.output) }) # Process output from stat models to fit structure of ml models (makes plotting easier) stat.outputs.transformed <- transfrom.stat.outputs(stat.outputs = stat.outputs, list.taxa = list.taxa, CV = CV, ODG = ODG) print(paste("\nSimulation time of statistical model ")) print(proc.time()-ptm) # ~~~~~~~~ ## ML #### # ~~~~~~~~ ptm <- proc.time() # to calculate time of simulation # Split computation of ML algorithm, because it' too heavy to read in if(CV|ODG){ temp.list.algo <- list(list.algo[1:3], list.algo[4:length(list.algo)]) } else { temp.list.algo <- list(list.algo) } temp.outputs <- list() for (n in 1:length(temp.list.algo)) { # n = 1 info.file.ml.name <- paste0("ML_models_", paste0(paste(temp.list.algo[[n]], collapse = "_"), "_"), info.file.name.models ) file.name <- paste0(dir.models.output, info.file.ml.name, ".rds") if(file.exists(file.name)){ cat("\nThe file already exists:\n", file.name, "\nReading it and uploading it in the environment.\n") if(CV | ODG){ temp.outputs[[n]] <- readRDS(file = file.name) } else { temp.outputs[[n]] <- readRDS(file = file.name) } } else { cat("\nNo ML outputs exist yet, we run the models and save the results in:\n", file.name) if(CV|ODG){ if(server){ # Compute three splits in parallel (should be run on the server) temp.outputs[[n]] <- mclapply(standardized.data.factors, mc.cores = n.cores.splits, FUN = apply.ml.model, tune.grid = NULL, temp.list.algo[[n]], list.taxa, env.fact, env.fact.full, CV, ODG, prev.inv = prev.inv) } else { # Compute one split after the other temp.outputs[[n]] <- lapply(standardized.data.factors, FUN = apply.ml.model, tune.grid = NULL, temp.list.algo[[n]], list.taxa, env.fact, env.fact.full, CV, ODG, prev.inv = prev.inv) } cat("\nSaving outputs of algorithms in:\n", file.name) saveRDS(temp.outputs[[n]], file = file.name, version = 2) } else { splitted.data <- list("Training data" = standardized.data.factors[[1]], "Testing data" = data.frame()) temp.outputs[[n]] <- apply.ml.model(splitted.data = splitted.data, tune.grid = NULL, list.algo = temp.list.algo[[n]], list.taxa = list.taxa, env.fact = env.fact, env.fact.full = env.fact.full, CV = CV, ODG = ODG, prev.inv = prev.inv) cat("\nSaving outputs of algorithms in:\n", file.name) saveRDS(temp.outputs[[n]], file = file.name, version = 2) } } } print(paste("Simulation time of different models ", info.file.ml.name)) print(proc.time()-ptm) } # ~~~~~~~~~ ## ANN #### # ~~~~~~~~~ info.file.ann.name <- paste0("ANN_models_", no.ann, "ann_", ifelse(models.analysis["ann.hyperparam"], "HyperparamTuning_", ""), ifelse(models.analysis["ann.random"], "RandomAnalysis_", ""), info.file.name.models) file.name <- paste0(dir.models.output, info.file.ann.name, ".rds") cat(file.name) # Run ANN everytime to produce ICE plos cat("Run ANN and save output in", file.name) if(CV|ODG){ # ann.outputs.cv <- readRDS(file = file.name) ann.outputs.cv <- lapply(standardized.data, function(split){ lapply(list.hyper.param, FUN = build_and_train_model, split = split, env.fact = env.fact, list.taxa = list.taxa, learning.rate = learning.rate, batch.size = batch.size, CV = CV, ODG = ODG) }) saveRDS(ann.outputs.cv, file = file.name) } else { # ann.outputs <- readRDS(file = file.name) ann.outputs <- lapply(list.hyper.param, FUN = build_and_train_model, split = standardized.data, env.fact = env.fact, list.taxa = list.taxa, learning.rate = learning.rate, batch.size = batch.size, CV = CV, ODG = ODG) saveRDS(ann.outputs, file = file.name) } # ~~~~~~~~~~~~~~~~~ ## Analysis RF #### # ~~~~~~~~~~~~~~~~~ if(CV|ODG){ if(models.analysis["rf.hyperparam"]){ # hyperparameter grid search list.tuned.grid <- list() # list of dataframes with columns for each hyperparameter # For 'rf' tuned.algo <- "rf" tuned.grid <- expand.grid(mtry = c(1,2,4,8)) # tuned.grid <- list(1,2,4,8) # # For 'RRF' # tuned.algo <- "RRF" # tuned.grid <- expand.grid(mtry = c(1,2), coefReg = c(1), coefImp = c(0, 0.5)) for (n in 1:nrow(tuned.grid)) { list.tuned.grid[[n]] <- tuned.grid[.(n),] names(list.tuned.grid)[[n]] <- paste(c(tuned.algo, "_", paste(tuned.grid[n,], colnames(tuned.grid), sep="")), collapse = "") } list.tuned.algo <- names(list.tuned.grid) no.analyzed.algo <- length(list.tuned.algo) names(list.tuned.algo) <- hcl.colors(no.analyzed.algo, palette = "Magenta") print(list.tuned.algo) info.file.ml.name <- paste0("ML_models_", no.analyzed.algo, "tuned_", tuned.algo, "_", info.file.name.models) file.name <- paste0(dir.models.output, info.file.ml.name, ".rds") if(file.exists(file.name)){ analysis.ml.outputs.cv <- readRDS(file.name) } else { analysis.ml.outputs.cv <- lapply(standardized.data.factors, function(split){ # split <- standardized.data.factors[[1]] lapply(list.tuned.grid, FUN = apply.ml.model, splitted.data = split, list.algo = tuned.algo, list.taxa = list.taxa, env.fact = env.fact, CV = CV, ODG = ODG, prev.inv = prev.inv) }) cat("\nSaving models outputs in:", file.name, "\n") saveRDS(analysis.ml.outputs.cv, file = file.name, version = 2) } list.models <- c(list.models, list.tuned.algo) } else if(models.analysis["rf.random"]){ # randomness analysis temp.list.algo <- list.algo[4:5] # select BCT and RF print(temp.list.algo) seeds <- c( 2020, 2021, 2022) grid.algo.seeds <- expand.grid("algorithm" = temp.list.algo, "seed" = seeds) grid.algo.seeds$algorithm <- as.character(grid.algo.seeds$algorithm) grid.algo.seeds$seed <- as.integer(grid.algo.seeds$seed) no.algo.seeds <- nrow(grid.algo.seeds) list.algo.seeds <- vector("list", no.algo.seeds) for (n in 1:no.algo.seeds) { list.algo.seeds[[n]] <- grid.algo.seeds[n,] names(list.algo.seeds)[n] <- paste(grid.algo.seeds[n,], collapse = "") } list.seed.algo <- names(list.algo.seeds) # make list of new algo names for (l in temp.list.algo) { # assign colors names(list.seed.algo)[which(grepl(l, list.seed.algo))] <- colorRampPalette(c("white", names(temp.list.algo[which(temp.list.algo == l)])))(length(seeds)) } list.models <- c(list.models, list.seed.algo) # append to list.models info.file.ml.name <- paste0("ML_models_", no.algo.seeds, "RandomAnalysis_", info.file.name.models) file.name <- paste0(dir.models.output, info.file.ml.name, ".rds") if(file.exists(file.name)){ analysis.ml.outputs.cv <- readRDS(file.name) } else { analysis.ml.outputs.cv <- lapply(standardized.data.factors, function(split){ # split <- standardized.data.factors[[1]] lapply(list.algo.seeds, function(algo.seed){apply.ml.model(splitted.data = split, list.algo = algo.seed[,"algorithm"], list.taxa = list.taxa, env.fact = env.fact, CV = CV, ODG = ODG, prev.inv = prev.inv, seed = algo.seed[,"seed"]) }) }) cat("\nSaving models outputs in:", file.name, "\n") saveRDS(analysis.ml.outputs.cv, file = file.name, version = 2) } } } # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # PROCESS OUTPUTS #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~ ## Merge outputs #### # ~~~~~~~~~~~~~~~~~~~ if(CV | ODG){ # Merge all CV outputs in one outputs.cv <- vector(mode = "list", length = no.splits) names(outputs.cv) <- list.splits for (s in list.splits) { #s = "Split3" if(exists("temp.outputs")){ outputs.cv[[s]][[list.ml[1]]] <- temp.outputs[[1]][[s]][[list.algo[1]]] # iGLM } if(exists("stat.outputs.transformed")){ outputs.cv[[s]][[list.stat.mod[1]]] <- stat.outputs.transformed[[1]][[s]] # hGLM outputs.cv[[s]][[list.stat.mod[2]]] <- stat.outputs.transformed[[2]][[s]] # chGLM } if(exists("temp.outputs")){ # rest of ml algo for (n in 1:length(temp.outputs)) { if(n == 1){ for (l in 2:length(temp.outputs[[n]][[s]]) ) { outputs.cv[[s]][[list.ml[l]]] <- temp.outputs[[n]][[s]][[list.algo[l]]] } } else { for (l in (length(temp.outputs[[n-1]][[s]])+1):(length(temp.outputs[[n-1]][[s]])+length(temp.outputs[[n]][[s]])) ) { outputs.cv[[s]][[list.ml[l]]] <- temp.outputs[[n]][[s]][[list.algo[l]]] } } } } if(exists("ann.outputs.cv")){ outputs.cv[[s]] <- append(outputs.cv[[s]], ann.outputs.cv[[s]]) } if(exists("analysis.ml.outputs.cv")){ if(models.analysis["rf.random"]){ # correct the weird listing for this output for (l in list.seed.algo) { analysis.ml.outputs.cv[[s]][[l]] <- analysis.ml.outputs.cv[[s]][[l]][[1]] } } if(models.analysis["rf.hyperparam"]){ # correct the weird listing for this output for (l in list.tuned.algo) { analysis.ml.outputs.cv[[s]][[l]] <- analysis.ml.outputs.cv[[s]][[l]][[1]] } } outputs.cv[[s]] <- append(outputs.cv[[s]], analysis.ml.outputs.cv[[s]]) } } } else { # Make final outputs as list outputs <- list() if(exists("temp.outputs")){ outputs[[list.ml[1]]] <- temp.outputs[[1]][[1]] } if(exists("stat.outputs.transformed")){ outputs[[list.stat.mod[1]]] <- stat.outputs.transformed[[1]] outputs[[list.stat.mod[2]]] <- stat.outputs.transformed[[2]] } if(exists("temp.outputs")){ for (l in 2:no.algo) { outputs[[list.ml[l]]] <- temp.outputs[[1]][[list.algo[l]]] } } if (exists("ann.outputs")){ outputs <- append(outputs, ann.outputs) } } # remove(temp.outputs) if(exists("outputs") | exists("outputs.cv")){ # Make sure list.models match with models output if(CV|ODG){ vec1 <- names(outputs.cv$Split1) vec2 <- list.models list.models <- vec2[match(vec1, vec2)] } else { vec1 <- names(outputs) vec2 <- list.models list.models <- vec2[match(vec1, vec2)] } } print(list.models) no.models <- length(list.models) show_col(names(list.models)) info.file.name <- paste0(no.models, "models_", ifelse(models.analysis["rf.hyperparam"], paste0(tuned.algo, "_HyperparamTuning_"), ""), ifelse(models.analysis["rf.random"], "RF_RandomAnalysis_", ""), ifelse(models.analysis["ann.hyperparam"], "ANN_HyperparamTuning_", ""), ifelse(models.analysis["ann.random"], "ANN_RandomAnalysis_", ""), info.file.name.models, "_") cat(info.file.name) # ~~~~~~~~~~~~~~~~~~~~ ## Results tables #### # ~~~~~~~~~~~~~~~~~~~~ # Produce final outputs with mean performance across splits if(CV | ODG){ # Make final outputs as tables df.cv <- make.df.outputs(outputs = outputs.cv, list.models = list.models, list.taxa = list.taxa, list.splits = list.splits, null.model = null.model, prev.inv = prev.inv, CV = CV, ODG = ODG) df.pred.perf.cv <- df.cv$`Table predictive performance CV` df.pred.perf <- df.cv$`Table predictive performance` df.fit.perf.cv <- df.cv$`Table fit performance CV` df.fit.perf <- df.cv$`Table fit performance` df.perf <- df.cv$`Table merged` remove(df.cv) } else { # Make final outputs as tables df.perf <- make.df.outputs(outputs = outputs, list.models = list.models, list.taxa = list.taxa, list.splits = list.splits, null.model = null.model, prev.inv = prev.inv, CV = CV, ODG = ODG) } # Make csv file with performance tables df.results <- df.perf df.results <- df.results %>% mutate_if(is.numeric, round, digits=2) df.results$Taxa <- gsub("Occurrence.", "", df.results$Taxa) # All results file.name <- paste(dir.workspace, info.file.name, "TableAllResults", ".csv", sep="") cat(file.name) write.table(df.results, file.name, sep=",", row.names=F, col.names=TRUE) # Summary statistics file.name <- paste(dir.workspace, info.file.name, "TableSummaryStat", ".csv", sep="") cat(file.name) df.summary <- sumtable(df.results, add.median = TRUE, out='return') write.table(df.summary, file.name, sep=",", row.names=F, col.names=TRUE) # Table 3: summary pred. perf. #### # Summarized table of AUC and stand. dev. predictive performance during CV file.name <- paste(dir.workspace, info.file.name, "TableSummaryStat_PredPerf", ".csv", sep="") cat(file.name) df.summary.pred.perf <- table.summary.pred.perf(df.summary = df.summary, list.models = list.models) write.table(df.summary.pred.perf, file.name, sep=",", row.names=F, col.names=TRUE) # Table SI A 4-5: standardize deviance per taxon #### df.stand.dev <- df.results[,c(which(colnames(df.results) %in% c("Taxa", "Prevalence")), which(grepl("dev.pred", colnames(df.results)) & !grepl("expl.pow", colnames(df.results))))] colnames(df.stand.dev)[which(grepl("dev.pred", colnames(df.stand.dev)))] <- list.models file.name <- paste(dir.workspace, info.file.name, "TableStandDev", ".csv", sep="") cat(file.name) write.table(df.stand.dev, file.name, sep=",", row.names=F, col.names=TRUE) # Table SI A 6-7: likelihood ratio per taxon #### df.likelihood.ratio <- df.results[,c(which(colnames(df.results) %in% c("Taxa", "Prevalence")), which(grepl("likeli", colnames(df.perf))))] colnames(df.likelihood.ratio)[which(grepl("likeli", colnames(df.likelihood.ratio)))] <- list.models file.name <- paste(dir.workspace, info.file.name, "TableLikelihoodRatio", ".csv", sep="") cat(file.name) write.table(df.likelihood.ratio, file.name, sep=",", row.names=F, col.names=TRUE) # Table SI A 8-9: AUC per taxon #### df.auc.pred <- df.results[,c(which(colnames(df.results) %in% c("Taxa", "Prevalence")), which(grepl("auc.pred", colnames(df.perf))))] colnames(df.auc.pred)[which(grepl("auc", colnames(df.auc.pred)))] <- list.models file.name <- paste(dir.workspace, info.file.name, "TableAUC", ".csv", sep="") cat(file.name) write.table(df.auc.pred, file.name, sep=",", row.names=F, col.names=TRUE) # Explore likelihood ratio if((CV|ODG) & "iGLM" %in% list.models){ temp.df <- arrange(df.perf, desc(iGLM.likelihood.ratio)) temp.df <- filter(temp.df, iGLM.likelihood.ratio > 1) cat("Following", length(temp.df$Taxa), "taxa have a likelihood ratio above 1 for iGLM:\n", gsub("Occurrence.", "", temp.df$Taxa), "summarized like:\n" ) print(summary(temp.df$iGLM.likelihood.ratio)) } # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # PLOTS #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Compare predictive performance #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if(case.compar["cv.odg"]){ names.appcase <- c("CV", "ODG") if(CV){ df.perf1 <- df.perf } else if(ODG){ df.perf2 <- df.perf } CV <- !CV ODG <- !ODG } else if(case.compar["temp.model"]){ names.appcase <- c("lm", "lme") df.perf1 <- df.perf lme.temp <- !lme.temp } temp.info.file.name <- paste0(no.models, "models_", ifelse(models.analysis["rf.hyperparam"], "RF_HyperparamTuning_", ""), ifelse(models.analysis["rf.random"], "RF_RandomAnalysis_", ""), ifelse(models.analysis["ann.hyperparam"], "ANN_HyperparamTuning_", ""), ifelse(models.analysis["ann.random"], "ANN_RandomAnalysis_", ""), file.prefix, no.taxa, "taxa_", ifelse(CV, "CV_", ifelse(ODG, paste0(paste(c("ODG_", ODG.info["training.ratio"], ODG.info["variable"]), collapse = ""), "_"), "FIT_")), ifelse(dl, "DL_", "no_DL_"), select.temp,"_") cat(temp.info.file.name) if(case.compar["cv.odg"]){ if(CV){ df.perf1 <- read.csv(paste(dir.workspace, temp.info.file.name, "TableAllResults", ".csv", sep=""), header=TRUE, sep=",", stringsAsFactors=FALSE) } else if(ODG){ df.perf2 <- read.csv(paste(dir.workspace, temp.info.file.name, "TableAllResults", ".csv", sep=""), header=TRUE, sep=",", stringsAsFactors=FALSE) } CV <- !CV ODG <- !ODG } else if(case.compar["temp.model"]){ df.perf2 <- read.csv(paste(dir.workspace, temp.info.file.name, "TableAllResults", ".csv", sep=""), header=TRUE, sep=",", stringsAsFactors=FALSE) lme.temp <- !lme.temp } if(exists("df.perf1")){ list.df.perf <- list(df.perf1, df.perf2) names(list.df.perf) <- names.appcase } else { list.df.perf <- list(df.perf) names(list.df.perf) <- ifelse(CV, "CV", ifelse(ODG, paste(c("ODG_", ODG.info["training.ratio"], ODG.info["variable"]), collapse = ""), "FIT")) } cat("\nPlots will be produce for the following application cases:", names(list.df.perf), "\nList of selected taxa:", sub("Occurrence.", "", select.taxa), "\n\n") if(length(list.df.perf) != 1){ # Prepare data for plots plot.data <- perf.plot.data(list.df.perf = list.df.perf) # Figure 1, SI A 19-20: boxplots comparison pred. perf. #### # Boxplots comparing predictive performance of various cases; calibration vs prediction, CV vs ODG, AUC, ANN hyperparameters list.plots <- plot.boxplots.compar.appcase(plot.data = plot.data, list.models = list.models, models.analysis = models.analysis) file.name <- "ModelCompar_Boxplots" if(length(list.df.perf) != 1){ temp.info.file.name <- gsub( ifelse(CV, "CV_", ifelse(ODG, paste0(paste(c("ODG_", ODG.info["training.ratio"], ODG.info["variable"]), collapse = ""), "_"), "FIT_")), "", info.file.name) } else { temp.info.file.name <- info.file.name } print.pdf.plots(list.plots = list.plots, width = 18, height = ifelse(any(models.analysis == TRUE), 21, 10), dir.output = dir.plots.output, info.file.name = temp.info.file.name, file.name = file.name, png = TRUE, png.vertical = ifelse(any(models.analysis == TRUE), T, F), png.ratio = 0.8) ggsave(file = paste0(dir.plots.output, temp.info.file.name, file.name, ".svg"), plot = list.plots[[1]], width = 13, height = 7) # Figure 2: bell plots comparison pred. perf. per prevalence #### if(!any(models.analysis == T)){ # Standardized deviance vs prevalence list.plots <- plot.perfvsprev.compar.appcase(plot.data = plot.data, list.models = list.models, list.taxa = list.taxa) file.name <- "ModelCompar_PerfVSPrev" print.pdf.plots(list.plots = list.plots, width = 15, height = ifelse(length(list.df.perf) == 1, 10, 15), dir.output = dir.plots.output, info.file.name = temp.info.file.name, file.name = file.name, png = TRUE, png.square = TRUE, png.ratio = 0.8) ggsave(file = paste0(dir.plots.output, temp.info.file.name, file.name, ".svg"), plot = list.plots[[1]], width = 14, height = 11) } # Table 4: likelihood ratio #### table.likeli.ratio <- table.likelihood.ratio(list.df.perf = list.df.perf, list.models = list.models, models.analysis = models.analysis) file.name <- paste(dir.workspace, temp.info.file.name, "TableStatLikeliRatio", ".csv", sep="") cat(file.name) write.table(table.likeli.ratio, file.name, sep=",", row.names=F, col.names=TRUE) } # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Compare GLM parameters #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ list.glm <- list.models[1:3] if(CV){ list.plots <- plot.glm.param(outputs.cv, df.perf, list.glm, list.taxa, env.fact.full, CV) } else if(!ODG) { list.plots <- plot.glm.param(outputs, df.perf, list.glm, list.taxa, env.fact.full, CV) } if(CV | !ODG){ file.name <- "GLMParametersComparison" cat(file.name) print.pdf.plots(list.plots = list.plots, width = 8.4, height = 11.88, # A4 proportions dir.output = dir.plots.output, info.file.name = info.file.name, file.name = file.name, png = TRUE, png.vertical = TRUE) } # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Map geographic distribution of predictions #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if(CV){ # select.models <- c("Null Model", list.models[7]) select.models <- list.models temp.select.taxa <- select.taxa list.df.models.pred <- make.list.models.pred(outputs.cv = outputs.cv, list.taxa = temp.select.taxa, list.models = list.models, prev.inv = prev.inv) # Figure 3, SI A 21-23: maps of predicted probability of occurrence #### list.plots <- lapply(list.df.models.pred, FUN = plot.maps.models.pred, inputs = inputs, select.models = select.models) file.name <- "MapsModelsPrediction" if(length(select.models) != length(list.models)){ file.name <- paste0(file.name, "_", length(select.models), "SelectMod") width = 18 height = 10 } else { # A4 format in inches width = 8.3 height = 11.7 } if(length(temp.select.taxa) != no.taxa){ file.name <- paste0(file.name, "_", length(temp.select.taxa), "SelectTaxa") } print.pdf.plots(list.plots = list.plots, width = 2*width, height = 2*height, dir.output = dir.plots.output, info.file.name = info.file.name, file.name = file.name, png = T, png.vertical = T, png.ratio = 1) if(length(select.models) == 2){ ggsave(file = paste0(dir.plots.output, "MapsModelsPrediction_Gammaridae_", "NullRF", ".svg"), plot = list.plots[[1]], width = 18, height = 10) } else { for (j in temp.select.taxa) { # j <- temp.select.taxa[1] cat("\nPrinting svg for", j) ggsave(file = paste0(dir.plots.output, "MapsModelsPrediction_", j, ".svg"), plot = list.plots[[j]], width = 18, height = 20) } } } # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Response shapes (ICE, PDP) #### # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if(plot.all.ICE == T){ # to produce all ICE/PDP provided in manuscript and Supp. Inf. temp.select.taxa <- list(select.taxa, list.taxa[which(list.taxa != "Occurrence.Perlodidae")]) temp.select.env.fact <- list(env.fact, env.fact[1]) } else { # temp.select.taxa <- list(select.taxa[1], select.taxa[2]) temp.select.env.fact <- list(env.fact[1], env.fact[2]) } # If CV or ODG, take just the first split for trained models analysis # Doesn't work for CV for now if(!CV & ODG){ outputs <- outputs.cv[[1]] normalization.data.cv <- normalization.data } if(!CV){ for (n in 1:length(temp.select.taxa)) { # n = 1 subselect.taxa <- temp.select.taxa[[n]] select.env.fact <- temp.select.env.fact[[n]] # subselect.taxa <- list.taxa[which(list.taxa != "Occurrence.Perlodidae")] # select.env.fact <- env.fact[1] names(subselect.taxa) <- gsub("Occurrence.", "", subselect.taxa) # ICE and PDP no.samples <- 100 no.steps <- 200 subselect <- 1 vect.seeds <- c(2020, 2021, 2022) file.name <- paste0(dir.workspace, info.file.name, "PlotDataICE_", no.samples, "Samp_", length(subselect.taxa), "SelectTaxa_", length(select.env.fact), "SelectEnvFact", ifelse(models.analysis["ice.random"], paste0("_RandomAnal", length(vect.seeds), "Seeds"), ""), ".rds") cat(file.name) # Produce dataframes for plotting ICE and PDP if(file.exists(file.name)){ cat("Reading RDS file with plot data:\n", file.name) list.ice.plot.data <- readRDS(file.name) } else { cat("Producing data for plotting ICE and PDP and saving it in\n", file.name) list.ice.plot.data <- lapply(subselect.taxa, FUN = ice.plot.data, outputs = outputs, ref.data = standardized.data[[1]], list.models = list.models, list.taxa = list.taxa, env.fact = env.fact, select.env.fact = select.env.fact, normalization.data = normalization.data, ODG = ODG, no.samples = no.samples, no.steps = no.steps, vect.seeds = vect.seeds) saveRDS(list.ice.plot.data, file = file.name) } # Figure 4, SI B and C: ICE with PDP on top #### # models.analysis["ice.random"] <- F list.list.ice.plots <- lapply(list.ice.plot.data, FUN = plot.ice.per.taxa, list.models = list.models, subselect = subselect, ice.random = models.analysis["ice.random"]) for (j in 1:length(subselect.taxa)) { taxon <- sub("Occurrence.", "", subselect.taxa[j]) file.name <- paste0("ICE_", no.samples, "Samp_", taxon, "_", length(select.env.fact), "EnvFact") if(models.analysis["ice.random"]){ file.name <- paste0(file.name, "_RandomAnal", length(vect.seeds), "Seeds") } cat("\nPrinting", file.name) print.pdf.plots(list.plots = list.list.ice.plots[[j]], width = 9, # 8.3, height = 6,# 11.7, # A4 format in inches dir.output = paste0(dir.plots.output, "ICE/"), info.file.name = info.file.name, file.name = file.name, png = F) # png = T, png.vertical = T, png.ratio = 0.7) } ggsave(file = paste0(dir.plots.output, "ICE/", info.file.name, "ICE_", no.samples, "Samp_Gammaridae_", "1EnvFact", ".svg"), plot = list.list.ice.plots$Gammaridae$Temperature, width = 8.3, height = 11.7) # Figure 5, SI A 24-26: overlapped PDP #### all.env.fact <- F list.list.overlapped.pdp <- lapply(list.ice.plot.data, FUN = plot.overlapped.pdp, list.models = list.models, ice.random = models.analysis["ice.random"], means = F, all.env.fact = all.env.fact) for (j in 1:length(subselect.taxa)) { taxon <- sub("Occurrence.", "", subselect.taxa[j]) file.name <- paste0("OverlappedPDP_", taxon, "_", ifelse(all.env.fact, "All", length(select.env.fact)), "EnvFact") if(models.analysis["ice.random"]){ file.name <- paste0(file.name, "_RandomAnal", length(vect.seeds), "Seeds") width = 8.3 height = 11.7 } else { width = 8 height = 6 } cat("\nPrinting", file.name) print.pdf.plots(list.plots = list.list.overlapped.pdp[[j]], width = width, height = height, dir.output = paste0(dir.plots.output, "ICE/"), info.file.name = info.file.name, file.name = file.name)#, # png = T, png.square = T, png.ratio = 1) } ggsave(file = paste0(dir.plots.output, "ICE/", info.file.name, "OverlappedPDP_", "Gammaridae_", "1EnvFact", ".svg"), plot = list.list.overlapped.pdp$Gammaridae$Temperature, width = 6, height = 4) # Simple response shapes (prediction vs observation) (not in the paper) list.list.plots <- lapply(subselect.taxa, FUN = plot.rs.taxa, outputs = outputs, list.models = list.models, normalization.data = normalization.data, env.fact = env.fact, CV = CV, ODG = ODG) for (j in 1:length(subselect.taxa)) { taxon <- sub("Occurrence.", "", subselect.taxa[j]) file.name <- paste0("RS_", taxon) print.pdf.plots(list.plots = list.list.plots[[j]], width = 8.3, height = 11.7, # A4 format in inches dir.output = paste0(dir.plots.output, "ICE/"), info.file.name = info.file.name, file.name = file.name) } } }
import 'package:flutter/material.dart'; import 'package:online_shop_app/constents.dart'; import 'package:online_shop_app/models/Product.dart'; import 'package:online_shop_app/screens/details/details_screen.dart'; import 'package:online_shop_app/screens/home/components/categories.dart'; import 'item_card.dart'; class Body extends StatelessWidget { const Body({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: kDefultPaddin), child: Text( "Women", style: Theme.of(context) .textTheme .headline5 ?.copyWith(fontWeight: FontWeight.bold), ), ), Categories(), Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: kDefultPaddin), child: GridView.builder( itemCount: products.length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: kDefultPaddin, crossAxisSpacing: kDefultPaddin, childAspectRatio: 0.75, ), itemBuilder: (context, index) => ItemCard( press: () => Navigator.push( context, MaterialPageRoute( builder: (context) => DetailsScreen( product: products[index], ))), product: products[index])), )) ], ); } }
@page @using TheCrewCommunity.Data.GameData @model TheCrewCommunity.Pages.Motorfest.ProSettings.AddCarProSettings @{ } <form id="proSubmitForm" method="post" asp-page-handler="SubmitProSettings"> <div class="vehicleSelectionBox"> <div class="selectWrapper"> <label for="discipline">Discipline:</label> <select name="discipline" id="discipline" onchange="updateBrands(this.value)"> <option value="null">Select Discipline</option> @{ foreach (VehicleCategory vCat in Model.VCatList) { <option value="@vCat.Id">@vCat.Name</option> } } </select> </div> <div class="selectWrapper"> <label for="brand">Brand:</label> <select name="brand" id="brand" onchange="updateModelList(document.getElementById('discipline').value, this.value)"> <option value="null">Select Brand</option> <!-- options will be dynamically populated --> </select> </div> <div class="selectWrapper"> <label for="model">Model:</label> <select name="VehicleId" id="model"> <option value="null">Select Model</option> <!-- options will be dynamically populated --> </select> </div> </div> <div class="ProSettingsContainer"> <div class="vehicleBox vehicleBoxWithHeader"> <div class="proSettingsBox"> <h3>Transmission</h3> <div class="proSettingsItem"> <label for="finalDrive" class="sliderName">Final Drive</label> <span class="slider-value"></span> <input name="FinalDrive" class="proSlider sliderPercentage" id="finalDrive" type="range" min="-20" max="0" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="powerDistribution">Power Distribution</label> <span class="slider-value-front"></span> <input name="PowerToFront" class="proSlider sliderPercentage proDistribution" id="powerDistribution" type="range" min="20" max="60" value="40" step="1" disabled/> <span class="slider-value-rear"></span> </div> <h3>Tires</h3> <div class="proSettingsItem"> <label class="sliderName" for="gripFront">Grip Front</label> <span class="slider-value"></span> <input name="GripFront" class="proSlider sliderPercentage" id="gripFront" type="range" min="-20" max="0" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="gripRear">Grip Rear</label> <span class="slider-value"></span> <input name="GripRear" class="proSlider sliderPercentage" id="gripRear" type="range" min="-20" max="0" value="0" step="1"/> </div> <h3>Brakes</h3> <div class="proSettingsItem"> <label class="sliderName" for="brakeBalance">Brake Balance</label> <span class="slider-value-front"></span> <input name="BrakeToFront" class="proSlider sliderPercentage proDistribution" id="brakeBalance" type="range" min="40" max="80" value="60" step="1"/> <span class="slider-value-rear"></span> </div> <div class="proSettingsItem"> <label class="sliderName" for="brakePower">Brake Power</label> <span class="slider-value"></span> <input name="BrakePower" class="proSlider sliderPercentage" id="brakePower" type="range" min="-30" max="0" value="0" step="1"/> </div> <h3>Aero</h3> <div class="proSettingsItem"> <label class="sliderName" for="loadFront">Load Front</label> <span class="slider-value"></span> <input name="LoadFront" class="proSlider sliderPercentage" id="loadFront" type="range" min="-30" max="0" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="loadRear">Load Rear</label> <span class="slider-value"></span> <input name="LoadRear" class="proSlider sliderPercentage" id="loadRear" type="range" min="-30" max="0" value="0" step="1"/> </div> <h3>Suspension</h3> <div class="proSettingsItem"> <label class="sliderName" for="springFront">Spring Front</label> <span class="slider-value"></span> <input name="SpringFront" class="proSlider sliderPercentage" id="springFront" type="range" min="-20" max="10" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="springRear">Spring Rear</label> <span class="slider-value"></span> <input name="SpringRear" class="proSlider sliderPercentage" id="springRear" type="range" min="-20" max="10" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="damperCompressionFront">Damper Compression Front</label> <span class="slider-value"></span> <input name="DamperCompressionFront" class="proSlider sliderPercentage" id="damperCompressionFront" type="range" min="-20" max="20" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="damperCompressionRear">Damper Compression Rear</label> <span class="slider-value"></span> <input name="DamperCompressionRear" class="proSlider sliderPercentage" id="damperCompressionRear" type="range" min="-20" max="20" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="damperReboundFront">Damper Rebound Front</label> <span class="slider-value"></span> <input name="DamperReboundFront" class="proSlider sliderPercentage" id="damperReboundFront" type="range" min="-20" max="20" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="damperReboundRear">Damper Rebound Rear</label> <span class="slider-value"></span> <input name="DamperReboundRear" class="proSlider sliderPercentage" id="damperReboundRear" type="range" min="-20" max="20" value="0" step="1"/> </div> <h3>Anti Roll Bars</h3> <div class="proSettingsItem"> <label class="sliderName" for="arbFront">ARB Front</label> <span class="slider-value"></span> <input name="AntiRollBarFront" class="proSlider sliderPercentage" id="arbFront" type="range" min="-20" max="10" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="arbRear">ARB Rear</label> <span class="slider-value"></span> <input name="AntiRollBarRear" class="proSlider sliderPercentage" id="arbRear" type="range" min="-20" max="10" value="0" step="1"/> </div> <h3>Alignment</h3> <div class="proSettingsItem"> <label class="sliderName" for="camberFront">Camber Front</label> <span class="slider-value"></span> <input name="CamberFront" class="proSlider sliderDegree" id="camberFront" type="range" min="-25" max="25" value="0" step="1"/> </div> <div class="proSettingsItem"> <label class="sliderName" for="camberRear">Camber Rear</label> <span class="slider-value"></span> <input name="CamberRear" class="proSlider sliderDegree" id="camberRear" type="range" min="-25" max="25" value="0" step="1"/> </div> </div> </div> <div class="sideInfoBox"> <label for="Name">Name:</label> <input name="Name" id="Name" class="proSettingsName" type="text" maxlength="40"/> <span asp-validation-for="FormData.Name" class="text-danger"></span> <label for="Description">Description:</label> <textarea name="Description" id="Description" class="ProSettingsDescription" maxlength="500" value=""></textarea> <button class="submitButton" type="submit">Submit Pro Settings</button> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) </div> </div> </form> <script> // handle slider logic window.onload = function() { let sliders = document.querySelectorAll('.proSlider'); sliders.forEach(function(slider) { let value = slider.value; if (slider.classList.contains('sliderPercentage')){ value+='%'; } else if (slider.classList.contains('sliderDegree')) { value = '0.'+value+'°' } if (slider.id ==="brakeBalance" || slider.id ==="powerDistribution"){ slider.parentElement.querySelector('.slider-value-front').innerText = value + ' Front'; slider.parentElement.querySelector('.slider-value-rear').innerText = (100 - slider.value) + '% Rear'; } else{ slider.previousElementSibling.innerText = value; } slider.oninput = function() { let value = this.value; if (slider.classList.contains('sliderPercentage')){ value+='%'; } else if (slider.classList.contains('sliderDegree')) { value = '0.'+value+'°'; } if (slider.id ==="brakeBalance" || slider.id ==="powerDistribution"){ slider.parentElement.querySelector('.slider-value-front').innerText = value + ' Front'; slider.parentElement.querySelector('.slider-value-rear').innerText = (100 - this.value) + ' Rear'; } else{ this.previousElementSibling.innerText = value; } } }); } // handle selectors function updateBrands(disciplineId) { fetch(`/Motorfest/ProSettings/AddCarProSettings?handler=LoadBrands&vCatId=${disciplineId}`) .then(response => response.json()) .then(data => { let brandSelect = $('#brand'); brandSelect.html('<option value="">Select Brand</option>' + data.map(brand => `<option value="${brand['id']}">${brand['name']}</option>` ).join('')); if(brandSelect.children('option').length > 1){ updateModelList(disciplineId, brandSelect.find('option').eq(1).val()); } }); } function updateModelList(disciplineId, brandId) { fetch(`/Motorfest/ProSettings/AddCarProSettings?handler=LoadVehicles&vCatId=${disciplineId}&brandId=${brandId}`) .then(response => response.json()) .then(data => { let vehicleSelect = $('#model'); vehicleSelect .html('<option value="">Select Model</option>' + data .map(vehicle =>`<option value="${vehicle['id']}">${vehicle['modelName']}</option>`) .join('') ); vehicleSelect.change(function () { let selectedVehicle = $(this).children("option:selected").val(); updatePowerDistribution(data, selectedVehicle); }); }); } function updatePowerDistribution(vehicleData, selectedVehicleId) { if (selectedVehicleId !== "") { let selectedVehicleObj = vehicleData.find(vehicle => vehicle['id'] === selectedVehicleId); if (selectedVehicleObj && selectedVehicleObj['transmission'] === '4wd') { $('#powerDistribution').prop('disabled', false); } else { $('#powerDistribution').prop('disabled', true); } } else { $('#powerDistribution').prop('disabled', true); } } </script>
#include "hzpch.h" #include "GameObject.h" #include "Components/Transform.h" #include "Components/CameraComponent.h" #include "UUID.h" #include <glm/gtc/matrix_transform.hpp> namespace Hazel { GameObject::GameObject(const std::shared_ptr<Scene>& ps, const entt::entity & entity, const std::string& name) : m_Scene(ps), m_InstanceId(entity), m_Name(name) { m_ID = std::make_shared<UUID>(); } GameObject::GameObject(const std::shared_ptr<Scene>& ps, const entt::entity& entity, const uint64_t& id, const std::string& name) : m_Scene(ps), m_InstanceId(entity), m_Name(name) { m_ID = std::make_shared<UUID>(); m_ID->SetId(id); } glm::vec3 GameObject::GetPosition() { HAZEL_ASSERT(HasComponent<Transform>(), "GameObject Missing TransformComponent"); return GetComponent<Transform>().Translation; } glm::vec3 GameObject::GetRotation() { HAZEL_ASSERT(HasComponent<Transform>(), "GameObject Missing TransformComponent"); return GetComponent<Transform>().Rotation; } glm::vec3 GameObject::GetPosition() const { HAZEL_ASSERT(HasComponent<Transform>(), "GameObject Missing TransformComponent"); return GetComponent<Transform>().Translation; } void GameObject::SetPosition(const glm::vec3& p) { HAZEL_ASSERT(HasComponent<Transform>(), "GameObject Missing TransformComponent"); GetComponent<Transform>().Translation = p; } glm::mat4 GameObject::GetTransformMat() { HAZEL_ASSERT(HasComponent<Transform>(), "GameObject Missing TransformComponent"); return GetComponent<Transform>().GetTransformMat(); } glm::mat4 GameObject::GetTransformMat() const { HAZEL_ASSERT(HasComponent<Transform>(), "GameObject Missing TransformComponent"); return GetComponent<Transform>().GetTransformMat(); } void GameObject::SetTransformMat(const glm::mat4& trans) { HAZEL_ASSERT(HasComponent<Transform>(), "GameObject Missing TransformComponent"); return GetComponent<Transform>().SetTransformMat(trans); } }
package lt.artsysoft.compiler.interpreter; import lt.artsysoft.compiler.analyzer.AnalyzerConfParseHelper; import lt.artsysoft.compiler.beans.Variable; import lt.artsysoft.compiler.beans.classifiers.VariableTypes; import lt.artsysoft.compiler.semantic_analizer.SemanticAnalizer; import lt.artsysoft.compiler.semantic_analizer.tables.VariablesTable; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Map; import java.util.TreeMap; /** * Created with IntelliJ IDEA. * User: Marik * Date: 13.12.25 * Time: 13.24 * To change this template use File | Settings | File Templates. */ public class InterpreterHelper { public static TreeMap<String, Variable> copyVariablesMap (TreeMap<String, Variable> mapToCopy) { TreeMap<String, Variable> copy = new TreeMap<>(); for(Map.Entry<String,Variable> entry : mapToCopy.entrySet()){ copy.put(entry.getKey(), new Variable(entry.getValue())); } return copy; } protected static boolean notOperation(String param1) { return !Boolean.parseBoolean(param1); } protected static boolean conjunctionOperation(String param1, String param2) { return Boolean.parseBoolean(param1) && Boolean.parseBoolean(param2); } protected static boolean disjunctionOperation(String param1, String param2) { return Boolean.parseBoolean(param1) || Boolean.parseBoolean(param2); } protected static Object sumOperation(String param1, String param2) { if (!isNumeric(param1) || !isNumeric(param2)) { param1 = removeQuotes(param1); param2 = removeQuotes(param2); return param1 + param2; } else if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) + Double.parseDouble(param2); } else { return Integer.parseInt(param1) + Integer.parseInt(param2); } } private static String removeQuotes (String param) { String returnValue = param; if ((param.startsWith("\"") && param.endsWith("\"")) || (param.startsWith("'") && param.endsWith("'"))) { returnValue = param.substring(1, param.length() - 1); } return returnValue; } protected static Object minusOperation(String param1, String param2) { if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) - Double.parseDouble(param2); } else { return Integer.parseInt(param1) - Integer.parseInt(param2); } } protected static boolean greaterOperation(String param1, String param2) { if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) > Double.parseDouble(param2); } else { return Integer.parseInt(param1) > Integer.parseInt(param2); } } protected static boolean greaterEqOperation(String param1, String param2) { if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) >= Double.parseDouble(param2); } else { return Integer.parseInt(param1) >= Integer.parseInt(param2); } } protected static boolean equalOperation(String param1, String param2) { if (param1.equals("true") || param1.equals("false")) { return Boolean.parseBoolean(param1) == Boolean.parseBoolean(param2); } else if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) == Double.parseDouble(param2); } else { try { return Integer.parseInt(param1) == Integer.parseInt(param2); } catch (NumberFormatException ex) { return param1.equals(param2); } } } protected static boolean notEqualOperation(String param1, String param2) { if (param1.equals("true") || param1.equals("false")) { return Boolean.parseBoolean(param1) != Boolean.parseBoolean(param2); } else if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) != Double.parseDouble(param2); } else { try { return Integer.parseInt(param1) != Integer.parseInt(param2); } catch (NumberFormatException ex) { return !param1.equals(param2); } } } protected static boolean lessOperation(String param1, String param2) { if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) <= Double.parseDouble(param2); } else { return Integer.parseInt(param1) < Integer.parseInt(param2); } } protected static boolean lessEqOperation(String param1, String param2) { if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) <= Double.parseDouble(param2); } else { return Integer.parseInt(param1) <= Integer.parseInt(param2); } } protected static Object multiplyOperation(String param1, String param2) { if (param1.lastIndexOf(".") != -1 || param2.lastIndexOf(".") != -1) { return Double.parseDouble(param1) * Double.parseDouble(param2); } else { return Integer.parseInt(param1) * Integer.parseInt(param2); } } public static void writeFuncOperation(String functionName, LinkedList<String> parametersStack, int size) { if (parametersStack.isEmpty()) { System.out.println(); } else { for (int i = parametersStack.size()-size; i < parametersStack.size(); i++ ) { String param = prepareParamFromName (parametersStack.get(i), functionName); param = removeQuotes(param); System.out.println(param); } } } public static void readFuncOperation(String functionName, LinkedList<String> parametersStack, int size) { if (parametersStack.isEmpty()) { inputStr(); } else { for (int i = parametersStack.size()-size; i < parametersStack.size(); i++ ) { Variable currentVar = VariablesTable.getTable().get(functionName).get(parametersStack.get(i)); String userInput = inputStr(); currentVar.setCurrentValue(userInput); } } } public static String substringFuncOperation(String functionName, LinkedList<String> parametersStack) { int from = Integer.parseInt(prepareParamFromName(parametersStack.get(parametersStack.size()-2), functionName)); int to = Integer.parseInt(prepareParamFromName(parametersStack.getLast(), functionName)); String string = prepareParamFromName (parametersStack.get(parametersStack.size()-3), functionName); string = removeQuotes(string); String substring = string.substring(from,to); return substring; } public static String toStringFuncOperation(String functionName, LinkedList<String> parametersStack) { String original = prepareParamFromName (parametersStack.getLast(), functionName); if (original.equals("true") || original.equals("false")) { original = AnalyzerConfParseHelper.getLexemBank().get("$" + original).getValue(); } return original; } private static String inputStr() { String aLine = null; BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); try { aLine = input.readLine(); } catch (Exception e) { e.printStackTrace(); } return aLine; } private static boolean isNumeric(String str) { return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. } protected static String prepareParam (Object operand, String function) { if (VariablesTable.getTable().get(function).containsKey(((Variable) operand).getName())) { Variable varOperand = (Variable) operand; return VariablesTable.getTable().get(function).get(varOperand.getName()).getCurrentValue().toString(); } else { stripCodeMarkers((Variable)operand); return ((Variable) operand).getCurrentValue().toString(); } } private static void stripCodeMarkers(Variable operand) { String fullVal = operand.getCurrentValue().toString(); if (fullVal.startsWith("\"") || fullVal.startsWith("'")) fullVal = fullVal.substring(1, fullVal.length() - 1); operand.setCurrentValue(fullVal); } protected static String prepareParamFromName (String name, String function) { String parameterValue; if (VariablesTable.getTable().get(function).containsKey(name)) parameterValue = VariablesTable.getTable().get(function).get(name).getCurrentValue().toString(); else parameterValue = name; return parameterValue; } protected static void removeFromParametersStack (LinkedList<String> parametersStack, int nrOfItems) { for (int i = 0; i < nrOfItems; i++) { parametersStack.removeLast(); } } }
# frozen_string_literal: true RSpec.describe(HTTP::Auth0) do subject(:config) { described_class.config } let(:client_id) { Faker::Internet.unique.password } let(:client_secret) { Faker::Internet.unique.password } let(:domain) { Faker::Internet.domain_name(subdomain: true) } after { described_class.reset_config } it "defaults to ENV['AUTH0_CLIENT_ID'] for client_id" do expect(config.client_id).to(eq(ENV["AUTH0_CLIENT_ID"])) end it "defaults to ENV['AUTH0_CLIENT_SECRET'] for client_secret" do expect(config.client_secret).to(eq(ENV["AUTH0_CLIENT_SECRET"])) end it "defaults to ENV['AUTH0_DOMAIN'] for domain" do expect(config.domain).to(eq(ENV["AUTH0_DOMAIN"])) end context "when configuring by passing a config block" do describe ".configure(&config)" do before do described_class.configure do |config| config.client_id = client_id config.client_secret = client_secret config.domain = domain end end it { expect(config.client_id).to(eq(client_id)) } it { expect(config.client_secret).to(eq(client_secret)) } it { expect(config.domain).to(eq(domain)) } it { expect(config.logger).to(be_an_instance_of(Logger)) } it { expect(config.seconds_before_refresh).to(eq(60)) } end end context "when configuring using .config" do describe ".config" do before do config.client_id = client_id config.client_secret = client_secret config.domain = domain end it { expect(config.client_id).to(eq(client_id)) } it { expect(config.client_secret).to(eq(client_secret)) } it { expect(config.domain).to(eq(domain)) } it { expect(config.logger).to(be_an_instance_of(Logger)) } it { expect(config.seconds_before_refresh).to(eq(60)) } end end end
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>vmlist</title> <!-- Bootstrap --> <link href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> {% include "header.html" %} <div class="panel panel-default"> <!-- Default panel contents --> <div class="panel-heading"> <h3> 虚机列表 {% if host_ip %} ({{ host_ip }}) {% endif %} </h3> </div> <button type="button" class="btn btn-primary " data-toggle="modal" data-target="#addVmModal"> 新建虚机 </button> <div class="panel-body"> <table class="table table-bordered table-hover table-condensed"> <thead> <tr> <th>序号</th> <th>虚机ID</th> <th>网卡信息</th> <th>状态</th> <th>CPU(Core)</th> <th>内存(GB)</th> <th>备注</th> <th>操作</th> </tr> </thead> <tbody> {% for info in vm_info %} <tr> <td>{{ forloop.counter }}</td> <td>{{ info.vm_id }}</td> <td> <dl class="dl-horizontal"> {% for vmnet_obj in vmnet_info %} {% if vmnet_obj.virt_machine_id == info.id %} <dt>Name: {{ vmnet_obj.net_name }}</dt> <dd>Ip: {{ vmnet_obj.net_ip }}</dd> <dd>VmMac: {{ vmnet_obj.net_mac }}</dd> <dd>HostMac: {{ vmnet_obj.bridge_mac }}</dd> {% endif %} {% endfor %} </dl> </td> <td> {% if info.vm_status == '1' %} 运行中 {% elif info.vm_status == '3' %} 暂停 {% elif info.vm_status == '5' %} 关机 {% endif %} <td> {% if info.cpu_num %} {{ info.cpu_num }} {% endif %} </td> <td> {% if info.mem_num %} {{ info.mem_num }} {% endif %} </td> <td> {% if info.description %} {{ info.description }} {% endif %} </td> <td> <div class="btn-group"> <button type="button" class="btn btn-default start_btn" value="{{ info.id }}" >开机</button> </div> <div class="btn-group"> <button type="button" class="btn btn-danger shutdown_btn" value="{{ info.id }}">关机</button> </div> <div class="btn-group"> <button type="button" class="btn btn-info reboot_btn " value="{{ info.id }}">重启</button> </div> <div class="btn-group"> <button type="button" class="btn btn-warning suspend_btn" value="{{ info.id }}">暂停</button> </div> <div class="btn-group"> <button type="button" class="btn btn-success resume_btn" value="{{ info.id }}">恢复</button> </div> <div class="btn-group"> <button type="button" data-loading-text="Loading..." class="btn btn-default vnc_btn" value="{{ info.id }}">VNC</button> </div> <!--<div class="btn-group">--> <!--<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">--> <!--Action <span class="caret"></span>--> <!--</button>--> <!--<ul class="dropdown-menu">--> <!--<li><button class="btn btn-default start_btn" value="{{ info.id }}">start</button></li>--> <!--<li><button class="btn btn-default shutdown_btn" value="{{ info.id }}">shutdown</button></li>--> <!--<li><button class="btn btn-default reboot_btn" value="{{ info.id }}">reboot</button></li>--> <!--<li><button class="btn btn-default suspend_btn" value="{{ info.id }}">suspend</button></li>--> <!--<li><button class="btn btn-default resume_btn" value="{{ info.id }}">resume</button></li>--> <!--</ul>--> <!--</div>--> </td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation"> <ul class="pager"> <li> {% if vm_info.has_previous %} <a href="?page={{ vm_info.previous_page_number }}"> 上一页 </a> {% endif %} </li> <li> 第 {{ vm_info.number }} 页 ; 总共{{ vm_info.paginator.num_pages }}页. </li> <li> {% if vm_info.has_next %} <a href="?page={{ vm_info.next_page_number }}"> 下一页 </a> {% endif %} </li> </ul> </nav> </div> </div> <div class="modal fade" id="addVmModal" tabindex="-1" role="dialog" aria-labelledby="addVmLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="addVmLabel">新建虚机</h4> </div> <div class="modal-body"> <form class="form-horizontal"> <div class="form-group"> <label for="vmid" class="col-sm-2 control-label">虚机名称</label> <div class="col-sm-10"> <input type="text" class="form-control" id="vmid" > </div> </div> <div class="form-group"> <label for="ostype" class="col-sm-2 control-label">系统版本</label> <div class="col-sm-10"> <input type="text" class="form-control" id="ostype" > </div> </div> <div class="form-group"> <label for="cpucores" class="col-sm-2 control-label">cpu</label> <div class="col-sm-10"> <input type="text" class="form-control" id="cpucores" > </div> </div> <div class="form-group"> <label for="mem" class="col-sm-2 control-label">内存</label> <div class="col-sm-10"> <input type="text" class="form-control" id="mem" > </div> </div> <div class="form-group"> <label for="disk" class="col-sm-2 control-label">磁盘</label> <div class="col-sm-10"> <input type="text" class="form-control" id="disk" > </div> </div> <div class="form-group"> <label for="cdrom" class="col-sm-2 control-label">CD-ROM</label> <div class="col-sm-10"> <input type="text" class="form-control" id="cdrom" > </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary add_btn">提交</button> </div> </div> </div> </div> </div> <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) --> <script src="/static/bootstrap-3.3.7-dist/js/jquery.min.js"></script> <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 --> <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <script> $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); </script> <script> $(".start_btn").click(function(e) { e.preventDefault(); var r=confirm("确定开机"); if (r==true) { $.ajax({ type: "POST", url: "/start-vm/", data: { id: $(this).val(), }, success: function(result) { alert('ok'); }, error: function(result) { alert('error'); } }); } }); </script> <script> $(".reboot_btn").click(function(e) { e.preventDefault(); var r=confirm("确定重启"); if (r==true) { $.ajax({ type: "POST", url: "/reboot-vm/", data: { id: $(this).val(), }, success: function (result) { alert('ok'); }, error: function (result) { alert('error'); } }); } }); </script> <script> $(".shutdown_btn").click(function(e) { e.preventDefault(); var r=confirm("确定关机"); if (r==true) { $.ajax({ type: "POST", url: "/shutdown-vm/", data: { id: $(this).val(), }, success: function (result) { alert('ok'); }, error: function (result) { alert('error'); } }); } }); </script> <script> $(".suspend_btn").click(function(e) { e.preventDefault(); var r=confirm("确定暂停"); if (r==true) { $.ajax({ type: "POST", url: "/suspend-vm/", data: { id: $(this).val(), }, success: function (result) { alert('ok'); }, error: function (result) { alert('error'); } }); } }); </script> <script> $(".resume_btn").click(function(e) { e.preventDefault(); var r=confirm("确定恢复"); if (r==true) { $.ajax({ type: "POST", url: "/resume-vm/", data: { id: $(this).val(), }, success: function (result) { alert('ok'); }, error: function (result) { alert('error'); } }); } }); </script> <script> $(".vnc_btn").click(function(e) { e.preventDefault(); { $.ajax({ type: "POST", url: "/vnc-vm/", data: { id: $(this).val(), }, success: function (result) { // alert('ok'); window.open(result) }, error: function (result) { alert('error'); } }); } }); </script> </body> </html>
// package.json var name = "anywidget"; var version = "0.7.1"; // src/widget.js function is_href(str) { return str.startsWith("http://") || str.startsWith("https://"); } async function load_css_href(href, anywidget_id) { let prev = document.querySelector(`link[id='${anywidget_id}']`); if (prev) { let newLink = ( /** @type {HTMLLinkElement} */ prev.cloneNode() ); newLink.href = href; newLink.addEventListener("load", () => prev?.remove()); prev.after(newLink); return; } return new Promise((resolve) => { let link = Object.assign(document.createElement("link"), { rel: "stylesheet", href, onload: resolve }); document.head.appendChild(link); }); } function load_css_text(css_text, anywidget_id) { let prev = document.querySelector(`style[id='${anywidget_id}']`); if (prev) { prev.textContent = css_text; return; } let style = Object.assign(document.createElement("style"), { id: anywidget_id, type: "text/css" }); style.appendChild(document.createTextNode(css_text)); document.head.appendChild(style); } async function load_css(css, anywidget_id) { if (!css) return; if (is_href(css)) return load_css_href(css, anywidget_id); return load_css_text(css, anywidget_id); } async function load_esm(esm) { if (is_href(esm)) { return import( /* webpackIgnore: true */ esm ); } let url = URL.createObjectURL(new Blob([esm], { type: "text/javascript" })); let widget; try { widget = await import( /* webpackIgnore: true */ url ); } catch (e) { console.log(e); throw e; } URL.revokeObjectURL(url); return widget; } function extract_context(view) { let model = { get: view.model.get.bind(view.model), set: view.model.set.bind(view.model), save_changes: view.model.save_changes.bind(view.model), send: view.model.send.bind(view.model), // @ts-expect-error on(name2, callback) { view.model.on(name2, callback, view); }, off(name2, callback) { view.model.off(name2, callback, view); }, widget_manager: view.model.widget_manager }; return { model, el: view.el }; } function widget_default({ DOMWidgetModel, DOMWidgetView }) { class AnyModel extends DOMWidgetModel { static model_name = "AnyModel"; static model_module = name; static model_module_version = version; static view_name = "AnyView"; static view_module = name; static view_module_version = version; /** @param {Parameters<InstanceType<DOMWidgetModel>["initialize"]>} args */ initialize(...args) { super.initialize(...args); this.on("change:_css", () => { let id = this.get("_anywidget_id"); if (!id) return; console.debug(`[anywidget] css hot updated: ${id}`); load_css(this.get("_css"), id); }); this.on("change:_esm", async () => { let id = this.get("_anywidget_id"); if (!id) return; console.debug(`[anywidget] esm hot updated: ${id}`); let views = ( /** @type {unknown} */ Object.values(this.views ?? {}) ); for await ( let view of /** @type {Promise<AnyView>[]} */ views ) { let widget = await load_esm(this.get("_esm")); try { await view._anywidget_cached_cleanup(); } catch (e) { console.warn("[anywidget] error cleaning up previous module.", e); view._anywidget_cached_cleanup = () => { }; } this.off(null, null, view); view.$el.empty(); let cleanup = await widget.render(extract_context(view)); view._anywidget_cached_cleanup = cleanup ?? (() => { }); } }); } /** * @param {Record<string, any>} state * * We override to support binary trailets because JSON.parse(JSON.stringify()) doesnt * propeprty clone binary data (it just returns an empty object). * * https://github.com/jupyter-widgets/ipywidgets/blob/47058a373d2c2b3acf101677b2745e14b76dd74b/packages/base/src/widget.ts#L562-L583 */ serialize(state) { let serializers = ( /** @type {DOMWidgetModel} */ this.constructor.serializers || {} ); for (let k of Object.keys(state)) { try { let serialize = serializers[k]?.serialize; if (serialize) { state[k] = serialize(state[k], this); } else { state[k] = structuredClone(state[k]); } if (typeof state[k]?.toJSON === "function") { state[k] = state[k].toJSON(); } } catch (e) { console.error("Error serializing widget state attribute: ", k); throw e; } } return state; } } class AnyView extends DOMWidgetView { async render() { await load_css(this.model.get("_css"), this.model.get("_anywidget_id")); let widget = await load_esm(this.model.get("_esm")); let cleanup = await widget.render(extract_context(this)); this._anywidget_cached_cleanup = cleanup ?? (() => { }); } /** @type {() => Promise<void> | void} */ _anywidget_cached_cleanup() { } async remove() { await this._anywidget_cached_cleanup(); return super.remove(); } } return { AnyModel, AnyView }; } // src/index.js define(["@jupyter-widgets/base"], widget_default);
package leet import ( "testing" ) func maxSubarrayLength(nums []int, k int) int { l, r := 0, 0 max := 1 nmap := make(map[int]int) for l < len(nums) { nmap[nums[l]] += 1 for nmap[nums[l]] > k { nmap[nums[r]] -= 1 r += 1 } if l-r+1 > max { max = l - r + 1 } l++ } return max } func Test2958Ex1(t *testing.T) { res := maxSubarrayLength([]int{1, 11}, 2) want := 2 if res != want { t.Fatalf("Got: '%v'; Want: '%v'", res, want) } } func Test2958Ex2(t *testing.T) { res := maxSubarrayLength([]int{1, 2, 3, 1, 2, 3, 1, 2}, 2) want := 6 if res != want { t.Fatalf("Got: '%v'; Want: '%v'", res, want) } } func Test2958Ex3(t *testing.T) { res := maxSubarrayLength([]int{1}, 2) want := 1 if res != want { t.Fatalf("Got: '%v'; Want: '%v'", res, want) } } func Test2958Ex4(t *testing.T) { res := maxSubarrayLength([]int{2, 2, 3}, 1) want := 2 if res != want { t.Fatalf("Got: '%v'; Want: '%v'", res, want) } }
import React, { useState } from "react"; import styled from "styled-components"; import "./accountIndex.css"; import { LoginForm } from "./loginForm"; import { SignupForm } from "./signupForm"; import { motion } from "framer-motion"; import { AccountContext } from "./accountContext"; import logo from "../../assets/gabilogo.png"; const BoxContainer = styled.div` width: 280px; min-height: 550px; display: flex; flex-direction: column; border-radius: 19px; background-color: #fff; box-shadow: 0 0 2px rgba(15, 15, 15, 0.28); position: relative; overflow: hidden; background: rgb(254, 204, 44); @media only screen and (max-width: 480px) { width: 300px; height: 600px; top: -20%; } `; const TopContainer = styled.div` width: 100%; height: 250px; display: flex; flex-direction: column; justify-content: flex-end; padding: 0 1.8em; padding-bottom: 5em; background: rgb(254, 204, 44); `; const BackDrop = styled(motion.div)` width: 160%; height: 550px; position: absolute; display: flex; flex-direction: column; border-radius: 50%; transform: rotate(60deg); top: -290px; left: -70px; background: white; `; const HeaderContainer = styled.div` width: 100%; display: flex; flex-direction: column; `; const HeaderText = styled.h2` font-size: 25px; font-weight: 600; line-height: 1.24; color: #fff; z-index: 10; margin: 0; color: black; `; const SmallText = styled.h5` color: black; font-weight: 500; font-size: 11px; z-index: 10; margin: 0; margin-top: 7px; @media only screen and (max-width: 480px) { font-size: 13px; } `; const InnerContainer = styled.div` width: 100%; display: flex; flex-direction: column; padding: 0 1.8em; background: rgb(254, 204, 44); `; const backdropVariants = { expanded: { width: "233%", height: "1050px", borderRadius: "20%", transform: "rotate(60deg)", }, collapsed: { width: "160%", height: "550px", borderRadius: "50%", transform: "rotate(60deg)", }, }; const expandingTransition = { type: "spring", duration: 2.5, stiffness: 30, }; export function AccountBox(props) { const [isExpanded, setExpanded] = useState(false); const [active, setActive] = useState("signin"); const playExpandedAnimation = () => { setExpanded(true); setTimeout(() => { setExpanded(false); }, expandingTransition.duration * 1000 - 1500); }; const switchToSignup = () => { playExpandedAnimation(); setTimeout(() => { setActive("signup"); }, 1000); }; const switchToSignin = () => { playExpandedAnimation(); setTimeout(() => { setActive("signin"); }, 1000); }; const contextValue = { switchToSignup, switchToSignin }; return ( <AccountContext.Provider value={contextValue}> <BoxContainer className="boxcontainer"> <TopContainer> <BackDrop initial={false} animate={isExpanded ? "expanded" : "collapsed"} variants={backdropVariants} transition={expandingTransition} /> {active === "signin" && ( <HeaderContainer> <img style={{ zIndex: "10000", width: "175px", padding: "5px", }} src={logo} alt="logo" /> <HeaderText> Dobrodosli </HeaderText> <SmallText> Molimo vas, prijavite se </SmallText> </HeaderContainer> )} {active === "signup" && ( <HeaderContainer> <img style={{ zIndex: "10000", width: "175px", padding: "5px" }} src={logo} alt="logo" /> <HeaderText> Dobrodosli </HeaderText> <SmallText> Molimo vas, registrujte se </SmallText> </HeaderContainer> )} </TopContainer> <InnerContainer> {active === "signin" && <LoginForm />} {active === "signup" && <SignupForm />} </InnerContainer> </BoxContainer> </AccountContext.Provider> ); }
```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Mi primera página en HTML</title> </head> <body> <h1>Título de la página</h1> <p>Mi primer Iframe en HTML</p> <iframe src="https://linkedin.com" width="500" height="800"></iframe> </body> </html> ``` Este fragmento de código HTML incluye una etiqueta `<iframe>` que se utiliza para incrustar contenido externo en una página web mediante una URL. Aquí está la explicación detallada: ```html <iframe src="https://linkedin.com" width="500" height="800"></iframe> ``` - `<iframe>`: Etiqueta que define un marco en línea (iframe) en HTML. - `src="https://linkedin.com"`: Atributo que especifica la fuente (URL) del contenido que se debe cargar dentro del iframe. En este caso, la URL es "https://linkedin.com", por lo que el iframe mostrará el contenido de LinkedIn. - `width="500"` y `height="800"`: Atributos que especifican el ancho y la altura del iframe en píxeles. En este caso, el iframe tendrá un ancho de 500 píxeles y una altura de 800 píxeles. Definiciones cortas de las etiquetas: - `<iframe>`: Etiqueta que define un marco en línea en HTML, utilizado para incrustar contenido externo en una página web. - `src`: Atributo que especifica la fuente (URL) del contenido que se debe cargar dentro del iframe. - `width` y `height`: Atributos que especifican el ancho y la altura del iframe, respectivamente. En resumen, este código HTML crea un iframe que carga el contenido de la URL "https://linkedin.com" con un ancho de 500 píxeles y una altura de 800 píxeles.
import { hashPassword, comparePasswords, createJWT, validateJWT, httpMethod, isJWTVerifyPayload, getUserFromCookie, validateCookie, } from './auth'; import bcrypt from 'bcrypt'; import { NextApiRequest, NextApiResponse } from 'next'; import { assertType } from '@/helpers/utils'; import { SignJWT, jwtVerify } from 'jose'; import { PrismaClient } from '@prisma/client'; import { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'; import { accessEnv } from './access-env'; describe('Authentication utilities', () => { let originalEnv: NodeJS.ProcessEnv; beforeEach(() => { originalEnv = process.env; process.env = { ...originalEnv, JWT_SECRET: 'testSecret', COOKIE_NAME: 'testCookie', }; }); afterEach(() => { process.env = originalEnv; jest.clearAllMocks(); }); it('should hash a given password', async () => { const bcryptSpy = jest.spyOn(bcrypt, 'hash'); const password = 'password'; await hashPassword(password); expect(bcryptSpy).toHaveBeenCalledWith(password, 10); }); it('should correctly compare a password and its hash', async () => { const password = 'password'; const hashedPassword = await hashPassword(password); const result = await comparePasswords(password, hashedPassword); expect(result).toBeTruthy(); }); it('createJWT should create a JWT with the user payload', async () => { const user = { id: '1', email: '[email protected]' }; const jwt = await createJWT(user); const jwtComponents = jwt.split('.'); expect(jwtComponents).toHaveLength(3); }); it('should create a JWT with correct payload and headers', async () => { const user = { id: '1', email: '[email protected]' }; const jwt = await createJWT(user); const decodedJwt: any = await jwtVerify( jwt, new TextEncoder().encode(accessEnv('JWT_SECRET')) ); expect(decodedJwt.payload.payload).toEqual(user); }); it('should correctly validate the JWT', async () => { const user = { id: '1', email: '[email protected]' }; const jwt = await createJWT(user); const decodedJwt = await validateJWT(jwt); expect(decodedJwt.payload).toEqual(user); }); it('should throw error for invalid JWT payload', async () => { // Create a JWT with missing 'email' field in the payload const secret = new TextEncoder().encode(accessEnv('JWT_SECRET')); const iat = Math.floor(Date.now() / 1000); const exp = iat + 60 * 60 * 24 * 7; const invalidPayload = { id: '1' }; const jwt = await new SignJWT({ payload: invalidPayload }) .setProtectedHeader({ alg: 'HS256', typ: 'JWT' }) .setExpirationTime(exp) .setIssuedAt(iat) .setNotBefore(iat) .sign(secret); await expect(validateJWT(jwt)).rejects.toThrow('Unexpected JWT payload'); }); it('should correctly retrieve the user', async () => { const user = { id: '1', email: '[email protected]' }; const jwt = await createJWT(user); const cookies = assertType<ReadonlyRequestCookies>({ get: (_name: string) => { return { value: jwt }; }, }); const mockDb = assertType<PrismaClient>({ user: { findUniqueOrThrow: jest.fn().mockResolvedValue(user), }, }); const retrievedUser = await getUserFromCookie({ cookies, db: mockDb, includeProjects: false, }); expect(retrievedUser).toEqual(user); }); it('should throw error when no JWT present', async () => { const cookies = assertType<ReadonlyRequestCookies>({ get: (_name: string) => { return null; }, }); const mockDb = assertType<PrismaClient>({ user: { findUniqueOrThrow: jest.fn(), }, }); await expect( getUserFromCookie({ cookies, db: mockDb, includeProjects: false }) ).rejects.toThrow('No JWT'); }); it('getUserFromCookie should throw error when user not found', async () => { const user = { id: '1', email: '[email protected]' }; const jwt = await createJWT(user); const cookies = assertType<ReadonlyRequestCookies>({ get: (_name: string) => { return { value: jwt }; }, }); const mockDb = assertType<PrismaClient>({ user: { findUniqueOrThrow: jest .fn() .mockRejectedValue(new Error('No User found')), }, }); await expect( getUserFromCookie({ cookies, db: mockDb, includeProjects: false }) ).rejects.toThrowError(new Error('No User found')); }); it('should identify valid and invalid payloads', () => { const validPayload = { payload: { id: '1', email: '[email protected]' }, exp: 1234567890, iat: 1234567890, nbf: 1234567890, }; const invalidPayload = { ...validPayload, exp: 'not-a-number' }; expect(isJWTVerifyPayload(validPayload)).toBeTruthy(); expect(isJWTVerifyPayload(invalidPayload)).toBeFalsy(); }); it('should validate HTTP method correctly', async () => { const handler = jest.fn(); const req = assertType<NextApiRequest>({ method: 'GET' }); const res = assertType<NextApiResponse>({ status: jest.fn().mockReturnThis(), json: jest.fn(), }); const wrappedHandler = httpMethod('GET')(handler); await wrappedHandler(req, res); expect(handler).toBeCalledTimes(1); expect(res.status).not.toBeCalled(); wrappedHandler(assertType<NextApiRequest>({ ...req, method: 'POST' }), res); expect(res.status).toBeCalledWith(405); }); it('should validate the cookie correctly', () => { const cookieName = accessEnv('COOKIE_NAME'); const req = assertType<NextApiRequest>({ cookies: { [cookieName]: 'testCookieValue', }, }); expect(validateCookie(req)).toEqual('testCookieValue'); }); it('should throw an error if the cookie does not exist', () => { const req = assertType<NextApiRequest>({ cookies: {}, }); expect(() => validateCookie(req)).toThrowError(new Error('Not authorized')); }); });
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <head> <meta charset="UTF-8"> <title>批量导入企业</title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <link rel="shortcut icon" type="image/x-icon" th:href="@{/favicon.ico}"/> <link rel="stylesheet" th:href="@{/lib/layui/css/layui.css}"> <link rel="stylesheet" th:href="@{/css/common.css}"> <link rel="stylesheet" th:href="@{/css/animate.min.css}"> </head> <body> <div class="page-loading"> <div class="rubik-loader"></div> </div> <div class="z-body animated fadeIn"> <form class="layui-form"> <div class="layui-upload"> <div class="layui-form-item"> <div class="layui-input-inline layui-col-md1"> <div class="layui-input-inline"> <input type="text" class="layui-input" id="year" name="year" placeholder="年份" lay-verify="required"> </div> </div> <div class="layui-input-inline"> <select id="cityCode" name="cityCode" lay-filter="cityCode" lay-verify="required"> <option value="">请选择实际城市</option> <option th:each="city : ${citys}" th:value="${city.cityCode}" th:text="${city.cityName}"> </option> </select> </div> <div class="layui-input-inline"> <select id="countyId" name="countyId" lay-filter="countyId" lay-verify="required"> <option value="">请选择实际区县</option> <option th:each="county : ${countys}" th:value="${county.countyId}" th:text="${county.countyName}"> </option> </select> </div> <div class="layui-input-inline"> <button class="layui-btn layui-btn-normal" id="filesUp" type="button">选择多文件</button> </div> </div> <div class="layui-form-item" style="margin-top: 10px"> <div class="layui-upload-list"> <table class="layui-table"> <thead> <tr><th>文件名</th> <th>大小</th> <th>状态</th> <th>操作</th> </tr></thead> <tbody id="demoList"></tbody> </table> </div> </div> <div class="layui-form-item"> <div class="layui-inline" style="width: 350px;"> <button class="layui-btn" id="filesUpAction" type="button" lay-filter="edit" lay-submit="">开始上传</button>&nbsp;&nbsp;&nbsp; <span id="msg" name="msg"></span> </div> </div> </div> <div class="layui-input-inline"> <button class="layui-btn layui-btn-warm" type="button" lay-filter="down" lay-submit="">模板下载</button>&nbsp;&nbsp;&nbsp; </div> <hr class="layui-bg-gray"> <blockquote class="layui-elem-quote layui-quote-nm"> <span style="color: red">注意:</span>请把文件中的字段相应填补,如果为数字填为“0”,如果是文字请填“无”。 </blockquote> </form> </div> <script th:src="@{/lib/jquery/jquery.min.js}"></script> <script th:src="@{/lib/layui/layui.js}"></script> <script th:src="@{/js/common.js}"></script> <script> layui.use(['table','form', 'element','upload'], function () { var table = layui.table //表格 ,form = layui.form //form表单 ,element = layui.element ,upload = layui.upload; //多文件列表示例 form.on('submit(down)', function (form) { window.location.href ='/file/temple/down?name='+ '企业'; }); var demoListView = $('#demoList') ,uploadListIns = upload.render({ elem: '#filesUp' ,url: '/file/upload/factory' ,accept: 'file' ,exts: 'xls|xlsx' //只允许上传压缩文件 ,size: 5000 //限制文件大小,单位 KB ,multiple: true ,auto: false ,bindAction: '#filesUpAction' ,before: function(obj){ this.data={'year':$('#year').val(),'countyId':$('#countyId').val()};//关键代码 } ,choose: function(obj){ var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列 //读取本地文件 obj.preview(function(index, file, result){ var tr = $(['<tr id="upload-'+ index +'">' ,'<td>'+ file.name +'</td>' ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>' ,'<td>等待上传</td>' ,'<td>' // ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>' ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>' ,'</td>' ,'</tr>'].join('')); //单个重传 tr.find('.demo-reload').on('click', function(){ obj.upload(index, file); }); //删除 tr.find('.demo-delete').on('click', function(){ delete files[index]; //删除对应的文件 tr.remove(); uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选 }); demoListView.append(tr); }); } ,done: function(res, index, upload){ if(res.code == 0){ //上传成功 layer.msg(res.msg,{icon: 6, time:1000}); $("#msg").html(res.msg) $('#msg').css("border", "5px solid green"); var tr = demoListView.find('tr#upload-'+ index) ,tds = tr.children(); tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>'); tds.eq(3).html(''); //清空操作 return delete this.files[index]; //删除文件队列已经上传成功的文件 }else{ this.error(res, index, upload); } } ,error: function(res,index, upload){ layer.msg(res.msg,{icon: 6, time:1000}); $("#msg").html(res.msg) $('#msg').css("border", "5px solid red"); var tr = demoListView.find('tr#upload-'+ index) ,tds = tr.children(); tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>'); tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传 } }); }) </script> </body> </html>
const { ethers } = require("hardhat") const BigNumber = require('bignumber.js'); const { COUNT, INITIALINDEX, MNEMONIC } = require("../hardhat.config.perf"); const { expect } = require("chai"); const hre = require("hardhat"); const accountsNum = parseInt(process.env.ACCOUNTSNUM) const depositAmount = parseFloat(process.env.DEPOSITAMOUNT) const minAmount = parseFloat(process.env.MINAMOUNT) const interval = COUNT let contractAddress if (hre.network.name === "gw_testnet_v1") { contractAddress = "0x9e593da2fb96abf2bd5483e7fc417508df6ea40e" } else if (hre.network.name === "gw_alphanet_v1") { contractAddress = "0x3F83d35De751C6CaF49665235590F5f4C4Db97dD" } else if (hre.network.name === "axon_alphanet") { contractAddress = "0x3abBB0D6ad848d64c8956edC9Bf6f18aC22E1485" } else if (hre.network.name === "fantom_testnet") { contractAddress = "0xbcab4f17Cf6Ea56326c4A910b2a13CbaD9B0fc73" } describe("recharge", async function () { it("recharge", async function () { const gasPrice = await getSufficientGasPrice() const signers = await ethers.getSigners() const addressList = await getAddressList(accountsNum, interval, MNEMONIC) if (addressList.length > 1) { for (let i = 1; i < addressList.length; i++) { const ethValue = ethers.parseUnits((depositAmount * COUNT * 1.1).toString(), "ether") const balance = await ethers.provider.getBalance(addressList[i]) const count = await ethers.provider.getTransactionCount(addressList[i]) if ((balance - ethValue) >= BigInt(0)) { console.log(`account${i * interval + Number(process.env.INITIALINDEX)} ${addressList[i]} has sufficient balance: ${ethers.formatEther(balance)} eth >= ${ethers.formatEther(ethValue)} eth,nonce: ${count}`) } else { const value = "0x" + (ethValue - balance).toString(16) await transferWithReceipt(signers[0].address, addressList[i], gasPrice, value); const newBalance = await ethers.provider.getBalance(addressList[i]) console.log(`account${i * interval + Number(process.env.INITIALINDEX)} ${addressList[i]} balance: ${ethers.formatEther(newBalance)} eth,nonce: ${count}`) } } } const balance = await ethers.provider.getBalance(addressList[0]) const count = await ethers.provider.getTransactionCount(addressList[0]) console.log(`account${INITIALINDEX} ${addressList[0]} balance: ${ethers.formatEther(balance)} eth,nonce: ${count}`) }).timeout(180000) }) describe("deposit", function () { it("deposit", async function () { console.log(`deposit from account${INITIALINDEX}`) const signers = await ethers.getSigners() const recipients = signers.map((item) => { return item.address; }) await deposit(recipients, 50) }).timeout(120000) }) describe("withdraw", function () { it("withdraw", async function () { console.log(`withdraw from account${INITIALINDEX}`) const signers = await ethers.getSigners() const wallet = ethers.HDNodeWallet.fromPhrase(MNEMONIC, null, "m/44'/60'/0'/0/0") const gasPrice = await getSufficientGasPrice() const requestFnList = signers.map((signer) => () => ethers.provider.getBalance(signer.address)) const reply = await concurrentRun(requestFnList, 20, "查询所有账户余额") const requestFnList1 = signers.map((signer) => () => ethers.provider.getTransactionCount(signer.address)) const reply1 = await concurrentRun(requestFnList1, 20, "查询所有账户nonce") for (let i = 0; i < COUNT; i++) { let value = reply[i] - BigInt(21000) * BigInt(gasPrice) if (value > 0) { let nonce = "0x" + reply1[i].toString(16) await transfer(signers[i].address, wallet.address, gasPrice, "0x" + value.toString(16), nonce) } } }).timeout(240000) }) describe("check accounts balance", function () { let signers, reply before(async function () { this.timeout(60000); console.log(`check from account${INITIALINDEX}`) signers = await ethers.getSigners() const requestFnList = signers.map((signer) => () => ethers.provider.getBalance(signer.address)) reply = await concurrentRun(requestFnList, 20, "查询所有账户余额"); }); it("checkAndDeposit", async function () { let recipients = [] for (let i = 0; i < signers.length; i++) { const balance = ethers.formatEther(reply[i]); if (balance < minAmount && (i + INITIALINDEX) % 100 === 0) { console.error(`account${i + INITIALINDEX} ${signers[i].address} has insufficient balance: ${balance} eth < ${minAmount} eth`); } if (balance < minAmount) { recipients.push(signers[i].address); } } if (recipients.length > 0) { await deposit(recipients, 50) console.log(`${recipients.length} accounts with insufficient balance`) } }).timeout(120000) it("afterDeposit", async function () { let j = 0 for (let i = 0; i < signers.length; i++) { let balance = ethers.formatEther(reply[i]) if (balance < depositAmount) { console.error(`account${i + INITIALINDEX} ${signers[i].address} balance: ${balance} eth < ${depositAmount} eth`) } else { // console.log(`account${i + INITIALINDEX} ${signers[i].address} balance: ${balance} eth}`) j++ } } expect(j).to.be.equal(COUNT) }).timeout(30000) it("afterWithdraw", async function () { let j = 0 let gasPrice = await getSufficientGasPrice() for (let i = 0; i < signers.length; i++) { let balance = ethers.formatEther(reply[i]) let value = reply[i] - BigInt(21000) * BigInt(gasPrice) if (INITIALINDEX !== 0 && value > 0) { console.error(`account${i + INITIALINDEX} ${signers[i].address} balance: ${balance} eth > ${ethers.formatEther(BigInt(21000) * BigInt(gasPrice))} eth`) } else { // console.log(`account${i + INITIALINDEX} ${signers[i].address} balance: ${balance} eth`) j++ } } expect(j).to.be.equal(COUNT) }).timeout(30000) }) async function deposit(recipients, recipientSize) { const BatchTransfer = await ethers.getContractFactory("BatchTransfer"); const batchTransfer = await BatchTransfer.attach(contractAddress); const loopCount = Math.floor(recipients.length / recipientSize) for (let j = 0; j < loopCount; j++) { let tmpRecipients = [] for (let k = j * recipientSize; k < (j + 1) * recipientSize; k++) { tmpRecipients.push(recipients[k]) } const tx = await batchTransfer.getFunction("transfer").send(tmpRecipients, ethers.parseUnits(depositAmount.toString(), "ether"), { value: ethers.parseEther((recipientSize * depositAmount).toString()) }); await tx.wait(); } const remainingNum = recipients.length % recipientSize const remainingRecipients = [] for (let m = loopCount * recipientSize; m < loopCount * recipientSize + remainingNum; m++) { remainingRecipients.push(recipients[m]) } if (remainingRecipients.length > 0) { const tx = await batchTransfer.getFunction("transfer").send(remainingRecipients, ethers.parseUnits(depositAmount.toString(), "ether"), { value: ethers.parseEther((remainingNum * depositAmount).toString()) }); await tx.wait(); console.log("txHash:", tx.hash); } } async function getAddressList(accountsNum, interval, mnemonic) { const wallet = ethers.HDNodeWallet.fromPhrase(mnemonic, null, "m"); let addressList = [] const loopCount = Math.ceil(accountsNum / interval) for (let i = 0; i < loopCount; i++) { let sum = i * interval + Number(process.env.INITIALINDEX) let hdNodeNew = wallet.derivePath("m/44'/60'/0'/0/" + sum) addressList.push(hdNodeNew.address) } return addressList } async function transferWithReceipt(from, to, gasPrice, value) { const tx = await ethers.provider.send("eth_sendTransaction", [{ from, to, "gas": "0xc738", //51000 "gasPrice": gasPrice, "value": value, }]) await getTxReceipt(ethers.provider, tx, 100) } async function transfer(from, to, gasPrice, value, nonce) { await ethers.provider.send("eth_sendTransaction", [{ from, to, "gas": "0x5208", //21000 "gasPrice": gasPrice, "value": value, "nonce": nonce }]) } async function getTxReceipt(provider, txHash, attempts) { for (let i = 0; i < attempts; i++) { const receipt = await provider.getTransactionReceipt(txHash); if (receipt !== null) { return receipt; } await sleep(1000); } return null; } async function sleep(timeOut) { await new Promise(r => setTimeout(r, timeOut)); } async function getSufficientGasPrice() { const gasPrice = (await ethers.provider.getFeeData()).gasPrice console.log(`gas price: ${gasPrice} wei`) // Multiply by 1.2 and round const myGasPrice = (gasPrice * BigInt(12) + BigInt(5)) / BigInt(10) console.log(`my gas price: ${myGasPrice} wei`) return "0x" + myGasPrice.toString(16) } /** * 执行多个异步任务 * @param {*} fnList 任务列表 * @param {*} max 最大并发数限制 * @param {*} taskName 任务名称 */ async function concurrentRun(fnList = [], max = 5, taskName = "未命名") { if (!fnList.length) return; const replyList = []; // 收集任务执行结果 const maxRetry = 3; // 设置最大重试次数 const schedule = async (index, retryCount = 0) => { return new Promise(async (resolve, reject) => { const fn = fnList[index]; if (!fn) return resolve(); try { // 执行当前异步任务 replyList[index] = await fn(); // 执行完当前任务后,继续执行任务池的剩余任务 await schedule(index + max); resolve(); } catch (error) { if (retryCount < maxRetry) { console.log(`Task ${index} failed, retrying... Retry count: ${retryCount + 1}`); await schedule(index, retryCount + 1); resolve(); } else { console.error(`Task ${index} failed after ${maxRetry} attempts`); reject(error); } } }); }; // 任务池执行程序 const scheduleList = new Array(max) .fill(0) .map((_, index) => schedule(index)); // 使用 Promise.all 批量执行 await Promise.all(scheduleList); return replyList; } module.exports = { concurrentRun, getTxReceipt };
package main import ( "tafexpr/variablecontext" "testing" "github.com/stretchr/testify/assert" ) func SetupVariableContext() variablecontext.IVariableContext { v := &variablecontext.VariableContext{} v.Init(true) var context variablecontext.IVariableContext = v return context } func SetupMockVariableContext() variablecontext.IVariableContext { v := &variablecontext.MockVariableContext{} v.Init(true) var context variablecontext.IVariableContext = v return context } func TestVariableDeclaration(t *testing.T) { p := SetupParser() p.VariableContext = SetupVariableContext() assert.Equal(t, true, p.Parse("$myVar")) assert.Equal(t, 1, p.IntValue) } func TestVariableDeclaration2(t *testing.T) { p := SetupParser() p.VariableContext = SetupVariableContext() assert.Equal(t, true, p.Parse("$myVa2r")) assert.Equal(t, 1, p.IntValue) } func TestVariableParenthesisDeclaration(t *testing.T) { p := SetupParser() p.VariableContext = SetupVariableContext() assert.Equal(t, true, p.Parse("($myVar)")) assert.Equal(t, 1, p.IntValue) } func TestVariableArithmetics(t *testing.T) { p := SetupParser() p.VariableContext = SetupVariableContext() assert.Equal(t, true, p.Parse("1 + 2 + ($myVar) + 5 * 3")) assert.Equal(t, 1+2+1+5*3, p.IntValue) } func TestVariableDoubleArithmetics(t *testing.T) { p := SetupParser() p.VariableContext = SetupVariableContext() assert.Equal(t, true, p.Parse("(100.22 * (200.33 + 3090.11)) - (60.35 + (90/5.2) * ($myVar2 + 2*($myvar + 1))) + $myVar - $myVar")) b := almostEqual((100.22*(200.33+3090.11))-(60.35+(90/5.2)*(1+2*(1+1)))+1-1, p.DoubleValue) assert.Equal(t, true, b) } /*func TestVariableDeclarationWithParenthesis(t *testing.T) { p := SetupParser() assert.Equal(t, true, p.Parse("$myVar")) assert.Equal(t, 100+200+3090, p.IntValue) }*/
#!/usr/bin/python3 """ Prints square using '#' """ def print_square(size): """ function to print square of given size Args: size: size of square Raises: TypeError: when size is not a valid integer """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if size == 0: return for i in range(size): [print("#", end="") for j in range(size)] print("")
# TSON Patch > Statically typed JSON Patch operations ## Usage You have some kind of nested data that you want to work with. It could look something like this: ```typescript export type User = { id: string; name: { first: string; last?: string; } friends: { [from: string]: Array<{ name: string }> } }; ``` A mess to work with, right? Not anymore: ### Basic operations All operations are pure and return shallow copies #### Get ```typescript import * as tp from 'tson-patch' tp.get(user, ['friends', 'college', 0, 'name']) // Compiles just fine tp.get(user, ['friends', 'college', 0, 'age']) // COMPILE ERROR: 'age' doesn't exist in 'name' ``` #### Set ```typescript tp.set(user, ['friends', 'college', 0, 'name'], 'John') // Now `user.friends.chess[0].name === 'John'` tp.set(user, ['friends', 'college', 0], {name: 'John'}) // Exactly the same tp.set(user, ['friends', 'college', 0, 'name'], {name: 'Oops'}) // COMPILE ERROR (types don't match) ``` #### Remove ```typescript tp.remove(user, ['id']) // COMPILE ERROR ('id' is not nullable) tp.remove(user, ['name', 'last']) // '<User but without last name>' ``` #### Move ```typescript tp.move(user, ['id'], ['friends', 'college']) // COMPILE ERROR (Types don't match) tp.move(user, ['id'], ['friends', 'college', 0, 'name']) // OK ``` #### Swap ```typescript tp.swap(user, ['id'], ['friends', 'chess']) // COMPILE ERROR (Types don't match) tp.swap(user, ['id'], ['friends', 'chess', 0, 'name']) // OK ```
import { AddAccountRepository } from '../../../../data/protocols/db/account/add-account-repository' import { AccountModel } from '../../../../domain/models/account' import { AddAccountModel } from '../../../../domain/usecases/account/add-account' import { map, mapAccounts } from './account-mapper' import { LoadAccountByEmailRepository } from '../../../../data/protocols/db/account/load-account-by-email-repository' import { PrismaClient } from '@prisma/client' import { LoadAccountByIdRepository } from '../../../../data/protocols/db/account/load-account-by-id-repository' import { LoadAccountsRepository } from '../../../../data/protocols/db/account/load-accounts-repository' export class AccountPgRepository implements AddAccountRepository, LoadAccountByEmailRepository, LoadAccountByIdRepository, LoadAccountsRepository { constructor(private readonly prisma: PrismaClient) {} async add(account: AddAccountModel): Promise<AccountModel> { const create = await this.prisma.users.create({ data: { name: account.name, email: account.email, password: account.password, isadmin: account.isAdmin } }) return map(create) } async loadByEmail(email: string): Promise<AccountModel> { const account = await this.prisma.users.findFirst({ where: { email } }) return account && map(account) } async loadById(id: string): Promise<AccountModel> { const intId = Number(id) const result = await this.prisma.users.findUnique({ where: { id: intId }, include: { role: { select: { name: true } } } }) if (result) { return map(result) } } async load(): Promise<AccountModel[]> { const accounts = await this.prisma.users.findMany({ include: { role: { select: { name: true } } } }) return mapAccounts(accounts) } }
/* * Copyright (C) 2014 - 2017 Contributors as noted in the AUTHORS.md file * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.wegtam.tensei.agent.transformers import akka.testkit.TestActorRef import akka.util.ByteString import com.wegtam.tensei.adt.TransformerOptions import com.wegtam.tensei.agent.ActorSpec import com.wegtam.tensei.agent.transformers.BaseTransformer.{ PrepareForTransformation, ReadyToTransform, StartTransformation, TransformerResponse } class CastStringToLongTest extends ActorSpec { describe("CastStringToLong") { describe("with empty string") { it("should return None") { val actor = TestActorRef(CastStringToLong.props) actor ! PrepareForTransformation expectMsg(ReadyToTransform) actor ! StartTransformation(List(ByteString("")), new TransformerOptions(classOf[String], classOf[String])) val response = TransformerResponse(List(None), None.getClass) expectMsg(response) } } describe("with invalid number string") { it("should return None") { val actor = TestActorRef(CastStringToLong.props) actor ! PrepareForTransformation expectMsg(ReadyToTransform) actor ! StartTransformation(List(ByteString("foo")), new TransformerOptions(classOf[String], classOf[String])) val response = TransformerResponse(List(None), None.getClass) expectMsg(response) } } describe("with valid number string") { it("should return the number as Long value") { val actor = TestActorRef(CastStringToLong.props) actor ! PrepareForTransformation expectMsg(ReadyToTransform) actor ! StartTransformation(List(ByteString("123")), new TransformerOptions(classOf[String], classOf[String])) val response = TransformerResponse(List(123L), Long.getClass) expectMsg(response) } it("should return the numbers as Long values") { val actor = TestActorRef(CastStringToLong.props) actor ! PrepareForTransformation expectMsg(ReadyToTransform) actor ! StartTransformation(List(ByteString("123"), ByteString("456"), ByteString("789"), ByteString("-1")), new TransformerOptions(classOf[String], classOf[String])) val response = TransformerResponse(List(123L, 456L, 789L, -1L), Long.getClass) expectMsg(response) } } } }
import torch from torch import nn # EMBEDDINGS class TimeEmbd(nn.Module): """ Do the time embedding changing from a scalar value to a vector of size C (the amount of channels). The resulting vector will be added across the CHANNELS of the representation of the image. Input: - channels: integer stating the amount of channels in x. Output: - vector in R^C represented in [1, C, 1, 1] for convenience. """ def __init__(self, channels): super().__init__() self.C = channels def forward(self, t): """ Forward pass for the time embedding. Args: - t (torch.Tensor): Scalar time value. Returns: - torch.Tensor: Time embedding of shape [1, C, 1, 1]. """ omega = torch.arange(1, self.C // 2 + 1).to(t.device) t = t.unsqueeze(0) p1 = (omega * t).sin() p2 = (omega * t).cos() t_emb = torch.cat((p1, p2), 0) return t_emb.unsqueeze(-1).unsqueeze(-1) class GenreEmbd(nn.Module): """ Do the genre embedding for the network. Contrary to TimeEmbd, this embedding IS learnable. Args: - genres (int): Number of genres. - channels (int): Number of channels for embedding. """ def __init__(self, genres, channels): super().__init__() self.model = nn.Embedding(genres, channels) def forward(self, genre): """ Forward pass for the genre embedding. Args: - genre (torch.Tensor): Genre label. Returns: - torch.Tensor: Genre embedding of shape [1, C, 1, 1]. """ return self.model(genre)[:, ..., None, None] # SUBARCHITECTURES class UNet(nn.Module): """ Implementation of the UNet class for prediction of reconstruction of x0. Substitutes RecoverX0 written before. Takes xt as input and tries to recover x0. """ def __init__(self): super().__init__() # Define model blocks self.fatten = nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1) self.down1 = Down(64, 128, 80, 2048) self.down2 = Down(128, 256, 40, 1024) self.down3 = Down(256, 512, 20, 512) self.up1 = Up(512, 256, 10, 256) self.up2 = Up(256, 128, 20, 512) self.up3 = Up(128, 64, 40, 1024) self.thin = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1) # Define time embeddings self.t1 = TimeEmbd(64) self.t2 = TimeEmbd(128) self.t3 = TimeEmbd(256) self.t4 = TimeEmbd(512) # Define genre embedding self.g1 = GenreEmbd(8, 64) self.g2 = GenreEmbd(8, 128) self.g3 = GenreEmbd(8, 256) self.g4 = GenreEmbd(8, 512) # Apply He initialization of parameters self.apply(self._init_weights) def _init_weights(self, module): """ Initialize weights for convolutional layers. Args: - module (nn.Module): Layer module. """ if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu") if module.bias is not None: nn.init.constant_(module.bias, 0) def forward(self, x, genre, t): """ Forward pass for the UNet model. Args: - x (torch.Tensor): Input tensor. - genre (torch.Tensor): Genre embedding tensor. - t (torch.Tensor): Time embedding tensor. Returns: - torch.Tensor: Output tensor. """ x = self.fatten(x) d1 = self.down1(x + self.t1(t) + self.g1(genre)) d2 = self.down2(d1 + self.t2(t) + self.g2(genre)) d3 = self.down3(d2 + self.t3(t) + self.g3(genre)) u = self.up1(d3 + self.t4(t) + self.g4(genre)) u = self.up2(u + d2 + self.t3(t) + self.g3(genre)) u = self.up3(u + d1 + self.t2(t) + self.g2(genre)) u = self.thin(u + self.t1(t) + self.g1(genre)) return u class Residual(nn.Module): """ Single residual block inside a UNet Block. Its input is x, and its output is the processing of x through model(x) plus x itself. Args: - in_ch (int): Number of input channels. - out_ch (int): Number of output channels. - height (int): Height of the input tensor. - width (int): Width of the input tensor. """ def __init__(self, in_ch, out_ch, height, width): super().__init__() self.model = nn.Sequential( nn.LayerNorm((height, width)), nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1, padding=1), nn.ReLU(), nn.Conv2d(out_ch, out_ch, kernel_size=3, stride=1, padding=1), ) def forward(self, x): """ Forward pass for the Residual block. Args: - x (torch.Tensor): Input tensor. Returns: - torch.Tensor: Output tensor. """ return self.model(x) + x class _UNetBlock(nn.Module): """ Parent class for either the downwards or upwards UNet block. The children classes Up and Down are a fixed instantiation of this parent class that either increase dimensions and reduce channels (Up), or reduce dimensions and increase channels (Down). Whether it is an Up or Down block is determined by the value self.up set at instantiation. Args: - up (bool): Boolean flag to determine the type of block. """ def __init__(self, up: bool): super().__init__() self.up = up def _generate_model(self, in_ch, out_ch, height, width): """ Generate the appropriate model depending on the value of the up flag. Args: - in_ch (int): Number of input channels. - out_ch (int): Number of output channels. - height (int): Height of the input tensor. - width (int): Width of the input tensor. Returns: - nn.Sequential: Generated model. """ if self.up: model = nn.Sequential( Residual(in_ch, in_ch, height, width), Residual(in_ch, in_ch, height, width), Residual(in_ch, in_ch, height, width), nn.LayerNorm((height, width)), nn.Upsample([height * 2, width * 2], mode="nearest"), nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1, padding=1), nn.LayerNorm((height * 2, width * 2)), ) else: model = nn.Sequential( Residual(in_ch, in_ch, height, width), Residual(in_ch, in_ch, height, width), Residual(in_ch, in_ch, height, width), nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=2, padding=1), ) return model def forward(self, x): pass class Down(_UNetBlock): """ Downsampling version of the UNet Block. Args: - in_channels (int): Number of input channels. - out_channels (int): Number of output channels. - height (int): Height of the input tensor. - width (int): Width of the input tensor. """ def __init__(self, in_channels, out_channels, height, width): super().__init__(up=False) self.model = super()._generate_model(in_channels, out_channels, height, width) def forward(self, x): """ Forward pass for the Down block. Args: - x (torch.Tensor): Input tensor. Returns: - torch.Tensor: Output tensor. """ x = self.model(x) return x class Up(_UNetBlock): """ Upsampling version of the UNet Block. Args: - in_channels (int): Number of input channels. - out_channels (int): Number of output channels. - height (int): Height of the input tensor. - width (int): Width of the input tensor. """ def __init__(self, in_channels, out_channels, height, width): super().__init__(up=True) self.model = super()._generate_model(in_channels, out_channels, height, width) def forward(self, x): """ Forward pass for the Up block. Args: - x (torch.Tensor): Input tensor. Returns: - torch.Tensor: Output tensor. """ x = self.model(x) return x # DIFFUSION class Diffusion(nn.Module): """ Implementation of Diffusion model. Args: - steps (int): Number of diffusion steps. - epsilon (float): Epsilon value for noise. """ def __init__(self, steps=100, epsilon=0.01): super().__init__() self.steps = steps self.tspan = torch.linspace(0, 1, steps) self.epsilon = torch.tensor(epsilon) self.up = UNet() self.loss = nn.MSELoss() def noise(self, x): """ The whole forward steps for the noise. Args: - x (torch.Tensor): Input tensor. Returns: - torch.Tensor: Noisy tensor. """ z = torch.randn_like(x) x_noisy = self._mu(1) * x + self._var(1) * z return x_noisy def alpha(self, t): """ Alpha value for a given time step. Args: - t (float): Time step. Returns: - float: Alpha value. """ return 1 - 0.9 * t def alpha_bar(self, end=None): """ Alpha bar value for a given end time step. Args: - end (float): End time step. Returns: - float: Alpha bar value. """ if end is None: end = self.tspan[-1] + 1 return torch.tensor([self.alpha(t) for t in self.tspan if t <= end]).prod() def _mu(self, t_final): """ Mu value for a given final time step. Args: - t_final (float): Final time step. Returns: - float: Mu value. """ return (torch.sqrt(self.epsilon).arccos() * t_final).cos() ** 2 def _var(self, t_final): """ Variance value for a given final time step. Args: - t_final (float): Final time step. Returns: - float: Variance value. """ return (1 - t_final + (self.epsilon.pow(2))).sqrt() def forward(self, x, y): """ Forward pass for the Diffusion model. Args: - x (torch.Tensor): Input tensor. - y (torch.Tensor): Genre embedding tensor. Returns: - torch.Tensor: Noisy tensor. - torch.Tensor: Loss value. """ x_noisy = self.noise(x) L = None for t in torch.linspace(1, 0, self.steps)[:-1]: pred = self.up(x_noisy, y, t) loss = self.loss(pred, x) if L is None: L = loss else: L += loss mu = self.mu_up(x_noisy, pred, t) var = self.var_up(t) x_noisy = mu + torch.randn_like(x_noisy) * var return x_noisy, L def mu_up(self, xt, x0, t): """ Mu update step for the diffusion process. Args: - xt (torch.Tensor): Noisy tensor. - x0 (torch.Tensor): Original tensor. - t (float): Time step. Returns: - torch.Tensor: Updated mu value. """ alpha_bar = self._mu(t).pow(2) alpha_bar_prev = self._mu(t - 1).pow(2) alpha = alpha_bar / alpha_bar_prev summand1 = (alpha.sqrt() * (1 - alpha_bar_prev) * xt) / (1 - alpha_bar) summand2 = (alpha_bar_prev.sqrt() * (1 - alpha) * x0) / (1 - alpha_bar) return summand1 + summand2 def var_up(self, t): """ Variance update step for the diffusion process. Args: - t (float): Time step. Returns: - float: Updated variance value. """ alpha_bar = self._mu(t).pow(2) alpha_bar_prev = self._mu(t - 1).pow(2) alpha = alpha_bar / alpha_bar_prev var_sq = (1 - alpha) * (1 - alpha_bar_prev) / (1 - alpha_bar) return var_sq @torch.no_grad() def sample(self, x, g): """ Sampling function for the Diffusion model. Takes a random array and a genre determiner, and returns the final image. Args: - x (torch.Tensor): Input tensor. - g (int): Genre label. Returns: - torch.Tensor: Output tensor. """ if not isinstance(g, torch.Tensor): g = torch.tensor([g]) if 80 not in x.shape or 2048 not in x.shape: raise ValueError("Input tensor must have shape [1, 1, 80, 2048].") if len(x.shape) != 4: x = x.view(1, 1, 80, 2048) for t in torch.linspace(1, 0, self.steps).to(x.device)[:-1]: pred = self.up(x, g, t) mu = self.mu_up(x, pred, t) var = self.var_up(t) x_noisy = mu + torch.randn_like(x) * var return x_noisy # IMPLEMENTATION # This block covers the different tests performed during development if __name__ == "__main__": # Check if Genre Embedding works if False: model = GenreEmbd(3, 2) g1 = torch.tensor([1]) print(g1.shape) print(model(g1).shape) g2 = torch.tensor([0, 1, 2, 2]) print(g2.shape) print(model(g2).shape) exit() # Check if Time Embedding works if False: model = TimeEmbd(3) t = torch.linspace(0, 1, 90) ts = t[3] print(ts.shape) print(model(ts).shape) exit() # Check if UNet works if False: x = torch.randn(4, 1, 80, 2048) y = torch.randint(0,7,[4,],) print(y) print(f"In: {x.shape}") model = UNet() out = model(x, y, torch.tensor(0.5)) print(f"Out: {out.shape}") exit() # Check if Diffusion works if False: x = torch.randn(4, 1, 80, 2048) y = torch.randint(0,7,[4,],) print(y) print(f"In: {x.shape}") D = Diffusion(3) desc = "Model with {} parameters and {} trainable parameters" print( desc.format( sum(p.numel() for p in D.parameters()), sum(p.numel() for p in D.parameters() if p.requires_grad), ) ) out, error = D(x, y) print(f"Final: {out.shape} with error {error}") error.backward() print(next(iter(D.parameters())).grad.mean()) exit() # Check if sampling works if True: model = Diffusion(10) if False: # Check if it works with the desired type of input x = torch.randn(1, 1, 80, 2048) g = torch.tensor([1]) pred = model.sample(x, g) print(pred.shape) exit() if True: # Check if it works with weird inputs x = torch.randn(80, 2048) g = 1 out = model.sample(x, g) print(out.mean())
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatVideoModule } from 'mat-video'; import { AppComponent } from './app.component'; import { HeaderComponent } from './components/header/header.component'; import { FooterComponent } from './components/footer/footer.component'; import { LoginComponent } from './components/login/login.component'; import { ParentComponent } from './components/parent/parent.component'; import { HomeComponent } from './components/home/home.component'; import { AppRoutingModule } from './app.routing.module'; import { LessonComponent } from './components/lesson/lesson.component'; import {TreeModule} from 'primeng/tree'; import {PanelModule} from 'primeng/panel'; import {DialogModule} from 'primeng/dialog'; import { RegisterComponent } from './components/register/register.component'; import { AboutComponent } from './components/about/about.component'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import { EnrolcourseComponent } from './components/enrolcourse/enrolcourse.component'; import { FullstackjavaComponent } from './components/instructor-led/fullstackjava/fullstackjava.component'; import { WebcourseComponent } from './components/instructor-led/webcourse/webcourse.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, HeaderComponent, FooterComponent, LoginComponent, LessonComponent, ParentComponent, RegisterComponent, AboutComponent, EnrolcourseComponent, FullstackjavaComponent, WebcourseComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, BrowserAnimationsModule, MatVideoModule, TreeModule, PanelModule, DialogModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }