text
stringlengths
184
4.48M
import { useExternalLinkOpener } from '@providers'; import { getValueFromLocalStorage, saveValueInLocalStorage } from '@src/utils/local-storage'; import { WarningModal } from '@src/views/browser-view/components'; import React, { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; export const DappBetaModal = (): React.ReactElement => { const { t } = useTranslation(); const [isModalVisible, setIsModalVisible] = useState(false); const openExternalLink = useExternalLinkOpener(); useEffect(() => { const showDappBetaModal = getValueFromLocalStorage('showDappBetaModal', true); setIsModalVisible(showDappBetaModal); }, []); const onClose = () => { saveValueInLocalStorage({ key: 'showDappBetaModal', value: false }); setIsModalVisible(false); }; const onLearnMore = () => { const showDappBetaModal = getValueFromLocalStorage('showDappBetaModal', true); if (showDappBetaModal) openExternalLink(process.env.FAQ_URL); onClose(); }; return ( <WarningModal header={t('dapp.betaModal.header')} content={ <p> {t('dapp.betaModal.content.1')} <br /> {t('dapp.betaModal.content.2')} </p> } confirmLabel={t('dapp.betaModal.btn.learnMore')} cancelLabel={t('dapp.betaModal.btn.close')} onConfirm={onLearnMore} onCancel={onClose} visible={isModalVisible} /> ); };
import React, { useEffect, useState } from 'react'; import { Col, message, Modal, Row, Tabs, TabsProps } from 'antd'; import { DMSButton } from '../../components/button/DMSButton.tsx'; import { FaPlay, FaPlusSquare, FaSquare, FaTrash } from 'react-icons/fa'; import { BsBootstrapReboot } from 'react-icons/bs'; import { GrResume } from 'react-icons/gr'; import { JobsTable } from './jobs-table'; import { useNavigate } from 'react-router-dom'; import { AppState, useDispatch, useSelector } from '../../redux/store'; import { getJobList } from '../../redux/slices/migration-jobs.slice.ts'; import { JobResponse } from '../../requests/types/job.interface.ts'; import { JobStatus, Phase } from '../../constant'; import { ExclamationCircleFilled } from '@ant-design/icons'; import { actionJob, deleteJob } from '../../requests/job.request.ts'; import { VscDebugRestart } from 'react-icons/vsc'; export const MigrationJobs: React.FC = () => { const navigate = useNavigate(); const projectId = useSelector((app: AppState) => app.migrationJob.projectId); const jobs = useSelector((app: AppState) => (app.migrationJob.jobList || []).slice().sort((a, b) => a.name.localeCompare(b.name)) ); const dispatch = useDispatch(); const [selectedRow, setSelectedRow] = React.useState<JobResponse[]>(); const [loadingButton, setLoadingButton] = useState<string | null>(null); const onChange = (key: string) => { console.log(key); }; const items: TabsProps['items'] = [ { key: '1', label: 'JOBS', children: <JobsTable jobs={jobs} setSelectedRow={setSelectedRow} /> } ]; const deleteSelectedJobs = async () => { try { setLoadingButton('delete'); if (selectedRow) selectedRow.map(async (item) => { await deleteJob(projectId, item.job_id); message.success('Deleted successfully'); dispatch(getJobList(projectId)); }); } finally { setLoadingButton(null); setSelectedRow([]); } }; const startJob = async () => { try { setLoadingButton('start'); if (selectedRow?.[0].job_id) { const startJobBody = { status: 'not started', action: 'start' }; await actionJob(projectId, selectedRow[0].job_id, startJobBody); message.success('Started a job'); dispatch(getJobList(projectId)); } } finally { setLoadingButton(null); setSelectedRow([]); } }; const stopJob = async () => { try { setLoadingButton('stop'); if (selectedRow?.[0].job_id) { const stopJobBody = { status: 'stopped' }; await actionJob(projectId, selectedRow[0].job_id, stopJobBody); message.success('Stopped a job'); dispatch(getJobList(projectId)); } } finally { setLoadingButton(null); setSelectedRow([]); } }; const resumeJob = async () => { try { setLoadingButton('resume'); if (selectedRow?.[0].job_id) { const resumeJobBody = { status: 'stopped', phase: 'cdc', action: 'resume' }; await actionJob(projectId, selectedRow[0].job_id, resumeJobBody); message.success('Resumed a job'); dispatch(getJobList(projectId)); } } finally { setLoadingButton(null); setSelectedRow([]); } }; const restartJob = async () => { try { setLoadingButton('restart'); if (selectedRow?.[0].job_id) { const resumeJobBody = { status: 'stopped', phase: 'full dump', action: 'restart' }; await actionJob(projectId, selectedRow[0].job_id, resumeJobBody); message.success('Restarted a job'); dispatch(getJobList(projectId)); } } finally { setLoadingButton(null); setSelectedRow([]); } }; useEffect(() => { dispatch(getJobList(projectId)); }, [projectId]); return ( <> <Row className="px-5 py-2 border-b-1 border-solid border-border"> <Col span={4}> <span className="text-xl font-bold">Migration jobs</span> </Col> <Col span={20}> <div className="flex gap-2 justify-start"> <DMSButton icon={<FaPlusSquare />} type="text" title="CREATE MIGRATION JOB" onClick={() => navigate('/migration-jobs/create')}> CREATE MIGRATION JOB </DMSButton> <DMSButton disabled={ !selectedRow || selectedRow.length !== 1 || !( selectedRow[0]?.status === JobStatus.NOT_STARTED && (selectedRow[0]?.source_id || selectedRow[0]?.target_id) ) } icon={<FaPlay />} onClick={() => startJob()} type="text" loading={loadingButton === 'start'} title="START"> START </DMSButton> <DMSButton disabled={ !selectedRow || selectedRow.length !== 1 || !( (selectedRow[0]?.status === JobStatus.RUNNING && selectedRow[0]?.phase === Phase.FULL_DUMP) || (selectedRow[0]?.status === JobStatus.RUNNING && selectedRow[0]?.phase === Phase.CDC) ) } icon={<FaSquare />} type="text" loading={loadingButton === 'stop'} onClick={() => stopJob()} title="STOP"> STOP </DMSButton> <DMSButton disabled={ !selectedRow || selectedRow.length !== 1 || !( (selectedRow[0]?.status === JobStatus.STOPPED && selectedRow[0]?.phase === Phase.CDC) || (selectedRow[0]?.status === JobStatus.FAILED && selectedRow[0]?.phase === Phase.CDC) ) } icon={<BsBootstrapReboot />} onClick={() => resumeJob()} type="text" loading={loadingButton === 'resume'} title="RESUME"> RESUME </DMSButton> <DMSButton disabled={ !selectedRow || selectedRow.length !== 1 || !( (selectedRow[0]?.status === JobStatus.STOPPED && selectedRow[0]?.phase === Phase.FULL_DUMP) || (selectedRow[0]?.status === JobStatus.FAILED && selectedRow[0]?.phase === Phase.FULL_DUMP) ) } icon={<GrResume />} type="text" loading={loadingButton === 'restart'} onClick={() => restartJob()} title="RESTART"> RESTART </DMSButton> <DMSButton disabled={ !selectedRow || selectedRow.length === 0 || selectedRow[0]?.status === JobStatus.STOPPING } loading={loadingButton === 'delete'} icon={<FaTrash />} onClick={() => { Modal.confirm({ centered: true, title: 'Do you want to delete these items?', icon: <ExclamationCircleFilled />, onOk() { deleteSelectedJobs(); }, okText: 'Yes', cancelText: 'No', okButtonProps: { className: 'bg-primary' }, cancelButtonProps: { className: 'border-primary text-primary' } }); }} type="text" title="DELETE"> DELETE </DMSButton> </div> </Col> </Row> <Row className="p-5"> <div className="font-normal"> Migration jobs allow you to move data from source to destination databases automatically </div> </Row> <div className="px-5 relative"> <VscDebugRestart className="absolute top-5 right-10 z-50 text-primary text-xl hover:cursor-pointer" title="Refresh" onClick={() => { dispatch(getJobList(projectId)); }} /> <Tabs defaultActiveKey="1" items={items} onChange={onChange} /> </div> </> ); };
from flask import Flask, request, jsonify from transformers import pipeline import urllib.parse app = Flask(__name__) # Load the sentiment analysis pipeline sentiment_analysis_pipeline = pipeline("sentiment-analysis") @app.route('/analyze-sentiment', methods=['GET']) def analyze_sentiment(): try: # Extract the textOriginal parameter from the URL text_original = request.args.get('textOriginal', '') # URL encode the textOriginal parameter encoded_text = urllib.parse.quote(text_original) # Perform sentiment analysis using Hugging Face Transformers sentiment_result = sentiment_analysis_pipeline(text_original) # Example response format: {'sentiment': 'POSITIVE', 'score': 0.99} response = { 'sentiment': sentiment_result[0]['label'], 'score': sentiment_result[0]['score'] } return jsonify(response) except Exception as e: error_message = {'error': str(e)} return jsonify(error_message), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
/** * This file contains several sets of settings for validating request queries and bodies * This file is for the user active games endpoint * We have three exports here that are used in the routing file * The purpose of this file is to sanitize and validate our input to make sure * there is no foul play about * @module UserProfilesValidationAndSanitation */ import {body, query} from "express-validator"; /** * This array stores the validation for our POST puzzle requests * This validation only applies for the body field * //todo add more validation and sanitization * The astricks are required because we are accessing values from an array */ exports.validateUserProfileBodyPOST = [ body().isArray().withMessage('body is not an array'), body('*.userID', 'userID did not match correct format').isString().isLength({ min: 1 }), body('*.userPreferences.savePuzzleData', 'savePuzzleData is not a boolean').optional().isBoolean(), body('*.userPreferences.theme', 'theme is not a correct value').optional().isString().isIn(["light", "dark", "auto"]), body('*.userPreferences.gamePreferences.notifyOnWrongCell', 'notifyOnWrongCell is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightAllPeers', 'highlightAllPeers is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightSelectedBox', 'highlightSelectedBox is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightSelectedRow', 'highlightSelectedRow is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightSelectedColumn', 'highlightSelectedColumn is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.playMusic', 'playMusic is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.musicIntensify', 'musicIntensify is not a boolean').optional().isBoolean(), ]; /** * This array stores the validation for our PATCH, GET, and DELETE requests * This validation only applies for the query fields * //todo add more validation and sanitization */ exports.validateUserProfileParameters = [ query('*.userID', 'userID did not match correct format').optional().isString().isLength({ min: 1 }), query('*.userPreferences.savePuzzleData', 'savePuzzleData is not a boolean').optional().isBoolean(), query('*.userPreferences.theme', 'theme is not a correct value').optional().isString().isIn(["light", "dark", "auto"]), query('*.userPreferences.gamePreferences.notifyOnWrongCell', 'notifyOnWrongCell is not a boolean').optional().isBoolean(), query('*.userPreferences.gamePreferences.highlightAllPeers', 'highlightAllPeers is not a boolean').optional().isBoolean(), query('*.userPreferences.gamePreferences.highlightSelectedBox', 'highlightSelectedBox is not a boolean').optional().isBoolean(), query('*.userPreferences.gamePreferences.highlightSelectedRow', 'highlightSelectedRow is not a boolean').optional().isBoolean(), query('*.userPreferences.gamePreferences.highlightSelectedColumn', 'highlightSelectedColumn is not a boolean').optional().isBoolean(), query('*.userPreferences.gamePreferences.playMusic', 'playMusic is not a boolean').optional().isBoolean(), query('*.userPreferences.gamePreferences.musicIntensify', 'musicIntensify is not a boolean').optional().isBoolean(), ]; /** * This array stores the validation for our PATCH requests * This validation only applies for the body field * //todo add more validation and sanitization * the Astricks are not needed here because in this instance we are not storing our values in an array * We also leave out the userID and puzzle fields because we do not want to replace those during a PATCH operation */ exports.validateUserProfileBodyPATCH = [ body('*.userPreferences.savePuzzleData', 'savePuzzleData is not a boolean').optional().isBoolean(), body('*.userPreferences.theme', 'theme is not a correct value').optional().isString().isIn(["light", "dark", "auto"]), body('*.userPreferences.gamePreferences.notifyOnWrongCell', 'notifyOnWrongCell is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightAllPeers', 'highlightAllPeers is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightSelectedBox', 'highlightSelectedBox is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightSelectedRow', 'highlightSelectedRow is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.highlightSelectedColumn', 'highlightSelectedColumn is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.playMusic', 'playMusic is not a boolean').optional().isBoolean(), body('*.userPreferences.gamePreferences.musicIntensify', 'musicIntensify is not a boolean').optional().isBoolean(), ];
#' Add taxonomic and threat status data #' #' Adds additional common and scientific names, and threat classification status #' information. #' #' Adds additional taxonomic data ("commonMaoriName", "alternativeNames", #' "species", "genus", "family", "order", "class", "phylum") and NZ Threat #' Classification Status information ("category", "status", "taxonomicStatus", #' "bioStatus"). See \href{https://nztcs.org.nz/home}{NZTCS} for details #' regarding the NZTCS variables. #' #' @param fishd A dataframe imported from the NZFFD using \code{nzffd_import} #' #' @return An NZFFD dataframe, with 12 additional columns. #' #' @examples #' nzffdr_taxon_threat(nzffdr::nzffdr_data) #' @export nzffdr_taxon_threat <- function(fishd){ if (is.data.frame(fishd) == FALSE) { stop("arg fishd must be a data.frame") } if("taxonName" %in% colnames(fishd) == FALSE) { stop("dataframe must include the \"taxonName\" column") } fishd <- merge(fishd, threat_status_names, by = "taxonName", all.x = TRUE) return(fishd) }
class SearchResponseData { SearchResponseData({ this.success, this.data, }); bool? success; Data? data; factory SearchResponseData.fromJson(Map<String, dynamic> json) => SearchResponseData( success: json["success"], data: json["data"]!=null&&json["data"]!.toString().length>0?Data.fromJson(json["data"]):null, ); Map<String, dynamic> toJson() => { "success": success, "data": data!.toJson(), }; } class Data { Data({ this.id, this.virusStatus, this.type, this.districtname, this.zonename, this.wardname, this.streetname, this.date, this.referenceNo, this.latitude, this.longitude, }); int? id; String? virusStatus; String? type; String? districtname; String? zonename; String? wardname; String? streetname; DateTime? date; String? referenceNo; String? latitude; String? longitude; factory Data.fromJson(Map<String, dynamic> json) => Data( id: json["id"], virusStatus: json["virus_status"], type: json["type"], districtname: json["districtname"], zonename: json["zonename"], wardname: json["wardname"], streetname: json["streetname"], date: DateTime.parse(json["date"]), referenceNo: json["referenceNo"], latitude: json["latitude"], longitude: json["longitude"], ); Map<String, dynamic> toJson() => { "id": id, "virus_status": virusStatus, "type": type, "districtname": districtname, "zonename": zonename, "wardname": wardname, "streetname": streetname, "date": "${date!.year.toString().padLeft(4, '0')}-${date!.month.toString().padLeft(2, '0')}-${date!.day.toString().padLeft(2, '0')}", "referenceNo": referenceNo, "latitude": latitude, "longitude": longitude, }; }
#include <string.h> #include <iostream> #include <fstream> using namespace std; /* Author: Aryan Rai Date: 3/25/22 Description: morse code to english translator Usage: morse_assn3 infile.txt -mc infile.mc */ //forward declerations const char* englishToMorse(char); char morseToEnglish(const char*); int main(int argc, char** argv) { //making sure all arguments are passed string fname = argv[1]; if(argc == 4){ //create and open outputfile ofstream outFile; outFile.open(string(argv[3])); //translating to morse if(string(argv[2]) == "-mc"){ cout<<"Translating "<<string(argv[1])<<" to Morse"<<endl; ifstream input(fname); char line[255]; while(input.getline(line,255,'\n')){ char* token; token = strtok(line,""); while(token != NULL){ for(int i = 0; i < strlen(token); i++) { char temp = token[i]; outFile<<englishToMorse(temp)<<'|'; } token = strtok(NULL, ""); outFile<<'\n'; } } } //translating to english if(string(argv[2]) == "-e"){ cout<<"Translating "<<string(argv[1])<<" to English"<<endl; ifstream input(fname); char line[255]; while(input.getline(line,255,'\n')){ const char* token; token = strtok(line,"|"); while(token != NULL){ outFile<<morseToEnglish(token)<<""; token = strtok(NULL, "|"); } outFile<<'\n'; } } outFile.close(); cout<<string(argv[3])<<" file completed."<<endl; } else printf("Error -- usage: <exe> <input file> <-mc|-e> <output file> "); //error message if wrong use return 0; } //switch case for morse translation(i know its supposed to not be 53 statments) const char* englishToMorse(char letter){ switch(letter) { case 'a' : return ".-"; case 'A': return ".-"; case 'b': return "-..."; case 'B': return "-..."; case 'c': return "-.-."; case 'C': return "-.-."; case 'd': return "-.."; case 'D': return "-.."; case 'e': return "."; case 'E': return "."; case 'f': return "..-."; case 'F': return "..-."; case 'g': return "--."; case 'G': return "--."; case 'h': return "...."; case 'H': return "...."; case 'i': return ".."; case 'I': return ".."; case 'j': return ".---"; case 'J': return ".---"; case 'k': return "-.-"; case 'K': return "-.-"; case 'l': return ".-.."; case 'L': return ".-.."; case 'm': return "--"; case 'M': return "--"; case 'n': return "-."; case 'N': return "-."; case 'o': return "---"; case 'O': return "---"; case 'p': return ".--."; case 'P': return ".--."; case 'q': return "--.-"; case 'Q': return "--.-"; case 'r': return ".-."; case 'R': return ".-."; case 's': return "..."; case 'S': return "..."; case 't': return "-"; case 'T': return "-"; case 'u': return "..-"; case 'U': return "..-"; case 'v': return "...-"; case 'V': return "...-"; case 'w': return ".--"; case 'W': return ".--"; case 'x': return "-..-"; case 'X': return "-..-"; case 'y': return "-.--"; case 'Y': return "-.--"; case 'z': return "--.."; case 'Z': return "--.."; case ' ': return "/"; case '\0':return "\n"; default: return "eeee"; } } //translating to english char morseToEnglish(const char* mor){ if(strcmp(mor,".-") == 0){ return 'A'; } else if(strcmp(mor,"-...") == 0){ return 'B'; } else if(strcmp(mor,"-.-.") == 0){ return 'C'; } else if(strcmp(mor,"-..") == 0){ return 'D'; } else if(strcmp(mor,".") == 0){ return 'E'; } else if(strcmp(mor,"..-.") == 0){ return 'F'; } else if(strcmp(mor,"--.") == 0){ return 'G'; } else if(strcmp(mor,"....") == 0){ return 'H'; } else if(strcmp(mor,"..") == 0){ return 'I'; } else if(strcmp(mor,".---") == 0){ return 'J'; } else if(strcmp(mor,"-.-") == 0){ return 'K'; } else if(strcmp(mor,".-..") == 0){ return 'L'; } else if(strcmp(mor,"--") == 0){ return 'M'; } else if(strcmp(mor,"-.") == 0){ return 'N'; } else if(strcmp(mor,"---") == 0){ return 'O'; } else if(strcmp(mor,".--.") == 0){ return 'P'; } else if(strcmp(mor,"--.-") == 0){ return 'Q'; } else if(strcmp(mor,".-.") == 0){ return 'R'; } else if(strcmp(mor,"...") == 0){ return 'S'; } else if(strcmp(mor,"-") == 0){ return 'T'; } else if(strcmp(mor,"..-") == 0){ return 'U'; } else if(strcmp(mor,"...-") == 0){ return 'V'; } else if(strcmp(mor,".--") == 0){ return 'W'; } else if(strcmp(mor,"-..-") == 0){ return 'X'; } else if(strcmp(mor,"-.--") == 0){ return 'Y'; } else if(strcmp(mor,"--..") == 0){ return 'Z'; } else if(strcmp(mor,"/") == 0){ return ' '; } else if(strcmp(mor,"/") == 0){ return ' '; } else return '#'; }
# LTLS This repository is for running LTLS seamlessly. ## Steps To Run: ### Step 1: Get Rust To run this, first rust must be installed on your machine: https://www.rust-lang.org/learn/get-started ### Step 2: Git Access The sole dependency of this repo is https://github.com/TechnionFV/rust-formal-verification.git Make sure you can access it since it is a private repo, this can be accomplished by asking me for access. #### Option 1 After getting access you should be cache your github credentials in your terminal: https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git #### Option 2 You can also cache your credentials temporarily by running ``` git config --global credential.helper store git pull ``` Then inserting your username and a one-time-password that can be requested in https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic ### Step 3: Build The best performance is reached when running in `release` mode, so the command to run this program would be: ``` cargo run --release <AIGER file> ``` This command fetches all the dependencies and compiles the code, if step 2 is not done (you were not granted access OR you did not cache your credentials) this command will fail. ## Notes: ### Compiling C++ This rust program depends on other rust programs that may depend on C++ code. So you might need to have Clang on your machine. ### Running offline Here is some information I found about downloading the rust compiler and installing offline: https://forge.rust-lang.org/infra/other-installation-methods.html Furthermore, some information that might be helpful in the case when you want to use cargo offline: https://www.reddit.com/r/rust/comments/137hmah/rust_offline/ More specifically, running with 'cargo run --release --offline' ### Compiling And Running Elsewhere Another solution is to compile the program anywhere, then send the executable to where it needs to go. To compile the executable run: ``` cargo build --release ``` Then you'll find the executable under `./target/release/ltls` ## Using different C++ compilers and linkers To compile the project you need to have a C++ compiler in order to compile CaDiCal. To set the compiler certain environment variables must be set before trying to compile. The C++ standard library may be linked to the crate target. By default it's: 1. `libc++` for macOS, FreeBSD, and OpenBSD 2. `libc++_shared` for Android, nothing for MSVC 3. `libstdc++` for anything else. It can be changed by setting the `CXXSTDLIB` environment variable. ### Using c++ Run these commands in order. ``` cargo clean unset CRATE_CC_NO_DEFAULTS unset CXXFLAGS unset CXXSTDLIB unset RUSTFLAGS export CXX=/usr/bin/g++ cargo test ``` ### Using Clang First you should get the C++ library that works with Clang using one of these commands (not sure which specific one, but the first should work): ``` sudo apt install libc++-dev sudo apt install libc++abi-dev sudo apt install libstdc++-dev ``` Then run these commands in order: ``` cargo clean unset CRATE_CC_NO_DEFAULTS unset CXXFLAGS unset CXXSTDLIB unset RUSTFLAGS export CXX=clang++ cargo test ``` ### Using LLD First get the linker using: ``` sudo apt install lld ``` Then run these commands in order: ``` cargo clean unset CRATE_CC_NO_DEFAULTS unset CXXFLAGS unset CXXSTDLIB export RUSTFLAGS="-C link-arg=-fuse-ld=lld" export CXX=g++ cargo test ``` ### Using g++ for linking There are situations, when running with a different g++ compiler than the one that `PATH` points to where the C++ standard library would not be found. To fix this, you need to tell rust compiler to link with the same version directly. Run these commands in order: ``` cargo clean unset CRATE_CC_NO_DEFAULTS unset CXXFLAGS unset CXXSTDLIB export RUSTFLAGS="-C linker=g++" export CXX=g++ cargo test ```
import { MapEntityWithVersions, Preload } from "./types"; import { babelMap, eslintMap } from "./maps"; import getEntitiesMapWithVersions from "./getEntitiesMapWithVersions"; import { wrappers, transform } from "@core/utils"; import log from "fancy-log"; function preload({ babel, eslint }: Preload) { const checkedEntities: MapEntityWithVersions[] = []; if (babel) { const pluginsAndPresets = transform.babelConfig(babel); const pluginsAndPresetsMap = getEntitiesMapWithVersions(pluginsAndPresets, { ...babelMap.plugins, ...babelMap.presets, }); checkedEntities.push(...Object.values(pluginsAndPresetsMap)); } if (eslint) { const pluginsExtendsAndParser = transform.eslintConfig(eslint); const pluginsExtendsAndParserMap = getEntitiesMapWithVersions(pluginsExtendsAndParser, { ...eslintMap.extendsMap, ...eslintMap.parser, ...eslintMap.plugins, }); checkedEntities.push(...Object.values(pluginsExtendsAndParserMap)); } if (checkedEntities.length) { log("Packages to install:"); } else { log("No packages need to be installed"); return; } const packagesToInstall = checkedEntities.reduce((acc, { nameInRegistry, desiredVersion }) => { const packageWithVersion = `${nameInRegistry}@${desiredVersion}`; log(`- ${packageWithVersion}`); return acc + `${packageWithVersion} `; }, ""); const command = `npm install ${packagesToInstall.trim()} --no-save --no-audit`; const output = wrappers.syncExec(command, { encoding: "utf8" }); log(output.trim()); } export default preload;
import { useRouter } from "next/router"; import { createContext, useEffect, useState } from "react"; import { getCurrentCountry, getData } from "../api/BaseApi"; import { CountryListOtherProps } from "../components/country-select"; import { LanguageListProps } from "../components/language-select"; interface CountryListProps { readonly current: CountryListOtherProps; readonly others: CountryListOtherProps[]; } const CountrySelectContext = createContext<{ selectCountryHandle: (text: string | number) => void; countryList: CountryListProps | undefined; languageList: LanguageListProps | undefined; selectedCountry: string | any; }>({ selectCountryHandle: (text: string | number) => {}, countryList: undefined, languageList: undefined, selectedCountry: "", }); interface CountrySelectContextProviderProps { readonly children: React.ReactNode; } export function CountrySelectContextProvider({ children, }: CountrySelectContextProviderProps) { const [countryList, setCountryList] = useState<CountryListProps | undefined>( undefined ); const [languageList, setLanguageList] = useState<LanguageListProps | any>([]); const { push, asPath, pathname, locale, query } = useRouter(); const currLang = typeof window !== "undefined" && localStorage.getItem("language_code"); const countryCode = query.country ? query.country : countryList?.current.code; const selectedCountry = typeof countryCode !== "undefined" ? countryCode : ""; const selectedLang = currLang !== null ? currLang : locale; useEffect(() => { localStorage.setItem("language_code", `${selectedLang}`); localStorage.setItem("country_code", `${selectedCountry}`); }, [selectedCountry, selectedLang]); useEffect(() => { push(`${pathname}?country=${selectedCountry}`, asPath, { locale: selectedLang, }); }, [countryList, selectedCountry, selectedLang]); useEffect(() => { getData("/countries/languages/?", selectedLang, selectedCountry) .then((res) => { setLanguageList(res.data); }) .catch((err) => console.log(err)); getData("/countries/list/?", selectedLang, selectedCountry) .then((res) => { setCountryList(res.data); }) .catch((err) => console.log(err)); }, [locale, selectedCountry]); function selectCountryHandle(text: string | number) { localStorage.setItem("country_code", `${text}`); push(`${pathname}?country=${text}`); } const context = { selectCountryHandle, countryList, languageList, selectedCountry, }; return ( <CountrySelectContext.Provider value={context}> {children} </CountrySelectContext.Provider> ); } export default CountrySelectContext;
// Define que o retorno será um HTMLAnchorElement const link = document.querySelector<HTMLAnchorElement>(".link"); link?.href; async function getData<T>(url: string): Promise<T> { const response = await fetch(url); return await response.json(); } interface Notebook { nome: string; } async function handleData() { const notebook = await getData<Notebook>("https://api.origamid.dev/json/notebook.json"); console.log(notebook.nome); }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admission extends Model { use HasFactory; protected $fillable = ['class_id', 'user_id']; public function getImageShowAttribute(){ return $this->image != "" ? asset('public/upload/admission/'. $this?->image) : asset('public/frontend/images/No-image.jpg'); } public function user(){ return $this->belongsTo(User::class,"user_id",'id'); } public function class(){ return $this->belongsTo(Classe::class,"class_id",'id'); } public function academic_year(){ return $this->belongsTo(AcademicYear::class,"academic_year_id",'id'); } public function session(){ return $this->belongsTo(Session::class,"session_id",'id'); } public function section(){ return $this->belongsTo(SchoolSection::class,"section_id",'id'); } public function group(){ return $this->belongsTo(Group::class,"group_id",'id'); } public function feeManagement(){ return $this->belongsTo(FeeManagement::class,"fee_id",'id'); } //present public function present_continent(){ return $this->belongsTo(Continent::class,"present_continent_id",'id'); } public function present_country(){ return $this->belongsTo(Country::class,"present_country_id",'id'); } public function present_state(){ return $this->belongsTo(State::class,"present_state_id",'id'); } public function present_city(){ return $this->belongsTo(City::class,"present_city_id",'id'); } //Permanent public function permanent_continent(){ return $this->belongsTo(Continent::class,"permanent_continent_id",'id'); } public function permanent_country(){ return $this->belongsTo(Country::class,"permanent_country_id",'id'); } public function permanent_state(){ return $this->belongsTo(State::class,"permanent_state_id",'id'); } public function permanent_city(){ return $this->belongsTo(City::class,"permanent_city_id",'id'); } public function pre_class(){ return $this->belongsTo(Classe::class,"pre_class_id",'id'); } public function certificate(){ return $this->hasMany(AdmissionCertificate::class,"admission_id",'id'); } }
import Image from 'next/image' import { PortableText } from '@portabletext/react' import RichTextType from 'app/(frontend)/types/richText' import ImageField from 'app/(frontend)/types/image' import portableTextComponents from 'app/(frontend)/utils/portableTextComponents' import Icon from 'app/(frontend)/components/Icon' import type { IconType, IconColor } from 'app/(frontend)/components/Icon/Icon' import cx from 'classnames' import styles from './TwoUp.module.scss' export interface TwoUpProps { image?: ImageField iconCard?: { rows?: { _key: string _type: 'row' text?: string icon?: IconType iconColor: IconColor }[] } logos?: { _key: string _type: 'linkedLogo' image: NonNullable<ImageField> externalUrl?: string }[] | null title?: string text?: RichTextType imageAlignment: 'left' | 'right' styleAsCard?: boolean } export interface TwoUpField extends TwoUpProps { _key: string _type: 'caseStudyTwoUp' } export default function TwoUp({ image, iconCard, logos, title, text, imageAlignment, styleAsCard, }: TwoUpProps) { const twoUpMarkup = ( <section className={cx(styles.container, { [styles.container__inCard]: styleAsCard })}> {(text || title || logos) && ( <div className={cx( styles.textWrap, styles[`textWrap__img${imageAlignment}`], { [styles.textWrap__inCard]: styleAsCard }, )} > {logos && ( <div className={cx(styles.logos, { [styles.logos__inCard]: styleAsCard })}> {logos.map((logo) => { const { _key, image: logoImage, externalUrl } = logo const logoImageEl = ( <Image className={styles.logo} src={logoImage.url} width={logoImage.width} height={logoImage.height} alt={logoImage.altText ?? ''} title={logoImage.title ?? undefined} /> ) return ( <div key={_key} className={styles.logoWrap}> {externalUrl ? ( <a href={externalUrl} className={styles.logoInner}> {logoImageEl} </a> ) : ( <div className={styles.logoInner}> {logoImageEl} </div> )} </div> ) })} </div> )} {(text || title) && ( <div className={styles.titleTextWrap}> {title && <h1 className={styles.title}>{title}</h1>} {text && ( <div className={styles.text}> <PortableText value={text} components={portableTextComponents()} /> </div> )} </div> )} </div> )} {(image || iconCard) && ( <div className={cx( styles.visuals, styles[`visuals__${imageAlignment}`], { [styles.visuals__inCard]: styleAsCard }, )} > {image && ( <div className={styles.imgWrap}> <Image className={styles.img} src={image.url} width={image.width} height={image.height} alt={image.altText ?? ''} title={image.title ?? undefined} /> </div> )} {iconCard && ( <div className={styles.iconCard}> {iconCard.rows?.map((row) => { const { _key, text: iconRowText, icon, iconColor, } = row return ( <div key={_key} className={styles.iconCard_Row}> {icon && ( <div className={styles.iconCard_Icon}> <Icon icon={icon} color={iconColor} /> </div> )} {iconRowText && <p className={styles.iconCard_Text}>{iconRowText}</p>} </div> ) })} </div> )} </div> )} </section> ) return ( styleAsCard ? ( <div className={styles.cardContainer}>{twoUpMarkup}</div> ) : twoUpMarkup ) }
import * as React from 'react'; import { StyleSheet, View, Image, TouchableWithoutFeedback } from 'react-native'; import { w } from '../../config/dimensions'; import { CustomizedText as Text } from "../../components/Text"; import useTheme from '../../hooks/useTheme'; import User from '../../types/User'; import app from '../../config/app'; import { defaultAvatar } from '../UserProfile'; import useAuth from '../../hooks/useAuth'; import getTimestamp from '../../functions/getTimestamp'; import Ionicons from 'react-native-vector-icons/Ionicons'; import Message from '../../types/Message'; export default function Conversation({ item, navigation }: any) { const { name, members, createdBy, messages, isGroup } = item; const { auth } = useAuth(); const { theme, mode } = useTheme(); const receiver = members.find((member: User) => member._id != auth.user._id) || {}; const avatar = receiver.picture ? app.route + receiver.picture.filename : undefined const lastMessage = messages[0] || { content: '', createdAt: new Date() }; const lastSeenAt = item.lastSeenAt[auth.user._id]; const recipientLastMessage = messages.find((msg: Message | any) => msg.isSystemMessage || msg.sender._id != auth.user._id); const seen = recipientLastMessage ? new Date(lastSeenAt).getTime() > new Date(recipientLastMessage.createdAt).getTime() : true; const chatName = isGroup ? name : receiver.name; const onPress = () => { navigation.navigate('Chat', { chat: item }) } return ( <TouchableWithoutFeedback onPress={onPress}> <View style={[styles.wrapper, { backgroundColor: theme.colors.bg.card, borderColor: theme.colors.disabled.light }]}> <View style={styles.container}> <View style={styles.left}> <View style={styles.profileView}> {isGroup ? <Ionicons name={'md-people-circle-outline'} size={w * 15} color={theme.colors.bg.blue} /> : <Image style={styles.profile} source={ avatar ? { uri: avatar } : defaultAvatar(receiver.isMale) } /> } </View> <View style={styles.info}> <Text numberOfLines={1} fontFamily={theme.fonts.FONT_BOLD} style={styles.usernameText}>{chatName}</Text> <Text numberOfLines={1} fontFamily={theme.fonts.FONT_MEDIUM} style={[styles.messageText, { color: theme.colors.text.gray }]}>{lastMessage.content}</Text> </View> </View> <View style={styles.right}> <View style={styles.metadata}> <Text numberOfLines={1} fontFamily={theme.fonts.FONT_REGULAR} style={[styles.createdAt, { color: theme.colors.text.gray }]}>{getTimestamp(lastMessage.createdAt)}</Text> <View style={[styles.dot, { backgroundColor: seen ? 'transparent' : theme.colors.bg.blue }]} /> </View> </View> </View> </View> </TouchableWithoutFeedback> ); } const styles = StyleSheet.create({ wrapper: { marginTop: "5%", paddingVertical: "5%", paddingHorizontal: "2%", borderRadius: 8, borderWidth: 0.5, }, container: { flexDirection: 'row', justifyContent: "space-between", height: w * 15, }, left: { flexDirection: 'row', height: w * 15, width: w * 55 }, right: { width: w * 20 }, usernameText: { fontSize: w * 4 }, messageText: { fontSize: w * 3.5, marginTop: "5%" }, info: { paddingHorizontal: "5%", justifyContent: "space-evenly" }, profile: { width: w * 15, height: w * 15, borderRadius: w * 7.5 }, profileView: { alignItems: "center", }, dot: { width: w * 3, height: w * 3, borderRadius: w * 1.5, alignSelf: "center", alignItems: "center", justifyContent: "center" }, metadata: { justifyContent: "space-around", height: "100%" }, createdAt: { fontSize: w * 2.5, alignSelf: "center" }, unread: { fontSize: w * 4.5, } });
import { getResponseData, apiNorma } from "./index"; import {deleteCookie, getCookie} from "../utils"; import {AppDispatch} from "../../utils/types"; import {POST_LOGOUT_REQUEST, POST_LOGOUT_SUCCESS, POST_LOGOUT_FAILED} from '../constants' export interface ILogoutAction { readonly type: typeof POST_LOGOUT_REQUEST; } export interface ILogoutFailedAction { readonly type: typeof POST_LOGOUT_FAILED; } export interface ILogoutSuccessAction { readonly type: typeof POST_LOGOUT_SUCCESS; } export const logoutAction = (): ILogoutAction => ({ type: POST_LOGOUT_REQUEST }); export const logoutFailedAction = (): ILogoutFailedAction => ({ type: POST_LOGOUT_FAILED }); export const logoutSuccessAction = (): ILogoutSuccessAction => ({ type: POST_LOGOUT_SUCCESS }); export function postLogout() { return function (dispatch: AppDispatch) { dispatch(logoutAction()) fetch(`${apiNorma}auth/logout`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: getCookie('refreshToken') }) }) .then(res => getResponseData(res)) .then(data => { if (data && data.success) { dispatch(logoutSuccessAction()) deleteCookie('refreshToken') deleteCookie('token') } else { dispatch(logoutFailedAction()) } }) .catch(err => { dispatch(logoutFailedAction()) }) } }
import { graphql } from 'gatsby'; import Img from 'gatsby-image'; import React from 'react'; import styled from 'styled-components'; import SEO from '../components/SEO'; const PizzaStyles = styled.div` display: grid; grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); gap: 2rem; margin: 0; padding: 0; `; export default function SinglePizzaPage({ location, data: { pizza } }) { return ( <> <SEO title={pizza.name} location={location} image={pizza.image?.asset?.fluid?.src} /> <PizzaStyles> <Img fluid={pizza.image.asset.fluid} alt={pizza.name} /> <div> <h2 className="mark">{pizza.name}</h2> {/* <p>Price: {pizza.price}</p> */} <ul> {pizza.toppings.map((topping) => ( <li key={topping.id}>{topping.name}</li> ))} </ul> </div> </PizzaStyles> </> ); } // The variable $slug is passed in the `context` parameter in gatsby-node's createPage() fn export const query = graphql` query singlePizzaQuery($slug: String!) { pizza: sanityPizza(slug: { current: { eq: $slug } }) { name price id toppings { name id vegetarian } image { asset { fluid(maxWidth: 800) { ...GatsbySanityImageFluid } } } } } `;
package gui.view.classroom; import java.io.IOException; import java.util.Comparator; import java.util.HashSet; import java.util.List; import connection.ConnectionError; import connection.ConnectionException; import gui.Main; import gui.SelectorController; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.util.Callback; import model.Aula; import model.Profesor; /** * Controlador de la pantalla de creación de aulas * @author Mario Núñez Izquierdo * @version 1.0 * */ public class ClassroomViewController extends SelectorController<Profesor> { @FXML TextField name; @FXML TextField capacity; @FXML TextArea description; private final Callback<ListView<Profesor>, ListCell<Profesor>> callback = new Callback<ListView<Profesor>, ListCell<Profesor>>() { @Override public ListCell<Profesor> call(ListView<Profesor> teachers) { ListCell<Profesor> cellsList = new ListCell<Profesor>() { @Override protected void updateItem(Profesor tea, boolean empty) { super.updateItem(tea, empty); if (tea != null) { setText(tea.getApellido1() + " " + tea.getApellido2() + ", " + tea.getNombre()); } else { setText(""); } } }; return cellsList; } }; /** * Cancela la creación del aula * * @throws IOException archino no encontrado */ @FXML private void cancel() throws IOException { if (cancelAlert()) { Main.setModifiedData(false); super.goBack(); } } /** * Crea el aula * @throws IOException archino no encontrado */ @FXML private void acept() throws IOException { Aula cla = new Aula(); if (this.capacity.getText().length() > 0 && !super.intPattern.matcher(this.capacity.getText()).find()) { cla.setCapacidad(Integer.parseInt(this.capacity.getText())); cla.setNombre(this.name.getText()); cla.setNotas(this.description.getText()); cla.setProfesors(new HashSet<Profesor>(super.getSelectedObjects())); try { if (Main.getClassroomService().add(cla)) { Alert alert = new Alert(AlertType.INFORMATION, "El nuevo aula se ha creado correctamente", ButtonType.OK); alert.initOwner(Main.getPrimaryStage()); alert.showAndWait(); Main.setModifiedData(false); Main.showManageView(); } } catch (ConnectionException cEx) { Alert alert = new Alert(AlertType.ERROR, cEx.getError().getText(), ButtonType.OK); alert.initOwner(Main.getPrimaryStage()); alert.showAndWait(); } } else { Alert alert = new Alert(AlertType.ERROR, ConnectionError.WRONG_CAPACITY.getText(), ButtonType.OK); alert.initOwner(Main.getPrimaryStage()); alert.showAndWait(); } } /** * Inicializa los elementos de selección de profesores * @param allTeachers todos los profesores de la base de datos */ public void setTeachers(List<Profesor> allTeachers) { super.initialize(callback, allTeachers, new SortTeacher()); } /** * Subclase para ordenar los profesores * @author Mario Núñez Izquierdo * @version 1.0 * */ private class SortTeacher implements Comparator<Profesor> { @Override public int compare(Profesor p1, Profesor p2) { String p1Display = "" + p1.getApellido1() + " " + p1.getApellido2() + ", " + p1.getNombre(); String p2Display = "" + p2.getApellido1() + " " + p2.getApellido2() + ", " + p2.getNombre(); return String.CASE_INSENSITIVE_ORDER.compare(p1Display, p2Display); } } }
// const jwt = require("jsonwebtoken"); const argon2 = require("argon2"); const models = require("../models"); const hashingOptions = { type: argon2.argon2id, memoryCost: 2 ** 16, timeCost: 5, parallelism: 1, }; const browse = (req, res) => { models.user .findAll() .then(([rows]) => { res.send(rows); }) .catch((err) => { console.error(err); res.sendStatus(500); }); }; const read = (req, res) => { models.user .find(req.params.id) .then(([rows]) => { if (rows[0] == null) { res.sendStatus(404); } else { res.status(req.method === "POST" ? 201 : 200).send(rows[0]); } }) .catch((err) => { console.error(err); res.sendStatus(500); }); }; const edit = (req, res) => { const user = req.body; // TODO validations (length, format...) user.id = parseInt(req.params.id, 10); models.user .update(user) .then(([result]) => { if (result.affectedRows === 0) { res.sendStatus(404); } else { res.sendStatus(204); } }) .catch((err) => { console.error(err); res.sendStatus(500); }); }; const add = (req, res) => { const user = req.body; // TODO validations (length, format...) models.user .insert(user) .then(([result]) => { res.status(201).json({ id: result.insertId }); }) .catch((err) => { console.error(err); res.sendStatus(500); }); }; const destroy = (req, res) => { models.user .delete(req.params.id) .then(([result]) => { if (result.affectedRows === 0) { res.sendStatus(404); } else { res.sendStatus(204); } }) .catch((err) => { console.error(err); res.sendStatus(500); }); }; const login = (req, res) => { const { email, password } = req.body; models.user .findByEmail(email) .then(([users]) => { if (users.length === 0) { res.sendStatus(404); } else if (!argon2.verifySync(users[0].hashedPassword, password)) { res.sendStatus(404); } // else { // const userData = { ...users[0] }; // const token = jwt.sign( // { // id: userData.id, // role: userData.role, // }, // process.env.JWT_SECRET, // { expiresIn: process.env.JWT_EXPIRESIN } // ); // delete userData.hashedPassword; // res // .cookie("accessToken", token, { // httpOnly: true, // secure: process.env.JWT_SECURE === "true", // maxAge: parseInt(process.env.JWT_COOKIE_MAXAGE, 10), // }) // .status(200) // .json(userData); // } }) .catch((err) => { console.error(err); res.sendStatus(500); }); }; const hashPassword = (req, res, next) => { const { password } = req.body; if (!password) { res.sendStatus(400); } else { argon2 .hash(password, hashingOptions) .then((hashedPassword) => { req.body.hashedPassword = hashedPassword; delete req.body.password; next(); }) .catch((err) => { console.error(err); res.sendStatus(500); }); } }; module.exports = { browse, read, edit, add, destroy, login, hashPassword, };
package nitish.doctorbookingapp.service; import nitish.doctorbookingapp.model.Appointment; import nitish.doctorbookingapp.model.Patient; import nitish.doctorbookingapp.model.dto.AuthenticationInputDto; import nitish.doctorbookingapp.repo.IAppointmentRepo; import nitish.doctorbookingapp.repo.IDoctorRepo; import nitish.doctorbookingapp.repo.IPatientRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; @Service public class AppointmentController { @Autowired IAppointmentRepo iAppointmentRepo; @Autowired PTokenService pTokenService; @Autowired IPatientRepo iPatientRepo; @Autowired IDoctorRepo iDoctorRepo; // method to book an appointment public String bookAppointment(AuthenticationInputDto authenticationInput, Appointment appointment) { //patient who has authentiation token they can only book any appointment //calling authenticate method to verify patient if (pTokenService.authenticate(authenticationInput)) { //get email from passed parameter authenticate input String mail = authenticationInput.getEmail(); //using email find patient Patient patient = iPatientRepo.findFirstByPatientEmail(mail); //set appointment appointment.setPatient(patient); //get doctor ID which has to be set in appointment Integer docId = appointment.getDoctor().getDocId(); //check if doctor exists or not by parameter passed doctor id //we are taking doctor id from patient that which doctor he/she wants to book boolean isDoctor = iDoctorRepo.existsById(docId); //if docotr is available then set the time and create appointment if (isDoctor) { appointment.setAppCreationTime(LocalDateTime.now()); iAppointmentRepo.save(appointment); return "apppointment confirmed at" + appointment.getAppCreationTime() + "with Dr." + appointment.getDoctor().getDocName(); } else { return "doctor doesn't exists";//return that doctor doesn't exists } } //if patient doesn't have authentication token then deny the access to book any appointment return "access denied"; } //method to cancel an appointment public String cancelAppointment(AuthenticationInputDto authenticationInput, Long appointmentId) { //verify the user by token //if he/she has valid token then take further inside the method if (pTokenService.authenticate(authenticationInput)) { //get mailID String email = authenticationInput.getEmail(); Patient curPatient = iPatientRepo.findFirstByPatientEmail(email); //find patient and then get the appointment booked already //if appointment is found then take inside the methode or else Appointment exixtingAppointment = iAppointmentRepo.findById(appointmentId).orElse(null); //delete the appointment if (curPatient.equals(exixtingAppointment.getPatient())) { iAppointmentRepo.deleteById(appointmentId); return "appointment with dr." + exixtingAppointment.getDoctor().getDocName() + "has been cancelled"; } //or else unauthorised access //which means patient have valid token but doesn't have any appointment return "UnAuthorised access"; } //not allowed because patient doesn't have access inside and patient doesn't have token return "Unauthenticated access"; } }
import { FC, MouseEvent, useCallback } from "react" import { GlobalMenuItemIconWrapper } from "./GlobalMenuItem.styled" interface Props { className?: string children: React.ReactNode isFocused: boolean onClick?: () => void } const GlobalMenuItem: FC<Props> = ({className, children, isFocused, onClick}) => { const handleOnClick = useCallback((e: MouseEvent) => { onClick && onClick() }, [onClick]) return ( <div className={`${className} flex flex-row items-center w-full gap-x-2 z-0`}> <div className={`${isFocused ? 'text-blue-300' : ''} cursor-pointer hover:text-blue-300`} onClick={handleOnClick}> {children} </div> { isFocused ? <GlobalMenuItemIconWrapper> <img src="/icons/ironman_icon.svg" alt="spiderman_blinker" width="24"/> </GlobalMenuItemIconWrapper> : // <GlobalMenuItemIconWrapper // className={`material-icons-outlined text-sm ${isFocused ? 'text-blue-300' : ''}`} // >keyboard_double_arrow_left</GlobalMenuItemIconWrapper> : <></> } </div> ) } export default GlobalMenuItem
use std::collections::BTreeMap; use nom::{ branch::alt, bytes::complete::tag, character::complete::{ self, alpha1, line_ending, multispace1, }, combinator::eof, multi::{fold_many1, many1}, sequence::{delimited, separated_pair, terminated}, IResult, Parser, }; use crate::custom_error::AocError; #[derive(Debug)] enum Direction { Left, Right, } fn parser( input: &str, ) -> IResult< &str, ( Vec<Direction>, BTreeMap<&str, (&str, &str)>, ), > { let (input, instructions) = many1(alt(( complete::char('R').map(|_| Direction::Right), complete::char('L').map(|_| Direction::Left), )))(input)?; let (input, _) = multispace1(input)?; let (input, map) = fold_many1( terminated( separated_pair( alpha1, tag(" = "), delimited( complete::char('('), separated_pair( alpha1, tag(", "), alpha1, ), complete::char(')'), ), ), alt((line_ending, eof)), ), BTreeMap::new, |mut acc: BTreeMap<&str, (&str, &str)>, (key, value)| { acc.insert(key, value); acc }, )(input)?; Ok((input, (instructions, map))) } #[tracing::instrument] pub fn process( input: &str, ) -> miette::Result<String, AocError> { let (input, (instructions, map)) = parser(input).expect("should validly parse"); debug_assert_eq!(input, ""); let mut current_node = "AAA"; let Some(step_count) = instructions.iter().cycle().enumerate().find_map( |(index, instruction)| { let options = map .get(current_node) .expect("always exist at a valid node"); let next_node = match instruction { Direction::Left => options.0, Direction::Right => options.1, }; if next_node == "ZZZ" { Some(index + 1) } else { current_node = next_node; None } }, ) else { panic!("infinite iterator can't produce None") }; Ok(step_count.to_string()) } #[cfg(test)] mod tests { use rstest::rstest; use super::*; #[rstest] #[case( "RL AAA = (BBB, CCC) BBB = (DDD, EEE) CCC = (ZZZ, GGG) DDD = (DDD, DDD) EEE = (EEE, EEE) GGG = (GGG, GGG) ZZZ = (ZZZ, ZZZ)", "2" )] #[case( "LLR AAA = (BBB, BBB) BBB = (AAA, ZZZ) ZZZ = (ZZZ, ZZZ)", "6" )] fn test_process( #[case] input: &str, #[case] expected: &str, ) -> miette::Result<()> { assert_eq!(expected, process(input)?); Ok(()) } }
/** Copyright 2021 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React, { useState } from "react"; import { useIntl } from "react-intl"; import { useSkills } from "../../hooks/community/useSkills"; import { useUserSkillInterest } from "../../hooks/community/useUserSkillInterest"; import { GetTranslation } from "../../utils/translationService"; import styles from "./ALMSkillComponent.module.css"; const ALMSkillComponent = (props: any) => { const { formatMessage } = useIntl(); const { items, fetchUserSkillInterest, saveUserSkillInterest, removeUserSkillInterest, loadMoreUserSkillInterest, hasMoreItems, } = useUserSkillInterest(); const { skills, fetchSkills, hasMoreSkills, loadMoreSkills } = useSkills(); const [mode, setMode] = useState("view"); const [selectedInterest, setSelectedInterest] = useState([] as any); const generalSkill = "general"; const removeFocus_lxpv = (event: Event) => { const currentSkill = event.target as HTMLElement; if (currentSkill) { currentSkill.blur(); } }; const clearSelectedSkills = () => { setSelectedInterest([]); }; const loadMoreSkillsHandler = async () => { await loadMoreSkills(); }; const toggleSkillSelection = (node: any) => { const skillId = node.id.split("skill-")[1]; let selectedSkills = selectedInterest; if (selectedSkills.indexOf(skillId) > -1) { selectedSkills.splice(selectedSkills.indexOf(skillId), 1); node.style.boxShadow = "none"; node.setAttribute("aria-pressed", "false"); } else { selectedSkills.push(skillId); node.style.boxShadow = "0 0 3pt 3pt #4283d0"; node.setAttribute("aria-pressed", "true"); } setSelectedInterest(selectedSkills); }; const handleClickOnSkillBox = (event: any) => { let node = event.target as HTMLElement; if ( node.className.indexOf("skillBoxSelectable") > -1 || node.className.indexOf("skillNameSelectable") > -1 ) { if (node.className.indexOf("skillName") > -1) { node = node.parentNode as HTMLElement; } toggleSkillSelection(node); } }; const scrollToSkillsSection = () => { document.getElementById("skills-section")?.scrollIntoView(); }; const editSkillInterest = async () => { await fetchSkills(); setMode("edit"); scrollToSkillsSection(); }; const saveSkillInterest = async () => { if (selectedInterest.length !== 0) { await saveUserSkillInterest(selectedInterest); await fetchUserSkillInterest(); } discardSelection(); }; const discardSelection = () => { clearSelectedSkills(); setMode("view"); scrollToSkillsSection(); }; const noSkillInterestPresent = () => { return ( !items || !items.length || items.length === 0 || (items.length === 1 && items[0].skill.name.toLowerCase() === generalSkill) ); }; const noSkillPresent = () => { return ( !skills || !skills.length || skills.length === 0 || (skills.length === 1 && skills[0].name.toLowerCase() === generalSkill) ); }; const removeSkillInterest = async (skillId: any) => { await removeUserSkillInterest(skillId); }; const getSkillLevelName = (levelId: any) => { if (levelId === "1") return formatMessage({ id: "alm.profile.skillLevel.beginner", defaultMessage: "Beginner", }); else if (levelId === "2") return formatMessage({ id: "alm.profile.skillLevel.intermediate", defaultMessage: "Intermediate", }); else if (levelId === "3") return formatMessage({ id: "alm.profile.skillLevel.advanced", defaultMessage: "Advanced", }); else return ""; }; const getFormattedSourceString = (source: any) => { if (source === "ADMIN_ASSIGN") return formatMessage({ id: "alm.profile.skills.adminAssign", defaultMessage: "Added by Admin", }); else if (source === "LO_ENROLL") return formatMessage({ id: "alm.profile.skills.loEnroll", defaultMessage: "Added based on your learnings", }); else if (source === "USER_SELECTED") return formatMessage({ id: "alm.profile.skills.selfAssigned", defaultMessage: "Self Assigned", }); else return ""; }; const getCreditsPercent = (a: any, b: any) => { const percent = (a * 100) / b > 100 ? 100 : (a * 100) / b; return " " + Math.round((percent + Number.EPSILON) * 100) / 100; }; const populateUserSkillInterestLevelData = (userSkillInterest: any) => { let pointsObject = {}; let pointsArray = []; if (userSkillInterest.userSkills) { for (let i = 0; i < userSkillInterest.userSkills.length; i++) { const skillEnrollmentDetails = userSkillInterest.userSkills[i].id.split("_"); const levelId = skillEnrollmentDetails[2]; if (levelId) { pointsObject = { levelId: levelId, pointsAchieved: userSkillInterest.userSkills[i].pointsEarned, totalPoints: userSkillInterest.userSkills[i].skillLevel.maxCredits, }; pointsArray.push(pointsObject); } } } return pointsArray; }; return ( <> <section id="skills-section" className={styles.skillsArea}> <div className={styles.skillsHeading}> {formatMessage({ id: "alm.profile.skills.areasOfInterest", defaultMessage: "Your Areas of Interest", })} </div> <hr /> <div className={styles.skillsDescription}> {formatMessage({ id: "alm.profile.skills.description", defaultMessage: "Select areas of interest. You will see recommendations based on your interest.", })} </div> {/* {!items && <ALMLoader></ALMLoader> } */} {mode === "view" && items?.length > 0 && ( <div className={styles.skillsContainer}> {items .filter( (skillInterest) => skillInterest.skill.name.toLowerCase() !== generalSkill ) .map((skillInterest) => { const id = skillInterest.skill.id; return ( <div key={id} className={styles.skillBox} tabIndex={0} id={"skill-" + id} aria-labelledby={"skillName-" + id} role="group" onMouseDown={(event: any) => { handleClickOnSkillBox(event); }} onMouseLeave={(event: any) => { removeFocus_lxpv(event); }} > <span className={styles.skillName}> {skillInterest.skill.name} </span> <button onClick={() => { removeSkillInterest(id); }} className={styles.removeInterestButton} aria-label={formatMessage({ id: "alm.profile.skills.removeInterest", defaultMessage: "Remove from My interests", })} title={formatMessage({ id: "alm.profile.skills.removeInterest", defaultMessage: "Remove from My interests", })} ></button> <div className={styles.arrowUp}></div> <div className={styles.skillDataTooltip} aria-hidden="true"> {skillInterest.skill.name} <br /> {skillInterest.source === "USER_SELECTED" ? ( `` ) : ( <div> {getFormattedSourceString(skillInterest.source)} </div> )} {populateUserSkillInterestLevelData(skillInterest).map( (level: any) => { return ( <div key={`${level.levelId}_${skillInterest.skill.id}`} > <strong> {getSkillLevelName(level.levelId)} </strong> : {getCreditsPercent( level.pointsAchieved, level.totalPoints )} % {formatMessage({ id: "alm.profile.skills.achieved", defaultMessage: " Achieved", })} </div> ); } )} </div> </div> ); })} </div> )} {mode === "view" && hasMoreItems && ( <button className={styles.showMoreButton} onClick={loadMoreUserSkillInterest} > {formatMessage({ id: "alm.profile.skills.viewMore", defaultMessage: "View more", })} </button> )} {mode === "view" && noSkillInterestPresent() && ( <div className={styles.skillsContainer}> <span> {GetTranslation("alm.profile.skills.noSkillInterest", true)} </span> </div> )} {mode === "view" && ( <div className={styles.modifyInterest}> <button className={`almButton primary ${styles.actionButton}`} onClick={editSkillInterest} > {formatMessage({ id: "alm.profile.skills.modifyInterest", defaultMessage: "Modify Interest", })} </button> </div> )} {mode === "edit" && skills?.length > 0 && ( <div className={styles.skillsContainer}> {skills .filter((skill) => skill.name.toLowerCase() !== generalSkill) .map((skill: any) => ( <button className={styles.skillBoxSelectable} tabIndex={0} id={"skill-" + skill.id} aria-labelledby={"skillName-" + skill.id} onClick={(event: any) => { handleClickOnSkillBox(event); }} onMouseLeave={(event: any) => { removeFocus_lxpv(event); }} aria-pressed={false} > <span className={styles.skillNameSelectable}> {skill.name} </span> </button> ))} </div> )} {mode === "edit" && hasMoreSkills && ( <button className={styles.showMoreButton} onClick={loadMoreSkillsHandler} > {formatMessage({ id: "alm.profile.skills.viewMore", defaultMessage: "View more", })} </button> )} {mode === "edit" && noSkillPresent() && ( <div className={styles.skillsContainer}> <span> {GetTranslation("alm.profile.skills.noSkill", true)} </span> </div> )} {mode === "edit" && ( <div className={styles.modifyInterest}> <button className={`almButton primary ${styles.actionButton}`} onClick={saveSkillInterest} > {formatMessage({ id: "alm.profile.skills.addInterest", defaultMessage: "Add Interest", })} </button> <button className={`almButton secondary ${styles.actionButton}`} onClick={discardSelection} > {formatMessage({ id: "alm.profile.skills.cancel", defaultMessage: "Cancel", })} </button> </div> )} </section> </> ); }; export default ALMSkillComponent;
import Foundation /* - MARK: Access Control 1. 접근 제어는 특정 코드의 접근을 다른 소스파일이나 모듈에서 제한하는 것을 의미한다. 2. 이렇게 하는 이유는 특정 코드의 세부적인 구현을 감추고 딱 필요한 만큼만 공개해 다른 곳에서 사용 가능하도록 하기 위함이다. 3. 접근 제어는 Swift의 거의 모든 문법에서 가능하다. 4. Swift에서는 기본 접근레벨을 제공하여 접근레벨의 처리를 용이하도록 한다. 5. 단일 타깃 앱에서는 특별히 접근 레벨을 명시하지 않아도 된다. 6. Public이 Private보다 높은 접근 레벨을 갖는다고 정의한다. */ /* - MARK: Module & Source File 1. Module: 코드를 배포하는 단일의 단위를 의미한다.하나의 프레임워크나 앱이 이 단위로 배포되고 다른 모듈을 사용할 시 import keyword를 사용한다. 1-1. Xcode의 build target은 Swift에서 분리된 단일 모듈로 취급된다. 2. Source File: Module을 이루고 있는 여러 파일들 중 소스파일을 의미한다. */ /* - MARK: Access Level // - MARK: Open & Public 1. 둘 다 다른 모듈에서 import하여 사용할 수 있다. 2. 다른 점은 Open은 오버라이딩 및 서브클래싱을 통해 함수 및 변수를 변형하여 사용 가능하지만, Public은 사용이 불가능하다. 3. 가장 높은 접근 레벨이다. // - MARK: Internal 1. 기본 접근레벨로 아무 접근 레벨도 설정하지 않으면 Internal로 간주된다. 2. Internal Level과 같은 경우 해당 모듈 전체에서 사용이 가능하도록 설정된다. 3. 해당 모듈에서 사용이 가능하다는 것은 하나의 앱을 구성하는 타겟 안에서는 모두 사용이 가능한 코드라는 말이 된다. // - MARK: File Private 1. 특정 엔티티를 선언한 파일 안에서만 사용이 가능하다. 2. 쉽게 설명하면 같은 소스파일 안에서만 해당 타입이 사용 가능함을 의미한다. // - MARK: Private 1. 특정 엔티티가 선언된 ({})안에서만 사용이 가능하다. 2. 쉽게 말해 특정 클래스, 구조체, 열거형, 익스텐션에 한해 사용이 가능함을 이야기한다. 3. 가장 낮은 접근 레벨이다. */ /* - MARK: Guiding Principle of Access Level 1. Swift에서는 더 낮은 접근 수준을 가진 엔티티에 특정 엔티티를 선언해 사용할 수 없다는 일반 가이드의 원칙을 따른다. 1-1. 예를 들어, Public 변수는 다른 internal, file-private, private 타입 등에서 정의될 수 없다. 왜냐하면 이렇게 되면 Public 변수는 Public 변수가 사용 될 곳들에서 사용이 불가해지기 때문이다. 2. 함수에서는 parameter 혹은 return value보다 더 높은 접근 레벨을 가질 수 없다. 2-1. 예를 들어, 함수가 더 높은 접근 레벨을 가진다고 가정하게 되면 함수에는 접근했는데 parameter 혹은 return value에 접근을 못해 함수를 사용할 수 없게 되기 때문이다. // - MARK: Default Access Level 1. 기본적으로 아무런 접근 레벨을 명시하지 않은 경우 Internal access Level을 가지게 된다. // - MARK: Access Levels for Single-target App 1. 단일 타깃 앱에서는 접근 레벨을 정의할 필요가 없지만, file-private 이나 private을 통해 앱 내에서 구현 사항을 숨길 수 있다. // - MARK: Access Levels for Frameworks 1. 프레임워크 개발 시, 다른 사람들이 해당 모듈에 접근 가능하도록 만들어야하기 때문에 public 혹은 open으로 만들어야 한다. 2. 프레임워크 개발 시, 구현의 감추고 싶은 부분이 존재한다면 internal을 선언해 감추면 된다. */ /* - MARK: Access levels for Test Targets 1. 기본적으로 open 혹은 public으로 지정된 엔티티만 외부 모듈에서 접근이 가능하다. 2. 하지만 유닛 테스트를 하는 경우에 모듈을 import 하기 위해 import 앞에 @testable이라는 attribute을 사용하여 붙여주면 해당 모듈을 테스트가 가능한 모듈로 컴파일하여 사용한다. */ /* - MARK: Access Control Syntax /* public class SomePublicClass {} internal class SomeInternalClass {} fileprivate class SomeFilePrivateClass {} private class SomePrivateClass {} public var somePublicVariable = 0 internal let someInternalConstant = 0 fileprivate func someFilePrivateFunction() {} private func somePrivateFunction() {} */ 1. 위의 구조처럼 각 접근차를 변수 타입 앞에 선언해주어 접근자를 명시 할 수 있다. 2. Interal 접근자는 생략하여 사용할 수 있다. */ /* - MARK: Custom Types 1. 커스텀 클래스에 특정 접근 레벨을 부여하면 해당 클래스 안의 프로퍼티, 매소드 등 모든 멤버의 접근 권한에 영향을 미친다. 2. Public Type은 기본적으로 Internal 맴버를 갖는다. 그 이유는 Framework 개발 시, 노출되면 안되는 API를 보호하기 위해서 설정되어 있는 것이다. 2-1. 만약 Public Type안의 맴버를 public하게 사용하고 싶다면 public 접근자를 붙여주면 된다. /* public class SomePublicClass { // explicitly public class public var somePublicProperty = 0 // explicitly public class member var someInternalProperty = 0 // implicitly internal class member fileprivate func someFilePrivateMethod() {} // explicitly file-private class member private func somePrivateMethod() {} // explicitly private class member } class SomeInternalClass { // implicitly internal class var someInternalProperty = 0 // implicitly internal class member fileprivate func someFilePrivateMethod() {} // explicitly file-private class member private func somePrivateMethod() {} // explicitly private class member } fileprivate class SomeFilePrivateClass { // explicitly file-private class func someFilePrivateMethod() {} // implicitly file-private class member private func somePrivateMethod() {} // explicitly private class member } private class SomePrivateClass { // explicitly private class func somePrivateMethod() {} // implicitly private class member } */ */ /* - MARK: Tuple Types 1. 튜플 타입은 사용되는 클래스, 구조체, 열거형, 함수등에 따라 자동으로 최소 레벨을 부여받는다. 2. 튜플은 가장 제한적인 레벨을 부여받기 때문에 명시적으로 접근자를 지정하지 않는다. */ /* - MARK: Function Types 1. 함수 타입의 접근 레벨은 파라미터 타입과 리턴 타입의 접근 레벨을 고려해 가장 낮은 최소의 접근레벨 이하의 레벨을 사용 해야 한다. 2. 그렇지 않으면 컴파일 시 에러를 발생시키게 된다. [Example] 1. Make Error: func someFunction() -> (SomeInternalClass, SomePrivateClass) { // function implementation goes here } 2. Fixed private func someFunction() -> (SomeInternalClass, SomePrivateClass) { // function implementation goes here } */ /* - MARK: Enumeration Types 1. 열거형의 각 Case는 열거형의 접근 레벨과 같은 접근 레벨을 부여 받는다. 2. 열거형의 각 Case는 개별적인 접근 레벨을 가질 수 없다. */ /* - MARK: Raw Values & Associate Value 1. 고유 값과 연관 값을 사용하는 경우 반드시 해당 타입보다 높은 접근 레벨을 가져야한다. // - MARK: Raw Values class Car: Int { case modelA = 0 case modelB = 1 case modelC = 2 } // - MARK: Associate Values class Animal { case dog(name: String) case cat(name: String) } */ /* - MARK: Nested Types 1. 중첩 타입으로 선언 된 타입은 상위에 묶여있는 타입의 접근 레벨과 동일한 접근 레벨을 갖는다. 2. 절대 더 낮은 접근 레벨을 갖을 수 없다. */ /* -MARK: SubClassing 1. 서브클래스는 수퍼클래스보다 더 높은 접근 레벨을 가질 수 없다. 1-1. 하지만 가끔 superClass보다 더 높은 접근 레벨을 갖는 경우가 있다. 예를 들어, 특정 method를 더 높은 접근 레벨로 오버라이드 했다고 가정했을 때, super.someMethod()를 호출하는 것이 가능하기 때문이다. 1-2. 서브 클래스에서 super.someMethod()를 호출하는 코드를 넣게 되면 결국 그 매소드를 사용하려면 접근 레벨이 그만큼 낮아지기 때문에 이러한 행위가 가능해지는 것이다. */ /* - MARK: Constants, Variables, Properties and Subscripts 1. 상수, 변수, 프로퍼티, 서브스크립트는 해당 타입보다 더 낮거나 높은 접근 레벨을 가질 수 없다. 2. 즉 같은 접근 레벨 혹은 더 낮은 접근 레벨을 가져야 한다. // - MARK: Getters & Setters 1. 상수, 변수, 프로퍼티, 서브스크립트와 동일한 접근 레벨을 갖는다. 2. 필요에 따라 Setter의 접근 레벨을 Getter의 접근 레벨보다 낮게 갖게 할 수 있다. - MARK: Set Setter's Access Level /* struct TrackedString { private(set) var numberOfEdits = 0 var value: String = "" { didSet { numberOfEdits += 1 } } } */ - MARK: Set Getter's Access Level too /* public struct TrackedString { public private(set) var numberOfEdits = 0 public var value: String = "" { didSet { numberOfEdits += 1 } } public init() {} } */ */ /* - MARK: Initializers 1. 기본적으로 초기자의 접근 레벨은 해당 타입과 같거나 낮아야 한다. 2. 예외적으로 지정 초기자(required initalizer)는 무조건 접근 레벨이 해당 타입과 같아야 한다. 2-1. 만약 지정 초기자의 접근 레벨이 더 낮은 경우 지정 초기자를 초기화 할 수 없는 경우가 발생할 수 있기 때문이다. // - MARK: Default Initializers 1. 기본 초기자는 Public 타입의 초기자가 아닌 이상 해당 타입과 동일한 접근 레벨을 갖는다. 2. 만약 public 타입으로 설정되어 있다면, 기본 초기자는 internal 접근 레벨을 기본적으로 갖는다. // - MARK: Default Memberwise Initializers for Structure Types 1. private, file-private 접근 레벨을 제외하고 다른 경우는 모두 internal level을 갖는다. 2. 위의 두 경우에는 동일한 접근 레벨을 갖는다 */ /* - MARK: Protocols 1. 기본적으로 protocol의 접근 레벨과 그 안의 요구사항들의 접근 레벨은 동일하다. // - MARK: Protocol Inheritance 1. 이미 존재하는 프로토콜을 상속받은 경우 상속받은 프로토콜은 같은 접근 레벨을 갖는다. // - MARK: Protocol Conformance 1. 해당 프로토콜에 순응할 시, 프로토콜에서의 요구사항의 구현은 무조건 protocol의 접근레벨에 맞게 제어해줘야 한다. */ /* - MARK: Extensions 1. 기존의 타입이 선언될 때 설정한 접근 레벨과 같은 레벨을 갖는다. 2. 익스텐션에 명시적으로 접근자를 제어할 수 있다. 3. 프로토콜의 Extension에서는 접근자를 제어할 수 없다. // - MARK: Private Members of Extension 1. 원본 선언에서 private 맴버로 선언한 것을 익스텐션에서 맴버로 접근할 수 있다. 2. 하나의 익스텐션에서 private으로 설정한 맴버를 같은 파일의 다른 익스텐션에서 맴버로 접근할 수 있다. 3. 하나의 익스텐션에서 private으로 선언한 맴버는 원본 선언에서 맴버로 사용할 수 있다. */ /* - MARK: Generic 1. 지네릭 타입은 해당 타입 혹은 함수, 자체 파라미터 타입 중 최소 접근 레벨을 갖는다. */ /* - MARK: Type aliases 1. 기존 타입을 다른 별칭으로 지정하는 타입은 본래의 타입이랑 같거나 낮은 접근 레벨을 갖는다. 2. 예를 들어, private인 타입이 존재한다고 할 때 별칭 타입은 private, file-private, public, open, internal 타입으로 선언 할 수 있다. */
import { createAsyncThunk } from "@reduxjs/toolkit"; import { logIn, checkUser, logout } from "../../api/authApi"; export const userLogin = createAsyncThunk("auth/userLogin", async (reqData, thunkAPI) => { try { const response = await logIn(reqData); if (response.error) { localStorage.removeItem("userToken"); return thunkAPI.rejectWithValue(); } else { localStorage.setItem("userToken", response.token); return response; } } catch (error) { const message = error?.response?.data?.message || error.message || error.toString(); thunkAPI.dispatch(message); return thunkAPI.rejectWithValue(); } }); export const checkUserToken = createAsyncThunk("auth/checkToken", async (token, thunkAPI) => { try { const response = await checkUser(token); console.log(`checkUserToken response ${JSON.stringify(response)}`); if (response.error) { localStorage.removeItem("userToken"); return thunkAPI.rejectWithValue(); } else { localStorage.setItem("userToken", response.token); return response; } // store user's token in local storage } catch (error) { const message = error.toString(); thunkAPI.dispatch(message); return thunkAPI.rejectWithValue(); } }); export const userLogout = createAsyncThunk("auth/userLogout", async (reqData, thunkAPI) => { try { const response = await logout(reqData); return response; } catch (error) { const message = error?.response?.data?.message || error.message || error.toString(); thunkAPI.dispatch(message); return thunkAPI.rejectWithValue(); } });
--- title: Wyklucz czcionki z renderowanego kodu HTML linktitle: Wyklucz czcionki z renderowanego kodu HTML second_title: GroupDocs.Viewer API .NET description: Dowiedz się, jak wykluczać czcionki z renderowanego kodu HTML przy użyciu narzędzia GroupDocs.Viewer dla platformy .NET. Postępuj zgodnie z tym przewodnikiem krok po kroku, aby uzyskać płynne wyświetlanie dokumentów. type: docs weight: 10 url: /pl/net/rendering-documents-html/exclude-fonts-html/ --- ## Wstęp GroupDocs.Viewer dla .NET to potężna biblioteka do renderowania dokumentów, która umożliwia programistom wyświetlanie ponad 50 formatów dokumentów w aplikacjach .NET bez konieczności stosowania zewnętrznych zależności. W tym samouczku skupimy się na konkretnej funkcji GroupDocs.Viewer: wykluczaniu czcionek z renderowanego wyniku HTML. ## Warunki wstępne Zanim zaczniesz, upewnij się, że masz następujące elementy: 1. Podstawowa znajomość programowania w C# i .NET. 2. Zainstalowany GroupDocs.Viewer dla .NET. Można go pobrać z[Tutaj](https://releases.groupdocs.com/viewer/net/). 3. Visual Studio lub dowolne inne IDE do programowania w języku C#. ## Importuj przestrzenie nazw W kodzie C# pamiętaj o uwzględnieniu niezbędnych przestrzeni nazw: ```csharp using System; using System.IO; using GroupDocs.Viewer.Options; ``` ## Krok 1: Zdefiniuj katalog wyjściowy Skonfiguruj katalog, w którym chcesz zapisywać renderowane pliki HTML. ```csharp string outputDirectory = "Your Document Directory"; ``` ## Krok 2: Zdefiniuj format ścieżki pliku strony Określ format ścieżek plików poszczególnych stron renderowanego dokumentu. ```csharp string pageFilePathFormat = Path.Combine(outputDirectory, "page_{0}.html"); ``` ## Krok 3: Zainicjuj obiekt przeglądarki Utwórz instancję obiektu Viewer z dokumentem, który chcesz wyrenderować. ```csharp using (Viewer viewer = new Viewer("YourDocumentPath")) { // Twój kod trafia tutaj } ``` ## Krok 4: Ustaw opcje widoku HTML Zdefiniuj opcje renderowania HTML, w tym format osadzonych zasobów i czcionek do wykluczenia. ```csharp HtmlViewOptions options = HtmlViewOptions.ForEmbeddedResources(pageFilePathFormat); options.FontsToExclude.Add("Arial"); ``` ## Krok 5: Renderuj dokument Przekaż opcje widoku HTML do obiektu Viewer, aby wyrenderować dokument. ```csharp viewer.View(options); ``` ## Krok 6: Wyprowadź lokalizację wyrenderowanego dokumentu Poinformuj użytkownika o lokalizacji, w której zapisywane są wyrenderowane pliki HTML. ```csharp Console.WriteLine($"\nSource document rendered successfully.\nCheck output in {outputDirectory}."); ``` ## Wniosek W tym samouczku nauczyliśmy się, jak używać programu GroupDocs.Viewer dla platformy .NET do wykluczania czcionek z renderowanych danych wyjściowych HTML. Wykonując kroki opisane powyżej, możesz dostosować proces renderowania do swoich konkretnych wymagań, zapewniając optymalne wyświetlanie dokumentów w swoich aplikacjach. ## Często zadawane pytania ### Czy mogę wykluczyć wiele czcionek z renderowanego kodu HTML? Tak, możesz dodać wiele nazw czcionek do pliku`FontsToExclude` lista w opcjach widoku HTML. ### Czy GroupDocs.Viewer jest kompatybilny ze wszystkimi frameworkami .NET? Tak, GroupDocs.Viewer obsługuje .NET Framework 4.6.1 i nowsze wersje. ### Czy mogę renderować dokumenty ze zdalnych lokalizacji? Tak, GroupDocs.Viewer obsługuje renderowanie dokumentów z magazynu lokalnego, a także zdalnych lokalizacji i strumieni. ### Czy GroupDocs.Viewer obsługuje responsywne projektowanie danych wyjściowych HTML? Tak, możesz włączyć renderowanie responsywne, dostosowując odpowiednio opcje widoku HTML. ### Czy dostępna jest pomoc techniczna dla GroupDocs.Viewer? Tak, możesz szukać pomocy i brać udział w dyskusjach na temat[Forum GroupDocs.Viewer](https://forum.groupdocs.com/c/viewer/9).
<template> <view> <!-- 选择收货地址的盒子 --> <!-- 没有数据展示 --> <view class="address-choose-box" v-if="JSON.stringify(address) === '{}'"> <button type="primary" size="mini" class="btnChooseAddress" @click="chooseAddress"> 请选择收货地址+ </button> </view> <!-- 选择收货地址信息的盒子 --> <!-- 有数据时展示 --> <view class="address-info-box" v-else @click="chooseAddress"> <view class="row1"> <view class="row1-left"> <view class="username" >收货人:<text>{{ address.userName }}</text></view > </view> <view class="row1-right"> <view class="phone" >电话:<text>{{ address.telNumber }}</text></view > <uni-icons type="arrowright" size="16"></uni-icons> </view> </view> <view class="row2"> <view class="row2-left">收货地址:</view> <view class="row2-right">{{ Theaddress }} </view> </view> </view> <!-- 底部的边框线 --> <image src="/static/cart_border@2x.png" class="address-border"></image> </view> </template> <script> import { mapState, mapMutations, mapGetters } from 'vuex' export default { data() { return {} }, methods: { ...mapMutations('m_user', ['updateAddress']), // 选择收货地址 async chooseAddress() { // 通过catch来捕获错误 const [err, succ] = await uni.chooseAddress().catch(err => err) // 选择了收货地址 if (err === null && succ.errMsg === 'chooseAddress:ok') { this.updateAddress(succ) } // 授权(安装和ios) if ( (err && err.errMsg === 'chooseAddress:fail auth deny') || err.errMsg === 'chooseAddress:fail authorize no response' ) { this.reAuth() // 重新授权 } }, // 地址授权 async reAuth() { // 提示消息 const [err2, confirmResult] = await uni.showModal({ content: '检测到您没打开地址权限,是否去设置打开?', confirmText: '确认', cancelText: '取消', }) if (err2) return // 遇到异常直接退出 // 点击了取消 if (confirmResult.cancel) return uni.$showMsg('您取消了地址授权!') // 点击了确定 if (confirmResult.confirm) // 进行授权 return uni.openSetting({ success: settingResult => { if (settingResult.authSetting['scope.address']) return uni.$showMsg('授权成功!请选择地址') if (!settingResult.authSetting['scope.address']) return uni.$showMsg('您取消了地址授权!') }, }) }, }, computed: { ...mapState('m_user', ['address']), ...mapGetters('m_user', ['Theaddress']), }, } </script> <style lang="scss"> // 底部边框线的样式 .address-border { display: block; width: 100%; height: 5px; } // 选择收货地址的盒子 .address-choose-box { height: 90px; display: flex; align-items: center; justify-content: center; } // 渲染收货信息的盒子 .address-info-box { font-size: 12px; height: 90px; display: flex; flex-direction: column; justify-content: center; padding: 0 5px; // 第一行 .row1 { display: flex; justify-content: space-between; .row1-right { display: flex; align-items: center; .phone { margin-right: 5px; } } } // 第二行 .row2 { display: flex; align-items: center; margin-top: 10px; .row2-left { white-space: nowrap; } } } </style>
import { Pipe, PipeTransform } from '@angular/core'; import {Store} from "../interfaces/store"; @Pipe({ name: 'filterStores' }) export class FilterStoresPipe implements PipeTransform { transform(items: Array<Store>, searchText: string) { const data = searchText.toLowerCase(); return items.filter(item => item.description?.toLowerCase() === data || item.code?.toLowerCase() === data || item.description?.toLowerCase().includes(data) || item.code?.toLowerCase().includes(data) ); } }
import { getServiceOrRegister } from '@blocksuite/blocks'; import { checkboxPureColumnConfig } from '@blocksuite/blocks/database-block/common/columns/checkbox/define'; import { datePureColumnConfig } from '@blocksuite/blocks/database-block/common/columns/date/define'; import { linkPureColumnConfig } from '@blocksuite/blocks/database-block/common/columns/link/define'; import { multiSelectColumnConfig } from '@blocksuite/blocks/database-block/common/columns/multi-select/cell-renderer'; import { numberPureColumnConfig } from '@blocksuite/blocks/database-block/common/columns/number/define'; import { progressPureColumnConfig } from '@blocksuite/blocks/database-block/common/columns/progress/define'; import { richTextPureColumnConfig } from '@blocksuite/blocks/database-block/common/columns/rich-text/define'; import type { DatabaseBlockModel } from '@blocksuite/blocks/models'; import { assertExists, Text, type Workspace } from '@blocksuite/store'; import { type InitFn } from './utils'; export const database: InitFn = async (workspace: Workspace, id: string) => { const page = workspace.createPage({ id }); await page.waitForLoaded(); page.awarenessStore.setFlag('enable_database', true); page.awarenessStore.setFlag('enable_database_filter', true); page.awarenessStore.setFlag('enable_data_view', true); // Add page block and surface block at root level const pageBlockId = page.addBlock('affine:page', { title: new Text('Welcome to BlockSuite Playground'), }); page.addBlock('affine:surface', {}, pageBlockId); // Add note block inside page block const noteId = page.addBlock('affine:note', {}, pageBlockId); const pId = page.addBlock('affine:paragraph', {}, noteId); const model = page.getBlockById(pId); assertExists(model); // Add database block inside note block const databaseId = page.addBlock( 'affine:database', { columns: [], cells: {}, }, noteId ); const service = await getServiceOrRegister('affine:database'); service.initDatabaseBlock(page, model, databaseId, 'table', true); const database = page.getBlockById(databaseId) as DatabaseBlockModel; database.addColumn( 'end', numberPureColumnConfig.create(numberPureColumnConfig.name) ); database.addColumn( 'end', richTextPureColumnConfig.create(richTextPureColumnConfig.name) ); database.addColumn( 'end', datePureColumnConfig.create(datePureColumnConfig.name) ); database.addColumn( 'end', linkPureColumnConfig.create(linkPureColumnConfig.name) ); database.addColumn( 'end', progressPureColumnConfig.create(progressPureColumnConfig.name) ); database.addColumn( 'end', checkboxPureColumnConfig.create(checkboxPureColumnConfig.name) ); database.addColumn( 'end', multiSelectColumnConfig.create(multiSelectColumnConfig.name) ); // Add a paragraph after database page.addBlock('affine:paragraph', {}, noteId); page.addBlock('affine:paragraph', {}, noteId); page.addBlock('affine:paragraph', {}, noteId); page.addBlock('affine:paragraph', {}, noteId); page.addBlock('affine:paragraph', {}, noteId); page.addBlock('affine:paragraph', {}, noteId); database.addView('kanban'); page.resetHistory(); }; database.id = 'database'; database.displayName = 'Database Example'; database.description = 'Database block basic example';
import argparse import gc import os from pathlib import Path from typing import List, Union from loguru import logger from clip_video_encode import clip_video_encode from datasets import VSPD def embed_vids(vids_to_encode: List[Union[str, os.PathLike]], out_dir: str, encoder_type: str = "blip2_both", batch_size: int = 100): """Embed the videos in batches """ # clip_video_encode expects both vids and dest to be strings # So we explicitly cast it as so vids_to_encode = [str(vid) for vid in vids_to_encode] for i in range(0, len(vids_to_encode) // batch_size + 1): start = i * batch_size end = min(start + batch_size, len(vids_to_encode)) vids = vids_to_encode[start: end] logger.info(f'Processing {start=}, {end=}') clip_video_encode(vids, dest=out_dir, output_format="files", take_every_nth=20, encoder_type=encoder_type, output_key_start=start, frame_workers=4, n_final_frames=8, ) # Garbage Collect to try to avoid memory leaks gc.collect() def main(): parser = argparse.ArgumentParser(description='Embed the raw video files and dump them') parser.add_argument('--dataset', required=True, type=str.lower, choices=["vspd", "tiktok-9k"], help='The dataset to be embedded') parser.add_argument('--data-dir', required=True, type=str, help='The root directory of the dataset') parser.add_argument('--out-dir', required=True, type=str, help='The output directory') parser.add_argument('--encoder-type', type=str, default="blip2_both", help='The Encoder type to use') parser.add_argument('--batch-size', type=int, default=100, help='Num of vids to embed in a batch') args = parser.parse_args() logger.info(args) # Create the output directory EMBEDDING_DIR_BASE = Path(args.out_dir).expanduser() EMBEDDING_DIR_BASE.mkdir(exist_ok=True) if args.dataset == 'vspd': dataset = VSPD(args.data_dir) elif args.dataset == 'tiktok-9k': ... paths, ids = dataset.paths() embed_vids( vids_to_encode=paths, out_dir=args.out_dir, encoder_type=args.encoder_type, batch_size=args.batch_size, ) if __name__ == '__main__': main()
<?php namespace Tests\Feature; use App\Models\Task; use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class TaskApiTest extends TestCase { use RefreshDatabase; protected $user; protected $other_user; protected function setUp(): void { parent::setUp(); $this->user = User::factory()->create(); $this->other_user = User::factory()->create(); $this->user->access_token = $this->user->createToken('auth')->plainTextToken; } public function test_task_created(): void { $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $this->user->access_token ])->postJson('/graphql', [ 'query' => ' mutation createTask($title: String!) { createTask(title: $title) { id title status user_id } } ', 'variables' => [ 'title' => 'Test Title', ], ]); $data = json_decode($response->getContent(), true); $response->assertJson([ 'data' => [ 'createTask' => [ 'id' => $data['data']['createTask']['id'], 'title' => 'Test Title', 'status' => false, 'user_id' => $this->user->id ] ] ]); } public function test_task_updated(): void { $task = Task::factory()->create(['user_id' => $this->user->id]); $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $this->user->access_token ])->postJson('/graphql', [ 'query' => ' mutation updateTask($title: String!, $id: ID!, $status: Boolean!) { updateTask(title: $title, id: $id, status: $status) { id title status user_id } } ', 'variables' => [ 'id' => $task->id, 'title' => 'Test Title Updated', 'status' => true, ], ]); $data = json_decode($response->getContent(), true); $response->assertJson([ 'data' => [ 'updateTask' => [ 'id' => $data['data']['updateTask']['id'], 'title' => 'Test Title Updated', 'status' => true, 'user_id' => $this->user->id ] ] ]); } public function test_task_deleted(): void { $task = Task::factory()->create(['user_id' => $this->user->id]); $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $this->user->access_token ])->postJson('/graphql', [ 'query' => ' mutation deleteTask($id: ID!) { deleteTask(id: $id) { msg } } ', 'variables' => [ 'id' => $task->id ], ]); $data = json_decode($response->getContent(), true); $response->assertJson([ 'data' => [ 'deleteTask'=> [ 'msg' => 'Task deleted successfully.' ] ] ]); } public function test_task_delete_by_status(): void { $task = Task::factory()->create(['user_id' => $this->user->id]); $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $this->user->access_token ])->postJson('/graphql', [ 'query' => ' mutation deleteTaskByStatus($status: Boolean!) { deleteTaskByStatus(status: $status) { msg } } ', 'variables' => [ 'status' => false ], ]); $data = json_decode($response->getContent(), true); $response->assertJson([ 'data' => [ 'deleteTaskByStatus'=> [ 'msg' => 'Task deleted successfully.' ] ] ]); } public function test_delete_all_task_by_current_user(): void { $task = Task::factory()->create(['user_id' => $this->user->id]); $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $this->user->access_token ])->postJson('/graphql', [ 'query' => ' mutation { deleteAllTask { msg } } ' ]); $data = json_decode($response->getContent(), true); $response->assertJson([ 'data' => [ 'deleteAllTask'=> [ 'msg' => 'Task deleted successfully.' ] ] ]); } public function test_update_constraints(): void { $task = Task::factory()->create(['user_id' => $this->other_user->id]); $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $this->user->access_token ])->postJson('/graphql', [ 'query' => ' mutation updateTask($title: String!, $id: ID!, $status: Boolean!) { updateTask(title: $title, id: $id, status: $status) { id title status user_id } } ', 'variables' => [ 'id' => $task->id, 'title' => 'Test Title Updated', 'status' => true, ], ]); $response->assertJsonFragment([ "message" => "You are not authorized to delete this task." ]); } public function test_delete_constraints(): void { $task = Task::factory()->create(['user_id' => $this->other_user->id]); $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $this->user->access_token ])->postJson('/graphql', [ 'query' => ' mutation deleteTask($id: ID!) { deleteTask(id: $id) { msg } } ', 'variables' => [ 'id' => $task->id ], ]); $response->assertJsonFragment([ "message" => "You are not authorized to delete this task." ]); } }
import React from 'react' import Screen from '../components/Screen' import { FlatList } from 'react-native-gesture-handler' import Card from '../components/Card' import { StyleSheet } from 'react-native' import colors from '../config/colors' const listing = [ { id: 1, title: 'Jean Jacket for sale', price: 100, image: require('../assets/jeanJacket.jpg') }, { id: 2, title: 'Good as new old chair', price: 1000, image: require('../assets/oldChair.jpg') }, ] const ListingsScreen = () => { return ( <Screen style={styles.screen}> <FlatList data={listing} keyExtractor={(listing) => listing.id.toString()} renderItem={({item}) => <Card title={item.title} subTitle={'$' + item.price} image={item.image}/>} /> </Screen> ) }; const styles = StyleSheet.create({ screen: { padding: 20, backgroundColor: colors.light, } }) export default ListingsScreen
<script setup lang="ts"> import { reactive, computed } from 'vue'; import { useRecipeStore } from '@/stores/recipes'; import { useRouter } from 'vue-router'; import type { RecipeI } from '@/types/recipe'; // Define a new interface for form data interface FormData { image: string; name: string; description: string; ingredients: string; instructions: string; } // Access recipe store and router const recipeStore = useRecipeStore(); const router = useRouter(); // Define reactive form data object const formData = reactive<FormData>({ image: '', name: '', description: '', ingredients: '', instructions: '' }); // Computed property to determine if the form is invalid const isFormInvalid = computed(() => { return Object.values(formData).some((value) => !value); }); // Function to handle image upload const handleImageUpload = (event: Event) => { const target = event.target as HTMLInputElement; const file = (target.files as FileList)[0]; if (file) { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { formData.image = reader.result as string; }; } }; // Function to handle form submission const handleFormSubmit = async () => { try { const ingredients: string[] = formData.ingredients .split('\n') .map((ingredient: string) => ingredient.trim()); const newRecipe: RecipeI = { id: Date.now().toString(), ...formData, ingredients, status: 'pending', createdAt: new Date().toISOString() }; await recipeStore.addRecipe(newRecipe); // Reset form data resetForm(); router.push({ name: 'home' }); } catch (error) { console.error('Error adding recipe:', error); } }; // Function to reset form data const resetForm = () => { Object.assign(formData, { image: '', name: '', description: '', ingredients: '', instructions: '' }); }; </script> <template> <form @submit.prevent="handleFormSubmit" class="grid grid-cols-12 gap-4"> <div class="col-span-12 md:col-span-6"> <!-- Recipe image upload --> <div class="mb-4"> <label class="block mb-2 text-sm font-medium text-gray-900" for="recipe_image" >Upload image</label > <input class="block w-full text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 focus:outline-none file:py-2 file:px-3 file:border-none file:bg-violet-500 file:text-white hover:file:cursor-pointer hover:file:bg-violet-600 transition-all" id="recipe_image" type="file" accept="image/*" @change="handleImageUpload" required /> </div> <!-- Recipe name --> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="name"> Name </label> <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="name" type="text" placeholder="Enter recipe name" required v-model="formData.name" /> </div> <!-- Recipe description --> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="description"> Description </label> <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="description" placeholder="Enter recipe description" rows="6" required v-model="formData.description" ></textarea> </div> </div> <div class="col-span-12 md:col-span-6"> <!-- Recipe ingredients --> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="ingredients"> Ingredients </label> <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="ingredients" placeholder="Enter recipe ingredients" rows="6" required v-model="formData.ingredients" ></textarea> </div> <!-- Recipe instructions --> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="instructions"> Instructions </label> <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="instructions" placeholder="Enter recipe instructions" rows="6" required v-model="formData.instructions" ></textarea> </div> <!-- Recipe submit action --> <div class="flex justify-end"> <button :class="`bg-violet-500 hover:bg-violet-600 text-white font-semibold py-2 px-4 rounded focus:outline-none focus:shadow-outline ${isFormInvalid || recipeStore.isLoading ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'} `" type="submit" :disabled="isFormInvalid || recipeStore.isLoading" > {{ recipeStore.isLoading ? 'Creating Recipe...' : 'Create Recipe' }} </button> </div> </div> </form> </template>
<mat-sidenav-container class="app-sidenav-container" [class.dark-theme]="isDarkTheme" [dir]="this.dir"> <mat-sidenav #sidenav [mode]="isScreenSmall() ? 'over' : 'side'" [opened] = !isScreenSmall() class="app-sidenav mat-elevation-z10"> <mat-toolbar color="primary"> Contacts </mat-toolbar> <mat-nav-list> <mat-list-item *ngFor="let user of users | async"> <a matLine [routerLink]="['/app', user.id ]"> <mat-icon svgIcon='{{user.avatar}}'></mat-icon> {{ user.name }}</a> </mat-list-item> </mat-nav-list> </mat-sidenav> <mat-sidenav-content> <app-toolbar (toggleSidenav)="sidenav.toggle()" (toggleTheme)="toggleTheme()" (toggleDir)="toggleDir()"></app-toolbar> <div class="wrapper"> <router-outlet></router-outlet> </div> </mat-sidenav-content> </mat-sidenav-container>
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#" style="font-weight: bold;"><i class="fa-solid fa-earth-africa"></i>XSHOP</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> </ul> <form action="/logoutForm" method="get" class="d-flex input-group w-auto"> <button class="btn btn-outline-primary" type="submit" data-mdb-ripple-color="dark" > Logout </button> </form> </div> </div> </nav> {{! Carousel }} <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel" > <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1" ></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2" ></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3" ></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="https://images.pexels.com/photos/322207/pexels-photo-322207.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" style="height: 700px;" class="d-block w-100" alt="..." /> </div> <div class="carousel-item"> <img src="https://images.pexels.com/photos/135620/pexels-photo-135620.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" style="height: 700px;" class="d-block w-100" alt="..." /> </div> <div class="carousel-item"> <img src="https://images.pexels.com/photos/291762/pexels-photo-291762.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" style="height: 700px;" class="d-block w-100" alt="..." /> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev" > <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next" > <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> {{! End of carousel }} {{! Card }} <div class="container-fluid"> <div class="row row-cols-1 row-cols-md-3 g-4 mt-4"> {{#each product}} <div class="col-lg-3 col-md-6 sm-12"> <div class="card h-100"> <img src="{{this.image}}" style="height: 300px; width: 300px; margin-left: 30px;" class="card-img-top" alt="Carousel-Image" /> <div class="card-body"> <h5 class="card-title">{{this.title}}</h5> <p class="card-text" style="font-weight: bold;">Price : ${{this.price}}/-</p> <p class="card-text" style="font-weight: 600;">Category : {{this.category}}</p> <p class="card-text">{{this.description}}</p> </div> <div class="card-footer" style="display: flex;"> <button type="button" class="btn btn-primary">Buy Now</button> <p style="margin-left: auto; font-weight: bolder;" class="card-text mt-1" >Rating : {{this.rating.rate}}</p> </div> </div> </div> {{/each}} </div> </div> {{! End of card }} {{! Footer }} <div class="container-fluid"> <footer class="d-flex flex-wrap justify-content-between align-items-center py-3 my-4" style=" border-top: 2px solid rgb(41, 37, 37);" > <p class="col-md-4 col-sm-12 mb-0" style="margin: auto; padding-left: 120px;">&copy; Powerd By : 2021 RocketJS</p> </footer> </div> {{! End of Footer }}
# app/models.py from flask import current_app from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(120), nullable=False) monthly_budget = db.Column(db.Float, nullable=False, default=1e9) phone_num = db.Column(db.Integer, nullable=False, default=1) def __repr__(self): return f'<User {self.username}>' def save_to_db(self): db.session.add(self) db.session.commit() def update_password(self, new_password): try: self.password = new_password db.session.commit() return True except Exception as e: current_app.logger.error(f"Error updating user password: {str(e)}") db.session.rollback() return False def update_monthly_budget(self, new_budget): try: self.monthly_budget = new_budget db.session.commit() return True except Exception as e: current_app.logger.error(f"Error updating user monthly budget: {str(e)}") db.session.rollback() return False def update_phone_number(self, new_phone_num): try: self.phone_num = new_phone_num db.session.commit() return True except Exception as e: current_app.logger.error(f"Error updating user phone number: {str(e)}") db.session.rollback() return False from datetime import datetime from app import db class Expense(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) call_duration = db.Column(db.Integer, nullable=False, default=0) messages = db.Column(db.Integer, nullable=False, default=0) data_usage = db.Column(db.Float, nullable=False, default=0.0) timestamp = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
/** summary: 介绍什么是联结,为什么使用联结,如何编写联结的SELECT语句 12-1: 联结 SQL最强大的功能之一就是能在数据查询的执行中联结(join)表。联结是利用SQL的SELECT能执行的最重要的操作。 12-1-1: 关系表 关系表的设计就是要把信息分解成多个表,一类数据一个表。各表通过某些共同的值互相关联(所以才叫关系数据库) 关系数据可以有效地存储,方便地处理。因此关系数据库的可伸缩性远比非关系数据库要好。 12-1-2 为什么使用联结 将数据分解为多个表能有效地存储,更方便地处理,并且可伸缩性更好。但是这些好处是有代价的。 联结是一种机制,用来在一条select语句中关联表,因此称为联结。使用特殊的语法,可以联结多个表返回一组输出,联结在运行时关联表中正确的行。 12-2: 创建联结 创建联结非常简单,指定要联结的所有表以及关联它们的方式即可。 12-2-1 WHERE子句的重要性 在联结两个表时,实际要做的是将第一个表中的每一行与第二个表中的每一行配对。WHERE子句作为过滤条件,只包含那些匹配给定条件(这里是联结条件)的行。 没有WHERE子句,第一个表中的每一行将与第二个表中的每一行配对,而不管它们逻辑上是否能配在一起。 12-2-2 内联结 等值联结(equijoin),基于两个表之间的相等测试,也称为内联结(inner join) 12-2-3 联结多个表 SQL不限制一条select语句中可以联结的表的数目。 创建联结的基本规则也相同。首先列出所有的表,然后定义表之间的关系。 tip: 可伸缩(scale): 能够适应不断增加的工作量而不失败。设计良好的数据库或应用程序称为可伸缩性好(scale well); 笛卡儿积(cartesian product): 由没有联结条件的表关系返回的结果称为笛卡儿积。检索出的行的数目将是第一个表中的行数乘以第二个表中的行数; 返回笛卡尔积的联结,也称叉联结; 多做实验:执行任一给定的SQL操作一般不止一种方法。很少有绝对正确或绝对错误的方法。性能可能会受操作类型、所使用的DBMS、表中数据量、是否存在索引或键等条件的影响。 因此,有必要试验不同的选择机制,找出最适合具体情况的方法。 warn: 完全限定列名: 在引用的列可能出现歧义时,必须使用完全限定列名(用一个句点分割表名和列名)。 要保证所有联结都有where子句,否则dbms将返回比想要的数据多得多的数据。同理,要保证where子句的正确性。 性能考虑:不要联结不必要的表,联结的表越多,性能下降越厉害。 联结中表的最大数目: 虽然SQL本身不限制每个联结约束中表的数目,但实际上许多dbms都有限制。 */ -- 简单等值联结 select vend_name, prod_name, prod_price from vendors, products where vendors.vend_id = products.vend_id; -- 内联结 select vend_name, prod_name, prod_price from vendors inner join products p on vendors.vend_id = p.vend_id; select prod_name, vend_name, prod_price, quantity from orderitems, products, vendors where products.vend_id = vendors.vend_id and orderitems.prod_id = products.prod_id and order_num = '20007'; -- 子查询 select cust_name, cust_contact from customers where cust_id in ( select cust_id from orders where order_num in ( select order_num from orderitems where prod_id = 'RGAN01' ) ); -- 联结查询 select cust_name, cust_contact from customers, orders, orderitems where customers.cust_id = orders.cust_id and orders.order_num = orderitems.order_num and prod_id = 'RGAN01'
#Set the variables statement_one and statement_two equal to the results # of the following boolean expressions: #Statement one: #(2 + 2 + 2 >= 6) and (-1 * -1 < 0) #Statement two: #(4 * 2 <= 8) and (7 - 1 == 6) statement_one = (2 + 2 + 2 >= 6) and (-1 * -1 < 0) statement_two = (4 * 2 <= 8) and (7 - 1 == 6) #Let’s return to Calvin Coolidge’s Cool College. 120 credits aren’t the only graduation requirement # , you also need to have a GPA of 2.0 or higher. #Rewrite the if statement so that it checks to see if a student meets both requirements using an and statement. #If they do, print the string: #"You meet the requirements to graduate!" credits = 120 gpa = 3.4 if credits >= 120 and gpa >= 2.0: print("You meet the requirements to graduate!") #Set the variables statement_one and statement_two equal to the results of the following boolean expressions: #Statement_one: not (4 + 5 <= 9) #Statement two: not (8 * 2) != 20 - 4 statement_one = (4 + 5 <= 9) statement_two = not (8 * 2) != 20 - 4 credits = 120 gpa = 1.8 #The registrar’s office at Calvin Coolidge’s Cool College has been so impressed with your work so far that they have another task for you. #They want you to return to a previous if statement and add in several checks using and and not statements: #If a student’s credits is not greater or equal to 120, it should print: #"You do not have enough credits to graduate." #If their gpa is not greater or equal to 2.0, it should print: # "Your GPA is not high enough to graduate." #If their credits is not greater than or equal to 120 and their gpa is not greater than or equal to 2.0, it should print: #"You do not meet either requirement to graduate!" if not credits >= 120: print("You do not have enough credits to graduate.") if not gpa >= 2.0: print("Your GPA is not high enough to graduate.") if not (credits >= 120) and not (gpa >= 2.0): print("You do not meet either requirement to graduate!")kjk
# Please write a function named triangle, which draws a triangle of hashes, and takes one argument. # The triangle should be as tall and as wide as the value of the argument. # The function should call the function line from the exercise above for the actual printing out. # Copy your solution to that exercise above the code for this exercise. # Please don't change anything in the line function. # Some examples: # triangle(6) # print() # triangle(3) # # # ## # ### # #### # ##### # ###### # # # ## # ### def line(number, string): if string == "": print("*" * number) else: print(string[0] * number) def triangle(size): index = 1 while index <= size: line(index, "#") index += 1
package com.bigbigdw.manavara.best.screen import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.ModalBottomSheetState import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.AsyncImage import com.bigbigdw.manavara.R import com.bigbigdw.manavara.best.getBestListTodayJson import com.bigbigdw.manavara.best.getBestListWeekJson import com.bigbigdw.manavara.best.getBookItemWeekTrophy import com.bigbigdw.manavara.best.getBookMapJson import com.bigbigdw.manavara.best.getTrophyWeekMonthJson import com.bigbigdw.manavara.best.models.ItemBestInfo import com.bigbigdw.manavara.best.models.ItemBookInfo import com.bigbigdw.manavara.best.setIsPicked import com.bigbigdw.manavara.best.viewModels.ViewModelBest import com.bigbigdw.manavara.main.viewModels.ViewModelMain import com.bigbigdw.manavara.ui.theme.color000000 import com.bigbigdw.manavara.ui.theme.color02BC77 import com.bigbigdw.manavara.ui.theme.color1CE3EE import com.bigbigdw.manavara.ui.theme.color20459E import com.bigbigdw.manavara.ui.theme.color4AD7CF import com.bigbigdw.manavara.ui.theme.color8E8E8E import com.bigbigdw.manavara.ui.theme.color8F8F8F import com.bigbigdw.manavara.ui.theme.colorF6F6F6 import com.bigbigdw.manavara.ui.theme.colorFF2366 import com.bigbigdw.manavara.util.getWeekDate import com.bigbigdw.manavara.util.screen.ScreenBookCard import com.bigbigdw.manavara.util.screen.ScreenBookCardItem import com.bigbigdw.manavara.util.screen.ScreenEmpty import com.bigbigdw.manavara.util.screen.ScreenItemKeyword import com.bigbigdw.manavara.util.screen.spannableString import com.bigbigdw.manavara.util.weekListAll import com.bigbigdw.manavara.util.weekListOneWord import kotlinx.coroutines.launch @OptIn(ExperimentalMaterialApi::class) @Composable fun ScreenTodayBest( listState: LazyListState, modalSheetState: ModalBottomSheetState?, dialogOpen: MutableState<Boolean>?, viewModelMain: ViewModelMain, ) { val mainState = viewModelMain.state.collectAsState().value val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "ViewModelStoreOwner is null." } val viewModelBest: ViewModelBest = viewModel(viewModelStoreOwner = viewModelStoreOwner) val bestState = viewModelBest.state.collectAsState().value LaunchedEffect(mainState.platform, mainState.isPickedBookCode){ setIsPicked( context = context, platform = mainState.platform, type = mainState.type, ) { itemPickInfo -> getBookMapJson( platform = mainState.platform, type = mainState.type, context = context ){ itemBookInfoMap -> getBestListTodayJson( context = context, platform = mainState.platform, type = mainState.type, itemPickMap = itemPickInfo ) { itemBookInfoList -> viewModelBest.setItemBestInfoList(itemBookInfoMap = itemBookInfoMap, itemBookInfoList = itemBookInfoList) } } } } LazyColumn( state = listState, modifier = Modifier .background(colorF6F6F6) .padding(16.dp, 0.dp, 16.dp, 0.dp) .fillMaxSize(), ) { item { Spacer(modifier = Modifier.size(16.dp)) } itemsIndexed(bestState.itemBookInfoList) { index, item -> ListBestToday( itemBookInfo = item, index = index, backGroundColor = if(item.belong == "SHARED"){ Color(0xFFEFE1FC) } else { Color.White } ){ getBookItemWeekTrophy( bookCode = item.bookCode, platform = mainState.platform, type = mainState.type ){ viewModelMain.setItemBestInfoTrophyList( itemBestInfoTrophyList = it, itemBookInfo = item ) } coroutineScope.launch { modalSheetState?.show() dialogOpen?.value = true } } } item { Spacer(modifier = Modifier.size(60.dp)) } } } @Composable fun ListBestToday( itemBookInfo: ItemBookInfo, index: Int, backGroundColor : Color = Color.White, needStatus : Boolean = true, onClick: () -> Unit ) { Row( Modifier .fillMaxWidth() .padding(0.dp, 8.dp), verticalAlignment = Alignment.CenterVertically, ) { AsyncImage( model = itemBookInfo.bookImg, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .size(56.dp) .clip(CircleShape) ) Spacer(modifier = Modifier.width(4.dp)) Button( modifier = Modifier .fillMaxSize() .padding(4.dp, 0.dp, 0.dp, 0.dp) .fillMaxWidth() .height(56.dp), shape = RoundedCornerShape(25.dp), colors = ButtonDefaults.buttonColors(containerColor = backGroundColor), onClick = { onClick() }, contentPadding = PaddingValues( start = 0.dp, top = 0.dp, end = 0.dp, bottom = 0.dp, ), content = { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Text( text = "${index + 1} ", modifier = Modifier .wrapContentHeight() .padding(16.dp, 0.dp, 0.dp, 0.dp), fontSize = 24.sp, textAlign = TextAlign.Left, color = color20459E, fontWeight = FontWeight.Bold, ) Text( maxLines = 1, text = itemBookInfo.title, modifier = Modifier .wrapContentHeight() .weight(1f), fontSize = 18.sp, textAlign = TextAlign.Left, color = Color.Black, fontWeight = FontWeight.Bold, overflow = TextOverflow.Ellipsis, ) Spacer(modifier = Modifier.width(16.dp)) if(needStatus){ if (itemBookInfo.totalCount > 1) { if (itemBookInfo.currentDiff > 0) { Image( painter = painterResource(id = R.drawable.ic_arrow_drop_up_24px), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.size(20.dp) ) } else if (itemBookInfo.currentDiff < 0) { Image( painter = painterResource(id = R.drawable.ic_arrow_drop_down_24px), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.size(20.dp) ) } } Text( text = if (itemBookInfo.totalCount > 1) { if (itemBookInfo.currentDiff != 0) { itemBookInfo.currentDiff.toString() } else { "-" } } else { "NEW" }, modifier = Modifier .wrapContentHeight() .padding(0.dp, 0.dp, 16.dp, 0.dp) .wrapContentSize(), fontSize = 14.sp, textAlign = TextAlign.Left, color = if (itemBookInfo.totalCount > 1) { if (itemBookInfo.currentDiff != 0) { if (itemBookInfo.currentDiff > 0) { color02BC77 } else if (itemBookInfo.currentDiff < 0) { colorFF2366 } else { color1CE3EE } } else { color1CE3EE } } else { color1CE3EE }, fontWeight = FontWeight.Bold, overflow = TextOverflow.Ellipsis ) } } }) } } @OptIn(ExperimentalMaterialApi::class) @Composable fun ScreenTodayWeek( modalSheetState: ModalBottomSheetState?, dialogOpen: MutableState<Boolean>?, viewModelMain: ViewModelMain, dayType : String = "WEEK" ) { val mainState = viewModelMain.state.collectAsState().value val (getDate, setDate) = remember { mutableStateOf("전체") } val listState = rememberLazyListState() val coroutineScope = rememberCoroutineScope() val context = LocalContext.current val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "ViewModelStoreOwner is null." } val viewModelBest: ViewModelBest = viewModel(viewModelStoreOwner = viewModelStoreOwner) val bestState = viewModelBest.state.collectAsState().value LaunchedEffect(mainState.platform, mainState.isPickedBookCode){ setIsPicked( context = context, platform = mainState.platform, type = mainState.type, ) { itemPickInfo -> getBookMapJson( platform = mainState.platform, type = mainState.type, context = context ) { itemBookInfoMap -> getBestListWeekJson( context = context, platform = mainState.platform, type = mainState.type, itemPickInfo = itemPickInfo ) { weekList -> getTrophyWeekMonthJson( platform = mainState.platform, type = mainState.type, dayType = dayType, context = context ) { weekTrophyList -> val filteredList: ArrayList<ItemBookInfo> = ArrayList() for (trophyItem in weekTrophyList) { val bookCode = trophyItem.bookCode val bookInfo = itemBookInfoMap[bookCode] if (bookInfo != null) { if(itemPickInfo[bookInfo.bookCode] != null){ bookInfo.belong = "SHARED" } else { bookInfo.belong = "" } filteredList.add(bookInfo) } } viewModelBest.setWeekList( weekTrophyList = weekTrophyList, weekList = weekList, itemBookInfoMap = itemBookInfoMap, filteredList = filteredList ) } } } } } Column( modifier = Modifier .background(colorF6F6F6) .padding(16.dp, 0.dp, 16.dp, 0.dp) ) { Spacer(modifier = Modifier.size(8.dp)) LazyRow( modifier = Modifier .padding(8.dp, 8.dp, 0.dp, 8.dp) .background(color = colorF6F6F6), ) { itemsIndexed(if(dayType == "WEEK"){ weekListAll() } else { val arrayList = ArrayList<String>() var count = 0 arrayList.add("전체") for (item in bestState.weekMonthList) { count += 1 arrayList.add("${count}주차") } arrayList }) { index, item -> Box(modifier = Modifier.padding(0.dp, 0.dp, 8.dp, 0.dp)) { ScreenItemKeyword( getter = getDate, onClick = { coroutineScope.launch { setDate(item) listState.scrollToItem(index = 0) } }, title = item, getValue = item ) } } } Spacer(modifier = Modifier.size(8.dp)) LazyColumn(state = listState) { if (getDate == "전체") { itemsIndexed(bestState.filteredList) { index, item -> ScreenBookCard( type = dayType, item = item, index = index, backgroundColor = if(item.belong == "SHARED"){ Color(0xFFEFE1FC) } else { Color.White } ){ coroutineScope.launch { getBookItemWeekTrophy( bookCode = item.bookCode, type = mainState.type, platform = mainState.platform ) { itemBestInfoTrophyList -> viewModelMain.setItemBestInfoTrophyList( itemBookInfo = item, itemBestInfoTrophyList = itemBestInfoTrophyList ) } modalSheetState?.show() dialogOpen?.value = true listState.scrollToItem(index = 0) } } } } else { if (bestState.weekMonthList[getWeekDate(getDate)].size > 0) { itemsIndexed(bestState.weekMonthList[getWeekDate(getDate)]) { index, item -> ListBestToday( itemBookInfo = item, index = index, backGroundColor = if(item.belong == "SHARED"){ Color(0xFFEFE1FC) } else { Color.White } ){ getBookItemWeekTrophy( bookCode = item.bookCode, platform = mainState.platform, type = mainState.type ){ viewModelMain.setItemBestInfoTrophyList( itemBestInfoTrophyList = it, itemBookInfo = item ) } coroutineScope.launch { modalSheetState?.show() dialogOpen?.value = true } } } } else { item { Box(modifier = Modifier.fillMaxSize()) { ScreenEmpty(str = "데이터가 없습니다") } } } } } } } @Composable fun ScreenDialogBest( item: ItemBookInfo, isPicked : Boolean, trophy: ArrayList<ItemBestInfo>, isExpandedScreen: Boolean, needTrophyList: Boolean = true, btnPickText: String = "작품 PICK 하기", onClickLeft: () -> Unit, onClickRight: () -> Unit, ) { Column( modifier = Modifier .fillMaxWidth() .padding(12.dp) ) { ScreenBookCardItem(mode = "NUMBER", item = item, index = -1) Spacer(modifier = Modifier.size(8.dp)) if(isExpandedScreen){ Spacer(modifier = Modifier.size(8.dp)) if (item.intro.isNotEmpty()) { Text( text = item.intro, maxLines = 5, overflow = TextOverflow.Ellipsis, color = color8E8E8E, fontSize = 16.sp, ) } } } if(needTrophyList){ Row( Modifier .fillMaxWidth() .padding(16.dp, 0.dp, 16.dp, 16.dp), ) { trophy.forEachIndexed { index, item -> Box( modifier = Modifier.weight(1f), contentAlignment = Alignment.Center ) { Column { Text( modifier = Modifier.fillMaxWidth(), text = weekListOneWord()[index], color = if (item.number > -1) { color1CE3EE } else { color8F8F8F }, fontSize = 16.sp, textAlign = TextAlign.Center ) Box( modifier = Modifier .fillMaxWidth() .padding(4.dp, 0.dp), contentAlignment = Alignment.Center ) { Image( contentScale = ContentScale.FillWidth, painter = painterResource( id = if (item.number > -1) { R.drawable.icon_trophy_fill_on } else { R.drawable.icon_trophy_fill_off } ), contentDescription = null, modifier = Modifier .width(28.dp) .height(28.dp) ) } if(item.number > -1){ Text( modifier = Modifier.fillMaxWidth(), text = "${item.number + 1}등", color = color1CE3EE, fontSize = 16.sp, textAlign = TextAlign.Center, fontWeight = FontWeight.Bold ) } } } } } } if(!isExpandedScreen){ Row( Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Button( colors = ButtonDefaults.buttonColors( containerColor = if (isPicked) { color4AD7CF } else { color8F8F8F } ), onClick = { onClickLeft() }, modifier = Modifier .weight(1f) .height(48.dp), shape = RoundedCornerShape(0.dp, 0.dp, 0.dp, 0.dp) ) { Text( text = btnPickText, textAlign = TextAlign.Center, color = if (isPicked) { Color.Black } else { Color.White }, fontSize = 16.sp, fontWeight = FontWeight.Bold ) } Button( colors = ButtonDefaults.buttonColors(containerColor = color20459E), onClick = { onClickRight() }, modifier = Modifier .weight(1f) .height(48.dp), shape = RoundedCornerShape(0.dp, 0.dp, 0.dp, 0.dp) ) { Text( text = "작품 보러가기", textAlign = TextAlign.Center, color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Bold ) } } } } @Composable fun ScreenItemBestCount(item: ItemBookInfo) { Row { Box( modifier = Modifier.weight(1f) ) { Column { Row { Image( contentScale = ContentScale.FillWidth, painter = painterResource(id = R.drawable.icon_best), contentDescription = null, modifier = Modifier .width(20.dp) .height(20.dp) ) Spacer(modifier = Modifier.size(4.dp)) Text( text = spannableString( textFront = "베스트 총합 : ", color = color000000, textEnd = "${item.total}" ), color = color8E8E8E, fontSize = 16.sp, ) } Row { Image( contentScale = ContentScale.FillWidth, painter = painterResource(id = R.drawable.icon_trophy), contentDescription = null, modifier = Modifier .width(20.dp) .height(20.dp) ) Spacer(modifier = Modifier.size(4.dp)) Text( text = spannableString( textFront = "주간 총점 : ", color = color000000, textEnd = "${item.totalWeek}" ), color = color8E8E8E, fontSize = 16.sp, ) } Row { Image( contentScale = ContentScale.FillWidth, painter = painterResource(id = R.drawable.icon_trophy), contentDescription = null, modifier = Modifier .width(20.dp) .height(20.dp) ) Spacer(modifier = Modifier.size(4.dp)) Text( text = spannableString( textFront = "월간 총점 : ", color = color000000, textEnd = "${item.totalMonth}" ), color = color8E8E8E, fontSize = 16.sp, ) } } } Box( modifier = Modifier.weight(1f) ) { Column { Row { Image( contentScale = ContentScale.FillWidth, painter = painterResource(id = R.drawable.icon_best_gr), contentDescription = null, modifier = Modifier .width(20.dp) .height(20.dp) ) Spacer(modifier = Modifier.size(4.dp)) Text( text = spannableString( textFront = "총 베스트 횟수 : ", color = color000000, textEnd = "${item.totalCount}" ), color = color8E8E8E, fontSize = 16.sp, ) } Row { Image( contentScale = ContentScale.FillWidth, painter = painterResource(id = R.drawable.icon_trophy_gr), contentDescription = null, modifier = Modifier .width(20.dp) .height(20.dp) ) Spacer(modifier = Modifier.size(4.dp)) Text( text = spannableString( textFront = "주간 베스트 횟수 : ", color = color000000, textEnd = item.totalWeekCount.toString() ), color = color8E8E8E, fontSize = 16.sp, ) } Row { Image( contentScale = ContentScale.FillWidth, painter = painterResource(id = R.drawable.icon_trophy_gr), contentDescription = null, modifier = Modifier .width(20.dp) .height(20.dp) ) Spacer(modifier = Modifier.size(4.dp)) Text( text = spannableString( textFront = "월간 베스트 횟수 : ", color = color000000, textEnd = item.totalMonthCount.toString() ), color = color8E8E8E, fontSize = 16.sp, ) } } } } }
import 'package:flutter/cupertino.dart'; enum ThemeType { auto, light, dark; String? get stringify { switch (this) { case ThemeType.auto: return "auto"; case ThemeType.light: return "light"; case ThemeType.dark: return "dark"; } } String? display(BuildContext context) { switch (this) { case ThemeType.auto: return "auto"; case ThemeType.light: return "light"; case ThemeType.dark: return "dark"; default: return null; } } static ThemeType fromString(String? type) { if (type == null) return ThemeType.auto; switch (type) { case "auto": return ThemeType.auto; case "light": return ThemeType.light; case "dark": return ThemeType.dark; default: return ThemeType.auto; } } }
const CURRENT_VERSION = 11; const PROTO_KEY = "$$proto"; export class Store<T> { storage: DurableObjectStorage; key: string; reviver: (k: string, v: any) => any | undefined; public constructor(storage: DurableObjectStorage, key: string, types: Record<string, any>) { this.storage = storage; this.key = key; this.reviver = makeReviver(types); } public async get(): Promise<T | undefined> { const raw = await this.storage.get(this.path()); if (raw === undefined) { return undefined; } if (typeof raw !== "string") { throw(`unexpected value in get: ${raw}`); } return JSON.parse(raw, this.reviver); } public async record(prefix?: string): Promise<Record<string, T>> { const suffix = prefix ? prefix+":" : ""; const path = `${this.path()}::${suffix}`; const items = await this.storage.list({ prefix: path, }); const record: Record<string, T> = {}; let buf: string | null = null; let wip: string | null = null; for (let [k, raw] of items.entries()) { if (typeof raw !== "string") { throw(`unexpected value in record: ${raw}`); } const hash = k.indexOf("#"); const n = Number(k.slice(hash+1)); if (hash !== -1) { const root = k.slice(0, hash); if (raw == EOF) { raw = buf; buf = null; wip = null; } else { if (wip && root != wip) { console.warn("stray:", k, raw, "wip:", wip); continue; } if (n == 0) { wip = root; } if (buf) { buf += raw; } else { buf = raw; } continue; } } try { const v = JSON.parse(raw as string, this.reviver); record[k.slice(path.length)] = v; } catch (ex) { console.warn("failed to parse json:", path, ex); } } return record; } public async put(v: T): Promise<void> { const path = this.path(); const enc = this.encode(v); return this.storage.put(path, enc); } public async putRecord(prefix: string, record: Record<string, T>) { const puts = []; for (const [key, value] of Object.entries(record)) { const path = this.recordPath(prefix, key); const chunks = this.chunk(path, value) puts.push(this.multiput(chunks)); } return Promise.all(puts); } public async putRecordItem(prefix: string, key: string, value: T) { const path = this.recordPath(prefix, key); const chunks = this.chunk(path, value) return this.multiput(chunks); } public async delete(): Promise<boolean> { return this.storage.delete(this.path()); } private encode(value: T): string { return JSON.stringify(value, replacer); } private multiput(chunks: Record<string, string>) { for (const [k, v] of Object.entries(chunks)) { this.storage.put(k, v); } // return this.storage.put(chunks); } private chunk(key: string, value: T): Record<string, string> { const size = (CF_MAXSIZE-key.length-1)/2; // 2-byte per character const str = JSON.stringify(value, replacer); // if (str.length < size) { // return {[key]: str}; // } const obj: Record<string, string> = {}; let i = 0; for (let pos = 0; pos < str.length; pos += size) { const chunk = str.slice(pos, pos+size); obj[`${key}#${i}`] = chunk; i++; } obj[`${key}#${i}`] = EOF; console.table(obj); return obj; } private path(): string { return `${this.key}:v${CURRENT_VERSION}`; } private recordPath(prefix = "", key = ""): string { return `${this.path()}::${prefix}:${key}`; } } export function replacer(k: string, v: any): any { if (Array.isArray(v)) { return v.map(function(x, y) { return replacer(y.toString(), x); }); } if (typeof v == "object" && v != null) { const proto = Object.getPrototypeOf(v); const name = proto.constructor.name; if (name === "Object") { return v; } if (proto) { return {...v, [PROTO_KEY]: name}; } } return v; } const EOF = "\0x1E" // File Separator const CF_MAXSIZE = 131072; export function makeReviver(types: Record<string, any> = globalThis) { return function(k: string, v: any) { if (typeof v !== "object" || v == null) { return v; } if (typeof v[PROTO_KEY] !== "string") { return v; } const proto = types[v[PROTO_KEY]]; if (!proto || !proto?.prototype) { return v; } delete v[PROTO_KEY]; Object.setPrototypeOf(v, proto.prototype); return v; }; }
--- title: vue -> todo demo(computed,directives,对象index,hashchange) --- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body { margin: 0; background-color: #fafafa; font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif; } h2 { margin: 0; font-size: 12px; } a { color: #000; text-decoration: none; } input { outline: 0; } button { margin: 0; padding: 0; border: 0; background: none; font-size: 100%; vertical-align: baseline; font-family: inherit; font-weight: inherit; color: inherit; outline: 0; } ul { padding: 0; margin: 0; list-style: none; } .page-top { width: 100%; height: 40px; background-color: #db4c3f; } .page-content { width: 50%; margin: 0px auto; } .page-content h2 { line-height: 40px; font-size: 18px; color: #fff; } .main { width: 50%; margin: 0px auto; box-sizing: border-box; } .task-input { width: 99%; height: 30px; outline: 0; border: 1px solid #ccc; } .task-count { display: flex; margin: 10px 0; } .task-count li { padding-left: 10px; flex: 1; color: #dd4b39; } .task-count li:nth-child(1) { padding: 5px 0 0 10px; } .action { text-align: center; display: flex; } .action a { margin: 0px 10px; flex: 1; padding: 5px 0; color: #777; } .action a:nth-child(3) { margin-right: 0; } .active { border: 1px solid rgba(175, 47, 47, 0.2); } .tasks { background-color: #fff; } .no-task-tip { padding: 10px 0 10px 10px; display: block; border-bottom: 1px solid #ededed; color: #777; } .big-title { color: #222; } .todo-list { margin: 0; padding: 0; list-style: none; } .todo-list li { position: relative; font-size: 16px; border-bottom: 1px solid #ededed; } .todo-list li:hover { background-color: #fafafa; } .todo-list li.editing { border-bottom: none; padding: 0; } .todo-list li.editing .edit { display: block; width: 506px; padding: 13px 17px 12px 17px; margin: 0 0 0 43px; } .todo-list li.editing .view { display: none; } .todo-list li .toggle { text-align: center; width: 40px; /* auto, since non-WebKit browsers doesn't support input styling */ height: auto; position: absolute; top: 5px; bottom: 0; margin: auto 0; border: none; /* Mobile Safari */ -webkit-appearance: none; appearance: none; } .toggle { text-align: center; width: 40px; /* auto, since non-WebKit browsers doesn't support input styling */ height: auto; position: absolute; top: 5px; bottom: 0; margin: auto 0; border: none; /* Mobile Safari */ -webkit-appearance: none; appearance: none; } .toggle:after { content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="40" fill="none" stroke="#ededed" stroke-width="3"/></svg>'); } .toggle:checked:after { content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="40" fill="none" stroke="#bddad5" stroke-width="3"/><path fill="#5dc2af" d="M72 25L42 71 27 56l-4 4 20 20 34-52z"/></svg>'); } .todo-list li label { white-space: pre-line; word-break: break-all; padding: 15px 60px 15px 15px; margin-left: 45px; display: block; line-height: 1.2; transition: color 0.4s; } .todo-list li.completed label { color: #d9d9d9; text-decoration: line-through; } /*.tip-toggle { padding-left: 0; position: relative; } .tip-toggle .toggle { top: -2px; } .tip-toggle span { margin-left: 45px; }*/ .todo-list li .destroy { display: none; position: absolute; top: 0; right: 10px; bottom: 0; width: 40px; height: 40px; margin: auto 0; font-size: 30px; color: #cc9a9a; margin-bottom: 11px; transition: color 0.2s ease-out; } .todo-list li .destroy:hover { color: #af5b5e; } .todo-list li .destroy:after { content: '×'; } .todo-list li:hover .destroy { display: block; } .todo-list li .edit { display: none; } .todo-list li.editing:last-child { margin-bottom: -1px; } </style> <script src="{{site.baseurl}}/js/vue.js"></script> <!-- <script src="../js/vue.js"></script> --> </head> <body> {% raw %} <div class="page-top"> <div class="page-content"> <h2>任务计划列表</h2> </div> </div> <div class="main"> <h3 class="big-title">添加任务:</h3> <input placeholder="例如:吃饭睡觉打豆豆; 提示:+回车即可添加任务" class="task-input" type="text" v-model="todo" v-on:keyup.13="addTodo" /> <ul class="task-count" v-show="list.length"> <li>{{noCheckeLength}}个任务未完成</li> <li class="action"> <a :class="{active:visibility === 'all'}" href="#all">所有任务</a> <a :class="{active:visibility === 'unfinished'}" href="#unfinished">未完成的任务</a> <a :class="{active:visibility === 'finished'}" href="#finished">完成的任务</a> </li> </ul> <h3 class="big-title">任务列表:</h3> <div class="tasks"> <span class="no-task-tip" v-show="!list.length">还没有添加任何任务</span> <ul class="todo-list"> <li class="todo" :class="{completed: item.isChecked,editing: item === edtorTodos}" v-for="item in filteredList"> <div class="view"> <input class="toggle" type="checkbox" v-model="item.isChecked" /> <label @dblclick="edtorTodo(item)">{{ item.title }}</label> <button class="destroy" @click="deleteTodo(item)"></button> </div> <input v-foucs="edtorTodos === item" class="edit" type="text" v-model="item.title" @blur="edtorTodoed(item)" @keyup.13="edtorTodoed(item)" @keyup.esc="cancelTodo(item)" /> </li> </ul> </div> </div> {% endraw %} <script> // const list = [{ // title: "吃饭打豆豆", // isChecked: false, // }, { // title: "艾斯酷", // isChecked: true // }]; var store = { save(key, value) { localStorage.setItem(key, JSON.stringify(value)); }, fetch(key) { return JSON.parse(localStorage.getItem(key)) || []; } }; const list = store.fetch("iscool-class"); const filter = { all(list) { return list }, finished(list) { return list.filter(item => item.isChecked); }, unfinished(list) { return list.filter(item => !item.isChecked); } } var vm = new Vue({ el: ".main", data: { list, todo: "", edtorTodos: "", //记录正在编辑的数据 beforeTitle: "", //记录正在编辑的数据titile visibility: "all" }, watch: { list: { handler() { store.save("iscool-class", this.list); }, deep: true } }, computed: { noCheckeLength() { return this.list.filter(item => !item.isChecked).length; }, filteredList() { return filter[this.visibility] ? filter[this.visibility](list) : list; } }, methods: { addTodo() { this.list.push({ title: this.todo, isChecked: false }); this.todo = ""; }, deleteTodo(todo) { const index = this.list.indexOf(todo); this.list.splice(index, 1); }, edtorTodo(todo) { // 记录当前编辑前titile,取消还原 this.beforeTitle = todo.title; this.edtorTodos = todo; }, edtorTodoed(todo) { //编辑任务成功 this.edtorTodos = ""; }, cancelTodo(todo) { todo.title = this.beforeTitle; this.beforeTitle = ""; this.edtorTodos = ""; //让div显示 } }, directives: { "foucs": { update(el, binding) { // 值为真 if (binding.value) { el.focus(); } } } } }); function watchHashChange() { const hash = window.location.hash.slice(1); vm.visibility = hash; } watchHashChange(); window.addEventListener("hashchange", watchHashChange); </script> </body> </html>
<div> <div class="panel panel-default"> <div class="panel-body"> <ng-form name="providerForm" class="col-sm-6"> <caption>{{model.title}}</caption> <fieldset ng-disabled="model.disableForm"> <div class="form-group"> <label for="providerName">Nombre: </label> <input class="form-control input-sm" type="text" name="providerName" ng-model="model.name" required> </div> <span class="alert alert-danger" ng-show="providerForm.providerName.$invalid"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>El nombre del proveedor es requerido. </span> <phones phones="model.phones"></phones> </fieldset> <div class="btn-group" ng-show="!model.pop"> <button class="btn btn-success" ng-disabled="!providerForm.$valid" ng-if="!model.editingProvider" type="submit" ng-click="model.saveProvider()">Guardar</button> <button class="btn btn-warning" ng-if="model.editingProvider" ng-click="model.editProvider()">Editar</button> <button class="btn btn-danger" type="button" ng-click="model.cancelEdit()">Cancelar</button> </div> </ng-form> <ng-form name="invoiceForm" class="col-sm-6"> <!--<span ng-show="model.editingProvider" ng-click="model.invoiceForm()">Insertar Nuevo Documento</span>--> <caption>Insertar Nuevo Documento</caption> <div> <!-- ng-show="model.newInvoice">--> <div class="form-group"> <label for="type">Nuevo Documento</label> <select class="form-control dropdown" id="type" ng-model="model.selectedInvoiceType" ng-options="invoiceType for invoiceType in model.invoiceTypes"></select> </div> <div class="form-group"> <label for="invoiceNumber"># de Factura</label> <input class="form-control input-sm" type="text" id="invoiceNumber" ng-model="model.invoiceNumber"> </div> <div class="form-group"> <label for="amount">Monto</label> <money-input id="amount" text="model.invoiceAmount"></money-input> </div> <div class="form-group"> <label for="date">Fecha de Emision</label> <input class="form-control" type="date" id="date" ng-model="model.invoiceDate"> </div> <div class="form-group"> <label for="dueDate">Fecha de Vencimiento</label> <input class="form-control" type="date" id="dueDate" ng-model="model.invoiceDueDate"> </div> <div class="btn-group"> <button class="btn btn-success" type="button" ng-click="model.addInvoice()">Agregar Factura</button> <button class="btn btn-danger" type="button" ng-click="model.cancelInvoice()">Cancelar</button> </div> </div> </ng-form> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <caption>Documentos del Proveedor</caption> </div> <div class="panel-body"> <table class="table table-bordered table-striped table-hover"> <thead> <th># de Documento</th> <th>Tipo de Documento</th> <th>Monto</th> <th>Fecha Emision</th> <th>Fecha Vencimiento</th> <th>Saldo</th> </thead> <tr ng-repeat="invoice in model.invoices | orderBy:'-date'"> <td>{{invoice.number}}</td> <td>{{invoice.type}}</td> <td>{{invoice.amount | currency}}</td> <td>{{invoice.date | date:"MM/dd/yyyy"}}</td> <td>{{invoice.due | date:"MM/dd/yyyy"}}</td> <td>{{invoice.balance | currency}}</td> </tr> </table> </div> </div> <div id="myModal" class="modal fade" role="dialog"> <message type="model.messageType" show="model.pop" message="model.message" confirm="model.confirm()" cancel="model.cancel()"></message> </div> </div>
# Notifier Bot Bot for broadcasting messages to Telegram groups and users via HTTP-requests. It has simple auth mechanism with a password. ## Get started ### How to run bot Use Docker image ```bash # To run docker run sdalbmstu/notifier-bot \ -e BOT_TOKEN=<your_telegram_token> \ -e BOT_PASSWORD=<your_password> \ -v <data_storage_folder>:/bot/.data \ -p 8080:3000 # To test curl -X POST http://localhost:8080/messages \ -H 'Content-Type: application/json' \ -d '{"text":"*Hello*","parseMode":"MarkdownV2"}' ``` ### How to broadcast a message Just send `POST` request to `/messages` with body like this ```json // Simple text { "text": "Hello" } // Markdown markup { "text": "[My webpage](https://sergsol.com/)", "parseMode": "MarkdownV2" } ``` ### How to start getting messages 1. Go to chat with your bot (or add him into a group) 2. Press `Start` 3. Enter your password as bot asked 4. You are ready 👌 Send a test message to ensure it works ## Development Clone repo and run commands ```bash yarn install --frozen-lockfile yarn dev <your_token> <your_password> <express_port> ```
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { DonutDetail } from '../interfaces/donut'; import { CartService } from '../services/cart.service'; import { DonutApiService } from '../services/donut-api.service'; @Component({ selector: 'app-details', templateUrl: './details.component.html', styleUrls: ['./details.component.css'], }) export class DetailsComponent implements OnInit { detail: DonutDetail | undefined; constructor( private donutApiService: DonutApiService, private cartService: CartService, private route: ActivatedRoute, private router: Router ) {} ngOnInit(): void { this.route.paramMap.subscribe((params) => { let id = Number(params.get('id')); this.getDetails(id); }); } getDetails(id: number) { this.donutApiService.getDonutDetail(id).subscribe({ next: (response) => (this.detail = response), error: (err) => console.log(err), }); } addToCart(item: DonutDetail) { this.cartService.addItem(item); this.router.navigate(['cart']); } }
<template> <v-dialog v-model="dialog" width="350"> <v-card height="450"> <v-container class="pt-4" fluid> <v-row style="height:400px;"> <v-treeview :items="myItems"> <template v-slot:prepend="{ item, open }"> <v-btn v-if="item.item_name" @click="select(item)" plain small> <v-icon class="mx-1" small>mdi-calendar-clock</v-icon>{{ item.item_name }} </v-btn> </template> </v-treeview> </v-row> <v-divider></v-divider> <v-row class="justify-end mt-4 mx-3"> <v-btn @click="cancel" class="mx-1" small>取消</v-btn> <v-btn @click="assignItem" class="mx-1" color="primary" small>确定</v-btn> </v-row> </v-container> </v-card> </v-dialog> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { name: 'ItemPicker', computed: { ...mapGetters("item", ["items"]), ...mapGetters("auth", ["authUser"]), myItems: function () { return [{ name: "我负责的", children: this.items.filter(item => item.item_owner == this.authUser.id && item.item_parent_object != this.parent.item_parent_object) }, { name: "我参与的", children: this.items.filter(item => { const paticipants = item.item_participant.split(',') if (paticipants.includes(this.authUser.id.toString()) && item.item_parent_object != this.parent.item_parent_object) { return item } }) } ] } }, data() { return { dialog: false, parent: null, selectedItem: null, } }, methods: { ...mapActions("item", ["getItems", "updateItem"]), open(parent) { this.dialog = true this.parent = parent this.getItems({ item_owner: this.authUser.id, item_participant: this.authUser.id }) }, select(item) { this.selectedItem = item }, cancel() { this.dialog = false }, assignItem() { const payload = { item_id : this.selectedItem.item_id, ...this.parent } this.updateItem(payload) this.dialog = false } } } </script>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- A CardView that contains a TextView --> <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/comment_card_view" android:layout_gravity="center" android:layout_margin="@dimen/medium_padding" android:layout_width="match_parent" android:layout_height="wrap_content" android:elevation="0dp" card_view:cardCornerRadius="4dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_margin="@dimen/small_padding" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="@dimen/avatar_side" android:layout_height="@dimen/avatar_side" android:layout_marginTop="@dimen/big_padding" android:layout_marginEnd="@dimen/medium_padding" android:layout_marginStart="@dimen/medium_padding" android:src="@drawable/no_avatar" /> <TextView android:id="@+id/comment_item_nickname" android:textSize="18dp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="Nickname" /> </LinearLayout> <TextView android:textSize="16sp" android:id="@+id/comment_info_text" android:layout_width="match_parent" android:padding="@dimen/medium_padding" android:layout_marginStart="@dimen/medium_padding" android:gravity="start" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end"> <Button android:textSize="12sp" android:id="@+id/comment_likes" android:layout_width="wrap_content" android:layout_height="wrap_content" style="?android:attr/borderlessButtonStyle" android:text="Up" android:layout_margin="-15dp" android:textColor="@color/comment_green" android:drawableStart="@drawable/arrow_up_green_24dp" /> <Button android:textSize="12sp" android:id="@+id/comment_dislikes" android:layout_width="wrap_content" android:layout_height="wrap_content" style="?android:attr/borderlessButtonStyle" android:text="Down" android:layout_margin="-5dp" android:textColor="@color/comment_red" android:drawableStart="@drawable/arrow_down_red_24dp" /> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout>
// import 'package:capstone_project/evac_user/evac_page.dart'; // import 'package:capstone_project/screens/registerUserInfo.dart'; // import 'package:capstone_project/services/globalvariable.dart'; // import 'package:capstone_project/services/helpermethods.dart'; // import 'package:capstone_project/shelter_user/shelter_page.dart'; // import 'package:capstone_project/widgets/bradDivider.dart'; // import 'package:capstone_project/widgets/drawer_list.dart'; // import 'package:capstone_project/widgets/home_button.dart'; // import 'package:capstone_project/widgets/top_bar.dart'; // import 'package:firebase_database/firebase_database.dart'; // import 'package:flutter/material.dart'; // class HomeScreen extends StatefulWidget { // static const id = 'HomeScreen'; // @override // _HomeScreenState createState() => _HomeScreenState(); // } // class _HomeScreenState extends State<HomeScreen> { // GlobalKey<ScaffoldState> _scaffoldkey = new GlobalKey<ScaffoldState>(); // void initState() { // super.initState(); // HelperMethods.getCurrentUserInfo(); // } // void showSnackBar(String title) { // final snackBar = SnackBar( // backgroundColor: Colors.deepOrange, // content: Text( // title, // textAlign: TextAlign.center, // style: TextStyle(fontSize: 15, wordSpacing: 2), // )); // _scaffoldkey.currentState.showSnackBar(snackBar); // } // var userValidator = FirebaseDatabase.instance // .reference() // .child('users/${currentFirebaseUser.uid}'); // @override // Widget build(BuildContext context) { // return Scaffold( // key: _scaffoldkey, // drawer: DrawerList(), // body: StreamBuilder( // stream: userValidator.onValue, // builder: (context, snapshot) { // return Stack(children: <Widget>[ // Column( // children: <Widget>[ // Container( // height: MediaQuery.of(context).size.height, // width: MediaQuery.of(context).size.width, // decoration: BoxDecoration( // image: DecorationImage( // image: // ExactAssetImage('assets/images/background.jpg'), // fit: BoxFit.fill, // alignment: Alignment.topCenter, // ), // ), // ), // ], // ), // //navigation drawer // // Positioned( // // top: 120, // // left: 20, // // child: GestureDetector( // // onTap: () { // // _scaffoldkey.currentState.openDrawer(); // // }, // // child: NavigationDrawer()), // // ), // // baynihan logo // Positioned( // top: 130, // left: 0, // right: 0, // child: Column( // children: <Widget>[ // CircleAvatar( // backgroundColor: Color.fromRGBO(0, 0, 0, 0), // radius: 50, // child: ClipOval( // child: Image.asset( // 'assets/images/logo_icon_final.png', // // height: 150, // // width: 150, // fit: BoxFit.cover, // ), // ), // ), // ], // )), // //SearchSheet // Positioned( // left: 0, // right: 0, // bottom: 0, // child: Container( // height: 350, // decoration: BoxDecoration( // borderRadius: BorderRadius.only( // topLeft: Radius.circular(30), // topRight: Radius.circular(30)), // gradient: LinearGradient( // begin: Alignment.topRight, // end: Alignment.bottomLeft, // colors: [ // Colors.black54, // Color.fromRGBO(0, 41, 102, 1) // ])), // child: Padding( // padding: const EdgeInsets.symmetric( // horizontal: 24, vertical: 18), // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: <Widget>[ // SizedBox(height: 5.0), // Text( // 'Nice to See you!', // style: // TextStyle(fontSize: 15, color: Colors.white), // ), // SizedBox(height: 10), // Text( // 'Search for Open-House Shelter?', // style: TextStyle( // fontSize: 20.0, // fontFamily: 'Brand-Regular', // color: Colors.white, // ), // ), // SizedBox(height: 10), // //Open shelter search // // ignore: deprecated_member_use // RaisedButton( // shape: new RoundedRectangleBorder( // borderRadius: new BorderRadius.circular(45)), // color: Colors.blue, // // textColor: Colors.white, // child: Padding( // padding: // const EdgeInsets.fromLTRB(0, 15, 0, 15), // child: Row( // children: <Widget>[ // Icon( // Icons.room, // color: Colors.white, // ), // SizedBox( // width: 20, // ), // Text( // 'Find available shelter', // style: TextStyle( // fontSize: 18, // letterSpacing: 2, // fontFamily: 'Brand-Bold', // color: Colors.white), // ), // ], // ), // ), // onPressed: () { // if (snapshot.data.snapshot.value == null) { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => // RegisterUserInfo())); // } else if (currentUserInfo.status == "true") { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => EvacUser())); // } else { // showSnackBar( // 'Your Registration is on process, Wait for awhile!'); // } // }, // ), // SizedBox(height: 20), // BrandDivider(), // SizedBox( // height: 17, // ), // //Shelter provider button // Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: <Widget>[ // SizedBox(height: 5), // Text( // 'Want to Open a Shelter?', // style: TextStyle( // fontSize: 20.0, // fontFamily: 'Brand-Regular', // color: Colors.white), // ), // SizedBox(height: 15), // ], // ), // RaisedButton( // shape: new RoundedRectangleBorder( // borderRadius: // new BorderRadius.circular(45)), // color: Colors.greenAccent, // // textColor: Colors.white, // child: Padding( // padding: // const EdgeInsets.fromLTRB(0, 15, 0, 15), // child: Row( // children: <Widget>[ // Icon( // Icons.roofing, // color: Colors.black, // ), // SizedBox( // width: 20, // ), // Text( // 'Create my Shelter', // style: TextStyle( // fontSize: 18, // letterSpacing: 2, // fontFamily: 'Brand-Bold', // color: Colors.black), // ), // ], // ), // ), // onPressed: () { // if (snapshot.data.snapshot.value == null) { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => // RegisterUserInfo())); // } else if (currentUserInfo.status == "true") { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => // ShelterPage())); // } else { // showSnackBar( // 'Your Registration is on process, Wait for awhile!'); // } // }), // ], // ), // ), // )), // TopBar(onPressed: () { // _scaffoldkey.currentState.openDrawer(); // }), // //middle button "search nearest evacuation" // Button(), // ]); // })); // } // }
package data import ( "github.com/bytearena/ecs" "ludum-dare-54/internal/constants" "ludum-dare-54/pkg/img" "ludum-dare-54/pkg/object" ) var ( CurrentTruck *Truck PickedTruckKey constants.TruckTypes ) type Truck struct { Trunk [][][]bool Wares []*Ware Width int Depth int Height int TotalSpace int FilledSpace int PercentFilled int TruckLabel string SpriteKey string CurrHeight int TileMap []*img.Sprite TileObject *object.Object TileEntity *ecs.Entity } func (t *Truck) CopyTruck() { CurrentTruck = &Truck{ Width: t.Width, Height: t.Height, Depth: t.Depth, TotalSpace: t.Width * t.Height * t.Depth, TruckLabel: t.TruckLabel, SpriteKey: t.SpriteKey, } for z := 0; z < t.Height; z++ { CurrentTruck.Trunk = append(CurrentTruck.Trunk, [][]bool{}) for y := 0; y < t.Depth; y++ { CurrentTruck.Trunk[z] = append(CurrentTruck.Trunk[z], []bool{}) for x := 0; x < t.Width; x++ { CurrentTruck.Trunk[z][y] = append(CurrentTruck.Trunk[z][y], false) } } } } var ( AvailableTrucks = map[string]*Truck{ constants.SmartCar: { Width: 4, Depth: 3, Height: 3, TruckLabel: "COMPACT", SpriteKey: "smart", }, constants.Minivan: { Width: 4, Depth: 4, Height: 3, TruckLabel: "MINIVAN", SpriteKey: "mini", }, constants.CargoVan: { Width: 5, Depth: 5, Height: 4, TruckLabel: "CARGO VAN", SpriteKey: "cargo", }, constants.SemiTruck: { Width: 5, Depth: 7, Height: 6, TruckLabel: "BOX TRUCK", SpriteKey: "box", }, constants.Wagon: { Width: 5, Depth: 5, Height: 5, TruckLabel: "CONASTOGA", SpriteKey: "wagon", }, } )
"""Tools for managing the find function.""" import logging import os from ..u_error import DebuggingError from ..u_misc import EMPTY from . import up_utils _LOGGER = logging.getLogger(__name__) def find(path, depth=None, class_=None, type_=None, catch_missing=False, catch_access_error=False, base=None, filter_=None, full_path=True, hidden=False, extn=EMPTY, extns=None, head=None, tail=None, filename=None): """Search for files within the given directory. This is aimed to mimic the behaviour of the linux/bash find command. Args: path (str): path to search in depth (int): maxiumum search depth class_ (class|True): typecast results to the given class, or if True return File/Dir objects type_ (char): filter results by type (d/f) catch_missing (bool): no error if path does not exist catch_access_error (bool): no error on access denied base (str): filter by exact file basename ie. bl will not match blah.txt, you'd need to use blah filter_ (str): apply filter string (eg. -jpg to ignore jpgs) full_path (bool): return full path (on by default) hidden (bool): include hidden files/dirs extn (str): filter by extension extns (str list): filter by list of extensions head (str): filter by start of filename tail (str): filter by end of filename filename (str): filter by exact filename match Returns: (str list): list of file paths """ from pini.utils import File, Dir _LOGGER.debug('FIND %s', path) if os.environ.get('PINI_DISABLE_FILE_SYSTEM'): raise DebuggingError( "Read yaml disabled using PINI_DISABLE_FILE_SYSTEM") _dir = Dir(up_utils.abs_path(path)) _data = _read_find_data( dir_=_dir, depth=depth, catch_missing=catch_missing, hidden=hidden, catch_access_error=catch_access_error) # Setup extns filter _extns = set(extns or []) if extn is not EMPTY: _LOGGER.debug(' - ADDING EXTN %s', extn) _extns.add(extn) _LOGGER.debug(' - EXTNS %s', _extns) _paths = [] for _path, _type in _data: # Apply filters if _result_is_filtered( result=_path, result_type=_type, type_=type_, filter_=filter_, base=base, extns=_extns, head=head, tail=tail, filename=filename): _LOGGER.debug(' - FILTERED') continue if not full_path: _path = _dir.rel_path(_path) # Class filter if class_: _class = class_ if _class is True: _class = {'f': File, 'd': Dir}[_type] try: _path = _class(_path) except ValueError: continue _paths.append(_path) return sorted(_paths) def _read_find_data( dir_, depth, hidden, catch_missing=False, catch_access_error=False): """Read find data for the given path. Args: dir_ (Dir): dir to search in depth (int): limit depth of search (subdir depth) hidden (bool): include hidden files/dirs catch_missing (bool): no error if path does not exist catch_access_error (bool): no error on access denied Returns: ((str, char) list): list of path/type data of dir contents """ from pini.utils import check_heart, Dir check_heart() _data = [] _LOGGER.debug('READ FIND DATA %s', dir_.path) if not dir_.exists(): if catch_missing: return _data raise OSError('Missing dir '+dir_.path) # Decrement depth _depth = depth if isinstance(_depth, int): _depth = _depth - 1 assert _depth is None or _depth >= 0 _LOGGER.debug(' - DEPTH %s', _depth) # Read contents try: _rc_paths = os.listdir(dir_.path) except OSError as _exc: if not catch_access_error: raise _exc _rc_paths = [] for _rc_path in _rc_paths: # Got through relative paths if not hidden and _rc_path.startswith('.'): continue _c_path = up_utils.abs_path( # Clean path '{}/{}'.format(dir_.path, _rc_path)) _LOGGER.debug(' - TESTING %s %s', _rc_path, _c_path) # Read type _type = None if os.path.isdir(_c_path): _type = 'd' elif os.path.isfile(_c_path): _type = 'f' else: _LOGGER.warning('Unrecognised file %s', _c_path) continue _LOGGER.debug(' - TYPE %s', _type) # Apply recursion (must happen before filters if _depth != 0 and _type == 'd': _LOGGER.debug(' - CHECKING CHILDREN') _data += _read_find_data( dir_=Dir(_c_path), depth=_depth, hidden=hidden, catch_access_error=catch_access_error) _data.append((_c_path, _type)) return _data def _result_is_filtered( # pylint: disable=too-many-return-statements result, result_type, type_, filter_, base, extns, head, tail, filename): """Check if the filters should remove the given path result. Args: result (str): path to result result_type (str): result type (d/f) type_ (str): type filter filter_ (str): string filter base (str): basename filter extns (str list): list of extensions to allow head (str): filename head filter tail (str): filename tail filter filename (str): filter by exact filename match Returns: (bool): whether result should be filtered """ from pini.utils import passes_filter, Path if type_ and result_type != type_: return True if filter_ and not passes_filter(result, filter_): return True _path_obj = Path(result) if base and _path_obj.base != base: _LOGGER.debug( ' - BASE FILTERED base=%s filter=%s', _path_obj.base, base) return True if extns and _path_obj.extn not in extns: return True if head and not _path_obj.base.startswith(head): return True if tail and not _path_obj.base.endswith(tail): return True if filename and _path_obj.filename != filename: return True return False
<script lang="ts" setup> import SearchIcon from '@/assets/svg/search_icon_2367fdg.svg' import { onClickOutside } from '@vueuse/core' interface IProps { isFocus: boolean } const props = defineProps<IProps>() const value = defineModel<string>() const emit = defineEmits(['update:is-focus']) const searchRef = ref<HTMLInputElement>() const inputRef = $ref<HTMLInputElement>() watch( () => props.isFocus, (val) => { if (val) inputRef?.focus() } ) const updateIsFocus = (val: boolean) => emit('update:is-focus', val) onClickOutside(searchRef, () => updateIsFocus(false)) </script> <template> <div ref="searchRef" class="relative flex cursor-text items-center rounded-[8px] bg-c4/50 px-[16px] dark:bg-c23/50" @click="updateIsFocus(true)" > <SearchIcon class="[&>path]:stroke-black [&>path]:dark:stroke-white" /> <input ref="inputRef" v-model="value" type="text" placeholder="Search" :class="[ 'absolute left-[40px] top-1/2 h-[30px] w-[calc(100%-40px-16px)] -translate-y-1/2 bg-transparent text-sm caret-c7 focus:outline-none', ]" /> </div> </template>
import React, { FunctionComponent } from "react"; import { ourApproachData } from "../../constants"; import styles from "../../style"; const Approach: FunctionComponent = () => { return ( <React.Fragment> <section id='approach' className={`w-full sm:${styles.marginY} my-24 mt-10 flex flex-col justify-center sm:items-center`} > <div className='flex flex-col justify-center items-center'> <h2 className='font-poppins font-semibold text-[36px]'> <span className='text-gradient'>Our Approach</span> </h2> <p className={`font-poppins font-normal text-dimWhite text-[16px] leading-[30.8px] md:text-[24px] mt-6`} > At C.H.A.S.E IT Solutions, we prioritize: </p> </div> <div className='w-full h-auto flex flex-row justify-center items-center mt-12'> <div className='grid md:grid-cols-2 sm:gap-8 gap-6'> {ourApproachData.map((data) => ( <div className='py-8 px-8 bg-discount-gradient rounded-[10px] mb-2 z-[5]'> <p className={`${styles.paragraph}`}> <span className='text-gradient font-semibold select-none text-[16px] sm:text-[20px]'> {data.title} </span> </p> <div> <p className={`font-poppins font-normal text-dimWhite sm:text-[18px] sm:leading-[30.8px] select-none mt-2 z-[5] text-[14px]`} > {data.description} </p> </div> </div> ))} </div> </div> </section> </React.Fragment> ); }; export default Approach;
package gendsl_test import ( "errors" "fmt" "os" "strings" "github.com/ccbhj/gendsl" ) func ExampleEvalExpr() { plusOp := func(_ *gendsl.EvalCtx, args []gendsl.Expr, _ map[string]gendsl.Value) (gendsl.Value, error) { var ret gendsl.Int for _, arg := range args { v, err := arg.Eval() if err != nil { return nil, err } if v.Type() == gendsl.ValueTypeInt { ret += v.(gendsl.Int) } } return ret, nil } result, err := gendsl.EvalExpr("(PLUS ONE $TWO @THREE 4)", gendsl.NewEnv().WithInt("ONE", 1). WithInt("$TWO", 2). WithInt("@THREE", 3). WithProcedure("PLUS", gendsl.Procedure{ Eval: gendsl.CheckNArgs("+", plusOp), }), ) if err != nil { panic(err) } fmt.Println(result.Unwrap()) // Output: 10 } func ExampleEvalExprWithData() { printlnOp := func(ectx *gendsl.EvalCtx, args []gendsl.Expr, _ map[string]gendsl.Value) (gendsl.Value, error) { output := ectx.UserData.(*os.File) for _, arg := range args { v, err := arg.Eval() if err != nil { return nil, err } fmt.Fprintln(output, v.Unwrap()) } return gendsl.Nil{}, nil } out := os.Stdout _, err := gendsl.EvalExprWithData("(PRINTLN ONE $TWO @THREE 4)", gendsl.NewEnv().WithInt("ONE", 1). WithInt("$TWO", 2). WithInt("@THREE", 3). WithProcedure("PRINTLN", gendsl.Procedure{ Eval: gendsl.CheckNArgs("+", printlnOp), }), out, ) if err != nil { panic(err) } // Output: // 1 // 2 // 3 // 4 } func ExampleExpr_Text() { printlnOp := func(ectx *gendsl.EvalCtx, args []gendsl.Expr, _ map[string]gendsl.Value) (gendsl.Value, error) { for _, arg := range args { v, err := arg.Eval() if err != nil { return nil, err } fmt.Println(v.Unwrap()) } return gendsl.Nil{}, nil } letOp := func(ectx *gendsl.EvalCtx, args []gendsl.Expr, _ map[string]gendsl.Value) (gendsl.Value, error) { nameExpr := args[0] if nameExpr.Type() != gendsl.ExprTypeIdentifier { return nil, errors.New("expecting an identifier") } name := strings.TrimSpace(nameExpr.Text()) val, err := args[1].Eval() if err != nil { return nil, err } return args[2].EvalWithEnv(ectx.Env().WithValue(name, val)) } script := ` (LET foo "bar" (PRINTLN foo)) ` _, err := gendsl.EvalExpr(script, gendsl.NewEnv().WithInt("ONE", 1). WithProcedure("LET", gendsl.Procedure{ Eval: gendsl.CheckNArgs("3", letOp), }). WithProcedure("PRINTLN", gendsl.Procedure{ Eval: gendsl.CheckNArgs("+", printlnOp), }), ) if err != nil { panic(err) } // Output: // bar }
import 'package:flutter/material.dart'; class CounterWidget extends StatefulWidget { final int initialValue; final ValueChanged<int> onCounterChanged; CounterWidget({Key? key, required this.initialValue, required this.onCounterChanged}) : super(key: key); @override _CounterWidgetState createState() => _CounterWidgetState(); } class _CounterWidgetState extends State<CounterWidget> { late int count; @override void initState() { super.initState(); count = widget.initialValue; } void increment() { setState(() { count++; }); widget.onCounterChanged(count); } void decrement() { setState(() { if (count > 0) { count--; } }); widget.onCounterChanged(count); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( width: 85, height: 140, decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), color: Color.fromARGB(255, 62, 55, 73), ), child: Stack( alignment: Alignment.center, children: [ Positioned( top: 12, child: InkWell( onTap: increment, child: Container( width: 30, height: 30, decoration: BoxDecoration( shape: BoxShape.circle, color: Color.fromARGB(255, 41, 29, 63), ), child: Icon( Icons.add, color: Colors.white, ), ), ), ), Positioned( bottom: 12, child: InkWell( onTap: decrement, child: Container( width: 30, height: 30, decoration: BoxDecoration( shape: BoxShape.circle, color: Color.fromARGB(255, 41, 29, 63), ), child: Icon( Icons.remove, color: Colors.white, ), ), ), ), Positioned( top: 52, child: Container( alignment: Alignment.center, width: 37, height: 37, decoration: BoxDecoration( shape: BoxShape.circle, color: Color.fromARGB(255, 104, 104, 104), ), child: Text( '$count', style: TextStyle( color: Colors.white, fontSize: 20, ), ), ), ), ], ), ), ], ); } }
// RGB_LED_flash.ino ESP32 maker kit version of RGB_LED_flash.py // devices (motors, servos as well as LEDs) essentially by switching them on and off very very fast // PWM has 2 main parameters: // - Frequency: the number of time per second that a pulse is generated // - Duty Cycle: the % of time during a single cycle that the signal is high // code developed and compiled using the Arduino IDE v1.8.13 // ESP32 Dev Module set as the Board in the IDE - using board version 1.0.4 // even though the board is probably the NodeMCU-32S i.e. 38 pin ESP32 // Flash Size: 4MB // Partition Scheme set to: Default 4MB with spiffs (1.2 MB App / 1.5MB SPIFFS) // lots of other Board settings! but none experimented with int red_positive_pin = 17; //red RGB LED on ESP32 Maker Kit1 int green_positive_pin = 16; //green RGB LED on ESP32 Maker Kit1 int blue_positive_pin = 4; //blue RGB LED on ESP32 Maker Kit1 // setting PWM properties const int freq = 5000; // 10 bit resolution gives 0-1023 duty cycle control - possible resolutions are: 8, 10, 12, 15 const int resolution = 10; const int redChannel = 0; const int greenChannel = 1; const int blueChannel = 2; bool printon = true; void setup() { Serial.begin(115200); delay(1500); // short delay to set up the monitor Serial.print("program starting ..... "); // pins 1, 3, 5, 14, and 15 are set HIGH on boot - so set them LOW unless/until they are needed pinMode(1, OUTPUT); pinMode(3, OUTPUT); pinMode(5, OUTPUT); pinMode(14, OUTPUT); pinMode(15, OUTPUT); digitalWrite(1, LOW); digitalWrite(3, LOW); digitalWrite(5, LOW); digitalWrite(14, LOW); digitalWrite(15, LOW); pinMode(red_positive_pin, OUTPUT); // no longer strictly needed as we are now using ledcWrite pinMode(green_positive_pin, OUTPUT); // ditto pinMode(blue_positive_pin, OUTPUT); // ditto // configure LED PWM functionalitites ledcSetup(redChannel, freq, resolution); ledcSetup(greenChannel, freq, resolution); ledcSetup(blueChannel, freq, resolution); // attach the channels to the GPIOs to be controlled ledcAttachPin(red_positive_pin, redChannel); ledcAttachPin(green_positive_pin, greenChannel); ledcAttachPin(blue_positive_pin, blueChannel); ledcWrite(redChannel, 0); ledcWrite(greenChannel, 0); ledcWrite(blueChannel, 0); } void loop() { if (printon) { Serial.println("blink the red, green and blue RGB LEDs on/off @100% with a 1 second delay"); printon = false; } ledcWrite(redChannel, 1023); ledcWrite(greenChannel, 0); ledcWrite(blueChannel, 0); delay(1000); ledcWrite(redChannel, 0); ledcWrite(greenChannel, 1023); ledcWrite(blueChannel, 0); delay(1000); ledcWrite(redChannel, 0); ledcWrite(greenChannel, 0); ledcWrite(blueChannel, 1023); delay(1000); }
const readline = require('readline'); // Define the list of information to be recalled const infoList = ["home address", "your school", "phone number", "parents' names", "your name"]; // Function to prompt user for information function promptUserInformation() { const userInformation = {}; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); console.log("Please provide the following information:"); let index = 0; return new Promise((resolve, reject) => { function promptInfo() { if (index < infoList.length) { rl.question(`What is your ${infoList[index]}? `, (answer) => { userInformation[infoList[index]] = answer.trim(); index++; promptInfo(); }); } else { rl.close(); resolve(userInformation); } } promptInfo(); }); } // Function to start Simon Says game function simonSaysGame(userInformation) { const shuffledInfoList = [...infoList].sort(() => Math.random() - 0.5); // Shuffle the list let correctAnswers = 0; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function askQuestion(index) { if (index < shuffledInfoList.length) { const info = shuffledInfoList[index]; rl.question(`Simon says, what is your ${info}? `, (answer) => { if (answer.trim().toLowerCase() === userInformation[info].toLowerCase()) { console.log("Correct!\n"); correctAnswers++; askQuestion(index + 1); } else { console.log(`Sorry, that's incorrect. The correct answer is: ${userInformation[info]}.\n`); askQuestion(index); // Repeat the same question } }); } else { rl.close(); if (correctAnswers === infoList.length) { console.log("Congratulations! You've successfully recalled all the information."); } else { console.log("You missed some information. Let's try again."); simonSaysGame(userInformation); } } } askQuestion(0); } // Start the game async function startSimonSaysGame() { const userInformation = await promptUserInformation(); simonSaysGame(userInformation); } startSimonSaysGame();
package com.codingub.belarusianhistory.domain.use_cases import com.codingub.belarusianhistory.data.remote.network.ServerResponse import com.codingub.belarusianhistory.domain.repos.UserRepository import com.codingub.belarusianhistory.sdk.AccessLevel import com.codingub.belarusianhistory.sdk.AchieveType import com.codingub.belarusianhistory.data.models.achieves.AchieveDto import javax.inject.Inject class LoginUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke(login: String, password: String): ServerResponse<Unit> { return repository.signIn(login, password) } } class RegisterUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke( login: String, username: String, password: String, accessLevel: AccessLevel ): ServerResponse<Unit> { return repository.signUp(login, username, password, accessLevel) } } class AuthUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke(): ServerResponse<Unit> { return repository.authenticate() } } class RoleUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke(parameters: AccessLevel): ServerResponse<Unit> { return repository.changeRoleByLogin( accessLevel = parameters ) } } class GetTypeResultsUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke( userLogin: String, type: AchieveType ) = repository.getTypeResults(userLogin, type) } class GetAllResultsUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke( userLogin: String ) = repository.getAllResults(userLogin) } class AddResultUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke( userLogin: String, answer: Any?, achieve: AchieveDto ) = repository.setResult(userLogin, answer, achieve) } class ResetResultsUseCase @Inject constructor(private val repository: UserRepository) { suspend operator fun invoke( userLogin: String, type: AchieveType ) = repository.resetResults(userLogin, type) }
import React, {useState} from 'react'; export function PizzaBlock({name, price, imageUrl, sizes, types}) { const [numberOfPizza, setNumberOfPizza] = useState(0) const onClickAdd = () => { setNumberOfPizza(numberOfPizza + 1) } const typeName = ['тонкое', 'традиционное'] const [activeType, setActiveType] = useState(0) const [activeSize, setActiveSize] = useState(0) return ( <div className='pizza-block-wrapper'> <div className="pizza-block"> <img className="pizza-block__image" src={imageUrl} alt="Pizza" /> <h4 className="pizza-block__title">{name}</h4> <div className="pizza-block__selector"> <ul> {types.map((typeID) => ( <li className={activeType === typeID ? 'active' : ''} onClick={() => setActiveType(typeID)} key={typeID}>{typeName[typeID]}</li> ))} </ul> <ul> {sizes.map((sizes, index) => ( <li className={activeSize === index ? 'active' : ''} onClick={() => setActiveSize(index)} key={sizes}>{sizes} см.</li> ))} </ul> </div> <div className="pizza-block__bottom"> <div className="pizza-block__price">от {price}₽</div> <button onClick={onClickAdd} className="button button--outline button--add"> <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M10.8 4.8H7.2V1.2C7.2 0.5373 6.6627 0 6 0C5.3373 0 4.8 0.5373 4.8 1.2V4.8H1.2C0.5373 4.8 0 5.3373 0 6C0 6.6627 0.5373 7.2 1.2 7.2H4.8V10.8C4.8 11.4627 5.3373 12 6 12C6.6627 12 7.2 11.4627 7.2 10.8V7.2H10.8C11.4627 7.2 12 6.6627 12 6C12 5.3373 11.4627 4.8 10.8 4.8Z" fill="white" /> </svg> <span>Добавить</span> <i>{numberOfPizza}</i> </button> </div> </div> </div> ) }
package io.harness.cvng.activity.source.resources; import static io.harness.cvng.core.services.CVNextGenConstants.ACTIVITY_SOURCE_RESOURCE; import io.harness.annotations.ExposeInternalException; import io.harness.cvng.activity.source.services.api.ActivitySourceService; import io.harness.cvng.beans.activity.ActivitySourceDTO; import io.harness.ng.beans.PageResponse; import io.harness.ng.core.dto.ErrorDTO; import io.harness.ng.core.dto.FailureDTO; import io.harness.ng.core.dto.ResponseDTO; import io.harness.security.annotations.NextGenManagerAuth; import com.codahale.metrics.annotation.ExceptionMetered; import com.codahale.metrics.annotation.Timed; import com.google.inject.Inject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import javax.validation.constraints.NotNull; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import retrofit2.http.Body; @Api(ACTIVITY_SOURCE_RESOURCE) @Path(ACTIVITY_SOURCE_RESOURCE) @Produces("application/json") @ExposeInternalException @NextGenManagerAuth @ApiResponses(value = { @ApiResponse(code = 400, response = FailureDTO.class, message = "Bad Request") , @ApiResponse(code = 500, response = ErrorDTO.class, message = "Internal server error") }) public class ActivitySourceResource { @Inject private ActivitySourceService activitySourceService; @POST @Timed @ExceptionMetered @ApiOperation(value = "register a kubernetes event source", nickname = "registerActivitySource") public ResponseDTO<String> registerActivitySource(@QueryParam("accountId") @NotNull String accountId, @QueryParam("orgIdentifier") @NotNull String orgIdentifier, @QueryParam("projectIdentifier") @NotNull String projectIdentifier, @Body ActivitySourceDTO activitySourceDTO) { return ResponseDTO.newResponse( activitySourceService.saveActivitySource(accountId, orgIdentifier, projectIdentifier, activitySourceDTO)); } @POST @Timed @ExceptionMetered @Path("create") @ApiOperation(value = "create an activity source", nickname = "createActivitySource") public ResponseDTO<String> createActivitySource( @QueryParam("accountId") @NotNull String accountId, @Body ActivitySourceDTO activitySourceDTO) { return ResponseDTO.newResponse(activitySourceService.create(accountId, activitySourceDTO)); } @PUT @Timed @ExceptionMetered @Path("{identifier}") @ApiOperation(value = "update an activity source by identifier", nickname = "putActivitySource") public ResponseDTO<String> updateActivitySource(@NotNull @PathParam("identifier") String identifier, @QueryParam("accountId") @NotNull String accountId, @Body ActivitySourceDTO activitySourceDTO) { return ResponseDTO.newResponse(activitySourceService.update(accountId, identifier, activitySourceDTO)); } @GET @Timed @ExceptionMetered @ApiOperation(value = "gets a kubernetes event source by identifier", nickname = "getActivitySource") public ResponseDTO<ActivitySourceDTO> getActivitySource(@QueryParam("accountId") @NotNull String accountId, @QueryParam("orgIdentifier") @NotNull String orgIdentifier, @QueryParam("projectIdentifier") @NotNull String projectIdentifier, @QueryParam("identifier") @NotNull String identifier) { return ResponseDTO.newResponse( activitySourceService.getActivitySource(accountId, orgIdentifier, projectIdentifier, identifier)); } @GET @Timed @ExceptionMetered @Path("/list") @ApiOperation(value = "lists all kubernetes event sources", nickname = "listActivitySources") public ResponseDTO<PageResponse<ActivitySourceDTO>> listActivitySources( @QueryParam("accountId") @NotNull String accountId, @QueryParam("orgIdentifier") @NotNull String orgIdentifier, @QueryParam("projectIdentifier") @NotNull String projectIdentifier, @QueryParam("offset") @NotNull Integer offset, @QueryParam("pageSize") @NotNull Integer pageSize, @QueryParam("filter") String filter) { return ResponseDTO.newResponse(activitySourceService.listActivitySources( accountId, orgIdentifier, projectIdentifier, offset, pageSize, filter)); } @DELETE @Timed @ExceptionMetered @Path("{identifier}") @ApiOperation(value = "deletes a kubernetes event source", nickname = "deleteKubernetesSource") public ResponseDTO<Boolean> deleteKubernetesSource(@QueryParam("accountId") @NotNull String accountId, @QueryParam("orgIdentifier") @NotNull String orgIdentifier, @QueryParam("projectIdentifier") @NotNull String projectIdentifier, @PathParam("identifier") @NotNull String identifier) { return ResponseDTO.newResponse( activitySourceService.deleteActivitySource(accountId, orgIdentifier, projectIdentifier, identifier)); } }
--- abbrlink: 8d64 categories: - - IM date: '2023-10-21 22:15:00' description: 本文讲诉我是为什么要设计,并将IM系统作为我项目开发经历的 tags: - 浅谈系列 title: 浅谈我为什么要设计一个IM系统 top_img: 'https://img.lazysun.me/202310291105487.webp' cover: 'https://img.lazysun.me/202310212220891.jpg' updated: aplayer: aside: comments: highlight_shrink: katex: keywords: mathjax: type: --- # 浅谈我为什么要设计一个IM系统 ## 想法的萌发 我曾经负责的一个学校项目因为使用人数增多,系统负载太高,当学生开始上实验课时,系统有一定几率会出现各种问题,如CPU过高,响应速度变慢等,于是,为了日后支撑更高的访问量,我尝试着将该微服务横向扩展,即部署集群服务。 在此期间,因为之前一直是单机部署,所以代码有不少都没有考虑到微服务会出现的情况。这是我在部署集群时遇到的一个难点之一,特别是测验模块中的websocket,如果集群部署的话,那么多个实例中的不同session就无法进行通信。于是,我开始寻找解决方案。寻找途中,我被 [即时通讯网 - 即时通讯开发者社区! (52im.net)](http://www.52im.net/) 中的内容所吸引,从里面了解到了长连接通信中可能会出现的各种问题。此时,想尝试写一个IM系统的种子已然在心中萌发。 ## 为什么要开始做IM项目 在看完 52im 网各方大佬的帖子后,我就觉得IM并不是一个容易的项目,恰恰相反,它的功能虽然简单,但是实现起来要考虑的却非常多。在国内IM产品中,哪怕QQ,微信等一直被人所贬低,但是毫无疑问,作为一个即时通讯软件,它们都是很优秀的。虽然从大一开始学习JAVA,也开发和维护了一些项目,但是却一直未从零开始设计并实现一个完整可用的系统。对于现在的我来说,IM项目是具有一定的挑战性的,因此我希望能借此项目提高我的技术,并在github上开源,熟悉github的操作流程。 ## IM即时通讯的难点及挑战 ### 前端问题 作为一名后端开发人员,我对前端并没有深入了解。若是只论普通写个demo小页面,还勉强能有个形状,但是像这种要求比较高的,就属实无能为力了。不过还好有一个资深前端大佬帮忙😋,才能让这个IM项目能有个好看的界面。但即使这样,作为IM客户端,功能实现起来也不是一件容易事。另一方面,因为我们对PC,IOS,Android端都不甚了解,因此目前只有web端。 ### IM性能问题 一套成熟的IM系统,毫无疑问是要顶住高并发量的,同时要保证消息的实时性,可靠性,一致性,幂等性。比如在一个群聊中,用户发的消息要保证能发送到每一位群成员手上,不丢消息,延迟低而且消息不能乱序,同时在弱网环境下,也不能出现消息重传导致接收者接收到多条同样的消息。这些实现起来都是有一定难度的。 ### 功能问题 如果设计出来的IM系统仅仅只有文本聊天功能,那毫无疑问是一个很无趣的系统。因此,在聊天频道中,图片,语音,文件,表情包等,都可以成为一种需求。而要如何存储,如何展示,这也是难点之一。 ## 记录下自己完成该IM项目的过程 在飞书知识库中写下IM项目的项目文档,这也算是项目的一个发展路程。 同时,接下来也会在博客上继续记录开发开发过程。 ## 项目地址 团队:[AnyTopVv (github.com)](https://github.com/AnyTopVv) 团队名是基于某几个有意义的词组成的🤗 项目命名:ATVV-IM 前端地址:[AnyTopVv/atvv-im-frontend: atvv-im前端仓库 (github.com)](https://github.com/AnyTopVv/atvv-im-frontend) 后端地址:[AnyTopVv/atvv-im (github.com)](https://github.com/AnyTopVv/atvv-im)
<?php use Illuminate\Support\Facades\Route; use App\Http\Livewire\Auth\ForgotPassword; use App\Http\Livewire\Auth\ResetPassword; use App\Http\Livewire\Auth\Register; use App\Http\Livewire\Auth\Login; use App\Http\Livewire\Dashboard; use App\Http\Livewire\Billing; use App\Http\Livewire\Profile; use App\Http\Livewire\Tables; use App\Http\Livewire\StaticSignIn; use App\Http\Livewire\StaticSignUp; use App\Http\Livewire\Rtl; use App\Http\Livewire\InventoryLivewire; use App\Http\Livewire\InventoryCreate; use App\Http\Livewire\InventoryForm; use App\Http\Livewire\LaravelExamples\inventorymanagement; use App\Http\Livewire\VirtualReality; use Illuminate\Http\Request; use App\Http\Controllers\InventoryController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return redirect('/login'); }); Route::middleware('guest')->group(function () { Route::get('/register', Register::class)->name('register'); Route::get('/login', Login::class)->name('login'); Route::get('/login/forgot-password', ForgotPassword::class)->name('forgot-password'); Route::get('/reset-password/{id}', ResetPassword::class)->name('reset-password')->middleware('signed'); }); Route::middleware('auth')->group(function () { Route::get('/dashboard', Dashboard::class)->name('dashboard'); Route::get('/add-inventory', InventoryForm::class)->name('add-inventory'); // Use InventoryForm here Route::get('/inventory-management', inventorymanagement::class)->name('inventory-management'); Route::delete('/inventory/{id}', [InventoryController::class, 'destroy'])->name('inventory.delete'); // Route::get('/dashboard', Dashboard::class)->name('dashboard'); // Route::get('/billing', Billing::class)->name('billing'); // Route::get('/profile', Profile::class)->name('profile'); // Route::get('/tables', Tables::class)->name('tables'); // Route::get('/static-sign-in', StaticSignIn::class)->name('sign-in'); // Route::get('/static-sign-up', StaticSignUp::class)->name('static-sign-up'); // Route::get('/rtl', Rtl::class)->name('rtl'); // Route::get('/virtual-reality', VirtualReality::class)->name('virtual-reality'); });
import 'package:bloc_sm_testing/features/cart/ui/cart.dart'; import 'package:bloc_sm_testing/features/home/bloc/home_bloc_bloc.dart'; import 'package:bloc_sm_testing/features/home/ui/product_tile_widget.dart'; import 'package:bloc_sm_testing/features/wishlist/ui/wishlist.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { final HomeBlocBloc homeBloc = HomeBlocBloc(); @override void initState() { homeBloc.add(HomeInitialEvent()); super.initState(); } @override Widget build(BuildContext context) { return BlocConsumer<HomeBlocBloc, HomeBlocState>( bloc: homeBloc, listenWhen: (previous, current) => current is HomeActionState, buildWhen: (previous, current) => current is! HomeActionState, listener: (context, state) { if (state is HomeNavigateToCartPageActionState) { Navigator.push( context, MaterialPageRoute(builder: (context) => const Cart()), ); } else if (state is HomeNavigateToWishlistPageActionState) { Navigator.push( context, MaterialPageRoute(builder: (context) => const WishList()), ); } else if (state is HomeProductItemWishlistedActionState) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Item added to wishlist successfully'))); } else if (state is HomeProductItemCartedActionState) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Item added to cart successfully'))); } }, builder: (context, state) { switch (state.runtimeType) { case HomeLoadingState: return const Scaffold( body: Center( child: CircularProgressIndicator(), ), ); case HomeLoadedSuccessState: final successState = state as HomeLoadedSuccessState; return Scaffold( appBar: AppBar( title: const Text( 'Groceries app', style: TextStyle( fontSize: 25, ), ), backgroundColor: Colors.teal, actions: [ IconButton( onPressed: () { homeBloc.add(HometWishlistButtonNavigateEvent()); }, icon: const Icon(Icons.favorite_border), ), IconButton( onPressed: () { homeBloc.add(HometCartButtonNavigateEvent()); }, icon: const Icon(Icons.shopping_bag_outlined), ), ], ), body: ListView.builder( itemCount: successState.products.length, itemBuilder: (context, index) { return ProductTileWidget( homeBloc: homeBloc, productdataModel: successState.products[index]); })); case HomeErrorState: return const Scaffold( body: Center( child: Text('something went wrong'), ), ); default: return const SizedBox(); } }, ); } }
import os import os.path from typing import Callable, Optional # Class for "following" files, i.e. capturing changes in a file as a # process writes output into it. Used for capturing cTOASTER model and # build process output for display in the GUI. class Tailer: """ Class for "following" files, capturing changes in a file as a process writes output into it. Used for capturing GENIE model and build process output for display in the GUI. """ def __init__(self, app, fname: str) -> None: """ Initializes the Tailer object. :param app: A Tkinter application object used for timers. :param fname: The filename of the file to follow. """ self.app = app # Tkinter application. self.fname: str = fname # Filename to follow. self.pos: int = 0 # Current position in the file. self.fp: Optional[os.fdopen] = None # Current file handle, initially None. self.after_id: Optional[int] = ( None # ID of the current "after" timer, initially None. ) self.cb: Optional[Callable] = ( None # Callback for reporting file changes, initially None. ) def start(self, cb: Callable) -> None: """ Start tailing the file, calling the given callback with new data as it's written. :param cb: A callback function that takes no arguments and returns None. """ self.cb = cb # Simplified condition check for readability if not self.after_id: self.after_id = self.app.after(0, self.read) def stop(self) -> None: """ Stop tailing the file and clean up resources. """ # Use a guard clause to reduce nesting and improve readability if self.after_id: self.app.after_cancel(self.after_id) self.after_id = None if self.fp: self.fp.close() self.fp = None def read(self) -> None: """ Attempt to read new data from the tailed file and report to the callback. """ # Check if the file is not open yet and if it exists. if not self.fp and os.path.exists(self.fname): # Open the file and start from the beginning. self.fp = open(self.fname, "r") # Specify mode explicitly for clarity self.pos = 0 if self.fp: # Determine the current size of the file. self.fp.seek(0, os.SEEK_END) size = self.fp.tell() # Local variable for clarity if size > self.pos: # If new content exists, read it and update the position. self.fp.seek(self.pos, os.SEEK_SET) new_data = self.fp.read( size - self.pos ) # More descriptive variable name self.pos = size if self.cb: # Ensure callback is not None before calling self.cb(new_data) # Schedule the next read. self.after_id = self.app.after(500, self.read)
import { useState, useEffect } from "react"; const Broker = () => { const [brokers, setBrokers] = useState([]); useEffect(() => { fetch("http://localhost:3000/brokers/get-all") .then((response) => response.json()) .then((data) => setBrokers(data)) .catch((error) => console.error("Error fetching brokers", error)); }, []); return ( <div className="px-28"> {/* Broker Row - 1 */} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8 pt-14"> {brokers.map((broker) => ( <div key={broker._id} className="w-full max-w-sm rounded-lg shadow-md bg-black border border-gray-200 dark:bg-white dark:hover:bg-green-100" > <div className="flex flex-col justify-between items-center h-full pb-16 pt-10"> <img className="w-32 h-32 mb-3 rounded-full shadow-2xl" style={{ boxShadow: "0 4px 6px rgba(0, 0, 0, 0.4)" }} // src={broker.image} src= "https://img.freepik.com/free-photo/young-bearded-man-with-striped-shirt_273609-5677.jpg?size=626&ext=jpg&ga=GA1.1.735520172.1710806400&semt=sph" alt={broker.fullName} /> <h5 className="mb-1 text-xl font-medium text-gray-900 dark:text-black mt-2"> {broker.fullName} </h5> <span className="text-sm text-black dark:text-black mt-2"> Email: {broker.email} </span> <span className="text-sm text-black mt-2"> Contact: {broker.contactNumber} </span> <span className="text-sm text-black mt-2"> Address: {broker.address} </span> <span className="text-sm text-black mt-2"> City: {broker.city} </span> </div> </div> ))} </div> </div> ); }; export default Broker;
import {proxy, useSnapshot} from "valtio" import {subscribeKey} from "valtio/utils" import "./index.css" const tick = () => { state.elapsed = window.performance.now() - state.start } const state = proxy({ start: window.performance.now(), duration: 10000, elapsed: 0, setDuration(e: React.ChangeEvent<HTMLInputElement>) { state.duration = Number(e.target.value) setTimeout(() => state.reset()) }, reset() { state.elapsed = 0 state.start = window.performance.now() tick() } }) let raf: number subscribeKey(state, "elapsed", () => { if (state.elapsed < state.duration) { raf = requestAnimationFrame(tick) } return () => { cancelAnimationFrame(raf) } }) raf = requestAnimationFrame(tick) const Progress = () => { const snap = useSnapshot(state) const progress = snap.elapsed / snap.duration return ( <div className="progress-container"> <progress value={progress} />{" "} <label>{((progress * snap.duration) / 1000).toFixed(1)}s</label> </div> ) } const Duration = () => { const snap = useSnapshot(state) return ( <input type="range" min="1" max="10000" value={snap.duration} onChange={snap.setDuration} /> ) } const Timer = () => { const snap = useSnapshot(state) return ( <div className="timer"> <Progress /> <Duration /> <button onClick={snap.reset}>Reset</button> </div> ) } export default Timer
import { useState, useContext } from "react"; import { motion, AnimatePresence } from "framer-motion"; import DropdownItems from "./DropdownItems"; import filterContext from "../../Store/filter-context"; import classes from "./DropdownMenu.module.css"; import arrowDown from "../../Assets/arrow-dropdown.svg"; const showMenu = { enter: { opacity: 1, y: 0, display: "block", }, exit: { y: -6, opacity: 0, transition: { duration: 0.2, }, transitionEnd: { display: "none", }, }, }; const DropdownMenu = () => { const [open, setOpen] = useState(false); const ctxFilter = useContext(filterContext); const filter = ["Angular", "Reactjs", "Vuejs"]; const handleFilter = (filter) => { ctxFilter.changeFilter(filter.toLowerCase()); }; return ( <div className={classes.filterContainer}> <div className={classes.filterContainer_header} onClick={() => { setOpen(!open); }} > <p className={classes.filterContainer_header_title}>Select your news</p> <img alt="img" className={classes.filterContainer_header_icon} src={arrowDown} /> </div> <AnimatePresence> <motion.div variants={showMenu} initial="exit" animate={open ? "enter" : "exit"} className={classes.filterContainer_dropdown} > {filter.map((item, index) => ( <DropdownItems key={index} link={item.toLowerCase()} item={item} select={handleFilter} > {item} </DropdownItems> ))} </motion.div> </AnimatePresence> </div> ); }; export default DropdownMenu;
import React, { useEffect, useState } from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import axios from 'axios'; import AdminDashboard from '../component/AdminDashboard' function EditUser() { const [users, setUsers] = useState([]); const [showDeleteAlert, setShowDeleteAlert] = useState(false); useEffect(() => { axios.get('http://localhost:4000/api/viewusers') .then(users => setUsers(users.data)) .catch(err => console.log(err)) }, []); const handleDeleteUser = async (userId) => { try { await axios.delete(`http://localhost:4000/api/delete/${userId}`); setUsers(users.filter(user => user._id !== userId)); setShowDeleteAlert(true); setTimeout(() => { window.location.reload(); }, 1000); } catch (error) { console.log(error); } }; return ( <div> <AdminDashboard /> <div className='w-100 vh-100 d-flex justify-content-center align-items-center '> <div className='w-50 border shadow'> {showDeleteAlert && ( <div className="alert alert-danger fade show" role="alert"> User deleted successfully! </div> )} <table className="table text-center p-2"> <thead className='table-light border'> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Age</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> {users.map((user, index) => ( <tr key={user._id}> <th scope="row">{index + 1}</th> <td>{user.Name}</td> <td>{user.Email}</td> <td>{user.Age}</td> <td><button className="btn btn-info btn-sm">Edit</button></td> <td> <button className="btn btn-danger btn-sm" onClick={() => handleDeleteUser(user._id)} > Delete </button> </td> </tr> ))} </tbody> </table> </div> </div> </div> ); } export default EditUser;
package com.neml.java.multithreading; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; public class ThreadPoolClass { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); for (int i = 0; i < 5; i++) { Runnable th = new ThreadClass("message " + i); executor.execute(th); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all threads"); } } class ThreadClass implements Runnable { Runnable r = new Runnable() { @Override public void run() { ScheduledMethod(); } }; String message; ThreadClass(String message) { this.message = message; } @Override public void run() { System.out.println(Thread.currentThread().getName() + " | message = " + message); waitForThread(); System.out.println(Thread.currentThread().getName() + " | End"); } void waitForThread() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } void ScheduledMethod() { System.out.println("This is scheduled Method"); } }
CREATE DATABASE exam_15_oct_2022; USE exam_15_oct_2022; CREATE TABLE products ( id INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(30) NOT NULL UNIQUE, `type` VARCHAR(30) NOT NULL, price DECIMAL(10 , 2 ) NOT NULL ); CREATE TABLE clients ( id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, birthdate DATE NOT NULL, card VARCHAR(50), review TEXT ); CREATE TABLE `tables` ( id INT PRIMARY KEY AUTO_INCREMENT, floor INT NOT NULL, reserved TINYINT(1), capacity INT NOT NULL ); CREATE TABLE waiters ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL, phone VARCHAR(50), salary DECIMAL(10 , 2 ) ); CREATE TABLE orders ( id INT AUTO_INCREMENT PRIMARY KEY, table_id INT NOT NULL, waiter_id INT NOT NULL, order_time TIME NOT NULL, payed_status TINYINT(1), CONSTRAINT fk_orders_tables FOREIGN KEY (table_id) REFERENCES `tables` (id), CONSTRAINT fk_orders_waiter FOREIGN KEY (waiter_id) REFERENCES waiters (id) ); CREATE TABLE orders_products ( order_id INT, product_id INT, CONSTRAINT fk_orders_products_order_id_orders_id FOREIGN KEY (order_id) REFERENCES orders (id), CONSTRAINT fk_orders_products_product_id_products_id FOREIGN KEY (product_id) REFERENCES products (id) ); CREATE TABLE orders_clients ( order_id INT, client_id INT, CONSTRAINT fk_orders_clients_order_id_orders_id FOREIGN KEY (order_id) REFERENCES orders (id), CONSTRAINT fk_orders_clients_client_id_clients_id FOREIGN KEY (client_id) REFERENCES clients (id) );
<script setup lang="ts"> import BaseBadge from './BaseBadge.vue'; import BaseCard from './BaseCard.vue'; defineProps<{ fullName: string; infoText: string; role: string; }>(); </script> <template> <section> <BaseCard> <template v-slot:header> <h3>{{ fullName }}</h3> <BaseBadge :type="role" :caption="role.toUpperCase()"></BaseBadge> </template> <p>{{ infoText }}</p> </BaseCard> </section> </template>
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_bcrypt import Bcrypt import os db = SQLAlchemy() def create_app(): app = Flask(__name__, template_folder='templates') app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.abspath('./testdb.db') app.secret_key = 'your_secret_key_here' db.init_app(app) login_manager = LoginManager() login_manager.init_app(app) from models import User @login_manager.user_loader def load_user(uid): return User.query.get(uid) from routes import register_routes register_routes(app, db) migrate = Migrate(app, db) return app
哦坏了 忘了粘原文了 大致这意思就是 给个数 保证是整数 看看这个整数是不是某个整数的平方数 我这边的思路呢 大致就是 α开算数平方根一定小于α (α∈整数,坏了 就这个水平还想考研? 哦法克 今天还他妈是CET4考试) 然后 小于α的数的平方一个个试↓ ![](20230312180152.png) ↑令人满意的4次基础测试 def is_square(n): if n < 0: return False elif n == 0: return True else: mark = 0 for i in range(1,n+1): # 0比较特殊就不用试了 if i*i == n: mark = 1 # 匹配到满足条件的数值后 标记转换为1 break if mark == 1: return True if mark == 0: return False ![](20230312180251.png) 就是这个效率吧 稍微大点的估计客户就等不起了 于是修改方法 平方结果大于α的直接终止循环 能节省很大一部分时间 但如果n的数值很大的话 还是要花很多时间的 ![](20230312192559.png) 虽然过了 其实这里边有个后续隐患 看代码 def is_square(n): if n < 0: return False elif n == 0: return True else: mark = 0 for i in range(n): # 如果n = 1 的话 这个循环只重复一次 即i = 1 结果就是 n = 1时 只进行0*0=0 导致mark还是0 输出为False ans = i*i if ans == n: mark = 1 break if ans > n: break if mark == 1: return True if mark == 0: return False --- 社区答案 基本上集中在使用math库 --- import math def is_square(n): try: return math.sqrt(n).is_integer() except ValueError: return False --- def is_square(n): if n>=0: if int(n**.5)**2 == n: return True return False --- def is_square(n): if n < 0: return False if n == 0: return True k = 1 while True: k_square = k**2 if k_square > n: return False if k_square == n: return True k = k + 1 --- import math def is_square(n): return n > -1 and math.sqrt(n) % 1 == 0; --- Orz def is_square(n): return n >= 0 and (n**0.5) % 1 == **0**
package com.example.mobiletworeview.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class RetrofitModule { private val apiUrl = "https://jsonplaceholder.typicode.com/" @Singleton @Provides fun provideRetrofit() : Retrofit { return Retrofit.Builder() .baseUrl(apiUrl) .addConverterFactory(GsonConverterFactory.create()) .build() } }
import { useRef, useEffect } from "react"; /** * A React hook that returns the previous value of a given value. * @param {*} value - The current value. * @returns {*} The previous value. */ function usePrev(value) { const ref = useRef(); useEffect(() => { ref.current = value; }, [value]); return ref.current; } export default usePrev;
from django.contrib import admin from .models import MenuItem, Category, CartMenuItem, Order, OrderItem @admin.register(MenuItem) class MenuItemAdmin(admin.ModelAdmin): list_display = ('title', 'price', 'featured', 'category') search_fields = ('title',) list_filter = ('featured', 'category') @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ('title', 'slug') search_fields = ('title',) @admin.register(CartMenuItem) class CartMenuItemAdmin(admin.ModelAdmin): list_display = ('user', 'menu_item', 'quantity') search_fields = ('user__username', 'menu_item__title') list_filter = ('user', 'menu_item') @admin.register(Order) class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'delivery_crew', 'status', 'total', 'date'] list_filter = ['status', 'date'] search_fields = ['user__username', 'delivery_crew__username'] readonly_fields = ['id'] @admin.register(OrderItem) class OrderItemAdmin(admin.ModelAdmin): list_display = ['id', 'order', 'menu_item', 'quantity', 'unit_price', 'price'] search_fields = ['order__id', 'menu_item__name'] readonly_fields = ['id']
import * as api from '../api/api' import { getErrorDataFromNetworkException } from '../common/utils' import { HIDE_MESSAGE, SEND_MESSAGE_ERROR, SET_LOADING, SHOW_MESSAGE, UNSET_LOADING, SHOW_ALERT, HIDE_ALERT, SEND_CONTACT_MESSAGE_ERROR, SHOW_CONTACT_MESSAGE, HIDE_CONTACT_MESSAGE } from './action-types' export function setGlobalLoading (message) { return { type: SET_LOADING, data: { message } } } export function unsetGlobalLoading () { return { type: UNSET_LOADING } } export function sendMessage (msg) { return async (dispatch, getState) => { const investor = getState().global.investor || { id: 0 } try { await api.sendMessage({ investorId: investor.id, message: msg }) dispatch(hideMessage()) } catch (err) { dispatch({ type: SEND_MESSAGE_ERROR, data: getErrorDataFromNetworkException(err) }) throw new Error(getErrorDataFromNetworkException(err).errorMessage) } } } export function showMessage (investor) { return { type: SHOW_MESSAGE, data: { investor: investor } } } export function hideMessage () { return { type: HIDE_MESSAGE } } export function sendContactMessage (msg) { return async (dispatch) => { try { await api.sendContact({ message: msg }) dispatch(hideContactMessage()) } catch (err) { dispatch({ type: SEND_CONTACT_MESSAGE_ERROR, data: getErrorDataFromNetworkException(err) }) throw new Error(getErrorDataFromNetworkException(err).errorMessage) } } } export function showContactMessage () { return { type: SHOW_CONTACT_MESSAGE } } export function hideContactMessage () { return { type: HIDE_CONTACT_MESSAGE } } export function showAlertError (message) { return { type: SHOW_ALERT, message, alertType: 'error' } } export function hideAlert () { return { type: HIDE_ALERT } }
# TessuMod: Mod for integrating TeamSpeak into World of Tanks # Copyright (C) 2015 Janne Hakonen # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import collections import json import os class KeyValueStorage(collections.MutableMapping): def __init__(self, storage_path): self.__storage_path = storage_path self.__cache_mapping = {} self.__create_storage_dir() self.__load_cache_from_storage_path() def __create_storage_dir(self): if not os.path.isdir(self.__storage_path): os.makedirs(self.__storage_path) def __load_cache_from_storage_path(self): for filename in os.listdir(self.__storage_path): filepath = self.__make_key_path(filename) if os.path.isfile(filepath): with open(filepath, "r") as file: self.__cache_mapping[filename] = json.loads(file.read()) def __make_key_path(self, key): return os.path.join(self.__storage_path, key) def __getitem__(self, key): return self.__cache_mapping[key] def __setitem__(self, key, value): with open(self.__make_key_path(key), "w") as file: file.write(json.dumps(value)) self.__cache_mapping[key] = value def __delitem__(self, key): del self.__cache_mapping[key] os.remove(self.__make_key_path(key)) def __iter__(self): return iter(self.__cache_mapping) def __len__(self): return len(self.__cache_mapping)
--- layout: post title: "Eight Six Suited Vs Pocket Queens Poker Hand Odds | Which Is The Better Hand In Poker? A Complete Guide" author: reece categories: [ ] image: assets/images/86s-vs-qq.jpg description: "Discover the ultimate showdown between Eight Six Suited and Pair Of Queens in poker! Uncover the odds, strategies, and scenarios where one hand triumphs over the other. Get ready to up your poker game with this thrilling analysis." first_paragraph: "<p>Welcome to our latest poker strategy deep dive, where we're pitting two distinct hands against each other in a high-stakes showdown: Eight Six Suited vs Pair Of Queens.</p><p>In the dynamic world of poker, every decision counts, and knowing which hand holds the upper hand is key to your success at the table.</p><p>In this article, we'll dissect these two hands, explore the scenarios where one dominates the other, and equip you with the knowledge to make strategic choices that can tip the odds in your favor.</p><p>Get ready to unravel the intriguing dynamics of these poker hands and elevate your game to new heights.</p>" eq_1: 79.07 eq_2: 20.93 win_1: 78.89 tie: 0.35 win_2: 20.76 card_1_label: 86s card_2_label: QQ --- [comment]: # (sp0) ## Pre Flop Hand Match Up <div class="table hand-ratings" markdown="1"> ### Eight Six Suited vs Pair Of Queens - Odds Of Winning <div class="row graphs"> <div class="col-lg-6"> <h3>Win Probablility</h3> <canvas id="WinChart"></canvas> </div> <div class="col-lg-6"> <h3>Equity</h3> <canvas id="EquityChart"></canvas> </div> </div> Below, we present a detailed breakdown of the winning probabilities for each hand, providing you with the insight you need to navigate the intricate landscape of poker strategy and decision-making. Dive into these numbers, and you'll find yourself better equipped to make those crucial calls at the table. | ![image info](assets/images/hand1/8.png) ![image info](assets/images/hand1/6.png) | | ![image info](assets/images/hand2/q.png) ![image info](assets/images/hand2/qo.png) | | -------- | -------- | -------- | | Eight Six Suited (86s) | | Pair Of Queens (QQ) | | 78.89% | Win | 20.76% | | 0.35% | Tie | 0.35% | | 79.07% | Equity | 20.93% | [comment]: # (sp1) ### Eight Six Suited vs Pair Of Queens - Limit Poker Hand Ratings Top poker experts and players have crafted ways to judge the strength of starting hands in limit Texas hold'em. Below, you'll see a table breaking down hand rankings according to popular systems. Do remember, these rankings don't apply to no limit games. | ![image info](https://www.riverpairs.com/assets/images/hand1/8.png) ![image info](https://www.riverpairs.com/assets/images/hand1/6.png) | | ![image info](https://www.riverpairs.com/assets/images/hand2/q.png) ![image info](https://www.riverpairs.com/assets/images/hand2/qo.png) | | -------- | -------- | -------- | | Eight Six Suited | | Pair Of Queens | | 6 | **Sklansky Rating** [What is this?](/sklansky-rating-explained) | 1 | | 2.5 | **Chen Formula** [What is this?](/chen-formula-explained) | 14 | | - | **Hellmuth Tier** [What is this?](/Hellmuth-tier-explained) | 1 | | -0.07 | **Expected Value** [What is this?](/expected-value-explained) | 1.22 | [comment]: # (sp2) ### Eight Six Suited vs Pair Of Queens - Winning Hand Breakdown | ![image info](https://www.riverpairs.com/assets/images/hand1/8.png) ![image info](https://www.riverpairs.com/assets/images/hand1/6.png) | | ![image info](https://www.riverpairs.com/assets/images/hand2/q.png) ![image info](https://www.riverpairs.com/assets/images/hand2/qo.png) | | -------- | -------- | -------- | | Eight Six Suited | | Pair Of Queens | | 0 | High Card | 0 | | 10,261,440 | One Pair | 0 | | 12,686,004 | Two Pair | 1,515,888 | | 4,301,964 | Three Of A Kind | 1,040,112 | | 508,644 | Straight | 2,994,048 | | 746,616 | Flush | 2,202,648 | | 3,536,460 | Full House | 659,232 | | 372,588 | Four Of A Kind | 47,472 | | 5,724 | Straight Flush | 70,692 | [comment]: # (sp3) </div> [comment]: # (sp4) [comment]: # (sp5)
using PipeHow.AzBobbyTables.Validation; using System; using System.Collections; using System.Linq; using System.Management.Automation; namespace PipeHow.AzBobbyTables.Cmdlets; /// <summary> /// <para type="synopsis">Add one or more entities to an Azure Table.</para> /// </summary> [Cmdlet(VerbsCommon.Add, "AzDataTableEntity")] public class AddAzDataTableEntity : AzDataTableOperationCommand { /// <summary> /// <para type="description">The context used for the table, created with New-AzDataTableContext.</para> /// </summary> [Parameter(Mandatory = true)] public AzDataTableContext Context { get; set; } /// <summary> /// <para type="description">The entities to add to the table.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true)] [ValidateEntity] [ValidateNotNullOrEmpty()] public object[] Entity { get; set; } /// <summary> /// <para type="description">Overwrites provided entities if they exist.</para> /// </summary> [Parameter()] public SwitchParameter Force { get; set; } /// <summary> /// <para type="description">If the table should be created if it does not exist.</para> /// </summary> [Parameter()] public SwitchParameter CreateTableIfNotExists { get; set; } /// <summary> /// The process step of the pipeline. /// </summary> protected override void ProcessRecord() { if (tableService is null) { WriteError(new ErrorRecord(new InvalidOperationException("Could not establish connection!"), "ConnectionError", ErrorCategory.ConnectionError, null)); return; } try { switch (Entity.First()) { case Hashtable: tableService.AddEntitiesToTable(Entity.Cast<Hashtable>(), Force.IsPresent); break; case PSObject: tableService.AddEntitiesToTable(Entity.Cast<PSObject>(), Force.IsPresent); break; default: throw new ArgumentException($"Entities provided were not Hashtable or PSObject! First entity was of type {Entity.GetType().FullName}!"); } } catch (AzDataTableException ex) { WriteError(ex.ErrorRecord); } } }
import { TileTableData } from "../tileTableData/TileTableData"; import { BatchTableClassProperties } from "./BatchTableClassProperties"; import { Ids } from "./Ids"; import { PropertyTableModel } from "../metadata/PropertyTableModel"; import { PropertyModel } from "../metadata/PropertyModel"; import { DefaultPropertyModel } from "../metadata/DefaultPropertyModel"; import { DefaultPropertyTableModel } from "../metadata/DefaultPropertyTableModel"; import { TileFormatError } from "../tileFormats/TileFormatError"; /** * Methods to create `PropertyTableModel` instances for batch table data * * @internal */ export class BatchTablePropertyTableModels { /** * Creates a `PropertyTableModel` for the given batch table data. * * @param table - The table * @param binary - The binary data * @param externalProperties - External properties, i.e. property model * instances for properties of the batch table that are not stored in * the batch table binary. This is only required for the properties that * are encoded with the `3DTILES_draco_point_compression` extension, * where the actual data is stored in the feature table binary. These * models are accessed with property IDs. * @param numRows - The number of rows of the table * @returns The property table model * @throws TileFormatError If the table contained a property * that was neither found in the 'externalProperties', nor has * been a BatchTableBinaryBodyReference nor an array */ static create( table: { [key: string]: any }, binary: Buffer, externalProperties: { [key: string]: PropertyModel }, numRows: number ): PropertyTableModel { const propertyTableModel = new DefaultPropertyTableModel(numRows); const properties = Object.keys(table); for (const propertyName of properties) { if (propertyName === "extensions" || propertyName === "extras") { continue; } const propertyValue = table[propertyName]; const propertyId = Ids.sanitize(propertyName); const classProperty = BatchTableClassProperties.createClassProperty( propertyId, propertyValue ); propertyTableModel.addClassProperty(propertyId, classProperty); const externalProperty = externalProperties[propertyId]; if (externalProperty) { propertyTableModel.addPropertyModel(propertyId, externalProperty); } else if (TileTableData.isBatchTableBinaryBodyReference(propertyValue)) { const legacyType = propertyValue.type; const legacyComponentType = propertyValue.componentType; const byteOffset = propertyValue.byteOffset; const propertyModel = TileTableData.createNumericPropertyModel( legacyType, legacyComponentType, binary, byteOffset ); propertyTableModel.addPropertyModel(propertyId, propertyModel); } else if (Array.isArray(propertyValue)) { const propertyModel = new DefaultPropertyModel(propertyValue); propertyTableModel.addPropertyModel(propertyId, propertyModel); } else { throw new TileFormatError( `Property ${propertyId} was neither a binary body ` + `reference nor an array` ); } } return propertyTableModel; } }
/* * tests/atomspace/ValuationTableUTest.cxtest * * Copyright (C) 2017 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <iostream> #include <fstream> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/ValuationTable.h> #include <opencog/atoms/value/FloatValue.h> #include <opencog/atoms/base/Link.h> #include <opencog/atoms/base/Node.h> #include <opencog/util/Logger.h> using namespace opencog; using namespace std; class ValuationTableUTest : public CxxTest::TestSuite { private: AtomSpace* space; ValuationTable* vtable; public: ValuationTableUTest() { // Uncomment to enable logging //logger().setLevel(Logger::DEBUG); //logger().setPrintToStdoutFlag(true); space = new AtomSpace(); // vtable = (ValuationTable*) & (atomSpace->get_atomvtable()); vtable = new ValuationTable(); } ~ValuationTableUTest() { delete space; delete vtable; } void setUp() {} void tearDown() {} void testSimple() { Handle key = space->add_node(CONCEPT_NODE, "The F Key"); Handle blah = space->add_node(CONCEPT_NODE, "28675194"); ValuePtr fvalue(createFloatValue(2.222)); // Place a valuation in the table. vtable->addValuation(key, blah, fvalue); // Get it back, and make sure that its equal to what we put in. ValuePtr fetch = vtable->getValue(key, blah); TS_ASSERT_EQUALS(fvalue, fetch); } void testKeyset() { Handle ka = space->add_node(CONCEPT_NODE, "The F Key"); Handle kb = space->add_node(CONCEPT_NODE, "The G Key"); Handle kc = space->add_node(CONCEPT_NODE, "The H Key"); Handle blah = space->add_node(CONCEPT_NODE, "Hi Mom!"); ValuePtr fvalue(createFloatValue(2.222)); vtable->addValuation(ka, blah, fvalue); vtable->addValuation(kb, blah, fvalue); vtable->addValuation(kc, blah, fvalue); HandleSet keys = vtable->getKeys(blah); TS_ASSERT_EQUALS(3, keys.size()); TS_ASSERT(keys.end() != keys.find(ka)); TS_ASSERT(keys.end() != keys.find(kb)); TS_ASSERT(keys.end() != keys.find(kc)); } };
<script context="module" lang="ts"> /** @type {import('@sveltejs/kit').Load} */ export async function load({ fetch }) { const url = `/api/words/current.json`; const res: Response = await fetch(url); const data = await res.json(); return { props: { wordId: data.id } }; } </script> <script lang="ts"> import { onMount } from 'svelte'; import Board from '../components/Board.svelte'; import Keyboard from '../components/Keyboard/Keyboard.svelte'; import { createInitialGameState, gameState } from '../components/store'; export let wordId; onMount(() => { if ($gameState.wordId !== wordId) { const newState = createInitialGameState(wordId); $gameState = newState; } }); </script> <Board {wordId} /> <Keyboard />
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {HttpInterceptorBasicAuthService} from './services/http/http-interceptor-basic-auth.service' import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './components/login/login.component'; import { ErrorComponent } from './components/error/error.component'; import { HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http'; import { MenuComponent } from './components/menu/menu.component'; import { LogoutComponent } from './components/logout/logout.component'; import { UserHomeComponent } from './components/user-home/user-home.component'; import { NewticketrequestComponent } from './components/newticketrequest/newticketrequest.component'; import { UserRegistrationComponent } from './components/user-registration/user-registration.component'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { UserRegistrationConfirmationComponent } from './components/user-registration-confirmation/user-registration-confirmation.component'; import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component'; import { PasswordChangeComponent } from './components/password-change/password-change.component'; import { WelcomeComponent } from './components/welcome/welcome.component'; import { AdminLoginComponent } from './components/admin-login/admin-login.component'; import { AdminHomeComponent } from './components/admin-home/admin-home.component'; import { AdminTicketReviewComponent } from './components/admin-ticket-review/admin-ticket-review.component'; import { TicketRequestConfirmationComponent } from './components/ticket-request-confirmation/ticket-request-confirmation.component'; import {Ng2SearchPipeModule} from 'ng2-search-filter'; import {NgxPaginationModule} from 'ngx-pagination'; import {SortDirective} from './directives/sort.directive'; import { CoronaComponent } from './components/corona/corona.component'; import { TicketDetailComponent } from './components/ticket-detail/ticket-detail.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, ErrorComponent, MenuComponent, LogoutComponent, UserHomeComponent, NewticketrequestComponent, UserRegistrationComponent, UserRegistrationConfirmationComponent, ForgotPasswordComponent, PasswordChangeComponent, WelcomeComponent, AdminLoginComponent, AdminHomeComponent, AdminTicketReviewComponent, TicketRequestConfirmationComponent, SortDirective, CoronaComponent, TicketDetailComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, CommonModule, ReactiveFormsModule, FormsModule, Ng2SearchPipeModule, NgxPaginationModule ], providers: [ // UserDataService, {provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorBasicAuthService, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
--- title: OLED Display AutoHotkey Script for Automatically Dimming the Taskbar date: 2023-11-21 08:46:00 lastmod: 2023-11-23 10:52:31 categories: - guide tags: - oled - ahk - script aliases: share: true --- # OLED Display AutoHotkey Script for Automatically Dimming the Taskbar ## Goal 1. Auto-dim the taskbar to prevent burn in. 2. Keep the dimming when an app is opened in full-screen on a second monitor. 3. Stop the dimming if an app is opened full-screen on the primary monitor. ## Sources - Reddit source : [Screensaver and taskbar dimmer for protecting OLED displays during Windows desktop and gaming usage scenarios : r/OLED\_Gaming](https://www.reddit.com/r/OLED_Gaming/comments/sa6clj/screensaver_and_taskbar_dimmer_for_protecting/) - StackOverflow reference with script : [How can I make icons in the Windows 10 taskbar/quicklaunch/tray darker to help prevent burn-in on my OLED display? - Super User](https://superuser.com/a/1691664/1708452) - Detecting full screen app to stop dimming : [Detect Fullscreen application? - Ask for Help - AutoHotkey Community](https://www.autohotkey.com/board/topic/38882-detect-fullscreen-application/) - Detecting the screen the current window is on : [Detecting the screen the current window is on - Ask for Help - AutoHotkey Community](https://www.autohotkey.com/board/topic/85457-detecting-the-screen-the-current-window-is-on/) ## Script ```ahk SysGet, Monitor, Monitor ; Get monitor dimensions SysGet, WorkArea, MonitorWorkArea ; Get monitor work-area without taskbar dimtop := % WorkAreaBottom + 1 ; taskbar is assumed to start below the work-area Gui Color, 0,0 ; Black color Gui -Caption +ToolWindow +E0x20 ; No title bar, No taskbar button, Transparent for clicks Gui Show, X0 Y%dimtop% W%MonitorRight% H63 ; Create a semi-transparent cover window WinGet ID, ID, A ; Get its HWND/handle ID Winset AlwaysOnTop,ON,ahk_id %ID% ; Keep it always on the top WinSet Transparent,99,ahk_id %ID% ; Transparency 99/256 SetTimer, coverIt, 500 ; Repeat setting it to be on top of the taskbar return GetCurrentMonitor() { SysGet, numberOfMonitors, MonitorCount WinGetPos, winX, winY, winWidth, winHeight, A winMidX := winX + winWidth / 2 winMidY := winY + winHeight / 2 Loop %numberOfMonitors% { SysGet, monArea, Monitor, %A_Index% if (winMidX > monAreaLeft && winMidX < monAreaRight && winMidY < monAreaBottom && winMidY > monAreaTop) return A_Index } SysGet, primaryMonitor, MonitorPrimary return "No Monitor Found" } coverIt: WinGet style, Style, A ; Get active window style and dimensions WinGetPos ,,,winW,winH, A ; 0x800000 is WS_BORDER. ; 0x20000000 is WS_MINIMIZE. ; check no border and not minimized isfull := ((style & 0x20800000) = 0 and winH >= A_ScreenHeight and winW >= A_ScreenWidth) isPrimaryMonitor := (GetCurrentMonitor() = 1) if (isfull and isPrimaryMonitor) { WinHide, ahk_id %ID% } else { WinShow, ahk_id %ID% Winset AlwaysOnTop,ON,ahk_id %ID% ; Ensure it is still on the top } return ```
\clearpage \title{Finding root of nonlinear equation using False Position Method.} \author{} \date{} \maketitle \section*{Introduction} \subsection*{False Position Method} False position method is based on the fact that if $f(x)$ is real and continuous function, and for two initial guesses $a$ and $b$ brackets the root such that: $f(a)\times f(b) < 0$ then there exists at least one root between $a$ and $b$.\\\\ If $a$ and $b$ are two guesses then we compute new approximated root as: \[c = a - \frac{f(a)\times (b-a)}{f(b) - f(a)}\] Now we have following three different cases: \begin{itemize} \item If $f(c)=0$ then the root is c. \item If $f(a)\times f(b)< 0$ then root lies between $a$ and $c$. \item If $f(a)\times f(c)> 0$ then root lies between $b$ and $c$. \end{itemize} And then the process is repeated until we find the root within desired accuracy.\cite{falsePos} \section*{Tools Used} \begin{itemize} \item MATLAB R2021a - for writing and running code. \item MacTeX -\LaTeX compiler. \item VS Code with \LaTeX workshop extension as a text editor. \end{itemize} \section*{Process} \subsection*{Code for False Position:} \begin{minted}[breaklines, linenos]{matlab} % Clearing Screen clc % Setting x as symbolic variable syms x; % Input Section eqn = input('Enter non-linear equations: '); a = input('Enter first guess: '); b = input('Enter second guess: '); e = input('Tolerable error: '); % Finding Functional Value fa = eval(subs(eqn,x,a)); fb = eval(subs(eqn,x,b)); % Implementing False Position Method if fa*fb > 0 disp('Given initial values do not bracket the root.'); else c = a - (a-b) * fa/(fa-fb); fc = eval(subs(eqn,x,c)); fprintf('\n\na\t\t\tb\t\t\tc\t\t\tf(c)\n'); while abs(fc)>e fprintf('%f\t%f\t%f\t%f\n',a,b,c,fc); if fa*fc< 0 b =c; fb = eval(subs(eqn,x,b)); else a =c; fa = eval(subs(eqn,x,a)); end c = a - (a-b) * fa/(fa-fb); fc = eval(subs(eqn,x,c)); end fprintf('\nRoot is: %f\n', c); end \end{minted} \subsection*{Output} \begin{center} \centering \includegraphics[width = .9\textwidth]{false.jpeg} \captionof{figure}{Flase Position method} \end{center}
import React, { FC } from "react"; import { StyleProp, StyleSheet, Text, TextStyle, View, ViewStyle, } from "react-native"; type Props = { text?: string; textStyle?: StyleProp<TextStyle>; style?: StyleProp<ViewStyle>; }; const EmptyView: FC<Props> = ({ text = "Listen er tom", style, textStyle }) => { return ( <View style={[styles.container, style]}> <Text style={[styles.emptyText, textStyle]}>{text}</Text> </View> ); }; const styles = StyleSheet.create({ container: { justifyContent: "center", alignItems: "center", width: "100%", height: "100%", }, emptyText: { fontSize: 34, color: "#9b9c9e", fontFamily: "HelveticaNeueLTPro-Hv", textAlign: "center", }, }); export default EmptyView;
import csv import requests from params import Params as params_ def read_swarm(): """ Reads the swarm configuration file, which includes the list of nodes in the swarm. The function supports both online and offline modes. In online mode, it downloads the swarm configuration file from the specified URL. In offline mode, it reads the swarm configuration file from the local disk. """ if params_.offline_swarm: return read_file('../swarm.csv', 'local CSV file', params_.hw_id) else: print("Loading swarm configuration from online source...") try: print(f'Attempting to download file from: {params_.swarm_url}') response = requests.get(params_.swarm_url) if response.status_code != 200: print(f'Error downloading file: {response.status_code} {response.reason}') return None with open('online_swarm.csv', 'w') as f: f.write(response.text) return read_file('online_swarm.csv', 'online CSV file', params_.hw_id) except Exception as e: print(f"Failed to load online swarm configuration: {e}") print("Swarm configuration not found.") def read_file(filename, source, hw_id): with open(filename, newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if int(row['hw_id']) == int(hw_id): print(f"Configuration for HW_ID {hw_id} found in {source}.") return row return None if __name__ == '__main__': read_swarm()
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.tuantran.repository.impl; import com.tuantran.pojo.Cart; import com.tuantran.pojo.ReceiptDetail; import com.tuantran.pojo.ReceiptStatus; import com.tuantran.pojo.Receipts; import com.tuantran.pojo.Users; import com.tuantran.repository.FoodItemsRepository; import com.tuantran.repository.ReceiptRepository; import com.tuantran.repository.UsersRepository; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.persistence.NoResultException; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * * @author Administrator */ @Transactional @Repository public class ReceiptRepositoryImpl implements ReceiptRepository { @Autowired private LocalSessionFactoryBean factory; @Autowired private UsersRepository userRepo; @Autowired private FoodItemsRepository foodItemsRepo; @Autowired private Environment env; @Override @Transactional(propagation = Propagation.REQUIRED) public boolean addReceipt(Map<String, Cart> carts) { Session session = this.factory.getObject().getCurrentSession(); Receipts receipt = new Receipts(); try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Users user = this.userRepo.getUserByUsername_new(authentication.getName()); receipt.setUserId(user); receipt.setReceiptDate(new Date()); receipt.setActive(Boolean.TRUE); receipt.setStatusReceiptId(new ReceiptStatus(1)); session.save(user); double totalAmount = 0; for (Cart cart : carts.values()) { ReceiptDetail receiptDetail = new ReceiptDetail(); receiptDetail.setFooditemId(this.foodItemsRepo.getFoodItemById(Integer.parseInt(cart.getFoodId().toString()))); receiptDetail.setReceiptId(receipt); receiptDetail.setQuantity(cart.getQuantity()); receiptDetail.setUnitPrice(BigDecimal.valueOf(cart.getUnitPrice())); double amount = cart.getQuantity() * cart.getUnitPrice(); receiptDetail.setAmount(BigDecimal.valueOf(amount)); totalAmount += amount; session.save(receiptDetail); } receipt.setTotalPayment(BigDecimal.valueOf(totalAmount)); return true; } catch (HibernateException ex) { ex.printStackTrace(); return false; } } @Override public List<Receipts> getReceipts(Map<String, String> params) { Session session = this.factory.getObject().getCurrentSession(); // Query query = session.createQuery("From Fooditems"); CriteriaBuilder b = session.getCriteriaBuilder(); CriteriaQuery<Receipts> q = b.createQuery(Receipts.class); Root root = q.from(Receipts.class); q.select(root); if (params != null) { List<Predicate> predicates = new ArrayList<>(); String kw = params.get("userId"); if (kw != null && !kw.isEmpty()) { predicates.add(b.equal(root.get("userId"), Integer.parseInt(kw))); } // // String fromPrice = params.get("fromPrice"); // if (fromPrice != null && !fromPrice.isEmpty()) { // predicates.add(b.greaterThanOrEqualTo(root.get("price"), Double.parseDouble(fromPrice))); // } // // String toPrice = params.get("toPrice"); // if (toPrice != null && !toPrice.isEmpty()) { // predicates.add(b.lessThanOrEqualTo(root.get("price"), Double.parseDouble(toPrice))); // } // // String cateFoodId = params.get("cateFoodId"); // if (cateFoodId != null && !cateFoodId.isEmpty()) { // predicates.add(b.equal(root.get("categoryfoodId"), Integer.valueOf(cateFoodId))); // } // // String restaurantId = params.get("restaurantId"); // if (restaurantId != null && !restaurantId.isEmpty()) { // predicates.add(b.equal(root.get("restaurantId"), Integer.valueOf(restaurantId))); // } // q.where(predicates.toArray(Predicate[]::new)); } q.orderBy(b.desc(root.get("receiptDate"))); Query query = session.createQuery(q); if (params != null) { String page = params.get("page"); if (page != null && !page.isEmpty()) { int p = Integer.parseInt(page); int pageSize = Integer.parseInt(this.env.getProperty("PAGE_SIZE")); query.setMaxResults(pageSize); query.setFirstResult((p - 1) * pageSize); } } return query.getResultList(); } @Override public Receipts getReceiptById(int id) { try { Session session = this.factory.getObject().getCurrentSession(); CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery<Receipts> criteriaQuery = builder.createQuery(Receipts.class); Root<Receipts> root = criteriaQuery.from(Receipts.class); Predicate idPredicate = builder.equal(root.get("receiptId"), id); Predicate otherCondition = builder.equal(root.get("active"), Boolean.TRUE); Predicate finalPredicate = builder.and(idPredicate, otherCondition); criteriaQuery.where(finalPredicate); return session.createQuery(criteriaQuery).getSingleResult(); } catch (NoResultException e) { e.printStackTrace(); return null; } } @Override public boolean updateAcceptReceipt(Receipts receipt) { Session session = this.factory.getObject().getCurrentSession(); try { session.update(receipt); return true; } catch (HibernateException ex) { ex.printStackTrace(); return false; } } }
$black: #222; $white: #fafafa; $gold: #ba9261; body { margin: 0; font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif; color: $white; &:before { content: ""; display: block; position: fixed; left: 0; top: 0; background-image: url('/img/background.jpg'); background-size: cover; background-attachment: fixed; background-repeat: no-repeat; background-position: 50% 45%; width: 100%; height: 100%; z-index: -10; @supports (-webkit-overflow-scrolling: touch) { background-attachment: initial; } } a { color: $gold; text-decoration: none; } h1, h2, h3, h4, h5, h6 { font-family: 'Arizonia', Helvetica, sans-serif; color: $gold; margin-top: 1rem; margin-bottom: 1rem; } h1 { font-size: 3em; } h2 { font-size: 2.6em; } h3 { font-size: 2.4em; } h4 { font-size: 2em; } h5 { font-size: 1.7em; } h6 { font-size: 1.5em; } img { max-width: 100%; } .center { text-align: center; } .center-block { display: block; margin: auto; } #mobile-menu-curtain { display: none; position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1; } nav { display: -webkit-box; display: -ms-flexbox; display: flex; position: fixed; top: 0; left: 0; min-height: 51px; width: 100%; background-color: $white; text-transform: uppercase; text-align: center; z-index: 1; .nav-item { -webkit-transition: .25s all; -o-transition: .25s all; transition: .25s all; -ms-flex-preferred-size: 20%; flex-basis: 20%; cursor: pointer; padding: 1rem 0.5rem; &:hover, &.active { background-color: $gold; color: $white; } @media(max-width: 709px) { display: none; } } #mobile-menu-icon { display: none; position: absolute; top: -6px; right: 15px; margin: 1rem auto; width: 45px; height: 45px; -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .5s ease-in-out; -o-transition: .5s ease-in-out; transition: .5s ease-in-out; cursor: pointer; div { display: block; position: absolute; height: 7px; width: 100%; background-color: $black; border-radius: 9px; opacity: 1; left: 0; -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .25s ease-in-out; -o-transition: .25s ease-in-out; transition: .25s ease-in-out; &:nth-child(1) { top: 0px; } &:nth-child(2) { top: 12px; } &:nth-child(3) { top: 24px; } } &.open { div { &:nth-child(1) { top: 12px; -webkit-transform: rotate(135deg); -ms-transform: rotate(135deg); transform: rotate(135deg); } &:nth-child(2) { opacity: 0; left: -60px; } &:nth-child(3) { top: 12px; -webkit-transform: rotate(-135deg); -ms-transform: rotate(-135deg); transform: rotate(-135deg); } } } @media(max-width: 709px) { display: block; } } #mobile-menu { display: none; position: absolute; top: 51px; right: 0; background-color: $white; text-align: left; .nav-item { display: inline-block; -webkit-box-sizing: border-box; box-sizing: border-box; width: 100%; } } } section#monogram { margin-top: 3rem; text-align: center; @supports not (-ms-ime-align: auto) { svg { #graphic { stroke-dasharray: 9600; stroke-dashoffset: 9600; fill-opacity: 0; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards; animation-iteration: 1; -webkit-animation-name: DrawLine, FadeStroke, FillIn; animation-name: DrawLine, FadeStroke, FillIn; -webkit-animation-duration: 2s, 1s, 1s; animation-duration: 2s, 1s, 1s; -webkit-animation-delay: 1s, 3s, 3s; animation-delay: 1s, 3s, 3s; } @-webkit-keyframes DrawLine { to { stroke-dashoffset: 0; } } @keyframes DrawLine { to { stroke-dashoffset: 0; } } @-webkit-keyframes FadeStroke { to { stroke-opacity: 0; } } @keyframes FadeStroke { to { stroke-opacity: 0; } } @-webkit-keyframes FillIn { from { fill-opacity: 0; } to { fill-opacity: 1; } } @keyframes FillIn { from { fill-opacity: 0; } to { fill-opacity: 1; } } } } @supports (-ms-ime-align: auto) { svg { #graphic { stroke: none; } } } @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { svg { #graphic { stroke: none; } } } } section#content-container { position: relative; max-width: 800px; margin: 0 auto 3rem; border-radius: 5px; background-color: rgba(34,34,34,0.85); padding: 1rem; #close { position: absolute; top: -13px; right: 5px; font-size: 3rem; cursor: pointer; } .column-section { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-flow: row wrap; flex-flow: row wrap; .column { -webkit-box-flex: 1; -ms-flex: 1 1 48%; flex: 1 1 48%; padding: 20px 0; &.left-column { padding-right: 15px; } &:not(.left-column) { padding-left: 15px; } @media(max-width: 798px) { -ms-flex-preferred-size: 51%; flex-basis: 51%; &.left-column { padding-right: 0; } &:not(.left-column) { padding-left: 0; } } } &#registry-images { -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; .registry-image { margin: 1rem 0; text-align: center; } } } #rsvp-form-container { text-align: center; #rsvp-form { input { border: 1px solid $white; background-color: transparent; margin: 0.5rem auto; padding: 0.5rem; color: $white; font-size: 1rem; &[name="attendees"] { max-width: 30px; } &[name="phone"] { display: none; } } #rsvp-submit { margin-top: 0.5rem; border: none; background-color: $gold; padding: 0.5rem 1rem; font-size: 1rem; } } } } footer { position: fixed; bottom: 0; right: 0; padding: .25rem; background-color: $black; opacity: .8; font-size: .9rem; color: $white; text-align: center; p { margin: .25rem auto; } } }
import React, {useState, useEffect} from "react"; //components import Page from "../../components/Page"; import CheckVerbForm from "./components/CheckVerbForm"; import FormSettings from './components/FormSettings' // ui components import Grid from '@material-ui/core/Grid'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; import FormControl from '@material-ui/core/FormControl'; import ButtonGroup from '@material-ui/core/ButtonGroup'; import Button from '@material-ui/core/Button'; // others import {irregularVerbs} from "../../data"; import {getRandom} from "./helpers"; const defaultSettings = { withExtended: true, oneAttempt: false, numberOfCards: 10, }; // statuses const START = 'start'; const PROGRESS = 'progress'; const FINISH = 'finish'; const Training = () => { const [status, setStatus] = useState(START); const [settings, setSettings] = useState(defaultSettings); const [cards, setCards] = useState([]); const [words, setWords] = useState(irregularVerbs); const [step, setStep] = useState(0); const {withExtended, numberOfCards} = settings; useEffect(() => { setWords(withExtended ? irregularVerbs : irregularVerbs.filter(({extended}) => !extended)) }, [withExtended]); const start = (numberOfCards) => { setCards(getRandom(words, numberOfCards)); setStep(0); setStatus(PROGRESS); }; const finish = () => { setStatus(FINISH); }; const next = () => { const nextStep = step + 1; setStep(nextStep); if (nextStep === numberOfCards) { setStatus(FINISH); } }; const ProgressBlock = ( <div> <h6>{step + 1}/{numberOfCards}</h6> <CheckVerbForm handleOnSubmit={() => { next() }} word={cards[step]} stop={finish}/> </div> ); const FinishBlock = ( <Card> <CardContent> <Typography gutterBottom variant="h5" component="h2"> Your results </Typography> </CardContent> <CardActions> <FormControl> <ButtonGroup variant="contained" color="primary"> <Button onClick={() => { setStatus(START); }}>Repeat </Button> <Button onClick={() => { setStatus(START); setSettings(defaultSettings); }}>Go to Settings </Button> </ButtonGroup> </FormControl> </CardActions> </Card> ); return ( <Page title="Training"> <Grid container alignItems="center" justifyContent="center"> {status === START && <FormSettings settings={settings} maxNumberOfCards={words.length} setSettings={(newSettings) => { setSettings(newSettings) }} handleSubmit={(values) => { setSettings(values); start(values.numberOfCards); }}/>} {status === PROGRESS && ProgressBlock} {status === FINISH && FinishBlock} </Grid> </Page> ); }; export default Training
import { Body, Controller, Get, Post, Patch, Param, Query, Delete, Session, UseGuards, } from '@nestjs/common'; import { CreateUserDto } from './dtos/create-user.dto'; import { UsersService } from './users.service'; import { UpdateUserDto } from './dtos/update-user.dto'; import { Serialize } from 'src/interceptors/serialize.interceptor'; import { UserDto } from './dtos/user.dto'; import { AuthService } from './auth.service'; import { CurrentUser } from './decorators/current-user.decorator'; import { User } from './user.entity'; import { AuthGuard } from 'src/guards/auth.guard'; @Controller('auth') @Serialize(UserDto) export class UsersController { constructor( private userService: UsersService, private authService: AuthService, ) {} @Get('/whoami') @UseGuards(AuthGuard) async whoAmI(@CurrentUser() user: User) { return user; } @Post('/signup') async createUser( @Body() { email, password }: CreateUserDto, @Session() session: any, ) { const user = await this.authService.signup(email, password); session.userId = user.id; return user; } @Post('/signin') async signin( @Body() { email, password }: CreateUserDto, @Session() session: any, ) { const user = await this.authService.signin(email, password); session.userId = user.id; return user; } @Post('/signout') signout(@Session() session: any) { session.userId = null; return 'Logged out successfully'; } @Get('/:id') findUser(@Param('id') id: string) { return this.userService.findOne(id); } @Get() findAllUsers(@Query('email') email: string) { return this.userService.find(email); } @Patch('/:id') updateUser(@Param('id') id: string, @Body() body: UpdateUserDto) { console.log(body); return this.userService.update(id, body); } @Delete('/:id') removeUser(@Param('id') id: string) { return this.userService.remove(id); } }
# Wifi Manager for .NET MAUI Welcome to the documentation for the MAUI Wi-Fi Manager library, a comprehensive solution designed specifically for MAUI. This library empowers developers to effortlessly manage Wi-Fi networks within their cross-platform applications. With its intuitive APIs, you can seamlessly integrate Wi-Fi functionality, allowing users to connect to, add, and retrieve information about Wi-Fi networks with ease. [![WifiManager.Maui](https://img.shields.io/nuget/v/WifiManager.Maui)](https://www.nuget.org/packages/WifiManager.Maui/) ## Platform Support | S. No. | Platform | Support | Remarks | | ------ | ------------ | --------- | ----------- | | 1. | Android | &#9745; | | | 2. | iOS | &#9745; | | | 3. | Windows | &#9745; | | | 4. | Mac | &#x2612; | Coming Soon | | 5. | Tizen | &#x2612; | Coming Soon | ## Features - Connect Wi-Fi with SSID and Password: Enable users to connect to Wi-Fi networks by providing the SSID and password. - Add a New Wi-Fi Network: Seamlessly add new Wi-Fi networks to the device. - Get Current Network Info: Retrieve information about the currently connected Wi-Fi network. - Disconnect Wi-Fi: Allow users to disconnect from a Wi-Fi network. - Open Wi-Fi Setting: Provide a quick way for users to access their device's Wi-Fi settings. ## Getting started ### Initialization Before using the MAUI Wi-Fi Manager plugin in your application, it's essential to initialize it. Here's how to do it on different platforms: #### Android To use the MAUI Wi-Fi Manager on Android, you must initialize the plugin. Add the following code to your Android application: ```csharp WifiNetworkService.Init(this); ``` Android Permissions ```xml <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ``` Make sure you request location before scanning Wi-Fi #### iOS Add wifi-info and HotspotConfiguration in Entitlements.plist ```xml <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.developer.networking.wifi-info</key> <true/> <key>com.apple.developer.networking.HotspotConfiguration</key> <true/> </dict> </plist> ``` Request location permission on info.plist ```xml <key>NSLocationWhenInUseUsageDescription</key> <string>App want to access location to get ssid</string> ``` Example ```csharp PermissionStatus status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>(); if (status == PermissionStatus.Granted) { var response = await CrossWifiManager.Current.ScanWifiNetworks(); } else await DisplayAlert("No location permission", "Please provide location permission", "OK"); ``` #### Connect to Wi-Fi To connect to a Wi-Fi network programmatically, use the ConnectWifi method. This method takes the SSID and password as parameters. Here's an example: ```csharp var response = await CrossWifiManager.Current.ConnectWifi(ssid, password); ``` The NetworkData class is defined as follows: ```csharp public class NetworkData { public int StausId { get; set; } public string Ssid { get; set; } public int IpAddress { get; set; } public string GatewayAddress { get; set; } public object NativeObject { get; set; } public object Bssid { get; set; } public object SignalStrength { get; set; } } ``` #### Scan available Wi-Fi (Not available on iOS) You can available Wi-Fi networks using the ScanWifiNetworks method (Available on Android & Windows): ```csharp var response = await CrossWifiManager.Current.ScanWifiNetworks(); ``` #### Get Wi-Fi info You can retrieve information about the currently connected Wi-Fi network using the GetNetworkInfo method: ```csharp var response = await CrossWifiManager.Current.GetNetworkInfo(); ``` #### Disconnect Wi-Fi To disconnect from a Wi-Fi network, simply call the DisconnectWifi method with the SSID as a parameter: ```csharp CrossWifiManager.Current.DisconnectWifi(ssid); ``` #### Open Wi-Fi Setting If you want to provide users with a convenient way to access their device's Wi-Fi settings, use the OpenWifiSetting method: ```csharp var response = await CrossWifiManager.Current.OpenWifiSetting(); ``` I value your feedback! If you encounter any issues, have suggestions for improvement, or wish to report bugs, please open an issue on GitHub or GitLab repository ## License MIT License Copyright (c) 2023 Santosh Dahal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit import SwiftUI public enum Navigation: Equatable { /// PresentationStyle uses to choose correct form of pushing your screen. /// - Note: /// + fullscren - its normal presentation like `UINavigationController.push(...)` without additional settings. /// + modal - its modal presentation like `UINavigationController.present(...)` without additional settings. /// + bottomSheet - its modal presentation of the screen from bottom part with simple animation. /// + custom - its fully customisable animation for `UINavigationController.push(...)` with your own parameters. *WORK IN PROGRESS* public enum PresentationStyle { case fullscreen case modal case bottomSheet(BottomSheetSize) case custom(UIViewControllerTransitioningDelegate) } public enum BottomSheetSize { case fixed(CGFloat) case halfScreen case fullScreen case auto } public enum RestructActionAnimation { case forward case backward } public enum Action { case push(NaviduxScreen, ScreenConfig, PresentationStyle) case pop(NullablePayload) case popUntil(NaviduxScreen, NullablePayload) case restruct(screens: [NavigationRestructable], animationType: RestructActionAnimation) case replaceCertain(NaviduxScreen, ScreenConfig, RestructActionAnimation) case showAlert(AlertConfiguration) } } public protocol NavigationRestructable {}
import db from "../../Config/pg.config.js"; export default class CartController { async addProductToCart(req, res) { const { product_id, quantity } = req.body; const user_id = req.userID; //taken from JWT payload try { // Get [product details] to calculate total_price const productQuery = ` SELECT price FROM products WHERE id = $1; `; const productResult = await db.query(productQuery, [product_id]); const product = productResult.rows[0]; // Check if product is available if (product.length==0 || product.availability == false || product.quantity < quantity) { if(product.availability == false) { return res.status(400).json({ success: false, message: 'Product not available' }); } return res.status(400).json({ success: false, message: 'Product quantity exceeded' }); } // Calculate total_price for [cart item] const total_price = product.price * quantity; // [ Start transaction ] await db.query('BEGIN'); // Update [product quantity] in product table const updateProductQuery = ` UPDATE products SET quantity = quantity - $1 WHERE id = $2 RETURNING *; `; await db.query(updateProductQuery, [quantity, product_id]); // Add item to [ cart table ] const insertCartQuery = ` INSERT INTO cart (product_id, user_id, quantity, total_price) VALUES ($1, $2, $3, $4) RETURNING *; `; const newCart = await db.query(insertCartQuery, [product_id, user_id, quantity, total_price]); // [ Commit transaction ] await db.query('COMMIT'); res.status(201).send({ success: true, message: 'Cart item added successfully', cart: newCart.rows[0] }); } catch (error) { // [ Rollback transaction on error ] await db.query('ROLLBACK'); console.error('Error in Add Product to cart', error); res.status(500).send({ success: false, message: 'Error in Add Product to cart' }); } } async viewCart(req, res) { const user_id = req.userID; //taken from JWT payload try { const viewCartQuery = ` SELECT * FROM cart WHERE user_id = $1; `; const cartItems = await db.query(viewCartQuery, [user_id]); res.status(200).send({ success: true, cart: cartItems.rows }); } catch (error) { console.error('Error in View Cart', error); res.status(500).send({ success: false, message: 'Error in View Cart' }); } } async updateCart(req, res) { const cart_id = req.params.id; //cart_item id const { quantity } = req.body; // const user_id = req.userID; //taken from JWT payload try { // Get [cart details] to update quantity const cartQuery = ` SELECT product_id, quantity AS old_quantity FROM cart WHERE id = $1; `; const cartResult = await db.query(cartQuery, [cart_id]); const cart = cartResult.rows[0]; // const { product_id, quantity: oldQuantity } = cartResult.rows[0]; if (!cart) { return res.status(404).send({ success: false, message: 'Cart item not found' }); } // Get [ product details ] including price and availability const productQuery = ` SELECT price, quantity, availability FROM products WHERE id = $1; `; const productResult = await db.query(productQuery, [cart.product_id]); const product = productResult.rows[0]; if (!product || !product.availability) { return res.status(400).json({ success: false, message: 'Product not available' }); } // Calculate New total_price const total_price = product.price * quantity; // Check if product quantity is sufficient if (quantity > product.quantity) { return res.status(400).json({ success: false, message: 'Quantity exceeded from product availability' }); } // Start transaction await db.query('BEGIN'); // Update product quantity in product table // const updateProductQuery = ` // UPDATE products // SET quantity = quantity - ($1 - $2) // WHERE id = $3 // RETURNING *; // `; const updateProductQuery = ` UPDATE products SET quantity = quantity - (COALESCE($1, 0) - $2) WHERE id = $3 RETURNING *; `; await db.query(updateProductQuery, [quantity, cart.old_quantity, cart.product_id]); // Update cart item in cart table const updateCartQuery = ` UPDATE cart SET quantity = $1, total_price = $2 WHERE id = $3 RETURNING *; `; const updatedCart = await db.query(updateCartQuery, [quantity, total_price, cart_id]); // Commit transaction await db.query('COMMIT'); res.status(200).send({ success: true, message: 'Cart item updated successfully', cart: updatedCart.rows[0] }); } catch (error) { // [ Rollback transaction on error ] await db.query('ROLLBACK'); console.error('Error in update cart', error); res.status(500).send({ success: false, message: 'Error in update cart' }); } } async deleteCart(req, res) { const cart_id = req.params.id; //cart_item id try { // Get [ product_id and quantity ] of the cart item const cartQuery = ` SELECT product_id, quantity FROM cart WHERE id = $1; `; const cartResult = await db.query(cartQuery, [cart_id]); const cart = cartResult.rows[0]; // const { product_id, quantity } = cartResult.rows[0]; if (!cart) { return res.status(404).json({ success: false, message: 'Cart item not found' }); } // Start transaction await db.query('BEGIN'); // Update product quantity in product table const updateProductQuery = ` UPDATE products SET quantity = quantity + $1 WHERE id = $2 RETURNING *; `; await db.query(updateProductQuery, [cart.quantity, cart.product_id]); // Delete cart item const deleteCartQuery = ` DELETE FROM cart WHERE id = $1; `; await db.query(deleteCartQuery, [cart_id]); // [ Commit transaction ] await db.query('COMMIT'); res.status(200).send({ success: true, message: 'Cart item deleted successfully' }); } catch (error) { // [ Rollback transaction on error ] await db.query('ROLLBACK'); console.error('Error in Delete Cart Item', error); res.status(500).send({ success: false, message: 'Error in Delete Cart Item' }); } } }
--- layout: article title: Can AI progress continue at the current pace? tags: AI AI-governace-course license: true show_subscribe: false show_edit_on_github: false --- <p> This post is for <a href="https://course.aisafetyfundamentals.com/home/governance?week=1">Week 1: Introduction to AI and Machine Learning</a> of the <a href="https://course.aisafetyfundamentals.com/governance">BlueDot Impact AI Safety Fundamentals: Governance Course</a>. Each week of the course comprises some readings, a short essay writing task, and a 2-hour group discussion. This post is <a href="/2023/08/14/AI-governance-course-explainer.html">part of a series</a> that I'm publishing to show my work, document my current thinking on the topics, and better reflect on the group discussion on the topic as I explain <a href="/2023/08/14/AI-governance-course-explainer.html#org8fcce5a">here</a>. </p> <div id="outline-container-orgcccffd3" class="outline-2"> <h2 id="orgcccffd3">Essay task</h2> <div class="outline-text-2" id="text-orgcccffd3"> <p> <b>To what extent do you currently believe that AI progress can continue at the current pace? What are your uncertainties?</b> </p> <p> AI progress can continue at the current pace due mainly to the continuing increase in computing power available to train powerful AI systems. While improvements in all three inputs &#x2013; compute, algorithms, and data &#x2013; from the <a href="https://cset.georgetown.edu/wp-content/uploads/CSET-AI-Triad-Report.pdf">AI triad</a> have led to AI progress over the past decade, it appears that marginal increases in compute power will be most likely and lead to large increases in capabilities. </p> <p> The quality of compute available to train AI systems dictates the number of parameters that the system can use and this directly correlates to performance. As large AI labs gain more popularity and greater access to computation power it seems likely that progress will continue at the current pace, or perhaps even faster. Two key uncertainties I have is the ability of the physical manufacturing of compute infrastructure to match the demand from AI labs and the ability of AI labs to be able to afford to access the infrastructure. If there is an insufficient supply of computational infrastructure to meet the demand from AI labs then AI progress could be hampered. It seems unlikely that AI labs won't find a way to be profitable enough to continue to be able to afford their compute given the popularity of AI and the financial upside that it promises for downstream users. </p> <p> The quality of algorithms and data seems likely to only increase and consequently lead to continued AI progress. I'm uncertain about the improvement of both of these inputs, however. Algorithms could stagnate or just take a lot of additional time to develop but progress could be improved by using current AI systems to help progress the state of the art. Access to data seems likely to only improve over time, although I'm unsure if the quality of data could decrease over time as more AI-generated data is put out onto the internet. That said, even if the development of both algorithms and data were to stagnate, increased access to AI compute seems likely to be sufficient to allow AI progress to continue. This is demonstrated by the <a href="https://sites.research.google/parti/">Parti series of image models</a> in which models were trained in the same way except for increasing the number of parameters. Increasing the parameters resulted in significantly better image generation with the same algorithms and data so it seems likely that AI progress could continue only with increased compute. </p> <p> <i><a href="/2023/08/14/AI-governance-course-explainer.html#org45001ca">Essay task disclaimer</a></i> </p> </div> </div> <div id="outline-container-org463d7cd" class="outline-2"> <h2 id="org463d7cd">Group discussion</h2> <div class="outline-text-2" id="text-org463d7cd"> <p> <b>Reflections on feedback on my essay</b> </p> <ul class="org-ul"> <li>It would be interesting to understand the strength of correlation between compute and performance to present a more nuanced take on this.</li> <li>Further research into the availability of data over time and the degree to which a less-than-optimal amount of data would slow progress would be a valuable addition.</li> <li>What sorts of AI systems can benefit from the output of previous AI systems? How much is it bad for subsequent systems?</li> </ul> <p> <b>Some things I learnt</b> </p> <ul class="org-ul"> <li>People have forecast the availability of data quality. For example <a href="https://arxiv.org/abs/2211.04325">Will we run out of data? An analysis of the limits of scaling datasets in Machine Learning</a> suggests that high-quality &#x2013; loosely meaning human-generated and quality assured &#x2013; language data will likely be exhausted before 2026. Exhaustion of the data would mean that there's not enough data to follow the optimal scaling laws (I was recommended <a href="https://arxiv.org/abs/2203.15556">this paper</a> and the chinchilla paper for learning more about scaling laws).</li> </ul> <p> <b>Other thoughts</b> </p> <ul class="org-ul"> <li>A focus of the readings for the week was the AI triad &#x2013; algorithms, data, and compute &#x2013; a concept I was familiar with from preparing for <a href="http://engineeredforimpact.show/lennart">my podcast conversation with Lennart Heim</a>. <ul class="org-ul"> <li>We discussed the geopolitical, financial, and talent constraints that may impact the AI triad. Others suggested that these things should be part of the triad but I disagreed and here is why: <ul class="org-ul"> <li>The AI triad is a model of the inputs to creating AI systems and I see these additional factors &#x2013; geopolitical relations, financial costs of compute, and the availability of talent for selecting data and writing algorithms &#x2013; as contextual considerations around the inputs to training AI systems. They are the backdrop on which AI systems are trained. They can serve to modulate the availability and quality of the inputs but aren't inputs themselves. <ul class="org-ul"> <li>I guess this makes them potential levers for governance or, at least, important things to consider when analysing the effects of governance-based interventions.</li> </ul></li> </ul></li> <li>I found this discussion valuable for building upon my mental model of the AI triad by connecting it to the real world.</li> </ul></li> <li>I found the <a href="https://medium.com/@richardcngo/visualizing-the-deep-learning-revolution-722098eb9c5">this article which visualises the quality of different sized AI models</a> a useful illustration of the impact of compute on performance.</li> <li>I like the way discussion and feedback on written thoughts can reveal things I wouldn’t have otherwise thought about, or quirks/errors in my conception of things that I would have struggled to otherwise notice. <ul class="org-ul"> <li>For example, in the course of the discussion session I quickly defined "computing power" as "the physical compute chips on which the discrete operations required to execute the algorithms are performed". Someone pointed out that this doesn't capture floating-point operations (FLOPS) which I agree is a mistake a definition including FLOPS would be a more accurate measure of compute power.</li> </ul></li> </ul> <p> <b>Further reading</b> </p> <ul class="org-ul"> <li><a href="https://www.alignmentforum.org/posts/wgio8E758y9XWsi8j/grokking-forecasting-tai-with-biological-anchors#Affordability_of_compute">On the affordability of compute</a></li> </ul> <hr /> </div> </div> <div id="outline-container-orgc255db2" class="outline-2"> <h2 id="orgc255db2">Read more</h2> <div class="outline-text-2" id="text-orgc255db2"> <p> You can <a href="/2023/08/14/AI-governance-course-explainer.html#org2bf5124">view the rest of the series here</a> or <a href="/archive.html?tag=AI-governace-course">view any other posts related to the course here</a>. </p> </div> </div>
import React, { useEffect, useState } from "react"; import { useParams } from "react-router"; import { useDispatch } from "react-redux"; import { addFavorite } from "../state/favorites"; import axios from "axios"; const MediaItem = () => { const { type, id } = useParams(); const [item, setItem] = useState({}); const dispatch = useDispatch(); useEffect(() => { axios .get(`/api/${type}/${id}`) .then((res) => res.data) .then((media) => setItem(media)); }, [type, id]); return ( <div className="columns"> <div className="column is-one-third is-centered"> <div className="block"> <figure className="image"> <img src={`https://image.tmdb.org/t/p/w300_and_h450_bestv2${item.poster_path}`} alt={item.title || item.name} /> </figure> </div> <div className="tags"> {item.genres ? item.genres.map((genre, i) => ( <span key={i} className="tag is-info"> {genre.name} </span> )) : ""} </div> </div> <div className="column"> <div className="block"> <h1 className="title has-text-weight-bold mb-1"> {item.title || item.name} </h1> <p className="help">{item.release_date || item.first_air_date}</p> </div> {item.tagline ? ( <div className="block notification p-2"> <blockquote className="is-family-code has-text-grey has-text-centered is-italic has-text-weight-medium"> {`<< ${item.tagline} >>`} </blockquote> </div> ) : ( "" )} <div className="block"> <h2 className="title is-size-4 mb-2">Overview</h2> <p>{item.overview}</p> </div> {item.networks ? ( <div className="block"> <figure> <img className="logo" height="32" width="auto" src={`https://image.tmdb.org/t/p/original${item.networks[0].logo_path}`} alt={item.networks[0].name} /> </figure> </div> ) : ( "" )} {item.imdb_id ? ( <div className="block"> <a href={`https://www.imdb.com/title/${item.imdb_id}`}> <button className=" button has-text-weight-bold is-warning has-text-black"> <span className="icon-text"> <span className="icon"> <i className="fab fa-2x fa-imdb"></i> </span> <span className="ml-2">Rating and rewies</span> </span> </button> </a> </div> ) : ( "" )} {item.homepage ? ( <div className="block"> <p> <span className="has-text-grey has-text-weight-medium"> Official site:{" "} </span> <a href={item.homepage}>{item.homepage}</a> </p> </div> ) : ( "" )} <div className="block"> <button className="button is-white has-text-info" onClick={() => dispatch(addFavorite({ type, item }))} > <span className="icon has-text-love has-text-info"> <i className="fas fa-heart"></i> </span> <span>Add to Favorites</span> </button> </div> </div> </div> ); }; export default MediaItem;
// @ts-nocheck "use client"; import contractAddresses from "../../constants/networkMappings.json"; import ERC20_ABI from "../../constants/ERC20_ABI.json"; import FACTORY_ABI from "../../constants/FACTORY_ABI.json"; import { useNetwork, useAccount, useContractReads } from "wagmi"; import { Error } from "@/components/error"; import { useEffect, useState } from "react"; import { Spinner } from "@/components/spinner"; import Image from "next/image"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { BadgeDollarSign, Check, Copy, Forward, Globe, HeartHandshake, PlusCircle, Send, } from "lucide-react"; import { Popover, PopoverTrigger, PopoverContent, } from "@/components/ui/popover"; import { IssueTokens } from "./[token-actions]/_components/issue-tokens"; import { RedeemTokens } from "./[token-actions]/_components/redeem-tokens"; import { ClaimFee } from "./[token-actions]/_components/claim-fee"; const Tokens = function () { const { chain } = useNetwork(); const { address } = useAccount(); const chainId = (chain?.id?.toString() as string) || ("" as string); const [isLoaded, setIsLoaded] = useState(false); const TokenFactoryAddress = chainId in contractAddresses ? contractAddresses[chainId as keyof typeof contractAddresses][ "TokenFactory" ][ contractAddresses[chainId as keyof typeof contractAddresses][ "TokenFactory" ].length - 1 ] : null; useEffect(() => { setIsLoaded(true); }, []); const [tokens, setTokens] = useState<any[]>([]); const [tokenNames, setTokenNames] = useState<any[]>([]); const [tokenSymbols, setTokenSymbols] = useState<any[]>([]); const [copied, setCopied] = useState(false); const [showIssueTokenModal, setShowIssueTokenModal] = useState<boolean>(false); const TokenFactoryContract: any = { address: TokenFactoryAddress, abi: FACTORY_ABI, }; const { data, isFetching, isLoading, isSuccess, refetch } = useContractReads({ contracts: [ { ...TokenFactoryContract, functionName: "getAllNames", args: [address], }, { ...TokenFactoryContract, functionName: "getAllSymbols", args: [address], }, { ...TokenFactoryContract, functionName: "getAllTokenAddresses", args: [address], }, ], }); async function getUserIndexTokens() { refetch(); if (data !== undefined) { setTokenNames(data[0].result); setTokenSymbols(data[1].result); setTokens(data[2].result); } } useEffect(() => { getUserIndexTokens(); }, [address]); // console.log(data); if (!isLoaded) { return ( <div className="min-h-screen min-w-full mx-auto absolute top-[50%] left-[50%]"> <Spinner size={"lg"} /> </div> ); } const onCopy = (data: string) => { navigator.clipboard.writeText(data); setCopied(true); toast.success("Token address copied to clipboard!"); setTimeout(() => { setCopied(false); }, 1000); }; if (isLoaded) { return ( <> {chainId === undefined || !(chainId in contractAddresses) || !TokenFactoryAddress ? ( <Error /> ) : ( <> <div className="tokens-container lg:w-[60%] justify-between md:w-[70%] sm:w-[80%] lg:grid lg:grid-cols-3 gap-4 md:grid md:grid-cols-2 flex flex-col mx-auto px-5 py-10"> {tokenNames.length > 0 && tokenNames.map((_, index) => { if (isFetching) { return ( <div className="w-[12em] max-w-[15em] h-[30vh]" key={index} > <div className="flex items-center justify-center w-[100%] h-[100%] bg-white border border-white rounded-lg shadow dark:bg-gray-800 dark:border-orange-400"> <Spinner size={"lg"} /> </div> </div> ); } return ( <div className="max-w-[15em] bg-gray-100 border-2 border-white rounded-lg shadow dark:bg-gray-800 dark:border-orange-400" key={index} > <Image className="rounded-t-lg object-fill p-2 w-[100%] bg-gradient-to-br from-orange-100 to-orange-400 dark:bg-gradient-to-br dark:from-slate-700 dark:to-slate-900 dark:border dark:border-b-slate-400" src="/png/token-holder.png" alt="Polygon" height={100} width={100} /> <div className="p-5"> <div className="token-info flex justify-between items-center flex-wrap"> <h5 className="truncate mb-2 lg:text-2xl md:text-xl block text-base w-[100%] font-bold tracking-widest break-words text-gray-900 dark:text-white" title={`Index Token Name : ${tokenNames[index]}`} > {tokenNames[index]} </h5> <span className=" lg:pr-10 sm:pr-3 md:pr-5"> <h5 className="text-base text-muted-foreground/70 dark:text-muted-foreground/90" title="Index Token Symbol" > <span className="flex items-center "> {tokenSymbols[index]} <Popover> <PopoverTrigger asChild> <Button size="icon" variant={"ghost"} className="bg-transparent hover:bg-transparent" > <Forward className="h-5 w-5 text-blue-400 dark:text-orange-400 cursor-pointer ml-2" /> </Button> </PopoverTrigger> <PopoverContent className="w-72" align="end" alignOffset={8} forceMount > <div className="space-y-4"> <div className="flex justify-between items-center gap-x-2"> <Globe className=" text-sky-500 animate-pulse h-8 w-8" /> <p className="text-xs font-medium text-sky-500"> Share this token address with your friends to allow them to issue one for themselves </p> </div> <div className="flex items-center"> <input value={tokens[index]} className="flex-1 px-2 text-xs border rounded-l-md h-8 bg-muted truncate" disabled /> <Button onClick={() => { onCopy(tokens[index]); }} disabled={copied} className="h-8 rounded-l-none" > {copied ? ( <Check className="h-4 w-4" /> ) : ( <Copy className="h-4 w-4" /> )} </Button> </div> </div> </PopoverContent> </Popover> </span> </h5> </span> </div> <p className="group:invisble mb-3 font-normal truncate cursor-copy" title={tokens[index]} onClick={() => { navigator.clipboard.writeText(`${tokens[index]}`); toast.info( "Index Token address copied to clipboard" ); }} > {tokens[index]} </p> <div className="actions-container flex flex-col py-3 px-2"> <div className="my-2 w-[100%]"> <IssueTokens defaultTokenAddress={tokens[index]} ></IssueTokens> </div> <div className="my-2 w-[100%]"> <RedeemTokens defaultTokenAddress={tokens[index]} /> </div> <div className="my-2 w-[100%]"> <ClaimFee defaultTokenAddress={tokens[index]} /> </div> </div> </div> </div> ); })} </div> {!(tokenNames.length > 0) && ( <div className="empty-container"> <div className="title w-[80%] sm:w-[80%] lg:w-[40%] md:w-[60%] mx-auto mb-5 my-2 px-10 py-1 bg-blue-100 border-t border-b border-violet-700 text-violet-900 dark:border-blue-950 dark:text-blue-950 "> <p className="tracking-widest text-center mb-2 font-mono text-3xl font-semibold"> You haven&apos;t created any Index of your own. </p> <p className="text-justify font-mono text-xl"> If you want to interact with token created by someone else, use their address to issue or redeem a token. </p> </div> <div className="actions-container w-[80%] sm:w-[80%] lg:w-[40%] md:w-[60%] flex flex-col lg:flex-row items-center justify-between mx-auto py-3 px-2"> <div className="my-2 lg:my-0 w-[80%] md:w-[40%] lg:w-[25%]"> <IssueTokens defaultTokenAddress={""}></IssueTokens> </div> <div className="my-2 lg:my-0 w-[80%] md:w-[40%] lg:w-[25%]"> <RedeemTokens defaultTokenAddress={""} /> </div> </div> </div> )} </> )} </> ); } }; export default Tokens;
#include <Arduino.h> #include <U8g2lib.h> #include <Encoder.h> #include <AD9833.h> #include <SPI.h> #include <TimerOne.h> #include "util/delay.h" #include <EEPROM.h> // peripheria #define DC_RELAY_PIN 6 // high level to short the DC blocking capacitor #define MCP_CS_PIN 8 // low level to enable the MCP41010 // screen #define NOKIA_CLK_PIN 17 #define NOKIA_DATA_PIN 16 #define NOKIA_CS_PIN 14 #define NOKIA_DC_PIN 15 #define NOKIA_RESET_PIN 7 U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2( U8G2_R0, NOKIA_CLK_PIN, NOKIA_DATA_PIN, NOKIA_CS_PIN, NOKIA_DC_PIN, NOKIA_RESET_PIN ); // encoder #define ENC_LEFT_PIN 3 #define ENC_RIGHT_PIN 4 #define ENC_BUTTON_PIN 2 Encoder enc( ENC_LEFT_PIN, ENC_RIGHT_PIN ); long oldEncoderPosition; long newEncoderPosition; // generator #define DDS_FSYNC 9 #define CRYSTAL_CLOCK 25000000UL #define ACTIVE_REGISTER REG0 AD9833 gen( DDS_FSYNC, CRYSTAL_CLOCK ); // settings #define FREQ_EDITOR_MAX 12500000UL #define FREQ_EDITOR_MIN 0UL #define FREQ_EDITOR_WIDTH 11 #define FREQ_EDITOR_FRACT 2 #define AMP_EDITOR_MAX 100UL #define AMP_EDITOR_MIN 0UL #define AMP_EDITOR_WIDTH 5 #define AMP_EDITOR_FRACT 1 #define LONG_PRESS_DURATION 20 #define SHORT_PRESS_DURATION 2 char outputEnabled; char removeDcOffset; double frequency; double amplification; WaveformType waveform; typedef enum { NO_EDIT, ENABLED_EDIT, WAVEFORM_EDIT, REMOVEDC_EDIT, FREQ_EDIT, FREQ_SYM_EDIT, AMP_EDIT, AMP_SYM_EDIT, SAVE_EDIT } EditState; EditState state = NO_EDIT; uint8_t frequencyEditChar, ampEditChar; uint8_t scheduleScreenUpdate; double freqCharMultiplier(uint8_t n) { double multiplierLut[ FREQ_EDITOR_WIDTH + 1 ] = { 0, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, 0, 0.1, 0.01 }; if (n > FREQ_EDITOR_WIDTH) return 0; else return multiplierLut[n]; } double ampCharMultiplier(uint8_t n) { double multiplierLut[ AMP_EDITOR_WIDTH + 1 ] = { 0, 100, 10, 1, 0, 0.1 }; if ( n > AMP_EDITOR_WIDTH ) return 0; else return multiplierLut[n]; } void setup(void) { pinMode( ENC_BUTTON_PIN, INPUT); attachInterrupt( digitalPinToInterrupt(ENC_BUTTON_PIN), pushed, FALLING ); Timer1.initialize(250000); Timer1.attachInterrupt(timerInterrupt); pinMode( DC_RELAY_PIN, OUTPUT ); digitalWrite( DC_RELAY_PIN, LOW ); pinMode( MCP_CS_PIN, OUTPUT ); digitalWrite( MCP_CS_PIN, HIGH ); oldEncoderPosition = 0; gen.Begin(); gen.EnableOutput(false); gen.SetOutputSource(ACTIVE_REGISTER); u8g2.begin(); restoreSettings(); } void loop(void) { } void timerInterrupt(void) { if ( state != NO_EDIT ) { newEncoderPosition = enc.read(); if ( newEncoderPosition != oldEncoderPosition ) { char clockwise = newEncoderPosition > oldEncoderPosition; switch(state) { case NO_EDIT: break; case ENABLED_EDIT: outputEnabled = !outputEnabled; updateOutput(); break; case FREQ_EDIT: break; case FREQ_SYM_EDIT: frequency = frequency + (clockwise ? 1 : -1) * freqCharMultiplier(frequencyEditChar); updateFrequency(); break; case WAVEFORM_EDIT: switch(waveform) { case SINE_WAVE: waveform = clockwise ? TRIANGLE_WAVE : HALF_SQUARE_WAVE; break; case TRIANGLE_WAVE: waveform = clockwise ? SQUARE_WAVE : SINE_WAVE; break; case SQUARE_WAVE: waveform = clockwise ? HALF_SQUARE_WAVE : TRIANGLE_WAVE; break; case HALF_SQUARE_WAVE: waveform = clockwise ? SINE_WAVE : SQUARE_WAVE; break; default: waveform = SINE_WAVE; } updateWaveform(); removeDcOffset = ( ( waveform == SQUARE_WAVE ) || ( waveform == HALF_SQUARE_WAVE ) ) ? 0 : 1; updateDcOffsetRemoval(); break; case REMOVEDC_EDIT: removeDcOffset = !removeDcOffset; updateDcOffsetRemoval(); break; case AMP_EDIT: break; case AMP_SYM_EDIT: amplification = amplification + (clockwise ? 1 : -1) * ampCharMultiplier(ampEditChar); updateAmplification(); break; case SAVE_EDIT: break; } oldEncoderPosition = newEncoderPosition; } } if (scheduleScreenUpdate) { redrawScreen(); scheduleScreenUpdate = 0; } } void pushed(void) { char longPress = 0, shortPress = 0; uint8_t counter = 0; while ( !digitalRead(ENC_BUTTON_PIN) ) { if ( !shortPress ) { if ( counter >= SHORT_PRESS_DURATION ) { shortPress = 1; } } else { if ( counter >= LONG_PRESS_DURATION ) { longPress = 1; break; } } counter++; _delay_ms(50); } if ( !shortPress ) { return; } switch(state) { case NO_EDIT: state = ENABLED_EDIT; break; case ENABLED_EDIT: state = FREQ_EDIT; break; case FREQ_EDIT: if (longPress) { frequencyEditChar = FREQ_EDITOR_WIDTH; state = FREQ_SYM_EDIT; } else { state = WAVEFORM_EDIT; }; break; case FREQ_SYM_EDIT: if (longPress) { state = FREQ_EDIT; } else { if ( frequencyEditChar == FREQ_EDITOR_WIDTH - FREQ_EDITOR_FRACT + 1 ) { // check the dot frequencyEditChar = frequencyEditChar - 2; } else { if ( frequencyEditChar > 1 ) { frequencyEditChar--; } else { frequencyEditChar = FREQ_EDITOR_WIDTH; } } state = FREQ_SYM_EDIT; }; break; case WAVEFORM_EDIT: state = REMOVEDC_EDIT; break; case REMOVEDC_EDIT: state = AMP_EDIT; break; case AMP_EDIT: if (longPress) { ampEditChar = AMP_EDITOR_WIDTH; state = AMP_SYM_EDIT; } else { state = SAVE_EDIT; }; break; case AMP_SYM_EDIT: if (longPress) { state = AMP_EDIT; } else { if ( ampEditChar == AMP_EDITOR_WIDTH - AMP_EDITOR_FRACT + 1 ) { // check the dot ampEditChar = ampEditChar - 2; } else { if ( ampEditChar > 1 ) { ampEditChar--; } else { ampEditChar = AMP_EDITOR_WIDTH; } } state = AMP_SYM_EDIT; }; break; case SAVE_EDIT: if (longPress) { saveSettings(); state = NO_EDIT; } else { state = NO_EDIT; }; break; } scheduleScreenUpdate = 1; } void redrawScreen() { char str_buff[20], data_buff[12]; u8g2.firstPage(); do { u8g2.setFont(u8g2_font_micro_mr); // output enable status sprintf( str_buff, "Output enabled: %s", outputEnabled ? "YES" : "NO" ); u8g2.setDrawColor( state == ENABLED_EDIT ? 0 : 1 ); u8g2.drawStr( 0, 5, str_buff ); // actual frequency float actualFrequency = gen.GetActualProgrammedFrequency(REG0); dtostrf( actualFrequency, FREQ_EDITOR_WIDTH, FREQ_EDITOR_FRACT, data_buff ); sprintf( str_buff, "Freq.: %s Hz", data_buff ); u8g2.setDrawColor( state == FREQ_EDIT ? 0 : 1 ); u8g2.drawStr( 0, 13, str_buff ); if ( state == FREQ_SYM_EDIT ) { u8g2.drawBox( 23 + 4 * frequencyEditChar, 14, 5, 1 ); } // waveform switch(waveform) { case SINE_WAVE: strncpy( data_buff, "SINE", 10 ); break; case TRIANGLE_WAVE: strncpy( data_buff, "TRIANGLE", 10 ); break; case SQUARE_WAVE: strncpy( data_buff, "SQUARE", 10 ); break; case HALF_SQUARE_WAVE: strncpy( data_buff, "SQUARE/2", 10 ); break; } sprintf( str_buff, "Waveform: %s", data_buff ); u8g2.setDrawColor( state == WAVEFORM_EDIT ? 0 : 1 ); u8g2.drawStr( 0, 21, str_buff ); // dc offset removal status sprintf( str_buff, "Remove DC offset: %s", removeDcOffset ? "YES" : "NO" ); u8g2.setDrawColor( state == REMOVEDC_EDIT ? 0 : 1 ); u8g2.drawStr( 0, 29, str_buff ); // amplification dtostrf( amplification, AMP_EDITOR_WIDTH, AMP_EDITOR_FRACT, data_buff ); sprintf( str_buff, "Amplifier: %s %%", data_buff ); u8g2.setDrawColor( state == AMP_EDIT ? 0 : 1 ); u8g2.drawStr( 0, 37, str_buff ); if ( state == AMP_SYM_EDIT ) { u8g2.drawBox( 39 + 4 * ampEditChar, 38, 5, 1 ); } // save settings u8g2.setDrawColor( state == SAVE_EDIT ? 0 : 1 ); u8g2.drawStr( 0, 45, "Save settings" ); } while ( u8g2.nextPage() ); } void updateDcOffsetRemoval() { digitalWrite( DC_RELAY_PIN, !removeDcOffset ); scheduleScreenUpdate = 1; } void updateWaveform() { switch(waveform) { case SINE_WAVE: break; case TRIANGLE_WAVE: break; case SQUARE_WAVE: break; case HALF_SQUARE_WAVE: break; default: waveform = SINE_WAVE; } gen.SetWaveform( ACTIVE_REGISTER, waveform ); scheduleScreenUpdate = 1; } void updateFrequency() { if ( frequency > FREQ_EDITOR_MAX) { frequency = FREQ_EDITOR_MAX; } else if ( frequency < FREQ_EDITOR_MIN) { frequency = FREQ_EDITOR_MIN; } gen.SetFrequency( ACTIVE_REGISTER, frequency ); scheduleScreenUpdate = 1; } void updateOutput() { gen.EnableOutput(outputEnabled); scheduleScreenUpdate = 1; } void updateAmplification() { if ( amplification > AMP_EDITOR_MAX) { amplification = AMP_EDITOR_MAX; } else if (amplification < AMP_EDITOR_MIN) { amplification = AMP_EDITOR_MIN; } SPI.beginTransaction( SPISettings( 4000000, MSBFIRST, SPI_MODE0 ) ); digitalWrite( MCP_CS_PIN, LOW ); SPI.transfer( B00010001 ); SPI.transfer( (uint8_t)( 2.55 * amplification ) ); digitalWrite( MCP_CS_PIN, HIGH ); SPI.endTransaction(); scheduleScreenUpdate = 1; } void saveSettings() { int eeAddress = 0; EEPROM.put( eeAddress, frequency ); eeAddress += sizeof frequency; EEPROM.put( eeAddress, waveform ); eeAddress += sizeof waveform; EEPROM.put( eeAddress, removeDcOffset ); eeAddress += sizeof removeDcOffset; EEPROM.put( eeAddress, outputEnabled ); eeAddress += sizeof outputEnabled; EEPROM.put( eeAddress, amplification ); } void restoreSettings() { int eeAddress = 0; EEPROM.get( eeAddress, frequency ); updateFrequency(); eeAddress += sizeof frequency; EEPROM.get( eeAddress, waveform ); updateWaveform(); eeAddress += sizeof waveform; EEPROM.get( eeAddress, removeDcOffset ); updateDcOffsetRemoval(); eeAddress += sizeof removeDcOffset; EEPROM.get( eeAddress, outputEnabled ); updateOutput(); eeAddress += sizeof outputEnabled; EEPROM.get( eeAddress, amplification ); updateAmplification(); }
#include "assert.h" #include "polygon.h" #include "scene.h" #include "sdl_wrapper.h" #include "state.h" #include <math.h> #include <stdio.h> #include <stdlib.h> // color and window constants const rgb_color_t STAR_COLOR = {0.0, 1.0, 0.0}; const vector_t WINDOW_SIZE = (vector_t){.x = 1000, .y = 500}; const double OUTER_RADIUS = 50; const double INNER_RADIUS = OUTER_RADIUS / M_E; const size_t NUM_POINTS = 5; const vector_t INIT_STAR_CENTER = (vector_t){.x = 500, .y = 250}; const vector_t INIT_VELOCITY = (vector_t){.x = -150, .y = 120}; const double ANGULAR_VELOCITY = M_PI / 2; const double MASS = 6.9; typedef struct state { scene_t *scene; } state_t; /** * Creates a star-shaped polygon * Returns a polygon stored as a vec_list_t* */ list_t *create_star(size_t outer_radius, size_t inner_radius, size_t num_points, size_t center_x, size_t center_y) { double curr_angle; double x_outer; double y_outer; double x_inner; double y_inner; list_t *vertices = list_init(num_points * 2, free); for (size_t i = 0; i < num_points; i++) { curr_angle = 2 * M_PI * i / num_points; // Creates the vertices of the outer vertices of the star x_outer = cos(curr_angle) * outer_radius + center_x; y_outer = sin(curr_angle) * outer_radius + center_y; vector_t *out_rad_vec_ptr = malloc(sizeof(vector_t)); out_rad_vec_ptr->x = x_outer; out_rad_vec_ptr->y = y_outer; list_add(vertices, out_rad_vec_ptr); // Creates the vertices of the inner vertices of the star x_inner = cos(curr_angle + M_PI / num_points) * inner_radius + center_x; y_inner = sin(curr_angle + M_PI / num_points) * inner_radius + center_y; vector_t *in_rad_vec_ptr = malloc(sizeof(vector_t)); in_rad_vec_ptr->x = x_inner; in_rad_vec_ptr->y = y_inner; list_add(vertices, in_rad_vec_ptr); } return vertices; }; state_t *emscripten_init() { sdl_init(VEC_ZERO, WINDOW_SIZE); state_t *init_state = malloc(sizeof(state_t)); assert(init_state != NULL); init_state->scene = scene_init(); body_t *star = body_init(create_star(OUTER_RADIUS, INNER_RADIUS, NUM_POINTS, INIT_STAR_CENTER.x, INIT_STAR_CENTER.y), MASS, STAR_COLOR); scene_add_body(init_state->scene, star); body_set_velocity(scene_get_body(init_state->scene, 0), INIT_VELOCITY); body_set_ang_velocity(scene_get_body(init_state->scene, 0), ANGULAR_VELOCITY); return init_state; } /** * Checks if the star touches one of the boundaries. * Returns which boundary it touches if it does. * * @param state the state of the polygon * * Returns pointer to 2 boolean array; * position 0: True if we need to invert x component of velocity * position 1: True if we need to invert y component of velocity */ bool *star_on_window(state_t *state, double dt) { body_t *star = scene_get_body(state->scene, 0); double dx = body_get_velocity(star).x * dt; double dy = body_get_velocity(star).y * dt; bool *ans = malloc(sizeof(bool) * 2); ans[0] = false; ans[1] = false; size_t number_of_vertices = list_size(body_get_shape(star)); for (size_t v = 0; v < number_of_vertices; v++) { vector_t *my_vector = list_get(body_get_shape(star), v); if (WINDOW_SIZE.x < my_vector->x + dx) { ans[0] = true; } if (WINDOW_SIZE.y < my_vector->y + dy) { ans[1] = true; } if (my_vector->x + dx < 0) { ans[0] = true; } if (my_vector->y + dy < 0) { ans[1] = true; } } return ans; } /** * Updates the state of the polygon for given amount of time. * Translates and rotates the polygon, and also computes elastic collisions. * Note: mutates the original state. * * @param state the old state of the polygon * @param dt the time interval for which the movement is computed */ void update_scene(state_t *state, vector_t velocity, double dt) { body_t *star = scene_get_body(state->scene, 0); vector_t vel = body_get_velocity(star); bool *reflects = star_on_window(state, dt); // Elastic Collision if (reflects[0]) { vector_t new_vel = {-vel.x, vel.y}; body_set_velocity(star, new_vel); } if (reflects[1]) { vector_t new_vel = {vel.x, -vel.y}; body_set_velocity(star, new_vel); } body_update(star, dt); }; void emscripten_main(state_t *state) { sdl_clear(); body_t *star = scene_get_body(state->scene, 0); double dt = time_since_last_tick(); update_scene(state, body_get_velocity(star), dt); sdl_draw_polygon(body_get_shape(star), STAR_COLOR); sdl_show(); } void emscripten_free(state_t *state) { scene_free(state->scene); free(state); }
# make deterministic time dependent features import pandas as pd import polars as pl import numpy as np from statsmodels.tsa.deterministic import CalendarFourier, DeterministicProcess def make_date_process(train): dates = pd.date_range(train['prediction_datetime'].dt.date().min(), train['prediction_datetime'].dt.date().max()) fourier = CalendarFourier(freq="A", order=6) date_process = DeterministicProcess( dates, constant=True, order=1, seasonal=True, period=7, additional_terms=[fourier], drop=True ) return date_process def make_regression_features(train, clients, date_process): """ input features for the regression""" features = train.drop('target').join( clients, left_on=['county', 'is_business', 'product_type', 'date_when_predicting'], right_on=['county', 'is_business', 'product_type', 'date'], how='inner' ) # add date and time features features = features.with_columns( pl.col('prediction_datetime').dt.date().alias('prediction_date'), pl.col('prediction_datetime').dt.time().alias('prediction_time') ) # features from the date process date_features = date_process.range( features['prediction_date'].min(), features['prediction_date'].max() ).reset_index() date_features = pl.from_pandas(date_features).with_columns(pl.col('index').dt.date()) features = features.join(date_features, left_on=['prediction_date'], right_on=['index'], how='left') # time features: # to add: local holidays features = features.to_dummies('prediction_time') features = features.drop('prediction_time_10:00:00') # Other covariates features = features.with_columns(np.log1p(pl.col('installed_capacity'))) # some of these features should be included in the future columns_to_drop = ['eic_count', 'county', 'is_business', 'product_type', 'data_block_id', 'data_block_id_right', 'prediction_date', 'prediction_datetime', 'date_when_predicting' ] features = features.drop(columns_to_drop) return features def make_time_features(train, clients, date_process): """ input features for the time dependence regressions""" features = train.drop('target').join( clients, left_on=['county', 'is_business', 'product_type', 'date_when_predicting'], right_on=['county', 'is_business', 'product_type', 'date'], how='inner' ) # add date and time features features = features.with_columns( pl.col('prediction_datetime').dt.date().alias('prediction_date'), pl.col('prediction_datetime').dt.time().alias('prediction_time') ) # features from the date process date_features = date_process.range( features['prediction_date'].min(), features['prediction_date'].max() ).reset_index() date_features = pl.from_pandas(date_features).with_columns(pl.col('index').dt.date()) features = features.join(date_features, left_on=['prediction_date'], right_on=['index'], how='left') # time features: # to add: local holidays features = features.to_dummies('prediction_time') features = features.drop('prediction_time_10:00:00') # some of these features should be included in the future columns_to_drop = ['eic_count', 'installed_capacity', 'data_block_id', 'data_block_id_right', 'prediction_date', 'prediction_datetime', 'date_when_predicting' ] features = features.drop(columns_to_drop) return features