text
stringlengths
184
4.48M
package id.hangga import Const import kotlinx.coroutines.* import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.* import kotlin.system.measureTimeMillis fun performSingleFileOperation(): Long { return measureTimeMillis { runBlocking(Dispatchers.Default) { val job = async { // Simulasi latensi operasi file dengan penulisan ke file val filePath = Path.of("example.txt") Files.write( filePath, Const.LOREM_IPSUM.toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.APPEND ) ////println("File operation completed by coroutine") } job.await() } } } // Kotlin menggunakan Coroutine suspend fun performDataProcessingKotlin(): Long { val startTime = System.currentTimeMillis() val dataList = listOf("dummy_data1", "dummy_data2", "dummy_data3", "dummy_data4", "dummy_data5") coroutineScope { val jobs = dataList.map { data -> async { // Simulasi pemrosesan data val result = data.replace("_data", "-").uppercase(Locale.getDefault()) //println("Coroutine : Data processed: $result") } } jobs.awaitAll() } val endTime = System.currentTimeMillis() return endTime - startTime } suspend fun makeHttpRequestAsync(): Long = withContext(Dispatchers.IO) { val uri = URI.create(Const.DUMMY_API) val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder(uri).build() return@withContext try { var responseString: String measureTimeMillis { val response = client.send(request, HttpResponse.BodyHandlers.ofString()) responseString = response.body() // Do something with the response if needed } } catch (e: Exception) { e.printStackTrace() 0L } finally { // Tidak perlu menutup HttpClient di sini, karena HttpClient.newHttpClient() tidak membuat sumber daya yang perlu ditutup secara manual. } } /*suspend fun makeHttpRequestAsync(): Pair<String, Long> = withContext(Dispatchers.IO) { val uri = URI.create(Const.DUMMY_API) val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder(uri).build() return@withContext try { var responseString: String val executionTime = measureTimeMillis { val response = client.send(request, HttpResponse.BodyHandlers.ofString()) responseString = response.body() ////println("Request completed in ${executionTime}ms") } Pair(responseString, executionTime) } catch (e: Exception) { e.printStackTrace() Pair("", 0L) } finally { // Tidak perlu menutup HttpClient di sini, karena HttpClient.newHttpClient() tidak membuat sumber daya yang perlu ditutup secara manual. } }*/
import * as React from 'react'; import Popover from '@mui/material/Popover'; import Typography from '@mui/material/Typography'; import Button from '@mui/material/Button'; import {HitContext} from './context/hitState' import {useContext} from 'react'; export default function HitPopover({hit, setHit}){ const handleClick = (event) => { setHit(event.currentTarget); }; const handleClose = () => { setHit(null); }; const open = Boolean(hit); const id = open ? 'simple-popover' : undefined; return ( <div> <Button aria-describedby={id} variant="contained" onClick={handleClick}> Open Popover </Button> <Popover id={id} open={open} anchorEl={hit} onClose={handleClose} anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} > <Typography sx={{ p: 2 }}>Hit!</Typography> </Popover> </div> ); }
from decimal import Decimal from typing import List from spotipy import Spotify from wombeats.api_models import SpotipyTrackItem, SpotipyPlaylist from wombeats.models import SearchQuery, SearchResult import logging logger = logging.getLogger(__name__) class SpotifyAPIAccess: @classmethod def build(cls, client: Spotify): return cls(client) def __init__(self, client: Spotify): self.client = client def search(self, query: SearchQuery, pagination: int = 50) -> List[SearchResult]: if query.genre: filtered_playlists = self.filter_current_playlists_by_name(query.genre) all_search_results = [] for playlist in filtered_playlists: playlist_tracks = self._get_tracks_from_playlist(playlist.id) all_search_results.extend( self.filter_track_items_by_query(playlist_tracks, query)) return all_search_results else: query_str = query.query_str results = self.client.search(q=query_str, limit=pagination) all_spotipy_track_items: List[SpotipyTrackItem] = [] for track in results['tracks']['items']: track_item = SpotipyTrackItem(**track) all_spotipy_track_items.append(track_item) search_results = self.filter_track_items_by_query(all_spotipy_track_items, query) return search_results def pre_filter_tracks_by_search_query(self, track_items: List[SpotipyTrackItem], query: SearchQuery) -> List[SpotipyTrackItem]: if not query.artist and not query.album and not query.track and not query.year: return track_items filtered_artist_items = [track_item for track_item in track_items if (query.artist and query.artist == track_item.artists[0].name)] final_track_items = self.validate_filtered_items(filtered_artist_items, track_items) filtered_album_items = [track_item for track_item in final_track_items if (query.album and query.album == track_item.album.name)] final_track_items = self.validate_filtered_items(filtered_album_items, final_track_items) filtered_track_items = [track_item for track_item in final_track_items if (query.track and query.track == track_item.name)] final_track_items = self.validate_filtered_items(filtered_track_items, final_track_items) filtered_year_items = [track_item for track_item in final_track_items if (query.year and int(query.year) == track_item.album.release_date.year)] final_track_items = self.validate_filtered_items(filtered_year_items, final_track_items) return final_track_items @staticmethod def validate_filtered_items(filtered_items: List[SpotipyTrackItem], orig_track_items: List[SpotipyTrackItem] ): return filtered_items if len(filtered_items) > 0 else orig_track_items def filter_track_items_by_query(self, track_items: List[SpotipyTrackItem], query: SearchQuery): search_results: List[SearchResult] = [] pre_filtered_track_items = self.pre_filter_tracks_by_search_query(track_items, query) for track_item in pre_filtered_track_items: features = self.client.audio_features(track_item.uri) if not features or not features[0]: continue bpm_decimal = Decimal(features[0]["tempo"]) if query.from_bpm <= bpm_decimal <= query.to_bpm: search_result = SearchResult( artist=track_item.artists[0].name, album= track_item.album.name, track=track_item.name, track_uri=str(track_item.uri), release_date=str(track_item.album.release_date), bpm=str(int(bpm_decimal)), external_url=str(track_item.external_urls.spotify) ) search_results.append(search_result) return search_results def get_current_playlists(self, offset: int = 0) -> List[SpotipyPlaylist]: logger.info("Getting current user playlists") playlists = self.client.current_user_playlists(offset=offset) all_playlists = playlists["items"] logger.info(f"Done getting current user playlists: size: {len(all_playlists)}") spotipy_playlists: List[SpotipyPlaylist] = [] for item in all_playlists: spotipy_playlist = SpotipyPlaylist(**item) spotipy_playlists.append(spotipy_playlist) return spotipy_playlists def filter_current_playlists_by_name(self, name:str) -> List[SpotipyPlaylist]: offset = 0 all_playlists = [] while offset < 200: all_playlists.extend(self.get_current_playlists(offset=offset)) offset = offset + 49 return [playlist for playlist in all_playlists if name == playlist.name] def _get_tracks_from_playlist(self, playlist_id:str) -> List[SpotipyTrackItem] : results = self.client.playlist(playlist_id, fields="tracks,next") list_of_tracks: List[SpotipyTrackItem] = [] results_tracks = results["tracks"] for item in results_tracks["items"]: track = item["track"] track_item = SpotipyTrackItem(**track) list_of_tracks.append(track_item) return list_of_tracks def filter_playlist_tracks(self, playlist_id:str, query: SearchQuery) -> List[SearchResult]: playlist_tracks = self._get_tracks_from_playlist(playlist_id) return self.filter_track_items_by_query(playlist_tracks, query=query) def filter_new_music_friday_playlist(self, query: SearchQuery) -> List[SearchResult]: playlist_tracks = self._get_tracks_from_playlist("6ev6yxufHeDvitWMugIwXy") return self.filter_track_items_by_query(playlist_tracks, query=query)
import React from "react"; import ReactDOM from "react-dom/client"; import { extendTheme, ChakraProvider, ColorModeScript } from "@chakra-ui/react"; import { mode } from "@chakra-ui/theme-tools"; // Import mode function from Chakra UI import App from "./App.jsx"; import "./index.css"; import { BrowserRouter } from "react-router-dom"; const styles = { global: (props) => ({ body: { color: mode("#616161", "#1e1e1e")(props), bg: mode("#101010", "#000000")(props), }, }), }; const config = { initialColorMode: "dark", useSystemColorMode: true, }; const colors = { gray: { light: "#616161", dark: "#1e1e1e", }, }; const theme = extendTheme({ config, styles, colors }); ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <BrowserRouter> <ChakraProvider theme={theme}> <ColorModeScript initialColorMode={theme.config.initialColorMode} /> <App /> </ChakraProvider> </BrowserRouter> </React.StrictMode> );
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <ui:composition template="../template/templateInicio.xhtml"> <ui:define name="content"> <p:ajaxStatus onstart="PF('statusDialog').show();" onsuccess="PF('statusDialog').hide();"/> <p:dialog modal="true" widgetVar="statusDialog" header="Cargando" draggable="false" closable="false"> <p:graphicImage value="../../images/ajax-loader.gif" /> </p:dialog> <style type="text/css"> .ui-panel-title, .ui-panel-titlebar { background-color: #2264B1; color: #FFFFFF } </style> <h:form id="frmBucarPersona"> <p:growl showDetail="true" id="growl" /> <h:panelGrid columns="1" style="height: 370px;"> <p:panel id="pnlPersona" style="height: 370px;width: 700px;" > <f:facet name="header"> <p:outputLabel value="DATOS GENERALES"/> </f:facet> <h:panelGrid id="pnlGridBuscarPersona" columns="2" > <h:outputText value="Persona :"/> <p:selectOneRadio id="checkEsNatural" value="#{personaBean.persona.esNatural}" tabindex="1"> <f:selectItem itemLabel="Natural" itemValue="#{false}" /> <f:selectItem itemLabel="Jurídica" itemValue="#{true}" /> <p:ajax update="pnlPersona" event="valueChange" /> </p:selectOneRadio> <p:outputLabel for="inputTxtNombre" value="Nombre o Razon social:"/> <p:inputText id="inputTxtNombre" value="#{personaBean.persona.nombreRazonSocial}" required="true" style="width: 215px;text-transform: uppercase;" requiredMessage="El campo Nombre o Razon social es obligatorio" tabindex="2"> <f:converter converterId="lowerConverter"/> </p:inputText> <h:outputText value="Apellido paterno:" rendered="#{!personaBean.persona.esNatural}"/> <p:inputText id="inputTxtPaterno" value="#{personaBean.persona.apellidoPaterno}" style="width: 215px;text-transform: uppercase;" tabindex="3" rendered="#{!personaBean.persona.esNatural}"> <f:converter converterId="lowerConverter"/> </p:inputText> <h:outputText value="Apellido materno:" rendered="#{!personaBean.persona.esNatural}"/> <p:inputText id="inputTxtMaterno" value="#{personaBean.persona.apellidoMaterno}" tabindex="4" style="width: 215px;text-transform: uppercase;" rendered="#{!personaBean.persona.esNatural}" > <f:converter converterId="lowerConverter"/> </p:inputText> <p:outputLabel for="slcOneMenuTipoIdentificacion" value="Tipo de identificación:"/> <p:selectOneMenu id="slcOneMenuTipoIdentificacion" value="#{personaBean.persona.tipoIdentificacion}" tabindex="5" style="text-transform: uppercase;" required="true" requiredMessage="El campo Tipo de identificacion es obligatorio."> <f:selectItem itemLabel="---Seleccione una identificación---" itemValue="" /> <f:selectItems value="#{personaBean.listaTipoIdentificacion}" /> </p:selectOneMenu> <p:outputLabel for="slcOneMenuLocalidad" value="Lugar de emisión:"/> <p:selectOneMenu id="slcOneMenuLocalidad" value="#{personaBean.idLocalidad}" tabindex="6" required="true" requiredMessage="El campo Lugar de emisión es obligatorio." style="text-transform: uppercase;"> <f:selectItem itemLabel="---Seleccione un departamento---" itemValue="0L" /> <f:selectItems value="#{personaBean.listaLocalidad}" /> </p:selectOneMenu> <p:outputLabel for="inputTxtNroIdentificacion" value="Nro. de identificación:"/> <p:inputText id="inputTxtNroIdentificacion" value="#{personaBean.persona.nroIdentificacion}" tabindex="7" required="true" size="15" maxlength="15" autocomplete="false" onkeyup="$(this).val($(this).val().replace(/[^0-9]/g, ''));" style="width: 215px;text-transform: uppercase;" converterMessage="El valor del campo Nro. de identificación debe ser numerico." requiredMessage="El campo Nro. de identificación es obligatorio"> </p:inputText> <p:outputLabel for="inputTxtNombreComercial" value="Nombre comercial:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"/> <p:inputText id="inputTxtNombreComercial" value="#{personaBean.unidad.nombreComercial}" style="width: 215px;text-transform: uppercase;" tabindex="8" required="true" requiredMessage="El campo Nombre comercial es obligatorio."> <f:converter converterId="lowerConverter"/> </p:inputText> <p:outputLabel for="slcOneMenuTipoEmpresa" value="Tipo de empresa: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"/> <p:selectOneMenu id="slcOneMenuTipoEmpresa" value="#{personaBean.unidad.tipoEmpresa}" tabindex="9" style="width: 225px;text-transform: uppercase;" required="true" requiredMessage="El campo Tipo de empresa es obligatorio."> <f:selectItem itemLabel="---Seleccione una empresa---" itemValue="0" /> <f:selectItems value="#{personaBean.listaTipoEmpresa}" /> </p:selectOneMenu> <p:outputLabel for="slcOneMenuTipoSociedad" value="Tipo de sociedad:"/> <p:selectOneMenu id="slcOneMenuTipoSociedad" value="#{personaBean.unidad.tipoSociedad}" tabindex="10" style="text-transform: uppercase;" required="true" requiredMessage="El campo Tipo de sociedad es obligatorio."> <f:selectItem itemLabel="---Seleccione una sociedad---" itemValue="0" /> <f:selectItems value="#{personaBean.listaTipoSociedad}" /> </p:selectOneMenu> <p:outputLabel for="calendar" value="Fecha actividad:"/> <p:calendar id="calendar" value="#{personaBean.unidad.fechaNacimiento}" effect="slideDown" maxlength="10" tabindex="11" timeOnly="false" style="width:190px;" required="true" showOn="button" pattern="dd/MM/yyyy" navigator="true" converterMessage="El formato de la fecha es incorrecto. Ejemplo: dd/mm/yyyy" requiredMessage="El campo Fecha actividad es obligatorio."> </p:calendar> <p:outputLabel for="txtAreaActividadDeclarada" value="Actividad declarada:&nbsp;&nbsp;&nbsp;&nbsp;"/> <p:inputTextarea id="txtAreaActividadDeclarada" value="#{personaBean.unidad.actividadDeclarada}" rows="5" cols="50" autoResize="false" style="width: 220px;text-transform: uppercase;" tabindex="12" required="true" requiredMessage="El campo Actividad declarada es obligatorio."> <f:converter converterId="lowerConverter"/> </p:inputTextarea> </h:panelGrid> </p:panel> </h:panelGrid> <h:panelGrid columns="2" id="pnlGridDoble" > <p:panel id="pnlUsario" style="height: 140px;width: 700px;" > <f:facet name="header"> <p:outputLabel value="DATOS DE USUARIO DEL SISTEMA"/> </f:facet> <f:facet name="footer"> <p:commandButton value="Guardar" action="#{personaBean.registrar}" tabindex="17" process="@form" update="growl" icon="ui-icon-disk" /> <!-- <p:commandButton value="Rerporte" action="# {personaBean.crearReporte}" process="@this" icon="ui-icon-disk" />--> </f:facet> <h:panelGrid id="pnlGridUsuario" columns="2" > <h:outputText value="Usuario:"/> <p:inputText id="inputTxtUsuario" value="#{personaBean.usuario.usuario}" required="true" requiredMessage="El campo Usuario es obligatorio" style="width: 215px;" tabindex="14" autocomplete="off" > <p:watermark for="inputTxtUsuario" value="Correo electronico" /> </p:inputText> <h:outputText value="Contraseña:" /> <h:panelGrid columns="3"> <p:password id="inputTxtClave" value="#{personaBean.usuario.clave}" feedback="true" tabindex="15" required="true" requiredMessage="EL campo Contraseña es obligatorio" autocomplete="off" promptLabel="Ingrese su contraseña" weakLabel="Contraseña debil" goodLabel="Contraseña media" strongLabel="Contraseña fuerte" style="width: 215px;" /> <h:graphicImage value="/images/ayuda.png" id="grafayuda"/> <p:tooltip for="grafayuda"> <ol> <li>La Contrase&ntilde;a permite los siguientes caracteres especiales:<br /> <b> ` ~ ! @ # $ % ^ &amp; * ( ) _ = { } + \ | : ; &prime; &Prime; &lt; &gt; , - . ? /</b> </li> <li>La Contrase&ntilde;a permite validar que ingrese al menos un caracter especial, numerico y alfabetico</li> <li>La longitud minima requerida es de #{personaBean.LONGITUD_MINIMA} caracteres</li> </ol> <b>Ejemplo:</b> <pre>admin12@</pre> </p:tooltip> </h:panelGrid> <h:outputText value="Confirmar contraseña:" /> <p:password id="inputTxtConfirmar" value="#{personaBean.confirmarContrasenia}" feedback="true" tabindex="16" autocomplete="off" promptLabel="Ingrese su contraseña" weakLabel="Contraseña debil" goodLabel="Contraseña media" strongLabel="Contraseña fuerte" style="width: 215px;" /> </h:panelGrid> </p:panel> </h:panelGrid> <br/> </h:form> <p:dialog id="dlg" header="Confirmación" widgetVar="dlg" resizable="false" position="300,400" modal="true" dynamic="true"> <h:form id="frmDlg"> <h:panelGrid columns="1"> <h:outputText value="Se registrarón los datos exitosamente. Se le envió un email para completar su registro."/> <p:commandButton value="Aceptar" action="#{personaBean.volverLogin}"/> </h:panelGrid> </h:form> </p:dialog> </ui:define> </ui:composition> </html>
import { BadRequestException, Injectable } from '@nestjs/common'; import { BasePaginationDto } from './dto/base-pagination.dto'; import { FindManyOptions, FindOptionsOrder, FindOptionsWhere, Repository, } from 'typeorm'; import { BaseModel } from './entity/base.entity'; import { FILTER_MAPPER } from './const/filter-mapper.const'; import { ConfigService } from '@nestjs/config'; import { ENV_HOST_KEY, ENV_PROTOCOL_KEY } from './const/env-keys.const'; @Injectable() export class CommonService { constructor(private readonly configService: ConfigService) {} paginate<T extends BaseModel>( dto: BasePaginationDto, repository: Repository<T>, overrideFindOptions: FindManyOptions<T>, path: string, ) { if (dto.page) { return this.pagePaginate(dto, repository, overrideFindOptions); } else { return this.cursorPaginate(dto, repository, overrideFindOptions, path); } } private async cursorPaginate<T extends BaseModel>( dto: BasePaginationDto, repository: Repository<T>, overrideFindOptions: FindManyOptions<T> = {}, path: string, ) { const findOptions = this.composeFindOptions<T>(dto); const results = await repository.find({ ...findOptions, ...overrideFindOptions, }); // 해당하는 포스트가 0개 이상이면 // 마지막 포스트를 가져온다. // 아니면 null을 반환한다. const lastItem = results.length > 0 && results.length === dto.take ? results[results.length - 1] : null; const protocol = this.configService.get<string>(ENV_PROTOCOL_KEY); const host = this.configService.get<string>(ENV_HOST_KEY); const nextUrl = lastItem && new URL(`${protocol}://${host}/${path}`); /** * dto의 키값들을 루핑하면서 * 키값에 해당하는 벨류가 존재한다면 * param에 그대로 붙여넣는다. * * 단, where__id_more_than 값만 lastItem의 마지막 값욿 넣어준다. */ if (nextUrl) { for (const key of Object.keys(dto)) { if (dto[key]) { if ( key !== 'where__id__more_than' && key !== 'where__id__less_than' ) { nextUrl.searchParams.append(key, dto[key]); } } } let key = null; if (dto.order__createdAt === 'ASC') { key = 'where__id__more_than'; } else { key = 'where__id__less_than'; } nextUrl.searchParams.append(key, lastItem.id.toString()); } return { data: results, cursor: { after: lastItem?.id ?? null, }, count: results.length, next: nextUrl?.toString() ?? null, }; } private async pagePaginate<T extends BaseModel>( dto: BasePaginationDto, repository: Repository<T>, overrideFindOptions: FindManyOptions<T> = {}, ) { const findOptions = this.composeFindOptions<T>(dto); const [data, count] = await repository.findAndCount({ ...findOptions, ...overrideFindOptions, }); return { data, total: count, }; } private composeFindOptions<T extends BaseModel>( dto: BasePaginationDto, ): FindManyOptions<T> { /** * where, * order, * take, * skip -> page 기반일때만 */ /** * DTO의 현재 생긴 구조는 아래와 같다 * * { * where__id__more_than: 1, * ortder__createdAt: 'ASC', * } * * 현재는 where_likeCount__more_than/ where__id__less_than에 해당하는 where 필터만 사용중이지만 * 나중에 where__likeCount__more_than 이나 where__title__ilike 등 추가 필터를 넣고 싶어졌을떄 * 모든 where 필터들을 자동으로 파싱할 수 있을 만한 기능을 제작해야한다. * * 1) where로 시작한다면 필터 로직을 적용한다. * 2) order로 시작한다면 정렬 로직을 적용한다. * 3) 필터 로직을 작영힌디먄 '__' 기준으로 split 했을때 3개의 값으로 나뉘는지 * 2개의 값으로 나뉘는지 확인한다. * 3-1) 3개의 값으로 나뉘면 FILTERT_MAPPER에서 해당하는 operator함수를 찾아서 적용한다. * ['where', 'likeCount', 'more_than'] * 3-2 2개의 값으로 나뉘면 정확한 값을 필터하는 것이기 때문에 operator없이 적용한다. * ['where', 'id'] * 4) order의 경우 3-2와 같이 적용한다. * * */ let where: FindOptionsWhere<T> = {}; let order: FindOptionsOrder<T> = {}; for (const [key, value] of Object.entries(dto)) { // key -> where__id__more_than // value -> 1 if (key.startsWith('where__')) { where = { ...where, ...this.parseWhereFilter(key, value) }; } else if (key.startsWith('order__')) { order = { ...order, ...this.parseWhereFilter(key, value) }; } } return { where, order, take: dto.take, skip: dto.page ? dto.take * (dto.page - 1) : null, }; } private parseWhereFilter<T extends BaseModel>( key: string, value: any, ): FindOptionsWhere<T> | FindOptionsOrder<T> { const options: FindOptionsWhere<T> = {}; /** * 예를 들어 where__id__more_than * __을 기준으로 나눴을떄 * * ['where', 'id', 'more_than']으로 나눌 수 있다. */ const split = key.split('__'); if (split.length !== 2 && split.length !== 3) { throw new BadRequestException(` where 필터는 '__'로 split 했을때 2개 혹은 3개의 값으로 나뉘어야 합니다. - 문제가 되는 키값: ${key}`); } /** * 길이가 2일 경우는 * where__id=3 * * FindOPthinsWhere로 풀어보면 * 아래와 같다. * * { * where: { * id: 3 * } * } */ if (split.length === 2) { // ['where', 'id'] const [_, field] = split; /** * field -> 'id' * value -> 3 * * { * id: 3 * } */ options[field] = value; } else { /** * 길이가 3일 경우에는 Typeorm 유틸리티 적용이 필요한 경우다. * * where_id_more_than의 경우 * where는 버려도 되고 두번째 값은 필터할 키값이 되고 * 세번째 값은 typeorm 유틸리티가 된다. * * FILTER_MAPPER에 미리 정의해둔 값들로 * field 값에 FILTER_MAPPER에서 해당되는 utility를 가져온 후 * 값에 적용 해준다. */ // ['where', 'id', 'more_than'] const [_, field, operator] = split; // where__id__between = 3,4 // 만약에 split 대상 문자가 존재하지 않으면 길이가 무조건 1이다. // const values = value.toString().split(','); // field -> 'id' // operator -> 'more_than' // FILTER_MAPPER[operator] -> MoreThan // if (operator === 'between') { // options[field] = FILTER_MAPPER[operator](values[0], values[1]); // } else { // options[field] = FILTER_MAPPER[operator](value); // } if (operator === 'i_like') { options[field] = FILTER_MAPPER[operator](`%${value}%`); } else { options[field] = FILTER_MAPPER[operator](value); } } return options; } // private parseOrderFilter<T extends BaseModel>( // key: string, // value: any, // ): FindOptionsOrder<T> { // const order: FindOptionsOrder<T> = {}; // /** // * order는 무조건 두개로 스필릿된다. // */ // const split = key.split('__'); // if (split.length !== 2) { // throw new BadRequestException(` // order 필터는 '__'로 split 했을때 2개의 값으로 나뉘어야 합니다. - 문제가 되는 키값: ${key}`); // } // const [_, field] = split; // order[field] = value; // return order; // } }
/******************************************************************************* * McXtrace instrument definition URL=http://www.mcxtrace.org * * Instrument: Simple_1shell * * %Identification * Written by: Erik B Knudsen <erkn@fysik.dtu.dk> & Desiree D. M. Ferreira <desiree@space.dtu.dk> (email) * Date: 12/12/2016 * Origin: DTU Physics/DTU Space * Release: McXtrace 1.2 * Version: 1.0 * %INSTRUMENT_SITE: AstroX_ESA * * Single shell model of a true Wolter Type I optic * * %Description * Single shell example telescope using a combinatiopn pf parabolic/hyperbolic shell * optical plates covering the full circle. Reflectivity is 1 for all energies. * * Example: Simple_1shell.instr FL=12 * * %Parameters * FL: [m] The focal length of the optical system * plate_zdepth: [m] Plate length. * channel_yheight: [m] Channel height. * radius_p: [m] Radius at the entry to the primary (parabolic) shell. * radius_m: [m] Radius at the optics centre. * radius_h: [m] Radius at the exit of the secondary (hyperbolic) shell. * * %End *******************************************************************************/ /* Change name of instrument and input parameters with default values */ DEFINE INSTRUMENT Simple_1shell(FL=12, plate_zdepth=0.5, channel_yheight=1e-2, radius_m=0.534927, radius_p=0.535532 , radius_h=0.533113) /* The DECLARE section allows us to declare variables or small */ /* functions in C syntax. These may be used in the whole instrument. */ DECLARE %{ %} /* The INITIALIZE section is executed when the simulation starts */ /* (C code). You may use them as component parameter values. */ INITIALIZE %{ %} /* instrument is defined as a sequence of components. */ TRACE /* The Arm() class component defines reference points and orientations */ /* in 3D space. Every component instance must have a unique name. Here, */ /* Origin is used. This Arm() component is set to define the origin of */ /* our global coordinate system (AT (0,0,0) ABSOLUTE). It may be used */ /* for further RELATIVE reference, Other useful keywords are : ROTATED */ /* EXTEND GROUP PREVIOUS. Also think about adding an xray source ! */ /* Progress_bar is an Arm displaying simulation progress. */ COMPONENT Origin = Progress_bar() AT (0,0,0) ABSOLUTE EXTEND %{ %} COMPONENT src = Source_div( radius=radius_p,yheight=0, xwidth=0,focus_aw=0,focus_ah=0,E0=5,dE=1) AT(0,0,0) RELATIVE Origin COMPONENT detector_pre_optics = PSD_monitor(restore_xray=1, xwidth=radius_p*2*1.2, yheight=radius_p*2*1.2, nx=101, ny=51, filename="det_preo.dat") AT(0,0,1) RELATIVE Origin COMPONENT optics_centre = Arm() AT(0,0,1) RELATIVE Origin COMPONENT Shell_p_1 = Shell_p( radius_p=radius_p, radius_m=radius_m, zdepth=plate_zdepth, Z0=FL, yheight=channel_yheight, R_d=1) AT(0,0,0) RELATIVE optics_centre COMPONENT midopdet = PSD_monitor( restore_xray=1,xwidth=radius_m*2*1.2,yheight=radius_m*2*1.2,nx=201,ny=201, filename="midop.dat") AT(0,0,0) RELATIVE optics_centre COMPONENT Shell_h_1 = Shell_h( radius_m=radius_m, radius_h=radius_h, zdepth=plate_zdepth, Z0=FL, yheight=channel_yheight, R_d=1) AT(0,0,0) RELATIVE optics_centre EXTEND %{ /*filter off rays wich have not reflected*/ if (kx==0 && ky==0){ ABSORB; } %} COMPONENT detector_post_optics = PSD_monitor(restore_xray=1,xwidth=radius_h*2*1.2, yheight=radius_h*2*1.2, nx=201, ny=101, filename="det_posto.dat") AT(0,0,1) RELATIVE optics_centre /*soem monitors of varying size to catch the focal plane response*/ COMPONENT focal_detector = PSD_monitor(restore_xray=1,xwidth=1e-2, yheight=1e-2, nx=201, ny=201, filename="focal_det.dat") AT(0,0,FL) RELATIVE optics_centre COMPONENT superfocal_detector = PSD_monitor(restore_xray=1,xwidth=1e-6, yheight=1e-6, nx=201, ny=201, filename="superfocal_det.dat") AT(0,0,FL) RELATIVE optics_centre COMPONENT ultrafocal_detector = PSD_monitor(restore_xray=1,xwidth=1e-12, yheight=1e-12, nx=201, ny=201, filename="ultrafocal_det.dat") AT(0,0,FL) RELATIVE optics_centre COMPONENT FLmond= Monitor_nD( restore_xray=1,filename="FLmond",xwidth=0.1, yheight=0.1, options="x y auto",bins=501) AT(0,0,FL) RELATIVE optics_centre /* This section is executed when the simulation ends (C code). Other */ /* optional sections are : SAVE */ FINALLY %{ %} /* The END token marks the instrument definition end */ END
<?php namespace App\Domain\Payments\PlaceToPay; use App\Domain\Orders\Actions\UpdateOrderAction; use App\Domain\Orders\Enums\OrderStatus; use App\Domain\Orders\Models\Order; use App\Domain\Payments\Contracts\Payments; use App\Domain\Payments\Exceptions\PaymentException; use App\Domain\Users\Models\User; use App\Support\Exceptions\ApplicationException; use App\Support\Exceptions\CustomException; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Http; use Throwable; class PlaceToPayService implements Payments { /** * @throws CustomException */ public function paymentProcess(Request $request, User $user, Order $order): string { try { $paymentSession = $this->createPaymentSession($user, $order, $request->ip(), $request->userAgent()); $result = Http::post(config('placetopay.url').'/api/session', $paymentSession); if ($result->ok()) { $action = new UpdateOrderAction(); $data = [ 'requestId' => $result->json()['requestId'], 'processUrl' => $result->json()['processUrl'], ]; $action->execute($order, $data); Cache::forget('cart:'.$request->user()->getKey()); return $order->processUrl; } else { if ($result->json()['status']['reason'] === 401) { throw PaymentException::authError(); } throw PaymentException::sessionError($result->json()['status']['message']); } } catch (Throwable $e) { if ($e instanceof CustomException) { throw $e; } throw new ApplicationException($e, [ 'request' => $request->getContent(), 'user' => $user->toArray(), 'order' => $order->toArray(), ]); } } private function createPaymentSession(User $user, Order $order, string $ipAddress, string $userAgent): array { $auth = new Auth(); $buyer = new Buyer($user); $payment = new OrderToPayment($order); return [ 'locale' => 'en_CO', 'auth' => $auth->getAuth(), 'buyer' => $buyer->getBuyer(), 'payment' => $payment->getPayment(), 'expiration' => Carbon::now()->addMinutes(config('placetopay.expirationSession')), 'returnUrl' => route('payment.success'), 'cancelUrl' => route('payment.cancel'), 'ipAddress' => $ipAddress, 'userAgent' => $userAgent, ]; } public function checkPayment(Order $order): OrderStatus { $auth = new Auth(); $result = Http::post(config('placetopay.url')."/api/session/$order->requestId", [ 'auth' => $auth->getAuth(), ]); if ($result->ok()) { return $this->paymentStatus($result->json()['status']['status']); } else { return OrderStatus::PENDING; } } private function paymentStatus(string $status): OrderStatus { return match ($status) { 'APPROVED' => OrderStatus::ACCEPTED, 'REJECTED' => OrderStatus::REJECTED, default => OrderStatus::PENDING, }; } }
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from rasa_sdk import Action from rasa_sdk.events import SlotSet import zomatopy from emailpy import send_email import json import pandas as pd from rasa_core_sdk.events import AllSlotsReset from rasa_core_sdk.events import Restarted class ActionRestarted(Action): def name(self): return 'action_restart' def run(self, dispatcher, tracker, domain): return[Restarted()] class ActionSlotReset(Action): def name(self): return 'action_slot_reset' def run(self, dispatcher, tracker, domain): return[AllSlotsReset()] class ActionCheckLocation(Action): def name(self): return 'action_check_location' def run(self, dispatcher, tracker, domain): try: config={ "user_key":"5c982b6c16e36864cbe8a9ac0449ab7a"} zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') loc_valid=False loc_operational=False tier_1_2_cities = ['bangalore', 'chennai', 'delhi', 'hyderabad', 'kolkata', 'mumbai', 'ahmedabad', 'pune', 'agra', 'ajmer', 'aligarh', 'amravati', 'amritsar', 'asansol', 'aurangabad', 'bareilly', 'belgaum', 'bhavnagar', 'bhiwandi', 'bhopal', 'bhubaneswar', 'bikaner', 'bilaspur', 'bokaro steel city', 'chandigarh', 'coimbatore', 'nagpur', 'cuttack', 'dehradun', 'dhanbad', 'bhilai', 'durgapur', 'erode', 'faridabad', 'firozabad', 'ghaziabad', 'gorakhpur', 'gulbarga', 'guntur', 'gwalior', 'gurgaon', 'guwahati', 'hamirpur', 'hubli–dharwad', 'indore', 'jabalpur', 'jaipur', 'jalandhar', 'jammu', 'jamnagar', 'jamshedpur', 'jhansi', 'jodhpur', 'kakinada', 'kannur', 'kanpur', 'kochi', 'kolhapur', 'kollam', 'kozhikode', 'kurnool', 'ludhiana', 'lucknow', 'madurai', 'malappuram', 'mathura', 'goa', 'mangalore', 'meerut', 'moradabad', 'mysore', 'nanded', 'nashik', 'nellore', 'noida', 'patna', 'pondicherry', 'purulia', 'prayagraj', 'raipur', 'rajkot', 'rajahmundry', 'ranchi', 'rourkela', 'salem', 'sangli', 'shimla', 'siliguri', 'solapur', 'srinagar', 'thiruvananthapuram', 'thrissur', 'tiruchirappalli', 'tiruppur', 'ujjain', 'bijapur', 'vadodara', 'varanasi', 'vasai-virarcity', 'vijayawada', 'vellore', 'warangal', 'surat', 'visakhapatnam'] # Wikipedia January 2020 if(zomato.check_city_valid(loc)): # if valid # dispatcher.utter_message("Looking for "+str(loc).lower()+" in list") if(loc.lower() in tier_1_2_cities): loc_operational=True loc_valid=True else: # if city name not in zomato database # dispatcher.utter_message("couldn't find "+str(loc).lower()+" anywhere") loc_valid=False loc_operational=False return [SlotSet('location_valid', loc_valid), SlotSet('location_operational', loc_operational)] except: dispatcher.utter_message('Sorry, We do not operate in that area yet!') class ActionSearchRestaurants(Action): def name(self): return 'action_search_restaurants' def run(self, dispatcher, tracker, domain): try: config={ "user_key":"5c982b6c16e36864cbe8a9ac0449ab7a"} found_restaurants=True zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') budget = tracker.get_slot('budget') priceMin=0 priceMax=1000000 if(budget=="<300"): priceMax=299 elif(budget=="300-700"): priceMin=300 priceMax=699 else: priceMin=700 location_detail=zomato.get_location(loc, 1) d1 = json.loads(location_detail) try: if(len(d1) > 0): lat=d1["location_suggestions"][0]["latitude"] lon=d1["location_suggestions"][0]["longitude"] cuisines_dict={'american':1,'mexican':73,'bakery':5,'chinese':25,'cafe':30,'italian':55,'biryani':7,'north indian':50,'south indian':85} results=zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), 50) ## get a list of 50 restaurants then filter top 5 by budget except: dispatcher.utter_message('Sorry, We do not operate in that area yet!') if(not tracker.get_slot('location_operational')): dispatcher.utter_message('Sorry, We do not operate in that area yet!') elif(not tracker.get_slot('location_valid')): dispatcher.utter_message('Sorry, This is not a valid location') else: d = json.loads(results) # try: ## WHen API limits exceeded if d['results_found'] == 0: response= "no results" dispatcher.utter_message("Sorry, We couldn't find any "+str(cuisine)+" restaurants in "+str(loc)+".") found_restaurants=False else: r_data=[] for i,r in enumerate(d["restaurants"]): r_l=[] cost_for_two=int(r['restaurant']['average_cost_for_two']) if(cost_for_two>=priceMin and cost_for_two<=priceMax): r_l.append(r['restaurant']['id']) r_l.append(r['restaurant']['name']) r_l.append(float(r['restaurant']['user_rating']['aggregate_rating'])) r_l.append(cost_for_two) r_l.append(r['restaurant']['location']['address']) r_data.append(r_l) df=pd.DataFrame(data=r_data,columns=["ID","Name","Rating","Avg_Cost_for_Two","Address"]) df.set_index('ID', inplace=True) df=df.sort_values('Rating',ascending=False) if(len(df.Name)>=5): response="Showing Top rated restaurants in "+str(loc)+" : \n" for i in range(5): response += str(i+1)+". "+df.Name[i]+" in "+df.Address[i]+" has been rated "+str(df.Rating[i])+" \n" elif(len(df.Name)>0 and len(df.Name)<5): # Couldn't find 5 restaurants #response="Sorry we could not find enough restaurants with given details \n" #response+="Top "+str(len(df.Name))+" "+str(cuisine)+" restaurants near "+str(loc).rstrip()+"\n" for i in range(5): if (len(df.Name[i]) > 0): response += str(i + 1) + ". " + df.Name[i] + " in " + df.Address[i] + " has been rated " + str( df.Rating[i]) + " \n" else: response += str(i + 1) + ". " + " \n" else: response="Sorry, We couldn't find any matching restaurants for your requirements." found_restaurants=False # except: # dispatcher.utter_message("Sorry, We couldn't find any "+str(cuisine)+" restaurants in "+str(loc)+".") # found_restaurants=False dispatcher.utter_message(response) return [SlotSet('found_restaurants',found_restaurants)] except: dispatcher.utter_message('Sorry. No restaurants found!!') class ActionSearchRestaurantsTopTen(Action): def name(self): return 'action_send_email' def run(self, dispatcher, tracker, domain): try: mail_status=False config={ "user_key":"5c982b6c16e36864cbe8a9ac0449ab7a"} zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') user_domain = tracker.get_slot('email') found_restaurants = tracker.get_slot('found_restaurants') name = user_domain.split('@')[0] location_detail=zomato.get_location(loc, 1) d1 = json.loads(location_detail) lat=d1["location_suggestions"][0]["latitude"] lon=d1["location_suggestions"][0]["longitude"] cuisines_dict={'american':1,'mexican':73,'bakery':5,'chinese':25,'cafe':30,'italian':55,'biryani':7,'north indian':50,'south indian':85} budget = tracker.get_slot('budget') priceMin=0 priceMax=1000000 if(budget=="<300"): priceMax=299 elif(budget=="300-700"): priceMin=300 priceMax=699 else: priceMin=700 results=zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), 50) ## get a list of 50 restaurants then filter top 5 by budget if(not tracker.get_slot('location_operational')): dispatcher.utter_message('Sorry, We do not operate in that area yet') elif(not tracker.get_slot('location_valid')): dispatcher.utter_message('Sorry, This is not a valid location') else: d = json.loads(results) if d['results_found'] == 0: response = "No results found!!" else: r_data=[] for i,r in enumerate(d["restaurants"]): r_l=[] cost_for_two=int(r['restaurant']['average_cost_for_two']) if(cost_for_two>=priceMin and cost_for_two<=priceMax): r_l.append(r['restaurant']['id']) r_l.append(r['restaurant']['name']) r_l.append(float(r['restaurant']['user_rating']['aggregate_rating'])) r_l.append(cost_for_two) r_l.append(r['restaurant']['location']['address']) r_data.append(r_l) df=pd.DataFrame(data=r_data,columns=["ID","Name","Rating","Avg_Cost_for_Two","Address"]) df.set_index('ID', inplace=True) df=df.sort_values('Rating',ascending=False) if(found_restaurants==True): if(len(df.Name)>=10): response="Top 10 "+str(cuisine)+" restaurants near "+str(loc)+"\n\n" for i in range(10): response+=str(i+1)+". "+df.Name[i]+" in "+df.Address[i]+". Average Cost for Two is Rs. "+str(df.Avg_Cost_for_Two[i])+" has been rated "+str(df.Rating[i])+". \n" mail_status=True send_email(name,user_domain,response) elif(len(df.Name)>0 and len(df.Name)<10): # Couldn't find 10 restaurants response="All "+str(cuisine)+" restaurants near "+str(loc).rstrip()+"\n" for i in range(len(df.Name)): response+=str(i+1)+". "+df.Name[i]+" in "+df.Address[i]+". Average Cost for Two is Rs. "+str(df.Avg_Cost_for_Two[i])+" has been rated "+str(df.Rating[i])+". \n" mail_status=True send_email(name,user_domain,response) dispatcher.utter_message("Mail Sent!") else: mail_status=False dispatcher.utter_message("Sorry. No restaurants found!!") return [SlotSet('mail_sent',mail_status)] except: dispatcher.utter_message("Incorrect email, Failed to send email!!")
import express from "express"; import expressWs from "express-ws"; import cors from "cors"; import * as uuid from "uuid"; const PORT = process.env.PORT || 3000; const channelmetrics = {}; const app = express(); const appWithWS = expressWs(app); app.use(cors()); app.use(express.static("static")); var wss = appWithWS.getWss(); function broadcast(message, channel) { // console.log("broadcast", channel, message); wss.clients.forEach(function (client) { // console.log(" client @channel ", client._channel); if (client._channel === channel || channel === undefined) { client.send(message); } }); } setInterval(() => { // broadcast some stats let channels = []; let counter = 0; let channelcounter = {}; wss.clients.forEach(function (client) { const channel = client._channel; if (channels.indexOf(channel) === -1) { channels.push(channel); } counter++; if (channelcounter[channel] !== undefined) { channelcounter[channel] += 1; } else { channelcounter[channel] = 1; } }); // console.log("channels", channels, counter); channels = channels.map((c) => { return { id: c, metrics: channelmetrics[c], connections: channelcounter[c] || 0, }; }); broadcast( JSON.stringify({ type: ".stats", clients: counter, channels, }), undefined ); }, 3000); // app.ws("/broadcast", function (ws, req) { // let nodeid = -1; // let channel = "default"; // const id = uuid.v4(); // console.log("connected", channel, id); // ws._channel = channel; // ws.send( // JSON.stringify({ // type: "_welcome", // _channel: channel, // _id: id, // }) // ); // ws.on("message", function (msg) { // // console.log("got message", msg); // const decoded = JSON.parse(msg); // if (decoded && decoded.type === ".hello" && decoded.node) { // nodeid = decoded.node; // } // decoded._channel = channel; // decoded._id = id; // if (channel) { // broadcast(JSON.stringify(decoded), channel); // let metric = channelmetrics[channel]; // if (!metric) { // metric = {}; // metric.lastseen = Date.now(); // metric.events = 1; // channelmetrics[channel] = metric; // } else { // metric.lastseen = Date.now(); // metric.events++; // } // } // }); // ws.on("close", () => { // console.log("disconnect", channel, id, nodeid); // broadcast( // JSON.stringify({ // type: ".disconnect", // _node: nodeid, // _channel: channel, // _id: id, // }), // channel // ); // }); // }); app.ws("/broadcast/:channel", function (ws, req) { let nodeid = -1; let channel = req.params.channel; const id = uuid.v4(); console.log("connected", channel, id); ws._channel = channel; ws.send( JSON.stringify({ type: ".welcome", _channel: channel, _id: id, }) ); ws.on("message", function (msg) { // console.log("got message", msg); const decoded = JSON.parse(msg); if (decoded && decoded.type === ".hello") { nodeid = decoded.node; } decoded._channel = channel; decoded._id = id; if (channel) { broadcast(JSON.stringify(decoded), channel); let metric = channelmetrics[channel]; if (!metric) { metric = {}; metric.lastseen = Date.now(); metric.events = 1; channelmetrics[channel] = metric; } else { metric.lastseen = Date.now(); metric.events++; } } }); ws.on("close", () => { console.log("disconnect", channel, id, nodeid); broadcast( JSON.stringify({ type: ".disconnect", _node: nodeid, _channel: channel, _id: id, }), channel ); }); }); app.listen(PORT, function () { console.log(`web server listening on port ${PORT}`); });
import React, {useEffect, useState} from 'react'; import {View,Image, Text, ImageBackground, StyleSheet, Platform,ActivityIndicator} from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import Colors from '../CommonUtils/Colors'; import Images from '../CommonUtils/Images'; import Barcode from 'react-native-barcode-builder'; const LoyalityCard = props => { //alert(JSON.stringify(props)) return ( <ImageBackground source={Images.LoyalityCardBg} style={styles.CardImgBg} imageStyle={{borderRadius: 20}}> <View style={styles.flexView}> <View> <Text style={styles.CardHTxt}>Your Loyalty Points</Text> <Text style={[styles.CardTxt, {alignSelf: 'flex-start'}]}> {props.loyaltyPoints?props.loyaltyPoints:"0"} </Text> </View> <View> <Text style={styles.CardHTxt}>Redeemable Value</Text> <Text style={[styles.CardTxt, {alignSelf: 'flex-end'}]}> ${props.redeemPoints}</Text> </View> </View> {/* <Image source={Images.LoyalityBar} style={styles.BarCodeImg} /> */} {props.IsCardgot==true? <Barcode value={props.value ? props.value : '0000'} format="CODE39" height={40} text={props.value} width={1.1} lineColor={Colors.blackFirst} background={'transparent'} /> : <ActivityIndicator size="large" color="red" /> } <Text style={[styles.CardTxt, {fontSize: 14}]}>{props.userName}</Text> </ImageBackground> ); }; const styles = StyleSheet.create({ flexView: { flexDirection: 'row', justifyContent: 'space-between', }, CardImgBg: { height: hp('25%'), padding: wp('4%'), paddingHorizontal: wp('5%'), flex: 1, justifyContent: 'space-between', marginBottom: wp('3%'), }, CardHTxt: { color: Colors.grayfade, fontSize: 14, fontWeight: 'bold', marginBottom: wp('1%'), }, CardTxt: {marginTop:Platform.OS=='ios'?5:0, fontSize: 18, color: Colors.white, fontWeight: 'bold'}, BarCodeImg: { alignSelf: 'center', height: wp('10%'), width: wp('45%'), }, }); export default LoyalityCard;
import React, {useEffect, useState} from "react"; import "./home.css"; import axios from "axios"; import CustomerRow from "../row/CustumerRow"; function Home() { const [users, setUsers] = useState([]); const [user, setUser] = useState([]); useEffect(() => { getUsers(); }, []); const [checkboxes, setCheckboxes] = useState([]); const changeCheckboxes = (id) => { setCheckboxes( checkboxes.includes(id) ? checkboxes.filter((el) => el !== id) : [...checkboxes, id] ); }; const getUsers = async () => { const response = await axios.get("http://localhost:8000/server/users/data"); setUsers(response.data); }; const deleteUser = (id) => { let arrayids = []; users.forEach(d => { if (d.select) { arrayids.push(d.id); } }); axios.delete(`http://localhost:8000/server/users/delete/${arrayids}`); window.location.reload(true) } function blockUser(id) { let arrayids = []; users.forEach(d => { if (d.select) { arrayids.push(d.id); } }); axios.patch(`http://localhost:8000/server/users/block/${arrayids}`); window.location.reload(true) } function unblockUser(id) { let arrayids = []; users.forEach(d => { if (d.select) { arrayids.push(d.id); } }); axios.patch(`http://localhost:8000/server/users/unblock/${arrayids}`); window.location.reload(true) } return ( <main className='container'> <br/> <div className="btn-toolbar" role="toolbar"> <div className="btn-group me-2"> <button type="button" className="btn btn-danger" onClick={() => blockUser(13)}>Block</button> </div> <div className="btn-group me-2"> <button type="button" className="btn btn-success" onClick={() => unblockUser(13)}>Unblock</button> </div> <div className="btn-group"> <button onClick={() => deleteUser(14)}>Delete</button> </div> </div> <br/> <table className="table table-bordered"> <thead> <tr> <th scope="col"> <input type="checkbox" onChange={e => { let checked = e.target.checked; setUser( users.map(d => { d.select = checked; return d; }) ); }} /> </th> <th scope="col">Id</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Registration date</th> <th scope="col">Last login date</th> <th scope="col">Status</th> </tr> </thead> <tbody> <></> <CustomerRow stateCustomer={users} setCustomerState={setUsers} /> </tbody> </table> </main>); } export default Home;
// // RollView.swift // DiceRollr // // Created by Anthony Bath on 7/3/23. // import CoreHaptics import SwiftUI struct RollView: View { let DiceValues = [4, 6, 10, 12, 20, 100] @State private var die = [Dice]() @State private var isEditing = false @State private var engine: CHHapticEngine? var onRoll: (Roll) -> Void private var columns: [GridItem] { if die.count == 1 || die.count == 3 { return [GridItem(.flexible())] } return [GridItem(.flexible()), GridItem(.flexible())] } private var totalRoll: String { if die.allSatisfy({ $0.rolledValue == nil }) { return "?" } return "\(die.compactMap { $0.rolledValue }.reduce(0, { $0 + $1 }))" } var body: some View { NavigationStack { VStack(alignment: .center) { if die.count > 0 { LazyVGrid( columns: columns, alignment: .center, spacing: 100 ) { ForEach(die) { dice in VStack { HStack { if isEditing { Image(systemName: "chevron.left") .onTapGesture { updateDice(dice, direction: -1) } } ZStack { Group { if let roll = dice.rolledValue { Text("\(roll)") } else { Text("?") } } .frame(width: 64, height: 64, alignment: .top) .font(.title) Text("\(dice.value)") .font(.caption) .padding(3) .frame(width: 64, height: 64, alignment: .bottom) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(.primary, lineWidth: 2) ) } if isEditing { Image(systemName: "chevron.right") .onTapGesture { updateDice(dice, direction: 1) } } } if isEditing { Button(role: .destructive) { withAnimation { die.removeAll { $0 == dice } if die.count == 0 { isEditing = false } } DiceSaver().save(die) } label: { Image(systemName: "minus.circle") } .padding(.top, 5) } } .gesture(DragGesture(minimumDistance: 3.0, coordinateSpace: .local) .onEnded { value in if isEditing { switch(value.translation.width, value.translation.height) { case (...0, -30...30): updateDice(dice, direction: -1) break; case (0..., -30...30): updateDice(dice, direction: 1) default: break; } } } ) } } .padding(.bottom, 75) if !isEditing { HStack { Button { rollHaptics() die.forEach { rollDice($0)} onRoll(Roll(die: die)) } label: { Label("Roll", systemImage: "dice.fill") } .padding() .padding([.leading,.trailing]) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(.blue, lineWidth: 2) ) Text("Total Roll: \(totalRoll)") } } } else { Text("Add a Dice to get started!") } } .toolbar { if die.count > 0 { ToolbarItem(placement: .navigationBarLeading) { Button { withAnimation { isEditing.toggle() } } label: { Text(isEditing ? "Done" : "Edit") } } } ToolbarItem(placement: .navigationBarTrailing) { Button { addDice() } label: { Label("Add Dice", systemImage: "plus.square") } .disabled(die.count == 6) } } .navigationTitle("Your Dice") .onAppear { die = DiceLoader().load() prepareHaptics() } } } func prepareHaptics() { guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else { return } do { engine = try CHHapticEngine() try engine?.start() } catch { print("Error creating Haptics Engine: \(error.localizedDescription)") } } func rollHaptics() { guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else { return } var events = [CHHapticEvent]() let intensity = CHHapticEventParameter(parameterID: .hapticIntensity, value: 1) let sharpness = CHHapticEventParameter(parameterID: .hapticSharpness, value: 1) let event = CHHapticEvent( eventType: .hapticTransient, parameters: [intensity, sharpness], relativeTime: 0 ) events.append(event) do { let pattern = try CHHapticPattern(events: events, parameters: []) let player = try engine?.makePlayer(with: pattern) try player?.start(atTime: 0) } catch { print("Failed to play Haptics: \(error.localizedDescription)") } } func updateDice(_ dice: Dice, direction: Int) { let currentValueIndex = DiceValues.firstIndex(of: dice.value) ?? 0 var nextIndex = currentValueIndex + direction if nextIndex < 0 { nextIndex = DiceValues.count - 1 } if nextIndex == DiceValues.count { nextIndex = 0} let newValue = DiceValues[nextIndex] let newDice = Dice(id: dice.id, value: newValue) let currentDiceIndex = die.firstIndex(of: dice) ?? 0 withAnimation { die.remove(at: currentDiceIndex) die.insert(newDice, at: currentDiceIndex) } DiceSaver().save(die) } func rollDice(_ dice: Dice) { let currentDiceIndex = die.firstIndex(of: dice) ?? 0 let rollValue = Int.random(in: 1...dice.value) let updatedDice = Dice(id: dice.id, value: dice.value, rolledValue: rollValue) withAnimation { die.remove(at: currentDiceIndex) die.insert(updatedDice, at: currentDiceIndex) } DiceSaver().save(die) } func addDice() { withAnimation { die.append(Dice()) } DiceSaver().save(die) } } struct RollView_Previews: PreviewProvider { static var previews: some View { RollView(onRoll: { _ in }) } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modern Landing Page</title> <link rel="stylesheet" href="style.css"> </head> <body> <!-- navbar --> <nav class="relative container p-6 mx-auto"> <!-- flex container --> <div class="flex items-center justify-between"> <!-- logo --> <div class="pt-2"> <img src="img/logo.svg" alt=""> </div> <!-- logo end --> <!-- menu items --> <div class="hidden md:flex space-x-6"> <a href="#" class="hover:text-darkGrayishBlue">Pricing</a> <a href="#" class="hover:text-darkGrayishBlue">Product</a> <a href="#" class="hover:text-darkGrayishBlue">About Us</a> <a href="#" class="hover:text-darkGrayishBlue">Careers</a> <a href="#" class="hover:text-darkGrayishBlue">Community</a> </div> <!-- menu items end--> <!-- button --> <a href="#" class="hidden p-3 px-6 pt-2 text-white bg-brightRed rounded-full baseline hover:bg-brightRedLight md:block"> Get Started </a> <!-- button end --> <!-- Hamburger Icon --> <button id="menu-btn" class="block hamburger md:hidden focus:outline-none" > <span class="hamburger-top"></span> <span class="hamburger-middle"></span> <span class="hamburger-bottom"></span> </button> </div> <!-- Mobile Menu --> <div class="md:hidden"> <div id="menu" class="absolute flex-col items-center hidden self-end py-8 mt-10 space-y-6 font-bold bg-white sm:w-auto sm:self-center left-6 right-6 drop-shadow-md" > <a href="#">Pricing</a> <a href="#">Product</a> <a href="#">About Us</a> <a href="#">Careers</a> <a href="#">Community</a> </div> </div> </nav> <!-- navbar end --> <!-- Hero Section start --> <section id="hero"> <!-- flex container start --> <div class="container flex flex-col-reverse md:flex-row items-center px-6 mx-auto mt-10 space-y-0 md:space-y-0"> <!-- left items start --> <div class="flex flex-col mb-32 space-y-12 md:w-1/2"> <h1 class="max-w-md text-4xl font-bold text-center md:text-5xl md:text-left"> Bring everyone together to build better procucts </h1> <p class="max-w-sm text-center text-darkGrayishBlue md:text-left"> Manage makes it simple for software trams to plan day-to-day tasks while keeping the larger team goals in view. </p> <div class="flex justify-center md:justify-start"> <a href="#" class="p-3 px-6 pt-2 text-white bg-brightRed rounded-full baseline hover:bg-brightRedLight "> Get Started </a> </div> </div> <!-- left items end --> <!-- image start --> <div class="md:w-1/2"> <img src="img/illustration-intro.svg" alt=""> </div> <!-- image end --> </div> <!-- flex container end --> </section> <!-- Hero Section end --> <!-- Features ection start --> <section id="features"> <!-- flex container start --> <div class="container flex flex-col px-4 mx-auto mt-10 space-y-12 md:space-y-0 md:flex-row"> <!-- left column start --> <div class="flex flex-col space-y-12 md:w-1/2"> <h2 class="max-w-md text-4xl font-bold text-center md:text-left"> What's different about Manage? </h2> <p class="max-w-sm text-center text-darkGrayishBlue md:text-left"> Manage provides all the functionality your team needs, without the complexity. Our software is tailor-made for modern digital product teams. </p> </div> <!-- left column end --> <!-- right column start --> <div class="flex flex-col space-y-8 md:w-1/2"> <!-- single list item start --> <div class="flex flex-col space-y-3 md:space-y-0 md:space-x-6 md:flex-row"> <div class="rounded-l-full bg-brightRedSupLight md:bg-transparent"> <div class="flex items-center space-x-2"> <div class="px-4 py-2 text-white rounded-full md:py-1 bg-brightRed"> 01 </div> <h3 class="text-base font-bold md:mb-4 md:hidden"> Track company-wide progress </h3> </div> </div> <div> <h3 class="hidden mb-4 text-lg font-bold md:block"> Track company-wide progress </h3> <p class="text-darkGrayishBlue"> See how your day-to-day tasks fit into the wider vision. Go from tracking progress at the milestone level all the way down to the smallest of details. Never lose sight of the bigger picture again. </p> </div> </div> <!-- single list item end --> <!-- single list item start --> <div class="flex flex-col space-y-3 md:space-y-0 md:space-x-6 md:flex-row"> <div class="rounded-l-full bg-brightRedSupLight md:bg-transparent"> <div class="flex items-center space-x-2"> <div class="px-4 py-2 text-white rounded-full md:py-1 bg-brightRed"> 02 </div> <h3 class="text-base font-bold md:mb-4 md:hidden"> Advanced built-in reports </h3> </div> </div> <div> <h3 class="hidden mb-4 text-lg font-bold md:block"> Advanced built-in reports </h3> <p class="text-darkGrayishBlue"> Set internal delivery estimates and track progress toward company goals. Our customisable dashboard helps you build out the reports you need to keep key stakeholders informed. </p> </div> </div> <!-- single list item end --> <!-- single list item start --> <div class="flex flex-col space-y-3 md:space-y-0 md:space-x-6 md:flex-row"> <div class="rounded-l-full bg-brightRedSupLight md:bg-transparent"> <div class="flex items-center space-x-2"> <div class="px-4 py-2 text-white rounded-full md:py-1 bg-brightRed"> 03 </div> <h3 class="text-base font-bold md:mb-4 md:hidden"> Everything you need in one place </h3> </div> </div> <div> <h3 class="hidden mb-4 text-lg font-bold md:block"> Everything you need in one place </h3> <p class="text-darkGrayishBlue"> Stop jumping from one service to another to communicate, store files, track tasks and share documents. Manage offers an all-in-one team productivity solution. </p> </div> </div> <!-- single list item end --> </div> <!-- right column end --> </div> <!-- flex container end --> </section> <!-- Features Section end --> <!-- Testimonials Section start --> <section id="testimonials"> <div class="max-w-6xl px-5 mx-auto mt-32 text-center"> <h2 class="text-4xl font-bold text-center"> What's Different About Manage? </h2> <div class="flex flex-col mt-24 md:flex-row md:space-x-6"> <!-- single testimonial start --> <div class="flex flex-col items-center p-6 space-y-6 rounded-lg bg-veryLightGray md:w-1/3"> <img src="img/avatar-anisha.png" class="w-16 -mt-14 "> <h5 class="text-lg font-bold">Anisha Li</h5> <p class="text-sm text-darkGrayishBlue"> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Itaque, repellendus! </p> </div> <!-- single testimonial end --> <!-- single testimonial start --> <div class="hidden flex-col items-center p-6 space-y-6 rounded-lg bg-veryLightGray md:flex md:w-1/3"> <img src="img/avatar-ali.png" class="w-16 -mt-14 "> <h5 class="text-lg font-bold">Ali Hossain</h5> <p class="text-sm text-darkGrayishBlue"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Enim perferendis labore molestias impedit eveniet qui veniam? </p> </div> <!-- single testimonial end --> <!-- single testimonial start --> <div class="hidden flex-col items-center p-6 space-y-6 rounded-lg bg-veryLightGray md:flex md:w-1/3"> <img src="img/avatar-shanai.png" class="w-16 -mt-14 "> <h5 class="text-lg font-bold">Shanai Mahbub</h5> <p class="text-sm text-darkGrayishBlue"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Pariatur, nam! Fuga reiciendis mollitia iusto numquam non laboriosam, at accusamus placeat facilis, dolorum, esse recusandae? </p> </div> <!-- single testimonial end --> <!-- single testimonial start --> <div class="hidden flex-col items-center p-6 space-y-6 rounded-lg bg-veryLightGray md:flex md:w-1/3"> <img src="img/avatar-richard.png" class="w-16 -mt-14 "> <h5 class="text-lg font-bold">Richard Jak</h5> <p class="text-sm text-darkGrayishBlue"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Debitis ullam iure enim inventore rerum voluptatem nostrum necessitatibus? Ab porro nostrum labore quae blanditiis eum eveniet? </p> </div> <!-- single testimonial end --> </div> <div class="my-16"> <!-- button --> <a href="#" class="p-3 px-6 pt-2 text-white bg-brightRed rounded-full baseline hover:bg-brightRedLight"> Get Started </a> <!-- button end --> </div> </div> </section> <!-- Testimonials Section end --> <!-- CTA section start --> <section id="cta" class="bg-brightRed"> <div class="container flex flex-col items-center justify-between px-6 py-24 mx-auto space-y-12 md:py-12 md:flex-row md:space-y-0"> <h2 class="text-5xl font-bold leading-tight text-center text-white md:text-4xl md:max-w-xl md:text-left"> Simplify how your team works today </h2> <a href="#" class="p-3 px-6 pt-2 text-brightRed bg-white rounded-full baseline shadow-2xl hover:bg-gray-900"> Get Started </a> </div> </section> <!-- CTA section end -->` <!-- Footer --> <footer class="bg-veryDarkBlue"> <div class="container flex flex-col-reverse justify-between px-6 py-10 mx-auto space-y-8 md:flex-row md:space-y-0"> <!-- logo & social link start --> <div class="flex flex-col-reverse items-center justify-between space-y-12 md:flex-col md:space-y-0 md:items-start"> <div class="mx-auto my-6 text-center text-white md:hidden"> Copyright &copy; 2023, All Rights Reserved </div> <div> <img src="img/logo-white.svg" class="h-8"> </div> <div class="flex pt-4 justify-center space-x-4"> <a href="#"> <img src="img/icon-facebook.svg"> </a> <a href="#"> <img src="img/icon-instagram.svg"> </a> <a href="#"> <img src="img/icon-pinterest.svg"> </a> <a href="#"> <img src="img/icon-twitter.svg"> </a> <a href="#"> <img src="img/icon-youtube.svg"> </a> </div> </div> <!-- logo & social link end --> <!-- list container start --> <div class="flex justify-around space-x-32"> <div class="flex flex-col space-y-3 text-white"> <a href="#" class="hover:text-brightRed">Home</a> <a href="#" class="hover:text-brightRed">Pricing</a> <a href="#" class="hover:text-brightRed">Products</a> <a href="#" class="hover:text-brightRed">About Us</a> </div> <div class="flex flex-col space-y-3 text-white"> <a href="#" class="hover:text-brightRed">Careers</a> <a href="#" class="hover:text-brightRed">Community</a> <a href="#" class="hover:text-brightRed">Privacy Policy</a> </div> </div> <!-- list container end --> <!-- input container start --> <div class="flex flex-col justify-between"> <form action=""> <div class="flex space-x-3"> <input type="text" class="flex-1 px-4 rounded-full focus:outline-none" placeholder="Updaterd in your inbox"> <button class="px-6 py-2 text-white rounded-full bg-brightRedLight focus:outline-none"> Go </button> </div> </form> <div class="hidden text-white md:block"> Copyright &copy; 2023, All Rights Reserved </div> </div> <!-- input container end --> </div> </footer> <!-- Footer end --> <script src="js/script.js"></script> </body> </html>
package main import ( "context" "fmt" "net" _ "github.com/go-microservice-boilerplate/app/proxy/docs" "github.com/go-microservice-boilerplate/pkg/config" "github.com/go-microservice-boilerplate/pkg/helper" "github.com/go-microservice-boilerplate/pkg/log" "github.com/go-microservice-boilerplate/pkg/utils" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/proxy" "github.com/gofiber/swagger" "go.uber.org/fx" ) // @title go-microservice-boilerplate API Documentation // @version 1.0 // @description This is a sample server for go-microservice-boilerplate API Documentation. // @host localhost:8000 // @BasePath /api // @schemes http func main() { fx.New( fx.Provide(config.New), fx.Provide(log.New), fx.Provide(func() *fiber.App { return fiber.New(fiber.Config{ AppName: "Proxy", ErrorHandler: helper.ErrorHandler, }) }), fx.Invoke(func(lc fx.Lifecycle, app *fiber.App, cfg *config.Config, l *log.Logger) { app.Use(logger.New()) app.Get("/api/swagger/*", swagger.HandlerDefault) app.All("/api/v1*", func(c *fiber.Ctx) error { path, err := utils.SplitProxyPath(c, "/api/v1") if err != nil { return fiber.ErrNotFound } if err := proxy.Do(c, utils.GenerateURL(path, utils.OutgoingPath{ Version: "v1", HostSplit: "-api", Port: cfg.API.Port, })); err != nil { return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Cannot %s %s", c.Method(), c.Path())) } c.Response().Header.Del(fiber.HeaderServer) return nil }) lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { go app.Listen(net.JoinHostPort("", cfg.Proxy.Port)) return nil }, OnStop: func(ctx context.Context) error { return app.Shutdown() }, }) }), ). Run() }
#ifndef SMARTCARD_CARD_H #define SMARTCARD_CARD_H /* smartcard/card.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2017 by Bundesamt für Sicherheit in der Informationstechnik Software engineering by Intevation GmbH Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <vector> #include <string> namespace Kleo { namespace SmartCard { class ReaderStatus; /** Class to work with Smartcards or other Hardware tokens. */ class Card { public: enum AppType { UnknownApplication, OpenPGPApplication, NksApplication, P15Application, DinSigApplication, GeldkarteApplication, NumAppTypes }; enum PinState { UnknownPinState, NullPin, PinBlocked, NoPin, PinOk, NumPinStates }; enum Status { NoCard, CardPresent, CardActive, CardUsable, _NumScdStates, CardError = _NumScdStates, NumStates }; Card(); virtual ~Card() {} virtual bool operator == (const Card& other) const; bool operator != (const Card& other) const; void setStatus(Status s); Status status() const; virtual void setSerialNumber(const std::string &sn); std::string serialNumber() const; AppType appType() const; void setAppType(AppType type); void setAppVersion(int version); int appVersion() const; std::vector<PinState> pinStates() const; void setPinStates(std::vector<PinState> pinStates); void setSlot(int slot); int slot() const; bool hasNullPin() const; void setHasNullPin(bool value); bool canLearnKeys() const; void setCanLearnKeys(bool value); private: bool mCanLearn; bool mHasNullPin; Status mStatus; std::string mSerialNumber; AppType mAppType; int mAppVersion; std::vector<PinState> mPinStates; int mSlot; }; } // namespace Smartcard } // namespace Kleopatra #endif // SMARTCARD_CARD_H
import Head from "next/head" import Image from "next/image" import { useState } from "react" import { SubmitHandler, useForm } from "react-hook-form"; import useAuth from "../hooks/useAuth"; import ExceptionHandler from "../utils/ExceptionHandler"; interface Inputs { email: string; password: string; } function Login() { const [ login, setLogin ] = useState(false); const { signIn, signUp, error } = useAuth(); const { register, handleSubmit, watch, formState: { errors }, } = useForm<Inputs>(); const onSubmit: SubmitHandler<Inputs> = async (data) => { if(login) { await signIn(data.email, data.password); } else { await signUp(data.email, data.password); } }; return ( <div className="relative flex h-screen w-screen flex-col bg-black md:items-center md:justify-center md:bg-transparent"> <Head> <title>Netflix</title> <link rel="icon" href="/favicon.ico" /> </Head> <Image src="https://rb.gy/p2hphi" layout="fill" className="-z-10 !hidden opacity-60 sm:!inline" objectFit="cover" /> <img src="https://rb.gy/ulxxee" alt="Logo Netflix" className="absolute left-4 top-4 cursor-pointer object-contain md:left-10 md:top-6" width={150} height={150}/> <form className="relative mt-24 space-y-8 rounded bg-black/75 py-10 px-6 md:mt-0 md:max-w-md md:px-14" onSubmit={handleSubmit(onSubmit)}> <h1 className="text-4xl font-semibold"> Sign In</h1> <div className="space-y-4"> {error && <div className="relative px-5 py-2 rounded bg-orange-500 text-white"> {ExceptionHandler(error)}</div> } <label className="inline-block w-full"> <input type="email" placeholder="E-mail" className="input" {...register('email', {required:true})} /> {errors.email && <p className="p-1 text-[13px] font-light text-orange-500"> Please enter a valid email. </p>} </label> <label className="inline-block w-full"> <input type="password" placeholder="Password" className="input" {...register('password', {required:true})} /> {errors.password && <p className="p-1 text-[13px] font-light text-orange-500"> Your password mus contain between 4 and 60 characters. </p>} </label> </div> <button className="w-full rounded bg-[#e50914] py-3 font-semibold" onClick={() => setLogin(true)} >Sign In</button> <div className="text-[gray]"> New to Netflix?{" "} <button type="submit" className="text-white hover:underline" onClick={() => setLogin(false)} >Sign up now</button> </div> </form> </div> ) } export default Login
.\" This program is free software; you can redistribute it and/or modify it .\" under the terms of the GNU General Public License as published by the .\" Free Software Foundation; version 2. .\" .\" This program is distributed in the hope that it will be useful, but .\" WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General .\" Public License for more details. .\" .\" You should have received a copy of the GNU General Public License along .\" with this library; if not, write to the Free Software Foundation, Inc., .\" 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. .\" .\" See /usr/share/common-licenses/GPL-2 .\" .de URL \\$2 \(laURL: \\$1 \(ra\\$3 .. .if \n[.g] .mso www.tmac .TH game-data-packager 6 2015-09-09 .SH NOM game\-data\-packager \- construit des packages (.deb|.rpm|...) à partir des données de jeux . .SH SYNOPSIS \fBgame\-data\-packager\fR [\fIOPTIONS\fR] \fIJEU\fR [\fIOPTIONS\fR] [\fIOPTIONS LIÉES À CHAQUE JEU\fR] .SH DESCRIPTION De nombreux jeux open-source ont besoin de données qui sont licensées en des termes incompatibles avec les Principes du logiciel libre selon Debian .I ("Debian Free Software Guidelines") ainsi que des bonnes pratiques d''autre distribution Linux, ou bien qui ne sont pas du tout redistribuables légalement. . .br .B game\-data\-packager est un outil qui vous aide a assembler localement des packages contenant des données provenant de CD-ROMs, d'Internet ou d'ailleurs. .SH OPTIONS .TP \fB\-\-package\fR \fIPACKAGE\fR, \fB-p\fR \fIPACKAGE\fR Pour les jeux qui produisent plusieurs packages, ne produire que celui qui est spécifié. Cette option peut être utilisée plusieurs fois. Par exemple, .B game\-data\-packager quake2 \-i \-pquake2\-groundzero \-pquake2\-reckoning permettra de mettre à jour les deux extensions de Quake II (Ground Zero et The Reckoning), qui contiennent des modules compilés, sans devoir mettre à jour les données de base ou le package de musique. .TP .BR \-\-target\-format " " arch | deb | rpm Produit des packages dans le format désiré. Tous les formats, mis à part .B deb sont actuellement considérés comme experimentaux. Le format par défaut est celui du système sur lequel .B game\-data\-packager est exécuté. .TP .BR \-\-target\-distro " " fedora | suse | ... Pour les formats partagés par plusieurs distributions ( .BR rpm actuellement), suivre les particularités d'une distribution particulière. Ceci est aussi détecté automatiquement. .TP .BR \-i | \-\-install installer dirrectement le package créé avec .I \-\-install\-method et .IR \-\-gain\-root\-command . .TP .BR \-\-install\-method " " apt | dpkg | gdebi | gdebi\-gtk | gdebi\-kde | dnf | zypper | urpmi | rpm Installe les packages avec la commande désirée. Les commandes disponibles dépendent du format choisi avec .B \-\-target\-format . .TP .BR \-\-gain\-root\-command " " pkexec | sudo | su | super | really | \fICOMMAND\fR Utiliser la commande "préfixe" pour obtenir les droits superutilisateur. .B su correspond à la commande .B "su -c" les autres options correspondent à un adverbe ajouté devant la commande, de cette façon: .B "sudo dpkg -i ..." ou .BR "pkexec rpm -U ..." . .TP \fB\-d\fR \fIRÉPERTOIRE-DE-DESTINATION\fR | \fB\-\-destination\fR \fIRÉPERTOIRE-DE-DESTINATION\fR écrire les packages .deb|.rpm générés dans le répertoire désigné. .TP .B \-n | \-\-no\-install Ne pas installer les packages générés. .TP .B \-z | --compress Compresser les packages. (option par défaut si \-i n'est pas spécifié) .TP .B \-\-binary\-executables Autoriser la création de packages contenant du code binaire sans source disponible. Comme cela représente un risque de sécurité cela est désactivé par défaut. Ceci est par exemple nécessaire pour Quake 4 et Unreal. .TP .B --no\-compress Ne pas compresser les packages (option par défaut quand on utilise \-i) .TP .B \-\-download Télécharge automatiquement les fichiers manquant à partir d'Internet si possible. C'est le paramètre par défaut. .B \-\-no\-download Ne rien télécharger d'Internet. Si les fichiers manquants ne sont pas vraiment importants (documentation par exemple), des packages seront générés sans ces fichiers. Si par contre ces fichiers/patches sont indispensables, aucun package ne sera généré. .TP \fB\-\-save\-downloads\fR \fIRÉPERTOIRE\fR S'il y a lieu de télécharger des fichiers, les conserver dans \fIRÉPERTOIRE\fR. .TP .B \-\-verbose Donner plus de détails sur le traitement effectuée, en particulier celui effectué par les outils externes (innoextract, unarj...). .TP .B \-\-no\-verbose Ne pas afficher de détails supplémentaires, paramètre par défaut. .TP .B \-\-debug Afficher des informations utiles aux dévelopeurs de .B game\-data\-packager .TP .I JEU Nom-code du jeu à packager. Executer .B game\-data\-packager sans aucun paramètre afficher une liste des jeux possible. .SH OPTIONS LIÉES À CHAQUE JEU Certains jeux disposent d'options spécifiques. Executer \fBgame\-data\-packager\fR \fIJEU\fR \fB\-\-help\fR affichera les options spécifiques à ce jeu. .SH AUTRE FONCTIONNALITÉS .B game\-data\-packager steam [ .I \-i ] [ .I \-d répertoire-de-destination [ .I \-n ] ] [ .I \-z | --no\-compress ] [ .I --new | .I --all ] .br créera des packages pour tous vos jeux Steam compatibles en une fois. .br La plupart de ces jeux ne peuvent être téléchargés qu'avec la version 'Windows' de Steam qui aussi peux être exécutée via Wine; ou en utilisant l'utilitaire .B steamcmd . .TP .B --new ne créer de package .deb que pour les nouveaux jeux pas encore installés .TP .B --all créer tous les packages possibles .PP .B game\-data\-packager gog .br comparera tous vos jeux GOG.com avec ceux supportés par cet outil. .br Ensuite, chaque jeu doit être empacketé séparément. .SH VARIABLES D'ENVIRONNEMENT .TP .B LANGUAGE, LANG Lorsqu'un jeu est disponible en plusieurs langues, ces variables d'environment seront utilisées pour choisir la bonne version. .br Ces variables sont normallement déjà correctement configurées par votre environnement de bureau. .br Si le jeu n'est pas disponible en Français, l'Anglais est alors accepté comme alternative valable. .SH RÉPERTOIRES game\-data\-packager trouvera automatiquement les données utiles entre autres présentes dans ces répertoires: .TP .B ~/.steam/SteamApps/common/<game>/ .TP .B ~/.wine/drive_c/Program Files/Steam/SteamApps/common/<game>/ ainsi que l'équivalent ~/.PlayOnLinux/wineprefix/Steam/drive_c/... .TP .B X:/Program Files/Steam/SteamApps/common/<game>/ ou X:\\ est n'importe quel partition VFAT ou NTFS actuellement montée. .SH FICHIERS .TP .B /etc/game-data-packager.conf fichier de configuration de game-data-packager. .TP .B ~/.scummvmrc fournit l'emplacement des jeux enregistrés dans le launcher de ScummVM. .TP .B ~/.steam/config/loginusers.vdf est utilisé pour trouver l'ID Steam de l'utilisateur, qui sert ensuite à télécharger une liste des jeux possédés par l'utilisateur. .TP .B ~/.cache/lgogdownloader/gamedetails.json reprend une copie de la liste des jeux GOG.com achetés par l'utilisateur .SH VOIR AUSSI \fIpkexec\fP(1), \fIsudo\fP(8), \fIsu\fP(1), \fIlgogdownloader\fP(1) .br Project homepage: .URL "https://wiki.debian.org/fr/Games/GameDataPackager" .SH AUTEUR Copyright \(co 2015 Alexandre Detiste \fI<alexandre@detiste.be>\fP .br Traduis à partir de la version en anglais.
"use client"; import { ShowsidebarProvider } from "@/lib/context/show-sidebar-context"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { ThemeProvider } from "next-themes"; import { useState } from "react"; const Providers = ({ children, showSidebar, }: { children: React.ReactNode; showSidebar: boolean; }) => { const [queryClient] = useState( () => new QueryClient({ defaultOptions: { queries: { staleTime: 1 * 5000, }, }, }) ); return ( <ThemeProvider attribute="class" defaultTheme="system" enableSystem> <QueryClientProvider client={queryClient}> <ShowsidebarProvider showSidebar={showSidebar}> {children} </ShowsidebarProvider> {<ReactQueryDevtools initialIsOpen={false} />} </QueryClientProvider> </ThemeProvider> ); }; export default Providers;
package com.example.ejemplo.model; import java.time.LocalDateTime; import java.util.Objects; /** * Clase que representa una publicación en un foro. */ public class Post { private Long postId; // Clave Primaria private Forum forum; // Foro al que pertenece la publicación private User author; // Autor de la publicación private final String title; // Título de la publicación private final String content; // Contenido de la publicación private final LocalDateTime dateTime; // Fecha y hora de la publicación /** * Constructor de la clase Post. * * @param postId Identificador único de la publicación. * @param forum Foro al que pertenece la publicación. * @param author Autor de la publicación. * @param title Título de la publicación. * @param content Contenido de la publicación. * @param dateTime Fecha y hora de la publicación. */ public Post(Long postId, Forum forum, User author, String title, String content, LocalDateTime dateTime) { this.postId = postId; this.forum = forum; this.author = author; this.title = title; this.content = content; this.dateTime = dateTime; } public Long getPostId() { return postId; } public void setPostId(Long postId) { this.postId = postId; } public Forum getForum() { return forum; } public void setForum(Forum forum) { this.forum = forum; } public User getAuthor() { return author; } public void setAuthor(User author) { this.author = author; } public String getTitle() { return title; } public String getContent() { return content; } public LocalDateTime getDateTime() { return dateTime; } /** * Indica si el objeto Post es igual a otro objeto dado. * * @param o Objeto a comparar. * @return true si son iguales, false en caso contrario. */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Post post = (Post) o; return Objects.equals(postId, post.postId) && Objects.equals(forum, post.forum) && Objects.equals(author, post.author) && Objects.equals(title, post.title) && Objects.equals(content, post.content) && Objects.equals(dateTime, post.dateTime); } /** * Calcula el código hash del objeto Post. * * @return El código hash del objeto Post. */ @Override public int hashCode() { return Objects.hash(postId, forum, author, title, content, dateTime); } /** * Devuelve una representación en forma de cadena del objeto Post. * * @return La representación en forma de cadena del objeto Post. */ @Override public String toString() { return "Post{" + "postId=" + postId + ", forum=" + forum + ", author=" + author + ", title='" + title + '\'' + ", content='" + content + '\'' + ", dateTime=" + dateTime + '}'; } }
const mockedUsedNavigate = jest.fn(); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: () => mockedUsedNavigate, })); import { fireEvent, render, screen, cleanup } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import FrontCard from '../components/FrontCard'; import { EventActivity } from '../model/Event'; describe('FrontCard component', () => { //afterEach(cleanup) it('renders frontCard without errors', () => { render(<FrontCard searchText={''} />); }); it('renders checkbox label online without errors', () => { render(<FrontCard searchText={''} />); const onlineCheck = screen.getAllByLabelText( 'Online', )[0] as HTMLAnchorElement; expect(onlineCheck).toBeInTheDocument(); }); it('renders checkbox label live without errors', () => { render(<FrontCard searchText={''} />); const onsiteCheck = screen.getAllByLabelText( 'Live', )[0] as HTMLAnchorElement; expect(onsiteCheck).toBeInTheDocument(); }); it('renders online checkbox input without errors', () => { render(<FrontCard searchText={''} />); const onlineBox = screen.getAllByRole('checkbox')[0] as HTMLAnchorElement; expect(onlineBox).not.toBeChecked(); }); it('renders onsite checkbox input without errors', () => { render(<FrontCard searchText={''} />); const onsiteBox = screen.getAllByRole('checkbox')[1] as HTMLAnchorElement; expect(onsiteBox).not.toBeChecked(); }); it('renders activity title, location, description and date', () => { const testData: EventActivity = { id: 234, title: '', description: '', imgUrl: '', date: '', location: '', attending: false, comments: [], creator: '', }; render(<FrontCard searchText={''} />); screen.getAllByText(testData.title, { exact: false }); screen.getAllByText(testData.location, { exact: false }); screen.getAllByText(testData.description, { exact: false }); screen.getAllByText(testData.date, { exact: false }); }); it('renders image correctly with src imgUrl', () => { const { getAllByAltText } = render(<FrontCard searchText={''} />); const image = getAllByAltText('event icon')[0] as HTMLAnchorElement; expect(image).toHaveAttribute( 'src', 'https://images.unsplash.com/photo-1588286840104-8957b019727f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80', ); }); it('shows read more button responding correctly', () => { render(<FrontCard searchText={''} />); const button = screen.queryAllByText('Read more')[0] as HTMLAnchorElement; fireEvent.click(button); expect(button).toBeEnabled(); }); });
//Template_Literals 1.Multiline Strings a) console.log("string text line 1\n" + "string text line 2"); b) console.log(`string text line 1 string text line 2`); 2.String interpolation const a = 20; const b = 4; a) console.log("Twentyfour is " + (a + b) + " and\nnot " + (2 * a + b) + "."); b) console.log(`Twentyfour is ${a + b} andnot ${2 * a + b}.`); 3.Nesting templates a) let classes = "start screen"; classes += isLargeScreen() ? "" : item.isCollapsed ? " icon-expander" : " icon-collapser"; b) const classes = `start screen ${isLargeScreen() ? "" : item.isCollapsed ? "icon-expander" : "icon-collapser"}`; c) const classes = `start screen ${isLargeScreen() ? "" : `icon-${item.isCollapsed ? "expander" : "collapser"}`}`; 4.To escape a backtick a) `\`` === "`"; // true 5.To use dollar sign a) `\${1}` === "${1}"; // true
var express = require('express'); var router = express.Router(); let HAM = require('@harvardartmuseums/ham'); let applicationInfo = { title: 'Object Stories', description: 'Experimental templates for art' }; let ham = new HAM(process.env.HAM_APIKEY); /* GET home page. */ router.get('/', async function(req, res, next) { res.render('index', { about: applicationInfo }); }); router.get('/object/:id', async function(req, res, next) { let object = await ham.Objects.get(req.params.id); let template = "basic"; if (object.classification == "Coins"){ template = "coins"; // try to cut the description into the obverse and reverse sides var startIndex = object.description.indexOf("Obv.: "); var endIndex = object.description.indexOf("\r\n\r\n", startIndex); if (startIndex !== -1 && endIndex !== -1) { // Extract the content between "Obv.: " and "\r\n\r\n" object.coinObv = object.description.substring(startIndex + "Obv.: ".length, endIndex); object.coinRev = object.description.substring(endIndex + "\r\n\r\nRev.: ".length); } else { var endIndex = object.description.indexOf("\r\n", startIndex); if (startIndex !== -1 && endIndex !== -1){ object.coinObv = object.description.substring(startIndex + "Obv.: ".length, endIndex); object.coinRev = object.description.substring(endIndex + "\r\nRev.: ".length); } } } // run additional stats and aggregations // try to count the number of entries in the provenance description object.provenancecount = 0; if (object.provenance !== null) { object.provenancecount = (object.provenance.match(/\r\n/g) || []).length; } // try to extract the dimensions of the painting only (not frame) var endIndex = object.dimensions.indexOf("framed"); if (endIndex !== -1) { // Extract the content before "framed" object.dimNoFrame = object.dimensions.substring(0, endIndex); } else { var endIndex = object.dimensions.indexOf("frame"); if (endIndex !== -1){ object.dimNoFrame = object.dimensions.substring(0, endIndex); } } // append a "pretty print" version of the raw JSON; use to display the JSON directly on a web page object.raw = JSON.stringify(object, null, "\t"); if (object.gallery) { let gallery = await ham.Galleries.get(object.gallery.galleryid); object.gallery.details = gallery; // can add gallery to line 46 } // send the data to the template res.render('story-templates/'+template, {about: applicationInfo, data: object}); }); /* GET home page. */ router.get('/', async function(req, res, next) { res.render('index', { about: applicationInfo }); }); router.get('/object/:id/coolpage', async function(req, res, next) { let object = await ham.Objects.get(req.params.id); let params = {image:object.images[0].imageid,q:'type:face AND source:"AWS Rekognition"'}; let annotations = await ham.Annotations.search(params); if (annotations.records.length === 1){ object.pose = annotations["records"][0]["raw"]["Pose"]; } // append a "pretty print" version of the raw JSON; use to display the JSON directly on a web page object.raw = JSON.stringify(object, null, "\t"); res.render('story-templates/advanced', {about: applicationInfo, data: object}); }); // router.get('/object/:id', async function(req, res, next) { // let object = await ham.Objects.get(req.params.id) // // run additional stats and aggregations // // try to count the number of entries in the provenance description // object.provenancecount = 0; // if (object.provenance !== null) { // object.provenancecount = (object.provenance.match(/\r\n/g) || []).length; // } // // append a "pretty print" version of the raw JSON; use to display the JSON directly on a web page // object.raw = JSON.stringify(object, null, "\t"); // // send the data to the template // res.render('story-templates/basic', {about: applicationInfo, data: object}); // }); module.exports = router;
"""Conditional MNL model.""" import logging import numpy as np import pandas as pd import tensorflow as tf from .base_model import ChoiceModel class MNLCoefficients(object): """Base class to specify the structure of a cLogit.""" def __init__(self): """Instantiate a MNLCoefficients object.""" # User interface self.coefficients = {} # Handled by the model self.feature_to_weight = {} def add(self, coefficient_name, feature_name, items_indexes=None, items_names=None): """Add a coefficient to the model throught the specification of the utility. Parameters ---------- coefficient_name : str Name given to the coefficient. feature_name : str features name to which the coefficient is associated. It should work with the names given in the ChoiceDataset that will be used for parameters estimation. items_indexes : list of int, optional list of items indexes (in the ChoiceDataset) for which we need to add a coefficient, by default None items_names : list of str, optional list of items names (in the ChoiceDataset) for which we need to add a coefficient, by default None Raises ------ ValueError When names or indexes are both not specified. """ if items_indexes is None and items_names is None: raise ValueError("Either items_indexes or items_names must be specified") if isinstance(items_indexes, int): items_indexes = [items_indexes] if isinstance(items_names, str): items_names = [items_names] self.coefficients[coefficient_name] = { "feature_name": feature_name, "items_indexes": items_indexes, "items_names": items_names, } def add_shared(self, coefficient_name, feature_name, items_indexes=None, items_names=None): """Add a single, shared coefficient to the model throught the specification of the utility. Parameters ---------- coefficient_name : str Name given to the coefficient. feature_name : str features name to which the coefficient is associated. It should work with the names given in the ChoiceDataset that will be used for parameters estimation. items_indexes : list of int, optional list of items indexes (in the ChoiceDataset) for which the coefficient will be used, by default None items_names : list of str, optional list of items names (in the ChoiceDataset) for which the coefficient will be used, by default None Raises ------ ValueError When names or indexes are both not specified. """ if items_indexes is None and items_names is None: raise ValueError("Either items_indexes or items_names must be specified") if not coefficient_name: coefficient_name = f"beta_{feature_name}" if isinstance(items_indexes, int): logging.warning( "You have added a single index to a shared coefficient. This is not recommended.", "Returning to standard add_coefficients method.", ) self.add_coefficients(coefficient_name, feature_name, items_indexes, items_names) if isinstance(items_names, str): logging.warning( "You have added a single name to a shared coefficient. This is not recommended.", "Returning to standard add_coefficients method.", ) self.add_coefficients(coefficient_name, feature_name, items_indexes, items_names) self.coefficients[coefficient_name] = { "feature_name": feature_name, "items_indexes": [items_indexes] if items_indexes is not None else None, "items_names": items_names if items_names is not None else None, } def get(self, coefficient_name): """Getter of a coefficient specification, from its name. Parameters ---------- coefficient_name : str Name of the coefficient to get. Returns ------- dict specification of the coefficient. """ return self.coefficients[coefficient_name] def _add_tf_weight(self, weight_name, weight_index): """Create the Tensorflow weight corresponding for cLogit. Parameters ---------- weight_name : str Name of the weight to add. weight_index : int Index of the weight (in the conditionalMNL) to add. """ if weight_name not in self.coefficients.keys(): raise ValueError(f"Weight {weight_name} not in coefficients") if self.coefficients[weight_name]["feature_name"] in self.feature_to_weight.keys(): self.feature_to_weight[self.coefficients[weight_name]["feature_name"]].append( ( weight_name, weight_index, ) ) else: self.feature_to_weight[self.coefficients[weight_name]["feature_name"]] = [ ( weight_name, weight_index, ), ] @property def features_with_weights(self): """Get a list of the features that have a weight to be estimated. Returns ------- dict.keys List of the features that have a weight to be estimated. """ return self.feature_to_weight.keys() def get_weight_item_indexes(self, feature_name): """Get the indexes of the concerned items for a given weight. Parameters ---------- feature_name : str Features that is concerned by the weight. Returns ------- list List of indexes of the items concerned by the weight. int The index of the weight in the conditionalMNL weights. """ weights_info = self.feature_to_weight[feature_name] weight_names = [weight_info[0] for weight_info in weights_info] weight_indexs = [weight_info[1] for weight_info in weights_info] return [ self.coefficients[weight_name]["items_indexes"] for weight_name in weight_names ], weight_indexs @property def names(self): """Returns the list of coefficients. Returns ------- dict keys List of coefficients in the specification. """ return list(self.coefficients.keys()) class ConditionalLogit(ChoiceModel): """Conditional MNL that has a generic structure. It can be parametrized with a dictionnary. Arguments: ---------- coefficients: dict or MNLCoefficients Specfication of the model to be estimated. """ def __init__( self, coefficients=None, add_exit_choice=False, optimizer="lbfgs", lr=0.001, **kwargs, ): """Initialize of Conditional-MNL. Parameters ---------- coefficients : dict or MNLCoefficients Dictionnary containing the coefficients parametrization of the model. The dictionnary must have the following structure: {feature_name_1: mode_1, feature_name_2: mode_2, ...} mode must be among "constant", "item", "item-full" for now (same specifications as torch-choice). add_exit_choice : bool, optional Whether or not to normalize the probabilities computation with an exit choice whose utility would be 1, by default True """ super().__init__(add_exit_choice=add_exit_choice, optimizer=optimizer, lr=lr, **kwargs) self.coefficients = coefficients self.instantiated = False def add_coefficients( self, feature_name, coefficient_name="", items_indexes=None, items_names=None ): """Add a coefficient to the model throught the specification of the utility. Parameters ---------- feature_name : str features name to which the coefficient is associated. It should work with the names given in the ChoiceDataset that will be used for parameters estimation. coefficient_name : str, optional Name given to the coefficient. If not provided, name will be "beta_feature_name". items_indexes : list of int, optional list of items indexes (in the ChoiceDataset) for which we need to add a coefficient, by default None items_names : list of str, optional list of items names (in the ChoiceDataset) for which we need to add a coefficient, by default None Raises ------ ValueError When names or indexes are both not specified. """ self._add_coefficient( coefficient_name=coefficient_name, feature_name=feature_name, items_indexes=items_indexes, items_names=items_names, shared=False, ) def add_shared_coefficient( self, feature_name, coefficient_name="", items_indexes=None, items_names=None ): """Add a single, shared coefficient to the model throught the specification of the utility. Parameters ---------- feature_name : str features name to which the coefficient is associated. It should work with the names given in the ChoiceDataset that will be used for parameters estimation. coefficient_name : str, optional Name given to the coefficient. If not provided, name will be "beta_feature_name". items_indexes : list of int, optional list of items indexes (in the ChoiceDataset) for which the coefficient will be used, by default None items_names : list of str, optional list of items names (in the ChoiceDataset) for which the coefficient will be used, by default None Raises ------ ValueError When names or indexes are both not specified. """ self._add_coefficient( coefficient_name=coefficient_name, feature_name=feature_name, items_indexes=items_indexes, items_names=items_names, shared=True, ) def _add_coefficient(self, feature_name, coefficient_name, items_indexes, items_names, shared): if self.coefficients is None: self.coefficients = MNLCoefficients() elif not isinstance(self.coefficients, MNLCoefficients): raise ValueError("Cannot add coefficient on top of a dict instantiation.") coefficient_name = coefficient_name if coefficient_name else "beta_%s" % feature_name add_method = self.coefficients.add_shared if shared else self.coefficients.add add_method( coefficient_name=coefficient_name, feature_name=feature_name, items_indexes=items_indexes, items_names=items_names, ) def instantiate(self, choice_dataset): """Instantiate the model using the features in the choice_dataset. Parameters ---------- choice_dataset: ChoiceDataset Used to match the features names with the model coefficients. """ if not self.instantiated: if not isinstance(self.coefficients, MNLCoefficients): self._build_coefficients_from_dict(n_items=choice_dataset.get_n_items()) self.trainable_weights = self._instantiate_tf_weights() # Checking that no weight has been attributed to non existing feature in dataset dataset_stacked_features_names = [] if choice_dataset.shared_features_by_choice_names is not None: for i, feat_tuple in enumerate(choice_dataset.shared_features_by_choice_names): dataset_stacked_features_names.append(feat_tuple) if choice_dataset.items_features_by_choice_names is not None: for i, feat_tuple in enumerate(choice_dataset.items_features_by_choice_names): dataset_stacked_features_names.append(feat_tuple) dataset_stacked_features_names = np.concatenate(dataset_stacked_features_names).ravel() for feature_with_weight in self.coefficients.features_with_weights: if feature_with_weight != "intercept": if feature_with_weight not in dataset_stacked_features_names: raise ValueError( f"""Feature {feature_with_weight} has an attributed coefficient but is not in dataset""" ) self._store_dataset_features_names(choice_dataset) self.instantiated = True def _instantiate_tf_weights(self): """Instantiate the model from MNLCoefficients object. Returns ------- list of tf.Tensor List of the weights created coresponding to the specification. """ weights = [] for weight_nb, weight_name in enumerate(self.coefficients.names): n_weights = ( len(self.coefficients.get(weight_name)["items_indexes"]) if self.coefficients.get(weight_name)["items_indexes"] is not None else len(self.coefficients.get(weight_name)["items_names"]) ) weight = tf.Variable( tf.random_normal_initializer(0.0, 0.02, seed=42)(shape=(1, n_weights)), name=weight_name, ) weights.append(weight) self.coefficients._add_tf_weight(weight_name, weight_nb) self.trainable_weights = weights return weights def _build_coefficients_from_dict(self, n_items): """Build coefficients when they are given as a dictionnay. Parameters ---------- n_items : int Number of different items in the assortment. Used to create the right number of weights. """ coefficients = MNLCoefficients() for weight_counter, (feature, mode) in enumerate(self.coefficients.items()): if mode == "constant": coefficients.add_shared( feature + f"_w_{weight_counter}", feature, list(range(n_items)) ) elif mode == "item": coefficients.add(feature + f"_w_{weight_counter}", feature, list(range(1, n_items))) elif mode == "item-full": coefficients.add(feature + f"_w_{weight_counter}", feature, list(range(n_items))) else: raise ValueError(f"Mode {mode} not recognized.") self.coefficients = coefficients def _store_dataset_features_names(self, dataset): """Register the name of the features in the dataset. For later use in utility computation. Parameters ---------- dataset : ChoiceDataset ChoiceDataset used to fit the model. """ self._shared_features_by_choice_names = dataset.shared_features_by_choice_names self._items_features_by_choice_names = dataset.items_features_by_choice_names def compute_batch_utility( self, shared_features_by_choice, items_features_by_choice, available_items_by_choice, choices, verbose=1, ): """Compute the utility when the model is constructed from a MNLCoefficients object. Parameters ---------- shared_features_by_choice : tuple of np.ndarray (choices_features) a batch of shared features Shape must be (n_choices, n_shared_features) items_features_by_choice : tuple of np.ndarray (choices_items_features) a batch of items features Shape must be (n_choices, n_items_features) available_items_by_choice : np.ndarray A batch of items availabilities Shape must be (n_choices, n_items) choices: np.ndarray Choices Shape must be (n_choices, ) verbose : int, optional Parametrization of the logging outputs, by default 1 Returns ------- tf.Tensor Utilities corresponding of shape (n_choices, n_items) """ _ = choices n_items = available_items_by_choice.shape[1] n_choices = available_items_by_choice.shape[0] items_utilities_by_choice = [] if not isinstance(shared_features_by_choice, tuple): shared_features_by_choice = (shared_features_by_choice,) if not isinstance(items_features_by_choice, tuple): items_features_by_choice = (items_features_by_choice,) # Shared features if self._shared_features_by_choice_names is not None: for i, feat_tuple in enumerate(self._shared_features_by_choice_names): for j, feat in enumerate(feat_tuple): if feat in self.coefficients.features_with_weights: ( item_index_list, weight_index_list, ) = self.coefficients.get_weight_item_indexes(feat) for item_index, weight_index in zip(item_index_list, weight_index_list): partial_items_utility_by_choice = tf.zeros((n_choices, n_items)) partial_items_utility_by_choice = [ tf.zeros(n_choices) for _ in range(n_items) ] for q, idx in enumerate(item_index): if isinstance(idx, list): for k in idx: tf.cast(shared_features_by_choice[i][:, j], tf.float32) compute = tf.multiply( shared_features_by_choice[i][:, j], self.trainable_weights[weight_index][:, q], ) partial_items_utility_by_choice[k] += compute else: compute = tf.multiply( tf.cast(shared_features_by_choice[i][:, j], tf.float32), self.trainable_weights[weight_index][:, q], ) partial_items_utility_by_choice[idx] += compute items_utilities_by_choice.append( tf.cast( tf.stack(partial_items_utility_by_choice, axis=1), tf.float32 ) ) elif verbose > 0: logging.info( f"Feature {feat} is in dataset but has no weight assigned\ in utility computations" ) # Items features if self._items_features_by_choice_names is not None: for i, feat_tuple in enumerate(self._items_features_by_choice_names): for j, feat in enumerate(feat_tuple): if feat in self.coefficients.features_with_weights: ( item_index_list, weight_index_list, ) = self.coefficients.get_weight_item_indexes(feat) for item_index, weight_index in zip(item_index_list, weight_index_list): partial_items_utility_by_choice = tf.zeros((n_choices, n_items)) for q, idx in enumerate(item_index): if isinstance(idx, list): for k in idx: partial_items_utility_by_choice = tf.concat( [ partial_items_utility_by_choice[:, :k], tf.expand_dims( tf.multiply( tf.cast( items_features_by_choice[i][:, k, j], tf.float32, ), self.trainable_weights[weight_index][:, q], ), axis=-1, ), partial_items_utility_by_choice[:, k + 1 :], ], axis=1, ) else: partial_items_utility_by_choice = tf.concat( [ partial_items_utility_by_choice[:, :idx], tf.expand_dims( tf.multiply( tf.cast( items_features_by_choice[i][:, idx, j], tf.float32, ), self.trainable_weights[weight_index][:, q], ), axis=-1, ), partial_items_utility_by_choice[:, idx + 1 :], ], axis=1, ) items_utilities_by_choice.append( tf.cast(partial_items_utility_by_choice, tf.float32) ) elif verbose > 0: logging.info( f"Feature {feat} is in dataset but has no weight assigned\ in utility computations" ) if "intercept" in self.coefficients.features_with_weights: item_index_list, weight_index_list = self.coefficients.get_weight_item_indexes( "intercept" ) for item_index, weight_index in zip(item_index_list, weight_index_list): partial_items_utility_by_choice = tf.zeros((n_items,)) for q, idx in enumerate(item_index): partial_items_utility_by_choice = tf.concat( [ partial_items_utility_by_choice[:idx], self.trainable_weights[weight_index][:, q], partial_items_utility_by_choice[idx + 1 :], ], axis=0, ) partial_items_utility_by_choice = tf.stack( [partial_items_utility_by_choice] * n_choices, axis=0 ) items_utilities_by_choice.append( tf.cast(partial_items_utility_by_choice, tf.float32) ) return tf.reduce_sum(items_utilities_by_choice, axis=0) def fit(self, choice_dataset, get_report=False, **kwargs): """Fit function to estimate the paramters. Parameters ---------- choice_dataset : ChoiceDataset Choice dataset to use for the estimation. get_report: bool, optional Whether or not to compute a report of the estimation, by default False Returns ------- dict dict with fit history. """ self.instantiate(choice_dataset) fit = super().fit(choice_dataset=choice_dataset, **kwargs) if get_report: self.report = self.compute_report(choice_dataset) return fit def _fit_with_lbfgs( self, choice_dataset, sample_weight=None, get_report=False, **kwargs, ): """Specific fit function to estimate the paramters with LBFGS. Parameters ---------- choice_dataset : ChoiceDataset Choice dataset to use for the estimation. n_epochs : int Number of epochs to run. tolerance : float, optional Tolerance in the research of minimum, by default 1e-8 get_report: bool, optional Whether or not to compute a report of the estimation, by default False Returns ------- dict dict with fit history. """ self.instantiate(choice_dataset) fit = super()._fit_with_lbfgs( dataset=choice_dataset, sample_weight=sample_weight, **kwargs, ) if get_report: self.report = self.compute_report(choice_dataset) return fit def compute_report(self, dataset): """Compute a report of the estimated weights. Parameters ---------- dataset : ChoiceDataset ChoiceDataset used for the estimation of the weights that will be used to compute the Std Err of this estimation. Returns ------- pandas.DataFrame A DF with estimation, Std Err, z_value and p_value for each coefficient. """ import tensorflow_probability as tfp weights_std = self.get_weights_std(dataset) dist = tfp.distributions.Normal(loc=0.0, scale=1.0) names = [] z_values = [] estimations = [] p_z = [] i = 0 for weight in self.trainable_weights: for j in range(weight.shape[1]): if weight.shape[1] > 1: names.append(f"{weight.name[:-2]}_{j}") else: names.append(f"{weight.name[:-2]}") estimations.append(weight.numpy()[0][j]) z_values.append(weight.numpy()[0][j] / weights_std[i].numpy()) p_z.append(2 * (1 - dist.cdf(tf.math.abs(z_values[-1])).numpy())) i += 1 return pd.DataFrame( { "Coefficient Name": names, "Coefficient Estimation": estimations, "Std. Err": weights_std.numpy(), "z_value": z_values, "P(.>z)": p_z, }, ) def get_weights_std(self, dataset): """Approximates Std Err with Hessian matrix. Parameters ---------- dataset : ChoiceDataset ChoiceDataset used for the estimation of the weights that will be used to compute the Std Err of this estimation. Returns ------- tf.Tensor Estimation of the Std Err for the weights. """ # Loops of differentiation with tf.GradientTape() as tape_1: with tf.GradientTape(persistent=True) as tape_2: model = self.clone() w = tf.concat(self.trainable_weights, axis=1) tape_2.watch(w) tape_1.watch(w) mw = [] index = 0 for _w in self.trainable_weights: mw.append(w[:, index : index + _w.shape[1]]) index += _w.shape[1] model.trainable_weights = mw batch = next(dataset.iter_batch(batch_size=-1)) utilities = model.compute_batch_utility(*batch) probabilities = tf.nn.softmax(utilities, axis=-1) loss = tf.keras.losses.CategoricalCrossentropy(reduction="sum")( y_pred=probabilities, y_true=tf.one_hot(dataset.choices, depth=probabilities.shape[1]), ) # Compute the Jacobian jacobian = tape_2.jacobian(loss, w) # Compute the Hessian from the Jacobian hessian = tape_1.batch_jacobian(jacobian, w) inv_hessian = tf.linalg.inv(tf.squeeze(hessian)) return tf.sqrt([inv_hessian[i][i] for i in range(len(tf.squeeze(hessian)))]) def clone(self): """Return a clone of the model.""" clone = ConditionalLogit( coefficients=self.coefficients, add_exit_choice=self.add_exit_choice, optimizer=self.optimizer_name, ) if hasattr(self, "history"): clone.history = self.history if hasattr(self, "is_fitted"): clone.is_fitted = self.is_fitted if hasattr(self, "instantiated"): clone.instantiated = self.instantiated clone.loss = self.loss clone.label_smoothing = self.label_smoothing if hasattr(self, "report"): clone.report = self.report if hasattr(self, "trainable_weights"): clone.trainable_weights = self.trainable_weights if hasattr(self, "lr"): clone.lr = self.lr if hasattr(self, "_shared_features_by_choice_names"): clone._shared_features_by_choice_names = self._shared_features_by_choice_names if hasattr(self, "_items_features_by_choice_names"): clone._items_features_by_choice_names = self._items_features_by_choice_names return clone
"""Build openssl.""" from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING import sh from pythonforandroid.logger import shprint from pythonforandroid.recipe import Recipe from pythonforandroid.util import current_directory if TYPE_CHECKING: from typing import Any, ClassVar from pythonforandroid.archs import Arch from pythonforandroid.build import Context class OpenSSLRecipe(Recipe): """The OpenSSL libraries for python-for-android. This recipe will generate the following libraries as shared libraries (*.so): - crypto - ssl The generated openssl libraries are versioned, where the version is the recipe attribute :attr:`version` e.g.: ``libcrypto1.1.so``, ``libssl1.1.so``...so...to link your recipe with the openssl libs, remember to add the version at the end, e.g.: ``-lcrypto1.1 -lssl1.1``. Or better, you could do it dynamically using the methods: :meth:`include_flags`, :meth:`link_dirs_flags` and :meth:`link_libs_flags`. .. warning:: This recipe is very sensitive because is used for our core recipes, the python recipes. The used API should match with the one used in our python build, otherwise we will be unable to build the _ssl.so python module. .. versionchanged:: 0.6.0 - The gcc compiler has been deprecated in favour of clang and libraries updated to version 1.1.1 (LTS - supported until 11th September 2023) - Added two new methods to make easier to link with openssl: :meth:`include_flags` and :meth:`link_flags` - subclassed versioned_url - Adapted method :meth:`select_build_arch` to API 21+ - Add ability to build a legacy version of the openssl libs when using python2legacy or python3crystax. .. versionchanged:: 2019.06.06.1.dev0 - Removed legacy version of openssl libraries """ version: str = '1.1' """the major minor version used to link our recipes""" url_version: str = '1.1.1w' """the version used to download our libraries""" url: str = 'https://www.openssl.org/source/openssl-{url_version}.tar.gz' built_libraries: ClassVar[dict[str, str]] = { f'libcrypto{version}.so': '.', f'libssl{version}.so': '.', } ctx: Context @property def versioned_url(self: OpenSSLRecipe) -> str: if self.url is None: return None return self.url.format(url_version=self.url_version) def get_build_dir(self: OpenSSLRecipe, arch: str) -> str: return str( Path( self.get_build_container_dir(arch), self.name + self.version, ), ) def include_flags(self: OpenSSLRecipe, arch: Arch) -> str: """Return a string with the include folders.""" openssl_includes: str = str(Path(self.get_build_dir(arch.arch), 'include')) return ( ' ' '-I' + openssl_includes + ' ' '-I' + str(Path(openssl_includes, 'internal')) + ' ' '-I' + str(Path(openssl_includes, 'openssl')) ) def link_dirs_flags(self: OpenSSLRecipe, arch: Arch) -> str: """Return a string with the appropriate `-L<lib directory>` to link with the openssl libs. This string is usually added to the environment variable `LDFLAGS` """ return ' -L' + self.get_build_dir(arch.arch) def link_libs_flags(self: OpenSSLRecipe) -> str: """Return the appropriate `-l<lib>` flags to link with the openssl libs. This string is usually added to the environment variable `LIBS` """ return f' -lcrypto{self.version} -lssl{self.version}' def link_flags(self: OpenSSLRecipe, arch: Arch) -> str: """Return the flags to link with the openssl libraries. Format: `-L<lib directory> -l<lib>` """ return self.link_dirs_flags(arch) + self.link_libs_flags() def get_recipe_env(self: OpenSSLRecipe, arch: Arch | None = None) -> dict[str, Any]: env = super().get_recipe_env(arch) env['OPENSSL_VERSION'] = self.version env['MAKE'] = 'make' # This removes the '-j5', which isn't safe env['CC'] = 'clang' env['ANDROID_NDK_HOME'] = self.ctx.ndk_dir return env def select_build_arch(self: OpenSSLRecipe, arch: Arch) -> str: aname = arch.arch if 'arm64' in aname: return 'android-arm64' if 'v7a' in aname: return 'android-arm' if 'arm' in aname: return 'android' if 'x86_64' in aname: return 'android-x86_64' if 'x86' in aname: return 'android-x86' return 'linux-armv4' def build_arch(self: OpenSSLRecipe, arch: Arch) -> None: env = self.get_recipe_env(arch) with current_directory(self.get_build_dir(arch.arch)): # sh fails with code 255 trying to execute ./Configure # so instead we manually run perl passing in Configure perl = sh.Command('perl') buildarch: str = self.select_build_arch(arch) config_args = [ # TODO: Try to use system certeficates (or make it optional in the near future..) 'shared', 'no-dso', 'no-asm', buildarch, f'-D__ANDROID_API__={self.ctx.ndk_api}', ] shprint(perl, 'Configure', *config_args, _env=env) self.apply_patch('disable-sover.patch', arch.arch) self.apply_patch('use_app_path_env4conf.patch', arch.arch) shprint(sh.make, 'build_libs', _env=env) recipe = OpenSSLRecipe()
import { get, post, postFile } from "../http"; import utils from "../../utils/Utils"; import { BASE_PATH } from "../../constants"; import { utils as strings, general } from "../../constants/strings/fa"; class Entity { constructor() { this.errorMessage = ""; this.errorCode = 0; } async handleGet(url, data) { try { this.errorMessage = ""; this.errorCode = 0; const response = await get(url, data); return this.handleResponse(response); } catch (error) { console.error(error); if (error.message === "Network Error") { this.errorMessage = general.networkError; } else { this.errorMessage = error.message; } this.errorCode = 1000; return null; } } async handlePost(url, data = {}, withCredentials = true) { try { this.errorMessage = ""; this.errorCode = 0; const response = await post(url, data, withCredentials); return this.handleResponse(response); } catch (error) { if (error.response) { this.errorMessage = error.response.data; console.error(error.response.data); console.error(error.response.status); console.error(error.response.headers); return null; } else if (error.request) { this.errorMessage = error.request; console.error(error.request); return null; } console.error(error); if (error.message === "Network Error") { this.errorMessage = general.networkError; } else { this.errorMessage = error.message; } this.errorCode = 1000; return null; } } async handlePostFile(url, data) { try { this.errorMessage = ""; this.errorCode = 0; const response = await postFile(url, data); return this.handleResponse(response); } catch (error) { console.error(error); if (error.message === "Network Error") { this.errorMessage = general.networkError; } else { this.errorMessage = error.message; } this.errorCode = 1000; return null; } } handleResponse(response) { try { if (!utils.isJsonString(response.data)) { this.errorMessage = strings.notValidJson; return null; } if (response.data._result !== "1") { this.errorMessage = response.data._error; this.errorCode = response.data._errorCode; this.handleError(); return null; } return response.data; } catch (error) { console.error(error); this.errorMessage = error.message; this.errorCode = 1000; return null; } } handleError() { switch (this.errorCode) { case 1: case 2: window.location.href = BASE_PATH; break; default: return; } } } export default Entity;
<script setup> import AppLayout from '@/Layouts/AppLayout.vue' </script> <template> <AppLayout title="Asignaciones"> <template #header> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> Asignaciones </h2> </template> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg"> <table class="table-auto w-full"> <thead> <tr> <th class="px-4 py-2">ID</th> <th class="px-4 py-2">Marca Modelo</th> <th class="px-4 py-2">Nro. Serie</th> <th class="px-4 py-2">Nro. Inventario</th> <th class="px-4 py-2">Responsable</th> <th class="px-4 py-2">Fecha Asignación</th> <th class="px-4 py-2">División</th> <th class="px-4 py-2">Acciones</th> </tr> </thead> <tbody> <tr v-for="equipoUser in equipoUsers" :key="equipoUser.id"> <td class="border px-4 py-2">{{ equipoUser.id }}</td> <td class="border px-4 py-2">{{ equipoUser.nombre_marca + '/' + equipoUser.nombre_modelo }}</td> <td class="border px-4 py-2">{{ equipoUser.n_serie }}</td> <td class="border px-4 py-2">{{ equipoUser.n_inventario }}</td> <td class="border px-4 py-2">{{ equipoUser.name }}</td> <td class="border px-4 py-2">{{ equipoUser.fecha_asignacion }}</td> <td class="border px-4 py-2">{{ equipoUser.departamento + '/' + equipoUser.subdepartamento + '/' + equipoUser.unidad }}</td> <td class="border px-4 py-2"> <a href="#" class="text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Editar</a> <a href="#" class="text-sm bg-red-500 hover:bg-red-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Eliminar</a> </td> </tr> </tbody> </table> </div> </div> </div> </AppLayout> </template> <style> .table-auto tr:nth-child(even) { background-color: #f2f2f2; /* Color para filas alternas */ /* Opcional: añade una transición para que el cambio de color sea más suave */ transition: background-color 0.2s ease-in-out; } .table-auto tr:hover { background-color: #e0e0e0; /* Color para filas al pasar el cursor */ } .table-auto td, .table-auto th { border: 1px solid #ddd; text-align: center; } </style> <script> export default { props: { equipoUsers: Array } } </script>
## node.js获取参数res.query与res.params的区别 相同点:二者都可以获取get请求的参数 不同点:res.query与res.params获取的格式不同 - req.query也就是?id=参数,这样情况下,key和value都在请求的url中 - req.params也就是/,这样情况下,key在路由中,value是请求的url ```node.js req.query: router.get('/query', function (req, res, next) { console.log('get请求参数对象 :',req.query);//get请求对象:{q:'123',w:'456'} console.log('q的值为 :',req.query.q);//q的值:123 }); ``` ```node.js router.get('/test/:urlname', function (req, res,next) { console.log('url参数对象 :',req.params); //url参数对象:{urlname:'url123'} console.log('get请求参数对象 :',req.query);//{} console.log('q的值为 :',req.params.urlname);//q的值:url123 }); ```
import MiniCssExtractPlugin from 'mini-css-extract-plugin'; /** * css loader * * @public */ export const css = (app) => { const loader = `css-loader`; return app.build.makeLoader().setSrc(loader); }; /** * csv loader * * @public */ export const csv = (app) => { const loader = `csv-loader`; return app.build.makeLoader().setSrc(loader); }; /** * file loader * * @public */ export const file = (app) => { const loader = `file-loader`; return app.build.makeLoader().setSrc(loader); }; /** * html-loader * * @public */ export const html = (app) => { const loader = `html-loader`; return app.build.makeLoader().setSrc(loader); }; /** * remark-loader * * @public */ export const remark = (app) => { const loader = `remark-loader`; return app.build.makeLoader().setSrc(loader); }; /** * `mini-css-extract-plugin.loader` * * @public */ export const minicss = (app) => { return app.build.makeLoader().setSrc(MiniCssExtractPlugin.loader); }; /** * style-loader * * @public */ export const style = (app) => { const loader = `style-loader`; return app.build.makeLoader().setSrc(loader); }; /** * xml-loader * * @public */ export const xml = (app) => { const loader = `xml-loader`; return app.build.makeLoader().setSrc(loader); }; /** * yml-loader * * @public */ export const yml = (app) => { const loader = `yml-loader`; return app.build.makeLoader().setSrc(loader); }; //# sourceMappingURL=loaders.js.map
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8"> <title>Comparison</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="../style.css"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-light shrinkray"> <a class="navbar-brand" href="../Landing_Page.html"> <h1 class="my-auto">Lattitude</h1> </a> <button class="navbar-toggler shrinkray" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse bg-white row" id="navbarSupportedContent"> <form class="ml-lg-auto ml-md-3 mr-lg-3"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle link-c" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Plots </a> <div class="dropdown-menu" aria-labelledby="Dropdown"> <a class="dropdown-item" href="../Temp/Temp.html">Temperature</a> <a class="dropdown-item" href="../Hum/Hum.html">Humidity</a> <a class="dropdown-item" href="../Cloud/Cloud.html">Cloudiness</a> <a class="dropdown-item" href="../Wind/Wind.html">Wind Speed</a> </div> </li> <li class="nav-item"> <a class="nav-link link-c" href="../Comp/Comp.html">Comparison</a> </li> <li class="nav-item"> <a class="nav-link link-c" href="../Data/Data.html">Data</a> </li> </ul> </form> </div> </nav> <br> <div class="bg-white offset-lg-1 col-lg-10" > <br> <h4 style="margin-left: 5%; "> Comparison: Latitude vs. [X] </h4> <hr> <p style="margin-left: 5%"> Click Any Visualization To Go To In-Depth Analysis </p> <div class="container col-12"> <div class="row ml-auto mr-auto"> <div class="col-md-6"> <h5> Max Temperature </h5> <a href="../Temp/Temp.html"> <img src="../Figures/Fig1.png" alt="Temp" class="col"> </a> <hr class="show-me"> </div> <div class="col-md-6"> <h5> Humidity </h5> <a href="../Hum/Hum.html"> <img src="../Figures/Fig2.png" class="col" alt="Humidity"> </a> <hr class="show-me"> </div> </div> <div class="row ml-auto mr-auto"> <div class="col-md-6"> <h5> Cloudiness </h5> <a href="../Cloud/Cloud.html"> <img src="../Figures/Fig3.png" class="col" alt="Cloud"> </a> <hr class="show-me"> </div> <div class="col-md-6"> <h5> Wind Speed </h5> <a href="../Wind/Wind.html"> <img src="../Figures/Fig4.png" class="col" alt="Wind"> </a> </div> </div> </div> </div> </body> </html>
import { SlashCommand } from "../../lib/structures/SlashCommand"; export default new SlashCommand({ name: "rockpaperscissors", description: "Rock, paper or scrissors?", userPerms: ["SEND_MESSAGES"], options: [ { name: "choice", description: "Choose rock, paper or scissors?", type: "STRING", required: true, choices: [ { name: "rock ⛰️", value: "rock", }, { name: "paper 🧻", value: "paper", }, { name: "scissors ✂️", value: "scissors", }, ], }, ], run: async ({ client, interaction, utils, lang }) => { const { Fields } = lang.FunModule.Commands.RockPaperScissors; const player = interaction.user; const choices = ["🤜", "✋", "✌"]; const choice = interaction.options.getString("choice"); const BotChoice = choices[~~(Math.random() * choices.length)]; if (!["rock", "paper", "scissors"].includes(choice)) return interaction.reply({ embeds: [await utils.Usage("rockpaperscissors", interaction.guild)], ephemeral: true, }); const results = [`<@${player.id}> wins!`, `<@${client.user.id}> wins!`, `Tie.`]; let result: string; if (choice == "rock") { if (BotChoice === choices[0]) result = results[2]; if (BotChoice === choices[1]) result = results[1]; if (BotChoice === choices[2]) result = results[0]; return interaction.reply({ embeds: [ client.embed.create({ Fields: [ { name: utils.replaceText(Fields[0], "USER", player.username), value: choices[0], inline: true, }, { name: Fields[1], value: Fields[2], inline: true, }, { name: Fields[3], value: BotChoice, inline: true, }, { name: Fields[4], value: result, }, ], }), ], }); } if (choice == "paper") { if (BotChoice === choices[0]) result = results[0]; if (BotChoice === choices[1]) result = results[2]; if (BotChoice === choices[2]) result = results[1]; return interaction.reply({ embeds: [ client.embed.create({ Fields: [ { name: utils.replaceText(Fields[0], "USER", player.username), value: choices[1], inline: true, }, { name: Fields[1], value: Fields[2], inline: true, }, { name: Fields[3], value: BotChoice, inline: true, }, { name: Fields[4], value: result, }, ], }), ], }); } if (choice == "scissors") { if (BotChoice === choices[0]) result = results[1]; if (BotChoice === choices[1]) result = results[0]; if (BotChoice === choices[2]) result = results[2]; return interaction.reply({ embeds: [ client.embed.create({ Fields: [ { name: utils.replaceText(Fields[0], "USER", player.username), value: choices[2], inline: true, }, { name: Fields[1], value: Fields[2], inline: true, }, { name: Fields[3], value: BotChoice, inline: true, }, { name: Fields[4], value: result, }, ], }), ], }); } }, });
import { useCallback, useEffect } from 'react'; import { useSubscriber } from '../../hooks/useSubscriber'; import { EventName, Game } from '../../models'; import { getGame } from '../../services/gameService'; import { formatPrice } from '../../utils/formatPrice'; import GuessButtons from '../GuessButtons'; import Loader from '../Loader'; import Arrow from './Arrow'; import BitcoinLogo from './BitcoinLogo'; const GameData = () => { const [gameData, setGameData] = useSubscriber<Game | null>( EventName.Game, null, (e: any, prev: any) => { setGameData(e[0]); }, ); const fetchGameData = useCallback(async () => { const data = await getGame(); setGameData(data); }, [setGameData]); useEffect(() => { fetchGameData(); }, [fetchGameData]); return ( <div className="flex flex-col gap-8 items-center content-center p-8 bg-white bg-opacity-40 rounded-xl border-gray-100 shadow-lg"> <div className="flex gap-4 flex-row justify-between items-center"> <BitcoinLogo /> {gameData?.value ? ( <span className="flex-col flex text-3xl font-semibold"> {formatPrice(gameData?.value)} </span> ) : ( <Loader /> )} </div> {gameData?.difference && ( <div className="flex flex-row justify-center"> <div data-testid="difference-container" className={`text-2xl font-semibold flex items-center gap-1 rounded-lg bg-opacity-50 w-min px-8 ${ gameData?.difference >= 0 ? 'bg-green-400' : 'bg-red-400' } ${gameData?.difference >= 0 ? 'text-green-600' : 'text-red-600'} `} > <span>{gameData?.difference.toFixed(4)}%</span> <Arrow difference={gameData.difference} /> </div> </div> )} <div className="flex flex-row items-center"> <GuessButtons gameId={gameData?.id} /> </div> </div> ); }; export default GameData;
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.client.workspace; import com.google.gwt.user.client.ui.Widget; import ilarkesto.core.menu.MenuItem; import ilarkesto.core.menu.StaticMenu; import ilarkesto.core.menu.StaticMenuItem; import ilarkesto.core.menu.StaticSubmenu; import ilarkesto.core.menu.Submenu; import ilarkesto.gwt.client.AAction; import ilarkesto.gwt.client.NavigatorWidget; import scrum.client.collaboration.WikiWidget; import scrum.client.impediments.ImpedimentListWidget; import scrum.client.pr.BlogWidget; import scrum.client.project.ProductBacklogWidget; import scrum.client.tasks.WhiteboardWidget; /** * * */ public class ScrumNavigatorWidget extends NavigatorWidget<Object> { /** * * @param item * @return */ @Override protected String getHref(MenuItem item) { if (item instanceof StaticMenuItem) { StaticMenuItem staticItem = (StaticMenuItem) item; Object payload = staticItem.getPayload(); if ("sprint".equals(payload)) { return Navigator.getPageHref(WhiteboardWidget.class); } if ("product".equals(payload)) { return Navigator.getPageHref(ProductBacklogWidget.class); } if ("project".equals(payload)) { return Navigator.getPageHref(ImpedimentListWidget.class); } if ("collaboration".equals(payload)) { return Navigator.getPageHref(WikiWidget.class); } if ("administration".equals(payload)) { return Navigator.getPageHref(BlogWidget.class); } if (payload instanceof Widget) { return Navigator.getPageHref(((Widget) payload).getClass()); } } return super.getHref(item); } /** * * @param label * @param key */ public void addGroup(String label, String key) { final StaticSubmenu submenu = new StaticSubmenu(label); submenu.setPayload(key); menu.addItem(submenu); } /** * * @param group * @param label * @param widget */ public void addItem(String group, String label, final Widget widget) { final Submenu<StaticMenuItem> groupItem = (Submenu<StaticMenuItem>) menu.getItemByPayload(group); assert groupItem != null; StaticMenu menu = (StaticMenu) groupItem.getMenu(); StaticMenuItem subItem = menu.addItem(new StaticMenuItem(label)); subItem.setPayload(widget); subItem.setOnSelect(new Runnable() { @Override public void run() { groupItem.select(); } }); } /** * * @param label * @param widget */ public void addItem(String label, final Widget widget) { assert label != null; assert widget != null; addItem(label, widget, new Runnable() { @Override public void run() {} }); } /** * * @param widget * @return */ public SwitchAction createSwitchAction(Widget widget) { return new SwitchAction(widget); } /** * */ public class SwitchAction extends AAction { private Widget widget; private String label; /** * * @param widget */ public SwitchAction(Widget widget) { this.widget = widget; } @Override public String getLabel() { if (label != null) { return label; } StaticMenuItem item = menu.getItemByPayload(widget); return item.getLabel(); } @Override protected void onExecute() { select(widget); } @Override public String getTargetHistoryToken() { return Navigator.getPageHistoryToken(Page.getPageName(widget)); } /** * * @param label */ public void setLabel(String label) { this.label = label; } } }
import { NextApiRequest, NextApiResponse } from "next"; type method = "GET" | "POST" | "DELETE"; interface WithHandlerProps { methods: method[]; handler: (req: NextApiRequest, res: NextApiResponse) => void; } const withHandler = ({ methods, handler }: WithHandlerProps) => { return async (req: NextApiRequest, res: NextApiResponse) => { if (req.method && !methods.includes(req.method as any)) return res.status(405); // GET | POST | DELETE 이 아닐 때 try { await handler(req, res); } catch (error) { console.log(error); res.status(500).json({ error }); } }; }; export default withHandler; // 메소드 체크 및 에러 핸들러
import 'package:dartz/dartz.dart'; import 'package:meta/meta.dart'; import 'package:whixp/src/jid/jid.dart'; import 'package:whixp/src/log/log.dart'; import 'package:whixp/src/transport.dart'; import 'package:whixp/src/utils/utils.dart'; import 'package:xml/xml.dart' as xml; import 'package:xpath_selector_xml_parser/xpath_selector_xml_parser.dart'; part 'stanza.dart'; /// Gets two parameter; The first one is usually refers to language of the /// stanza. The second is for processing over current stanza and keeps [XMLBase] /// instance. typedef _GetterOrDeleter = dynamic Function(dynamic args, XMLBase base); /// Gets three params; The first one is usually refers to language of the /// current stanza. The second one is the parameter to set. The third one is /// [XMLBase] and refers to current stanza instance. typedef _Setter = void Function(dynamic args, dynamic value, XMLBase base); /// Applies the stanza's namespace to elements in an [xPath] expression. /// /// [split] indicates if the fixed XPath should be left as a list of element /// names of element names with namespaces. Defaults to `false`. /// /// [propogateNamespace] overrides propagating parent element namespaces to /// child elements. Useful if you wish to simply split an XPath that has /// non-specified namepsaces, adnd child and parent namespaces are konwn not to /// always match. Defaults to `true`. Tuple2<String?, List<String>?> fixNamespace( String xPath, { bool split = false, bool propogateNamespace = true, String defaultNamespace = '', }) { final fixed = <String>[]; final namespaceBlocks = xPath.split('{'); for (final block in namespaceBlocks) { late String namespace; late List<String> elements; if (block.contains('}')) { final namespaceBlockSplit = block.split('}'); namespace = namespaceBlockSplit[0]; elements = namespaceBlockSplit[1].split('/'); } else { namespace = defaultNamespace; elements = block.split('/'); } for (final element in elements) { late String tag; if (element.isNotEmpty) { if (propogateNamespace && element[0] != '*') { tag = '<$element xmlns="$namespace"/>'; } else { tag = element; } fixed.add(tag); } } } if (split) { return Tuple2(null, fixed); } return Tuple2(fixed.join('/'), null); } /// Associates a [stanza] object as a plugin for another stanza. /// /// [plugin] stanzas marked as iterable will be included in the list of /// substanzas for the parent, using `parent['subsstanzas']`. If the attribute /// `pluginMultiAttribute` was defined for the plugin, then the substanza set /// can be filtered to only instances of the plugin class. /// /// For instance, given a plugin class `Foo` with /// `pluginMultiAttribute = 'foos'` then: /// parent['foos'] /// would return a collection of all `Foo` substanzas. void registerStanzaPlugin( XMLBase stanza, XMLBase plugin, { /// Indicates if the plugin stanza should be included in the parent stanza's /// iterable [substanzas] interface results. bool iterable = false, /// Indicates if the plugin should be allowed to override the interface /// handlers for the parent stanza, based on the plugin's [overrides] field. bool overrides = false, }) { final tag = '{${plugin.namespace}}${plugin.name}'; stanza.pluginAttributeMapping[plugin.pluginAttribute] = plugin; stanza.pluginTagMapping[tag] = plugin; if (iterable) { stanza.pluginIterables.add(plugin); if (plugin.pluginMultiAttribute != null && plugin.pluginMultiAttribute!.isNotEmpty) { final multiplugin = multifactory(plugin, plugin.pluginMultiAttribute!); registerStanzaPlugin(stanza, multiplugin); } } if (overrides) { for (final interface in plugin.overrides) { stanza.pluginOverrides[interface] = plugin.pluginAttribute; } } } /// Returns a [XMLBase] class for handling reoccuring child stanzas. XMLBase multifactory(XMLBase stanza, String pluginAttribute) { final multistanza = _Multi( stanza.runtimeType, pluginAttribute: pluginAttribute, interfaces: {pluginAttribute}, languageInterfaces: {pluginAttribute}, isExtension: true, ); multistanza ..addGetters({ Symbol(pluginAttribute): (args, base) => multistanza.getMulti(base, args as String?), }) ..addSetters({ Symbol(pluginAttribute): (value, args, base) => multistanza.setMulti(base, value as List<dynamic>, args as String?), }) ..addDeleters({ Symbol(pluginAttribute): (args, base) => multistanza.deleteMulti(base, args as String?), }); return multistanza; } typedef _MultiFilter = bool Function(XMLBase); /// Multifactory class. Responsible to create an stanza with provided /// substanzas. class _Multi extends XMLBase { _Multi( this._multistanza, { super.getters, super.setters, super.deleters, super.pluginAttribute, super.interfaces, super.languageInterfaces, super.isExtension, super.element, super.parent, }); late final Type _multistanza; List<XMLBase> getMulti(XMLBase base, [String? lang]) { final parent = failWithoutParent(base); final iterable = _XMLBaseIterable(parent); final result = (lang == null || lang.isEmpty) || lang == '*' ? iterable.where(pluginFilter()) : iterable.where(pluginLanguageFilter(lang)); return result.toList(); } @override bool setup([xml.XmlElement? element]) { this.element = WhixpUtils.xmlElement(''); return false; } void setMulti(XMLBase base, List<dynamic> value, [String? language]) { final parent = failWithoutParent(base); _deleters[Symbol(pluginAttribute)]?.call(language, base); for (final sub in value) { parent.add(sub as XMLBase); } } XMLBase failWithoutParent(XMLBase base) { XMLBase? parent; if (base.parent != null) { parent = base.parent; } if (parent == null) { throw ArgumentError('No stanza parent for multifactory'); } return parent; } void deleteMulti(XMLBase base, [String? language]) { final parent = failWithoutParent(base); final iterable = _XMLBaseIterable(parent); final result = (language == null || language.isEmpty) || language == '*' ? iterable.where(pluginFilter()).toList() : iterable.where(pluginLanguageFilter(language)).toList(); if (result.isEmpty) { parent._plugins.remove(Tuple2(pluginAttribute, '')); parent._loadedPlugins.remove(pluginAttribute); parent.element!.children.remove(element); } else { while (result.isNotEmpty) { final stanza = result.removeLast(); parent.iterables.remove(stanza); parent.element!.children.remove(stanza.element); } } } _MultiFilter pluginFilter() => (x) => x.runtimeType == _multistanza; _MultiFilter pluginLanguageFilter(String? language) => (x) => x.runtimeType == _multistanza && x['lang'] == language; @override _Multi copy({xml.XmlElement? element, XMLBase? parent}) => _Multi( _multistanza, getters: getters, setters: setters, deleters: deleters, pluginAttribute: pluginAttribute, interfaces: interfaces, languageInterfaces: languageInterfaces, isExtension: isExtension, element: element, parent: parent, ); } class _XMLBaseIterable extends Iterable<XMLBase> { _XMLBaseIterable(this.parent); final XMLBase parent; @override Iterator<XMLBase> get iterator => _XMLBaseIterator(parent); } class _XMLBaseIterator implements Iterator<XMLBase> { final XMLBase parent; _XMLBaseIterator(this.parent); @override XMLBase get current { return parent.iterables[parent._index - 1]; } @override bool moveNext() { if (parent._index >= parent.iterables.length) { parent._index = 0; return false; } else { parent._incrementIndex.call(); return true; } } } /// ## XMLBase /// /// Designed for efficient manipulation of XML elements. Provides a set of /// methods and functionalities to create, modify, and interact with XML /// structures. /// /// Serves as a base and flexible XML manipulation tool for this package, /// designed to simplify the creation, modification, and interaction with /// XML. It offers a comprehensive set of features for constructing XML /// elements, managing attributes, handling child elements, and incorporating /// dynamic plugins to extend functionality. /// /// [XMLBase] is created to accommodate a wide range of XML manipulation tasks. /// Whether you are creating simple XML elements or dealing with complex /// structures, this class provides a versatile foundation. /// /// The extensibility of [XMLBase] is the key strength. You can integrate and /// manage plugins, which may include extensions or custom functionality. /// /// Stanzas are defined by their name, namespace, and interfaces. For example, /// a simplistic Message stanza could be defined as: /// ```dart /// class Message extends XMLBase { /// Message() /// : super( /// name: 'message', /// interfaces: {'to', 'from', 'type', 'body'}, /// subInterfaces: {'body'}, /// ); /// } /// ``` /// /// The resulting Message stanza's content may be accessed as so: /// ```dart /// message['to'] = 'vsevex@example.com'; /// message['body'] = 'salam'; /// log(message['body']); /// outputs 'salam' /// message.delete('body'); /// log(message['body']); /// will output empty string /// ``` /// /// ### Example: /// ```dart /// class TestStanza extends XMLBase { /// TestStanza({ /// super.name, /// super.namespace, /// super.pluginAttribute, /// super.pluginMultiAttribute, /// super.overrides, /// super.interfaces, /// super.subInterfaces, /// }); /// } /// /// void main() { /// final stanza = TestStanza({name: 'stanza'}); /// /// ...do whatever manipulation you want /// stanza['test'] = 'salam'; /// /// will add a 'test' child and assign 'salam' text to it /// } /// ``` /// /// Extending stanzas through the use of plugins (simple stanza that has /// pluginAttribute value) is like the following: /// ```dart /// class MessagePlugin extends XMLBase { /// MessagePlugin() /// : super( /// name: 'message', /// interfaces: {'cart', 'hert'}, /// pluginAttribute: 'custom', /// ); /// } /// ``` /// /// The plugin stanza class myst be associated with its intended container /// stanza by using [registerStanzaPlugin] method: /// ```dart /// final plugin = MessagePlugin(); /// message.registerPlugin(plugin); /// ``` /// /// The plugin may then be accessed as if it were built-in to the parent stanza: /// ```dart /// message['custom']['cart'] = 'test'; /// ``` class XMLBase { /// ## XMLBase /// /// Default constructor for creating an empty XML element. /// /// [XMLBase] is designed with customization in mind. Users can extend the /// class and override methods, allowing for the manipulation of custom fields /// and the implementation of specialized behavior when needed. XMLBase({ /// If no `name` is passed, sets the default name of the stanza to `stanza` this.name = 'stanza', /// If `null`, then default stanza namespace will be used String? namespace, this.transport, this.pluginAttribute = 'plugin', this.pluginMultiAttribute, this.overrides = const <String>[], Map<String, XMLBase>? pluginTagMapping, Map<String, XMLBase>? pluginAttributeMapping, /// Defaults to predefined ones this.interfaces = const <String>{'type', 'to', 'from', 'id', 'payload'}, this.subInterfaces = const <String>{}, this.boolInterfaces = const <String>{}, this.languageInterfaces = const <String>{}, Map<String, String>? pluginOverrides, Set<XMLBase>? pluginIterables, this.receive = false, this.isExtension = false, this.includeNamespace = true, Map<Symbol, _GetterOrDeleter>? getters, Map<Symbol, _Setter>? setters, Map<Symbol, _GetterOrDeleter>? deleters, this.element, this.parent, }) { this.pluginTagMapping = pluginTagMapping ?? <String, XMLBase>{}; this.pluginAttributeMapping = pluginAttributeMapping ?? <String, XMLBase>{}; this.pluginOverrides = pluginOverrides ?? <String, String>{}; this.pluginIterables = pluginIterables ?? <XMLBase>{}; /// Defaults to `CLIENT`. this.namespace = namespace ?? WhixpUtils.getNamespace('CLIENT'); /// Equal tag to the tag name. tag = _tagName; if (getters != null) addGetters(getters); if (setters != null) addSetters(setters); if (deleters != null) addDeleters(deleters); if (setup(element)) return; final children = <Tuple2<xml.XmlElement, XMLBase?>>{}; for (final child in element!.childElements.toSet()) { /// Must assign one of the namespaces. final namespace = child.getAttribute('xmlns') ?? element!.getAttribute('xmlns') ?? WhixpUtils.getNamespace('CLIENT'); final tag = '{$namespace}${child.localName}'; if (this.pluginTagMapping.containsKey(tag) && this.pluginTagMapping[tag] != null) { final pluginClass = this.pluginTagMapping[tag]; children.add(Tuple2(child, pluginClass)); } } /// Growable iterable fix for (final child in children) { initPlugin( child.value2!.pluginAttribute, existingXML: child.value1, reuse: false, ); } } /// Index to keep for iterables. int _index = 0; /// The XML tag name of the element, not including any namespace prefixes. @internal final String name; /// The XML namespace for the element. Given `<foo xmlns="bar" />`, then /// `namespace = "bar"` should be used. /// /// Defaults namespace in the constructor scope to `jabber:client` since this /// is being used in an XMPP library. @internal late String namespace; /// Unique identifiers of plugins across [XMLBase] classes. @internal final String pluginAttribute; /// [XMLBase] subclasses that are intended to be an iterable group of items, /// the `pluginMultiAttribute` value defines an interface for the parent /// stanza which returns the entire group of matching `substanzas`. @internal final String? pluginMultiAttribute; /// In some cases you may wish to override the behaviour of one of the /// parent stanza's interfaces. The `overrides` list specifies the interface /// name and access method to be overridden. For example, to override setting /// the parent's `condition` interface you would use: /// /// ```dart /// overrides = ['condition']; /// ``` /// /// Getting and deleting the `condition` interface would not be affected. @internal final List<String> overrides; /// A mapping of root element tag names /// (in `<$name xmlns="$namespace"/>` format) to the plugin classes /// responsible for them. @internal late final Map<String, XMLBase> pluginTagMapping; /// When there is a need to indicate initialize plugin or get plugin we will /// use [pluginAttributeMapping] keeper for this. @internal late final Map<String, XMLBase> pluginAttributeMapping; /// The set of keys that the stanza provides for accessing and manipulating /// the underlying XML object. This [Set] may be augmented with the /// [pluginAttribute] value of any registered stanza plugins. final Set<String> interfaces; /// A subset of `interfaces` which maps interfaces to direct subelements of /// the underlaying XML object. Using this [Set], the text of these /// subelements may be set, retrieved, or removed without needing to define /// custom methods. @internal final Set<String> subInterfaces; /// A subset of [interfaces] which maps to the presence of subelements to /// boolean values. Using this [Set] allows for quickly checking for the /// existence of empty subelements. @internal final Set<String> boolInterfaces; /// A subset of [interfaces] which maps to the presence of subelements to /// language values. @internal final Set<String> languageInterfaces; /// A [Map] of interface operations to the overriding functions. /// /// For instance, after overriding the `set` operation for the interface /// `body`, [pluginOverrides] would be: /// /// ```dart /// log(pluginOverrides); /// outputs {'body': Function()} /// ``` @internal late final Map<String, String> pluginOverrides; /// The set of stanza classes that can be iterated over using the `substanzas` /// interface. @internal late final Set<XMLBase> pluginIterables; /// Declares if stanza is incoming or outgoing stanza. Defaults to false. @internal final bool receive; /// If you need to add a new interface to an existing stanza, you can create /// a plugin and set `isExtension = true`. Be sure to set the /// [pluginAttribute] value to the desired interface name, and that it is the /// only interface listed in [interfaces]. Requests for the new interface /// from the parent stanza will be passed to the plugin directly. @internal final bool isExtension; /// Indicates that this stanza or stanza plugin should include [namespace]. /// You need to specify this value in order to add namespace to your stanza, /// 'cause defaults to `false`. @internal final bool includeNamespace; /// The helper [Map] contains all the required `setter` methods when there is /// a need to override the current setter method. late final Map<Symbol, _Setter> _setters = <Symbol, _Setter>{}; /// The helper [Map] contains all the required `getter` methods when there is /// a need to override the current getter method. late final Map<Symbol, _GetterOrDeleter> _getters = <Symbol, _GetterOrDeleter>{}; /// The helper [Map] contains all the required `delete` methods when there is /// a need to override the current delete method. late final Map<Symbol, _GetterOrDeleter> _deleters = <Symbol, _GetterOrDeleter>{}; @internal final iterables = <XMLBase>[]; /// Keeps all initialized plugins across stanza. final _plugins = <Tuple2<String, String>, XMLBase>{}; /// Keeps all loaded plugins across stanza. final _loadedPlugins = <String>{}; /// The underlying [element] for the stanza. @internal xml.XmlElement? element; /// The parent [XMLBase] element for the stanza. @internal final XMLBase? parent; /// Underlying [Transport] for this stanza class. Helps to interact with /// socket. @internal late Transport? transport; /// Tag name for the stanza in the format of "<$name xmlns="$namespace"/>". @internal late final String tag; /// The stanza's XML contents initializer. /// /// Will return `true` if XML was generated according to the stanza's /// definition instead of building a stanza object from an existing XML /// object. @internal bool setup([xml.XmlElement? element]) { if (this.element != null) { return false; } if (this.element == null && element != null) { this.element = element; return false; } xml.XmlElement lastXML = xml.XmlElement(xml.XmlName('')); int index = 0; for (final ename in name.split('/')) { final newElement = index == 0 && includeNamespace ? WhixpUtils.xmlElement(ename, namespace: namespace) : WhixpUtils.xmlElement(ename); if (this.element == null) { this.element = newElement; } else { lastXML.children.add(newElement); } lastXML = newElement; index++; } if (parent != null) { parent!.element!.children.add(this.element!); } return true; } /// Enables and initializes a stanza plugin. @internal XMLBase enable(String attribute, [String? language]) => initPlugin(attribute, language: language); /// Responsible to retrieve a stanza plugin through the passed [name] and /// [language]. /// /// If [check] is true, then the method returns null instead of creating the /// object. @internal XMLBase? getPlugin(String name, {String? language, bool check = false}) { /// If passed `language` is null, then try to retrieve it through built-in /// method. final lang = (language == null || language.isEmpty) ? _getLang : language; if (!pluginAttributeMapping.containsKey(name)) { return null; } final plugin = pluginAttributeMapping[name]; if (plugin == null) return null; if (plugin.isExtension) { if (_plugins[Tuple2(name, '')] != null) { return _plugins[Tuple2(name, '')]; } else { return check ? null : initPlugin(name, language: lang); } } else { if (_plugins[Tuple2(name, lang)] != null) { return _plugins[Tuple2(name, lang)]; } else { return check ? null : initPlugin(name, language: lang); } } } /// Responsible to enable and initialize a stanza plugin. @internal XMLBase initPlugin( String attribute, { String? language, xml.XmlElement? existingXML, bool reuse = true, XMLBase? element, }) { final defaultLanguage = _getLang; final lang = (language == null || language.isEmpty) ? defaultLanguage : language; late final pluginClass = pluginAttributeMapping[attribute]!; if (pluginClass.isExtension && _plugins[Tuple2(attribute, '')] != null) { return _plugins[Tuple2(attribute, '')]!; } if (reuse && _plugins[Tuple2(attribute, lang)] != null) { return _plugins[Tuple2(attribute, lang)]!; } late XMLBase plugin; if (element != null) { plugin = element; } else { plugin = pluginClass.copy(element: existingXML, parent: this); } if (plugin.isExtension) { _plugins[Tuple2(attribute, '')] = plugin; } else { if (lang != defaultLanguage) plugin['lang'] = lang; _plugins[Tuple2(attribute, lang)] = plugin; } if (pluginIterables.contains(pluginClass)) { iterables.add(plugin); if (pluginClass.pluginMultiAttribute != null) { initPlugin(pluginClass.pluginMultiAttribute!); } } /// Assign `attribute` to the list to indicate that this plugin is loaded /// already. _loadedPlugins.add(attribute); return plugin; } /// Returns the text contents of a sub element. /// /// In case the element does not exist, or it has not textual content, a [def] /// value can be returned instead. An empty string is returned if no other /// default is supplied. /// /// [String] or [Map] of String should be returned. If language is not defined /// then all sub texts will be returned. @internal dynamic getSubText( String name, { String def = '', String? language, }) { final castedName = '/${_fixNamespace(name).value1!}'; if (language != null && language == '*') { return _getAllSubText(name, def: def); } final defaultLanguage = _getLang; final lang = (language == null || language.isEmpty) ? defaultLanguage : language; final stanzas = element!.queryXPath(castedName).nodes; if (stanzas.isEmpty) return def; String? result; for (final stanza in stanzas) { if (stanza.isElement) { final node = stanza.node; if ((_lang(node) ?? defaultLanguage) == lang) { if (node.innerText.isEmpty) return def; result = node.innerText; break; } if (stanza.node.innerText.isNotEmpty) { result = stanza.node.innerText; } } } if (result != null) return result; return def; } /// Returns all sub text of the element. Map<String, String> _getAllSubText( String name, { String def = '', String? language, }) { final castedName = _fixNamespace(name).value1!; final defaultLanguage = _getLang; final results = <String, String>{}; final stanzas = element!.findAllElements(castedName); if (stanzas.isNotEmpty) { for (final stanza in stanzas) { final stanzaLanguage = _lang(stanza) ?? defaultLanguage; if (!(language != null) || language == "*" || language == defaultLanguage) { late String text; if (stanza.innerText.isEmpty) { text = def; } else { text = stanza.innerText; } results[stanzaLanguage] = text; } } } return results; } /// Sets the [text] contents of a sub element. /// /// In case the element does not exist, a element will be created, and its /// text contents will be set. /// /// If the [text] is set to an empty string, or null, then the element will be /// removed, unless [keep] is set to `true`. @internal xml.XmlNode? setSubText( String name, { String? text, bool keep = false, String? language, }) { final defaultLanguage = _getLang; final lang = (language == null || language.isEmpty) ? defaultLanguage : language; if ((text == null || text.isEmpty) && !keep) { deleteSub(name, language: lang); return null; } final path = _fixNamespace(name, split: true).value2!; final castedName = path.last; late xml.XmlNode? parent = element; late List<xml.XmlNode> elements = <xml.XmlElement>[]; List<String> missingPath = <String>[]; final searchOrder = List<String>.from(path)..removeLast(); while (searchOrder.isNotEmpty) { parent = element!.queryXPath('/${searchOrder.join('/')}').node?.node; final ename = searchOrder.removeLast(); if (parent != null) { break; } else { missingPath.add(ename); } } missingPath = missingPath.reversed.toList(); if (parent != null) { elements = element! .queryXPath('/${path.join('/')}') .nodes .map((item) => item.node) .toList(); } else { parent = element; elements = []; } for (final ename in missingPath) { final tempElement = xml.XmlElement(xml.XmlName(ename)); parent!.children.add(tempElement); parent = tempElement; } for (final element in elements) { final elanguage = _lang(element) ?? defaultLanguage; if ((lang.isEmpty && elanguage == defaultLanguage) || lang == elanguage) { element.innerText = text!; return element; } } final tempElement = xml.XmlElement(xml.XmlName(castedName)); tempElement.innerText = text!; if (lang.isNotEmpty && lang != defaultLanguage) { tempElement.setAttribute('xml:lang', lang); } parent!.children.add(tempElement); return tempElement; } /// Set text to wherever sub element under [name]. void _setAllSubText( String name, { required Map<String, String> values, bool keep = false, String? language, }) { deleteSub(name, language: language); for (final entry in values.entries) { if (!(language != null) || language == "*" || entry.key == language) { setSubText(name, text: entry.value, keep: keep, language: entry.key); } } } /// Remove sub elements that match the given [name] or XPath. /// /// If the element is in a path, then any parent elements that become empty /// after deleting the element may also be deleted if requested by setting /// [all] to `true`. @internal void deleteSub(String name, {bool all = false, String? language}) { final path = _fixNamespace(name, split: true).value2!; final originalTarget = path.last; final defaultLanguage = _getLang; final lang = (language == null || language.isEmpty) ? defaultLanguage : language; Iterable<int> enumerate<T>(List<T> iterable) sync* { for (int i = 0; i < iterable.length; i++) { yield i; } } late xml.XmlNode? parent = element; for (final level in enumerate(path)) { final elementPath = path.sublist(0, path.length - level).join('/'); final parentPath = (level > 0) ? path.sublist(0, path.length - level - 1).join('/') : null; final elements = element! .queryXPath('/$elementPath') .nodes .map((item) => item.node) .toList(); if (parentPath != null && parentPath.isNotEmpty) { parent = element!.queryXPath('/$parentPath').node?.node; } if (elements.isNotEmpty) { parent ??= element; for (final element in elements) { if (element is xml.XmlElement) { if (element.name.qualified == originalTarget || element.children.isEmpty) { final elementLanguage = _lang(element) ?? defaultLanguage; if (lang == '*' || elementLanguage == lang) { if (parent!.children[level].innerXml .contains(element.toXmlString())) { parent.children[level].innerXml = parent .children[level].innerXml .replaceFirst(element.toXmlString(), ''); } if (parent.children.contains(element)) { parent.children.remove(element); } } } } } } if (!all) { return; } } } Tuple2<String?, List<String>?> _fixNamespace( String xPath, { bool split = false, bool propogateNamespace = false, }) => fixNamespace( xPath, split: split, propogateNamespace: propogateNamespace, defaultNamespace: namespace, ); /// Return the value of top level attribute of the XML object. /// /// In case the attribute has not been set, a [def] value can be returned /// instead. An empty string is returned if not other default is supplied. @internal String getAttribute(String name, [String def = '']) { if (element == null) return def; return element!.getAttribute(name == 'lang' ? 'xml:lang' : name) ?? def; } /// Set the value of a top level [attribute] of the XML object. /// /// If the new [value] is null or an empty string, then the attribute will be /// removed. @internal void setAttribute( String attribute, [ String? value, ]) { if (value == null || value.isEmpty) { return; } element!.setAttribute(attribute == 'lang' ? 'xml:lang' : attribute, value); } /// Deletes attribute under [name] If there is not [element] associated, /// returns from the function. @internal void deleteAttribute(String name) { if (element == null) return; if (element!.getAttribute(name) != null) element!.removeAttribute(name); } /// Return the value of a stanza interface using operator overload. /// /// ### Example: /// ```dart /// final element = XMLBase(); /// log(element['body']); /// this must print out 'message contents' /// ``` /// /// Stanza interfaces are typically mapped directly to the underlying XML /// object, but can be overridden by the presence of a `getAttribute` method /// (or `foo` getter where the interface is named `foo`, etc). /// /// The search order for interface value retrieval for an interface named /// `foo` is: /// * The list of substanzas (`substanzas`) /// * The result of calling the `getFood` override handler /// * The result of calling `foo` getter /// * The contents of the `foo` subelement, if `foo` is listed in /// `subInterfaces` /// * True or false depending on the existence of a `foo` subelement and `foo` /// is in `boolInterfaces` /// * The value of the `foo` attribute of the XML object /// * The plugin named `foo` /// * An empty string /// /// The search for an element will go through the passed `fullAttribute`. dynamic operator [](String fullAttribute) { final split = '$fullAttribute|'.split('|'); final attribute = split[0]; final language = split[1]; /// Check for if `languageInterfaces` contains both `language` and /// `attribute` values, then assign `args` values respective to the check. final Map<String, String?> args = (languageInterfaces.contains(language) && languageInterfaces.contains(attribute)) ? {'lang': language} : {}; if (attribute == 'substanzas') { return iterables; } else if (interfaces.contains(attribute) || attribute == 'lang') { final getMethod = attribute.toLowerCase(); if (pluginOverrides.isNotEmpty) { final name = pluginOverrides[getMethod]; if (name != null && name.isNotEmpty) { final plugin = getPlugin(name, language: language); if (plugin != null) { final handler = plugin._getters[Symbol(getMethod)]; if (handler != null) return handler.call(args['lang'], plugin); } } } if (_getters.containsKey(Symbol(getMethod))) { return _getters[Symbol(getMethod)]?.call(args['lang'], this); } else { if (subInterfaces.contains(attribute)) { return getSubText(attribute, language: language); } else if (boolInterfaces.contains(attribute)) { return element!.getElement(attribute, namespace: namespace) != null; } else { return getAttribute(attribute); } } } else if (pluginAttributeMapping.containsKey(attribute)) { final plugin = getPlugin(attribute, language: language); if (plugin != null && plugin.isExtension) { return plugin[fullAttribute]; } return plugin; } else { return ''; } } /// Set the [value] of a stanza interface using operator overloading through /// the passed [attribute] string. /// /// ### Example: /// ```dart /// final element = XMLBase(); /// element['body'] = 'hert!'; /// log(element['body']); /// must output 'hert!' /// ``` /// /// Stanza interfaces are typically mapped directly to the underlying XML /// object, but can be overridden by the presence of a `setAttribute` method /// (or `foo` setter where the interface is named `foo`, etc.). void operator []=(String attribute, dynamic value) { final fullAttribute = attribute; final attributeLanguage = '$attribute|'.split('|'); final attrib = attributeLanguage[0]; final lang = attributeLanguage[1].isEmpty ? null : attributeLanguage[1]; final args = <String, String?>{}; if (languageInterfaces.contains(lang) && languageInterfaces.contains(attrib)) { args['lang'] = lang; } if (interfaces.contains(attrib) || attrib == 'lang') { if (value != null) { final setMethod = attrib.toLowerCase(); if (pluginOverrides.isNotEmpty) { final name = pluginOverrides[setMethod]; if (name != null && name.isNotEmpty) { final plugin = getPlugin(name, language: lang); if (plugin != null) { final handler = plugin._setters[Symbol(setMethod)]; if (handler != null) { return handler.call( value, args['lang'], plugin, ); } } } } if (_setters.containsKey(Symbol(setMethod))) { _setters[Symbol(setMethod)]?.call(value, args['lang'], this); } else { if (subInterfaces.contains(attrib)) { dynamic subvalue; if (value is JabberID) { subvalue = value.toString(); } subvalue ??= value; if (lang == '*') { return _setAllSubText( attrib, values: subvalue as Map<String, String>, language: '*', ); } setSubText(attrib, text: subvalue as String?, language: lang); return; } else if (boolInterfaces.contains(attrib)) { if (value != null && value as bool) { setSubText(attrib, text: '', keep: true, language: lang); return; } else { setSubText(attrib, text: '', language: lang); return; } } else { return setAttribute( attrib, (value != null && value is JabberID) ? value.toString() : value as String?, ); } } } } else if (pluginAttributeMapping.containsKey(attrib) && pluginAttributeMapping[attrib] != null) { final plugin = getPlugin(attrib, language: lang); if (plugin != null) { plugin[fullAttribute] = value; } } return; } /// Delete the value of a stanza interface. /// /// Stanza interfaces are typically mapped directly to the underlying XML /// object, but can be overridden by the presence of [noSuchMethod] by adding /// [Function] with [Symbol] key under [gettersAndSetters] [Map]. @internal void delete(String attribute) { final fullAttribute = attribute; final attributeLanguage = '$attribute|'.split('|'); final attrib = attributeLanguage[0]; final lang = attributeLanguage[1].isNotEmpty ? attributeLanguage[1] : null; final args = <String, String?>{}; if (languageInterfaces.contains(lang) && languageInterfaces.contains(attrib)) { args['lang'] = lang; } if (interfaces.contains(attrib) || attrib == 'lang') { final deleteMethod = attrib.toLowerCase(); if (pluginOverrides.isNotEmpty) { final name = pluginOverrides[deleteMethod]; if (name != null && name.isNotEmpty) { final plugin = getPlugin(attrib, language: lang); if (plugin != null) { final handler = plugin._deleters[Symbol(deleteMethod)]; if (handler != null) { handler.call(args['lang'], plugin); return; } } } } if (_deleters.containsKey(Symbol(deleteMethod))) { _deleters[Symbol(deleteMethod)]?.call(args['lang'], this); } else { if (subInterfaces.contains(attrib)) { return deleteSub(attrib, language: lang); } else if (boolInterfaces.contains(attrib)) { return deleteSub(attrib, language: lang); } else { return deleteAttribute(attrib); } } } else if (pluginAttributeMapping.containsKey(attrib) && pluginAttributeMapping[attrib] != null) { final plugin = getPlugin(attrib, language: lang, check: true); if (plugin == null) { return; } if (plugin.isExtension) { plugin.delete(fullAttribute); _plugins.remove(Tuple2(attrib, '')); } else { _plugins.remove(Tuple2(attrib, plugin['lang'])); } try { element!.children.remove(plugin.element); } catch (_) {} } } /// Add either an [xml.XmlElement] object or substanza to this stanza object. /// /// If a substanza object is appended, it will be added to the list of /// iterable stanzas. /// /// Allows stanza objects to be used like lists. XMLBase add(dynamic item) { late Tuple2<xml.XmlElement?, XMLBase?> tuple; if (item is xml.XmlElement) { tuple = Tuple2(item, null); } else { try { tuple = Tuple2(null, item as XMLBase); } on Exception { if (dynamic is! XMLBase || dynamic is! xml.XmlElement) { throw ArgumentError( 'The item that is going to be added should be either XMLBase or Xml Element', ); } } } if (tuple.value1 != null) { if (tuple.value1!.nodeType == xml.XmlNodeType.ELEMENT) { return _addXML(tuple.value1!); } else { throw ArgumentError('The provided element is not in type of XmlNode'); } } if (tuple.value2 != null) { final base = tuple.value2!; element?.children.add(base.element!); if (base == pluginTagMapping[base._tagName]) { initPlugin( base.pluginAttribute, existingXML: base.element, element: base, reuse: false, ); } else if (pluginIterables.contains(base)) { iterables.add(base); if (base.pluginMultiAttribute != null && base.pluginMultiAttribute!.isNotEmpty) { initPlugin(base.pluginMultiAttribute!); } } else { iterables.add(base); } } return this; } /// Adds child element to the underlying XML element. XMLBase _addXML(xml.XmlElement element) => this..element!.children.add(element); /// Returns the namespaced name of the stanza's root element. /// /// The format for the tag name is: '{namespace}elementName'. String get _tagName => '{$namespace}$name'; /// Gets current language of the xml element with xPath query. String? _lang(xml.XmlNode element) { final result = element .queryXPath( "//@*[local-name()='xml:lang' and namespace-uri()='${WhixpUtils.getNamespace('XML')}']", ) .node; if (result == null) return null; return result.node.getAttribute('xml:lang'); } /// Gets language from underlying parent. String get _getLang { if (element == null) return ''; final result = _lang(element!); if (result == null && parent != null) { return parent!['lang'] as String; } return result ?? ''; } /// Getter for stanza plugins list. @internal Map<Tuple2<String, String>, XMLBase> get plugins => _plugins; /// Compares a stanza object with an XPath-like expression. /// /// If the XPath matches the contents o the stanza obejct, the match is /// succesfull. /// /// The XPath expression may include checks for stanza attributes. @internal bool match(Tuple2<String?, List<String>?> xPath) { late List<String> xpath; if (xPath.value1 != null) { xpath = _fixNamespace(xPath.value1!, split: true).value2!; } else { xpath = xPath.value2!; } /// Extract the tag name and attribute checks for the first XPath node final components = xpath[0].split('@'); final tag = components[0]; final attributes = components.sublist(1); if (!{name, '{$namespace}$name'}.contains(tag) && !_loadedPlugins.contains(tag) && !pluginAttribute.contains(tag)) { return false; } /// Checks the rest of the XPath against any substanzas bool matchedSubstanzas = false; for (final substanza in iterables) { if (xpath.sublist(1).isEmpty) { break; } matchedSubstanzas = substanza.match(Tuple2(null, xpath.sublist(1))); if (matchedSubstanzas) { break; } } /// Checks attribute values for (final attribute in attributes) { final name = attribute.split('=')[0]; final value = attribute.split('=')[1]; if (this[name] != value) { return false; } } /// Checks sub interfaces if (xpath.length > 1) { final nextTag = xpath[1]; if (subInterfaces.contains(nextTag) && this[nextTag] != null) { return true; } } /// Attempt to continue matching the XPath using the stanza's plugin if (!matchedSubstanzas && xpath.length > 1) { final nextTag = xpath[1].split('@')[0].split('}').last; final tags = <int, String?>{}; int i = 0; for (final entry in _plugins.entries) { if (entry.key.value1 == nextTag) { tags[i] = entry.key.value2.isEmpty ? null : entry.key.value2; i++; } } for (final entry in tags.entries) { final plugin = getPlugin(nextTag, language: entry.value); if (plugin != null && plugin.match(Tuple2(null, xpath.sublist(1)))) { return true; } } return false; } /// Everything matched return true; } /// Returns the names of all stanza interfaces provided by the stanza object. /// /// Allows stanza objects to be used as [Map]. @internal List<String> get keys { final buffer = <String>[]; for (final x in interfaces) { buffer.add(x); } for (final x in _loadedPlugins) { buffer.add(x); } buffer.add('lang'); if (iterables.isNotEmpty) { buffer.add('substanzas'); } return buffer; } /// Set multiple stanza interface [values] using [Map]. /// /// Stanza plugin values may be set using nested [Map]s. set _values(Map<String, dynamic> values) { final iterableInterfaces = <String>[ for (final p in pluginIterables) p.pluginAttribute, ]; if (values.containsKey('lang')) { this['lang'] = values['lang']; } if (values.containsKey('substanzas')) { for (final stanza in iterables) { element!.children.remove(stanza.element); } iterables.clear(); final substanzas = values['substanzas'] as List<Map<String, dynamic>>; for (final submap in substanzas) { if (submap.containsKey('__childtag__')) { for (final subclass in pluginIterables) { final childtag = '{${subclass.namespace}}${subclass.name}'; if (submap['__childtag__'] == childtag) { final sub = subclass.copy(parent: this); sub.values = submap; iterables.add(sub); } } } } } for (final entry in values.entries) { final fullInterface = entry.key; final interfaceLanguage = '${entry.key}|'.split('|'); final interface = interfaceLanguage[0]; final language = interfaceLanguage[1]; if (interface == 'lang') { continue; } else if (interface == 'substanzas') { continue; } else if (interfaces.contains(interface)) { this[fullInterface] = entry.value; } else if (pluginAttributeMapping.containsKey(interface)) { if (!iterableInterfaces.contains(interface)) { final plugin = getPlugin(interface, language: language); if (plugin != null) { plugin.values = entry.value as Map<String, dynamic>; } } } } return; } /// Returns a JSON/Map version of the XML content exposed through the stanza's /// interfaces. Map<String, dynamic> get _values { final values = <String, dynamic>{}; values['lang'] = this['lang']; for (final interface in interfaces) { if (this[interface] is JabberID) { values[interface] = (this[interface] as JabberID).jid; } else { values[interface] = this[interface]; } if (languageInterfaces.contains(interface)) { values['$interface|*'] = this['$interface|*']; } } for (final plugin in _plugins.entries) { final lang = plugin.value['lang']; if (lang != null && (lang as String).isNotEmpty) { values['${plugin.key.value1}|$lang'] = plugin.value.values; } else { values[plugin.key.value1] = plugin.value.values; } } if (iterables.isNotEmpty) { final iter = <Map<String, dynamic>>[]; for (final stanza in iterables) { iter.add(stanza.values); if (iter.length - 1 >= 0) { iter[iter.length - 1]['__childtag__'] = stanza.tag; } } values['substanzas'] = iter; } return values; } /// Remove all XML element contents and plugins. @internal void clear() { element!.children.clear(); for (final plugin in _plugins.keys) { _plugins.remove(plugin); } } /// Returns a JSON/Map version of the XML content exposed through the stanza's /// interfaces. @internal Map<String, dynamic> get values => _values; /// Set multiple stanza interface [values] using [Map]. /// /// Stanza plugin values may be set using nested [Map]s. set values(Map<String, dynamic> values) => _values = values; /// Getter for private [Map] [_getters]. @internal Map<Symbol, _GetterOrDeleter> get getters => _getters; /// Getter for private [Map] [_setters]. @internal Map<Symbol, _Setter> get setters => _setters; /// Getter for private [Map] [_deleters]. @internal Map<Symbol, _GetterOrDeleter> get deleters => _deleters; /// You need to override this method in order to create a copy from an /// existing object due Dart do not have deep copy support for now. /// /// ### Example: /// ```dart /// class SimpleStanza extends XMLBase { /// SimpleStanza({super.element, super.parent}); /// /// @override /// XMLBase copy({xml.XmlElement? element, XMLBase? parent}) => /// SimpleStanza(element: element, parent: parent); /// } /// ``` @internal XMLBase copy({xml.XmlElement? element, XMLBase? parent}) => XMLBase( name: name, namespace: namespace, pluginAttribute: pluginAttribute, pluginMultiAttribute: pluginMultiAttribute, overrides: overrides, pluginTagMapping: pluginTagMapping, pluginAttributeMapping: pluginAttributeMapping, interfaces: interfaces, subInterfaces: subInterfaces, boolInterfaces: boolInterfaces, languageInterfaces: languageInterfaces, pluginIterables: pluginIterables, getters: _getters, setters: _setters, deleters: _deleters, isExtension: isExtension, includeNamespace: includeNamespace, element: element, parent: parent, ); /// Add a custom getter function to the [XMLBase] class, allowing users to /// extend behavior of the class by defining custom getters for specific /// attributes. /// /// ### Example: /// ```dart /// final base = XMLBase('someStanza'); /// base.addGetters({Symbol('value'): (args, base) { /// base.element.children!.remove(someChild); /// calling "value" getter will remove child /// }}); /// ``` @internal void addGetters(Map<Symbol, _GetterOrDeleter> getters) => _getters.addAll(getters); /// Adds custom setter functions to the [XMLBase] class, enabling users to /// extend the class by defining custom setters for specific attributes. /// /// ### Example: /// ```dart /// final base = XMLBase('someStanza'); /// base.addSetters({Symbol('value'): (args, value, base) { /// base.element.children!.remove(someChild); /// calling "value" setter will remove child /// }}); /// ``` @internal void addSetters(Map<Symbol, _Setter> setters) => _setters.addAll(setters); /// Adds custom deleter functions to the [XMLBase] class, allowing users to /// extend the class by defining custom deleter functions for specific /// attributes. /// /// ### Example: /// ```dart /// final base = XMLBase('someStanza'); /// base.addDeleters({Symbol('value'): (args, value, base) { /// base.element.children!.remove(someChild); /// calling "value" setter will remove child /// }}); /// ``` @internal void addDeleters(Map<Symbol, _GetterOrDeleter> deleters) => _deleters.addAll(deleters); /// When iterating over [XMLBase], helps to increment our plugin index. void _incrementIndex() => _index++; /// Returns a string serialization of the underlying XML object. @override String toString() => WhixpUtils.serialize(element) ?? ''; } /// Extender for [registerStanzaPlugin] method. extension RegisterStanza on XMLBase { /// Does what [registerStanzaPlugin] does. But without primary stanza. 'Cause /// it is called as the part of the primary stanza and do not need it to /// passed. /// /// [iterable] flag indicates if the plugin stanza should be included in the /// parent stanza's iterable [substanzas] interface results. /// /// [overrides] flag indicates if the plugin should be allowed to override the /// interface handlers for the parent stanza, based on the plugin's /// [overrides] field. @internal void registerPlugin( XMLBase plugin, { bool iterable = false, bool overrides = false, }) => registerStanzaPlugin( this, plugin, iterable: iterable, overrides: overrides, ); }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- css --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"/> <link rel="stylesheet" href="./mercari.css"/> <!-- script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script type="text/javascript"> //子カテゴリ自動生成 $(function () { $('.parent').change(function() { var parent = $('.parent').val(); $.ajax({ /* data: { searchName: $('#searchName').val() }, */ url: '/ajax/setUpCategoryName', data: { parentName: $('.parent').val() }, dataType: 'json' }) .done(function(childList) { $('select#area option').remove(); for (const child of childList) { $('select#area').append($('<option>').html(child).val(child)); } }) }); }); //孫カテゴリ自動生成 $(function () { $('.child').change(function() { var child = $('.child').val(); $.ajax({ url: '/ajax/setUpGrandChildCategoryName', data: {childName: child}, dataType: 'json' }) .done(function(grandChildList) { $('select#air option').remove(); for(const grandChild of grandChildList) { $('select#air').append($('<option>').html(grandChild).val(grandChild)); } }) }); }); </script> <title>Rakus Items</title> </head> <body> <!-- navbar --> <nav class="navbar navbar-inverse"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="./list.html">Rakus Items</a> </div> <div id="navbar" class="collapse navbar-collapse"> <div> <ul class="nav navbar-nav navbar-right"> <li><a id="logout" href="./login.html">Logout&nbsp;<i class="fa fa-power-off"></i></a></li> </ul> <p class="navbar-text navbar-right"> <span id="loginName">user: userName</span> </p> </div> </div> </nav> <!-- details --> <div id="input-main" class="container"> <a type="button" class="btn btn-default" href="./detail.html"><i class="fa fa-reply"></i> back</a> <h2>Edit</h2> <!-- edit form --> <form th:action="@{/editing}" method="POST" class="form-horizontal" th:object="${itemEditForm}"> <span th:each = "itemCategoryJoin : ${itemCategoryJoins}"> <!-- name --> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">name</label> <div class="col-sm-8"> <input type="text" class="form-control" id="inputName"/ name="name" th:value="${itemCategoryJoin.name}"> <span class="text-danger" th:if="${#fields.hasErrors('name')}" th:errors="*{name}" style="color:red">error:may not be empty</span> </div> </div> <!-- price --> <div class="form-group"> <label for="price" class="col-sm-2 control-label">price</label> <div class="col-sm-8"> <input type="text" class="form-control" id="price"/ name="price" th:value="${itemCategoryJoin.price}"> <span class="text-danger" th:if="${#fields.hasErrors('price')}" th:errors="*{price}" style="color:red">error:may not be empty</span> </div> </div> <!-- category --> <div class="form-group"> <label for="category" class="col-sm-2 control-label">category</label> <div class="col-sm-8"> <select class="form-control parent" name="parentCategoryName"> <option th:each = "categorie : ${categories}" th:value="${categorie.name}" th:text="${categorie.name}" th:selected="${categorie.name == name.parentName}">parentCategory</option> </select> </div> </div> <div class="form-group"> <label for="category" class="col-sm-2 control-label"></label> <div class="col-sm-8"> <select class="form-control child" id="area" name="childCategoryName"> <option id="childList" th:each = "childName : ${childNameList}" th:text="${childName}" th:selected="${childName == childName1}">parentCategory</option> </select> </div> </div> <div class="form-group"> <label for="category" class="col-sm-2 control-label"></label> <div class="col-sm-8"> <select class="form-control" id="air" name="grandchildCategoryName"> <option th:each = "grandChildName : ${grandChildNameList}" th:text="${grandChildName}" th:selected="${grandChildName == name.grandChildName}">parentCategory</option> </select> </div> </div> <!-- brand --> <div class="form-group"> <label for="brand" class="col-sm-2 control-label">brand</label> <div class="col-sm-8"> <input type="text" id="brand" class="form-control" name="brand"/ th:value="${itemCategoryJoin.brand}"> <!-- <span class="text-danger" th:if="${#fields.hasErrors('brand')}" th:errors="*{brand}" style="color:red">error:may not be empty</span> --> </div> </div> <!-- condition --> <div class="form-group"> <label for="condition" class="col-sm-2 control-label">condition</label> <div class="col-sm-8"> <span th:each="condition : ${conditionList}"> <label for="condition1" class="radio-inline"> <span> <input type="radio" name="condition" id="condition1" value="1"/ th:value="${condition.key}" th:text="${condition.value}" th:checked="${condition.value == itemCategoryJoin.condition}"> </span> </label> </span> </div> </div> <div class="form-group"> <label for="category" class="col-sm-2 control-label"></label> <div class="col-sm-8"> <span class="text-danger" th:if="${#fields.hasErrors('condition')}" th:errors="*{condition}" style="color:red">error:may not be empty</span> </div> </div> <!-- description --> <div class="form-group"> <label for="description" class="col-sm-2 control-label">description</label> <div class="col-sm-8"> <input name="description" id="description" class="form-control" rows="5" th:value="${itemCategoryJoin.description}"> <span class="text-danger" th:if="${#fields.hasErrors('description')}" th:errors="*{description}" style="color:red">error:may not be empty</span> <input type="hidden" name="id" th:value="${itemCategoryJoin.id}"> </div> </div> <!-- submit button --> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </span> </form> </div> </body> </html>
import React from 'react' import PropTypes from 'prop-types' import UploadMultiImages from 'components/UploadMultiImages' import { FormFeedback, Input, Spinner, FormGroup, Row, Col, Label, Button } from 'reactstrap' import { STRING } from 'constants/Constant' UploadMultiImageTour.propTypes = { listImage: PropTypes.array, editTour: PropTypes.bool, } UploadMultiImageTour.defaultProps = { listImage: [], editTour: false, } function UploadMultiImageTour(props) { const { listImage, editTour } = props return ( <Row> <Col xs="12" md="3" lg="2"> <Label for="exampleEmail">{STRING.tourPhoto}</Label> </Col> <Col xs="12" md="8" lg="9" className="row"> {listImage?.map((item, index) => ( <Col xs="6" sm="4" xl="3" xxl="2" key={index}> {index === 0 ? ( <UploadMultiImages numberOfElement={1} text={STRING.avatar} index={index} changeMultiImages={props.handleChangeMultiImg} fileListImg={item?.fileList} edit={editTour} // detail={productDetail} /> ) : ( <UploadMultiImages numberOfElement={1} text={`Ảnh số ${index}`} index={index} changeMultiImages={props.handleChangeMultiImg} fileListImg={item?.fileList} edit={editTour} // detail={productDetail} /> )} </Col> ))} </Col> </Row> ) } export default React.memo(UploadMultiImageTour)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Creational.Prototype.Example2 { internal class Program { static void Main(string[] args) { // Create prototype object ICloneable originalPerson = new Person { Name = "Luis", Age = 23 }; // Clone the prototype object ICloneable clonedPerson = originalPerson.Clone(); //modifi the clone without affecting the original ((Person)clonedPerson).Name = "Bob"; ((Person)clonedPerson).Age = 25; // Show details Console.WriteLine("Original Personl"); originalPerson.Display(); Console.WriteLine("Cloned Person"); clonedPerson.Display(); } } }
import React from "react"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import LoginPage from "./components/LoginPage/LoginPage"; import List from "./components/List/List"; import RouteGuard from "./components/RouteGuard/RouteGuard"; import AddEntityForm from "./components/AddEntityForm/AddEntityForm"; import Attributes from "./components/Attributes/Attributes"; import Attribute from "./components/Attribute/Attribute"; import Details from "./components/Details/Details"; import EditEntityForm from "./components/EditEntityForm/EditEntityForm"; import { listConfig } from "./components/List/config"; import { detailsConfig } from "./components/Details/config"; import { createConfig } from "./components/AddEntityForm/config"; import { editConfig } from "./components/EditEntityForm/config"; const App = () => { return ( <BrowserRouter> <Routes> <Route path="/" element={<LoginPage />} /> {listConfig.map(list => ( <Route path={list.path} element={ <RouteGuard> <List {...list}/> </RouteGuard> } /> ))} <Route path="/attributes" element={ <RouteGuard> <Attributes /> </RouteGuard> } /> <Route path="/attribute/:type" element={ <RouteGuard> <Attribute /> </RouteGuard> } /> {detailsConfig.map(detail => ( <Route path={`${detail.path}/:id`} element={ <RouteGuard> <Details {...detail} /> </RouteGuard> } /> ))} {editConfig.map(edit => ( <Route path={`${edit.path}/edit/:id`} element={ <RouteGuard> <EditEntityForm {...edit}/> </RouteGuard> } /> ))} {createConfig.map(create => ( <Route path={`/add${create.path}`} element={ <RouteGuard> <AddEntityForm {...create} /> </RouteGuard> } /> ))} </Routes> </BrowserRouter> ); }; export default App;
using DG.Tweening; using AwesomeTools.Inputs; using UnityEngine; using UsefulComponents; using AwesomeTools.Sound; using AwesomeTools; namespace Tomato { public class Worm : MonoBehaviour { public static int UncatchedWormCount; private const string crawlingSound = "Crawling"; private const string animationName = "Drag"; private const string animationOnScene = "OnScene"; [SerializeField] private Collider2D _selfCollider; [SerializeField] private Animator _animator; [SerializeField] private SpriteRenderer _sprite; [SerializeField] private RandomMover _randomMover; [SerializeField] private DragAndDrop _dragAndDrop; [SerializeField] private MoveToDestinationOnDragEnd _destinationOnDrag; private SoundSystem _soundSystem; private Vector3 _cachedScale; private Vector3 _destinationPoint; private int _nonDragSortingOrder; public bool _onAdditionalAction; /// <summary> /// Вводимо систему вводу [inputSystem] - присвоє систему вводу до "DragAndDrop" та /// кінцеву точку для скрипту "MoveToDestinationOnDragEnd" [_destinationOnDrag] /// </summary> public void Construct(InputSystem inputSystem, SoundSystem soundSystem) { _soundSystem = soundSystem; _dragAndDrop.Construct(inputSystem); _destinationPoint = transform.position; _destinationOnDrag.Construct(_destinationPoint); _destinationOnDrag.OnMoveComplete += MakeInteractable; WormsBasket.OnOneWormLeft += () => _onAdditionalAction = true; _onAdditionalAction = false; } /// <summary> /// Запа'ятовує розмір елементу і присвоює ф-ції до подій "DragAndDrop" /// </summary> private void Awake() { _cachedScale = transform.localScale; transform.localScale = Vector3.zero; _dragAndDrop.OnDragStart += StopCrawlingSound; _dragAndDrop.OnDragStart += DisableMoving; _dragAndDrop.OnDragStart += SetDragSortingOrder; _dragAndDrop.OnDragStart += () => ChangeDragAnimation(true); _dragAndDrop.OnDragEnded += MakeNonInteractable; _dragAndDrop.OnDragEnded += SetUnDragSortingOrder; _dragAndDrop.OnDragEnded += EnableMoving; } /// <summary> /// Видаляє ф-ції з подій "DragAndDrop" /// </summary> private void OnDestroy() { _dragAndDrop.OnDragStart -= DisableMoving; _dragAndDrop.OnDragStart -= SetDragSortingOrder; _dragAndDrop.OnDragStart -= () => ChangeDragAnimation(true); _dragAndDrop.OnDragEnded -= MakeNonInteractable; _dragAndDrop.OnDragEnded -= SetUnDragSortingOrder; _dragAndDrop.OnDragEnded -= EnableMoving; } /// <summary> /// Вводимо порядок в слою [nonDragSortingOrder] - запам'ятовує порядок слою в полі "_nonDragSortingOrder" /// </summary> public void SetNonDragSortingOrder(int nonDragSortingOrder) { _nonDragSortingOrder = nonDragSortingOrder; } /// <summary> /// Присвоює значення "position.y" до скрипту "RandomMover" /// </summary> public void SetYToMover() { _randomMover.InitialPosY(); _animator.SetBool(animationOnScene, true); } /// <summary> /// Відтворює звук повзання "crawlingSound" /// </summary> private void PlayCrawlingSound() { _soundSystem.PlaySound(crawlingSound); } /// <summary> /// Зупиняє звук повзання "crawlingSound" /// </summary> public void StopCrawlingSound() { UncatchedWormCount--; if(UncatchedWormCount < 1) { _soundSystem.StopSound(crawlingSound); } } /// <summary> /// Забороняє взаємодію з елементом і зупиняє елемент /// </summary> public void MakeNonInteractable() { DOTween.Kill(gameObject); _dragAndDrop.IsDraggable = false; _selfCollider.enabled = false; ChangeDragAnimation(false); DisableMoving(); } /// <summary> /// Дозволяє взаємодію з елементом /// </summary> public void MakeInteractable() { UncatchedWormCount++; if(_onAdditionalAction) { PlayCrawlingSound(); } _selfCollider.enabled = true; _dragAndDrop.IsDraggable = true; ChangeDragAnimation(false); } /// <summary> /// Вводимо порядок в слою [_indexSortingOrder] - присвоює спрайту елемента [_sprite] порядок в слою /// </summary> public void SetVisualNonInteractOrder(int _indexSortingOrder) { _sprite.sortingOrder = _indexSortingOrder; _sprite.DOFade(0.7f, 1).SetLink(_sprite.gameObject); } /// <summary> /// Вводимо булеве значення [value]- присвоює булеве значення до аніматора елементу [_animator] /// </summary> public void ChangeDragAnimation(bool value) { HintSystem.Instance.HidePointerHint(); _animator.SetBool(animationName, value); } /// <summary> /// Показує елемент /// </summary> public void Appear() { transform.DOScale(_cachedScale, 1f).SetLink(gameObject).OnComplete(SetYToMover); DOVirtual.DelayedCall(0.5f, () => { PlayCrawlingSound(); } ); } /// <summary> /// Присвоює порядок слою,коли тримаєш елемент /// </summary> private void SetDragSortingOrder() => _sprite.sortingOrder = 16; /// <summary> /// Присвоює порядок слою, коли не тримаєш елемент /// </summary> private void SetUnDragSortingOrder() => _sprite.sortingOrder = _nonDragSortingOrder; /// <summary> /// Забороняє рух елементу /// </summary> private void DisableMoving() { _randomMover.enabled = false; } /// <summary> /// Дозволяє рух елементу /// </summary> private void EnableMoving() => _randomMover.enabled = true; } }
import { NextFunction, Request, Response, Router } from 'express'; import validationMiddleware from '../../middleware/validation.middleware'; import HttpException from '../../utils/exceptions/http.exception'; import Controller from '../../utils/interfaces/controller.Interface'; import PostService from './post.service'; import validate from './post.validation'; class PostController implements Controller { public path = '/posts'; public router = Router(); private PostService = new PostService(); constructor() { this.initializeRoutes(); } private initializeRoutes(): void { this.router.post( `${this.path}`, validationMiddleware(validate.create), this.create ); } private create = async ( req: Request, res: Response, next: NextFunction ): Promise<Response | void> => { try { const { title, body } = req.body; const post = this.PostService.create(title, body); res.status(201).json({ post }); } catch (err) { next(new HttpException(400, 'Cannot create post')); } }; } export default PostController;
package com.projects.eventsbook.service.order; import com.projects.eventsbook.DAO.BoughtTicketRepositoryJPA; import com.projects.eventsbook.DAO.EventRepositoryJPA; import com.projects.eventsbook.DAO.GroupRepositoryJpa; import com.projects.eventsbook.DAO.UserRepository; import com.projects.eventsbook.entity.*; import com.projects.eventsbook.exceptions.InvalidOperationException; import com.projects.eventsbook.exceptions.NoEntityFoundException; import com.projects.eventsbook.util.RetrieveUtil; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import java.util.UUID; import java.util.stream.IntStream; @Transactional @Component public class OrderServiceImpl implements OrderService{ private final UserRepository userRepository; private final BoughtTicketRepositoryJPA boughtTicketRepository; private final EventRepositoryJPA eventRepository; private final GroupRepositoryJpa groupRepository; public OrderServiceImpl(UserRepository userRepository, BoughtTicketRepositoryJPA boughtTicketRepository, EventRepositoryJPA eventRepository, GroupRepositoryJpa groupRepository) { this.userRepository = userRepository; this.boughtTicketRepository = boughtTicketRepository; this.eventRepository = eventRepository; this.groupRepository = groupRepository; } @Override public void createOrder(Long userId, Long eventId, Long ticketTemplateId, Integer ticketsCount) { User currentUser = RetrieveUtil.getByIdWithException(this.userRepository, userId); Event currentEvent = RetrieveUtil.getByIdWithException(this.eventRepository, eventId); Optional<TicketTemplate> ticketToBuy = currentEvent.getTicketTemplateById(ticketTemplateId); if (ticketToBuy.isEmpty()) { throw new NoEntityFoundException("No such ticket template!"); } TicketTemplate ticket = ticketToBuy.get(); double orderPrice = ticketsCount * ticket.getPrice(); if (currentUser.getBalance() < orderPrice) { throw new InvalidOperationException("Insufficient funds in account"); } if (ticket.getCurrentTicketsCount() < ticketsCount) { throw new InvalidOperationException("You can but only " + ticket.getCurrentTicketsCount() + " tickets"); } currentUser.setBalance(currentUser.getBalance() - orderPrice); currentEvent.getEventGroup().setBalance(currentEvent.getEventGroup().getBalance() + orderPrice); ticket.setCurrentTicketsCount(ticket.getCurrentTicketsCount() - ticketsCount); BoughtTicket order = new BoughtTicket(ticket, currentUser, ticketsCount); eventRepository.save(currentEvent); userRepository.save(currentUser); createActivations(order); boughtTicketRepository.save(order); groupRepository.save(currentEvent.getEventGroup()); } private void createActivations(BoughtTicket order) { IntStream.range(0, order.getTicketsCount()) .forEach(number -> { order .getTicketActivations() .add(new TicketActivation(UUID.randomUUID().toString(), order)); }); } }
package com.st00.afir.android_me.ui; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.GridView; import android.widget.Toast; import com.st00.afir.android_me.R; import com.st00.afir.android_me.data.AndroidImageAssets; public class MainActivity extends AppCompatActivity implements MasterListFragment.OnImageClickListener { private int headIndex; private int bodyIndex; private int legIndex; private boolean mTwoPane; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); if (findViewById(R.id.android_me_linear_layout) != null) { // This LinearLayout will only initially exist in the two-pane tablet case mTwoPane = true; // Change the GridView to space out the images more on tablet GridView gridView = (GridView) findViewById(R.id.images_grid_view); gridView.setNumColumns(2); // Getting rid of the "Next" button that appears on phones for launching a separate activity Button nextButton = (Button) findViewById(R.id.next_button); nextButton.setVisibility(View.GONE); if (savedInstanceState == null) { // In two-pane mode, add initial BodyPartFragments to the screen FragmentManager fragmentManager = getSupportFragmentManager(); // Creating a new head fragment BodyPartFragment headFragment = new BodyPartFragment(); headFragment.setImageIds(AndroidImageAssets.getHeads()); // Add the fragment to its container using a transaction fragmentManager.beginTransaction() .add(R.id.head_container, headFragment) .commit(); // New body fragment BodyPartFragment bodyFragment = new BodyPartFragment(); bodyFragment.setImageIds(AndroidImageAssets.getBodies()); fragmentManager.beginTransaction() .add(R.id.body_container, bodyFragment) .commit(); // New leg fragment BodyPartFragment legFragment = new BodyPartFragment(); legFragment.setImageIds(AndroidImageAssets.getLegs()); fragmentManager.beginTransaction() .add(R.id.leg_container, legFragment) .commit(); } } else { // We're in single-pane mode and displaying fragments on a phone in separate activities mTwoPane = false; } } @Override public void onImageSelected(int position) { Toast.makeText(this, "position clicked: " + position, Toast.LENGTH_SHORT).show(); int bodyPartNumber = position / 12; // Store the correct list index no matter where in the image list has been clicked // This ensures that the index will always be a value between 0-11 int listIndex = position - 12 * bodyPartNumber; // Set the currently displayed item for the correct body part fragment if (mTwoPane) { // Create two=pane interaction BodyPartFragment newFragment = new BodyPartFragment(); // Set the currently displayed item for the correct body part fragment switch (bodyPartNumber) { case 0: // A head image has been clicked // Give the correct image resources to the new fragment newFragment.setImageIds(AndroidImageAssets.getHeads()); newFragment.setListIndex(listIndex); // Replace the old head fragment with a new one getSupportFragmentManager().beginTransaction() .replace(R.id.head_container, newFragment) .commit(); break; case 1: newFragment.setImageIds(AndroidImageAssets.getBodies()); newFragment.setListIndex(listIndex); getSupportFragmentManager().beginTransaction() .replace(R.id.body_container, newFragment) .commit(); break; case 2: newFragment.setImageIds(AndroidImageAssets.getLegs()); newFragment.setListIndex(listIndex); getSupportFragmentManager().beginTransaction() .replace(R.id.leg_container, newFragment) .commit(); break; default: break; } } else { switch (bodyPartNumber) { case 0: headIndex = listIndex; break; case 1: bodyIndex = listIndex; break; case 2: legIndex = listIndex; break; default: break; } } // Put this information in a Bundle and attach it to an Intent that will launch an AndroidMeActivity Bundle b = new Bundle(); b.putInt("headIndex", headIndex); b.putInt("bodyIndex", bodyIndex); b.putInt("legIndex", legIndex); // Attach the Bundle to an intent final Intent intent = new Intent(this, AndroidMeActivity.class); intent.putExtras(b); // The "Next" button launches a new AndroidMeActivity Button nextButton = (Button) findViewById(R.id.next_button); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(intent); } }); } }
<template> <div ref="rootElem" class="example-item"> <h3>{{ title }}</h3> <div class="case-items"> <slot /> </div> <HtmlPreviewer :source="source" /> </div> </template> <script lang="ts" setup> import { ref, onMounted, nextTick } from 'vue' const props = defineProps<{ title: string source: string }>() const rootElem = ref(null) onMounted(() => { if (rootElem.value === null) return const itemsElem = (rootElem.value as HTMLDivElement).querySelector('.case-items') as HTMLDivElement nextTick(() => { if (itemsElem) { itemsElem.style.height = itemsElem.offsetHeight + 'px' } }) }) </script> <style lang="scss" scoped> .example-item__tools { padding-bottom: var(--space-1); border-bottom: 1px solid var(--color-border); } .case-items { &--inline { display: flex; align-items: flex-end; } } </style>
import PropTypes from 'prop-types' import Button from './Button' import {useLocation} from 'react-router-dom' const Header = (props) => { const location = useLocation() return ( <header className='header'> <h1>{props.title}</h1> {location.pathname === '/' && <Button color={props.showAdd ? 'red' : 'green'} text={props.showAdd ? 'Close' : 'Add'} onClick={props.onAdd} />} </header> ) } Header.defaultProps = { title: "Task Tracker" } Header.propTypes = { title: PropTypes.string.isRequired } //CSS in JS // const headingStyle = { // color: 'red', // backgroundColor: 'black' // } export default Header
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <link href="assets/vendor/icofont/icofont.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <link href="assets/img/favicon.png" rel="icon"> <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon"> <link rel="stylesheet" type="text/css" href="/css/style.css"> <title>Add pet</title> </head> <body> <div id="topbar" class="d-none d-lg-flex align-items-center fixed-top"> </div> <header id="header" class="fixed-top"> <div class="container d-flex align-items-center"> <h1 class="logo mr-auto"> <a href="/home">Pet Clinic</a> </h1> <nav class="nav-menu d-none d-lg-block"> <ul> <li class="active"><a href="/home">Home</a></li> <li><a href="/home/#about">About</a></li> <li><a href="/home/#services">Services</a></li> <li><a href="/home/#contact">Contact</a></li> <li><a href="/add/pet/#my-pet">My Pets</a></li> <li> <security:authorize access="isAuthenticated()"> <li><a>Welcome: <c:out value="${currentUser.username}"></c:out></a></li> <li> <form id="logoutForm" method="POST" action="/logout"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> <input type="submit" class="btn btn-link" value="Logout!" /> </form> </li> </security:authorize> </li> </ul> </nav> <a href="/add/appointment" class="appointment-btn scrollto">Make an Appointment</a> </div> </header> <section id="appointment" class="appointment section-bg "> <div class="spacetop"> <div class="d-flex justify-content-evenly"> <div class="section-title"> <h2>Add your pet</h2> <p></p> </div> </div> <div class="d-flex justify-content-evenly"> <div> <form:form class="php-email-form" action="/add/pet" method="POST" modelAttribute="petModel"> <div class="form-row"> <div class="col-md-12 form-group"> <form:label class="form-label" path="name">Name</form:label> <form:input class="form-control" id="name" path="name" /> <div class="validate"></div> </div> <div class="col-md-12 form-group"> <form:label class="form-label" path="age">Age</form:label> <form:input class="form-control" type="number" path="age" /> <div class="validate"></div> </div> <div class="col-md-12 form-group"> <form:label class="form-label" path="sex">Sex</form:label> <form:input class="form-control" id="name" path="sex" /> <div class="validate"></div> </div> <p> <form:hidden path="owner" value="${currentUser.id}"/> </p> </div> <div class="col-md-12 form-group"> <form:label class="form-label" path="specie">Specie</form:label> <form:select path="specie" class="form-select"> <form:option value="NONE">Select pet</form:option> <c:forEach items="${species}" var="specie"> <form:option value="${specie.id}">${specie.specieName}</form:option> </c:forEach> </form:select> </div> <br/> <div class="d-flex justify-content-center"> <button type="submit">Register</button> </div> </form:form> </div> </div> </section> <section id="my-pet" class="services"> <div class="container"> <div class="section-title"> <h2>Upcoming</h2> <p>Keep track of your pet Info</p> </div> <div class="container d-flex align-items-center"> <div class="table-responsive"> <table class="table table-condensed table-bordered"> <thead> <tr> <th>Pet Name</th> <th>Pet Type</th> <th>Pet Age</th> <th>Visit Date</th> <th>Hour</th> <th>Service</th> <th>Veterinarian/Groomer</th> <th></th> </tr> </thead> <tbody> <!-- Single event in a single day --> <c:forEach items="${nextAppointments}" var="appointment"> <tr> <td>${appointment.pet.name} </td> <td>${appointment.pet.specie.specieName} </td> <td>${appointment.pet.age} </td> <c:set var="today" value="${appointment.dateTime}" /> <td><fmt:formatDate type="both" value="${today}" pattern="d-MMMM-yyyy"/></td> <c:set var="time" value="${appointment.time}" /> <td><fmt:formatDate type="both" value="${time}" pattern="hh:mm a"/></td> <td>${appointment.service}</td> <td>${appointment.assigned.nombre}</td> <td><button type="submit">Update Date</button></td> </c:forEach> </tr> </tbody> </table> </div> </div> </div> </section><!-- End Services Section --> <section id="my-pet" class="services"> <div class="container"> <div class="section-title"> <h2>My Pet</h2> <p>Past Appointments</p> </div> <div class="container d-flex align-items-center"> <div class="table-responsive"> <table class="table table-condensed table-bordered"> <thead> <tr> <th>Pet Name</th> <th>Pet Type</th> <th>Pet Age</th> <th>Visit Date</th> <th>Hour</th> <th>Service</th> <th>Veterinarian/Groomer</th> </tr> </thead> <tbody> <!-- Single event in a single day --> <c:forEach items="${pastAppointment}" var="appointment"> <tr> <td>${appointment.pet.name} </td> <td>${appointment.pet.specie.specieName} </td> <td>${appointment.pet.age} </td> <c:set var="today" value="${appointment.dateTime}" /> <td><fmt:formatDate type="both" value="${today}" pattern="d-MMMM-yyyy"/></td> <c:set var="time" value="${appointment.time}" /> <td><fmt:formatDate type="both" value="${time}" pattern="hh:mm a"/></td> <td>${appointment.service}</td> <td>${appointment.assigned.nombre}</td> </c:forEach> </tr> </tbody> </table> </div> </div> </div> </section><!-- End Services Section --> </body> </html>
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { EvaluacionesComponent } from './evaluaciones/evaluaciones.component'; import { ContactoComponent } from './contacto/contacto.component'; import { TransaccionComponent } from './transaccion/transaccion.component'; import { PayComponent } from './pay/pay.component'; const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent, }, { path: 'pay', component: PayComponent, }, { path: 'evaluaciones', component: EvaluacionesComponent }, { path: 'contacto', component: ContactoComponent }, { path: 'transaccion', component: TransaccionComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
import {Injectable} from '@angular/core'; import {HttpClient, HttpErrorResponse, HttpEventType} from "@angular/common/http"; import {audit, catchError, first, forkJoin, interval, map, Observable, Subject, Subscription, takeUntil} from "rxjs"; import { ApiFailure, Auth, Bucket, Chart, ChartDiscriminator, ChartPoint, ChartQuery, ChartSeries, ChartSeriesQuery, CreatePostData, Dimensions, DocumentData, Media, MediaType, Page, PageParams, Post, PostDetail, PostItemDetail, PostSearchQuery, SearchPost, SearchPostItem, Tag, Upload } from "@core/models"; import {environment} from "@src/environments/environment"; export interface UploadProgress { type: 'progress' | 'complete' body: any | undefined, bytesPerSec: number | undefined, progress: number | undefined, uploadedBytes: number | undefined, content: Media | undefined, thumbnail: Media | undefined, } interface QueuedFile { file: File, auth: Auth, subject: Subject<UploadProgress>, cancellationToken: Observable<any> } @Injectable({ providedIn: 'root' }) export class ApiService { private queue: QueuedFile[] = []; private isRunning = false; private workerPromise: null | Promise<void> = null; constructor(private client: HttpClient) { } public getAllBuckets(): Observable<Bucket[]> { return this.get('/buckets').pipe( map((json) => { return json.map((x: any) => this.mapBucket(x)); }) ) } public getBucketById(id: number): Observable<Bucket> { return this.get(`/buckets/${id}`).pipe( map((json) => { return this.mapBucket(json); }) ) } public getPostById(auth: Auth, id: number): Observable<PostDetail> { return this.authenticatedGet(auth, `/posts/${id}`).pipe( map((json) => { return this.mapPostDetail(json) }) ) } public deletePost(auth: Auth, id: number): Observable<any> { return this.authenticatedDelete(auth, `/posts/${id}`) } public searchTags(auth: Auth, pageParams: PageParams, query: string): Observable<{ tags: Tag[], page: Page }> { return this.authenticatedGet(auth, `/tags?offset=${encodeURIComponent(pageParams.offset)}&size=${encodeURIComponent(pageParams.pageSize)}&query=${encodeURIComponent(query)}`).pipe( map((json) => { return { tags: json.data.map((t: any) => this.mapTag(t)), page: this.mapPage(json) } }) ) } public searchPostItems(auth: Auth, postId: number, pageParams: PageParams): Observable<{ items: SearchPostItem[], page: Page }> { return this.authenticatedGet(auth, `/posts/${encodeURIComponent(postId)}/items?offset=${encodeURIComponent(pageParams.offset)}&size=${encodeURIComponent(pageParams.pageSize)}`).pipe( map((json) => { return { items: json.data.map((t: any) => this.mapSearchPostItem(auth, t)), page: this.mapPage(json) } }) ) } public createTag(auth: Auth, name: string, groupId: number | null): Observable<Tag> { return this.authenticatedPost(auth, '/tags', { name, group: groupId }).pipe( map(json => this.mapTag(json)) ); } public removeTag(auth: Auth, id: number): Observable<any> { return this.authenticatedDelete(auth, `/tags/${id}`); } public getPostItemById(auth: Auth, postId: number, position: number): Observable<PostItemDetail> { return this.authenticatedGet(auth, `/posts/${postId}/items/${position}`).pipe( map((json) => this.mapPostItem(auth, json)) ) } public getMediaById(auth: Auth, id: number): Observable<Media> { return this.authenticatedGet(auth, `/media/${id}`).pipe( map((json) => { return this.mapMedia(auth, json) }) ) } public searchPosts(auth: Auth, query: PostSearchQuery, pageParams: PageParams): Observable<{ posts: SearchPost[], page: Page }> { let tagItems = query.items.filter(x => x.type == 'tag'); let tagIds = ''; let textItems = query.items.filter(x => x.type == 'text'); let text = ''; if (tagItems.length > 0) { tagIds = '&tags=' + tagItems.map(x => x.type == 'tag' ? x.tag.id : 0).join(','); } if (textItems.length > 0) { text = '&text=' + encodeURIComponent(textItems.map(x => x.type == 'text' ? x.str : '').join(' ')); } let queryStr = `${tagIds}${text}&order=${query.order}&seed=${query.seed}`; return this.authenticatedGet(auth, `/posts?offset=${encodeURIComponent(pageParams.offset)}&size=${encodeURIComponent(pageParams.pageSize)}${queryStr}`).pipe( map((json) => { return { posts: json.data.map((p: any) => this.mapSearchPost(auth, p)), page: this.mapPage(json) } }) ) } public loadChart(auth: Auth, query: ChartQuery): Observable<Chart> { return forkJoin(query.series.map(x => this.loadChartSeries(auth, x, query.discriminator))) .pipe( map(x => new Chart(query.name, x, query.discriminator)) ) } public updatePost(auth: Auth, postId: number, title: string | null, description: string | null, source: string | null, tagIds: number[]): Observable<Post> { return this.authenticatedPut(auth, `/posts/${encodeURIComponent(postId)}`, { title, description, source, tag_ids: tagIds }).pipe( map((json) => this.mapPost(json)) ) } // downloads public createPost(auth: Auth, postInfo: CreatePostData, files: Upload[]): Observable<{ batchId: number, posts: Post[] }> { return this.authenticatedPost(auth, '/posts', { title: postInfo.title, description: postInfo.description, source: postInfo.source, flatten: postInfo.flatten, tag_ids: postInfo.tags.map(x => x.id), items: files.filter(x => x.content !== null).map(upload => ({ content_id: upload.content?.id, metadata: { original_filename: upload.file.name, original_directory: null, original_modified_at: new Date(upload.file.lastModified).toISOString(), original_accessed_at: null, } })) }).pipe( map(json => { return { batchId: json.batch.id, posts: json.posts.map((x: any) => this.mapPost(x)) } }) ); } public login(bucketId: number, password: string | null, privateSession: boolean): Observable<Auth> { return this.post(`/buckets/${bucketId}/auth`, {password}).pipe( map((json) => { return this.mapAuth(bucketId, privateSession, json); }) ) } public uploadFile(auth: Auth, file: File, cancellationToken: Observable<any> | null): Observable<UploadProgress> { let subject = new Subject<UploadProgress>(); this.queue.push({ file, subject, auth, cancellationToken: cancellationToken || new Subject() }); this.runQueue(); return subject.asObservable(); } private loadChartSeries(auth: Auth, query: ChartSeriesQuery, discriminatorQuery: ChartDiscriminator): Observable<ChartSeries> { let select; switch (query.select) { case "count": select = 'Count' break; } let discriminator; let secs; switch (discriminatorQuery.duration) { case 'day': secs = 60 * 60 * 24; break; case 'hour': secs = 60 * 60; break; case 'week': secs = 60 * 60 * 24 * 7; break; case 'month': secs = 60 * 60 * 24 * 365 / 12; break; case 'year': secs = 60 * 60 * 24 * 365; break; } switch (discriminatorQuery.discriminator) { case "none": discriminator = 'None'; break; case 'duration': discriminator = {Duration: {nanos: 0, secs}} break; } let textItems = query.filter.items.filter(x => x.type == 'text').map((x: any) => x.str); let text = null; if (textItems.length > 0) { text = textItems.join(' '); } let tagItems = query.filter.items.filter(x => x.type == 'tag').map((x: any) => x.tag.id); let tags = null; if (tagItems.length > 0) { tags = tagItems; } return this.authenticatedPost(auth, `/posts/graph`, { select, discriminator, filter: { tags, text } }).pipe( map(json => new ChartSeries(query.name, json.points.map((x: any) => this.mapChartPoint(x)))) ) } private runQueue() { if (this.workerPromise) { return; } this.workerPromise = this.runQueueLoop(); } private async runQueueLoop() { let next: QueuedFile | undefined = undefined; while (next = this.queue.shift()) { await this.uploadQueuedFile(next); } this.workerPromise = null; } private uploadQueuedFile(file: QueuedFile): Promise<void> { return new Promise((resolve) => { let prevTime = new Date(); let prevLoaded = 0; let cancelSubscription: Subscription | null = null; let resolved = false; let subscription = this.authenticatedPost(file.auth, '/content', file.file, { reportProgress: true, observe: 'events', responseType: 'json' }).pipe( takeUntil(file.cancellationToken), catchError(err => { file.subject.error(err); resolve(); cancelSubscription?.unsubscribe(); throw err; }), audit(() => interval(500)) ) .subscribe(event => { if (event.type == HttpEventType.UploadProgress) { let now = new Date(); let secDiff = (now.getTime() - prevTime.getTime()) / 1000; file.subject.next({ type: 'progress', body: undefined, bytesPerSec: (event.loaded - prevLoaded) / secDiff, progress: event.loaded / event.total! * 100.0, uploadedBytes: event.loaded!, content: undefined, thumbnail: undefined }); prevTime = now; prevLoaded = event.loaded; if (event.loaded == event.total!) { resolve(); resolved = true; } } else if (event.type == HttpEventType.Response) { file.subject.next({ type: 'complete', body: event.body, bytesPerSec: undefined, progress: undefined, uploadedBytes: undefined, content: this.mapMedia(file.auth, event.body.content.obj), thumbnail: this.mapMedia(file.auth, event.body.thumbnail.obj), }); file.subject.complete(); cancelSubscription?.unsubscribe(); if (!resolved) { resolve(); } } }); cancelSubscription = file.cancellationToken.pipe(first()).subscribe(() => { subscription.unsubscribe(); file.subject.complete(); resolve(); }) }); } // http basics private get(url: string, options?: any): Observable<any> { return this.pipeRequest(this.client.get(`${environment.api}${url}`, options)); } private authenticatedGet(auth: Auth, url: string): Observable<any> { return this.pipeRequest(this.client.get(`${auth.base}${url}`, this.authRequestOptions(auth))); } private post(url: string, data: any, options?: any): Observable<any> { return this.pipeRequest(this.client.post(`${environment.api}${url}`, data, options)); } private authenticatedPost(auth: Auth, url: string, data: any, options?: any): Observable<any> { return this.pipeRequest(this.client.post(`${auth.base}${url}`, data, {...this.authRequestOptions(auth), ...options})); } private authenticatedPut(auth: Auth, url: string, data: any, options?: any): Observable<any> { return this.pipeRequest(this.client.put(`${auth.base}${url}`, data, {...this.authRequestOptions(auth), ...options})); } private authenticatedDelete(auth: Auth, url: string, options?: any): Observable<any> { return this.pipeRequest(this.client.delete(`${auth.base}${url}`, {...this.authRequestOptions(auth), ...options})); } private authRequestOptions(_auth: Auth): any { return { withCredentials: true } } private pipeRequest(req: Observable<any>): Observable<any> { return req.pipe( catchError(async (err: HttpErrorResponse) => { if (typeof err.error?.message == 'string' && typeof err.error?.status == 'number' && typeof err.error?.status_text == 'string') { throw new ApiFailure(err.error.message, err.error.inner_error, err.error.status, err.error.status_text); } throw err; }) ); } private mapBucket(json: any): Bucket { return new Bucket(json.id, json.name, json.password_protected, json.encrypted); } private mapAuth(bucketId: number, privateSession: boolean, json: any): Auth { let url = new URL(environment.api + "/buckets/" + bucketId, document.location.toString()); return new Auth(bucketId, json.token, privateSession, url.hostname, url.pathname, url.protocol, url.port == '' ? null : url.port); } private mapPage(json: any): Page { return new Page( new PageParams(json.page_size, json.page_number), json.total_row_count ) } private mapSearchPost(auth: Auth, json: any): SearchPost { return new SearchPost( json.post.id, json.post.source, json.post.title, json.post.description, new Date(json.post.created_at), json.item_count, json.contains_document, json.contains_image, json.contains_video, json.contains_moving_image, json.duration, json.thumbnail == null ? null : this.mapMedia(auth, json.thumbnail), json.file_name ) } private mapChartPoint(json: any): ChartPoint { let x; let type; if (typeof json.y === 'string') { type = 'none'; } else { type = 'time'; x = new Date(json.x.Date) } return { type, x, y: json.y } as ChartPoint } private mapMedia(auth: Auth, json: any): Media { let dimensions = null; let duration = null; let documentData = null; let videoEncoding = null; let mediaType: MediaType = 'unknown'; if (!!json.metadata.Image) { dimensions = new Dimensions(json.metadata.Image.dims.width, json.metadata.Image.dims.height); mediaType = 'image'; } else if (!!json.metadata.Video) { dimensions = new Dimensions(json.metadata.Video.dims.width, json.metadata.Video.dims.height); duration = json.metadata.Video.duration; videoEncoding = json.metadata.Video.video_encoding; mediaType = 'video'; } else if (!!json.metadata.Document) { documentData = new DocumentData( new Dimensions( json.metadata.Document.page_size.width, json.metadata.Document.page_size.height, ), json.metadata.Document.pages, json.metadata.Document.author, json.metadata.Document.title ); mediaType = 'document'; } return new Media( json.id, videoEncoding, dimensions, duration, json.file_size, json.sha1, json.sha256, json.md5, json.mime, documentData, mediaType, `${auth.base}/media/${json.id}/file` ); } private mapPostDetail(json: any): PostDetail { return new PostDetail( json.post.id, json.post.source, json.post.title, json.post.description, new Date(json.post.created_at), json.item_count, json.tags.map((x: any) => this.mapTag(x)) ) } private mapTag(json: any): Tag { return new Tag(json.id, json.name, null); } private mapPost(json: any): Post { return new Post( json.id, json.source, json.title, json.description, new Date(json.created_at), ) } private mapSearchPostItem(auth: Auth, json: any): SearchPostItem { return new SearchPostItem( json.item.post.id, json.item.position, json.contains_image, json.contains_moving_image, json.contains_video, json.contains_document, json.duration, this.mapMedia(auth, json.thumbnail) ); } private mapPostItem(auth: Auth, json: any): PostItemDetail { return new PostItemDetail( json.post.obj.id, json.position, this.mapMedia(auth, json.content.obj.content.obj), ); } }
// Example makes use of `wagmi` with `ether.js` on Ethereum --> `npm install wagmi ethers@^5` import { getDefaultProvider } from 'ethers'; import { FC, PropsWithChildren, createContext, useContext, useState, } from 'react'; import { WagmiConfig, configureChains, createClient, mainnet } from 'wagmi'; import { WalletConnectConnector } from 'wagmi/connectors/walletConnect'; import { infuraProvider } from 'wagmi/providers/infura'; export const connector = new WalletConnectConnector({ chains: [mainnet], options: { projectId: 'f633a048d4392b31be9fce99e7b417db', }, }); type EvmWalletProviderContextData = { walletAdapter: 'walletconnect' | 'metamask'; setWalletAdapter: React.Dispatch< React.SetStateAction<'metamask' | 'walletconnect'> >; }; const EvmWalletProviderContext = createContext<EvmWalletProviderContextData>( {} as EvmWalletProviderContextData, ); export const useEvmWallet = () => { const context = useContext(EvmWalletProviderContext); if (!context) { throw new Error('useEvmWallet must be used within a EvmWalletProvider'); } return context; }; export const EvmWalletProvider: FC<PropsWithChildren> = ({ children }) => { const [walletAdapter, setWalletAdapter] = useState< 'walletconnect' | 'metamask' >('metamask'); const metamaskClient = createClient({ autoConnect: true, provider: getDefaultProvider(), }); const { provider } = configureChains( [mainnet], [infuraProvider({ apiKey: '9c9ff698105d4f6b9b2b93eddc0dff72' })], ); const walletConnectClient = createClient({ autoConnect: true, connectors: [connector], provider: provider, }); return ( <EvmWalletProviderContext.Provider value={{ walletAdapter, setWalletAdapter }} > {walletAdapter === 'metamask' ? ( <WagmiConfig client={metamaskClient}>{children}</WagmiConfig> ) : ( <WagmiConfig client={walletConnectClient}>{children}</WagmiConfig> )} </EvmWalletProviderContext.Provider> ); };
use std::collections::HashMap; use crate::{ codegen::{CodegenError, CodegenResult}, parser::ast::{Block, BlockItem, DeclOrExpr, Expr, Statement, VarDecl, VarSize}, }; #[derive(Debug, PartialEq)] pub struct CodegenFunction { pub stack: FuncStack, pub op_stack_depth: usize, pub loops: Vec<Loop>, } #[derive(Debug, PartialEq)] pub enum CodegenVar { StackVar(StackVar), } #[derive(Debug, PartialEq)] pub struct StackVar { /// Size of the variable. pub size: VarSize, /// Offset from the stack pointer. pub offset: usize, } #[derive(Debug, PartialEq)] pub struct FuncStack { pub var_map: HashMap<String, CodegenVar>, pub size: usize, pub op_count: usize, } #[derive(Debug, PartialEq)] pub struct Loop { pub start_label: String, pub end_label: String, } impl CodegenFunction { pub fn new(block: &Block) -> CodegenResult<CodegenFunction> { Ok(CodegenFunction { stack: block.to_func_stack()?, op_stack_depth: 0, loops: vec![], }) } } impl Block { fn to_func_stack(&self) -> CodegenResult<FuncStack> { let mut stack = FuncStack { var_map: HashMap::new(), size: 0, op_count: 0, }; self.func_stack(&mut stack)?; // Stack size has to be 16 byte aligned. // https://stackoverflow.com/a/34504752/3582646 if stack.size % 16 != 0 { stack.size += 16 - (stack.size % 16); } // Invert all the offsets, it seems to be the common convention. for var in stack.var_map.values_mut() { match var { CodegenVar::StackVar(var) => { var.offset = stack.size - var.offset; } } } Ok(stack) } fn func_stack(&self, stack: &mut FuncStack) -> CodegenResult<()> { for item in &self.items { match item { BlockItem::Declaration(var_decl) => { var_decl.func_stack(stack)?; } BlockItem::Statement(stmt) => { stmt.func_stack(stack)?; } } } Ok(()) } } impl Statement { fn func_stack(&self, stack: &mut FuncStack) -> CodegenResult<usize> { match self { Statement::Expression(expr) | Statement::Return(expr) => { // Also look at the arithmetic operations that need to push to stack and // and find the largest tree node. expr.func_stack(stack)?; } Statement::Conditional(cond) => { // Look at the conditional statements. cond.if_stmt.func_stack(stack)?; if let Some(else_stmt) = &cond.else_stmt { else_stmt.func_stack(stack)?; } } Statement::Block(block) => { block.func_stack(stack)?; } Statement::While(expr, stmt) => { expr.func_stack(stack)?; stmt.func_stack(stack)?; } Statement::DoWhile(stmt, expr) => { stmt.func_stack(stack)?; expr.func_stack(stack)?; } Statement::For(for_loop) => { for_loop.init.func_stack(stack)?; for_loop.condition.func_stack(stack)?; for_loop.increment.func_stack(stack)?; for_loop.body.func_stack(stack)?; } Statement::Break | Statement::Continue | Statement::Null => {} } Ok(0) } } impl Expr { fn func_stack(&self, stack: &mut FuncStack) -> CodegenResult<()> { match self { Expr::Assignment(_, expr) => expr.func_stack(stack)?, Expr::UnaryOp(_, expr) => expr.func_stack(stack)?, Expr::BinaryOp(op, lhs, rhs) => { lhs.func_stack(stack)?; rhs.func_stack(stack)?; if !op.is_short_circuiting_op() { // FIXME: Currently we support only word variable size for operations. stack.size += VarSize::Word.to_bytes(); stack.var_map.insert( format!("op_{}", stack.op_count), CodegenVar::StackVar(StackVar { size: VarSize::Word, offset: stack.size, }), ); stack.op_count += 1; } } Expr::TernaryConditional(ternary) => { ternary.condition.func_stack(stack)?; ternary.if_expr.func_stack(stack)?; ternary.else_expr.func_stack(stack)?; } Expr::Var(_) => {} Expr::Constant(_) => {} Expr::Null => {} } Ok(()) } } impl VarDecl { fn func_stack(&self, stack: &mut FuncStack) -> CodegenResult<()> { if stack.var_map.contains_key(&self.name) { return Err(CodegenError::VarAlreadyDeclared(self.name.clone())); } let byte_size = self.get_byte_size(); stack.size += byte_size; // We need to invert the offsets at the end. stack.var_map.insert( self.name.clone(), CodegenVar::StackVar(StackVar { size: self.size, offset: stack.size, }), ); Ok(()) } } impl DeclOrExpr { fn func_stack(&self, stack: &mut FuncStack) -> CodegenResult<()> { match self { DeclOrExpr::Expression(expr) => expr.func_stack(stack), DeclOrExpr::Declaration(decl) => decl.func_stack(stack), } } } impl CodegenVar { pub fn get_stack_offset(&self) -> CodegenResult<usize> { match self { CodegenVar::StackVar(var) => Ok(var.offset), } } }
--- title: How To Create a Polaroid Collage for 2024 date: 2024-05-19T05:12:01.525Z updated: 2024-05-20T05:12:01.525Z tags: - ai - animation videos categories: - ai description: This Article Describes How To Create a Polaroid Collage for 2024 excerpt: This Article Describes How To Create a Polaroid Collage for 2024 keywords: ai animation ai animation how to create a polaroid collage,how to create the best video collages,polaroid collage,ai animation how to make a polaroid collage,how to make a polaroid collage,ai animation how to create a polaroid collage,how to create a polaroid collage thumbnail: https://www.lifewire.com/thmb/MgXYGqoMMbFkRcMCb9oaCyNjJGE=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/6g-4717cafbb03b4d0eb3dae878b5ad134e.png --- ## How To Create a Polaroid Collage? ##### How To Create a Polaroid Collage? An easy yet powerful editor Numerous effects to choose from Detailed tutorials provided by the official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) As it is said that “Old is gold”, the same holds true when it comes to collages. No matter how advanced the technology has become or the design has evolved with collages the old-fashioned polaroid collages are never out of fashion. Polaroid images are small pocket-sized images having a white border developed using polaroid cameras. When it comes to collages, you can develop these images using your special camera and then lay them out in the desired pattern. With everything taking the digital route, collage creation is no exception and now you can quickly create customized polarised collages using all your favorite pictures. Learn more about polaroid collages, the best tools for their creation, and more in the following parts. #### In this article 01 [How to Create an Impressive Polaroid Collage](#Part 1) 02 [How to Create a Polaroid Photo Collage in Photoshop](#Part 2) 03 [Best Place to Get Stock Images for Your Polaroid Collage](#Part 3) 04 [How to Make a Photo Collage Online](#Part 4) ## Part 1 How to Create an Impressive Polaroid Collage Like any other collage, a polaroid collage is one where several polaroid styles images are placed together in the desired pattern. To create an eye-catchy polaroid collage, some of the basic requirements are as follows. ![Polaroid Collage](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-01.jpg) ### 01Use the right tool First of all, select the right tool that can help you create the desired collage. There are several online as well as desktop programs available for this. Choose a tool that comes with multiple **polaroid collage template** and offers different editing options. ### 02Select a layout/design/template Next, select the desired layout or the **polaroid frame collage** template from the available options that match your requirements. ### 03Add high-quality images Now it's time to add the images to the template. To make an impressive collage make sure to add high-quality images. You can either use the images captured by you or can also use the stock images available at different online sites. ### 04Personalize and customize the collage Next, it's time to customize the collage. After the images are added, you can further add elements like text, filters, effects, and others to make your collage look more appealing. ### 05Save, print, or share the collage Finally, it's time to save the collage, print it, or share it over online sites, social media platforms, or with your near and dear ones. ## Part 2 How to Create a Polaroid Photo Collage in Photoshop To create an interesting polaroid collage Photoshop works as a good tool. Both Photoshop CS6 and Photoshop Creative Cloud can be used for creating the desired collage with slight changes in the functioning of both versions. ### 01Steps to create polaroid collage using Photoshop **polaroid collage maker** **Step 1\.** Launch the Photoshop tool and add the first image. Choose the Rectangle Tool using its icon which is present in the lower half of the Tools panel. ![Create Polaroid Collage Photoshop 1](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-02.jpg) **Step 2\.** Next, at the left corner of the interface set the Shape option as Tool Mode for drawing the vector shapes. ![Create Polaroid Collage Photoshop 2](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-03.jpg) **Step 3\.** Next, choose the color of the rectangle shape, and to fill this select black at the Fill color swatch in the Options bar. A dialog box will appear to choose the type of fill and here you need to select the Solid Color option. Click on the Enter button to close the dialog box. ![Create Polaroid Collage Photoshop 3](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-04.jpg) **Step 4\.** Also, ensure that there are no strokes around the edges, and for this tap on the Stroke swatch box on the right side of the Options bar. A Stroke Type dialog box will open where you need to select the None icon. Click on Enter to close the pop-up window. **Step 5\.** When all the above settings are done, press and hold the Shift key and then you need to click and drag the shape to move into the square box. ![Create Polaroid Collage Photoshop 4](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-05.jpg) **Step 6\.** A newly added shape layer will now appear at the Layers panel. Now you need to make a copy of this shape and then resize it for creating the outer frame of the polaroid. The duplicate shape layer will be created and will appear on the Layers panel. Rename these shapes as desired. **Step 7\.** Now after selecting the border layer in the layers panel click again on the Fill color swatch and choose the White color (to make it look like a polaroid image). **Step 8\.** Next, move to the Edit menu and select Free Transform Path which will create the transform handles around the shape which can also be used for resizing. **Step 9\.** A shadow to the border can also be added by clicking on the icon of Layer Styles and then choosing the Drop Shadow option from the list. **Step 10\.** Choose the image area from the Layers panel. **Step 11\.** Next, use the Knockout function from the Blending Options. **Step 12\.** Now select both shape layers and group the layers by clicking on New Group from Layers in the menu. Give a desired name to the group. **Step 13\.** Next, click on the Background layer and choose New Fill or Adjustment Layer. **Step 14\.** Tap on the Polaroid layer group from the Layers panel and select it. **Step 15\.** Go to the Edit menu and select the Free Transform option. **Step 16\.** Now when all the major work is done, it's time to create a duplicate layer group to create a new polaroid. ![Create Polaroid Collage Photoshop 5](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-06.jpg) When multiple layer groups are added your **polaroid photo collage** will be ready. ## Part 3 How to Make a Photo Collage Online Creating a polaroid collage using Photoshop is quite complicated and a lengthy process. So, if you are looking for a simpler and quicker way to create the desired collage, we suggest using an online tool. Fotor is one such decent tool that works from your browser and comes with several pre-designed collage templates including polaroid. The interface of this **polaroid collage app** is simple where you just need to select the polaroid-based template from the available options, add images, customize the collage by adding a text, filter, or any other element, and then download the created collage. The interface is simple and user-friendly and the process of creating the collage is fast. ![Fotor](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-07.jpg) ## Part 4 Best Place To Get Stock Images For Your Polaroid Collage To create an eye-catchy collage, the images added also need to be interesting. Besides your local pictures, you can even get stock images available at several sites. One such tool for stock images that we recommend is **[Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**. Though this is an advanced video editing tool supporting a wide range of functions, it also comes with a library of images and other media files that can be used. You can search from a vast collection of images in different categories and genres to be used for your collage. Additionally, the software also supports a split-screen feature where multiple videos can be played that appears like a video collage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## **●** Ending Thoughts **→** **●** Polaroid picture collage is one of the most interesting ways of making a collage. **●** Photoshop is a great tool for creating a polaroid collage like a pro. **●** Online tools like Fotor and others are simple and user-friendly and come with pre-designed templates for creating a polaroid collage. **●** Wondershare Filmora is an excellent software to search for stock images and other files, editing videos, and also create a video collage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) As it is said that “Old is gold”, the same holds true when it comes to collages. No matter how advanced the technology has become or the design has evolved with collages the old-fashioned polaroid collages are never out of fashion. Polaroid images are small pocket-sized images having a white border developed using polaroid cameras. When it comes to collages, you can develop these images using your special camera and then lay them out in the desired pattern. With everything taking the digital route, collage creation is no exception and now you can quickly create customized polarised collages using all your favorite pictures. Learn more about polaroid collages, the best tools for their creation, and more in the following parts. #### In this article 01 [How to Create an Impressive Polaroid Collage](#Part 1) 02 [How to Create a Polaroid Photo Collage in Photoshop](#Part 2) 03 [Best Place to Get Stock Images for Your Polaroid Collage](#Part 3) 04 [How to Make a Photo Collage Online](#Part 4) ## Part 1 How to Create an Impressive Polaroid Collage Like any other collage, a polaroid collage is one where several polaroid styles images are placed together in the desired pattern. To create an eye-catchy polaroid collage, some of the basic requirements are as follows. ![Polaroid Collage](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-01.jpg) ### 01Use the right tool First of all, select the right tool that can help you create the desired collage. There are several online as well as desktop programs available for this. Choose a tool that comes with multiple **polaroid collage template** and offers different editing options. ### 02Select a layout/design/template Next, select the desired layout or the **polaroid frame collage** template from the available options that match your requirements. ### 03Add high-quality images Now it's time to add the images to the template. To make an impressive collage make sure to add high-quality images. You can either use the images captured by you or can also use the stock images available at different online sites. ### 04Personalize and customize the collage Next, it's time to customize the collage. After the images are added, you can further add elements like text, filters, effects, and others to make your collage look more appealing. ### 05Save, print, or share the collage Finally, it's time to save the collage, print it, or share it over online sites, social media platforms, or with your near and dear ones. ## Part 2 How to Create a Polaroid Photo Collage in Photoshop To create an interesting polaroid collage Photoshop works as a good tool. Both Photoshop CS6 and Photoshop Creative Cloud can be used for creating the desired collage with slight changes in the functioning of both versions. ### 01Steps to create polaroid collage using Photoshop **polaroid collage maker** **Step 1\.** Launch the Photoshop tool and add the first image. Choose the Rectangle Tool using its icon which is present in the lower half of the Tools panel. ![Create Polaroid Collage Photoshop 1](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-02.jpg) **Step 2\.** Next, at the left corner of the interface set the Shape option as Tool Mode for drawing the vector shapes. ![Create Polaroid Collage Photoshop 2](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-03.jpg) **Step 3\.** Next, choose the color of the rectangle shape, and to fill this select black at the Fill color swatch in the Options bar. A dialog box will appear to choose the type of fill and here you need to select the Solid Color option. Click on the Enter button to close the dialog box. ![Create Polaroid Collage Photoshop 3](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-04.jpg) **Step 4\.** Also, ensure that there are no strokes around the edges, and for this tap on the Stroke swatch box on the right side of the Options bar. A Stroke Type dialog box will open where you need to select the None icon. Click on Enter to close the pop-up window. **Step 5\.** When all the above settings are done, press and hold the Shift key and then you need to click and drag the shape to move into the square box. ![Create Polaroid Collage Photoshop 4](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-05.jpg) **Step 6\.** A newly added shape layer will now appear at the Layers panel. Now you need to make a copy of this shape and then resize it for creating the outer frame of the polaroid. The duplicate shape layer will be created and will appear on the Layers panel. Rename these shapes as desired. **Step 7\.** Now after selecting the border layer in the layers panel click again on the Fill color swatch and choose the White color (to make it look like a polaroid image). **Step 8\.** Next, move to the Edit menu and select Free Transform Path which will create the transform handles around the shape which can also be used for resizing. **Step 9\.** A shadow to the border can also be added by clicking on the icon of Layer Styles and then choosing the Drop Shadow option from the list. **Step 10\.** Choose the image area from the Layers panel. **Step 11\.** Next, use the Knockout function from the Blending Options. **Step 12\.** Now select both shape layers and group the layers by clicking on New Group from Layers in the menu. Give a desired name to the group. **Step 13\.** Next, click on the Background layer and choose New Fill or Adjustment Layer. **Step 14\.** Tap on the Polaroid layer group from the Layers panel and select it. **Step 15\.** Go to the Edit menu and select the Free Transform option. **Step 16\.** Now when all the major work is done, it's time to create a duplicate layer group to create a new polaroid. ![Create Polaroid Collage Photoshop 5](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-06.jpg) When multiple layer groups are added your **polaroid photo collage** will be ready. ## Part 3 How to Make a Photo Collage Online Creating a polaroid collage using Photoshop is quite complicated and a lengthy process. So, if you are looking for a simpler and quicker way to create the desired collage, we suggest using an online tool. Fotor is one such decent tool that works from your browser and comes with several pre-designed collage templates including polaroid. The interface of this **polaroid collage app** is simple where you just need to select the polaroid-based template from the available options, add images, customize the collage by adding a text, filter, or any other element, and then download the created collage. The interface is simple and user-friendly and the process of creating the collage is fast. ![Fotor](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-07.jpg) ## Part 4 Best Place To Get Stock Images For Your Polaroid Collage To create an eye-catchy collage, the images added also need to be interesting. Besides your local pictures, you can even get stock images available at several sites. One such tool for stock images that we recommend is **[Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**. Though this is an advanced video editing tool supporting a wide range of functions, it also comes with a library of images and other media files that can be used. You can search from a vast collection of images in different categories and genres to be used for your collage. Additionally, the software also supports a split-screen feature where multiple videos can be played that appears like a video collage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## **●** Ending Thoughts **→** **●** Polaroid picture collage is one of the most interesting ways of making a collage. **●** Photoshop is a great tool for creating a polaroid collage like a pro. **●** Online tools like Fotor and others are simple and user-friendly and come with pre-designed templates for creating a polaroid collage. **●** Wondershare Filmora is an excellent software to search for stock images and other files, editing videos, and also create a video collage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) As it is said that “Old is gold”, the same holds true when it comes to collages. No matter how advanced the technology has become or the design has evolved with collages the old-fashioned polaroid collages are never out of fashion. Polaroid images are small pocket-sized images having a white border developed using polaroid cameras. When it comes to collages, you can develop these images using your special camera and then lay them out in the desired pattern. With everything taking the digital route, collage creation is no exception and now you can quickly create customized polarised collages using all your favorite pictures. Learn more about polaroid collages, the best tools for their creation, and more in the following parts. #### In this article 01 [How to Create an Impressive Polaroid Collage](#Part 1) 02 [How to Create a Polaroid Photo Collage in Photoshop](#Part 2) 03 [Best Place to Get Stock Images for Your Polaroid Collage](#Part 3) 04 [How to Make a Photo Collage Online](#Part 4) ## Part 1 How to Create an Impressive Polaroid Collage Like any other collage, a polaroid collage is one where several polaroid styles images are placed together in the desired pattern. To create an eye-catchy polaroid collage, some of the basic requirements are as follows. ![Polaroid Collage](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-01.jpg) ### 01Use the right tool First of all, select the right tool that can help you create the desired collage. There are several online as well as desktop programs available for this. Choose a tool that comes with multiple **polaroid collage template** and offers different editing options. ### 02Select a layout/design/template Next, select the desired layout or the **polaroid frame collage** template from the available options that match your requirements. ### 03Add high-quality images Now it's time to add the images to the template. To make an impressive collage make sure to add high-quality images. You can either use the images captured by you or can also use the stock images available at different online sites. ### 04Personalize and customize the collage Next, it's time to customize the collage. After the images are added, you can further add elements like text, filters, effects, and others to make your collage look more appealing. ### 05Save, print, or share the collage Finally, it's time to save the collage, print it, or share it over online sites, social media platforms, or with your near and dear ones. ## Part 2 How to Create a Polaroid Photo Collage in Photoshop To create an interesting polaroid collage Photoshop works as a good tool. Both Photoshop CS6 and Photoshop Creative Cloud can be used for creating the desired collage with slight changes in the functioning of both versions. ### 01Steps to create polaroid collage using Photoshop **polaroid collage maker** **Step 1\.** Launch the Photoshop tool and add the first image. Choose the Rectangle Tool using its icon which is present in the lower half of the Tools panel. ![Create Polaroid Collage Photoshop 1](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-02.jpg) **Step 2\.** Next, at the left corner of the interface set the Shape option as Tool Mode for drawing the vector shapes. ![Create Polaroid Collage Photoshop 2](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-03.jpg) **Step 3\.** Next, choose the color of the rectangle shape, and to fill this select black at the Fill color swatch in the Options bar. A dialog box will appear to choose the type of fill and here you need to select the Solid Color option. Click on the Enter button to close the dialog box. ![Create Polaroid Collage Photoshop 3](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-04.jpg) **Step 4\.** Also, ensure that there are no strokes around the edges, and for this tap on the Stroke swatch box on the right side of the Options bar. A Stroke Type dialog box will open where you need to select the None icon. Click on Enter to close the pop-up window. **Step 5\.** When all the above settings are done, press and hold the Shift key and then you need to click and drag the shape to move into the square box. ![Create Polaroid Collage Photoshop 4](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-05.jpg) **Step 6\.** A newly added shape layer will now appear at the Layers panel. Now you need to make a copy of this shape and then resize it for creating the outer frame of the polaroid. The duplicate shape layer will be created and will appear on the Layers panel. Rename these shapes as desired. **Step 7\.** Now after selecting the border layer in the layers panel click again on the Fill color swatch and choose the White color (to make it look like a polaroid image). **Step 8\.** Next, move to the Edit menu and select Free Transform Path which will create the transform handles around the shape which can also be used for resizing. **Step 9\.** A shadow to the border can also be added by clicking on the icon of Layer Styles and then choosing the Drop Shadow option from the list. **Step 10\.** Choose the image area from the Layers panel. **Step 11\.** Next, use the Knockout function from the Blending Options. **Step 12\.** Now select both shape layers and group the layers by clicking on New Group from Layers in the menu. Give a desired name to the group. **Step 13\.** Next, click on the Background layer and choose New Fill or Adjustment Layer. **Step 14\.** Tap on the Polaroid layer group from the Layers panel and select it. **Step 15\.** Go to the Edit menu and select the Free Transform option. **Step 16\.** Now when all the major work is done, it's time to create a duplicate layer group to create a new polaroid. ![Create Polaroid Collage Photoshop 5](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-06.jpg) When multiple layer groups are added your **polaroid photo collage** will be ready. ## Part 3 How to Make a Photo Collage Online Creating a polaroid collage using Photoshop is quite complicated and a lengthy process. So, if you are looking for a simpler and quicker way to create the desired collage, we suggest using an online tool. Fotor is one such decent tool that works from your browser and comes with several pre-designed collage templates including polaroid. The interface of this **polaroid collage app** is simple where you just need to select the polaroid-based template from the available options, add images, customize the collage by adding a text, filter, or any other element, and then download the created collage. The interface is simple and user-friendly and the process of creating the collage is fast. ![Fotor](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-07.jpg) ## Part 4 Best Place To Get Stock Images For Your Polaroid Collage To create an eye-catchy collage, the images added also need to be interesting. Besides your local pictures, you can even get stock images available at several sites. One such tool for stock images that we recommend is **[Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**. Though this is an advanced video editing tool supporting a wide range of functions, it also comes with a library of images and other media files that can be used. You can search from a vast collection of images in different categories and genres to be used for your collage. Additionally, the software also supports a split-screen feature where multiple videos can be played that appears like a video collage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## **●** Ending Thoughts **→** **●** Polaroid picture collage is one of the most interesting ways of making a collage. **●** Photoshop is a great tool for creating a polaroid collage like a pro. **●** Online tools like Fotor and others are simple and user-friendly and come with pre-designed templates for creating a polaroid collage. **●** Wondershare Filmora is an excellent software to search for stock images and other files, editing videos, and also create a video collage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) As it is said that “Old is gold”, the same holds true when it comes to collages. No matter how advanced the technology has become or the design has evolved with collages the old-fashioned polaroid collages are never out of fashion. Polaroid images are small pocket-sized images having a white border developed using polaroid cameras. When it comes to collages, you can develop these images using your special camera and then lay them out in the desired pattern. With everything taking the digital route, collage creation is no exception and now you can quickly create customized polarised collages using all your favorite pictures. Learn more about polaroid collages, the best tools for their creation, and more in the following parts. #### In this article 01 [How to Create an Impressive Polaroid Collage](#Part 1) 02 [How to Create a Polaroid Photo Collage in Photoshop](#Part 2) 03 [Best Place to Get Stock Images for Your Polaroid Collage](#Part 3) 04 [How to Make a Photo Collage Online](#Part 4) ## Part 1 How to Create an Impressive Polaroid Collage Like any other collage, a polaroid collage is one where several polaroid styles images are placed together in the desired pattern. To create an eye-catchy polaroid collage, some of the basic requirements are as follows. ![Polaroid Collage](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-01.jpg) ### 01Use the right tool First of all, select the right tool that can help you create the desired collage. There are several online as well as desktop programs available for this. Choose a tool that comes with multiple **polaroid collage template** and offers different editing options. ### 02Select a layout/design/template Next, select the desired layout or the **polaroid frame collage** template from the available options that match your requirements. ### 03Add high-quality images Now it's time to add the images to the template. To make an impressive collage make sure to add high-quality images. You can either use the images captured by you or can also use the stock images available at different online sites. ### 04Personalize and customize the collage Next, it's time to customize the collage. After the images are added, you can further add elements like text, filters, effects, and others to make your collage look more appealing. ### 05Save, print, or share the collage Finally, it's time to save the collage, print it, or share it over online sites, social media platforms, or with your near and dear ones. ## Part 2 How to Create a Polaroid Photo Collage in Photoshop To create an interesting polaroid collage Photoshop works as a good tool. Both Photoshop CS6 and Photoshop Creative Cloud can be used for creating the desired collage with slight changes in the functioning of both versions. ### 01Steps to create polaroid collage using Photoshop **polaroid collage maker** **Step 1\.** Launch the Photoshop tool and add the first image. Choose the Rectangle Tool using its icon which is present in the lower half of the Tools panel. ![Create Polaroid Collage Photoshop 1](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-02.jpg) **Step 2\.** Next, at the left corner of the interface set the Shape option as Tool Mode for drawing the vector shapes. ![Create Polaroid Collage Photoshop 2](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-03.jpg) **Step 3\.** Next, choose the color of the rectangle shape, and to fill this select black at the Fill color swatch in the Options bar. A dialog box will appear to choose the type of fill and here you need to select the Solid Color option. Click on the Enter button to close the dialog box. ![Create Polaroid Collage Photoshop 3](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-04.jpg) **Step 4\.** Also, ensure that there are no strokes around the edges, and for this tap on the Stroke swatch box on the right side of the Options bar. A Stroke Type dialog box will open where you need to select the None icon. Click on Enter to close the pop-up window. **Step 5\.** When all the above settings are done, press and hold the Shift key and then you need to click and drag the shape to move into the square box. ![Create Polaroid Collage Photoshop 4](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-05.jpg) **Step 6\.** A newly added shape layer will now appear at the Layers panel. Now you need to make a copy of this shape and then resize it for creating the outer frame of the polaroid. The duplicate shape layer will be created and will appear on the Layers panel. Rename these shapes as desired. **Step 7\.** Now after selecting the border layer in the layers panel click again on the Fill color swatch and choose the White color (to make it look like a polaroid image). **Step 8\.** Next, move to the Edit menu and select Free Transform Path which will create the transform handles around the shape which can also be used for resizing. **Step 9\.** A shadow to the border can also be added by clicking on the icon of Layer Styles and then choosing the Drop Shadow option from the list. **Step 10\.** Choose the image area from the Layers panel. **Step 11\.** Next, use the Knockout function from the Blending Options. **Step 12\.** Now select both shape layers and group the layers by clicking on New Group from Layers in the menu. Give a desired name to the group. **Step 13\.** Next, click on the Background layer and choose New Fill or Adjustment Layer. **Step 14\.** Tap on the Polaroid layer group from the Layers panel and select it. **Step 15\.** Go to the Edit menu and select the Free Transform option. **Step 16\.** Now when all the major work is done, it's time to create a duplicate layer group to create a new polaroid. ![Create Polaroid Collage Photoshop 5](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-06.jpg) When multiple layer groups are added your **polaroid photo collage** will be ready. ## Part 3 How to Make a Photo Collage Online Creating a polaroid collage using Photoshop is quite complicated and a lengthy process. So, if you are looking for a simpler and quicker way to create the desired collage, we suggest using an online tool. Fotor is one such decent tool that works from your browser and comes with several pre-designed collage templates including polaroid. The interface of this **polaroid collage app** is simple where you just need to select the polaroid-based template from the available options, add images, customize the collage by adding a text, filter, or any other element, and then download the created collage. The interface is simple and user-friendly and the process of creating the collage is fast. ![Fotor](https://images.wondershare.com/filmora/article-images/2022/04/how-to-create-a-polaroid-collage-07.jpg) ## Part 4 Best Place To Get Stock Images For Your Polaroid Collage To create an eye-catchy collage, the images added also need to be interesting. Besides your local pictures, you can even get stock images available at several sites. One such tool for stock images that we recommend is **[Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**. Though this is an advanced video editing tool supporting a wide range of functions, it also comes with a library of images and other media files that can be used. You can search from a vast collection of images in different categories and genres to be used for your collage. Additionally, the software also supports a split-screen feature where multiple videos can be played that appears like a video collage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## **●** Ending Thoughts **→** **●** Polaroid picture collage is one of the most interesting ways of making a collage. **●** Photoshop is a great tool for creating a polaroid collage like a pro. **●** Online tools like Fotor and others are simple and user-friendly and come with pre-designed templates for creating a polaroid collage. **●** Wondershare Filmora is an excellent software to search for stock images and other files, editing videos, and also create a video collage. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Learn to Splice Videos Together on iPhone ##### Create High-Quality Video - Wondershare Filmora An easy and powerful YouTube video editor Numerous video and audio effects to choose from Detailed tutorials provided by the official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Your iPhone comes with so many features, including a camera. You, therefore, have a great chance to take photos, record videos, and catch every moment at your will. You’ll need to share your videos on social media sites or other platforms. Remember, you can spice them up with other add-ons. The most sophisticated way is to splice your iPhone, merging your videos into a compelling piece of art. Let’s uncover several video editors that you can use on your iPhone for splicing your videos. ![splice videos together iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-1.png) #### In this article 01 [How to Splice Videos on an iPhone](#part1) 02 [\[Desktop solution\] Splice videos with Filmora](#part2) ## How to Splice Videos on an iPhone The iPhone lets you do simple edits in the camera roll, such as trimming videos. However, when it comes to joining multiple clips, you need to step up your game with video editors. We bring you exclusive tools that you can use to splice videos together on your iPhone. ### Method 1: Using iMovie on the iPhone, splice videos together This splicing app from Apple is smart at editing professional-quality videos. You can get it for free to splice your videos on the iPhone. Color grading, narration, and the green-screen effect are just a few of the many tools available in iMovie. #### Features of iMovie * Combine multiple videos and transitions. * Green-screen controls to soften the effects that you add to your movie. * Freely adjust the level of your audio clip. * Timeline mode features include a color balance and tone adjusting feature. * A people detection feature that quickly recognizes characters in a film. * Directly export your spliced video to social networking sites or upload it to a cloud service. * Excellent tools to facilitate video editing. #### Steps to splice video on iMovie Step 1\. First, visit the "App Store, download the iMovie app, and install it on your iPhone. Step 2\. Once iMovie is installed on your iPhone, you can then launch it and continue with the splicing mission of your videos. Step 3\. Check the main screen of the app for the "three" tabs located at the top. Choose the tab indicated as the "Projects to create a new project" option. You’ll then be redirected to the next screen, where you should then tap on the "Create Project" option. Step 4\. When prompted, please choose the "Movie" option as the project type to create. Step 5\. Next, select the videos you want and tap on the "Add" option to add your videos from your iPhone Camera Roll. Next, tap on the "Create Movie" option at the bottom. Step 6\. iMovie lets you add any effects to your video at this point. Once completed, tap on the "Done" tab found at the top-left corner of your iPhone’s screen. Finally, save your combined videos into one file. You can also directly upload your video to cloud storage platforms. ![splice video iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-2.png) ### Method 2: Using Filmora on the iPhone, splice videos together Filmora is another app that lets you splice iOS in a few steps. It presents an intuitive interface with powerful video editing features. You can add background music, motion effects, and text effects to your video, and merge several clips into one. Let's check out how to combine your videos on the iPhone. #### Filmora's Features * The Transitions feature lets you create interestingly moving clips. * Simple editing features to trim, cut, and merge videos. * The Canvas feature is suitable for choosing the best aspect ratio for your video. * You can also play your footage backward with the reverse feature. * You can easily adjust the speed of your video by speeding it up or slowing it down. #### A guide to splice video with Filmora Step 1\. You first need to download and install the "Filmora Go" app on your iPhone. Step 2\. Next, hit the "New Project" button and begin to select the videos you wish to splice. Step 3\. Add the selected videos to the interface by clicking on the "Import" button. The "Edit" panel will automatically open. Step 4\. Check for the available tools in the "Editing panel" section. You can now freely use the available effects, like adding music, cropping your videos, adding text, among other effects. Step 5: Finally, you can save and export your video to other media platforms if you want. ### Method 3: Splice videos together on the iPhone using Quik You can also splice your iPhone with Quik Video Editor. Quik video editor is quite advanced and will support the merging of various video clips into one. With this app, you can escalate your video editing gigs, such as adding text, filters, music, among other options. Follow these steps to merge your videos. #### Quik's distinguishing characteristics * You can energize your videos by adjusting the speed. Likewise, you can stop the time with Freeze Frame. * Use exclusive filters to tweak your video to perfection, such as snow and water filters. * Easily add music to your video. * Sync your edits with royalty-free tracks. * Trimming, cropping, and other simple edits #### How to splice video with Quik Step 1\. Download and install the "Quik" app on your iPhone, then fire it up. Step 2\. Next, begin to create a new project in the Quik video editor on your iPhone. Just tap on the "All photos" dropdown, then select the "Videos" option. Choose the video clips that you wish to splice on your iPhone. Step 3\. You can also get other effects to add to your video. At the bottom, check out the "Effect" tab. Here, you can easily add music, filters, and others to polish your movie. Step 4\. Finally, click on the "Save" tab to save the merged videos. ![how to splice video on iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-4.png) ## \[Desktop solution\] Splice videos with Filmora Apart from splicing videos on the iPhone, you can also utilize the desktop to merge your videos. Many users like to transfer their data, including videos, to a desktop for backup or to create memory space on their phones. This may result in too many videos saved on your desktop. You can splice them together into a single movie by using Filmora. This video editor works on both Windows and Mac computers. It is also easy to use, enabling a simple drop-and-drag action. Besides, it harbors spending editing features and an additional 300+ built-in visual effects like overlays, transitions, and filters. Here are some notable features of Filmora. #### Key Features of Filmora * It will merge your videos without any quality loss to the original file. * Easily speed up hi-res footage with the Proxy workflow feature. * Use the instant mode feature to quickly edit your videos. * With the masking feature, you can easily animate and customize the mask for an improved finish. * This app also comes with an in-built stock media feature that facilitates free copyright stock footage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later #### Steps to using Filmora to splice videos Filmora supports Windows and Macs. So first, choose your computer’s version and download the correct one. Then follow these steps to splice your videos. Step 1: Add videos. After installing and launching Filmora on your PC, continue to add the videos that you want to splice. So, click on the "Import" tab to load your clips into the program. You can also drag and drop the video clips directly into the media library. Step 2\. Splice video All the videos you’ve added will show up as thumbnails in the editor’s window. Now simply drag and drop the clips to the same video track in the timeline. Next, place the "Playhead" at the starting point of the clip where you want the sliced video to start playing. Your videos will be spliced together seamlessly. You can also use the "Preview" feature to preview your video before saving it to the computer. Step 3: Finalize your video. Filmora comes with numerous editing features that let you rotate, trim, add titles, transitions, set speed, add music, and much more. To trim your clip, simply move the "Playhead" to the position you wish to cut first. Next, click on the split icon in the toolbar. You can also right-click on any transition to apply effects, add subtitles, rotate, and perform other advanced editing. Step 4\. Save and Export Ascertain that your video is good enough, then hit the "Create" tab. Continue to save and export your video in any format. Just click on the "Export" tab to finally share your video on platforms like YouTube and Vimeo. You can also directly convert to other portable devices like the iPhone. ## Conclusion ●Several options are available to splice video on the iPhone. You can use the free app, iMovie, for iPhone and Mac. Filmora and Quik are also uniquely able to splice video into a single merge. However, if you wish to retain the original quality of your video, Filmora Video Editor is the option to settle for. It has improved features that will manage any form of edit in simple steps. More so, you can easily share your finished video on social media sites as well as upload it directly to streaming sites like YouTube and Vimeo.es. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Your iPhone comes with so many features, including a camera. You, therefore, have a great chance to take photos, record videos, and catch every moment at your will. You’ll need to share your videos on social media sites or other platforms. Remember, you can spice them up with other add-ons. The most sophisticated way is to splice your iPhone, merging your videos into a compelling piece of art. Let’s uncover several video editors that you can use on your iPhone for splicing your videos. ![splice videos together iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-1.png) #### In this article 01 [How to Splice Videos on an iPhone](#part1) 02 [\[Desktop solution\] Splice videos with Filmora](#part2) ## How to Splice Videos on an iPhone The iPhone lets you do simple edits in the camera roll, such as trimming videos. However, when it comes to joining multiple clips, you need to step up your game with video editors. We bring you exclusive tools that you can use to splice videos together on your iPhone. ### Method 1: Using iMovie on the iPhone, splice videos together This splicing app from Apple is smart at editing professional-quality videos. You can get it for free to splice your videos on the iPhone. Color grading, narration, and the green-screen effect are just a few of the many tools available in iMovie. #### Features of iMovie * Combine multiple videos and transitions. * Green-screen controls to soften the effects that you add to your movie. * Freely adjust the level of your audio clip. * Timeline mode features include a color balance and tone adjusting feature. * A people detection feature that quickly recognizes characters in a film. * Directly export your spliced video to social networking sites or upload it to a cloud service. * Excellent tools to facilitate video editing. #### Steps to splice video on iMovie Step 1\. First, visit the "App Store, download the iMovie app, and install it on your iPhone. Step 2\. Once iMovie is installed on your iPhone, you can then launch it and continue with the splicing mission of your videos. Step 3\. Check the main screen of the app for the "three" tabs located at the top. Choose the tab indicated as the "Projects to create a new project" option. You’ll then be redirected to the next screen, where you should then tap on the "Create Project" option. Step 4\. When prompted, please choose the "Movie" option as the project type to create. Step 5\. Next, select the videos you want and tap on the "Add" option to add your videos from your iPhone Camera Roll. Next, tap on the "Create Movie" option at the bottom. Step 6\. iMovie lets you add any effects to your video at this point. Once completed, tap on the "Done" tab found at the top-left corner of your iPhone’s screen. Finally, save your combined videos into one file. You can also directly upload your video to cloud storage platforms. ![splice video iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-2.png) ### Method 2: Using Filmora on the iPhone, splice videos together Filmora is another app that lets you splice iOS in a few steps. It presents an intuitive interface with powerful video editing features. You can add background music, motion effects, and text effects to your video, and merge several clips into one. Let's check out how to combine your videos on the iPhone. #### Filmora's Features * The Transitions feature lets you create interestingly moving clips. * Simple editing features to trim, cut, and merge videos. * The Canvas feature is suitable for choosing the best aspect ratio for your video. * You can also play your footage backward with the reverse feature. * You can easily adjust the speed of your video by speeding it up or slowing it down. #### A guide to splice video with Filmora Step 1\. You first need to download and install the "Filmora Go" app on your iPhone. Step 2\. Next, hit the "New Project" button and begin to select the videos you wish to splice. Step 3\. Add the selected videos to the interface by clicking on the "Import" button. The "Edit" panel will automatically open. Step 4\. Check for the available tools in the "Editing panel" section. You can now freely use the available effects, like adding music, cropping your videos, adding text, among other effects. Step 5: Finally, you can save and export your video to other media platforms if you want. ### Method 3: Splice videos together on the iPhone using Quik You can also splice your iPhone with Quik Video Editor. Quik video editor is quite advanced and will support the merging of various video clips into one. With this app, you can escalate your video editing gigs, such as adding text, filters, music, among other options. Follow these steps to merge your videos. #### Quik's distinguishing characteristics * You can energize your videos by adjusting the speed. Likewise, you can stop the time with Freeze Frame. * Use exclusive filters to tweak your video to perfection, such as snow and water filters. * Easily add music to your video. * Sync your edits with royalty-free tracks. * Trimming, cropping, and other simple edits #### How to splice video with Quik Step 1\. Download and install the "Quik" app on your iPhone, then fire it up. Step 2\. Next, begin to create a new project in the Quik video editor on your iPhone. Just tap on the "All photos" dropdown, then select the "Videos" option. Choose the video clips that you wish to splice on your iPhone. Step 3\. You can also get other effects to add to your video. At the bottom, check out the "Effect" tab. Here, you can easily add music, filters, and others to polish your movie. Step 4\. Finally, click on the "Save" tab to save the merged videos. ![how to splice video on iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-4.png) ## \[Desktop solution\] Splice videos with Filmora Apart from splicing videos on the iPhone, you can also utilize the desktop to merge your videos. Many users like to transfer their data, including videos, to a desktop for backup or to create memory space on their phones. This may result in too many videos saved on your desktop. You can splice them together into a single movie by using Filmora. This video editor works on both Windows and Mac computers. It is also easy to use, enabling a simple drop-and-drag action. Besides, it harbors spending editing features and an additional 300+ built-in visual effects like overlays, transitions, and filters. Here are some notable features of Filmora. #### Key Features of Filmora * It will merge your videos without any quality loss to the original file. * Easily speed up hi-res footage with the Proxy workflow feature. * Use the instant mode feature to quickly edit your videos. * With the masking feature, you can easily animate and customize the mask for an improved finish. * This app also comes with an in-built stock media feature that facilitates free copyright stock footage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later #### Steps to using Filmora to splice videos Filmora supports Windows and Macs. So first, choose your computer’s version and download the correct one. Then follow these steps to splice your videos. Step 1: Add videos. After installing and launching Filmora on your PC, continue to add the videos that you want to splice. So, click on the "Import" tab to load your clips into the program. You can also drag and drop the video clips directly into the media library. Step 2\. Splice video All the videos you’ve added will show up as thumbnails in the editor’s window. Now simply drag and drop the clips to the same video track in the timeline. Next, place the "Playhead" at the starting point of the clip where you want the sliced video to start playing. Your videos will be spliced together seamlessly. You can also use the "Preview" feature to preview your video before saving it to the computer. Step 3: Finalize your video. Filmora comes with numerous editing features that let you rotate, trim, add titles, transitions, set speed, add music, and much more. To trim your clip, simply move the "Playhead" to the position you wish to cut first. Next, click on the split icon in the toolbar. You can also right-click on any transition to apply effects, add subtitles, rotate, and perform other advanced editing. Step 4\. Save and Export Ascertain that your video is good enough, then hit the "Create" tab. Continue to save and export your video in any format. Just click on the "Export" tab to finally share your video on platforms like YouTube and Vimeo. You can also directly convert to other portable devices like the iPhone. ## Conclusion ●Several options are available to splice video on the iPhone. You can use the free app, iMovie, for iPhone and Mac. Filmora and Quik are also uniquely able to splice video into a single merge. However, if you wish to retain the original quality of your video, Filmora Video Editor is the option to settle for. It has improved features that will manage any form of edit in simple steps. More so, you can easily share your finished video on social media sites as well as upload it directly to streaming sites like YouTube and Vimeo.es. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Your iPhone comes with so many features, including a camera. You, therefore, have a great chance to take photos, record videos, and catch every moment at your will. You’ll need to share your videos on social media sites or other platforms. Remember, you can spice them up with other add-ons. The most sophisticated way is to splice your iPhone, merging your videos into a compelling piece of art. Let’s uncover several video editors that you can use on your iPhone for splicing your videos. ![splice videos together iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-1.png) #### In this article 01 [How to Splice Videos on an iPhone](#part1) 02 [\[Desktop solution\] Splice videos with Filmora](#part2) ## How to Splice Videos on an iPhone The iPhone lets you do simple edits in the camera roll, such as trimming videos. However, when it comes to joining multiple clips, you need to step up your game with video editors. We bring you exclusive tools that you can use to splice videos together on your iPhone. ### Method 1: Using iMovie on the iPhone, splice videos together This splicing app from Apple is smart at editing professional-quality videos. You can get it for free to splice your videos on the iPhone. Color grading, narration, and the green-screen effect are just a few of the many tools available in iMovie. #### Features of iMovie * Combine multiple videos and transitions. * Green-screen controls to soften the effects that you add to your movie. * Freely adjust the level of your audio clip. * Timeline mode features include a color balance and tone adjusting feature. * A people detection feature that quickly recognizes characters in a film. * Directly export your spliced video to social networking sites or upload it to a cloud service. * Excellent tools to facilitate video editing. #### Steps to splice video on iMovie Step 1\. First, visit the "App Store, download the iMovie app, and install it on your iPhone. Step 2\. Once iMovie is installed on your iPhone, you can then launch it and continue with the splicing mission of your videos. Step 3\. Check the main screen of the app for the "three" tabs located at the top. Choose the tab indicated as the "Projects to create a new project" option. You’ll then be redirected to the next screen, where you should then tap on the "Create Project" option. Step 4\. When prompted, please choose the "Movie" option as the project type to create. Step 5\. Next, select the videos you want and tap on the "Add" option to add your videos from your iPhone Camera Roll. Next, tap on the "Create Movie" option at the bottom. Step 6\. iMovie lets you add any effects to your video at this point. Once completed, tap on the "Done" tab found at the top-left corner of your iPhone’s screen. Finally, save your combined videos into one file. You can also directly upload your video to cloud storage platforms. ![splice video iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-2.png) ### Method 2: Using Filmora on the iPhone, splice videos together Filmora is another app that lets you splice iOS in a few steps. It presents an intuitive interface with powerful video editing features. You can add background music, motion effects, and text effects to your video, and merge several clips into one. Let's check out how to combine your videos on the iPhone. #### Filmora's Features * The Transitions feature lets you create interestingly moving clips. * Simple editing features to trim, cut, and merge videos. * The Canvas feature is suitable for choosing the best aspect ratio for your video. * You can also play your footage backward with the reverse feature. * You can easily adjust the speed of your video by speeding it up or slowing it down. #### A guide to splice video with Filmora Step 1\. You first need to download and install the "Filmora Go" app on your iPhone. Step 2\. Next, hit the "New Project" button and begin to select the videos you wish to splice. Step 3\. Add the selected videos to the interface by clicking on the "Import" button. The "Edit" panel will automatically open. Step 4\. Check for the available tools in the "Editing panel" section. You can now freely use the available effects, like adding music, cropping your videos, adding text, among other effects. Step 5: Finally, you can save and export your video to other media platforms if you want. ### Method 3: Splice videos together on the iPhone using Quik You can also splice your iPhone with Quik Video Editor. Quik video editor is quite advanced and will support the merging of various video clips into one. With this app, you can escalate your video editing gigs, such as adding text, filters, music, among other options. Follow these steps to merge your videos. #### Quik's distinguishing characteristics * You can energize your videos by adjusting the speed. Likewise, you can stop the time with Freeze Frame. * Use exclusive filters to tweak your video to perfection, such as snow and water filters. * Easily add music to your video. * Sync your edits with royalty-free tracks. * Trimming, cropping, and other simple edits #### How to splice video with Quik Step 1\. Download and install the "Quik" app on your iPhone, then fire it up. Step 2\. Next, begin to create a new project in the Quik video editor on your iPhone. Just tap on the "All photos" dropdown, then select the "Videos" option. Choose the video clips that you wish to splice on your iPhone. Step 3\. You can also get other effects to add to your video. At the bottom, check out the "Effect" tab. Here, you can easily add music, filters, and others to polish your movie. Step 4\. Finally, click on the "Save" tab to save the merged videos. ![how to splice video on iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-4.png) ## \[Desktop solution\] Splice videos with Filmora Apart from splicing videos on the iPhone, you can also utilize the desktop to merge your videos. Many users like to transfer their data, including videos, to a desktop for backup or to create memory space on their phones. This may result in too many videos saved on your desktop. You can splice them together into a single movie by using Filmora. This video editor works on both Windows and Mac computers. It is also easy to use, enabling a simple drop-and-drag action. Besides, it harbors spending editing features and an additional 300+ built-in visual effects like overlays, transitions, and filters. Here are some notable features of Filmora. #### Key Features of Filmora * It will merge your videos without any quality loss to the original file. * Easily speed up hi-res footage with the Proxy workflow feature. * Use the instant mode feature to quickly edit your videos. * With the masking feature, you can easily animate and customize the mask for an improved finish. * This app also comes with an in-built stock media feature that facilitates free copyright stock footage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later #### Steps to using Filmora to splice videos Filmora supports Windows and Macs. So first, choose your computer’s version and download the correct one. Then follow these steps to splice your videos. Step 1: Add videos. After installing and launching Filmora on your PC, continue to add the videos that you want to splice. So, click on the "Import" tab to load your clips into the program. You can also drag and drop the video clips directly into the media library. Step 2\. Splice video All the videos you’ve added will show up as thumbnails in the editor’s window. Now simply drag and drop the clips to the same video track in the timeline. Next, place the "Playhead" at the starting point of the clip where you want the sliced video to start playing. Your videos will be spliced together seamlessly. You can also use the "Preview" feature to preview your video before saving it to the computer. Step 3: Finalize your video. Filmora comes with numerous editing features that let you rotate, trim, add titles, transitions, set speed, add music, and much more. To trim your clip, simply move the "Playhead" to the position you wish to cut first. Next, click on the split icon in the toolbar. You can also right-click on any transition to apply effects, add subtitles, rotate, and perform other advanced editing. Step 4\. Save and Export Ascertain that your video is good enough, then hit the "Create" tab. Continue to save and export your video in any format. Just click on the "Export" tab to finally share your video on platforms like YouTube and Vimeo. You can also directly convert to other portable devices like the iPhone. ## Conclusion ●Several options are available to splice video on the iPhone. You can use the free app, iMovie, for iPhone and Mac. Filmora and Quik are also uniquely able to splice video into a single merge. However, if you wish to retain the original quality of your video, Filmora Video Editor is the option to settle for. It has improved features that will manage any form of edit in simple steps. More so, you can easily share your finished video on social media sites as well as upload it directly to streaming sites like YouTube and Vimeo.es. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Your iPhone comes with so many features, including a camera. You, therefore, have a great chance to take photos, record videos, and catch every moment at your will. You’ll need to share your videos on social media sites or other platforms. Remember, you can spice them up with other add-ons. The most sophisticated way is to splice your iPhone, merging your videos into a compelling piece of art. Let’s uncover several video editors that you can use on your iPhone for splicing your videos. ![splice videos together iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-1.png) #### In this article 01 [How to Splice Videos on an iPhone](#part1) 02 [\[Desktop solution\] Splice videos with Filmora](#part2) ## How to Splice Videos on an iPhone The iPhone lets you do simple edits in the camera roll, such as trimming videos. However, when it comes to joining multiple clips, you need to step up your game with video editors. We bring you exclusive tools that you can use to splice videos together on your iPhone. ### Method 1: Using iMovie on the iPhone, splice videos together This splicing app from Apple is smart at editing professional-quality videos. You can get it for free to splice your videos on the iPhone. Color grading, narration, and the green-screen effect are just a few of the many tools available in iMovie. #### Features of iMovie * Combine multiple videos and transitions. * Green-screen controls to soften the effects that you add to your movie. * Freely adjust the level of your audio clip. * Timeline mode features include a color balance and tone adjusting feature. * A people detection feature that quickly recognizes characters in a film. * Directly export your spliced video to social networking sites or upload it to a cloud service. * Excellent tools to facilitate video editing. #### Steps to splice video on iMovie Step 1\. First, visit the "App Store, download the iMovie app, and install it on your iPhone. Step 2\. Once iMovie is installed on your iPhone, you can then launch it and continue with the splicing mission of your videos. Step 3\. Check the main screen of the app for the "three" tabs located at the top. Choose the tab indicated as the "Projects to create a new project" option. You’ll then be redirected to the next screen, where you should then tap on the "Create Project" option. Step 4\. When prompted, please choose the "Movie" option as the project type to create. Step 5\. Next, select the videos you want and tap on the "Add" option to add your videos from your iPhone Camera Roll. Next, tap on the "Create Movie" option at the bottom. Step 6\. iMovie lets you add any effects to your video at this point. Once completed, tap on the "Done" tab found at the top-left corner of your iPhone’s screen. Finally, save your combined videos into one file. You can also directly upload your video to cloud storage platforms. ![splice video iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-2.png) ### Method 2: Using Filmora on the iPhone, splice videos together Filmora is another app that lets you splice iOS in a few steps. It presents an intuitive interface with powerful video editing features. You can add background music, motion effects, and text effects to your video, and merge several clips into one. Let's check out how to combine your videos on the iPhone. #### Filmora's Features * The Transitions feature lets you create interestingly moving clips. * Simple editing features to trim, cut, and merge videos. * The Canvas feature is suitable for choosing the best aspect ratio for your video. * You can also play your footage backward with the reverse feature. * You can easily adjust the speed of your video by speeding it up or slowing it down. #### A guide to splice video with Filmora Step 1\. You first need to download and install the "Filmora Go" app on your iPhone. Step 2\. Next, hit the "New Project" button and begin to select the videos you wish to splice. Step 3\. Add the selected videos to the interface by clicking on the "Import" button. The "Edit" panel will automatically open. Step 4\. Check for the available tools in the "Editing panel" section. You can now freely use the available effects, like adding music, cropping your videos, adding text, among other effects. Step 5: Finally, you can save and export your video to other media platforms if you want. ### Method 3: Splice videos together on the iPhone using Quik You can also splice your iPhone with Quik Video Editor. Quik video editor is quite advanced and will support the merging of various video clips into one. With this app, you can escalate your video editing gigs, such as adding text, filters, music, among other options. Follow these steps to merge your videos. #### Quik's distinguishing characteristics * You can energize your videos by adjusting the speed. Likewise, you can stop the time with Freeze Frame. * Use exclusive filters to tweak your video to perfection, such as snow and water filters. * Easily add music to your video. * Sync your edits with royalty-free tracks. * Trimming, cropping, and other simple edits #### How to splice video with Quik Step 1\. Download and install the "Quik" app on your iPhone, then fire it up. Step 2\. Next, begin to create a new project in the Quik video editor on your iPhone. Just tap on the "All photos" dropdown, then select the "Videos" option. Choose the video clips that you wish to splice on your iPhone. Step 3\. You can also get other effects to add to your video. At the bottom, check out the "Effect" tab. Here, you can easily add music, filters, and others to polish your movie. Step 4\. Finally, click on the "Save" tab to save the merged videos. ![how to splice video on iphone](https://images.wondershare.com/filmora/article-images/2022/03/splice-videos-together-iphone-4.png) ## \[Desktop solution\] Splice videos with Filmora Apart from splicing videos on the iPhone, you can also utilize the desktop to merge your videos. Many users like to transfer their data, including videos, to a desktop for backup or to create memory space on their phones. This may result in too many videos saved on your desktop. You can splice them together into a single movie by using Filmora. This video editor works on both Windows and Mac computers. It is also easy to use, enabling a simple drop-and-drag action. Besides, it harbors spending editing features and an additional 300+ built-in visual effects like overlays, transitions, and filters. Here are some notable features of Filmora. #### Key Features of Filmora * It will merge your videos without any quality loss to the original file. * Easily speed up hi-res footage with the Proxy workflow feature. * Use the instant mode feature to quickly edit your videos. * With the masking feature, you can easily animate and customize the mask for an improved finish. * This app also comes with an in-built stock media feature that facilitates free copyright stock footage. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later #### Steps to using Filmora to splice videos Filmora supports Windows and Macs. So first, choose your computer’s version and download the correct one. Then follow these steps to splice your videos. Step 1: Add videos. After installing and launching Filmora on your PC, continue to add the videos that you want to splice. So, click on the "Import" tab to load your clips into the program. You can also drag and drop the video clips directly into the media library. Step 2\. Splice video All the videos you’ve added will show up as thumbnails in the editor’s window. Now simply drag and drop the clips to the same video track in the timeline. Next, place the "Playhead" at the starting point of the clip where you want the sliced video to start playing. Your videos will be spliced together seamlessly. You can also use the "Preview" feature to preview your video before saving it to the computer. Step 3: Finalize your video. Filmora comes with numerous editing features that let you rotate, trim, add titles, transitions, set speed, add music, and much more. To trim your clip, simply move the "Playhead" to the position you wish to cut first. Next, click on the split icon in the toolbar. You can also right-click on any transition to apply effects, add subtitles, rotate, and perform other advanced editing. Step 4\. Save and Export Ascertain that your video is good enough, then hit the "Create" tab. Continue to save and export your video in any format. Just click on the "Export" tab to finally share your video on platforms like YouTube and Vimeo. You can also directly convert to other portable devices like the iPhone. ## Conclusion ●Several options are available to splice video on the iPhone. You can use the free app, iMovie, for iPhone and Mac. Filmora and Quik are also uniquely able to splice video into a single merge. However, if you wish to retain the original quality of your video, Filmora Video Editor is the option to settle for. It has improved features that will manage any form of edit in simple steps. More so, you can easily share your finished video on social media sites as well as upload it directly to streaming sites like YouTube and Vimeo.es. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## How To Make a Timelapse in After Effects Time-Lapse movies are great for a variety of projects; you can use them as establishing shots in sitcoms, corporate marketing videos, and they can make lovely backgrounds for animated slideshows. A time-lapse video is essentially a series of photographs taken at regular intervals to depict how the environment changes gradually over a shorter period of time. In this article, we'll demonstrate how you may quickly and easily build an After Effects time-lapse effect. With that said, let's start! ## Step 1\. Create a new composition Calculating your composition length to accommodate the frame rate and number of images is the first step in generating a time-lapse video. 1. Verify the number of images you have for your Sequence. 2. New Composition Creation. Selecting a frame rate: A time lapse film produced at 30 frames per second will flow smoothly, but you can select any frame rate you like. 3. To determine the duration of your composition, divide the number of photographs you have by the frame rate you've chosen. For instance, if you use 600 photos at 30 frames per second, your composition will last 20 seconds. ## Step 2\. Import your images You are prepared to make a time-lapse sequence if all of your photographs are saved to the same folder and are in the same order. If you are working directly from your Camera, you will likely have Camera Raw files, although this procedure works with PNG and JPEG sequences. 1. Press Command/Control I on your keyboard or select File > Import. Find the folder holding your image sequence. 2. To begin, select the first picture in the sequence. If all of your images have accurate names, After Effects will be able to identify a sequence of images. 3. Make sure the Force Alphabetical Order and Camera Raw Sequence checkboxes are selected. Your Time-Lapse Sequence will display in the Project Browser Panel after you click Import. 4. Once you've watched how it plays, you can adjust the Frame Rate by right-clicking the Sequence in the Project Browser and selecting Interpret Footage > Main. 5. To update your time-lapse, modify the Frame Rate setting and click OK. ![import images into after effects](https://images.wondershare.com/filmora/article-images/2022/11/import-images-into-after-effects.jpg) ## Step 3\. Create movements 1. After Effects' Time-Lapse Sequence can be used just like any other standalone clip. This implies that you may give your time-lapse clip movement by adding Keyframes and Effects. 2. Place your Playhead at the beginning of the clip after choosing the Image Sequence. Make a keyframe for the scale or position. 3. To generate a second Keyframe for the value of your choice, move to the end of the clip. Make any necessary Clip modifications. 4. Right-click on the timeline, choose New > Adjustment Layer, then add your effects to the Adjustment Layer to add effects like noise and grain. ## Step 4\. Create slow motion from a video You can import your video after you've shot it to prepare it for editing. The same steps, including naming your photos in order, must be taken for the Time Lapse sequence. It may be advantageous to entirely rename both your Image Sequence and Performer clip. 1. Drag the finished Time Lapse sequence to your Timeline after completing it as previously explained. 2. Over the Time Lapse, add the Performer Clip to the Timeline. 3. Choose Time>Time Stretch by performing a right-click on the performer clip. 4. You can alter the Stretch Factor or Duration in the dialogue box. When you alter one parameter, the other will reflect the new Stretch Factor or Duration for you. ## Step 5\. Make an overlay You can alter the Stretch Factor or Duration in the dialogue box. When you alter one parameter, the other will reflect the new Stretch Factor or Duration for you. 1. Find Luma Key in the Effect Control Panel and drag it to your clip. 2. Change the Key Type setting in the Effect Control Panel to Key Out Brighter. 3. The Threshold, Tolerance, and Edge settings should be adjusted until only the silhouette is visible. 4. Use the Pen or Mask Tool to create a circle around the parts you want to delete if you discover any corners of your clip that are still visible. 5. Add any Effects, such as Light Leaks, to your Adjustment Layer by choosing "Right-click > New > Adjustment layer." ![make an overlay after effects](https://images.wondershare.com/filmora/article-images/2022/11/make-an-overlay-after-effects.jpg) After Effects CC must be opened, a new project must be created, the Import File menu option must be selected, and the appropriate folder containing the altered still images must be located and selected before the time-lapse photos can be turned into a film. You need to make sure that the JPEG Series box is checked, as well as the Force Alphabetical Order box. Once you have clicked on the first image in the sequence. The time-lapse video that you uploaded appears in the project library. After performing a right-click on the filename, select "New Comp from Selection" from the context menu. ## Step 6\. Exporting your video After getting our sequence to perform some kind of slow, understated animation so that it appears as though the camera is moving dramatically, we will need to export a video file. Go to File > Export > Add to Render Queue, then open the Render Queue dialog box by going to Window > Render Queue. From there, you can choose the Output Module and change the settings in the options dialog box. Finally, choose the Output To option and select the location on your computer where you would like to save the video clip that we are currently rendering and exporting. ![add to render queue after effects](https://images.wondershare.com/filmora/article-images/2022/11/add-to-render-queue-after-effects.jpg) ## Conclusion No matter how you make your time lapse videos, After Effects has a ton of features you can use to modify and enhance the way they look. Now that you are familiar with the fundamentals, you can play with the Frame Rates and Composition options. Check out this helpful manual for more information on Time Stretching and Remapping in After Effects. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Final Cut Pro - How to Download and Install It We all know that video editing takes the video content to a whole another level. The video editing tools provide the users with an opportunity to modify their created videos. And one such pioneering application available for video editing in the market is the Final Cut Pro. It is an iOS-based application that facilitates dozens of editing tools for its users. Also, it comes with a free trial for all users. Visual contents are a key factor in providing information to the audience since they are more effective than text. And with the introduction of applications like YouTube, Facebook, and other video streaming platforms, the necessity for quality video content has greatly increased. The video editing tools are perfect applications to make any video more attractive and cinematic. In this article, we are going to look into the process of editing videos with Final Cut Pro and the different benefits of using this application. ## How to Download and Install Final Cut Pro? Final Cut Pro is a very popular iOS application that has limitless possibilities in editing and creating videos. And one of the main reasons for its popularity is because its user interface allows even the new users to work with videos flawlessly. And if you have an apple device and you are looking for an application that can help you edit your video contents, then this application is just for you. ![final cut pro](https://images.wondershare.com/filmora/article-images/final-cut-pro.jpg) For final cut pro free download and installation, you will need to follow these steps: * First, go to the apple store from your iOS device and search for Final Cut Pro in the search bar provided. This will open the application page where the Final Cut Pro icon will be shown. * Now, you can click on the "Free Trial" option to download the 90-day free trial version, and then the download will start. Again, in this step, if you have already tried the free version and want to buy the premium version of Final Cut Pro by paying the required amount. To do that you can click on the "Buy" option and the download will start after you initiate the payment. * Alternatively, you can download the Final Cut Pro application from your web browser too. To do that first open any web browser and search for Final Cut Pro in the search bar. * The first result will be from the official apple website with the "Final Cut Pro" name on it. Click on that and you will be headed to the official apple website. * Here you will see the same "Free Trial" or "Buy" option which you can choose as explained in the previous steps. * After the file is downloaded to your device, click on the "Install" option and the installation will start. This process will take some time and after it's completed, you will be able to use the Final Cut Pro without any issues. ![fcp free trial](https://images.wondershare.com/filmora/article-images/fcp-free-trial.jpg) ## Key Features of Final Cut Pro The several key features of Final Cut Pro are: * Importing and exporting high-quality HD videos are possible * Multiple resolution and format support for any video * Easy to use basic tools such as cropping, merging, filters, and many more. * Dozens of editing tools such as transitions, texts, etc. * An intuitive user interface to encourage users with its simple approach * Modern metal engine support for faster delivery of videos * Workflow extension support for an extension to other applications * Advanced color grading tools to create stunning cinematic videos ## How to Edit Videos with Final Cut Pro Final Cut Pro is believed to be one of the most efficient applications in video editing. This is because of its simple yet efficient interface for designing and creating awesome cinematic videos. It has industry-standard color grading tools that work with AI power to enable its users to enhance their video creations. It also is available with voiceover and video overlay features. Now, these can help social media content creators easily develop their video content. And after installing Final Cut Pro if you are overwhelmed by its tons of features, then here are the steps following which you will be able to use Final Cut Pro: * First, open the application. Now, it will ask to allow for the permissions to use your files along with your camera and other audiovisual devices. After allowing that, you will be able to enter the user interface of Final Cut Pro. * Here, you will have to click on the "New project" icon. * It will then ask you to import any media files to the application. Select the video file that you want to edit and it will take some time to import the media file. ![fcp new project icon](https://images.wondershare.com/filmora/article-images/fcp-new-project-icon.jpg) * Alternatively, you can also import any media file by pressing the "cmd+I" keys and selecting the video file. You should note that Final Cut Pro organizes all the contents and media files into different libraries, events as well as projects. This way if you are working on multiple projects, then it is easy to switch between them. * Now, after importing, a thumbnail of your media file will be appearing at the bottom of the screen. * You can now trim or crop your media files from the below timeline. And if you want to add new clips to your project, then you can do so by clicking the "+" icon available. * In the timeline, you can also rearrange the timeline of your video clips. * You can add texts and titles to your videos by clicking on the "Titles" options located in the toolbar. This toolbar is the same browser where you imported the media files in the previous steps. You can also add transitions to add subtle movements between hard-cut clips. ![fcp timeline](https://images.wondershare.com/filmora/article-images/fcp-timeline.jpg) * The effect tools available in the toolbar allow you to use the built-in effects that can bring life to any video. And along with this, you can also use the colors tool to color grade your videos and make them more cinematic. There is also the option to add music and voiceover to your project if you need that. ![fcp title](https://images.wondershare.com/filmora/article-images/fcp-title.jpg) * After you are done with your changes, click on the "share" option available on the screen and then click on "Share Master File" and you will be able to export the project successfully. ## Final Cut Pro Alternative to Edit Videos Content creators who have access to Apple devices can enjoy the features of Final Cut Pro without any difficulties. But for people with other operating systems, Final Cut Pro isn't available. It is why they need alternatives for this application. And if you are looking for the best alternative to Final Cut Pro, then Filmora is the best choice for you. Here is how you can use Filmora to edit your contents: ![filmora video editor](https://images.wondershare.com/filmora/guide/filmora-split-button.jpg) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later * First, install the Filmora application and then open it on your device. * Then click on the "Import" option and then select the video files that you want to edit. * Now if you have selected multiple video files, then you can rearrange, cut, split, and trim your videos in your preferred order. * After you are done with that head to the toolbar where you will be able to add effects, music, transition, and texts to your clip. * WonderShare Filmora also supports voiceover and video overlay that is perfect for content creators. * After you have finished editing your videos, click on the "Export" option available on the toolbar and then save the video file to your device. ## FAQs about Final Cut Pro 1\. Is Final Cut Pro available for free? Final Cut Pro is available with a free trial for all the users who are on iOS. But to unlock all the tools of Final Cut Pro you will need to purchase the application. It can be done by paying a premium amount of money to the company. 2\. Is Final Cut Pro for mac only? Yes, Final Cut Pro is only available for Mac and it isn't supported in any other operating system. For users who have any other OS, they can try using Filmora. It is one of the best alternatives for Final Cut Pro on the market. 3\. Is the Final Cut Pro good for editing? Yes, Final Cut Pro is believed to be one of the finest video editing applications that even is used by popular content creators. This application has a variety of tools that can elevate the content of any video to a whole another level. Final Cut Pro is one of the most trusted video editing applications. This is used by most content creators around the world and it is popular because of its versatile tools. This article discussed some of the key aspects of Final Cut Pro and how it can help creators and general users fulfill their needs for video editing. And for creators who are looking for any alternatives to final cut pro editing, we also discussed the use of Filmora thoroughly which can help them create stunning videos. ![fcp free trial](https://images.wondershare.com/filmora/article-images/fcp-free-trial.jpg) ## Key Features of Final Cut Pro The several key features of Final Cut Pro are: * Importing and exporting high-quality HD videos are possible * Multiple resolution and format support for any video * Easy to use basic tools such as cropping, merging, filters, and many more. * Dozens of editing tools such as transitions, texts, etc. * An intuitive user interface to encourage users with its simple approach * Modern metal engine support for faster delivery of videos * Workflow extension support for an extension to other applications * Advanced color grading tools to create stunning cinematic videos ## How to Edit Videos with Final Cut Pro Final Cut Pro is believed to be one of the most efficient applications in video editing. This is because of its simple yet efficient interface for designing and creating awesome cinematic videos. It has industry-standard color grading tools that work with AI power to enable its users to enhance their video creations. It also is available with voiceover and video overlay features. Now, these can help social media content creators easily develop their video content. And after installing Final Cut Pro if you are overwhelmed by its tons of features, then here are the steps following which you will be able to use Final Cut Pro: * First, open the application. Now, it will ask to allow for the permissions to use your files along with your camera and other audiovisual devices. After allowing that, you will be able to enter the user interface of Final Cut Pro. * Here, you will have to click on the "New project" icon. * It will then ask you to import any media files to the application. Select the video file that you want to edit and it will take some time to import the media file. ![fcp new project icon](https://images.wondershare.com/filmora/article-images/fcp-new-project-icon.jpg) * Alternatively, you can also import any media file by pressing the "cmd+I" keys and selecting the video file. You should note that Final Cut Pro organizes all the contents and media files into different libraries, events as well as projects. This way if you are working on multiple projects, then it is easy to switch between them. * Now, after importing, a thumbnail of your media file will be appearing at the bottom of the screen. * You can now trim or crop your media files from the below timeline. And if you want to add new clips to your project, then you can do so by clicking the "+" icon available. * In the timeline, you can also rearrange the timeline of your video clips. * You can add texts and titles to your videos by clicking on the "Titles" options located in the toolbar. This toolbar is the same browser where you imported the media files in the previous steps. You can also add transitions to add subtle movements between hard-cut clips. ![fcp timeline](https://images.wondershare.com/filmora/article-images/fcp-timeline.jpg) * The effect tools available in the toolbar allow you to use the built-in effects that can bring life to any video. And along with this, you can also use the colors tool to color grade your videos and make them more cinematic. There is also the option to add music and voiceover to your project if you need that. ![fcp title](https://images.wondershare.com/filmora/article-images/fcp-title.jpg) * After you are done with your changes, click on the "share" option available on the screen and then click on "Share Master File" and you will be able to export the project successfully. ## Final Cut Pro Alternative to Edit Videos Content creators who have access to Apple devices can enjoy the features of Final Cut Pro without any difficulties. But for people with other operating systems, Final Cut Pro isn't available. It is why they need alternatives for this application. And if you are looking for the best alternative to Final Cut Pro, then Filmora is the best choice for you. Here is how you can use Filmora to edit your contents: ![filmora video editor](https://images.wondershare.com/filmora/guide/filmora-split-button.jpg) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later * First, install the Filmora application and then open it on your device. * Then click on the "Import" option and then select the video files that you want to edit. * Now if you have selected multiple video files, then you can rearrange, cut, split, and trim your videos in your preferred order. * After you are done with that head to the toolbar where you will be able to add effects, music, transition, and texts to your clip. * WonderShare Filmora also supports voiceover and video overlay that is perfect for content creators. * After you have finished editing your videos, click on the "Export" option available on the toolbar and then save the video file to your device. ## FAQs about Final Cut Pro 1\. Is Final Cut Pro available for free? Final Cut Pro is available with a free trial for all the users who are on iOS. But to unlock all the tools of Final Cut Pro you will need to purchase the application. It can be done by paying a premium amount of money to the company. 2\. Is Final Cut Pro for mac only? Yes, Final Cut Pro is only available for Mac and it isn't supported in any other operating system. For users who have any other OS, they can try using Filmora. It is one of the best alternatives for Final Cut Pro on the market. 3\. Is the Final Cut Pro good for editing? Yes, Final Cut Pro is believed to be one of the finest video editing applications that even is used by popular content creators. This application has a variety of tools that can elevate the content of any video to a whole another level. Final Cut Pro is one of the most trusted video editing applications. This is used by most content creators around the world and it is popular because of its versatile tools. This article discussed some of the key aspects of Final Cut Pro and how it can help creators and general users fulfill their needs for video editing. And for creators who are looking for any alternatives to final cut pro editing, we also discussed the use of Filmora thoroughly which can help them create stunning videos. ![fcp free trial](https://images.wondershare.com/filmora/article-images/fcp-free-trial.jpg) ## Key Features of Final Cut Pro The several key features of Final Cut Pro are: * Importing and exporting high-quality HD videos are possible * Multiple resolution and format support for any video * Easy to use basic tools such as cropping, merging, filters, and many more. * Dozens of editing tools such as transitions, texts, etc. * An intuitive user interface to encourage users with its simple approach * Modern metal engine support for faster delivery of videos * Workflow extension support for an extension to other applications * Advanced color grading tools to create stunning cinematic videos ## How to Edit Videos with Final Cut Pro Final Cut Pro is believed to be one of the most efficient applications in video editing. This is because of its simple yet efficient interface for designing and creating awesome cinematic videos. It has industry-standard color grading tools that work with AI power to enable its users to enhance their video creations. It also is available with voiceover and video overlay features. Now, these can help social media content creators easily develop their video content. And after installing Final Cut Pro if you are overwhelmed by its tons of features, then here are the steps following which you will be able to use Final Cut Pro: * First, open the application. Now, it will ask to allow for the permissions to use your files along with your camera and other audiovisual devices. After allowing that, you will be able to enter the user interface of Final Cut Pro. * Here, you will have to click on the "New project" icon. * It will then ask you to import any media files to the application. Select the video file that you want to edit and it will take some time to import the media file. ![fcp new project icon](https://images.wondershare.com/filmora/article-images/fcp-new-project-icon.jpg) * Alternatively, you can also import any media file by pressing the "cmd+I" keys and selecting the video file. You should note that Final Cut Pro organizes all the contents and media files into different libraries, events as well as projects. This way if you are working on multiple projects, then it is easy to switch between them. * Now, after importing, a thumbnail of your media file will be appearing at the bottom of the screen. * You can now trim or crop your media files from the below timeline. And if you want to add new clips to your project, then you can do so by clicking the "+" icon available. * In the timeline, you can also rearrange the timeline of your video clips. * You can add texts and titles to your videos by clicking on the "Titles" options located in the toolbar. This toolbar is the same browser where you imported the media files in the previous steps. You can also add transitions to add subtle movements between hard-cut clips. ![fcp timeline](https://images.wondershare.com/filmora/article-images/fcp-timeline.jpg) * The effect tools available in the toolbar allow you to use the built-in effects that can bring life to any video. And along with this, you can also use the colors tool to color grade your videos and make them more cinematic. There is also the option to add music and voiceover to your project if you need that. ![fcp title](https://images.wondershare.com/filmora/article-images/fcp-title.jpg) * After you are done with your changes, click on the "share" option available on the screen and then click on "Share Master File" and you will be able to export the project successfully. ## Final Cut Pro Alternative to Edit Videos Content creators who have access to Apple devices can enjoy the features of Final Cut Pro without any difficulties. But for people with other operating systems, Final Cut Pro isn't available. It is why they need alternatives for this application. And if you are looking for the best alternative to Final Cut Pro, then Filmora is the best choice for you. Here is how you can use Filmora to edit your contents: ![filmora video editor](https://images.wondershare.com/filmora/guide/filmora-split-button.jpg) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later * First, install the Filmora application and then open it on your device. * Then click on the "Import" option and then select the video files that you want to edit. * Now if you have selected multiple video files, then you can rearrange, cut, split, and trim your videos in your preferred order. * After you are done with that head to the toolbar where you will be able to add effects, music, transition, and texts to your clip. * WonderShare Filmora also supports voiceover and video overlay that is perfect for content creators. * After you have finished editing your videos, click on the "Export" option available on the toolbar and then save the video file to your device. ## FAQs about Final Cut Pro 1\. Is Final Cut Pro available for free? Final Cut Pro is available with a free trial for all the users who are on iOS. But to unlock all the tools of Final Cut Pro you will need to purchase the application. It can be done by paying a premium amount of money to the company. 2\. Is Final Cut Pro for mac only? Yes, Final Cut Pro is only available for Mac and it isn't supported in any other operating system. For users who have any other OS, they can try using Filmora. It is one of the best alternatives for Final Cut Pro on the market. 3\. Is the Final Cut Pro good for editing? Yes, Final Cut Pro is believed to be one of the finest video editing applications that even is used by popular content creators. This application has a variety of tools that can elevate the content of any video to a whole another level. Final Cut Pro is one of the most trusted video editing applications. This is used by most content creators around the world and it is popular because of its versatile tools. This article discussed some of the key aspects of Final Cut Pro and how it can help creators and general users fulfill their needs for video editing. And for creators who are looking for any alternatives to final cut pro editing, we also discussed the use of Filmora thoroughly which can help them create stunning videos. ![fcp free trial](https://images.wondershare.com/filmora/article-images/fcp-free-trial.jpg) ## Key Features of Final Cut Pro The several key features of Final Cut Pro are: * Importing and exporting high-quality HD videos are possible * Multiple resolution and format support for any video * Easy to use basic tools such as cropping, merging, filters, and many more. * Dozens of editing tools such as transitions, texts, etc. * An intuitive user interface to encourage users with its simple approach * Modern metal engine support for faster delivery of videos * Workflow extension support for an extension to other applications * Advanced color grading tools to create stunning cinematic videos ## How to Edit Videos with Final Cut Pro Final Cut Pro is believed to be one of the most efficient applications in video editing. This is because of its simple yet efficient interface for designing and creating awesome cinematic videos. It has industry-standard color grading tools that work with AI power to enable its users to enhance their video creations. It also is available with voiceover and video overlay features. Now, these can help social media content creators easily develop their video content. And after installing Final Cut Pro if you are overwhelmed by its tons of features, then here are the steps following which you will be able to use Final Cut Pro: * First, open the application. Now, it will ask to allow for the permissions to use your files along with your camera and other audiovisual devices. After allowing that, you will be able to enter the user interface of Final Cut Pro. * Here, you will have to click on the "New project" icon. * It will then ask you to import any media files to the application. Select the video file that you want to edit and it will take some time to import the media file. ![fcp new project icon](https://images.wondershare.com/filmora/article-images/fcp-new-project-icon.jpg) * Alternatively, you can also import any media file by pressing the "cmd+I" keys and selecting the video file. You should note that Final Cut Pro organizes all the contents and media files into different libraries, events as well as projects. This way if you are working on multiple projects, then it is easy to switch between them. * Now, after importing, a thumbnail of your media file will be appearing at the bottom of the screen. * You can now trim or crop your media files from the below timeline. And if you want to add new clips to your project, then you can do so by clicking the "+" icon available. * In the timeline, you can also rearrange the timeline of your video clips. * You can add texts and titles to your videos by clicking on the "Titles" options located in the toolbar. This toolbar is the same browser where you imported the media files in the previous steps. You can also add transitions to add subtle movements between hard-cut clips. ![fcp timeline](https://images.wondershare.com/filmora/article-images/fcp-timeline.jpg) * The effect tools available in the toolbar allow you to use the built-in effects that can bring life to any video. And along with this, you can also use the colors tool to color grade your videos and make them more cinematic. There is also the option to add music and voiceover to your project if you need that. ![fcp title](https://images.wondershare.com/filmora/article-images/fcp-title.jpg) * After you are done with your changes, click on the "share" option available on the screen and then click on "Share Master File" and you will be able to export the project successfully. ## Final Cut Pro Alternative to Edit Videos Content creators who have access to Apple devices can enjoy the features of Final Cut Pro without any difficulties. But for people with other operating systems, Final Cut Pro isn't available. It is why they need alternatives for this application. And if you are looking for the best alternative to Final Cut Pro, then Filmora is the best choice for you. Here is how you can use Filmora to edit your contents: ![filmora video editor](https://images.wondershare.com/filmora/guide/filmora-split-button.jpg) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later * First, install the Filmora application and then open it on your device. * Then click on the "Import" option and then select the video files that you want to edit. * Now if you have selected multiple video files, then you can rearrange, cut, split, and trim your videos in your preferred order. * After you are done with that head to the toolbar where you will be able to add effects, music, transition, and texts to your clip. * WonderShare Filmora also supports voiceover and video overlay that is perfect for content creators. * After you have finished editing your videos, click on the "Export" option available on the toolbar and then save the video file to your device. ## FAQs about Final Cut Pro 1\. Is Final Cut Pro available for free? Final Cut Pro is available with a free trial for all the users who are on iOS. But to unlock all the tools of Final Cut Pro you will need to purchase the application. It can be done by paying a premium amount of money to the company. 2\. Is Final Cut Pro for mac only? Yes, Final Cut Pro is only available for Mac and it isn't supported in any other operating system. For users who have any other OS, they can try using Filmora. It is one of the best alternatives for Final Cut Pro on the market. 3\. Is the Final Cut Pro good for editing? Yes, Final Cut Pro is believed to be one of the finest video editing applications that even is used by popular content creators. This application has a variety of tools that can elevate the content of any video to a whole another level. Final Cut Pro is one of the most trusted video editing applications. This is used by most content creators around the world and it is popular because of its versatile tools. This article discussed some of the key aspects of Final Cut Pro and how it can help creators and general users fulfill their needs for video editing. And for creators who are looking for any alternatives to final cut pro editing, we also discussed the use of Filmora thoroughly which can help them create stunning videos. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://ai-video-editing.techidaily.com/2024-approved-guide-of-8-photo-collage-apps-for-pc/"><u>2024 Approved Guide of 8 Photo Collage Apps for PC</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-how-to-create-a-bokeh-effect-for-2024/"><u>New How to Create a Bokeh Effect for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-in-2024-in-this-article-we-will-discuss-what-lens-distortion-is-how-it-may-be-fixed-and-the-factors-you-need-to-pay-attention-to-avoid-lens-distortion-w/"><u>New In 2024, In This Article, We Will Discuss What Lens Distortion Is, How It May Be Fixed, and the Factors You Need to Pay Attention to Avoid Lens Distortion when Taking or Recording Videos</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/in-2024-how-to-splice-videos-together-on-iphone/"><u>In 2024, How to Splice Videos Together on iPhone</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-what-if-youtube-zoom-to-fill-not-working-for-2024/"><u>Updated What If YouTube Zoom to Fill Not Working for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-2024-approved-are-you-in-a-funny-chat-with-a-friend-and-want-to-send-a-gif-but-couldnt-find-one-here-we-will-provide-you-with-the-top-image-for-gif-/"><u>Updated 2024 Approved Are You in a Funny Chat with a Friend and Want to Send a GIF but Couldnt Find One? Here We Will Provide You with the Top Image for GIF Converters. So, Let Us See How to Turn Images Into GIFs Very Quickly</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/top-5-online-video-converter-for-instagram-for-2024/"><u>Top 5 Online Video Converter for Instagram for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-best-8-augmented-reality-video-games/"><u>New Best 8 Augmented Reality Video Games</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-how-to-livestream-zoom-on-facebook-for-2024/"><u>Updated How to Livestream Zoom on Facebook for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-quick-answer-why-did-filmora-ai-portrait-attract-people/"><u>New Quick Answer Why Did Filmora AI Portrait Attract People?</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/the-easiest-way-to-make-time-lapse-videos-yes-you-can-make-a-time-lapse-video-with-your-phone-it-powers-a-very-simple-and-easy-way-to-make-time-lapse-videos/"><u>The Easiest Way to Make Time-Lapse Videos. Yes, You Can Make a Time-Lapse Video with Your Phone. It Powers a Very Simple and Easy Way to Make Time-Lapse Videos</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-here-you-can-lean-about-the-different-ways-for-gimp-transparent-background-png-format-files-for-2024/"><u>Updated Here You Can Lean About the Different Ways for GIMP Transparent Background PNG Format Files for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/2024-approved-voice-changer-for-discord-use-voicemod-on-discord/"><u>2024 Approved Voice Changer for Discord | Use Voicemod on Discord</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-in-2024-12-top-picks-of-video-enhancer-software/"><u>Updated In 2024, 12 Top Picks of Video Enhancer Software</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-in-2024-5-methods-to-make-a-fake-facetime-call-video/"><u>New In 2024, 5 Methods to Make a Fake Facetime Call Video</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/2024-approved-best-video-editing-courses-online-with-certificate/"><u>2024 Approved Best Video Editing Courses Online with Certificate</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/in-2024-best-things-people-know-about-wedding-slideshow/"><u>In 2024, Best Things People Know About Wedding Slideshow</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-2024-approved-how-to-use-zoom-in-google/"><u>New 2024 Approved How to Use Zoom in Google</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-2024-approved-can-you-make-an-fcpx-slideshow-undoubtedly-yes-with-the-unlimited-best-fcpx-slideshow-templates-available-to-know-how-to-follow-the-di/"><u>Updated 2024 Approved Can You Make an Fcpx Slideshow? Undoubtedly Yes, with the Unlimited Best Fcpx Slideshow Templates Available. To Know How to, Follow the Discussion Below</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-in-2024-how-to-quickly-create-a-screen-print-effect-in-photoshop-detailed-guide/"><u>Updated In 2024, How To Quickly Create A Screen Print Effect In Photoshop Detailed Guide</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-using-adobe-after-effects-as-a-pro-level-editing-platforms-demands-you-to-add-expressions-in-after-effects-if-youre-looking-for-the-solutions-on-after-e/"><u>New Using Adobe After Effects as a Pro-Level Editing Platforms Demands You to Add Expressions in After Effects. If Youre Looking for the Solutions on After Effects How to Add Expressions Then Weve Got You Covered. Learn More Here</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-2024-approved-good-slideshow-makers-sometimes-cost-high-and-free-slideshow-makers-provide-slideshows-with-the-watermark-how-to-cope-with-this-proble/"><u>Updated 2024 Approved Good Slideshow Makers Sometimes Cost High and Free Slideshow Makers Provide Slideshows with the Watermark. How to Cope with This Problem? This Article Gives Solutions</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-2024-approved-how-to-change-aspect-ratio-in-imovie/"><u>New 2024 Approved How to Change Aspect Ratio in iMovie</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/in-2024-do-you-want-to-experiment-with-various-sky-backgrounds-for-your-footage-learn-about-sky-replacement-after-effects-in-this-article-with-a-step-by-ste/"><u>In 2024, Do You Want to Experiment with Various Sky Backgrounds for Your Footage? Learn About Sky Replacement After Effects in This Article with a Step-by-Step Guide</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/which-is-the-best-video-slideshow-maker-available-online-methods-to-prepare-custom-slideshows-for-google-presentation-how-to-make-a-slide-show-video/"><u>Which Is the Best Video Slideshow Maker Available Online? Methods to Prepare Custom Slideshows for Google Presentation. How to Make a Slide Show Video?</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-how-to-make-foggy-text-reflection-effect/"><u>Updated How to Make Foggy Text Reflection Effect</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-are-you-searching-for-the-best-cinematic-luts-for-premiere-pro-you-are-in-the-right-place-because-this-article-is-dedicated-to-luts/"><u>Updated Are You Searching for the Best Cinematic LUTs for Premiere Pro? You Are in the Right Place because This Article Is Dedicated to LUTs</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/1713964911357-new-the-premiere-pro-video-templates-help-make-original-content-of-broadcast-quality-the-article-introduces-10-free-premiere-pro-templates-that-are-sure-to-/"><u>New The Premiere Pro Video Templates Help Make Original Content of Broadcast Quality. The Article Introduces 10 Free Premiere Pro Templates that Are Sure to Make Your Life Easy for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-2024-approved-guaranteed-10-storyboard-creators-to-make-animation-easier/"><u>Updated 2024 Approved Guaranteed 10 Storyboard Creators To Make Animation Easier</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-2024-approved-how-to-rotate-videos-with-media-player-classic/"><u>New 2024 Approved How to Rotate Videos With Media Player Classic</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/1713965399894-updated-unleash-the-power-of-video-slow-motion-with-wondershare-filmora-find-out-how-to-create-slow-motion-video-with-the-effective-speed-ramping-feature-on/"><u>Updated Unleash the Power of Video Slow Motion with Wondershare Filmora. Find Out How to Create Slow Motion Video with the Effective Speed Ramping Feature on Filmora for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-2024-approved-time-lapse-videos-play-an-important-part-in-videography-if-you-want-to-start-video-shooting-then-you-shouldnt-miss-time-lapse-video-th/"><u>Updated 2024 Approved Time Lapse Videos Play an Important Part in Videography. If You Want to Start Video Shooting, Then You Shouldnt Miss Time Lapse Video. This Article Will Show You some Ideas over This</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-2024-approved-how-to-download-and-use-vegas-pro/"><u>New 2024 Approved How to Download and Use Vegas Pro</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/1713954129060-updated-how-to-change-quicktime-player-speed-on-mac-in-2024/"><u>Updated | How to Change Quicktime Player Speed on Mac, In 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-a-guide-to-motion-tracking-using-the-best-video-editors-for-2024/"><u>Updated A Guide To Motion Tracking Using The Best Video Editors for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/new-2024-approved-video-inspiration-for-birthday-slideshow/"><u>New 2024 Approved Video Inspiration for Birthday Slideshow</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/2024-approved-this-article-presents-a-guide-to-using-the-keyframe-feature-for-creating-competent-films-with-detailed-instructions-and-filmoras-grow-and-win-/"><u>2024 Approved This Article Presents a Guide to Using the Keyframe Feature for Creating Competent Films with Detailed Instructions and Filmoras Grow and Win Program Contest</u></a></li> <li><a href="https://ios-unlock.techidaily.com/in-2024-how-to-unlock-a-found-apple-iphone-6s-plus-by-drfone-ios/"><u>In 2024, How To Unlock A Found Apple iPhone 6s Plus?</u></a></li> <li><a href="https://pokemon-go-android.techidaily.com/in-2024-preparation-to-beat-giovani-in-pokemon-go-for-realme-12-proplus-5g-drfone-by-drfone-virtual-android/"><u>In 2024, Preparation to Beat Giovani in Pokemon Go For Realme 12 Pro+ 5G | Dr.fone</u></a></li> <li><a href="https://bypass-frp.techidaily.com/5-quick-methods-to-bypass-xiaomi-redmi-12-frp-by-drfone-android/"><u>5 Quick Methods to Bypass Xiaomi Redmi 12 FRP</u></a></li> <li><a href="https://location-social.techidaily.com/top-7-skype-hacker-to-hack-any-skype-account-on-your-apple-iphone-15-drfone-by-drfone-virtual-ios/"><u>Top 7 Skype Hacker to Hack Any Skype Account On your Apple iPhone 15 | Dr.fone</u></a></li> <li><a href="https://techidaily.com/sign-word-2003-documents-online-for-free-by-ldigisigner-sign-a-word-sign-a-word/"><u>Sign Word 2003 Documents Online for Free</u></a></li> <li><a href="https://android-unlock.techidaily.com/tips-and-tricks-for-setting-up-your-vivo-y17s-phone-pattern-lock-by-drfone-android/"><u>Tips and Tricks for Setting Up your Vivo Y17s Phone Pattern Lock</u></a></li> <li><a href="https://location-social.techidaily.com/in-2024-top-7-skype-hacker-to-hack-any-skype-account-on-your-vivo-y77t-drfone-by-drfone-virtual-android/"><u>In 2024, Top 7 Skype Hacker to Hack Any Skype Account On your Vivo Y77t | Dr.fone</u></a></li> <li><a href="https://animation-videos.techidaily.com/updated-12-animation-video-maker-that-can-triple-your-conversion-rates/"><u>Updated 12 Animation Video Maker That Can Triple Your Conversion Rates</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/chrome-video-translators-top-5-video-translation-chrome-extensions-for-2024/"><u>Chrome Video Translators Top 5 Video Translation Chrome Extensions for 2024</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/updated-in-2024-how-to-translate-youtube-videos-without-cc/"><u>Updated In 2024, How to Translate YouTube Videos Without CC</u></a></li> <li><a href="https://phone-solutions.techidaily.com/4-easy-ways-for-your-xiaomi-redmi-note-12r-hard-reset-drfone-by-drfone-reset-android-reset-android/"><u>4 Easy Ways for Your Xiaomi Redmi Note 12R Hard Reset | Dr.fone</u></a></li> <li><a href="https://android-location-track.techidaily.com/in-2024-how-to-spy-on-text-messages-from-computer-and-oneplus-nord-3-5g-drfone-by-drfone-virtual-android/"><u>In 2024, How to Spy on Text Messages from Computer & OnePlus Nord 3 5G | Dr.fone</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-how-to-migrate-android-data-from-tecno-spark-20-pro-to-new-android-phone-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, How to Migrate Android Data From Tecno Spark 20 Pro to New Android Phone? | Dr.fone</u></a></li> </ul></div>
using System; using System.Collections.Generic; using System.Data; using Unit05.Game.Casting; using Unit05.Game.Services; namespace Unit05.Game.Scripting { /// <summary> /// <para>An update action that handles interactions between the actors.</para> /// <para> /// The responsibility of HandleCollisionsAction is to handle the situation when the Cycle /// collides with the food, or the Cycle collides with its segments, or the game is over. /// </para> /// </summary> public class HandleCollisionsAction : Action { private bool _isGameOver = false; /// <summary> /// Constructs a new instance of HandleCollisionsAction. /// </summary> public HandleCollisionsAction() { } /// <inheritdoc/> public void Execute(Cast cast, Script script) { if (_isGameOver == false) { HandleSegmentCollisions(cast); HandleGameOver(cast); } } /// <summary> /// Sets the game over flag if the Cycle collides with one of its segments. /// </summary> /// <param name="cast">The cast of actors.</param> private void HandleSegmentCollisions(Cast cast) { foreach(Cycle cycle in cast.GetActors("cycles")) { Actor head = cycle.GetHead(); foreach(Cycle othercycle in cast.GetActors("cycles")) { List<Actor> body = othercycle.GetBody(); foreach (Actor segment in body) { if (segment.GetPosition().Equals(head.GetPosition()) ) { _isGameOver = true; } } } } } private void HandleGameOver(Cast cast) { if (_isGameOver == true) { // create a "game over" message int x = Constants.MAX_X / 2; int y = Constants.MAX_Y / 2; Point position = new Point(x, y); Actor message = new Actor(); message.SetText("Game Over!"); message.SetPosition(position); cast.AddActor("messages", message); // make everything white foreach (Cycle cycle in cast.GetActors("cycles")) { List<Actor> segments = cycle.GetSegments(); foreach (Actor segment in segments) { segment.SetColor(Constants.WHITE); } } } } } }
<?php /* +---------------------------------------------------------------------------+ | OpenX v${RELEASE_MAJOR_MINOR} | | =======${RELEASE_MAJOR_MINOR_DOUBLE_UNDERLINE} | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation; either version 2 of the License, or | | (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License | | along with this program; if not, write to the Free Software | | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | +---------------------------------------------------------------------------+ $Id$ */ require_once MAX_PATH . '/lib/OA/Maintenance/Priority/DeliveryLimitation.php'; require_once MAX_PATH . '/lib/pear/Date.php'; /** * @package OpenXMaintenance * @subpackage TestSuite * @author Andrew Hill <andrew.hill@openx.org> */ class Test_OA_Maintenance_Priority_DeliveryLimitation_Date extends UnitTestCase { function setUp() { // Install the openXDeliveryLog plugin TestEnv::uninstallPluginPackage('openXDeliveryLimitations', false); TestEnv::installPluginPackage('openXDeliveryLimitations', false); } function tearDown() { // Uninstall the openXDeliveryLog plugin TestEnv::uninstallPluginPackage('openXDeliveryLimitations', false); } /** * A method to test the deliveryBlocked() method. * * Test 1: Test date == delivery requirement * Test 2: Test date != delivery requirement * Test 3: Test date <= delivery requirement * Test 4: Test date >= delivery requirement * Test 5: Test date < delivery requirement * Test 6: Test date > delivery requirement * Test 7: Bad input, no date object passed to method */ function testDeliveryBlocked() { // Set timezone to UTC OA_setTimeZoneUTC(); $oDate = new Date('2005-04-03'); $oEarlierDate = new Date('2005-04-02'); $oLaterDate = new Date('2005-04-04'); $limitationData = $oDate->format('%Y%m%d@%Z'); // Test 1 $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '==', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); // Test with same date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oDate)); // Test with ealier date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oEarlierDate)); // Test with later date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oLaterDate)); // Test 2 $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '!=', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); // Test with same date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oDate)); // Test with ealier date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oEarlierDate)); // Test with later date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oLaterDate)); // Test 3 $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '<=', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); // Test with same date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oDate)); // Test with ealier date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oEarlierDate)); // Test with later date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oLaterDate)); // Test 4 $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '>=', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); // Test with same date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oDate)); // Test with ealier date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oEarlierDate)); // Test with later date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oLaterDate)); // Test 5 $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '<', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); // Test with same date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oDate)); // Test with ealier date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oEarlierDate)); // Test with later date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oLaterDate)); // Test 6 $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '>', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); // Test with same date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oDate)); // Test with ealier date: true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oEarlierDate)); // Test with later date: false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oLaterDate)); // Test 7 $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '>', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); PEAR::pushErrorHandling(null); $this->assertTrue(is_a($oLimitationDate->deliveryBlocked('not a date'), 'pear_error')); PEAR::popErrorHandling(); // Test with PST timezone $limitationData = $oDate->format('%Y%m%d').'@America/New_York'; $aDeliveryLimitation = array( 'ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Date', 'comparison' => '==', 'data' => $limitationData, 'executionorder' => 1 ); $oLimitationDate = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); // Test with same date (-1 day, 19pm in EST): true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oDate)); // Test with ealier date (-2 days, 19pm in EST): true, ad is inactive $this->assertTrue($oLimitationDate->deliveryBlocked($oEarlierDate)); // Test with later date (-0 days, 19pm in EST): false, ad is active $this->assertFalse($oLimitationDate->deliveryBlocked($oLaterDate)); // Reset timezone OA_setTimeZoneLocal(); } } ?>
/* * * Copyright 2024 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const parseArgs = require('minimist'); const PROTO_PATH = __dirname + '/../protos/echo.proto'; const packageDefinition = protoLoader.loadSync( PROTO_PATH, {keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const echoProto = grpc.loadPackageDefinition(packageDefinition).grpc.examples.echo; function authInterceptor(options, nextCall) { const requester = (new grpc.RequesterBuilder()) .withStart((metadata, listener, next) => { metadata.set('authorization', 'some-secret-token'); next(metadata, listener); }).build(); return new grpc.InterceptingCall(nextCall(options), requester); } // logger is to mock a sophisticated logging system. To simplify the example, we just print out the content. function logger(format, ...args) { console.log(`LOG (client):\t${format}\n`, ...args); } function loggingInterceptor(options, nextCall) { const listener = (new grpc.ListenerBuilder()) .withOnReceiveMessage((message, next) => { logger(`Receive a message ${JSON.stringify(message)} at ${(new Date()).toISOString()}`); next(message); }).build(); const requester = (new grpc.RequesterBuilder()) .withSendMessage((message, next) => { logger(`Send a message ${JSON.stringify(message)} at ${(new Date()).toISOString()}`); next(message); }).build(); return new grpc.InterceptingCall(nextCall(options), requester); } function callUnaryEcho(client, message) { return new Promise((resolve, reject) => { const deadline = new Date(); deadline.setSeconds(deadline.getSeconds() + 10); client.unaryEcho({message: message}, {deadline}, (error, value) => { if (error) { reject(error); return; } console.log(`UnaryEcho: ${JSON.stringify(value)}`); resolve(); }); }); } function callBidiStreamingEcho(client) { return new Promise((resolve, reject) => { const deadline = new Date(); deadline.setSeconds(deadline.getSeconds() + 10); const call = client.bidirectionalStreamingEcho({deadline}); call.on('data', value => { console.log(`BidiStreamingEcho: ${JSON.stringify(value)}`); }); call.on('status', status => { if (status.code === grpc.status.OK) { resolve(); } else { reject(status); } }); call.on('error', () => { // Ignore error event }); for (let i = 0; i < 5; i++) { call.write({message: `Request ${i + 1}`}); } call.end(); }); } async function main() { let argv = parseArgs(process.argv.slice(2), { string: 'target', default: {target: 'localhost:50051'} }); const client = new echoProto.Echo(argv.target, grpc.credentials.createInsecure(), {interceptors: [authInterceptor, loggingInterceptor]}); await callUnaryEcho(client, 'hello world'); await callBidiStreamingEcho(client); } main();
import Image from "next/image"; import { FC, ReactNode } from "react"; export interface CommunityRowProps { pfp: string; serverName: string; completedBounties: number; raffleTicketsSold: number; totalPoints: number; } const CommunityRow: FC<CommunityRowProps> = ({ pfp, serverName, completedBounties, raffleTicketsSold, totalPoints, }) => { return ( <> <CommunityCell> <img src={pfp} alt={`${serverName} profile picture`} className=" flex-shrink-0 w-16 h-16 rounded-full bg-neutral-800 " /> </CommunityCell> <CommunityCell> <h3 className="text-xl font-bold">{serverName}</h3> </CommunityCell> <CommunityCell> <p className="text-center">{completedBounties}</p> </CommunityCell> <CommunityCell> <p className="text-center">{raffleTicketsSold}</p> </CommunityCell> <CommunityCell> <p className="text-center text-themeSkyBlue font-bold text-xl">{totalPoints}</p> </CommunityCell> </> ) } export default CommunityRow const CommunityCell: FC<{ children: ReactNode }> = ({ children }) => ( <div className="border-y border-themeWhite/20 border-collapse py-4 px-4 flex items-center justify-center flex-shrink-0"> {children} </div> )
package com.mrugendra.notificationtest.Network import android.util.Log import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.Timestamp import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.Source import com.google.firebase.messaging.FirebaseMessaging import com.mrugendra.notificationtest.data.Identified import com.mrugendra.notificationtest.data.Unidentified import com.mrugendra.notificationtest.data.deliveryPerson import com.mrugendra.notificationtest.data.residents import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withContext import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine interface FirebaseAPI{ suspend fun getFCMToken():String suspend fun AlreadyExist(token:String):Boolean suspend fun updateDatabaseToken(token:String, username:String,password: String) suspend fun getResidentsList():List<residents> suspend fun signOutUser(currentToken : String) suspend fun checkUsersReturnFalse(username: String, password: String):Boolean suspend fun getIdentifiedList():List<Identified> suspend fun getUnidentifiedList():List<Unidentified> suspend fun getDeliveryPeopleList():List<deliveryPerson> } val TAG = "MyFirebaseMessagingService" class NetworkFirebaseAPI( val db : FirebaseFirestore, val tokenCollection : CollectionReference, val residentCollection : CollectionReference, val userLoginCollection :CollectionReference, val identifiedCollection: CollectionReference, val unidentifiedCollection:CollectionReference, val deliveryCollection:CollectionReference ):FirebaseAPI{ override suspend fun getFCMToken():String { return withContext(Dispatchers.IO) { return@withContext suspendCoroutine<String> { continuation-> FirebaseMessaging.getInstance().token .addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Fetching FCM registration token failed", task.exception) continuation.resume("Failed to fetch the token") return@OnCompleteListener } val token = task.result continuation.resume(token?:"Token is null") Log.d(TAG, "token: $token") }) } } } override suspend fun AlreadyExist(token:String):Boolean{ return try { val result = tokenCollection .whereEqualTo("token",token) .get(Source.SERVER) .await() Log.d(TAG,"${result.documents}") result.isEmpty }catch (e:Exception){ Log.e(TAG,"Backend: unable to fetch") throw e // false } } override suspend fun updateDatabaseToken(token: String, username: String, password: String) { // AlreadyExist(token) Log.d(TAG, "Database update called") val resident = hashMapOf( "username" to username, "password" to password, "token" to token ) tokenCollection .document(token) .set(resident) .addOnSuccessListener { documentRef -> Log.d(TAG, "Document updated with ID: ${documentRef.toString()}") } .addOnFailureListener { e -> Log.d(TAG, "Error adding : ", e) throw e // return@addOnFailureListener } } override suspend fun getResidentsList(): List<residents> { val residentsList = mutableListOf<residents>() Log.d(TAG,"residents fetching from api") try{ val querySnapshop = residentCollection .get() .await() for (document in querySnapshop.documents){ val name = document.getString("name")?:"" val id = document.getString("id")?:"" val info = document.getString("info")?:"" val profilePhoto = document.getString("profilePhoto")?:"" val resident = residents(name,id,info,profilePhoto) Log.d(TAG,"Resident with id : ${resident.id} got") residentsList.add(resident) } } catch( e:Exception ){ Log.d(TAG,"Failed to get the data") throw e } Log.d(TAG,"residents is empyt : ${residentsList.isEmpty()}") return if(residentsList.isNotEmpty()) residentsList else throw Exception() } override suspend fun signOutUser(currentToken: String) { try{ tokenCollection .document(currentToken) .delete() .addOnSuccessListener { Log.d(TAG, "successfully deleted $currentToken") } }catch (e:Exception){ throw e } } override suspend fun checkUsersReturnFalse(username: String, password: String): Boolean { return try{ val result = tokenCollection .whereEqualTo("username" , username) .whereEqualTo("password",password) .get() result.await().isEmpty }catch (e:Exception){ throw e } } override suspend fun getIdentifiedList(): List<Identified> { val IdentifiedList = mutableListOf<Identified>() Log.d(TAG,"identified fetching from api") try{ val querySnapshop = identifiedCollection .get() .await() for (document in querySnapshop.documents){ val name = document.getString("name")?:"" val id = document.getString("id")?:"" val time = document.getTimestamp("timeStamp")?: Timestamp.now() val identf = Identified(id,name,time) Log.d(TAG,"Resident with id : ${identf.id} got") IdentifiedList.add(identf) } } catch( e:Exception ){ Log.d(TAG,"Failed to get the idenfied data") throw e } Log.d(TAG,"identified is empyt : ${IdentifiedList.isEmpty()}") return if(IdentifiedList.isNotEmpty()) IdentifiedList else throw Exception() } override suspend fun getUnidentifiedList(): List<Unidentified> { val UnidentifiedList = mutableListOf<Unidentified>() Log.d(TAG,"Unidentified fetching from api") try{ val querySnapshot = unidentifiedCollection .get() .await() for (document in querySnapshot.documents){ val image = document.getString("imageLink")?:"" val time = document.getTimestamp("timeStamp")?: Timestamp.now() val unidentf = Unidentified(image,time) Log.d(TAG,"Fetched the Unidentified") UnidentifiedList.add(unidentf) } } catch( e:Exception ){ Log.d(TAG,"Failed to get the data") throw e } Log.d(TAG,"Unidentified is empyt : ${UnidentifiedList.isEmpty()}") return if(UnidentifiedList.isNotEmpty()) UnidentifiedList else throw Exception() } override suspend fun getDeliveryPeopleList(): List<deliveryPerson> { val deliverPersonList = mutableListOf<deliveryPerson>() Log.d(TAG,"Delivery fetching from api") try{ val querySnapshot = deliveryCollection .get() .await() for (document in querySnapshot.documents){ val image = document.getString("imageLink")?:"" val time = document.getTimestamp("timeStamp")?: Timestamp.now() val unidentf = deliveryPerson(image,time) Log.d(TAG,"Fetched the Delivery") deliverPersonList.add(unidentf) } } catch( e:Exception ){ Log.d(TAG,"Failed to get the data") throw e } Log.d(TAG,"Delivery is empyt : ${deliverPersonList.isEmpty()}") return if(deliverPersonList.isNotEmpty()) deliverPersonList else throw Exception() } }
{% docs col_app_id %} Application ID e.g. `angry-birds` is used to distinguish different applications that are being tracked by the same Snowplow stack, e.g. production versus dev. {% enddocs %} {% docs col_platform %} Platform e.g. `web`. {% enddocs %} {% docs col_etl_tstamp %} Timestamp event began ETL e.g. `2017-01-26 00:01:25.292`. {% enddocs %} {% docs col_collector_tstamp %} Time stamp for the event recorded by the collector e.g. `2013-11-26 00:02:05`. {% enddocs %} {% docs col_dvce_created_tstamp %} Timestamp event was recorded on the client device e.g. `2013-11-26 00:03:57.885`. {% enddocs %} {% docs col_event %} The type of event recorded e.g. `page_view`. {% enddocs %} {% docs col_event_id %} A UUID for each event e.g. `c6ef3124-b53a-4b13-a233-0088f79dcbcb`. {% enddocs %} {% docs col_txn_id %} Transaction ID set client-side, used to de-dupe records e.g. `421828`. {% enddocs %} {% docs col_name_tracker %} Tracker namespace e.g. `sp1`. {% enddocs %} {% docs col_v_tracker %} Tracker version e.g. `js-3.0.0`. {% enddocs %} {% docs col_v_collector %} Collector version e.g. `ssc-2.1.0-kinesis`. {% enddocs %} {% docs col_v_etl %} ETL version e.g. `snowplow-micro-1.1.0-common-1.4.2`. {% enddocs %} {% docs col_user_id %} Unique ID set by business e.g. `jon.doe@email.com`. {% enddocs %} {% docs col_user_ipaddress %} User IP address e.g. `92.231.54.234`. {% enddocs %} {% docs col_user_fingerprint %} A user fingerprint generated by looking at the individual browser features e.g. `2161814971`. {% enddocs %} {% docs col_domain_userid %} User ID set by Snowplow using 1st party cookie e.g. `bc2e92ec6c204a14`. {% enddocs %} {% docs col_start_tstamp %} The `collector_tstamp` when the session began. {% enddocs %} {% docs col_end_tstamp %} The `collector_tstamp` when the session ended. {% enddocs %} {% docs col_session_index %} A visit / session index e.g. `3`. {% enddocs %} {% docs col_previous_session_id %} A previous visit / session index e.g. `3`. {% enddocs %} {% docs col_first_event_id %} The event ID of the first event. {% enddocs %} {% docs col_session_first_event_id %} A first visit / session index e.g. `3`. {% enddocs %} {% docs col_session_last_event_id %} A last visit / session index e.g. `3`. {% enddocs %} {% docs col_network_userid %} User ID set by Snowplow using 3rd party cookie e.g. `ecdff4d0-9175-40ac-a8bb-325c49733607`. {% enddocs %} {% docs col_geo_country %} ISO 3166-1 code for the country the visitor is located in e.g. `GB`, `US`. {% enddocs %} {% docs col_geo_region %} ISO-3166-2 code for country region the visitor is in e.g. `I9`, `TX`. {% enddocs %} {% docs col_geo_city %} City the visitor is in e.g. `New York`, `London`. {% enddocs %} {% docs col_geo_zipcode %} Postcode the visitor is in e.g. `94109`. {% enddocs %} {% docs col_geo_latitude %} Visitor location latitude e.g. `37.443604`. {% enddocs %} {% docs col_geo_longitude %} Visitor location longitude e.g. `-122.4124`. {% enddocs %} {% docs col_geo_region_name %} Visitor region name e.g. `Florida`. {% enddocs %} {% docs col_ip_isp %} Visitor's ISP e.g. `FDN Communications`. {% enddocs %} {% docs col_ip_organization %} Organization associated with the visitor's IP address - defaults to ISP name if none is found e.g. `Bouygues Telecom`. {% enddocs %} {% docs col_ip_domain %} Second level domain name associated with the visitor's IP address e.g. `nuvox.net`. {% enddocs %} {% docs col_ip_netspeed %} Visitor's connection type e.g. `Cable/DSL`. {% enddocs %} {% docs col_page_url %} The page URL e.g. `http://www.example.com`. {% enddocs %} {% docs col_page_title %} Web page title e.g. `Snowplow Docs - Understanding the structure of Snowplow data`. {% enddocs %} {% docs col_page_referrer %} URL of the referrer e.g. `http://www.referrer.com`. {% enddocs %} {% docs col_page_urlscheme %} Scheme aka protocol e.g. `https`. {% enddocs %} {% docs col_page_urlhost %} Host aka domain e.g. `“www.snowplowanalytics.com`. {% enddocs %} {% docs col_page_urlport %} Port if specified, 80 if not. {% enddocs %} {% docs col_page_urlpath %} Path to page e.g. `/product/index.html`. {% enddocs %} {% docs col_page_urlquery %} Querystring e.g. `id=GTM-DLRG`. {% enddocs %} {% docs col_page_urlfragment %} Fragment aka anchor e.g. `4-conclusion`. {% enddocs %} {% docs col_refr_urlscheme %} Referer scheme e.g. `http`. {% enddocs %} {% docs col_refr_urlhost %} Referer host e.g. `www.bing.com`. {% enddocs %} {% docs col_refr_urlport %} Referer port e.g. `80`. {% enddocs %} {% docs col_refr_urlpath %} Referer page path e.g. `/images/search`. {% enddocs %} {% docs col_refr_urlquery %} Referer URL querystring e.g. `q=psychic+oracle+cards`. {% enddocs %} {% docs col_refr_urlfragment %} Referer URL fragment. {% enddocs %} {% docs col_refr_medium %} Type of referer e.g. `search`, `internal`. {% enddocs %} {% docs col_refr_source %} Name of referer if recognised e.g. `Bing images`. {% enddocs %} {% docs col_refr_term %} Keywords if source is a search engine e.g. `psychic oracle cards`. {% enddocs %} {% docs col_mkt_medium %} Type of traffic source e.g. `cpc`, `affiliate`, `organic`, `social`. {% enddocs %} {% docs col_mkt_source %} The company / website where the traffic came from e.g. `Google`, `Facebook`. {% enddocs %} {% docs col_mkt_term %} Any keywords associated with the referrer e.g. `new age tarot decks`. {% enddocs %} {% docs col_mkt_content %} The content of the ad. (Or an ID so that it can be looked up.) e.g. `13894723`. {% enddocs %} {% docs col_mkt_campaign %} The campaign ID e.g. `diageo-123`. {% enddocs %} {% docs col_se_category %} Category of event e.g. `ecomm`, `video`. {% enddocs %} {% docs col_se_action %} Action performed / event name e.g. `add-to-basket`, `play-video`. {% enddocs %} {% docs col_se_label %} The object of the action e.g. the ID of the video played or SKU of the product added-to-basket e.g. `pbz00123`. {% enddocs %} {% docs col_se_property %} A property associated with the object of the action e.g. `HD`, `large`. {% enddocs %} {% docs col_se_value %} A value associated with the event / action e.g. the value of goods added-to-basket e.g. `9.99`. {% enddocs %} {% docs col_tr_orderid %} Order ID e.g. `#134`. {% enddocs %} {% docs col_tr_affiliation %} Transaction affiliation (e.g. store where sale took place) e.g. `web`. {% enddocs %} {% docs col_tr_total %} Total transaction value e.g. `12.99`. {% enddocs %} {% docs col_tr_tax %} Total tax included in transaction value e.g. `3.00`. {% enddocs %} {% docs col_tr_shipping %} Delivery cost charged e.g. `0.00`. {% enddocs %} {% docs col_tr_city %} Delivery address, city e.g. `London`. {% enddocs %} {% docs col_tr_state %} Delivery address, state e.g. `Washington`. {% enddocs %} {% docs col_tr_country %} Delivery address, country e.g. `France`. {% enddocs %} {% docs col_ti_orderid %} Order ID e.g. `#134`. {% enddocs %} {% docs col_ti_sku %} Product SKU e.g. `pbz00123`. {% enddocs %} {% docs col_ti_name %} Product name e.g. `Cone pendulum`. {% enddocs %} {% docs col_ti_category %} Product category e.g. `New Age`. {% enddocs %} {% docs col_ti_price %} Product unit price e.g. `9.99`. {% enddocs %} {% docs col_ti_quantity %} Number of product in transaction e.g. `2`. {% enddocs %} {% docs col_pp_xoffset_min %} Minimum page x offset seen in the last ping period e.g. `0`. {% enddocs %} {% docs col_pp_xoffset_max %} Maximum page x offset seen in the last ping period e.g. `100`. {% enddocs %} {% docs col_pp_yoffset_min %} Minimum page y offset seen in the last ping period e.g. `0`. {% enddocs %} {% docs col_pp_yoffset_max %} Maximum page y offset seen in the last ping period e.g. `200`. {% enddocs %} {% docs col_useragent %} Raw useragent. {% enddocs %} {% docs col_br_name %} Browser name e.g. `Firefox 12`. {% enddocs %} {% docs col_br_family %} Browser family e.g. `Firefox`. {% enddocs %} {% docs col_br_version %} Browser version e.g. `12.0`. {% enddocs %} {% docs col_br_type %} Browser type e.g. `Browser`. {% enddocs %} {% docs col_br_renderengine %} Browser rendering engine e.g. `GECKO`. {% enddocs %} {% docs col_br_lang %} Language the browser is set to e.g. `en-GB`. {% enddocs %} {% docs col_br_features_pdf %} Whether the browser recognizes PDFs e.g. `True`. {% enddocs %} {% docs col_br_features_flash %} Whether Flash is installed e.g. `True`. {% enddocs %} {% docs col_br_features_java %} Whether Java is installed e.g. `True`. {% enddocs %} {% docs col_br_features_director %} Whether Adobe Shockwave is installed e.g. `True`. {% enddocs %} {% docs col_br_features_quicktime %} Whether QuickTime is installed e.g. `True`. {% enddocs %} {% docs col_br_features_realplayer %} Whether RealPlayer is installed e.g. `True`. {% enddocs %} {% docs col_br_features_windowsmedia %} Whether mplayer2 is installed e.g. `True`. {% enddocs %} {% docs col_br_features_gears %} Whether Google Gears is installed e.g. `True`. {% enddocs %} {% docs col_br_features_silverlight %} Whether Microsoft Silverlight is installed e.g. `True`. {% enddocs %} {% docs col_br_cookies %} Whether cookies are enabled e.g. `True`. {% enddocs %} {% docs col_br_colordepth %} Bit depth of the browser color palette e.g. `24`. {% enddocs %} {% docs col_br_viewwidth %} Viewport width e.g. `1000`. {% enddocs %} {% docs col_br_viewheight %} Viewport height e.g. `1000`. {% enddocs %} {% docs col_os_name %} Name of operating system e.g. `Android`. {% enddocs %} {% docs col_os_family %} Operating system family e.g. `Linux`. {% enddocs %} {% docs col_os_manufacturer %} Company responsible for OS e.g. `Apple`. {% enddocs %} {% docs col_os_timezone %} Client operating system timezone e.g. `Europe/London`. {% enddocs %} {% docs col_dvce_type %} Type of device e.g. `Computer`. {% enddocs %} {% docs col_dvce_ismobile %} Is the device mobile? e.g. `True`. {% enddocs %} {% docs col_dvce_screenwidth %} Screen width in pixels e.g. `1900`. {% enddocs %} {% docs col_dvce_screenheight %} Screen height in pixels e.g. `1024`. {% enddocs %} {% docs col_doc_charset %} The page's character encoding e.g. `UTF-8`. {% enddocs %} {% docs col_doc_width %} The page's width in pixels e.g. `1024`. {% enddocs %} {% docs col_doc_height %} The page's height in pixels e.g. `3000`. {% enddocs %} {% docs col_tr_currency %} Currency e.g. `USD`. {% enddocs %} {% docs col_tr_total_base %} Total in base currency e.g. `12.99`. {% enddocs %} {% docs col_tr_tax_base %} Total tax in base currency e.g. `3.00`. {% enddocs %} {% docs col_tr_shipping_base %} decimal Delivery cost in base currency e.g. `0.00`. {% enddocs %} {% docs col_ti_currency %} Currency e.g. `EUR`. {% enddocs %} {% docs col_ti_price_base %} decimal Price in base currency e.g. `9.99`. {% enddocs %} {% docs col_base_currency %} Reporting currency e.g. `GBP`. {% enddocs %} {% docs col_geo_timezone %} Visitor timezone name e.g. `Europe/London`. {% enddocs %} {% docs col_mkt_clickid %} The click ID e.g. `ac3d8e459`. {% enddocs %} {% docs col_mkt_network %} The ad network to which the click ID belongs e.g. `DoubleClick`. {% enddocs %} {% docs col_etl_tags %} JSON of tags for this ETL run e.g. `“['prod']”`. {% enddocs %} {% docs col_dvce_sent_tstamp %} When the event was sent by the client device e.g. `2013-11-26 00:03:58.032`. {% enddocs %} {% docs col_refr_domain_userid %} The Snowplow domain_userid of the referring website e.g. `bc2e92ec6c204a14`. {% enddocs %} {% docs col_refr_dvce_tstamp %} The time of attaching the domain_userid to the inbound link e.g. `2013-11-26 00:02:05`. {% enddocs %} {% docs col_session_id %} A visit / session UUID e.g. `c6ef3124-b53a-4b13-a233-0088f79dcbcb`. {% enddocs %} {% docs col_domain_sessionid %} A visit / session UUID e.g. `c6ef3124-b53a-4b13-a233-0088f79dcbcb`. {% enddocs %} {% docs col_domain_sessionidx %} A visit / session index e.g. `3`. {% enddocs %} {% docs col_first_session_id %} The UUID of the first session of a user e.g. `c6ef3124-b53a-4b13-a233-0088f79dcbcb`. {% enddocs %} {% docs col_last_session_id %} The UUID of the last session of a user e.g. `c6ef3124-b53a-4b13-a233-0088f79dcbcb`. {% enddocs %} {% docs col_derived_tstamp %} Timestamp making allowance for innaccurate device clock e.g. `2013-11-26 00:02:04`. {% enddocs %} {% docs col_event_vendor %} Who defined the event e.g. `com.acme`. {% enddocs %} {% docs col_event_name %} Event name e.g. `link_click`. {% enddocs %} {% docs col_event_format %} Format for event e.g. `jsonschema`. {% enddocs %} {% docs col_event_version %} Version of event schema e.g. `1-0-2`. {% enddocs %} {% docs col_event_fingerprint %} Hash client-set event fields e.g. `AADCE520E20C2899F4CED228A79A3083`. {% enddocs %} {% docs col_true_tstamp %} User-set “true timestamp” for the event e.g. `2013-11-26 00:02:04`. {% enddocs %} {% docs col_page_view_id %} A UUID for each page view e.g. `c6ef3124-b53a-4b13-a233-0088f79dcbcb`. {% enddocs %} {% docs col_category %} Category based on activity if the IP/UA is a spider or robot, BROWSER otherwise. {% enddocs %} {% docs col_primary_impact %} Whether the spider or robot would affect page impression measurement, ad impression measurement, both or none. {% enddocs %} {% docs col_reason %} Type of failed check if the IP/UA is a spider or robot, PASSED_ALL otherwise. {% enddocs %} {% docs col_spider_or_robot %} True if the IP address or user agent checked against the list is a spider or robot, false otherwise. {% enddocs %} {% docs col_device_family %} Device type. {% enddocs %} <!-- Breaking naming convention to avoid clash with same col name from atomic.events --> {% docs col_ua_os_family %} Operation system name. {% enddocs %} {% docs col_useragent_family %} Useragent family (browser) name. {% enddocs %} {% docs col_os_major %} Operation system major version. {% enddocs %} {% docs col_os_minor %} Operation system minor version. {% enddocs %} {% docs col_os_patch %} Operation system patch version. {% enddocs %} {% docs col_os_patch_minor %} Operation system patch minor version. {% enddocs %} {% docs col_os_version %} Operation system full version. {% enddocs %} {% docs col_useragent_major %} Useragent major version. {% enddocs %} {% docs col_useragent_minor %} Useragent minor version. {% enddocs %} {% docs col_useragent_patch %} Useragent patch version. {% enddocs %} {% docs col_useragent_version %} Full version of the useragent. {% enddocs %} {% docs col_device_class %} Class of device e.g. `phone`. {% enddocs %} {% docs col_agent_class %} Class of agent e.g. `browser`. {% enddocs %} {% docs col_agent_name %} Name of agent e.g. `Chrome`. {% enddocs %} {% docs col_agent_name_version %} Name and version of agent e.g. `Chrome 53.0.2785.124`. {% enddocs %} {% docs col_agent_name_version_major %} Name and major version of agent e.g. `Chrome 53`. {% enddocs %} {% docs col_agent_version %} Version of agent e.g. `53.0.2785.124`. {% enddocs %} {% docs col_agent_version_major %} Major version of agent e.g. `53`. {% enddocs %} {% docs col_device_brand %} Brand of device e.g. `Google`. {% enddocs %} {% docs col_device_name %} Name of device e.g. `Google Nexus 6`. {% enddocs %} {% docs col_device_version %} Version of device e.g. `6.0`. {% enddocs %} {% docs col_layout_engine_class %} Class of layout engine e.g. `Browser`. {% enddocs %} {% docs col_layout_engine_name %} Name of layout engine e.g. `Blink`. {% enddocs %} {% docs col_layout_engine_name_version %} Name and version of layout engine e.g. `Blink 53.0`. {% enddocs %} {% docs col_layout_engine_name_version_major %} Name and major version of layout engine e.g. `Blink 53`. {% enddocs %} {% docs col_layout_engine_version %} Version of layout engine e.g. `53.0`. {% enddocs %} {% docs col_layout_engine_version_major %} Major version of layout engine e.g. `53`. {% enddocs %} {% docs col_operating_system_class %} Class of the OS e.g. `Mobile`. {% enddocs %} {% docs col_operating_system_name %} Name of the OS e.g. `Android`. {% enddocs %} {% docs col_operating_system_name_version %} Name and version of the OS e.g. `Android 7.0`. {% enddocs %} {% docs col_operating_system_version %} Version of the OS e.g. `7.0`. {% enddocs %} {% docs col_model_tstamp %} The current timestamp when the model processed this row. {% enddocs %} {% docs col_has_install %} Yes/No whether application is installed or not. {% enddocs %} {% docs col_screen_views_in_session %} Total number of screen views within a session. {% enddocs %} {% docs col_screen_views %} Total number of screen views within a session. {% enddocs %} {% docs col_screen_view_id %} The UUID of a screen view. {% enddocs %} {% docs col_screen_view_in_session_index %} The index of the screen view within the session. This is generated by the tracker. {% enddocs %} {% docs col_screen_view_name %} Name of the screen viewed. {% enddocs %} {% docs col_screen_view_transition_type %} The type of transition that led to the screen being viewed. {% enddocs %} {% docs col_screen_view_type %} The type of screen that was viewed. {% enddocs %} {% docs col_screen_view_previous_id %} The UUID of the previous screen view. {% enddocs %} {% docs col_screen_view_previous_name %} The name of the previous screen view. {% enddocs %} {% docs col_screen_view_previous_type %} The type of the previous screen viewed. {% enddocs %} {% docs col_screen_names_viewed %} The number of different screens viewed where the unique screens are counted by the screen names. {% enddocs %} {% docs col_app_errors %} Total number of app errors. {% enddocs %} {% docs col_fatal_app_errors %} Totoal number of fatal app errors. {% enddocs %} {% docs col_first_event_name %} Name of the first event fired in the session. {% enddocs %} {% docs col_last_event_name %} Name of the last event fired in the session. {% enddocs %} {% docs col_first_screen_view_name %} Name of the first screen viewed. {% enddocs %} {% docs col_first_screen_view_transition_type %} Type of transition for the first screen view. {% enddocs %} {% docs col_first_screen_view_type %} Type of first screen view. {% enddocs %} {% docs col_last_screen_view_name %} Name of the last screen viewed. {% enddocs %} {% docs col_last_screen_view_transition_type %} Type of transition for the last screen view. {% enddocs %} {% docs col_last_screen_view_type %} Type of last screen view. {% enddocs %} {% docs col_device_manufacturer %} Manufacturer name of the device eg. `Apple`. {% enddocs %} {% docs col_device_model %} Model of the mobile device. {% enddocs %} {% docs col_os_type %} Type of OS running on the mobile device. {% enddocs %} {% docs col_android_idfa %} Identifier for Advertisers for Android devices. {% enddocs %} {% docs col_apple_idfa %} Identifier for Advertisers for Apple devices. {% enddocs %} {% docs col_apple_idfv %} Identifier for Vendors for Apple devices. {% enddocs %} {% docs col_open_idfa %} Identifier for Vendors for Open devices. {% enddocs %} {% docs col_device_latitude %} Latitude coordinates for device location. {% enddocs %} {% docs col_device_longitude %} Longitude coordinates for device location. {% enddocs %} {% docs col_device_latitude_longitude_accuracy %} Accuracy of Latitude and Longitude coordinates for device location. {% enddocs %} {% docs col_device_altitude %} Altitude coordinates for device location. {% enddocs %} {% docs col_device_altitude_accuracy %} Accuracy of device altitude coordinates. {% enddocs %} {% docs col_device_bearing %} Horizontal angle between device and true north. {% enddocs %} {% docs col_device_speed %} Mobile device speed. {% enddocs %} {% docs col_carrier %} Carrier serivce provider used within device. {% enddocs %} {% docs col_network_technology %} technology used by the network provider of the device. {% enddocs %} {% docs col_network_type %} Type of network eg. `3G`. {% enddocs %} {% docs col_build %} The build of the application. {% enddocs %} {% docs col_first_build %} First build of the application. {% enddocs %} {% docs col_last_build %} Last build of the application. {% enddocs %} {% docs col_version %} The application version. {% enddocs %} {% docs col_first_version %} First application version. {% enddocs %} {% docs col_last_version %} Last application version. {% enddocs %} {% docs col_session_duration_s %} Total duration of a session in seconds. {% enddocs %} {% docs col_device_user_id %} Unique device user id. {% enddocs %} {% docs col_sessions %} Total number of session for the user. {% enddocs %} {% docs col_session_start_tstamp %} Timestamp for the start of the session, based on `derived_tstamp`. {% enddocs %} {% docs col_session_end_tstamp %} Timestamp for the end of the session, based on `derived_tstamp`. {% enddocs %} {% docs col_user_start_tstamp %} Earliest timestamp for the user's activity, based on `derived_tstamp`. {% enddocs %} {% docs col_user_end_tstamp %} Latest timestamp for the user's activity, based on `derived_tstamp`. {% enddocs %} {% docs col_sessions_duration_s %} Total session duration for the specific user. {% enddocs %} {% docs col_active_days %} Total number of active days for the user. {% enddocs %} {% docs col_last_carrier %} Last carrier provider for user. {% enddocs %} {% docs col_first_carrier %} First carrier for user. {% enddocs %} {% docs col_first_os_version %} First Operating System version for user device. {% enddocs %} {% docs col_last_os_version %} Last Operating System version for user device. {% enddocs %} {% docs col_screen_view_controller %} The name of the view controller. {% enddocs %} {% docs col_screen_type %} The type of screen that was viewed. {% enddocs %} {% docs col_screen_top_view_controller %} The name of the root view controller. {% enddocs %} {% docs col_screen_fragment %} The name of the screen fragment (also known as an anchor). {% enddocs %} {% docs col_screen_activity %} The name of the Activity element in the screen. {% enddocs %} {% docs col_screen_name %} The name set for a specific screen, e.g. `DemoScreenName`. {% enddocs %} {% docs col_screen_id %} A UUID for each screen e.g. `738f1fbc-5298-46fa-9474-bc0a65f014ab`. {% enddocs %} {% docs col_root_id %} The corresponding UUID used in the root table. {% enddocs %} {% docs col_root_tstamp %} The timestamp for when this event was produced. {% enddocs %} {% docs col_id %} A UUID for each row in the table. {% enddocs %}
/*********************************************************************** * This file is part of iDempiere ERP Open Source * * http://www.idempiere.org * * * * Copyright (C) Contributors * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * * MA 02110-1301, USA. * * * * Contributors: * * - hengsin * **********************************************************************/ package org.idempiere.test.form; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Vector; import org.compiere.grid.CreateFromDepositBatch; import org.compiere.minigrid.MiniTableImpl; import org.compiere.model.GridTab; import org.compiere.model.GridWindow; import org.compiere.model.MDepositBatch; import org.compiere.model.MDepositBatchLine; import org.compiere.model.MPayment; import org.compiere.model.MQuery; import org.compiere.model.SystemIDs; import org.compiere.process.DocAction; import org.compiere.process.ProcessInfo; import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; import org.compiere.util.TimeUtil; import org.compiere.wf.MWorkflow; import org.idempiere.test.AbstractTestCase; import org.idempiere.test.DictionaryIDs; import org.junit.jupiter.api.Test; /** * * @author hengsin * */ public class CreateFromDepositBatchFormTest extends AbstractTestCase { public CreateFromDepositBatchFormTest() { } @Test public void testCreateFromDepositBatch() { MPayment payment = new MPayment(Env.getCtx(), 0, getTrxName()); payment.setC_DocType_ID(true); payment.setC_BPartner_ID(DictionaryIDs.C_BPartner.JOE_BLOCK.id); payment.setTenderType(MPayment.TENDERTYPE_DirectDebit); int C_BankAccount_ID = DB.getSQLValueEx(getTrxName(), "SELECT C_BankAccount_ID FROM C_BankAccount WHERE IsActive='Y' AND AD_Client_ID=? " + "AND IsDefault='Y' ORDER BY C_BankAccount_ID", getAD_Client_ID()); payment.setC_BankAccount_ID(C_BankAccount_ID); payment.setC_Currency_ID(Env.getContextAsInt(Env.getCtx(), Env.C_CURRENCY_ID)); payment.setPayAmt(new BigDecimal("10.00")); payment.saveEx(); ProcessInfo pi = MWorkflow.runDocumentActionWorkflow(payment, DocAction.ACTION_Complete); assertFalse(pi.isError(), pi.getSummary()); payment.load(getTrxName()); assertEquals(DocAction.STATUS_Completed, payment.getDocStatus(), "Unexpected document status"); Timestamp today = TimeUtil.getDay(System.currentTimeMillis()); MDepositBatch batch = new MDepositBatch(Env.getCtx(), 0, getTrxName()); batch.setC_BankAccount_ID(C_BankAccount_ID); batch.setC_DocType_ID(payment.getC_DocType_ID()); batch.setDateDeposit(today); batch.setDateAcct(today); batch.setDateDoc(today); batch.saveEx(); GridWindow gridWindow = GridWindow.get(Env.getCtx(), 1, SystemIDs.WINDOW_PAYMENTS_INTO_BATCH); assertNotNull(gridWindow, "Failed to load grid window of Payments into batch"); gridWindow.initTab(0); GridTab gridTab = gridWindow.getTab(0); MQuery query = new MQuery(MDepositBatch.Table_Name); query.addRestriction(MDepositBatch.COLUMNNAME_C_DepositBatch_ID, "=", batch.get_ID()); gridTab.setQuery(query); gridTab.getTableModel().setImportingMode(false, getTrxName()); gridTab.query(false); assertEquals(1, gridTab.getRowCount(), "Unexpected number of row retrieve from DB"); assertEquals(batch.get_ID(), gridTab.getRecord_ID(), "Wrong record id"); CreateFromDepositBatchImpl form = new CreateFromDepositBatchImpl(gridTab); form.setTrxName(getTrxName()); Timestamp dateFrom = TimeUtil.addDays(today, -1); Timestamp dateTo = TimeUtil.addDays(today, 1); form.loadPayments(C_BankAccount_ID, null, null, dateFrom, dateTo, null, null, payment.getC_DocType_ID(), null, null); assertTrue(form.minitable.getRowCount() > 0, "Failed to load data from DB"); form.minitable.setSelectedRow(-1); for (int i = 0; i < form.minitable.getRowCount(); i++) { KeyNamePair pp = (KeyNamePair) form.minitable.getValueAt(i, 2); if (pp.getKey() == payment.get_ID()) { form.minitable.setValueAt(Boolean.TRUE, i, 0); form.minitable.setSelectedRow(i); break; } } assertTrue(form.minitable.getSelectedRow() >= 0, "Failed to find payment record"); assertTrue(form.save(form.minitable, getTrxName()), "Failed to save changes"); batch.load(getTrxName()); MDepositBatchLine[] lines = batch.getLines(); assertNotNull(lines, "Null deposit batch line"); assertEquals(1, lines.length, "Unexpected number of batch lines"); assertEquals(payment.get_ID(), lines[0].getC_Payment_ID()); } private static class CreateFromDepositBatchImpl extends CreateFromDepositBatch { private MiniTableImpl minitable = null; public CreateFromDepositBatchImpl(GridTab mTab) { super(mTab); try { dynInit(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } @Override public Object getWindow() { return this; } @Override protected boolean dynInit() throws Exception { super.dynInit(); minitable = new MiniTableImpl(); for(String column : getOISColumnNames()) { minitable.addColumn(column); } configureMiniTable(minitable); return true; } public void loadPayments(Integer BankAccount, Integer BPartner, String DocumentNo, Timestamp DateFrom, Timestamp DateTo, BigDecimal AmtFrom, BigDecimal AmtTo, Integer DocType, String TenderType, String AuthCode) { Vector<Vector<Object>> datas = super.getBankAccountData(BankAccount, BPartner, DocumentNo, DateFrom, DateTo, AmtFrom, AmtTo, DocType, TenderType, AuthCode); for(int i = 0; i < datas.size(); i++) { minitable.setRowCount(i+1); Vector<Object> data = datas.get(i); for(int j = 0; j < data.size(); j++) { minitable.setValueAt(data.get(j), i, j); } } } } }
import { styled } from "@stitches/react"; import { useRouter } from "next/router"; const BackButton = () => { const { back } = useRouter(); const handleOnClick = () => back(); return ( <Button id="back" onClick={handleOnClick}> 뒤로가기 </Button> ); }; const Button = styled("button", { padding: 7.5, color: "#2c7fff", background: "#fff", border: "1px solid #ccc", borderRadius: 5, cursor: "pointer", "&:hover": { background: "#2c7fff", color: "#fff", }, transition: "background 0.5s ease, color 0.25s ease", }); export default BackButton;
/* * Copyright 2020 Solubris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.solubris.typedtuples.accumulator; import com.solubris.typedtuples.immutable.ImmutableTuple; import com.solubris.typedtuples.mutable.MutableTuple; import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; class DecupleAccumulatorImplTest { final int a = 0; final int b = 1; final int c = 2; final int d = 3; final int e = 4; final int f = 5; final int g = 6; final int h = 7; final int i = 8; final int j = 9; @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getFirst(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getFirst().apply(null, null); Assertions.assertThat(actual).isEqualTo(a); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getSecond(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getSecond().apply(null, null); Assertions.assertThat(actual).isEqualTo(b); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getThird(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getThird().apply(null, null); Assertions.assertThat(actual).isEqualTo(c); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getFourth(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getFourth().apply(null, null); Assertions.assertThat(actual).isEqualTo(d); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getFifth(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getFifth().apply(null, null); Assertions.assertThat(actual).isEqualTo(e); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getSixth(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getSixth().apply(null, null); Assertions.assertThat(actual).isEqualTo(f); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getSeventh(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getSeventh().apply(null, null); Assertions.assertThat(actual).isEqualTo(g); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getEighth(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getEighth().apply(null, null); Assertions.assertThat(actual).isEqualTo(h); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getNinth(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getNinth().apply(null, null); Assertions.assertThat(actual).isEqualTo(i); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void getTenth(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actual = underTest.getTenth().apply(null, null); Assertions.assertThat(actual).isEqualTo(value); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void accumulate(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var expected = MutableTuple.of(a, b, c, d, e, f, g, h, i, value); var acc = MutableTuple.of(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); var t = MutableTuple.of(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); underTest.accumulate(acc, t); Assertions.assertThat(acc).isEqualTo(expected); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void of(Integer value) { DecupleAccumulator<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = Accumulator.of((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var actualA = underTest.getFirst().apply(null, null); Assertions.assertThat(actualA).isEqualTo(a); var actualB = underTest.getSecond().apply(null, null); Assertions.assertThat(actualB).isEqualTo(b); var actualC = underTest.getThird().apply(null, null); Assertions.assertThat(actualC).isEqualTo(c); var actualD = underTest.getFourth().apply(null, null); Assertions.assertThat(actualD).isEqualTo(d); var actualE = underTest.getFifth().apply(null, null); Assertions.assertThat(actualE).isEqualTo(e); var actualF = underTest.getSixth().apply(null, null); Assertions.assertThat(actualF).isEqualTo(f); var actualG = underTest.getSeventh().apply(null, null); Assertions.assertThat(actualG).isEqualTo(g); var actualH = underTest.getEighth().apply(null, null); Assertions.assertThat(actualH).isEqualTo(h); var actualI = underTest.getNinth().apply(null, null); Assertions.assertThat(actualI).isEqualTo(i); var actualValue = underTest.getTenth().apply(null, null); Assertions.assertThat(actualValue).isEqualTo(value); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void mutableCombine(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var expected = MutableTuple.of(a, b, c, d, e, f, g, h, i, value); var l = MutableTuple.of(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); var r = MutableTuple.of(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); var actual = underTest.combine(l, r); Assertions.assertThat(actual).isEqualTo(expected); } @ParameterizedTest @ValueSource( ints = 1 ) @NullSource void immutableCombine(Integer value) { DecupleAccumulatorImpl<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> underTest = new DecupleAccumulatorImpl<>((l, r) -> a, (l, r) -> b, (l, r) -> c, (l, r) -> d, (l, r) -> e, (l, r) -> f, (l, r) -> g, (l, r) -> h, (l, r) -> i, (l, r) -> value); var expected = ImmutableTuple.of(a, b, c, d, e, f, g, h, i, value); var l = ImmutableTuple.of(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); var r = ImmutableTuple.of(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); var actual = underTest.combine(l, r); Assertions.assertThat(actual).isEqualTo(expected); } }
import React from 'react'; import {AnswerObject} from "../App" import {Wrapper, ButtonWrapper} from "./QuestionCard.styles" type props = { question: string; answers: string[]; callback: (e: React.MouseEvent<HTMLButtonElement>) => void; userAnswer: AnswerObject | undefined; questionNr: number; totalQuestions: number; } const QuestionCard: React.FC<props> = ({question,answers,callback,userAnswer,questionNr,totalQuestions}) => { return ( <Wrapper> <p className='number'> Question: {questionNr} / {totalQuestions} </p> <p dangerouslySetInnerHTML={{__html: question}}/> <div> {answers.map( answer => ( <ButtonWrapper key={answer} correct={userAnswer?.correctAnswer === answer} userClicked={userAnswer?.answer === answer} > <button disabled={userAnswer ? true : false} onClick={callback} value={answer}> <span dangerouslySetInnerHTML={{__html: answer}}/> </button> </ButtonWrapper> ))} </div> </Wrapper> ) } export default QuestionCard
import 'dart:convert'; import 'package:urbetrack/models/models.dart'; import 'package:http/http.dart' as http; import 'package:urbetrack/models/starship.dart'; class SwapiService { Future<CharacterResponse> getStarWarsCharactersData(nextPage) async { try { final response = await http.get(Uri.parse(nextPage)); return CharacterResponse.fromJson(json.decode(response.body)); } catch (error) { throw Exception('Oh no! We have a problem. Check it out! : $error'); } } Future<String> getPlanetName(planetUrl) async { try { final response = await http.get(Uri.parse(planetUrl)); return Planet.fromJson(json.decode(response.body)).name; } catch (error) { throw Exception('Oh no! We have a problem. Check it out! : $error'); } } Future getVehicles(List<String> vehicles) async { try { final vehiclesData = vehicles.map((vehicleUrl) async { final response = await http.get(Uri.parse(vehicleUrl)); return Vehicle.fromJson(jsonDecode(response.body)); }); final List<Vehicle> characterVehicles = await Future.wait(vehiclesData); return characterVehicles; } catch (error) { throw Exception('Oh no! We have a problem. Check it out! : $error'); } } Future getStarships(List<String> starships) async { try { final starshipsData = starships.map((starshipUrl) async { final response = await http.get(Uri.parse(starshipUrl)); return Starship.fromJson(jsonDecode(response.body)); }); final List<Starship> characterStarships = await Future.wait(starshipsData); return characterStarships; } catch (error) { throw Exception('Oh no! We have a problem. Check it out! : $error'); } } }
stopwords=%w{the a by on far of are with just but and to the my I has some in} lines=File.readlines("text.txt") lines_count=lines.size text=lines.join # Count the characters character_count = text.length character_count_nospaces = text.gsub(/\s+/, '').length # Count the words, sentences, and paragraphs word_count = text.split.length sentence_count = text.split(/\.|\?|!/).length paragraph_count = text.split(/\n\n/).length # count them, and work out the percentage of non-stop words # against all words all_words = text.scan(/\w+/) good_words = all_words.select{ |word| !stopwords.include?(word) } puts "#{good_words.length} " good_percentage = ((good_words.length.to_f / all_words.length.to_f) * 100).to_i puts "#{} " # Summarize the text by cherry picking some choice sentences sentences = text.gsub(/\s+/, ' ').strip.split(/\.|\?|!/) sentences_sorted = sentences.sort_by { |sentence| sentence.length } one_third = sentences_sorted.length / 3 ideal_sentences = sentences_sorted.slice(one_third, one_third + 1) ideal_sentences = ideal_sentences.select { |sentence| sentence =~ /is|are/ } # Give the analysis back to the user puts "#{lines_count} lines" puts "#{character_count} characters" puts "#{character_count_nospaces} characters (excluding spaces)" puts "#{word_count} words" puts "#{sentence_count} sentences" puts "#{paragraph_count} paragraphs" puts "#{sentence_count.to_f / paragraph_count.to_f} sentences per paragraph (average)" puts "#{word_count.to_f / sentence_count.to_f} words per sentence (average)" puts "#{good_percentage}% of words are non-fluff words" puts "Summary:\n\n" + ideal_sentences.join(". ")
import { useContract, useOwnedNFTs, ConnectWallet, useAddress, ThirdwebNftMedia } from "@thirdweb-dev/react"; import React, { useEffect, useState } from "react"; import Container from "../../components/Container/Container"; import { useRouter } from "next/router"; import styles from "../../styles/Buy.module.css"; import Balance from "../../components/balance"; export default function Open() { const { contract } = useContract("0xC07476cAdd6A58720fC5EFda711077757a5aadd9"); const address = useAddress(); const { data: nftsData, isLoading: nftsLoading } = useOwnedNFTs(contract, address); const router = useRouter(); const [showLoading, setShowLoading] = useState(true); const sourceComponent = router.query.source || ""; useEffect(() => { const timer = setTimeout(() => { setShowLoading(false); }, 2000); return () => clearTimeout(timer); }, []); if (showLoading) { return ( <div className="backdrop-filter backdrop-blur-lg w-screen h-screen flex justify-center items-center"> <div className="text-center px-6 py-10 bg-white rounded-xl shadow-xl"> <p className="text-xl font-bold text-gray-900 mb-4">Loading...</p> <div className="w-64 h-4 bg-gray-300 rounded-full overflow-hidden"> <div className={`${styles.loadbar} h-full bg-blue-500 animate-progress`}></div> </div> </div> </div> ); } if (!address) { return ( <div className="backdrop-filter backdrop-blur-lg w-screen h-screen flex justify-center items-center"> <div className="w-full max-w-2xl px-6 py-10 bg-white rounded-xl shadow-xl"> <p className="text-center text-xl font-bold text-gray-900 mb-8"> Please connect your wallet to see your NFTs. </p> <div className="flex justify-center"> <ConnectWallet /> </div> </div> </div> ); } return ( <Container maxWidth="lg"> <div className="mt-32 text-center text-xl"> <h1 className="mb-8 font-bold text-6xl lg:text-7xl text-ellipsis animate-pulse animate-infinite animate-ease-out animate-reverse bg-gradient-to-r from-gray-300 via-gray-500 to-pink-300 text-transparent bg-clip-text"> Rewards Zone </h1> <Balance /> {nftsData && nftsData.length > 0 ? ( <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-8 bg-opacity-50 bg-slate-900 border rounded-2xl "> {nftsData.map((nft) => ( <div key={nft.metadata.id} className="animate-fade-down shadow-lg hover:shadow-slate-400 p-2 m-8 backdrop-brightness-50 rounded-lg cursor-pointer"> <p>{nft.metadata.name}</p> <ThirdwebNftMedia metadata={nft.metadata} /> <p>{nft.metadata.description}</p> </div> ))} </div> ) : ( <div className="backdrop-filter backdrop-blur-lg p-24 bg-opacity-50 bg-slate-900 border m-8 rounded-2xl flex flex-col justify-center items-center"> <p className="text-center text-xl font-bold text-gray-900 mb-8">No NFTs available.</p> </div> )} </div> </Container> ); }
# Contributing to Control Plane :+1::tada: First off, thanks for taking the time to contribute! :tada::+1: Control Plane use the Apache 2.0 licence and accepts contributions via GitHub pull requests. The following is a set of guidelines for contributing to a Control Plane project. We generally have stricter rules as we focus on security but don't let that discourage you from creating your PR, it can be incrementally fixed to fit the rules. Also feel free to propose changes to this document in a pull request. ## Table Of Contents - [Contributing to Control Plane](#contributing-to-control-plane) - [Table Of Contents](#table-of-contents) - [How Can I Contribute?](#how-can-i-contribute) - [Reporting Bugs](#reporting-bugs) - [Before Submitting a Bug Report](#before-submitting-a-bug-report) - [How Do I Submit a (Good) Bug Report?](#how-do-i-submit-a-good-bug-report) - [Suggesting Enhancements](#suggesting-enhancements) - [Before Submitting an Enhancement Suggestion](#before-submitting-an-enhancement-suggestion) - [How Do I Submit A (Good) Enhancement Suggestion?](#how-do-i-submit-a-good-enhancement-suggestion) - [Your First Code Contribution](#your-first-code-contribution) - [Development](#development) - [Pull Requests](#pull-requests) - [Style Guides](#style-guides) - [Git Commit Messages](#git-commit-messages) --- ## How Can I Contribute? ### Reporting Bugs This section guides you through submitting a bug report. Following these guidelines helps maintainers understand your report, reproduce the behaviour, and find related reports. Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out the issue template for bugs, the information it asks for helps us resolve issues faster. > **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue > and include a link to the original issue in the body of your new one. #### Before Submitting a Bug Report - **Perform a cursory search** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one #### How Do I Submit a (Good) Bug Report? Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue on within the repository and provide the following information by filling in the issue template. Explain the problem and include additional details to help maintainers reproduce the problem: - **Use a clear and descriptive title** for the issue to identify the problem - **Describe the exact steps which reproduce the problem** in as many details as possible. - **Describe the behaviour you observed after following the steps** and point out what exactly is the problem with that behaviour - **Explain which behaviour you expected to see instead and why.** Provide more context by answering these questions: - **Did the problem start happening recently** or was this always a problem? - If the problem started happening recently, **can you reproduce the problem in an older version/release of the Training Infrastructure?** What's the most recent version in which the problem doesn't happen? - **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens ### Suggesting Enhancements This section guides you through submitting an enhancement suggestion for Training Infrastructure, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers understand your suggestion and find related suggestions. Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in the template feature request template, including the steps that you imagine you would take if the feature you're requesting existed. #### Before Submitting an Enhancement Suggestion - **Check if there's already a covering enhancement** - **Perform a cursory search** to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one #### How Do I Submit A (Good) Enhancement Suggestion? Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). Make sure to provide the following information: - **Use a clear and descriptive title** for the issue to identify the suggestion - **Provide a step-by-step description of the suggested enhancement** in as many details as possible - **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines) - **Describe the current behaviour** and **explain which behaviour you expected to see instead** and why - **Explain why this enhancement would be useful** to most Kubesec users and isn't something that can or should be implemented as a separate community project - **List some other tools where this enhancement exists.** - **Specify which version of Kubesec you're using.** You can get the exact version by running `kubesec version` in your terminal - **Specify the name and version of the OS you're using.** ### Your First Code Contribution Unsure where to begin contributing to the Training infrastructure? You can start by looking through these `Good First Issue` and `Help Wanted` issues: - [Good First Issue issues][good_first_issue] - issues which should only require a few lines of code, and a test or two - [Help wanted issues][help_wanted] - issues which should be a bit more involved than `Good First Issue` issues Both issue lists are sorted by total number of comments. While not perfect, number of comments is a reasonable proxy for impact a given change will have. #### Development - TBC ### Pull Requests The process described here has several goals: - Maintain training quality - Fix problems that are important to the training team and users - Enable a sustainable system for training maintainers to review contributions Please follow these steps to have your contribution considered by the maintainers: 1. Follow all instructions in the template 2. Follow the [style guides](#style-guides) 3. After you submit your pull request, verify that all [status checks](https://help.github.com/articles/about-status-checks/) are passing <details> <summary>What if the status checks are failing?</summary> If a status check is failing, and you believe that the failure is unrelated to your change, please leave a comment on the pull request explaining why you believe the failure is unrelated. A maintainer will re-run the status check for you. If we conclude that the failure was a false positive, then we will open an issue to track that problem with our status check suite. </details> While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional tests, or other changes before your pull request can be ultimately accepted. ## Style Guides ### Git Commit Messages - It's strongly preferred you [GPG Verify][commit_signing] your commits if you can - Follow [Conventional Commits](https://www.conventionalcommits.org) - Use the present tense ("add feature" not "added feature") - Use the imperative mood ("move cursor to..." not "moves cursor to...") - Limit the first line to 72 characters or less - Reference issues and pull requests liberally after the first line
# # This file is licensed under the Affero General Public License (AGPL) version 3. # # Copyright 2014-2016 OpenMarket Ltd # Copyright (C) 2023 New Vector, Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # See the GNU Affero General Public License for more details: # <https://www.gnu.org/licenses/agpl-3.0.html>. # # Originally licensed under the Apache License, Version 2.0: # <http://www.apache.org/licenses/LICENSE-2.0>. # # [This file includes modifications made by New Vector Limited] # # """ This module contains REST servlets to do with presence: /presence/<paths> """ import logging from typing import TYPE_CHECKING, Tuple from synapse.api.errors import AuthError, SynapseError from synapse.handlers.presence import format_user_presence_state from synapse.http.server import HttpServer from synapse.http.servlet import RestServlet, parse_json_object_from_request from synapse.http.site import SynapseRequest from synapse.rest.client._base import client_patterns from synapse.types import JsonDict, UserID if TYPE_CHECKING: from synapse.server import HomeServer logger = logging.getLogger(__name__) class PresenceStatusRestServlet(RestServlet): PATTERNS = client_patterns("/presence/(?P<user_id>[^/]*)/status", v1=True) CATEGORY = "Presence requests" def __init__(self, hs: "HomeServer"): super().__init__() self.hs = hs self.presence_handler = hs.get_presence_handler() self.clock = hs.get_clock() self.auth = hs.get_auth() async def on_GET( self, request: SynapseRequest, user_id: str ) -> Tuple[int, JsonDict]: requester = await self.auth.get_user_by_req(request) user = UserID.from_string(user_id) if not self.hs.config.server.presence_enabled: return 200, {"presence": "offline"} if requester.user != user: allowed = await self.presence_handler.is_visible( observed_user=user, observer_user=requester.user ) if not allowed: raise AuthError(403, "You are not allowed to see their presence.") state = await self.presence_handler.get_state(target_user=user) result = format_user_presence_state( state, self.clock.time_msec(), include_user_id=False ) return 200, result async def on_PUT( self, request: SynapseRequest, user_id: str ) -> Tuple[int, JsonDict]: requester = await self.auth.get_user_by_req(request) user = UserID.from_string(user_id) if requester.user != user: raise AuthError(403, "Can only set your own presence state") state = {} content = parse_json_object_from_request(request) try: state["presence"] = content.pop("presence") if "status_msg" in content: state["status_msg"] = content.pop("status_msg") if not isinstance(state["status_msg"], str): raise SynapseError(400, "status_msg must be a string.") if content: raise KeyError() except SynapseError as e: raise e except Exception: raise SynapseError(400, "Unable to parse state") if self.hs.config.server.track_presence: await self.presence_handler.set_state(user, requester.device_id, state) return 200, {} def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None: PresenceStatusRestServlet(hs).register(http_server)
#include "include/dataCollection.hpp" int main() { // Тестируем класс на параметризованный констурктор, сеттор и вывод в консоль size_t sizeOfDynamicArray1 = 3; size_t sizeOfDynamicArray2 = 2; std::string nameOfTestDataObject1 = "Object of DataCollection class"; DataCollection data(sizeOfDynamicArray1, sizeOfDynamicArray2, nameOfTestDataObject1); int dynamicArray1[] = {1, 2, 3}; int dynamicArray2[] = {4, 5}; data.setDynamicArrays(dynamicArray1, dynamicArray2); std::cout << data << std::endl; // Здесь тестируем конструктор по умолчанию auto newData = DataCollection(); // А вот здесь присваивающий опретор присвоения newData = data; // Как видим вначале выводятся данные из первого динамического массива, а затем из второго for (size_t i = 0; i < sizeOfDynamicArray1 + sizeOfDynamicArray2; i++) { std::cout << newData[i] << std::endl; } // Здесь же можно продемонстрировать существующую проверку на выход за пределы массивов // Очевидно вызовет ошибку // std::cout << newData[sizeOfDynamicArray1 + sizeOfDynamicArray2]; // Проверка работоспособности копирующего конструктора auto copiedData = DataCollection(newData); std::cout << copiedData << std::endl; // Проверка работоспособности перемещающего конструктора auto movedData = DataCollection(std::move(newData)); std::cout << movedData << std::endl; // Проверка работоспособности перемещающего оператора присвоения // Создаём новый объект класса DataCollection int sizeOfDynamicArray3 = 3; int sizeOfDynamicArray4 = 4; std::string nameOfTestDataObject2 = "Object1"; DataCollection newObject1(sizeOfDynamicArray3, sizeOfDynamicArray4, nameOfTestDataObject2); int dynamicArray3[] = {1, 2, 3}; int dynamicArray4[] = {4, 5, 6, 7}; newObject1.setDynamicArrays(dynamicArray3, dynamicArray4); // Выводим исходный объект std::cout << "Original Object:\n" << newObject1 << std::endl; // Создаём второй объект DataCollection newObject2; // Используем перемещающий оператор присвоения, чтобы переместить данные из newObject1 в newObject2 newObject2 = std::move(newObject1); // Отображаем модифицированные объекты std::cout << "Object 1 after move:\n" << newObject1 << std::endl; std::cout << "Object 2 after move assignment:\n" << newObject2 << std::endl; return 0; }
# -*- coding: utf-8 -*- """ Utilities for the internetnl tool """ import getpass import logging import ssl import sys from pathlib import Path from urllib.parse import urlparse import keyring import pandas as pd import requests try: import requests_kerberos_proxy except ImportError: requests_kerberos_proxy = None else: try: from requests_kerberos_proxy.util import get_session except ImportError as err: raise ImportError( "Module 'request_kerberos_proxy' was found but 'get_session' could not be imported" ) from requests.auth import HTTPBasicAuth from tldextract import tldextract from tqdm import tqdm _logger = logging.getLogger("internetnl-scan") class Credentials(object): """stores the user credentials in a key ring""" def __init__(self, service_name="Internet.nl"): self.service_name = service_name self.username = None self.password = None self.http_auth = None self._credentials = None self.get_credentials() def get_credentials(self): """Get the user credentials, either via cli, or via keyring""" self._credentials = keyring.get_credential(self.service_name, None) if self._credentials is None: _logger.debug("Get credentials from cli") self.username = input("Username: ") self.password = getpass.getpass() keyring.set_password( service_name=self.service_name, username=self.username, password=self.password, ) else: _logger.debug("Get credentials from keyring") self.username = self._credentials.username self.password = self._credentials.password self.http_auth = HTTPBasicAuth(self.username, self.password) def reset_credentials(self): """in case of login failure: reset the stored credentials""" keyring.delete_password(service_name=self.service_name, username=self.username) def response_to_dataframe(response): """ Convert the Internet.nl response to pandas dataframe Args: response: the returned response ot the Internet.nl API Returns: Pandas dataframe """ result = response.json() all_scans = result["requests"] all_scans = [pd.DataFrame.from_dict(scan, orient="index").T for scan in all_scans] scans_df = pd.concat(all_scans).reset_index().drop("index", axis=1) return scans_df def _flatten_dict(current_key, current_value, new_dict): """ Given the current key and value of a dict, set the value as a string or as a dict and create a new key based on the current key and dict key Args: current_key (str): the current key string current_value (str): the current key value new_dict (dict): a new dictionary with the new keys which is modified in place """ if isinstance(current_value, dict): for key, value in current_value.items(): new_key = "_".join([current_key, key]) _flatten_dict(new_key, value, new_dict) else: new_dict[current_key] = current_value # noinspection GrazieInspection def scan_result_to_dataframes(domains): """ Convert a dict internet.nl scans to a flat dictionary with on entry per result type Args: domains: dict keys are the urls, values are the nested json results Returns: dict with four tables """ tables = dict() _logger.info("Converting the results to a dataframe") for domain, properties in tqdm(domains.items()): for table_key, table_prop in properties.items(): if table_key not in tables.keys(): tables[table_key] = dict() if isinstance(table_prop, dict): new_dict = dict() for prop_key, prop_val in table_prop.items(): _flatten_dict(prop_key, prop_val, new_dict) tables[table_key][domain] = new_dict else: tables[table_key][domain] = table_prop # convert the dictionaries to a pandas data frames for table_key, table_prop in tables.items(): tables[table_key] = pd.DataFrame.from_dict(table_prop, orient="index") return tables def make_cache_file_name(directory, scan_id, scan_type): """build the cache file name""" cache_file_name = f"{scan_id}_{scan_type}.pkl" return directory / Path(cache_file_name) def query_yes_no(question, default_answer="no"): """Ask a yes/no question via raw_input() and return their answer. Parameters ---------- question : str A question to ask the user default_answer : str, optional A default answer that is given when only return is hit. Default to 'no' Returns ------- str: "yes" or "no", depending on the input of the user """ valid = {"yes": "yes", "y": "yes", "ye": "yes", "no": "no", "n": "no"} if not default_answer: prompt = " [y/n] " elif default_answer == "yes": prompt = " [Y/n] " elif default_answer == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default_answer) while 1: # sys.stdout.write(question + prompt) _logger.warning(question + prompt) choice = input().lower() if default_answer is not None and choice == "": return default_answer elif choice in list(valid.keys()): return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") def clean_list_of_urls(urls_to_scan: list): """cleans up the urls in a list""" new_url_list = list() for url in urls_to_scan: clean_url, suffix = get_clean_url(url) if clean_url is not None and clean_url not in new_url_list: new_url_list.append(clean_url) return new_url_list def remove_sub_domain(url: str) -> str: """remove www or any other subdomain from the url""" if requests_kerberos_proxy is None: session = requests.Session() else: session = get_session() tld = tldextract.extract(url, session=session) domain_and_suffix = ".".join([tld.domain, tld.suffix]) return domain_and_suffix def remove_sub_domains(urls_to_scan: list) -> list: """remove www or any other subdomain from the url""" new_url_list = list() for url in urls_to_scan: domain_and_suffix = remove_sub_domain(url) new_url_list.append(domain_and_suffix) return new_url_list def get_clean_url(url, cache_dir=None): """ Turns an url into a clean url and adds it Args: url (str): url to clean cache_dir (str): directory name in case the tld cached data needs to be read Returns: str, str: cleaned url, the suffix """ clean_url = url suffix = None if cache_dir is not None: extract = tldextract.TLDExtract(cache_dir=cache_dir) session = None else: extract = tldextract.extract if requests_kerberos_proxy is None: session = requests.Session() else: session = get_session() try: url = url.strip() except AttributeError: pass else: try: tld = extract(url, session=session) except TypeError as type_err: _logger.debug(f"{type_err}Type error occurred for {url}") except ssl.SSLEOFError as ssl_err: _logger.debug(f"{ssl_err}\nSSLEOF error occurred for {url}") except requests.exceptions.SSLError as req_err: _logger.debug(f"{req_err}\nSSLError error occurred for {url}") else: if tld.subdomain == "" and tld.domain == "" and tld.suffix == "": clean_url = None elif tld.subdomain == "" and tld.suffix == "": clean_url = None elif tld.subdomain == "" and tld.domain == "": clean_url = None elif tld.domain == "" and tld.suffix == "": clean_url = None elif tld.subdomain == "": clean_url = ".".join([tld.domain, tld.suffix]) elif tld.suffix == "": clean_url = ".".join([tld.subdomain, tld.domain]) elif tld.domain == "": clean_url = ".".join([tld.subdomain, tld.suffix]) else: clean_url = ".".join([tld.subdomain, tld.domain, tld.suffix]) if clean_url is not None: if " " in clean_url: _logger.debug( f"{clean_url} cannot be real url with space. skipping" ) clean_url = None else: # We hebben een url gevonden. Maak hem met kleine letters en sla de suffix op clean_url = clean_url.lower() suffix = tld.suffix.lower() return clean_url, suffix def validate_url(url_to_check: str) -> bool: """ Test if a string is a valid url Args: url_to_check (str): Url to check if it is a valid url Returns: bool: True if url is valid """ try: result = urlparse(url_to_check) except AttributeError: return False else: return result def get_urls_from_domain_file( domain_file: str | Path, url_column_key: str = None, sep: str = ",", column_number: int = 0, ) -> list: """ Get urls from a file name Args: domain_file (str): the file name to be read url_column_key (str, optional): The name of the column containing the url values. Defaults to None, meaning that the file does not have a header sep (str, optional): The separator of the file column_number (int, optional): The column number to read in case no header is given Returns: list: list of cleaned url's """ _logger.info(f"Reading urls from {domain_file}") if url_column_key is not None: # if a key name is given, use that column urls_df = pd.read_csv(domain_file, sep=sep) # remove the white spaces from the column names urls_df.columns = [col.strip() for col in urls_df.columns] dirty_urls = urls_df[url_column_key].to_list() else: # read the file including the header and pick the first column urls_df = pd.read_csv(domain_file, sep=sep, header=None) dirty_urls = urls_df[column_number].to_list() # remove leading white spaces and None line's urls = [] for url_to_clean in dirty_urls: try: clean_url = url_to_clean.strip() except AttributeError: # remove all empty and non-valid URL's _logger.debug(f"Skipping empty url") else: if validate_url(clean_url): urls.append(clean_url) else: _logger.debug(f"Skipping invalid url {clean_url}") return urls
<!DOCTYPE html> <html lang="en"> <head> <title>04 - Time Formatted with observed attributes</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <link rel="stylesheet" href="styles.css" /> <script> class TimeFormatted extends HTMLElement { connectedCallback() { if (!this.rendered) { this.render(); this.rendered = true; } } static get observedAttributes() { return [ 'datetime', 'year', 'month', 'day', 'hour', 'minute', 'second', 'time-zone-name', ]; } attributeChangedCallback(name, oldValue, newValue) { this.render(); } render() { let date = new Date(this.getAttribute('datetime') || Date.now()); this.innerHTML = new Intl.DateTimeFormat('default', { year: this.getAttribute('year') || undefined, month: this.getAttribute('month') || undefined, day: this.getAttribute('day') || undefined, hour: this.getAttribute('hour') || undefined, minute: this.getAttribute('minute') || undefined, second: this.getAttribute('second') || undefined, timeZoneName: this.getAttribute('time-zone-name') || undefined, }).format(date); } } // let the browser know that <my-element> is served by our new class customElements.define('time-formatted', TimeFormatted); </script> </head> <body> <nav> <a href="/">Home</a> </nav> <main> <h1>04 - time-formatted with observed attributes</h1> <p> <time-formatted id="timeElement" hour="numeric" minute="numeric" second="numeric" ></time-formatted> </p> </main> <script> setInterval(() => timeElement.setAttribute('datetime', new Date()), 1000); </script> </body> </html>
package com.mnlin.linemenuview.dagger.module; import android.view.ViewGroup; import com.mnlin.linemenuview.base.BaseFragment; import com.mnlin.linemenuview.dagger.scope.PerFragment; import com.mnlin.linemenuview.base.BaseActivity; import dagger.Module; import dagger.Provides; /** * 功能----碎片实例提供器 * <p> * Created by MNLIN on 2017/9/23. */ @PerFragment @Module public class FragmentModule { private BaseFragment baseFragment; public FragmentModule(BaseFragment baseFragment) { this.baseFragment = baseFragment; } /** * 为fragment提供上下文 */ @Provides @PerFragment BaseActivity provideBaseActivity(){ return ((BaseActivity) baseFragment.getActivity()); } /** * 为fragment设定根部局 */ @Provides @PerFragment ViewGroup provideViewGroup(){ return ((ViewGroup) baseFragment.getView()); } }
package main import ( "context" "crypto/tls" "flag" "log/slog" "os" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/manager" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" "installer.operators.ethr.gg/installer/api/v1alpha1" installeroperatorsethrggv1alpha1 "installer.operators.ethr.gg/installer/api/v1alpha1" "installer.operators.ethr.gg/installer/internal/controller" // +kubebuilder:scaffold:imports ) var ( scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") ) var VERSION string = "development" // production builds have VERSION dynamically linked. func init() { slog.SetLogLoggerLevel(slog.LevelDebug) slog.Debug("Initialization", slog.Group("variable", slog.String("name", "VERSION"), slog.String("value", VERSION))) if e := os.Setenv("VERSION", VERSION); e != nil { panic(e) } utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(v1alpha1.AddToScheme(scheme)) utilruntime.Must(v1alpha1.AddToScheme(scheme)) utilruntime.Must(installeroperatorsethrggv1alpha1.AddToScheme(scheme)) // +kubebuilder:scaffold:scheme } func main() { ctx := context.Background() var metricsAddr string var enableLeaderElection bool var probeAddr string var secureMetrics bool var enableHTTP2 bool flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") flag.BoolVar(&enableLeaderElection, "leader-elect", false, "Enable leader election for controller manager. "+ "Enabling this will ensure there is only one active controller manager.") flag.BoolVar(&secureMetrics, "metrics-secure", false, "If set the metrics endpoint is served securely") flag.BoolVar(&enableHTTP2, "enable-http2", false, "If set, HTTP/2 will be enabled for the metrics and webhook servers") opts := zap.Options{ Development: true, } opts.BindFlags(flag.CommandLine) flag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will // prevent from being vulnerable to the HTTP/2 Stream Cancellation and // Rapid Reset CVEs. For more information see: // - https://github.com/advisories/GHSA-qppj-fm5r-hxr3 // - https://github.com/advisories/GHSA-4374-p667-p6c8 disableHTTP2 := func(c *tls.Config) { setupLog.Info("disabling http/2") c.NextProtos = []string{"http/1.1"} } tlsOpts := []func(*tls.Config){} if !enableHTTP2 { tlsOpts = append(tlsOpts, disableHTTP2) } webhookServer := webhook.NewServer(webhook.Options{ TLSOpts: tlsOpts, }) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, Metrics: metricsserver.Options{ BindAddress: ":8080", SecureServing: secureMetrics, TLSOpts: tlsOpts, }, WebhookServer: webhookServer, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "3614bd78.analytics.operators.ethr.gg", LeaderElectionReleaseOnCancel: true, }) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) } if err = (&controller.HelmReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Report") os.Exit(1) } if err = (&controller.KustomizeReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Kustomize") os.Exit(1) } if err = (&controller.ManifestReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Manifest") os.Exit(1) } if err = (&controller.GitOpsReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "GitOps") os.Exit(1) } // +kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up health check") os.Exit(1) } if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up ready check") os.Exit(1) } var information = manager.RunnableFunc(func(ctx context.Context) error { slog.InfoContext(ctx, "Attempting to Establish Authenticated Session", slog.String("version", VERSION)) configuration := mgr.GetConfig() clientset, e := kubernetes.NewForConfig(configuration) if e != nil { return e } pods, e := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{}) if e != nil { return e } slog.InfoContext(ctx, "Total Pods on Cluster", slog.Int("value", len(pods.Items))) return nil }) var initialize = manager.RunnableFunc(func(ctx context.Context) error { { t := "Manifest" name := "flux" namespace := "installer-system" url := "https://github.com/fluxcd/flux2/releases/latest/download/install.yaml" object := &v1alpha1.Manifest{} if e := mgr.GetClient().Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, object); e != nil && errors.IsNotFound(e) { slog.InfoContext(ctx, "Executing Operator First-Time Setup", slog.String("version", VERSION), slog.String("type", t), slog.String("name", name), slog.String("namespace", namespace)) object.SetURL(url) object.SetName(name) object.SetType(v1alpha1.Standard) object.SetNamespace(namespace) if e := mgr.GetClient().Create(ctx, object); e != nil { slog.ErrorContext(ctx, "Unexpected Error While Attempting to Create ", slog.String("version", VERSION), slog.String("type", t), slog.String("name", name), slog.String("namespace", namespace), slog.String("error", e.Error())) return e } slog.InfoContext(ctx, "Successfully Established an Operator Setup CR", slog.String("version", VERSION), slog.String("type", t), slog.String("name", name), slog.String("namespace", namespace)) } else if e != nil { slog.ErrorContext(ctx, "Error While Attempting to Retrieve Primary Installer", slog.String("version", VERSION), slog.String("Type", t), slog.String("error", e.Error())) return e } } return nil }) _ = information // if e := mgr.Add(information); e != nil { // slog.ErrorContext(ctx, "Unable to Add Information Callable To Operator", slog.String("error", e.Error())) // // panic(e) // } if e := mgr.Add(initialize); e != nil { slog.ErrorContext(ctx, "Unable to Add Initialization Callable To Operator", slog.String("error", e.Error())) panic(e) } setupLog.Info("starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } }
/* * OpenRDK : OpenSource Robot Development Kit * Copyright (C) 2007, 2008 Daniele Calisi, Andrea Censi (<first_name>.<last_name>@dis.uniroma1.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef RDK2_GEOMETRY_DMATRIX #define RDK2_GEOMETRY_DMATRIX #include <assert.h> #include <iostream> #include <sstream> #include <stdexcept> #include <rdkcore/textutils/textutils.h> #include "utils.h" #include "point2.h" namespace RDK2 { namespace Geometry { class DNotInvertibleMatrixException: public std::exception {}; class DIncompatibleMatrixException: public std::exception {}; class DNotSquareMatrixException: public std::exception {}; /** Attenzione al costruttore: rows,columns == height,width Attenzione ai metodi di accesso: at(i,j) � l'elemento alla riga i e colonna j Se state usando DMatrix per rappresentare mappe o altre cose spaziali, vi conviene usare la classe Viewport che ha implementato per bene i metodi per passare dalle coordinate mondo alla cella delle griglia e viceversa. (non ve ne pentirete) Se volete usare x,y vi conviene accedere in questo modo: at(y, x) ovvero y->righe, x->colonne. Questa classe implementa il copy-on-write. Da utente, � tutto nascosto ai vostri occhi. Se aggiungete metodi che cambiano i dati, ricordate di chiamare willModify() prima di modificare effettivamente. */ template <class X> class DMatrix { public: /** Default constructor X() is called for every cell. */ DMatrix(int rows=1, int columns=1); ~DMatrix(); DMatrix(const DMatrix&); DMatrix& operator=(const DMatrix&); X * operator[](int i) { willModify(); return mrows[i]; } const X * operator[](int row) const { return mrows[row]; } int rows() const { return nrows; } int columns() const { return ncols; } /** Returns a copy of the sub-matrix i,j-i+m,j+n. Can go over the borders, will be padded with zero. */ DMatrix<X> aPieceOfYou(int i, int j, int m, int n, X zero=0) const; /** Returns the 2m+1 square sub-matrix around point i,j */ DMatrix<X> around(int i, int j, int m, X zero=0) const; /** Returns value at row=i,column=j of zero if out of borders */ X at(int i, int j, X zero=0) const; /** Access element at row=i=y,column=j=x; throws exception if out of borders */ // AC: il nome el (per "elemento") � brutto ma non ho // voluto toccare il metodo sopra X& el(int i, int j) throw(std::invalid_argument); const X& el(int i, int j) const throw(std::invalid_argument); /** Equivalent to el(p.y, p.x) */ X& el(const Point2<int>&p) throw(std::invalid_argument){ return el(p.y, p.x); } const X& el(const Point2<int>&p) const throw(std::invalid_argument){ return el(p.y, p.x); } /** Checks whether point is inside the matrix. */ bool isInside(int i, int j) const; /** Equivalent to isInside(p.y, p.x) */ bool isInside(const Point2<int>&p) const { return isInside(p.y, p.x); } /** Set all elements to value */ void setAll(const X& x); /** Applies an operation to all elements */ template<class Op> void applyAll(Op&op) { willModify(); for(int a=0;a<nrows*ncols;a++) op(elems[a]); } // for(Point2i c = grid.begin(); c != grid.end(); c = grid.next(c) ) { Point2<int> begin() { return Point2<int>(0,0); } Point2<int> end() { return Point2<int>(-1,-1); } Point2<int> next(const Point2<int>&prev) { if(prev.x<columns()-1) return Point2<int>(prev.x+1,prev.y); else { if(prev.y<rows()-1) return Point2<int>(0,prev.y+1); else return end(); } } /// These methods do the copy-on-write protected: /// Call this method before modifying the data. void willModify() { if ((*shares)>1) detach(); } void detach(); public: /// /// For matrixes holding numbers /// /** Correlation (sum of product of corresponding elements). Note that return value is passed as a reference beacause of compiler's problems with templates. */ template <class Y, class Z> void product(const DMatrix<Y>&, Z&z) const; /** Multiplies all elements by a value. */ void multAll(const X& x); DMatrix transpose() const; const X det() const; DMatrix inv() const; //bool isPositiveDefinite() const; /// Returns the identity matrix. static DMatrix I(int n); DMatrix operator*(const DMatrix&) const; DMatrix operator+(const DMatrix&) const; DMatrix operator-(const DMatrix&) const; DMatrix operator*(const X&) const; bool operator==(const DMatrix&) const; protected: int nrows,ncols; X * elems; X ** mrows; int * shares; public: // Workaround for friend templates classes (DMatrix<X>!=DMatrix<Y>) X* getElems() { willModify(); return elems; } const X* getElems() const { return elems; } public: /** Output as space separated row1 .. rowN **/ std::string outputSpaceSeparated() const; }; typedef DMatrix<double> DMatrixD; }} // end namespaces (we need to #include!) #include "dmatrix_imp.hpp" #include "dmatrix_numeric.hpp" namespace RDK2 { namespace Geometry { template <class X> std::ostream& operator<<(std::ostream& os, const DMatrix<X> &m); /** Rotation matrix 2x2*/ template <class X> DMatrix<X> MRot(X theta); bool parseMatrix( const std::vector<std::string>& sv, int start_index, int rows, int columns, DMatrix<double> &d, std::string*error=NULL); }} // end namespaces #endif
import React, { useEffect, useState } from 'react' import { Button, Table, Popover, Modal, Tag ,Switch} from 'antd'; import axios from 'axios'; import { DeleteOutlined, EditOutlined, ExclamationCircleFilled } from '@ant-design/icons'; const { confirm } = Modal; export default function RightList() { const [dataSource, setDataSource] = useState([]); // 表的配置 const columns = [ { title: "ID", dataIndex: 'id', }, { title: "权限名称", dataIndex: 'title', }, { title: "权限路径", dataIndex: 'key', render: (text) => <Tag color={"gold"}>{text}</Tag>, }, { title: "操作", render: (item) => <div> {/* 冒泡提示框 */} <Popover content={ <div style={{ textAlign: "center" }}> {/* 开关 ,开关可以通过 checked 属性值控制!!!*/} <Switch checked={item.pagepermisson} onChange={()=>handleSwitch(item)} /> </div>} title="页面配置项" // 配置触发的事件,如果是""就说明永远不会触发,即点击也没用了 trigger={(item.pagepermisson == 1 || item.pagepermisson === 0) ? "click" : "" }> {/* 按钮的内容也可以是icon图标哦 , 给按钮加上 disabled 属性可以使按钮禁用哦!!! */} <Button shape="circle" icon={<EditOutlined />} disabled={!(item.pagepermisson == 1 || item.pagepermisson === 0)} /> </Popover> &nbsp; {/* 点击的话会弹出确认框哦 */} <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => handleConfirm(item)} /> </div> } ]; // 开关的事件处理 const handleSwitch = (item) => { item.pagepermisson = item.pagepermisson === 0 ? 1 : 0; setDataSource([...dataSource]); if (item.grade === 1) axios.patch(`http://localhost:8000/rights/${item.id}`, { pagepermisson: item.pagepermisson }) else axios.patch(`http://localhost:8000/children/${item.id}`, { pagepermisson: item.pagepermisson }) console.log(item.pagepermisson); } // 删除的事件处理 const handleDelete = (item) => { if (item.grade === 1) { setDataSource(dataSource.filter((i) => i.id !== item.id)) axios.delete(`http://localhost:8000/rights/${item.id}`) } else { dataSource.map((i) => { if (i.id === item.rightId) { i.children = i.children.filter((a)=> a.id !== item.id) } }) setDataSource([...dataSource]); axios.delete(`http://localhost:8000/children/${item.id}`) } } // 弹出确认框的事件 const handleConfirm = (item) => { confirm({ title: '您确定要删除么?', icon: <ExclamationCircleFilled />, content: '确定删除点击OK,取消点击Cancel', onOk() { handleDelete(item); }, onCancel() { }, }); } useEffect(() => { axios.get('http://localhost:8000/rights?_embed=children').then((res) => { setDataSource(res.data); }) },[]) return ( <Table columns={columns} dataSource={dataSource} pagination={{ pageSize: 5 }} /> ) }
import React from "react"; import { ArrowsExpand, CloudArrowDown, Collection, JournalArrowDown, PatchCheck, Percent, Person, ShieldCheck, Tree, } from "react-bootstrap-icons"; import bg from "../../images/about-bg.png"; const About = () => { const styles = { topDiv: "bg-gradient-to-r from-red-500 to-pink-500 py-12 flex flex-col justify-center items-center text-white", topHead: "border-b-2 text-3xl font-bold mb-2 pb-2", topGridMain: "bg-gray-100", topGridWrapper: "grid grid-cols-12 gap-6 mx-5 md:mx-14 lg:mx-36 py-8", topGridItem: "col-span-12 md:col-span-4 p-10 flex flex-col justify-center items-center text-center rounded-2xl bg-gray-200 border-slate-300 cursor-pointer border-2 hover:-translate-y-4 transition-transform", topIconDiv: "w-10 h-10 flex items-center justify-center text-white rounded-full text-2xl", topGridHead: "font-bold my-3", topGridShort: "leading-7", whyMain: "p-10 md:px-12 lg:px-24 relative overflow-hidden", whyBg: "absolute top-0 left-0 opacity-80 w-full", whyHead: "text-4xl font-medium relative -top-5 text-center text-white", whyGrid: "grid grid-cols-12 mt-5 gap-6", whyGridItem: "h-48 cursor-pointer hover:scale-105 transition relative col-span-12 md:col-span-6 lg:col-span-4 bg-white text-black p-5 shadow-2xl rounded-b-2xl rounded-tl-2xl hover:bg-gradient-to-b from-red-500 to-pink-500 hover:text-white", whyIcon: "absolute top-0 right-0 w-10 h-10 text-2xl flex items-center justify-center bg-pink-500 text-white rounded-bl-2xl", whyItemHead: "text-2xl font-medium mb-2", }; /* //Styles topDiv : the whole page topHead : the Heading of the page topGridMain : the section after Heading. Contains 3 cards topGridWrapper : wrapper div for all the cards inside topGrid topGridItem: the card inside grid wrapper topIconDiv : the icon inside grid card */ return ( <div> <div className={styles.topDiv}> <h1 className={styles.topHead}>About Us</h1> <p className='text-center'>We are a start-up aimed at providing premium education at affordable prices</p> </div> <div className={styles.topGridMain}> <div className={styles.topGridWrapper}> {/*Clean Design Card*/} <div className={styles.topGridItem}> <div className="p-2 rounded-full bg-red-200"> <div className="p-2 rounded-full bg-red-300"> <div className="p-2 rounded-full bg-red-400"> <div className={`${styles.topIconDiv} bg-red-500`}> <Person /> </div> </div> </div> </div> <h2 className={`${styles.topGridHead} text-red-700`}> 1-to-1 MENTORSHIP </h2> <p className={styles.topGridShort}> You get mentored by our Expert faculty on any courses you enroll </p> </div> {/*Secure Data Card*/} <div className={styles.topGridItem}> <div className="p-2 rounded-full bg-blue-200"> <div className="p-2 rounded-full bg-blue-300"> <div className="p-2 rounded-full bg-blue-400"> <div className={`${styles.topIconDiv} bg-blue-500`}> <CloudArrowDown /> </div> </div> </div> </div> <h2 className={`${styles.topGridHead} text-blue-700`}> OFFLINE VIEWING </h2> <p className={styles.topGridShort}> Learn on the go even without connecting to the internet by saving the lectures offline. </p> </div> {/*Retina Ready Card*/} <div className={styles.topGridItem}> <div className="p-2 rounded-full bg-green-200"> <div className="p-2 rounded-full bg-green-300"> <div className="p-2 rounded-full bg-green-400"> <div className={`${styles.topIconDiv} bg-green-500`}> <ShieldCheck /> </div> </div> </div> </div> <h2 className={`${styles.topGridHead} text-green-700`}> SECURE DATA </h2> <p className={styles.topGridShort}> You data is encrypted and secured so much that even we can't access it! </p> </div> </div> </div> <div className={styles.whyMain}> <img className={styles.whyBg} src={bg} alt="" /> <h1 className={styles.whyHead}>Why Choose Us</h1> <div className={styles.whyGrid}> <div className={styles.whyGridItem}> <div className={styles.whyIcon}> <Tree /> </div> <h4 className={styles.whyItemHead}>Trending Courses</h4> <p> Our courses are always updated according to the latest technologies </p> </div> <div className={styles.whyGridItem}> <div className={styles.whyIcon}> <JournalArrowDown /> </div> <h4 className={styles.whyItemHead}>e-Books Library</h4> <p> Get access to exclusive e-books from our expert faculty to boost your learning. </p> </div> <div className={styles.whyGridItem}> <div className={styles.whyIcon}> <PatchCheck /> </div> <h4 className={styles.whyItemHead}>Certified Teachers</h4> <p> All our instructors are from Premier Institues and Fortune 500 companies. So you can be rest assured of getting the best of education. </p> </div> <div className={styles.whyGridItem}> <div className={styles.whyIcon}> <Percent /> </div> <h4 className={styles.whyItemHead}>Instant Support</h4> <p> You get access to priority support on any issue you face. </p> </div> <div className={styles.whyGridItem}> <div className={styles.whyIcon}> <ArrowsExpand /> </div> <h4 className={styles.whyItemHead}>Industry Level Projects</h4> <p> Nuild industry grade projects to showcase your skills to potential recruiters </p> </div> <div className={styles.whyGridItem}> <div className={styles.whyIcon}> <Collection /> </div> <h4 className={styles.whyItemHead}>Placement Assistance</h4> <p> We prepare you for your interviews with our industry standard syllabus and courses. </p> </div> </div> </div> </div> ); }; export default About;
<form [formGroup]="loginForm" (ngSubmit)="handleLogin()" class="rounded shadow w-75 mx-auto bg-main-light p-3 mt-4"> <div class="form-item mt-1"> <label for="email">Email</label> <input type="email" id="email" placeholder="abdalrhamanmahfouz@gmail.com" formControlName="email" class="form-control"> <div class="alert alert-danger p-1 " *ngIf="loginForm.get('email')?.errors && loginForm.get('email')?.touched "> <p class="m-0" *ngIf="loginForm.get('email')?.getError('required')">Email is required. </p> <p class="m-0" *ngIf="loginForm.get('email')?.getError('email')"> Invalid email.</p> </div> </div> <div class="form-item mt-1 mb-2"> <label for="password">Password</label> <input [type]="changetype?'password':'text'" placeholder="Pa$$w0rd!!!" id="password" formControlName="password" class="form-control"> <span class="eyeicon position-absolute eyeicon" (click)="viewpass()"><i [ngClass]="visible?'fa fa-eye':'fa fa-eye-slash'"></i> </span> <div class="alert alert-danger p-1 " *ngIf="loginForm.get('password')?.errors && loginForm.get('password')?.touched "> <p class="m-0" *ngIf="loginForm.get('password')?.getError('required')">Password is required. </p> <p class="m-0" *ngIf="loginForm.get('password')?.getError('pattern')"> Password should contains at least one uppercase letter, one lowercase letter, one digit, and one non-alphanumeric character.</p> </div> </div> <div class="d-flex spcial-reset"> <button *ngIf="!isLoding" [disabled]="loginForm.invalid" type="submit" class="main-btn">Login </button> <span class="main-btn " *ngIf="isLoding"><i class="fas fa-spin fa-spinner"></i></span> <a class="my-1 text-decoration-none ms-4 main-color fw-bold" routerLink="/Register">Don't have an account ? </a> <a class="my-1 text-decoration-none ms-4 main-color fw-bold" routerLink="/Password-reset">Or Forgot Password ?</a> </div> </form>
package com.azx.gateway.config; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; @Component public class RouteFilter extends ZuulFilter { @Autowired TokenStore tokenStore; @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); if (ctx.getRequest().getHeader("Authorization") != null && ctx.getRequest().getRequestURL().indexOf("oauth/token") == -1) { String header = ctx.getRequest().getHeader("Authorization"); String token = header.substring(7, header.length()); OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token); Map<String, Object> tokenAddInfo = existingAccessToken.getAdditionalInformation(); ctx.addZuulRequestHeader("userName", tokenAddInfo.get("userName").toString()); } return null; } }
// apiService.js import axios from 'axios'; const BASE_URL = process.env.REACT_APP_BASE_URL; export const getAllBlogs = async () => { try { const response = await axios.get(`${BASE_URL}/api/blogs`); return response.data; } catch (error) { console.error('Error fetching blogs:', error); throw error; } }; export const getBlogById = async (id) => { try { const response = await axios.get(`${BASE_URL}/api/blogs/${id}`); return response.data; } catch (error) { console.error('Error fetching blog by ID:', error); throw error; } }; export const addBlog = async (blogData) => { try { const response = await axios.post(`${BASE_URL}/api/blogs`, blogData, { headers: { 'Content-Type': 'application/json', }, }); return response.data; } catch (error) { console.error('Error adding blog:', error); throw error; } }; export const addLike = async (blogId, userId) => { try { const postId = blogId; const response = await axios.post(`${BASE_URL}/api/likes`, { postId, userId }); console.log(response.data) return response.data; } catch (error) { console.error('Error adding like:', error); throw error; } }; export const addComment = async (commentData) => { try { const response = await axios.post(`${BASE_URL}/api/comments`, commentData, { headers: { 'Content-Type': 'application/json', }, }); return response.data; } catch (error) { console.error('Error adding comment:', error); throw error; } }; export const getCommentsByBlogId = async (blogId) => { try { const response = await axios.get(`${BASE_URL}/api/comments/${blogId}`); return response.data; } catch (error) { console.error('Error fetching comments:', error); throw error; } }; export const updateProfile = async (userData) => { try { let response; if (userData instanceof FormData) { response = await axios.put(`${BASE_URL}/api/profiles/update`, userData, { headers: { 'Content-Type': 'multipart/form-data' } }); } else { response = await axios.put(`${BASE_URL}/api/profiles/update`, userData); } return response.data; } catch (error) { throw error; } }; // Upload profile picture export const uploadProfilePic = async (formData) => { try { const response = await axios.post(`${BASE_URL}/api/profiles/upload-profile-pic`, formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); return response.data; } catch (error) { throw error; } }; export const getCurrentUserProfile = async (userId) => { try { const response = await axios.get(`${BASE_URL}/api/profiles/current-profile`, { params: { userId } }); return response.data; } catch (error) { console.error('Error fetching current user profile:', error); throw error; } }; export const checkUsernameAvailability = async (username) => { try { const response = await axios.get(`${BASE_URL}/api/profiles/check-username`,{username:username}); return response.data.available; // Assuming the response contains a boolean field 'available' } catch (error) { console.error('Error checking username availability:', error); return false; // Return false by default if an error occurs } }; export const getUserProfileByUsername = async (username) => { try { const response = await axios.get(`${BASE_URL}/api/profiles/username/${username}`); return response.data; } catch (error) { console.error('Error fetching user profile:', error); throw error; } };
#include "lists.h" /** * add_dnodeint_end -add a node at the start of list * @head: header of list * @n: number of node * Return: address of new node */ dlistint_t *add_dnodeint_end(dlistint_t **head, const int n) { dlistint_t *new, *headcopy; headcopy = *head; if (head == NULL) return (NULL); new = malloc(sizeof(dlistint_t)); if (new == NULL) return (NULL); new->n = n; if (*head == NULL) { new->next = NULL; new->prev = NULL; *head = new; } else { while (headcopy->next != NULL) headcopy = headcopy->next; new->next = NULL; new->prev = headcopy; headcopy->next = new; } return (new); }
# Chapter 7: Indexing Vectors with [] # Boat sale: creating the data vectors boat.names <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") boat.colors <- c("black", "green", "pink", "blue", "blue", "green", "green", "yellow", "black", "black") boat.ages <- c(143, 53, 356, 23, 647, 24, 532, 43, 66, 86) boat.prices <- c(53, 87, 54, 66, 264, 32, 532, 58, 99, 132) boat.costs <- c(52, 80, 20, 100, 189, 12, 520, 68, 80, 100) # What is the price of the first boat? boat.prices[1] #what were the ages of the first 5 boats boat.ages[1:5] # what were the names of the black boats? boat.names[boat.colors == "black"] # what were the prices of the grean or yellow boats? boat.prices[boat.colors == "green" | boat.colors == "yellow"] #change the price of boat "s" to 100 boat.prices[boat.names == "s"] <- 100 #what was the median price of black boats less than 100 years old? median(boat.prices[boat.colors == "black" & boat.ages < 100]) # How many pink boats were there? sum(boat.colors == "pink") # what percent of boats were older than 100 years old? mean(boat.ages < 100) ## 7.1 Numerical Indexing # what is the first boat name? boat.names[1] # What are the first 5 boat colors? boat.colors[1:5] # what is every second boat age? boat.ages[seq(1,5, by = 2)] # What is the first boat age (3 times) boat.ages[c(1, 1, 1)] #make code clearer my.index <- 3:5 boat.names[my.index] ## 7.2 Logical Indexing #logical vectors only contain T and F values a <- c(1, 2, 3, 4, 5) a[c(TRUE, FALSE, TRUE, FALSE, TRUE)] # Which ages are > 100? boat.ages > 100 # Which ages are equal to 23? boat.ages == 23 # Which boat names are equal to c? boat.names == "c" # Can also compare vectors # Which boats had a higher price than cost? boat.prices > boat.costs # Which boats had a lower price than cost? boat.prices < boat.costs ## Can use it to index any vector with the same length # What were the prices of boats older than 100? boat.prices[boat.ages > 100] ##How it works step-by-step # Which boats are older than 100 years? boat.ages > 100 # Writing the logical index by hand (you'd never do this!) # Show me all of the boat prices where the logical vector is TRUE: boat.prices[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE)] # Doing it all in one step! You get the same answer: boat.prices[boat.ages > 100] #7.2.1 & (and), | (or), %in% ## | will be true if any of the logical vectors are true and & will be true # only if all the values in the logical vector is true # Which boats had prices greater than 200 OR less than 100? boat.prices > 200 | boat.prices < 100 # What were the NAMES of these boats boat.names[boat.prices > 200 | boat.prices < 100] # Boat names of boats with a color of black OR with a price > 100 boat.names[boat.colors == "black" | boat.prices > 100] # Names of blue boats with a price greater than 200 boat.names[boat.colors == "blue" & boat.prices > 200] # Which boats were black or brown, AND had a price less than 100? (boat.colors == "black" | boat.colors == "brown") & boat.prices < 100 # What were the names of these boats? boat.names[(boat.colors == "black" | boat.colors == "brown") & boat.prices < 100] # %in% helps to creat multiple OR arguments x <- c("a", "t", "a", "b", "z") # values of wither a, b, c, or d x == "a" | x == "b" | x == "c" | x == "d" # can get the same answer by doing this x %in% c("a", "b", "c", "d") ##7.2.2 Counts and percentages from logical vectors x <- c(1, 2, 3, -5, -5, -5, -5, -5) x > 0 sum(x > 0) mean(x >0) #How many of X are Y” or “What percent of X are Y”, you use sum() or mean() function with a logical vector as an argument. ##7.2.3 Additional Logical Functions #can use them to figure out which values satisfy a criteria # A vector of sex information sex <- c("m", "m", "f", "m", "f", "f") # Which values of sex are m? which(sex == "m") # Which values of sex are f? which(sex == "f") ## 7.3 Changing Values of a Vector #create a vector with 10 1s a <- rep(1, 10) #change the first 5 values to 9s a[1:5] <- 9 a # change the last 5 values to 0s a[6:10] <- 0 a # x is a vector of numbers that should be from 1 to 10 x <- c(5, -5, 7, 4, 11, 5, -2) # Assign values less than 1 to 1 x[x < 1] <- 1 # Assign values greater than 10 to 10 x[x > 10] <- 10 # Print the result! x #Note: when you assign new values to a vector, you should always reassign # a vector of the same length as the number of values you are updating #Example: a <- rep(1, 10) # To update should assign a new vector of 5 9s a[1:5] <- c(9, 9, 9, 9, 9) a #7.3.1 happy <- c(1, 4, 2, 999, 2, 3, -2, 3, 2, 999) # Which values of happy are NOT in the set 1:5? invalid <- (happy %in% 1:5) == FALSE invalid # Convert any invalid values in happy to NA happy[invalid] <- NA happy # Convert all values of happy that are NOT integers from 1 to 5 to NA happy[(happy %in% 1:5) == FALSE] <- NA # Include na.rm = TRUE to ignore NA values mean(happy, na.rm = TRUE) #7.4 Test your might! # 0 Create new data vectors for each column movie <- c("Whatever Works", "It Follows", "Love and Mercy", "The Goonies", "Jiro Dreams of Sushi", "There Will be Blood", "Moon", "Spice World", "Serenity", "Finding Vivian Maier") year <- c(2009, 2015, 2015, 1985, 2012, 2007, 2009,1988, 2005, 2014) boxoffice <- c(35.0, 15.0, 15.0, 62.0, 3.0, 10.0, 321.0, 79.0, 39.0, 1.5) genre <- c("Comedy", "Horror", "Drama", "Adventure", "Documentary", "Drama", "Science Fiction", "Comedy", "Science Fiction", "Documentary") time <- c(92, 97, 120, 90, 81, 158, 97, -84, 119, 84) rating <- c("PG-13", "R", "R", "PG", "G", "R", "R", "PG-13", "PG-13", "Unrated") # 1. What is the name of the 10th movie in the list movie[10] # 2. Genres of the firsdt 4 movies genre[1:4] # 3. Correct spice world movie movie[movie == "Spice World"] <- "The Naked Gun" # 4. Names of movies made before 1990 movie[year < 1990] # 5. How many movies were dramas? Percent Comedies? sum(genre == "Drama") mean(genre == "Comedy") # 6. One time vector is invalid. Convert invalid to NA. Then calc movie time time [time < 0] <- NA mean(time, na.rm = TRUE) # 7. Names of the comedy movies? boxoffice totals? movie[genre == "Comedy"] boxoffice[genre == "Comedy"] #8. What were the names of the movies that made less than $50 mill and were comedies movie[boxoffice < 50 & genre == "Comedy"] #9. What is the mediam boxoffice revenue of G or PG rated movies? median(boxoffice[rating%in% c("G", "PG")]) #10. What percent of movies were either R or comedies mean(rating == "R" | genre == "Comedy")
import React from "react"; import user from "./user.json"; import statisticalData from "./statistical-data.json"; import friends from "./friends.json"; import transactions from "./transactions.json"; import Profile from "./components/Profile"; import Statistics from "./components/Statistics"; import FriendList from "./components/FriendList"; import TransactionHistory from "./components/TransactionHistory"; const App = () => ( <div> <Profile name={user.name} tag={user.tag} location={user.location} avatar={user.avatar} stats={user.stats} /> <Statistics title="Upload stats" stats={statisticalData} /> <FriendList friends={friends} /> <TransactionHistory items={transactions} /> </div> ); export default App;
package board.inventoryservice; import board.inventoryservice.Repositories.ProductRepository; import board.inventoryservice.entities.Product; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import java.util.List; @SpringBootApplication @EnableDiscoveryClient public class InventoryServiceApplication { public static void main(String[] args) { SpringApplication.run(InventoryServiceApplication.class, args); } @Bean CommandLineRunner start(ProductRepository productRepository) { return args -> { productRepository.saveAll(List.of( Product.builder().name("pc").price(5555).quantity(777777).build(), Product.builder().name("phone").price(5555).quantity(777777).build(), Product.builder().name("disk").price(5555).quantity(777777).build() )); productRepository.findAll().forEach(System.out::println); }; } }
<?php /** * @package AkeebaReleaseSystem * @copyright Copyright (c)2010-2011 Nicholas K. Dionysopoulos * @license GNU General Public License version 3, or later * @version $Id$ */ defined('_JEXEC') or die('Restricted Access'); jimport('joomla.application.component.view'); class ArsViewBase extends JView { function display($tpl = null) { $model = $this->getModel(); $task = $model->getState('task','cmd'); // Include the Chameleon helper require_once dirname(__FILE__).DS.'..'.DS.'helpers'.DS.'chameleon.php'; // Call the relevant method $method_name = 'on'.ucfirst($task); if(method_exists($this, $method_name)) { $this->$method_name(); } else { $this->onDisplay(); } // Add the CSS/JS definitions $doc = JFactory::getDocument(); if($doc->getType() == 'html') { require_once JPATH_COMPONENT.DS.'helpers'.DS.'includes.php'; ArsHelperIncludes::includeMedia(); } // Pass the data $this->assignRef( 'items', $model->itemList ); $this->assignRef( 'item', $model->item ); $this->assignRef( 'lists', $model->lists ); $this->assignRef( 'pagination', $model->pagination ); // Pass the parameters $app = JFactory::getApplication(); $params =& $app->getPageParameters('com_ars'); $this->assignRef( 'params', $params ); parent::display($tpl); } function getSubLayout($layout, $altview = null) { $file = $layout; $file = preg_replace('/[^A-Z0-9_\.-]/i', '', $file); if(is_null($altview)) { $altview = $this->getName(); } $path = $this->_basePath. '/views/' . strtolower($altview) . '/tmpl'; $template = JFactory::getApplication()->getTemplate(); $altpath = JPATH_ROOT.'/templates/'.$template.'/html/com_ars/'.strtolower($altview); jimport('joomla.filesystem.path'); $filetofind = $this->_createFileName('template', array('name' => $file)); $subtemplate = JPath::find($altpath, $filetofind); if($subtemplate == false) { $subtemplate = JPath::find($path, $filetofind); } if($subtemplate == false) { $filetofind = $this->_createFileName('', array('name' => 'default')); $subtemplate = JPath::find($altpath, $filetofind); } if($subtemplate == false) { $subtemplate = JPath::find($path, $filetofind); } return $subtemplate; } }
import { constType, nonNegativeIntegerType, RecordClass, recordClassType, recordType, RecordType, } from "paratype"; import { FlowOperation } from "./FlowOperation"; import { FlowOperationRegistry } from "../internal/class-registry"; import { TableOperation } from "./TableOperation"; import { FlowTable } from "../nodes/FlowTable"; import { CellRange } from "../selection/CellRange"; import { InsertTableColumn } from "./InsertTableColumn"; import { removalAfterInsertion, removalAfterRemoval } from "../internal/transform-helpers"; const Props = { position: nonNegativeIntegerType, column: nonNegativeIntegerType, count: nonNegativeIntegerType, }; const Data = { remove: constType("table_column"), table: Props.position, column: Props.column, count: Props.count, }; const PropsType: RecordType<RemoveTableColumnProps> = recordType(Props); const DataType: RecordType<RemoveTableColumnData> = recordType(Data).withOptional("count"); const propsToData = ({position, column, count }: RemoveTableColumnProps): RemoveTableColumnData => { const data: RemoveTableColumnData = { remove: "table_column", table: position, column, }; if (count !== 1) { data.count = count; } return data; }; /** * The base record class for {@link RemoveTableColumn} * @public */ export const RemoveTableColumnBase = RecordClass(PropsType, TableOperation, DataType, propsToData); /** * Properties of {@link RemoveTableColumn} * @public */ export interface RemoveTableColumnProps { /** The affected flow position */ position: number; /** The column index */ column: number; /** The number of columns to insert */ count: number; } /** * Data of {@link RemoveTableColumn} * @public */ export interface RemoveTableColumnData { /** Data discriminator */ remove: "table_column"; /** {@inheritdoc RemoveTableColumnProps.position} */ table: number; /** {@inheritdoc RemoveTableColumnProps.column} */ column: number; /** {@inheritdoc RemoveTableColumnProps.count} */ count?: number; } /** * Represents an operation that removes a table column * @public * @sealed */ @FlowOperationRegistry.register export class RemoveTableColumn extends RemoveTableColumnBase implements RemoveTableColumnProps { /** The run-time type that represents this class */ public static readonly classType = recordClassType(() => RemoveTableColumn); /** Gets an instance of the current class from the specified data */ public static fromData(input: RemoveTableColumnData): RemoveTableColumn { const { table: position, column, count = 1} = input; const props: RemoveTableColumnProps = { position, column, count }; return new RemoveTableColumn(props); } /** {@inheritdoc TableOperation.invertForTable} */ protected invertForTable(): FlowOperation | null { const { position, column, count } = this; return new InsertTableColumn({ position, column, count }); } /** {@inheritdoc TableOperation.mergeNextInSameTable} */ protected mergeNextInSameTable(): FlowOperation | null { return null; } /** {@inheritdoc TableOperation.transformInSameTable} */ protected transformInSameTable(other: TableOperation): FlowOperation | null { return other.afterRemoveColumn(this.column, this.count); } /** {@inheritdoc TableOperation.applyToTable} */ protected applyToTable(table: FlowTable): FlowTable { return table.removeColumn(this.column, this.count); } /** {@inheritdoc TableOperation.applyToCellRange} */ protected applyToCellRange(range: CellRange): CellRange | null { return range.afterRemoveColumn(this.column, this.count); } afterInsertColumn(index: number, count: number): TableOperation | null { return removalAfterInsertion(this, "column", index, count); } afterRemoveColumn(index: number, count: number): TableOperation | null { return removalAfterRemoval(this, "column", index, count); } afterInsertRow(): TableOperation | null{ // This operation applies to all rows, so it's unaffected return this; } afterRemoveRow(): TableOperation | null{ // This operation applies to all rows, so it's unaffected return this; } }
/** * Copyright 2021 Rochester Institute of Technology (RIT). Developed with * government support under contract 70RCSA22C00000008 awarded by the United * States Department of Homeland Security for Cybersecurity and Infrastructure Security Agency. * * 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. */ /** * Copyright 2023 Rochester Institute of Technology (RIT). Developed with * government support under contract 70RCSA22C00000008 awarded by the United * States Department of Homeland Security for Cybersecurity and Infrastructure Security Agency.for Cybersecurity and Infrastructure Security Agency. * * 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. */ package edu.rit.se.nvip.crawler.htmlparser; import edu.rit.se.nvip.db.model.RawVulnerability; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; public class CoreParser extends AbstractCveParser { public static final String DOMAIN_NAME = "coresecurity"; public CoreParser() { sourceDomainName = DOMAIN_NAME; } /** * Parse advisories listed to coresecurity.com/core-labs/advisories * Ex: <a href="https://www.coresecurity.com/core-labs/advisories/pydio-cells-204-multiple-vulnerabilities">...</a> * @param domainName - core domain name */ public CoreParser(String domainName) { sourceDomainName = domainName; } @Override public List<RawVulnerability> parseWebPage(String sSourceURL, String sCVEContentHTML) { List<RawVulnerability> vulnList = new ArrayList<>(); Document doc = Jsoup.parse(sCVEContentHTML); // get publish and last update date under the Advisory information section Elements advisoryInfo = doc.select("h2:contains(Advisory Information)"); Element advisoryPara = advisoryInfo.first(); String publishDate = ""; String lastUpdatedDate = ""; if (advisoryPara != null) { advisoryPara = advisoryPara.nextElementSibling(); if (advisoryPara != null) { String[] pubSplit = advisoryPara.text().split("published: "); String[] updateSplit = advisoryPara.text().split("last update: "); publishDate = pubSplit[1].split(" ")[0]; lastUpdatedDate = updateSplit[1].split(" ")[0]; } } // get CVE IDs under Vulnerability Information section Element vulnInfo = doc.select("h2:contains(Vulnerability Information)").first(); if (vulnInfo == null) return vulnList; Element vulnPara = vulnInfo.nextElementSibling(); if (vulnPara == null) return vulnList; // usually separated by , or ; Set<String> cves = getCVEs(vulnPara.text()); // get Vulnerability Description for every CVE on page StringBuilder vulnDesc = new StringBuilder(); Element descTitle = doc.select("h2:contains(Vulnerability Description)").first(); if (descTitle != null) { Element next = descTitle.nextElementSibling(); while (next != null && !next.tagName().contains("h")) { vulnDesc.append(next.text()); next = next.nextElementSibling(); } } // get Technical Description foreach CVE on the page, combine with main Vulnerability Description // Note: good chance these technical descriptions are out of order found in cves list Elements techDescs = doc.select("h2:contains(7.), h3:contains(7.)"); // remove the main 7.Technical Description header from the list techDescs.remove(0); if (techDescs.size() != 0) { for (Element techDescTitle : techDescs) { Element nextTech = techDescTitle.nextElementSibling(); if (nextTech == null) continue; String desc = nextTech.text(); // if multiple, these might have [ CVE ] if (desc.contains("[CVE-")) { // connect this to one of our above CVEs and add to vuln list Iterator<String> iter = cves.iterator(); while(iter.hasNext()) { String c = iter.next(); if (desc.contains(c)) { desc = desc.split(c+"]")[1]; vulnList.add(new RawVulnerability( sSourceURL, c, publishDate, lastUpdatedDate, vulnDesc + desc, getClass().getSimpleName() )); iter.remove(); } } } // if single, these might not have [ ] else { // outlier: CVE alone on a line under it // source: https://www.coresecurity.com/core-labs/advisories/viper-rgb-driver-multiple-vulnerabilities // if it goes right into proof of concept code or talks about versions not patched, skip for now... // otherwise, this looks to be just a single CVE, just attach this desc to main vulndesc if (!desc.contains("the following exploit:") && !desc.contains("Below")) { vulnDesc.append(desc); } } } } if (cves.size() != 0) { for (String c : cves) { vulnList.add(new RawVulnerability( sSourceURL, c, publishDate, lastUpdatedDate, vulnDesc.toString(), getClass().getSimpleName() )); cves.remove(c); } } return vulnList; } }
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use App\Models\Tag; use App\Models\Comment; use App\Models\State; use App\Models\Article; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { // \App\Models\User::factory(10)->create(); $tags = Tag::factory(10)->create(); $articles = Article::factory(20)->create(); $tags_id = $tags->pluck('id'); // https://laravel.com/docs/8.x/collections#method-pluck $articles->each(function ($article) use ($tags_id) { $article->tags()->attach($tags_id->random(3)); Comment::factory(3)->create([ 'article_id' => $article->id ]); State::factory(1)->create([ 'article_id' => $article->id ]); }); } }
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MatIconModule } from '@angular/material/icon'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { SharedModule } from 'src/app/shared/shared.module'; import { DashboardComponent } from './dashboard.component'; describe('DashboardComponent', () => { let component: DashboardComponent; let fixture: ComponentFixture<DashboardComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ RouterTestingModule, BrowserAnimationsModule, MatIconModule, SharedModule ], declarations: [DashboardComponent] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(DashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have refreshTweet defined', () => { expect(component.refreshTweets).toBeDefined(); }); it('should have goToProfile defined', () => { expect(component.gotoProfile).toBeDefined(); }); it('should have userNameClickEvent to be defined', () => { expect(component.userNameClickEvent).toBeDefined(); }); it('should have profile value set from data service', () => { expect(component.profile).toBeNull(); }); });
<?php namespace App\Http\Controllers; use App\Doctors; use App\Patients; use App\Polyclinics; use Illuminate\Http\Request; class PatientsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $patients = Patients::all(); return view('patients.index', compact('patients')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $polyclinics = Polyclinics::all(); $doctors = Doctors::all(); return view('patients.create', compact('polyclinics', 'doctors')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Patients::create($request->all()); return redirect()->route('patients.index'); } /** * Display the specified resource. * * @param \App\Patients $patients * @return \Illuminate\Http\Response */ public function show(Patients $patients) { // } /** * Show the form for editing the specified resource. * * @param \App\Patients $patients * @return \Illuminate\Http\Response */ public function edit($id) { $polyclinics = Polyclinics::all(); $doctors = Doctors::all(); $patients = Patients::find($id); return view('patients.edit', compact('doctors', 'polyclinics', 'patients')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Patients $patients * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $request->validate([ 'registration_code' => 'required', 'name' => 'required', 'birthdate' => 'required', 'gender' => 'required', 'polyclinic_id' => 'required', 'doctor_id' => 'required', ]); $patients = Patients::find($id); $patients->registration_code = $request->registration_code; $patients->name = $request->name; $patients->birthdate = $request->birthdate; $patients->gender = $request->gender; $patients->polyclinic_id = $request->polyclinic_id; $patients->doctor_id = $request->doctor_id; $patients->save(); return redirect()->route('patients.index')->with('success', 'Patiens updated!'); } /** * Remove the specified resource from storage. * * @param \App\Patients $patients * @return \Illuminate\Http\Response */ public function destroy($id) { $patients = Patients::find($id); $patients->delete(); return redirect()->route('patients.index')->with('success', 'Patiens deleted!'); } }
import React from 'react'; import Select from '@material-ui/core/Select'; import InputLabel from '@material-ui/core/InputLabel'; export default function TextInput(props) { const [state, setState] = React.useState({ propValue: props.value, }); console.log(state.propValue) let custom_attr = {} if(props.isError){ custom_attr = {...custom_attr, error: true, helperText: props.isError}; } const optionList = props.dropDownList.map((data, key) => <option key={key} value={data.value}>{ data.name }</option> ); return ( <React.Fragment> <InputLabel htmlFor="filled-age-native-simple">{ props.title }</InputLabel> <Select native // value={state.propValue} onChange={props.handleChange} inputProps={{ name: 'age', id: 'filled-age-native-simple', }} variant="outlined" {...custom_attr} fullWidth > <option aria-label="None" value="">{ props.placeholder }</option> { optionList } </Select> </React.Fragment> ); }
/* * Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com * * 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. */ package io.github.jwdeveloper.tiktok.mockClient; import io.github.jwdeveloper.tiktok.TikTokLiveClientBuilder; import io.github.jwdeveloper.tiktok.TikTokRoomInfo; import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException; import io.github.jwdeveloper.tiktok.gifts.TikTokGiftManager; import io.github.jwdeveloper.tiktok.handlers.TikTokMessageHandlerRegistration; import io.github.jwdeveloper.tiktok.handlers.events.TikTokGiftEventHandler; import io.github.jwdeveloper.tiktok.handlers.events.TikTokRoomInfoEventHandler; import io.github.jwdeveloper.tiktok.handlers.events.TikTokSocialMediaEventHandler; import io.github.jwdeveloper.tiktok.http.TikTokCookieJar; import io.github.jwdeveloper.tiktok.http.TikTokHttpClient; import io.github.jwdeveloper.tiktok.http.TikTokHttpRequestFactory; import io.github.jwdeveloper.tiktok.listener.TikTokListenersManager; import io.github.jwdeveloper.tiktok.mappers.TikTokGenericEventMapper; import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse; import io.github.jwdeveloper.tiktok.mockClient.mocks.ApiServiceMock; import io.github.jwdeveloper.tiktok.mockClient.mocks.LiveClientMock; import io.github.jwdeveloper.tiktok.mockClient.mocks.WebsocketClientMock; import java.util.Base64; import java.util.List; import java.util.Stack; public class TikTokMockBuilder extends TikTokLiveClientBuilder { Stack<WebcastResponse> responses; public TikTokMockBuilder(String userName) { super(userName); responses = new Stack<>(); } public TikTokMockBuilder addResponse(String value) { var bytes = Base64.getDecoder().decode(value); return addResponse(bytes); } public TikTokMockBuilder addResponses(List<String> values) { for (var value : values) { try { addResponse(value); } catch (Exception e) { throw new TikTokLiveException(value, e); } } return this; } public TikTokMockBuilder addResponse(byte[] bytes) { try { var response = WebcastResponse.parseFrom(bytes); return addResponse(response); } catch (Exception e) { throw new RuntimeException("Unable to parse response from bytes", e); } } public TikTokMockBuilder addResponse(WebcastResponse message) { responses.push(message); return this; } @Override public LiveClientMock build() { validate(); var cookie = new TikTokCookieJar(); var tiktokRoomInfo = new TikTokRoomInfo(); tiktokRoomInfo.setHostName(clientSettings.getHostName()); var listenerManager = new TikTokListenersManager(listeners, tikTokEventHandler); var giftManager = new TikTokGiftManager(logger); var requestFactory = new TikTokHttpRequestFactory(cookie); var apiClient = new TikTokHttpClient(cookie, requestFactory); var apiService = new ApiServiceMock(apiClient, logger, clientSettings); var webResponseHandler = new TikTokMessageHandlerRegistration(tikTokEventHandler, new TikTokRoomInfoEventHandler(tiktokRoomInfo), new TikTokGenericEventMapper(), new TikTokGiftEventHandler(giftManager), new TikTokSocialMediaEventHandler(tiktokRoomInfo)); var webSocketClient = new WebsocketClientMock(logger, responses, webResponseHandler); return new LiveClientMock(tiktokRoomInfo, apiService, webSocketClient, giftManager, tikTokEventHandler, clientSettings, listenerManager, logger); } @Override public LiveClientMock buildAndConnect() { var client = build(); client.connect(); return client; } }
import { DataTypes,Model, Sequelize } from 'sequelize'; import db from '../infrastructure/sequelize'; interface PlayerAttributes { id: number; name: string; date: string; winPercentage: number; createdAt: Date; updatedAt: Date; } export interface PlayerInstance extends Model<PlayerAttributes>, PlayerAttributes {} export const PlayerDb = db.define<PlayerInstance>('players', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING }, date: { type: DataTypes.STRING }, winPercentage: { type: DataTypes.FLOAT }, createdAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: false }, updatedAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: false } }); interface IRollAttributes{ id: number; roll1: number; roll2: number; total: number; result: string; createdAt: Date; updatedAt: Date; playerId: number; } export interface IRollInstance extends Model<IRollAttributes>, IRollAttributes {} export const Roll = db.define<IRollInstance>('rolls', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, roll1: { type: DataTypes.INTEGER, allowNull: false }, roll2: { type: DataTypes.INTEGER, allowNull: false }, total: { type: DataTypes.INTEGER, allowNull: false }, result: { type: DataTypes.STRING, allowNull: false }, createdAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: false }, updatedAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: false }, playerId: { type: DataTypes.INTEGER, references: { model: 'players', key: 'id' }, allowNull: false } }); PlayerDb.sync(); Roll.sync();
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_memchr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: maria-sg <maria-sg@student.42prague.com +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/08/15 21:34:43 by maria-sg #+# #+# */ /* Updated: 2023/08/15 21:46:19 by maria-sg ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void *ft_memchr(const void *s, int c, size_t n) { size_t i; unsigned char *str; i = 0; str = (unsigned char *)s; while (n > i) { if (str[i] == (unsigned char)c) return (&str[i]); i++; } return (NULL); } // int main() // { // const char str[] = "Hi, How. are you."; // const char ch = '.'; // char *ret; // ret = ft_memchr(str, ch, strlen(str)); // printf("String after |%c| is - |%s|\n", ch, ret); // return(0); // }
/* * onejit - JIT compiler in C++ * * Copyright (C) 2018-2021 Massimiliano Ghilardi * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * stmt1.hpp * * Created on Jan 18, 2021 * Author Massimiliano Ghilardi */ #ifndef ONEJIT_IR_STMT1_HPP #define ONEJIT_IR_STMT1_HPP #include <onejit/fmt.hpp> #include <onejit/ir/label.hpp> #include <onejit/ir/stmt.hpp> #include <onejit/mir/fwd.hpp> #include <onejit/opstmt1.hpp> #include <onejit/x64/fwd.hpp> namespace onejit { namespace ir { class Stmt1 : public Stmt { using Base = Stmt; friend class Node; friend class ::onejit::Compiler; friend class ::onejit::Func; friend class ::onejit::Test; friend class x64::Compiler; friend class mir::Compiler; public: /** * construct an invalid Stmt1 * exists only to allow placing Stmt1 in containers * and similar uses that require a default constructor. * * to create a valid Stmt1, construct one of the derived classes */ constexpr Stmt1() noexcept : Base{} { } constexpr OpStmt1 op() const noexcept { return OpStmt1(Base::op()); } static constexpr Type type() noexcept { return STMT_1; } static constexpr uint32_t children() noexcept { return 1; } // shortcut for child_is<Expr>(0) Expr arg() const noexcept { return child_is<Expr>(0); } const Fmt &format(const Fmt &fmt, Syntax syntax = Syntax::Default, size_t depth = 0) const; protected: // downcast Node to Stmt1 constexpr explicit Stmt1(const Node &node) noexcept : Base{node} { } // downcast helper static constexpr bool is_allowed_type(Type t) noexcept { return t == STMT_1; } // used by subclasses and by Compiler::compile() Stmt1(Func &func, Expr arg, OpStmt1 op) noexcept : Base{create(func, arg, op)} { } private: static constexpr bool child_result_is_used(uint32_t /*i*/) noexcept { return true; } static Node create(Func &func, Expr arg, OpStmt1 op) noexcept; }; class Goto : public Stmt1 { using Base = Stmt1; friend class Node; friend class ::onejit::Func; public: /** * construct an invalid Goto * exists only to allow placing Goto in containers * and similar uses that require a default constructor. * * to create a valid Goto, use one of the other constructors. */ constexpr Goto() noexcept : Base{} { } Goto(Func &func, Label target) noexcept // : Base{func, target, GOTO} { } static constexpr OpStmt1 op() noexcept { return GOTO; } // shortcut for child_is<Label>(0) Label to() const noexcept { return child_is<Label>(0); } private: // downcast Node to Goto constexpr explicit Goto(const Node &node) noexcept : Base{node} { } // downcast helper static constexpr bool is_allowed_op(uint16_t op) noexcept { return op == GOTO; } }; // statement to increment an expression by one, i.e. expr++ class Inc : public Stmt1 { using Base = Stmt1; friend class Node; friend class ::onejit::Func; public: /** * construct an invalid Inc * exists only to allow placing Inc in containers * and similar uses that require a default constructor. * * to create a valid Inc, use one of the other constructors. */ constexpr Inc() noexcept : Base{} { } // expr must be Var or Mem Inc(Func &func, Expr expr) noexcept // : Base{func, expr, INC} { } static constexpr OpStmt1 op() noexcept { return INC; } // shortcut for child_is<Expr>(0) Expr expr() const noexcept { return child_is<Expr>(0); } private: // downcast Node to Inc constexpr explicit Inc(const Node &node) noexcept : Base{node} { } // downcast helper static constexpr bool is_allowed_op(uint16_t op) noexcept { return op == INC; } }; // statement to decrement an expression by one, i.e. expr-- class Dec : public Stmt1 { using Base = Stmt1; friend class Node; friend class ::onejit::Func; public: /** * construct an invalid Dec * exists only to allow placing Dec in containers * and similar uses that require a default constructor. * * to create a valid Dec, use one of the other constructors. */ constexpr Dec() noexcept : Base{} { } // expr must be Var or Mem Dec(Func &func, Expr expr) noexcept // : Base{func, expr, DEC} { } static constexpr OpStmt1 op() noexcept { return DEC; } // shortcut for child_is<Expr>(0) Expr expr() const noexcept { return child_is<Expr>(0); } private: // downcast Node to Dec constexpr explicit Dec(const Node &node) noexcept : Base{node} { } // downcast helper static constexpr bool is_allowed_op(uint16_t op) noexcept { return op == DEC; } }; } // namespace ir } // namespace onejit #endif // ONEJIT_IR_STMT1_HPP
import { Injectable } from "@angular/core"; import { HttpClient } from '@angular/common/http'; import { Recipe } from './models'; @Injectable() export class RecipesService { private AUTH_PATH: string = `http://localhost:8080`; private USER_ID: string = localStorage.getItem('intelli-user'); constructor(private http: HttpClient) {} getRecipeImagesPath(): string { return `${this.AUTH_PATH}/recipe-images`; } async getAllRecipes(): Promise<Recipe[]> { const url = `${this.AUTH_PATH}/users/${this.USER_ID}/recipes`; return this.http.get(url).toPromise().then((recipes: Recipe[]) => { return recipes; }); } async getRecipe(recipeId: string): Promise<Recipe> { const url = `${this.AUTH_PATH}/users/${this.USER_ID}/recipes/${recipeId}`; return this.http.get(url).toPromise().then((recipe: Recipe) => { return recipe; }); } async createRecipe(recipe: Recipe): Promise<Recipe> { const url = `${this.AUTH_PATH}/users/${this.USER_ID}/recipes`; return this.http.post(url, recipe).toPromise().then((createdRecipe: Recipe) => { return createdRecipe; }); } async updateRecipe(recipeId: string, recipe: Recipe): Promise<Recipe> { const url = `${this.AUTH_PATH}/users/${this.USER_ID}/recipes/${recipeId}`; return this.http.put(url, recipe).toPromise().then((updatedRecipe: Recipe) => { return updatedRecipe; }); } async deleteRecipe(recipeId: string): Promise<unknown> { const url = `${this.AUTH_PATH}/users/${this.USER_ID}/recipes/${recipeId}`; return this.http.delete(url).toPromise(); } async uploadImageToRecipe(recipeId: string, image: any): Promise<any> { const url = `${this.AUTH_PATH}/users/${this.USER_ID}/recipes/${recipeId}/images`; let formData: FormData = new FormData(); formData.append('file', image); return this.http.post(url, formData).toPromise(); } }
import { fireEvent, render } from '@testing-utils/library' import React from 'react' import { Button, Text } from 'react-native' import { act } from 'react-test-renderer' import { NotificationProvider, NotifyOptions, useNotification, } from '../notification' function TestComponent(options: NotifyOptions) { const notification = useNotification() return ( <> <Button title="hide" onPress={() => notification.hide()} /> <Button title="show" onPress={() => notification.show(options)} /> </> ) } jest.useFakeTimers() describe('notification context', () => { it('should render basic success alert', () => { const { getByText } = render( <NotificationProvider> <TestComponent message="custom-message" type="success" /> </NotificationProvider>, ) fireEvent.press(getByText('show')) expect(getByText('custom-message')).toBeDefined() }) it('should render basic error alert', () => { const { getByText } = render( <NotificationProvider> <TestComponent message="custom-message" type="error" /> </NotificationProvider>, ) fireEvent.press(getByText('show')) expect(getByText('custom-message')).toBeDefined() }) it('should remove notification when time is up', () => { const { getByText, queryByText } = render( <NotificationProvider> <TestComponent message="custom-message" type="error" duration={1000} /> </NotificationProvider>, ) fireEvent.press(getByText('show')) act(() => { jest.advanceTimersByTime(1000) }) expect(queryByText('custom-message')).toBeNull() }) it('should remove notification when hide method is called', () => { const { getByText, queryByText } = render( <NotificationProvider> <TestComponent message="custom-message" type="error" duration={10000} /> </NotificationProvider>, ) fireEvent.press(getByText('show')) fireEvent.press(getByText('hide')) act(() => { jest.advanceTimersByTime(250) }) expect(queryByText('custom-message')).toBeNull() }) it('should render notification with action', () => { const { getByText } = render( <NotificationProvider> <TestComponent message="message" type="success" action={() => <Text>custom-action</Text>} /> </NotificationProvider>, ) fireEvent.press(getByText('show')) expect(getByText('custom-action')).toBeDefined() }) })
use crate::{ cpu::{ operand::{go, step, IO8}, Cpu, }, peripherals::Peripherals, }; use std::sync::atomic::{AtomicU16, AtomicU8, Ordering::Relaxed}; #[allow(clippy::upper_case_acronyms)] #[allow(dead_code)] #[derive(Debug, Copy, Clone)] pub enum Indirect { BC, DE, HL, CFF, HLD, HLI, } impl IO8<Indirect> for Cpu { fn read8(&mut self, bus: &Peripherals, src: Indirect) -> Option<u8> { step!( None, { 0: { VAL8.store(match src { Indirect::BC => bus.read(self.regs.bc()), Indirect::DE => bus.read(self.regs.de()), Indirect::HL => bus.read(self.regs.hl()), Indirect::CFF => bus.read(0xff00 | u16::from(self.regs.c)), Indirect::HLD => { let hl = self.regs.hl(); self.regs.set_hl(hl.wrapping_sub(1)); bus.read(hl) }, Indirect::HLI => { let hl = self.regs.hl(); self.regs.set_hl(hl.wrapping_add(1)); bus.read(hl) }, }, Relaxed); go!(1); return None; }, 1: { go!(0); #[allow(clippy::needless_return)] return Some(VAL8.load(Relaxed)); }, } ); } fn write8(&mut self, bus: &mut Peripherals, dst: Indirect, val: u8) -> Option<()> { step!( None, { 0: { match dst { Indirect::BC => bus.write(self.regs.bc(), val), Indirect::DE => bus.write(self.regs.de(), val), Indirect::HL => bus.write(self.regs.hl(), val), Indirect::CFF => bus.write(0xff00 | u16::from(self.regs.c), val), Indirect::HLD => { let hl = self.regs.hl(); self.regs.set_hl(hl.wrapping_sub(1)); bus.write(hl, val) }, Indirect::HLI => { let hl = self.regs.hl(); self.regs.set_hl(hl.wrapping_add(1)); bus.write(hl, val) }, } go!(1); return None; }, 1: { go!(0); #[allow(clippy::needless_return)] return Some(()); }, } ); } }
--- title: "\"[New] 2024 Approved Harmonizing Your Spotify Queue with YouTube Music Catalogs\"" date: 2024-06-06T15:39:39.997Z updated: 2024-06-07T15:39:39.997Z tags: - ai video - ai youtube categories: - ai - youtube description: "\"This Article Describes [New] 2024 Approved: Harmonizing Your Spotify Queue with YouTube Music Catalogs\"" excerpt: "\"This Article Describes [New] 2024 Approved: Harmonizing Your Spotify Queue with YouTube Music Catalogs\"" keywords: "\"Harmonize Spotify Queue,YouTube Music Catalog,Spotify & YouTube Sync,Streamline Playlists,Unified Song Library,Cross-Platform Syncing,Consolidate Music Hits\"" thumbnail: https://thmb.techidaily.com/bb9708a331c4c3dd31e799c079bb73652a9e75d1a08dd178d051b1af275cc7e6.jpg --- ## Harmonizing Your Spotify Queue with YouTube Music Catalogs Do you want to transfer your playlist to YouTube Music from Spotify? After all, there are some significant advantages to using the former over the latter. For one, YouTube Music offers a broader range of songs and videos without ads. Though Spotify is a widely used music streaming app, its many limitations for non-Premium members have driven users to look for alternatives. For example, 30-second ads that play every 15 minutes and the inability to skip songs are among the app's most frustrating features. So, if you're ready to **convert Spotify playlists to YouTube Music**, let's get started! ## Recommendation And Guidance For Using The Playlist Transfer Tools With Spotify and YouTube Music, you can access millions of songs and playlists at the click of a button. But what if you want to move your Spotify playlist to YouTube Music? Luckily, the following 5 best tools can help you to do just that. | **Name** | **Price** | **Transfer amount limit** | **Speed** | **Compatibility** | | -------------------------------------------------- | --------- | ------------------------- | --------------- | --------------------------------------------------------------------------------------------------- | | [**Playlist Buddy**](#%5FPlaylist%5FBuddy) | Free | 250 songs per playlist. | 1 minute | YouTube and Spotify | | [**TuneMyMusic**](#%5FTune%5FMy%5FMusic) | Free | 1,000 tracks | 38 seconds. | Spotify, Itunes, Apple Music, Nanpster, YouTube, Deezer, Tidal, Google Play Music, and Amazon Music | | [**Soundiiz**](#%5FSoundiiz) | Free | 200 tracks | 26 seconds. | Spotify, Apple Music, YouTube Music, TIDAL, and more | | [**Playlist Converter**](#%5FPlaylist%5FConverter) | Free | unlimited | Slow processing | YouTube Music, Spotify, PLS, Deezer | | [**SongShift**](#%5FSongShift) | Free | Unlimited | 40 seconds | Spotify, YouTube Music, Apple Music, Deezer, Amazon Music, Discogs, and more | ### [Playlist Buddy](https://playlistbuddy.com/) Playlist Buddy is a free-to-use online tool that is fully dedicated to converting your Spotify playlist to YouTube within a minute. The program is quick, easy, and simple- so there's no excuse not to try it out! ##### Key Features * Transfers playlists one-by-one * Free to use * Compatible with YouTube and Spotify * Can convert your lists to a CSV file ##### Limitations * Cannot be used for other music streaming services * Limited to only 250 tracks per playlist ##### How To Use? To transfer your Spotify Playlist to YouTube Music using the Playlist Buddy, do the following steps: Step1 First, open a browser on your PC and visit the **"Playlist Buddy"** site. Click **"Login to Spotify."** Step2 Now, click **"Agree"** to provide access to your account information. Click the **"Sign in YouTube"** button and log in to your account. Step3 Select your Spotify playlist, click **"Convert Playlist,"** and Playlist Buddy will start transferring your **Spotify to YouTube playlist.** ![converting spotify playlist to youtube music using playlist buddy](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-playlist-buddy.png) ### [Tune My Music](https://www.tunemymusic.com/) Tune My Music is another free tool that offers 96% accuracy while converting your Spotify playlist to YouTube Music. With this platform, you can transfer up to 1000 tracks at a time in just a few seconds. ##### Key Features * Intuitive interface and workflow * Can transfer playlists in batches * Transfers tracks in 38 seconds * Synchronizes two playlists from two different music services * Backups your songs ##### Limitations * Does not transfer playlists/tracks in order * No playlist descriptions ##### How To Use? The following steps will help you use the TuneMyMusic platform to convert your Spotify playlist to YouTube Music: Step1 Visit the Tune My Music website using your browser and click the **"Let's Start"** option. Step2 On the **"Select The Source"** page, choose **"Spotify"** as your source and sign in to your account. Step3 Now, load your Spotify playlist or paste its URL from your account. Click **"Next: Select Destination"** on the next page and choose **"YouTube Music"** from the given options. ![converting spotify playlist to youtube music using tunemymusic](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-tunemymusic.png) Finally, click **"Start Moving My Music"** to convert your Spotify playlist to YouTube Music. ### [Soundiiz](https://soundiiz.com/) If you want to quickly and instantly **convert your Spotify playlist to YouTube,** Soundiiz is the right solution for you! This tool is free and compatible with multiple musics streaming services. ##### Key Features * 98% accuracy while transferring songs * Fast transfer of playlists between many platforms * No app download is required * Excellent UI ##### Limitations * Transfers albums, artists, and liked songs only in the premium version * Can only transfer 200 tracks ##### How To Use Follow these steps to convert your Spotify playlist to YouTube music using Soundiiz: Step1 In the first step, visit the Soundiiz website and click the "Start Now" option. Step2 Select the **"Sign in with Spotify"** option from the list to log in to your account and click **"Access"** to provide permission to access your details. ![converting spotify playlist to youtube music using soundiiz](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-soundiiz.png) Step3 Select **"YouTube Music"** from the left-side panel and click **"Connect."** Now, sign in to your account. Step4 Now, open the **"Transfer"** tab, choose **"Spotify"** as a source, and go to **"Playlists."** Choose the Spotify playlist and click **"Confirm and Continue."** ![transferring spotify playlist to youtube music using soundiiz](https://images.wondershare.com/filmora/article-images/2023/03/transferring-spotify-playlist-to-youtube-music-using-soundiiz.png) Step5 Configure your playlist and click the **"Save Configuration"** option. Next, click **"Confirm"** and choose **"YouTube Music"** on the next page to convert your **Spotify to a YouTube playlist.** ### [Playlist Converter](http://www.playlist-converter.net/) Playlist Converter allows you to take your favorite Spotify playlists and convert them to YouTube Music, Apple Music, Google Play Music, or Amazon Music. This handy platform is easy-to-use and only takes a few minutes to convert your favorite playlists. ##### Key Features * Converts to multiple music sources and file formats * Available for free * Unlimited transfers * No registration is required ##### Limitations * Not much accurate * It takes time to process ##### How To Use? To use the Playlist Converter tool for converting Spotify playlists to YouTube Music, follow these steps in sequence: Step1 Visit the Playlist Converter website using your browser and go to the **"Spotify"** tab. Step2 Click **"Log in with Spotify"** and sign in to your account. Make sure to provide access to your details. Step3 Select your Spotify playlist and click **"Export to YouTube Account."** Next, click the **"Login With YouTube and Export the Playlist"** option and sign in to your account. ![converting spotify playlist to youtube music using playlist converter](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-playlist-converter.png) Playlist Converter will fetch your playlist details and transfer them to your YouTube account. ### [SongShift](https://apps.apple.com/us/app/songshift/id1097974566) SongShift is an iOS app that allows you to transfer your songs between music streaming platforms. It's an excellent way to keep all your song tracks in one place, no matter where you prefer to stream them. The app is easy to use and only takes a few steps to get started! ##### Key Features * It lets you fix mismatches * Excellent user experience and interface * Transfers tracks to multiple music streaming platforms * Unlimited song transfer ##### Limitations * Only available for iOS devices ##### How To Use? Here's how you can use the SongShift app to convert your **Spotify playlist to your YouTube Music** account: Step1 Open the App Store on your iOS device, install the **SongShift app** and launch it. Step2 On the app's main page, tap **"Connect Your Music"** and go to the **"Music Services"** page. Select **"Spotify"** and click the **"Connect"** option. ![converting spotify playlist to youtube music using songshift app](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-songshift-app.png) Step3 Now, sign in to your Spotify account and tap the **"Plus"** icon at the bottom of the screen. Step4 Tap the **"Setup Source"** option under New Configuration and choose **"Spotify"** as the source service. ![selecting setup source in songshift](https://images.wondershare.com/filmora/article-images/2023/03/selecting-setup-source-in-songshift.png) Next, tap **"Playlist"** under the **"Select Media Type"** header and find your Spotify playlist. Step5 Afterward, tap the "Setup Destination" option and select **"YouTube Music."** Now, choose your destination type and tap **"I'm Finished"** to start transferring your Spotify playlist to YouTube Music. ## Bonus Video Tutorial: Another Way To _See_ the Music - Audio Visualization Effects Hopefully, this article helped resolve your query, and you can now quickly transfer all your favorite playlists from Spotify to YouTube Music. Besides, before the end, we want to show you another exciting way to feel the music - Audio Visualization Effects. The effect will intelligently match the sound in your video while also adding dynamic effects. You can try it in a user-friendly video editor [Filmora](https://tools.techidaily.com/wondershare/filmora/download/). If you want to know more about the effect and how to realize it with Filmoea, please watch the video we specially prepared for you below. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ## Conclusion This comprehensive guide recommends the 5 best tools to help you **convert Spotify playlists to YouTube Music.** In addition, we've provided a step-by-step process of using each tool, its key features, and its limitations to help you make the right decisions. [Playlist Buddy](https://playlistbuddy.com/) Playlist Buddy is a free-to-use online tool that is fully dedicated to converting your Spotify playlist to YouTube within a minute. The program is quick, easy, and simple- so there's no excuse not to try it out! ##### Key Features * Transfers playlists one-by-one * Free to use * Compatible with YouTube and Spotify * Can convert your lists to a CSV file ##### Limitations * Cannot be used for other music streaming services * Limited to only 250 tracks per playlist ##### How To Use? To transfer your Spotify Playlist to YouTube Music using the Playlist Buddy, do the following steps: Step1 First, open a browser on your PC and visit the **"Playlist Buddy"** site. Click **"Login to Spotify."** Step2 Now, click **"Agree"** to provide access to your account information. Click the **"Sign in YouTube"** button and log in to your account. Step3 Select your Spotify playlist, click **"Convert Playlist,"** and Playlist Buddy will start transferring your **Spotify to YouTube playlist.** ![converting spotify playlist to youtube music using playlist buddy](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-playlist-buddy.png) ### [Tune My Music](https://www.tunemymusic.com/) Tune My Music is another free tool that offers 96% accuracy while converting your Spotify playlist to YouTube Music. With this platform, you can transfer up to 1000 tracks at a time in just a few seconds. ##### Key Features * Intuitive interface and workflow * Can transfer playlists in batches * Transfers tracks in 38 seconds * Synchronizes two playlists from two different music services * Backups your songs ##### Limitations * Does not transfer playlists/tracks in order * No playlist descriptions ##### How To Use? The following steps will help you use the TuneMyMusic platform to convert your Spotify playlist to YouTube Music: Step1 Visit the Tune My Music website using your browser and click the **"Let's Start"** option. Step2 On the **"Select The Source"** page, choose **"Spotify"** as your source and sign in to your account. Step3 Now, load your Spotify playlist or paste its URL from your account. Click **"Next: Select Destination"** on the next page and choose **"YouTube Music"** from the given options. ![converting spotify playlist to youtube music using tunemymusic](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-tunemymusic.png) Finally, click **"Start Moving My Music"** to convert your Spotify playlist to YouTube Music. ### [Soundiiz](https://soundiiz.com/) If you want to quickly and instantly **convert your Spotify playlist to YouTube,** Soundiiz is the right solution for you! This tool is free and compatible with multiple musics streaming services. ##### Key Features * 98% accuracy while transferring songs * Fast transfer of playlists between many platforms * No app download is required * Excellent UI ##### Limitations * Transfers albums, artists, and liked songs only in the premium version * Can only transfer 200 tracks ##### How To Use Follow these steps to convert your Spotify playlist to YouTube music using Soundiiz: Step1 In the first step, visit the Soundiiz website and click the "Start Now" option. Step2 Select the **"Sign in with Spotify"** option from the list to log in to your account and click **"Access"** to provide permission to access your details. ![converting spotify playlist to youtube music using soundiiz](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-soundiiz.png) Step3 Select **"YouTube Music"** from the left-side panel and click **"Connect."** Now, sign in to your account. Step4 Now, open the **"Transfer"** tab, choose **"Spotify"** as a source, and go to **"Playlists."** Choose the Spotify playlist and click **"Confirm and Continue."** ![transferring spotify playlist to youtube music using soundiiz](https://images.wondershare.com/filmora/article-images/2023/03/transferring-spotify-playlist-to-youtube-music-using-soundiiz.png) Step5 Configure your playlist and click the **"Save Configuration"** option. Next, click **"Confirm"** and choose **"YouTube Music"** on the next page to convert your **Spotify to a YouTube playlist.** ### [Playlist Converter](http://www.playlist-converter.net/) Playlist Converter allows you to take your favorite Spotify playlists and convert them to YouTube Music, Apple Music, Google Play Music, or Amazon Music. This handy platform is easy-to-use and only takes a few minutes to convert your favorite playlists. ##### Key Features * Converts to multiple music sources and file formats * Available for free * Unlimited transfers * No registration is required ##### Limitations * Not much accurate * It takes time to process ##### How To Use? To use the Playlist Converter tool for converting Spotify playlists to YouTube Music, follow these steps in sequence: Step1 Visit the Playlist Converter website using your browser and go to the **"Spotify"** tab. Step2 Click **"Log in with Spotify"** and sign in to your account. Make sure to provide access to your details. Step3 Select your Spotify playlist and click **"Export to YouTube Account."** Next, click the **"Login With YouTube and Export the Playlist"** option and sign in to your account. ![converting spotify playlist to youtube music using playlist converter](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-playlist-converter.png) Playlist Converter will fetch your playlist details and transfer them to your YouTube account. ### [SongShift](https://apps.apple.com/us/app/songshift/id1097974566) SongShift is an iOS app that allows you to transfer your songs between music streaming platforms. It's an excellent way to keep all your song tracks in one place, no matter where you prefer to stream them. The app is easy to use and only takes a few steps to get started! ##### Key Features * It lets you fix mismatches * Excellent user experience and interface * Transfers tracks to multiple music streaming platforms * Unlimited song transfer ##### Limitations * Only available for iOS devices ##### How To Use? Here's how you can use the SongShift app to convert your **Spotify playlist to your YouTube Music** account: Step1 Open the App Store on your iOS device, install the **SongShift app** and launch it. Step2 On the app's main page, tap **"Connect Your Music"** and go to the **"Music Services"** page. Select **"Spotify"** and click the **"Connect"** option. ![converting spotify playlist to youtube music using songshift app](https://images.wondershare.com/filmora/article-images/2023/03/converting-spotify-playlist-to-youtube-music-using-songshift-app.png) Step3 Now, sign in to your Spotify account and tap the **"Plus"** icon at the bottom of the screen. Step4 Tap the **"Setup Source"** option under New Configuration and choose **"Spotify"** as the source service. ![selecting setup source in songshift](https://images.wondershare.com/filmora/article-images/2023/03/selecting-setup-source-in-songshift.png) Next, tap **"Playlist"** under the **"Select Media Type"** header and find your Spotify playlist. Step5 Afterward, tap the "Setup Destination" option and select **"YouTube Music."** Now, choose your destination type and tap **"I'm Finished"** to start transferring your Spotify playlist to YouTube Music. ## Bonus Video Tutorial: Another Way To _See_ the Music - Audio Visualization Effects Hopefully, this article helped resolve your query, and you can now quickly transfer all your favorite playlists from Spotify to YouTube Music. Besides, before the end, we want to show you another exciting way to feel the music - Audio Visualization Effects. The effect will intelligently match the sound in your video while also adding dynamic effects. You can try it in a user-friendly video editor [Filmora](https://tools.techidaily.com/wondershare/filmora/download/). If you want to know more about the effect and how to realize it with Filmoea, please watch the video we specially prepared for you below. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ## Conclusion This comprehensive guide recommends the 5 best tools to help you **convert Spotify playlists to YouTube Music.** In addition, we've provided a step-by-step process of using each tool, its key features, and its limitations to help you make the right decisions. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Overcoming Obscured Views During YouTube Playback There might be some instances where when you try to play a clip on one of the most popular streaming video sites, you are displayed with a **YouTube black screen**. There could be several reasons behind this. That said, the following sections discuss some of the common causes of **YouTube video black screen**, and explain how you can fix the issue easily with merely a few simple mouse clicks. Here, you will also learn how to resolve the problem if it occurs on your smartphone. ## Best Video Editor for YouTubers: Wondershare Filmora Filmora is one of the most popular video editing software among YouTubers, whether you’re creating gameplay, education, travel videos, or other types of videos, you will find Filmora perfectly meets your needs. You can create the YouTube video at the correct aspect ratio to [remove the black bar](https://tools.techidaily.com/wondershare/filmora/download/), record the screen, webcam, and voiceover at the same time, edit as you like. ##### Wondershare Filmora Create stunning effects with simple clicks. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) --- ## Part 1: What Causes a YouTube Black Screen Error? As mentioned earlier, although there could be any reason for **videos black on YouTube**, some of the most common ones are listed below: **Obsolete Web Browser** Because the websites and online portals are regularly updated by the developers to keep them secure from intruders and attackers, the web browsers must also be updated accordingly to keep up the pace. If your instance of the web browser is outdated, you may experience a **YouTube TV black screen**. **Incompatible Browser Extensions** This mostly happens while using Google Chrome. Because Chrome Web Store is populated with a plethora of extensions, it is likely that any of those might become outdated (or get updated), thus becoming incompatible with the current version of the web browser. **Slow Internet Connection** This issue could be from your Internet Service Provider’s (ISP’s) side. At your part, the maximum you can do is, try switching to a wired network, or if you are using Wi-Fi, consider taking your PC or laptop closer to the wireless router. **Stale DNS Cache** Every time you visit a website, its DNS (Domain Name System) record is automatically stored in the DNS cache. This helps in the address resolution process (fetching the URL) the next time you open the site. If the DNS information gets stale in the DNS cache, the browser may fail to locate the website, a YouTube video in this case, and you will be displayed with the black screen. **Outdated Display Driver** As it is with Windows itself, even the graphic card driver must be updated regularly to maintain your PC’s health. If an updated version of the display driver is not installed on your Windows computer, you may experience **YouTube black screen**. ## Part 2: How to Fix YouTube Video Black Screen \[\*Quick Way\] Depending on the root cause of the issue, the solutions to fix the **YouTube video black screen** issue may differ. Nevertheless, some of the most effective remedies are discussed below in detail: ### 1\. Web Browser Solution(s) **Solution 1: Update Your Web Browser** When you experience **YouTube video black screen**, try updating your web browser to its latest version. Assuming that you’re using Google Chrome, the update process is given below: Launch Google Chrome, click the **Customize and control Google Chrome** icon from the top-right corner, and then select **Update Google Chrome** from the menu that appears. **Note:** If the **Update Google Chrome** option isn’t available, it simply means that you are already using the latest version of the browser **Solution 2: Restart the Web Browser** If the video isn’t visible even after updating Google Chrome, or if you’re already using the most recent version but the issue is still there, you can close the web browser, and relaunch it to see if that helps. **Solution 3: Use a Different Browser** If Google Chrome itself is the culprit, the video should be visible on a different browser. You may consider using Mozilla Firefox or the Windows’ default app, Microsoft Edge. Copy the URL of the faulty video from Google Chrome’s address bar, and then launch a different web browser, and paste the copied URL in the new browser’s address bar. Press **Enter** and see if the video plays correctly. **Solution 4: Clean the Web Browser** Sometimes even the web browser history and caches can also prevent a YouTube video from being displayed. Therefore, it would be a good idea to clear the browser data, and see if it helps. The process is given below: After launching the web browser (Google Chrome is used here for example), go to the **Customize and control Google Chrome** menu, and then go to **More tools**, and then select **Clear browsing data**. ![clear google chrome cache](https://images.wondershare.com/filmora/article-images/clear-google-chrome-cache.jpg) Switch between the **Basic** and **Advanced** tabs on the **Clear browsing data** box to choose the records that you want to delete, and then choose your preferred duration of the records from the **Time range** drop-down list. ![clear google chrome browsing data](https://images.wondershare.com/filmora/article-images/clear-browsing-data-chrome.jpg) Click **Clear data** from the bottom-right corner to clear browsing caches. **Solution 5: Disable/Remove the Extensions** If one or more browser extensions are incompatible, even then you may experience **YouTube black screen**. In such a case, you can disable those extensions, or permanently remove them to resolve the issue. You can learn the process of doing so by following the instructions that are given below: Launch Google Chrome and go to the **Customize and control Google Chrome** menu, go to **More tools,** then select **Extensions** from the submenu that appears. Turn off the switch for each of the installed extensions to check if the issue is fixed. ![disable google chrome extension](https://images.wondershare.com/filmora/article-images/disable-google-chrome-extensions.jpg) **Note:** If this solution works, you can try enabling the extensions one at a time, and check turning on which one causes **YouTube video black screen**. Once the culprit extension is found, you can click **Remove** to get rid of it altogether. **Solution 6: Reinstall the Browser** If the video is visible on a different web browser, probably the default one that you are using got corrupted. A quick resolution would be to remove its instance from your PC, and install a fresh copy. To do so: • Type **Control Panel** in the **Cortana** search box, and then click **Control Panel** from the results list. • On the **Control Panel** window, click **Uninstall a program** from under the **Programs** • Click to select the browser from the list of installed apps (Google Chrome here) and select **Uninstall** from above the list. • Follow the on-screen instructions from there to remove the web browser from your PC. Next, use Microsoft Edge (or any other browser) to download and install a fresh copy of Google Chrome and see if the issue is fixed ### 2\. ISP or Internet Speed Solution(s) If you are experiencing a slow Internet connection, the issue might be either from your Internet Service Provider’s (ISP’s) side, or on your part. In any case, you can try the following solutions to fix the issue: **Solution 1: Get Your PC/Laptop Closer to the Router** If you are using a Wi-Fi network, consider bringing your device a bit closer to the wireless router and see if the issue is fixed. You may also want to recheck and ensure that there are no highly magnetic devices (a speaker or something similar) placed near the router. **Solution 2: Switch to a Wired Network** If the problem persists, try connecting your laptop/desktop PC to your router with a LAN cable, and then try reopening the YouTube video to see if it plays correctly this time. **PC/Windows Solution(s)** At times, your computer could be the main culprit, and trying some basic troubleshooting steps might resolve the issue. Some of the most effective solutions are listed below: **Solution 1: Clear DNS Cache** Clearing the DNS cache ensures that your PC is now ready to accept and save new DNS records in the cache. The process of clearing the existing cache data is listed below: Type **CMD** in the **Cortana** search box, and click **Run as administrator** from the right menu of the results list. Click **Yes** on the **User Account Control** confirmation box, and in the **Command Prompt** window, type **IPCONFIG /FLUSHDNS** and press Enter ![use command to fix YouTube black screen](https://images.wondershare.com/filmora/article-images/use-command-to-fix-youtube-black-screen.jpg) Try opening the YouTube video again and see if the issue is fixed **Solution 2: Update the Graphic Card Driver** Anything that you see on your computer screen is because of the graphics card. Since a driver is needed to interact with the device, an old one might prevent the videos from getting displayed. If the graphics card is the culprit, the chances are that you won’t be able to see any video at all, be it from YouTube or offline. Therefore, checking if you are using the latest version of the graphic card driver wouldn’t harm you. The process is given below: Right-click **Start** and go to **Device Manager** from the context menu Expand the **Display adapters** tree on the **Device Manager** snap-in, and right-click the graphics card from the list and select **Update driver** from the context menu. ![upgrade graphic card to fix YouTube black screen](https://images.wondershare.com/filmora/article-images/upgrade-graphic-card-to-fix-youtube-video-black-screen.jpg) Click **Search automatically for drivers** from the next screen that appears and follow the on-screen instructions from there to update the graphic card driver. **Note:** If your PC has multiple graphic cards installed in it, you will have to follow this procedure for each of them individually. ## Part 3: How to Troubleshoot YouTube Black Screen on Mobile? If you wish to watch online videos on your smartphone, but experience **YouTube video black screen**, the process of fixing the issue on the phones is comparatively simple. The steps that are given below explain the procedure: ### How to Troubleshoot YouTube Black Screen on Android **Clear the Cache** Go to **Settings** and then tap **Apps** from the **Settings** Go to YouTube and then scroll down to Storage. Tap it and then select **Clear data and Clear cache**. Relaunch YouTube and see if the issue is fixed. ![fix YouTube black screen on Android](https://images.wondershare.com/filmora/article-images/fix-youtube-video-black-screen-android.jpg) ### How to Troubleshoot YouTube Black Screen On iOS **Delete and Reinstall the App** Long-tap the YouTube app on your iOS device, and then tap **Remove App**, and then select **Delete App**. ![fix YouTube black screen on iPhone](https://images.wondershare.com/filmora/article-images/delete-youtube-from-iphone.jpg) Go to **App Store** and download and install a fresh copy of YouTube, and see if the problem is resolved. **Conclusion** There could be several reasons for **YouTube black screen**, and depending on the root cause of the issue, the troubleshooting methods may vary. While some inconsistencies can be fixed from within the web browser itself, at times you may need to tweak your operating system to get an accurate solution. Likewise, while using an Android smartphone, you can clear YouTube data and cache; and remove and reinstall the app altogether when on an iOS device. <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://eaxpv-info.techidaily.com/new-inspiration-boost-with-leading-hr-tapes/"><u>[New] Inspiration Boost with Leading HR Tapes</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-dissecting-youtubes-user-commentary-for-2024/"><u>[Updated] Dissecting YouTubes' User Commentary for 2024</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-in-2024-from-editing-to-sharing-youtube-mastery-with-adobe-premiere/"><u>[New] In 2024, From Editing to Sharing YouTube Mastery with Adobe Premiere</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-in-2024-from-draft-to-edit-essential-film-techniques-via-youtube/"><u>[Updated] In 2024, From Draft to Edit Essential Film Techniques via YouTube</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-2024-approved-fitness-forward-6-video-concepts-to-energize-your-online-community/"><u>[Updated] 2024 Approved Fitness Forward 6 Video Concepts to Energize Your Online Community</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-global-leaderboard-top-subscribers-by-youtube-star-for-2024/"><u>[New] Global Leaderboard Top Subscribers by YouTube Star for 2024</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-in-2024-follow-the-flow-of-forum-fancies/"><u>[Updated] In 2024, Follow the Flow of Forum Fancies</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-in-2024-essential-3d-toolkit-creating-engaging-video-beginnings/"><u>[Updated] In 2024, Essential 3D Toolkit Creating Engaging Video Beginnings</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-how-does-youtube-work-after-a-video-is-uploaded-for-2024/"><u>[Updated] How Does YouTube Work After a Video Is Uploaded for 2024</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-the-art-of-lyric-videos-using-lyric-video-maker-software/"><u>[New] The Art of Lyric Videos Using Lyric Video Maker Software</u></a></li> <li><a href="https://location-social.techidaily.com/top-7-skype-hacker-to-hack-any-skype-account-on-your-samsung-galaxy-xcover-6-pro-tactical-edition-drfone-by-drfone-virtual-android/"><u>Top 7 Skype Hacker to Hack Any Skype Account On your Samsung Galaxy XCover 6 Pro Tactical Edition | Dr.fone</u></a></li> <li><a href="https://review-topics.techidaily.com/recover-lost-data-from-itel-a70-by-fonelab-android-recover-data/"><u>Recover lost data from Itel A70</u></a></li> <li><a href="https://voice-adjusting.techidaily.com/updated-navigating-advanced-sound-design-the-top-5-most-innovative-ducking-plugins-for-the-year-for-2024/"><u>Updated Navigating Advanced Sound Design The Top 5 Most Innovative Ducking Plugins for the Year for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-top-10-budget-friendly-filmmaking-tools-for-indie-creators-for-2024/"><u>New Top 10 Budget-Friendly Filmmaking Tools for Indie Creators for 2024</u></a></li> <li><a href="https://extra-approaches.techidaily.com/new-premium-quality-computers-at-your-desk/"><u>[New] Premium Quality Computers at Your Desk</u></a></li> <li><a href="https://screen-sharing-recording.techidaily.com/new-in-2024-the-complete-screenrec-manual-for-laptops/"><u>[New] In 2024, The Complete ScreenRec Manual for Laptops</u></a></li> <li><a href="https://tiktok-videos.techidaily.com/beat-the-crowd-tiktok-hits-and-amazon-deals-to-know-for-2024/"><u>Beat the Crowd TikTok Hits and Amazon Deals to Know for 2024</u></a></li> <li><a href="https://extra-skills.techidaily.com/new-optimal-camcorders-transforming-podcast-engagement/"><u>[New] Optimal Camcorders Transforming Podcast Engagement</u></a></li> <li><a href="https://instagram-video-recordings.techidaily.com/updated-crafting-content-that-captivates-instagrams-roadmap-to-success-for-2024/"><u>[Updated] Crafting Content that Captivates Instagram’s Roadmap to Success for 2024</u></a></li> <li><a href="https://apple-account.techidaily.com/in-2024-how-to-fix-when-apple-account-locked-from-iphone-15-pro-by-drfone-ios/"><u>In 2024, How to Fix when Apple Account Locked From iPhone 15 Pro?</u></a></li> </ul></div>
--- title: "Gatekeeper" metaTitle: "Candy Machine Guards - Gatekeeper" description: "The Gatekeeper guard checks whether the minting wallet has a valid Gateway Token from a specified Gatekeeper Network." --- ## Overview The **Gatekeeper** guard checks whether the minting wallet has a valid **Gateway Token** from a specified **Gatekeeper Network**. In most cases, this token will be obtained after completing a Captcha challenge but any Gatekeeper Network may be used. There isn’t much to set up on the Candy Machine side but, depending on the selected Gatekeeper Network, you may need to ask the minting wallet to perform so pre-validation checks to grant them the required Gateway Token. Here are some additional recommended materials you may find helpful when setting up a Gatekeep Network. - [The CIVIC Documentation](https://docs.civic.com/civic-pass/overview) - [Gateway JS Library](https://www.npmjs.com/package/@identity.com/solana-gateway-ts) - [Gateway React Components](https://www.npmjs.com/package/@civic/solana-gateway-react) {% diagram %} {% node %} {% node #candy-machine label="Candy Machine" theme="blue" /%} {% node label="Owner: Candy Machine Core Program" theme="dimmed" /%} {% /node %} {% node parent="candy-machine" y="100" x="22" %} {% node #candy-guard label="Candy Guard" theme="blue" /%} {% node label="Owner: Candy Guard Program" theme="dimmed" /%} {% node #candy-guard-guards label="Guards" theme="mint" z=1/%} {% node #gatekeeper label="Gatekeeper" /%} {% node #gatekeeper-network label="- Gatekeeper Network" /%} {% node #expire label="- Expire on use" /%} {% node label="..." /%} {% /node %} {% node parent="gatekeeper" x="250" y="-17" %} {% node #request-token theme="indigo" %} Request Gateway Token from the Gatekeeper Network e.g. Captcha {% /node %} {% /node %} {% node parent="request-token" y="140" x="34" %} {% node #gateway-token theme="indigo" label="Gateway Token" /%} {% /node %} {% node parent="candy-machine" x="600" %} {% node #mint-candy-guard theme="pink" %} Mint from _Candy Guard Program_ {% /node %} {% /node %} {% node parent="mint-candy-guard" y="-20" x="100" theme="transparent" %} Access Control {% /node %} {% node parent="mint-candy-guard" y="150" x="-9" %} {% node #mint-candy-machine theme="pink" %} Mint from _Candy Machine Program_ {% /node %} {% /node %} {% node parent="mint-candy-machine" y="-20" x="140" theme="transparent" %} Mint Logic {% /node %} {% node #nft parent="mint-candy-machine" y="140" x="78" theme="blue" %} NFT {% /node %} {% edge from="mint-candy-machine" to="nft" path="straight" /%} {% edge from="candy-guard" to="candy-machine" /%} {% edge from="gatekeeper-network" to="request-token" /%} {% edge from="request-token" to="gateway-token" /%} {% edge from="gateway-token" to="mint-candy-guard" arrow="none" dashed=true /%} {% node theme="transparent" parent="mint-candy-guard" x="-210" %} if a valid token for the given Network and payer does not exist Minting will fail {% /node %} {% edge from="mint-candy-guard" to="mint-candy-machine" path="straight" /%} {% /diagram %} ## Guard Settings The Gatekeeper guard contains the following settings: - **Gatekeeper Network**: The public key of the Gatekeeper Network that will be used to check the validity of the minting wallet. For instance, you may use the "**Civic Captcha Pass**" Network — which ensures the minting wallet has passed a captcha — by using the following address: `ignREusXmGrscGNUesoU9mxfds9AiYTezUKex2PsZV6`. - **Expire On Use**: Whether we should mark the Gateway Token of the minting wallet as expired after the NFT has been minting. - When set to `true`, they will need to go through the Gatekeeper Network again to mint another NFT. - When set to `false`, they will be able to mint another NFT until the Gateway Token expires naturally. {% dialect-switcher title="Set up a Candy Machine using the Gatekeeper guard" %} {% dialect title="JavaScript" id="js" %} {% totem %} ```ts create(umi, { // ... guards: { gatekeeper: some({ network: publicKey("ignREusXmGrscGNUesoU9mxfds9AiYTezUKex2PsZV6"), expireOnUse: true, }), }, }); ``` API References: [create](https://mpl-candy-machine-js-docs.vercel.app/functions/create.html), [Gatekeeper](https://mpl-candy-machine-js-docs.vercel.app/types/Gatekeeper.html) {% /totem %} {% /dialect %} {% dialect title="Sugar" id="sugar" %} {% totem %} Add this object into the guard section your config.json file: ```json "gatekeeper" : { "gatekeeperNetwork": "<PUBKEY>", "expireOnUse": boolean } ``` {% /totem %} {% /dialect %} {% /dialect-switcher %} ## Mint Settings The Gatekeeper guard accepts the following mint settings: - **Gatekeeper Network**: The public key of the Gatekeeper Network that will be used to check the validity of the minting wallet. - **Expire On Use**: Whether we should mark the Gateway Token of the minting wallet as expired after the NFT has been minting. - **Token Account** (optional): As a little disclaimer, you should very rarely need to provide this setting but it’s here if you need to. This refers to the Gateway Token PDA derived from the payer and the Gatekeeper Network which is used to verify the payer's eligibility to mint. This PDA address can be inferred by our SDKs which is why you do not need to provide it. However, some Gatekeeper Networks may issue multiple Gateway Tokens to the same wallet. To differentiate their PDA addresses, it uses a **Seeds** array which defaults to `[0, 0, 0, 0, 0, 0, 0, 0]`. Note that, if you’re planning on constructing instructions without the help of our SDKs, you will need to provide these Mint Settings and more as a combination of instruction arguments and remaining accounts. See the [Candy Guard’s program documentation](https://github.com/metaplex-foundation/mpl-candy-machine/tree/main/programs/candy-guard#gatekeeper) for more details. {% dialect-switcher title="Mint with the Gatekeeper Guard" %} {% dialect title="JavaScript" id="js" %} {% totem %} You may pass the Mint Settings of the Gatekeeper guard using the `mintArgs` argument like so. ```ts mintV2(umi, { // ... mintArgs: { gatekeeper: some({ network: publicKey("ignREusXmGrscGNUesoU9mxfds9AiYTezUKex2PsZV6"), expireOnUse: true, }), }, }); ``` {% /totem %} {% /dialect %} {% dialect title="Sugar" id="sugar" %} {% totem %} _As soon as a guard is assigned you cannot use sugar to mint - therefore there are no specific mint settings._ {% /totem %} {% /dialect %} {% /dialect-switcher %} ## Route Instruction _The Gatekeeper guard does not support the route instruction._
<div align="center"> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/banner.png" width="100%" alt="Banner"> </div> # ✨ SheGuard SheGuard stands as the quintessential companion for women, ensuring their safety in every circumstance. Through its user-friendly features, it empowers you to swiftly alert your loved ones of your whereabouts and connect with emergency services effortlessly. ## Screenshots 📱 <div align="center"> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/onboarding.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/signin.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/signup.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/home.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/profile.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/edit_profile.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/contacts.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/helpline.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/safety_tips.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/settings.jpg" width="15%" /> <img src="https://github.com/Mahmud0808/SheGuard/blob/master/screenshots/about.jpg" width="15%" /> </div> ## Features 🔥 - **User Management:** - **Login and Registration:** Easy access for users. - **Safety Measures:** - **Live Location Sharing:** Instantly share your location with trusted contacts. - **Trusted Contacts:** Add up to 10 trusted contacts for quick access. - **User Notifications:** Alert contacts who are also SheGuard users via notifications. - **SMS Notifications:** Reach out to non-users via SMS notifications. - **Emergency Assistance:** - **Emergency Helplines:** Access important emergency contact numbers. - **Safety Tips:** Learn from a list of safety tips to stay secure. - **SOS Mode:** - **Shake Detection:** Trigger SOS mode with a simple shake gesture. - **Audible Alert:** Activate a loud siren to attract attention. - **Automatic Emergency Call:** Connect with emergency services instantly in SOS mode. ## Architecture 🗼 This app uses [***Firebase***](https://firebase.google.com/) services. ## Build-Tool 🧰 You need to have [Android Studio Giraffe or above](https://developer.android.com/studio) to build this project. ## Getting Started 🚀 - In Android Studio project, go to `Tools` > `Firebase` > `Authentication` > `Authenticate using a custom authentication system`: - First, `Connect to Firebase` - After that, `Add the Firebase Authentication SDK to your app` - Now open your project's [Firebase Console](https://console.firebase.google.com/) > `Authentication` > `Sign-in method`: - Enable `Email/Password` - Do not enable `Email link (passwordless sign-in)` - Enable [Cloud Messaging](https://console.cloud.google.com/apis/library/googlecloudmessaging.googleapis.com) API library - Enable [Token Service API](https://console.cloud.google.com/apis/library/securetoken.googleapis.com) - Again, Open your project's [Firebase Console](https://console.firebase.google.com/) > `Settings icon` (beside Project Overview) > `Users and permissions` > `Cloud Messaging`: - Copy the `Server Key` of Cloud Messaging API and paste it in [NotificationAPI.java](https://github.com/Mahmud0808/SheGuard/blob/master/app/src/main/java/com/android/sheguard/api/NotificationAPI.java) - That's it. Now you are good to go! ## Contact 📩 Wanna reach out to me? DM me at 👇 Email: mahmudul15-13791@diu.edu.bd ## Donation 💰 If this project help you reduce time to develop, you can give me a cup of coffee :) <a href="https://www.buymeacoffee.com/DrDisagree"><img src="https://github.com/Mahmud0808/Iconify/blob/beta/.github/resources/bmc-button.png" width="30%" alt="Buy me a coffee" /></a> ## Credits 🤝 - [icons8.com](https://icons8.com) for the in-app icons.
/* * SPDX-License-Identifier: GPL-3.0-only * MuseScore-CLA-applies * * MuseScore * Music Composition & Notation * * Copyright (C) 2021 MuseScore BVBA and others * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "read302.h" #include "global/defer.h" #include "iengravingfont.h" #include "rw/compat/compatutils.h" #include "style/style.h" #include "dom/audio.h" #include "dom/excerpt.h" #include "dom/factory.h" #include "dom/masterscore.h" #include "dom/part.h" #include "dom/score.h" #include "dom/scoreorder.h" #include "dom/spanner.h" #include "dom/staff.h" #include "dom/text.h" #include "../read400/staffrw.h" #include "../read400/tread.h" #include "../compat/readstyle.h" #include "log.h" using namespace mu; using namespace mu::engraving; using namespace mu::engraving::rw; using namespace mu::engraving::read400; using namespace mu::engraving::read302; using namespace mu::engraving::compat; bool Read302::readScore302(Score* score, XmlReader& e, ReadContext& ctx) { while (e.readNextStartElement()) { ctx.setTrack(mu::nidx); const AsciiStringView tag(e.name()); if (tag == "Staff") { read400::StaffRead::readStaff(score, e, ctx); } else if (tag == "Omr") { e.skipCurrentElement(); } else if (tag == "Audio") { score->m_audio = new Audio; read400::TRead::read(score->m_audio, e, ctx); } else if (tag == "showOmr") { e.skipCurrentElement(); } else if (tag == "playMode") { score->m_playMode = PlayMode(e.readInt()); } else if (tag == "LayerTag") { e.skipCurrentElement(); } else if (tag == "Layer") { e.skipCurrentElement(); } else if (tag == "currentLayer") { e.skipCurrentElement(); } else if (tag == "Synthesizer") { score->m_synthesizerState.read(e); } else if (tag == "page-offset") { score->m_pageNumberOffset = e.readInt(); } else if (tag == "Division") { score->m_fileDivision = e.readInt(); } else if (tag == "showInvisible") { score->m_showInvisible = e.readInt(); } else if (tag == "showUnprintable") { score->m_showUnprintable = e.readInt(); } else if (tag == "showFrames") { score->m_showFrames = e.readInt(); } else if (tag == "showMargins") { score->m_showPageborders = e.readInt(); } else if (tag == "markIrregularMeasures") { score->m_markIrregularMeasures = e.readInt(); } else if (tag == "Style") { double sp = score->style().value(Sid::spatium).toReal(); ReadStyleHook::readStyleTag(score, e); // if (_layoutMode == LayoutMode::FLOAT || _layoutMode == LayoutMode::SYSTEM) { if (score->layoutOptions().isMode(LayoutMode::FLOAT)) { // style should not change spatium in // float mode score->style().set(Sid::spatium, sp); } score->m_engravingFont = engravingFonts()->fontByName(score->style().styleSt(Sid::MusicalSymbolFont).toStdString()); } else if (tag == "copyright" || tag == "rights") { score->setMetaTag(u"copyright", Text::readXmlText(e, score)); } else if (tag == "movement-number") { score->setMetaTag(u"movementNumber", e.readText()); } else if (tag == "movement-title") { score->setMetaTag(u"movementTitle", e.readText()); } else if (tag == "work-number") { score->setMetaTag(u"workNumber", e.readText()); } else if (tag == "work-title") { score->setMetaTag(u"workTitle", e.readText()); } else if (tag == "source") { score->setMetaTag(u"source", e.readText()); } else if (tag == "metaTag") { String name = e.attribute("name"); score->setMetaTag(name, e.readText()); } else if (tag == "Order") { ScoreOrder order; order.read(e); if (order.isValid()) { score->setScoreOrder(order); } } else if (tag == "Part") { Part* part = new Part(score); read400::TRead::read(part, e, ctx); score->appendPart(part); } else if ((tag == "HairPin") || (tag == "Ottava") || (tag == "TextLine") || (tag == "Volta") || (tag == "Trill") || (tag == "Slur") || (tag == "Pedal")) { Spanner* s = toSpanner(Factory::createItemByName(tag, score->dummy())); read400::TRead::readItem(s, e, ctx); score->addSpanner(s); } else if (tag == "Excerpt") { if (MScore::noExcerpts) { e.skipCurrentElement(); } else { if (score->isMaster()) { MasterScore* mScore = static_cast<MasterScore*>(score); Excerpt* ex = new Excerpt(mScore); read400::TRead::read(ex, e, ctx); mScore->excerpts().push_back(ex); } else { LOGD("Score::read(): part cannot have parts"); e.skipCurrentElement(); } } } else if (e.name() == "Tracklist") { int strack = e.intAttribute("sTrack", -1); int dtrack = e.intAttribute("dstTrack", -1); if (strack != -1 && dtrack != -1) { ctx.tracks().insert({ strack, dtrack }); } e.skipCurrentElement(); } else if (tag == "Score") { // recursion if (MScore::noExcerpts) { e.skipCurrentElement(); } else { ctx.tracks().clear(); // ??? MasterScore* m = score->masterScore(); Score* s = m->createScore(); ReadStyleHook::setupDefaultStyle(s); Excerpt* ex = new Excerpt(m); ex->setExcerptScore(s); ctx.setLastMeasure(nullptr); Score* curScore = ctx.score(); ctx.setScore(s); ctx.setMasterCtx(&ctx); readScore302(s, e, ctx); ctx.setScore(curScore); s->linkMeasures(m); ex->setTracksMapping(ctx.tracks()); m->addExcerpt(ex); } } else if (tag == "name") { String n = e.readText(); if (!score->isMaster()) { //ignore the name if it's not a child score score->excerpt()->setName(n); } } else if (tag == "layoutMode") { String s = e.readText(); if (s == "line") { score->setLayoutMode(LayoutMode::LINE); } else if (s == "system") { score->setLayoutMode(LayoutMode::SYSTEM); } else { LOGD("layoutMode: %s", muPrintable(s)); } } else { e.unknown(); } } ctx.reconnectBrokenConnectors(); if (e.error() != XmlStreamReader::NoError) { if (e.error() == XmlStreamReader::CustomError) { LOGE() << e.errorString(); } else { LOGE() << String(u"XML read error at line %1, column %2: %3").arg(e.lineNumber(), e.columnNumber()) .arg(String::fromAscii(e.name().ascii())); } return false; } score->connectTies(); score->m_fileDivision = Constants::DIVISION; if (score->mscVersion() == 302) { // MuseScore 3.6.x scores had some wrong instrument IDs for (Part* part : score->parts()) { for (const auto& pair : part->instruments()) { fixInstrumentId(pair.second); } } } else { // Older scores had no IDs at all for (Part* part : score->parts()) { for (const auto& pair : part->instruments()) { pair.second->updateInstrumentId(); } } } score->setUpTempoMap(); for (Part* p : score->m_parts) { p->updateHarmonyChannels(false); } score->masterScore()->rebuildMidiMapping(); score->masterScore()->updateChannel(); for (Staff* staff : score->staves()) { staff->updateOttava(); } if (score->isMaster()) { CompatUtils::assignInitialPartToExcerpts(score->masterScore()->excerpts()); } return true; } Err Read302::readScore(Score* score, XmlReader& e, ReadInOutData* out) { ReadContext ctx(score); DEFER { if (out) { out->settingsCompat = std::move(ctx.settingCompat()); } }; while (e.readNextStartElement()) { const AsciiStringView tag(e.name()); if (tag == "programVersion") { score->setMscoreVersion(e.readText()); } else if (tag == "programRevision") { score->setMscoreRevision(e.readInt(nullptr, 16)); } else if (tag == "Score") { if (!readScore302(score, e, ctx)) { if (e.error() == XmlStreamReader::CustomError) { return Err::FileCriticallyCorrupted; } return Err::FileBadFormat; } } else if (tag == "Revision") { e.skipCurrentElement(); } } return Err::NoError; } void Read302::fixInstrumentId(Instrument* instrument) { String id = instrument->id(); String trackName = instrument->trackName().toLower(); // incorrect instrument IDs in 3.6.x if (id == u"Winds") { id = u"winds"; } else if (id == u"harmonica-d12high-g") { id = u"harmonica-d10high-g"; } else if (id == u"harmonica-d12f") { id = u"harmonica-d10f"; } else if (id == u"harmonica-d12d") { id = u"harmonica-d10d"; } else if (id == u"harmonica-d12c") { id = u"harmonica-d10c"; } else if (id == u"harmonica-d12a") { id = u"harmonica-d10a"; } else if (id == u"harmonica-d12-g") { id = u"harmonica-d10g"; } else if (id == u"drumset" && trackName == u"percussion") { id = u"percussion"; } else if (id == u"cymbal" && trackName == u"cymbals") { id = u"marching-cymbals"; } else if (id == u"bass-drum" && trackName == u"bass drums") { id = u"marching-bass-drums"; } instrument->setId(id); } bool Read302::pasteStaff(XmlReader&, Segment*, staff_idx_t, Fraction) { UNREACHABLE; return false; } void Read302::pasteSymbols(XmlReader&, ChordRest*) { UNREACHABLE; } void Read302::doReadItem(EngravingItem*, XmlReader&) { UNREACHABLE; }
import numpy as np import pytorch_lightning as pl from sklearn.model_selection import train_test_split from sklearn.datasets import make_blobs import torch from torch.utils.data import DataLoader, TensorDataset from scipy.stats import multivariate_normal import matplotlib.pyplot as plt class BlobDataModule(pl.LightningDataModule): def __init__( self, n_samples=1000, n_features=2, n_compoments=10, cluster_std=1, batch_size=128, seed=42, structured=True, radius=20, N=100, ood_data=False, omit_quadrant=False ): super().__init__() self.save_hyperparameters() np.random.seed(seed) def prepare_data(self): if self.hparams.structured: self.__make_structured_blobs() else: self.X, self.y = make_blobs( n_samples=self.hparams.n_samples, n_features=self.hparams.n_features, centers=self.hparams.n_compoments, cluster_std=self.hparams.cluster_std, random_state=self.hparams.seed ) if self.hparams.ood_data: self.__make_ood_circle() def setup(self, stage=None): self.__setup() def __setup(self, ova_num=-1): # 80/20 split # train_X, test_X, train_y, test_y = train_test_split(self.X, self.y, test_size=0.2, stratify=self.y, random_state=self.hparams.seed) if self.hparams.ood_data: if self.hparams.omit_quadrant: ff = np.logical_or(self.X_ood[:, 0] > 0, self.X_ood[:, 1] > 0) self.X_ood = self.X_ood[ff] self.y_ood = self.y_ood[ff] self.X = np.concatenate((self.X, self.X_ood), axis=0) self.y = np.concatenate((self.y, self.y_ood), axis=0) train_X, train_y = self.X, self.y if ova_num >= 0: # OVA relabeling func = np.vectorize(lambda x: 1 if x == ova_num else 0) train_y = func(train_y) # test_y = func(test_y) # OVA undersampling n_minority_samples = train_y.sum() idx_negative_samples = np.where(train_y == 0)[0] idx_positive_samples = np.where(train_y == 1)[0] idx_chosen_samples = np.random.choice( idx_negative_samples, n_minority_samples) idx_samples = np.concatenate( (idx_chosen_samples, idx_positive_samples)) train_X, train_y = train_X[idx_samples], train_y[idx_samples] # Create datasets: self.train_dataset = TensorDataset( torch.FloatTensor(train_X), torch.LongTensor(train_y)) # self.test_dataset = TensorDataset(torch.FloatTensor(test_X), torch.LongTensor(test_y)) def add_ova_filter(self, ova_num): self.__setup(ova_num) def filter_out(self, ova_num): # Aims to filter out all images which do not belong to the positive # class of the current OVA model/ova_num train_X, train_y = self.X, self.y func = np.vectorize(lambda x: x if x == ova_num else -1) train_y = func(train_y) idx_positive_samples = np.where(train_y == ova_num)[0] train_X, train_y = train_X[idx_positive_samples], train_y[idx_positive_samples] self.train_dataset = TensorDataset( torch.FloatTensor(train_X), torch.LongTensor(train_y)) def get_data(self): return (self.X, self.y) def train_dataloader(self, shuffle=True): return DataLoader( self.train_dataset, batch_size=self.hparams.batch_size, num_workers=4, shuffle=shuffle) def test_dataloader(self): return DataLoader( self.train_dataset, batch_size=self.hparams.batch_size, num_workers=4, shuffle=False) def __make_structured_blobs(self): r = self.hparams.radius N = self.hparams.N clusters = self.hparams.n_compoments step = N // clusters samples = self.hparams.n_samples theta = np.linspace(0, 2 * np.pi, N) a = r * np.cos(theta) b = r * np.sin(theta) X = [] y = [] i = 0 while i * step < N: means = (a[i * step], b[i * step]) cov = [[1, 0], [0, 1]] X.append( np.random.multivariate_normal( means, cov, samples).squeeze()) y.append(np.repeat(i, samples)) i += 1 self.X = np.stack(X).reshape(-1, 2) self.y = np.stack(y).reshape(-1) def __make_ood_circle(self): r = self.hparams.radius * 2.5 N = 100 samples = 10 theta = np.linspace(0, 2 * np.pi, N) a = r * np.cos(theta) b = r * np.sin(theta) X_ood = [] y_ood = [] for _a, _b in zip(a, b): means = (_a, _b) cov = [[10, 0], [0, 10]] X_ood.append( np.random.multivariate_normal( means, cov, samples).squeeze()) y_ood.append(np.repeat(10, samples)) self.X_ood = np.stack(X_ood).reshape(-1, 2) self.y_ood = np.stack(y_ood).reshape(-1)