text stringlengths 184 4.48M |
|---|
source("scripts/00-setup.R")
source("../post_GAN_functions.R")
gaussian_df_z <- as.matrix(read.csv("gan-input/gaussian_df_z.csv"))
# Define function that generates data from all four approaches
# directly from the stored weights
gen_synth_25_gaussians <-
function(dp = T,
nmp = 2.165,
mb = 50,
l2clip = 1,
Z_dim = 25,
n_generators = 50,
steps = 100,
MW_epsilon = 0.1,
last_model_PGB = 12250,
last_model_GAN = 19000,
n_samples = 2500,
window = NULL,
MW_init = F,
run = 1,
GPU = 0L,
data = gaussian_df_z) {
require(tensorflow)
require(zeallot)
require(reticulate)
if (dp) {
model_path <-
paste0("models/run", run, "/nmp-", nmp, "-mb-", mb, "-l2clip-", l2clip, "/toy-example-")
} else {
model_path <- paste0("models/run",run,"/nodp/toy-example-")
}
tf$reset_default_graph()
config <- tf$ConfigProto(device_count = list('GPU' = GPU))
sess <- tf$Session(config = config)
# Load meta graph and restore weights
saver <-
tf$train$import_meta_graph(paste0(model_path, last_model_PGB, ".meta"))
ids <- c(1:last_model_PGB)[(1:last_model_PGB %% 5 == 0)][]
last_ids <- ids[(length(ids) - (n_generators - 1)):length(ids)]
graph <- tf$get_default_graph()
# Recreate Generator weights and Generator
G_W1 = graph$get_tensor_by_name("G_W1:0")
G_b1 = graph$get_tensor_by_name("G_b1:0")
G_W1_1 = graph$get_tensor_by_name("G_W1_1:0")
G_b1_1 = graph$get_tensor_by_name("G_b1_1:0")
G_W1_2 = graph$get_tensor_by_name("G_W1_2:0")
G_b1_2 = graph$get_tensor_by_name("G_b1_2:0")
G_W2 = graph$get_tensor_by_name("G_W2:0")
G_b2 = graph$get_tensor_by_name("G_b2:0")
generator <- function(z) {
G_h1 = tf$nn$leaky_relu(tf$matmul(Z, G_W1) + G_b1)
G_h1 = tf$nn$dropout(G_h1, rate = 0.5)
G_h1_1 = tf$nn$leaky_relu(tf$matmul(G_h1, G_W1_1) + G_b1_1)
G_h1_1 = tf$nn$dropout(G_h1_1, rate = 0.5)
G_h1_2 = tf$nn$leaky_relu(tf$matmul(G_h1_1, G_W1_2) + G_b1_2)
G_h1_2 = tf$nn$dropout(G_h1_2, rate = 0.5)
G_log_prob = tf$matmul(G_h1_2, G_W2) + G_b2
G_prob = G_log_prob
return(G_prob)
}
Z = tf$placeholder(tf$float32, shape = list(NULL, Z_dim))
G_sample <- generator(Z)
sample_Z <- function(m, n) {
matrix(rnorm(m * n), nrow = m, ncol = n)
}
X = tf$placeholder(tf$float32, shape = list(NULL, ncol(data)))
# Recreate Discriminator weights and Discriminator
D_W1 = graph$get_tensor_by_name("D_W1:0")
D_b1 = graph$get_tensor_by_name("D_b1:0")
D_W1_1 = graph$get_tensor_by_name("D_W1_1:0")
D_b1_1 = graph$get_tensor_by_name("D_b1_1:0")
D_W1_2 = graph$get_tensor_by_name("D_W1_2:0")
D_b1_2 = graph$get_tensor_by_name("D_b1_2:0")
D_W2 = graph$get_tensor_by_name("D_W2:0")
D_b2 = graph$get_tensor_by_name("D_b2:0")
discriminator <- function(x) {
D_h1 = tf$nn$leaky_relu(tf$matmul(x, D_W1) + D_b1)
D_h1_1 = tf$nn$leaky_relu(tf$matmul(D_h1, D_W1_1) + D_b1_1)
D_h1_2 = tf$nn$leaky_relu(tf$matmul(D_h1_1, D_W1_2) + D_b1_2)
D_logit = tf$matmul(D_h1_2, D_W2) + D_b2
D_prob = tf$nn$sigmoid(D_logit)
return(list(D_prob, D_logit))
}
c(D_real, D_logit_real) %<-% discriminator(X)
c(D_fake, D_logit_fake) %<-% discriminator(G_sample)
D_loss_real <-
tf$nn$sigmoid_cross_entropy_with_logits(logits = D_logit_real,
labels = tf$ones_like(D_logit_real))
D_loss_fake <-
tf$nn$sigmoid_cross_entropy_with_logits(logits = D_logit_fake,
labels = tf$ones_like(D_logit_fake))
vector_D_loss <- D_loss_real + D_loss_fake
D_loss <- tf$reduce_mean(vector_D_loss)
# Now create samples and from the last generators
runs <- last_ids
# Number of total samples drawn across all generators
total_samples <- n_samples * length(runs)
# Empty matrix to hold the discriminator scores of fake data from each discriminator
D_m_fake <-
matrix(NA, nrow = length(runs), ncol = total_samples)
# Empty object to get discriminator scores on real data from each discriminator
D_m_real <- NULL
# Empty object to hold the samples from each generator (B in the paper)
sample_G_m <- NULL
# Loop over last runs and append sample_G_m = B
for (i in runs) {
saver$restore(sess, paste0(model_path, i))
sample_G_m <-
rbind(sample_G_m, sess$run(G_sample, feed_dict = dict(Z = sample_Z(
n_samples, Z_dim
))))
}
for (i in runs) {
sel <- runs == i
saver$restore(sess, paste0(model_path, i))
tmp_mean <- mean(sess$run(D_real, feed_dict = dict(X = data)))
D_m_real <- c(D_m_real, tmp_mean)
D_m_fake[sel, ] <-
sess$run(D_real, feed_dict = dict(X = sample_G_m))
cat(which(sel), "\n")
}
# Sample from last Generator (for comparison)
# Sample from last Generator
saver$restore(sess, paste0(model_path, last_model_GAN))
# Sample 50,000 examples from last Generator for DRS to work
sample <-
sess$run(G_sample, feed_dict = dict(Z = sample_Z(50000, Z_dim)))
# Get Discriminator scores of sample for DRS
last_D <- sess$run(D_real, feed_dict = dict(X = sample))
# Get DRS sample indices
sample_sel <- rejection_sample(last_D)
# Subset last Generator sample to DRS sample
o_DRS <- sample[sample_sel, ]
# Get post-GAN Boosting sample and Discriminator scores
c(sample_PGB, D_PGB) %<-% post_gan_boosting(d_score_fake = D_m_fake,
d_score_real = D_m_real,
B = sample_G_m,
real_N = nrow(data),
steps = steps,
MW_epsilon = MW_epsilon,
N_generators = length(runs),
averaging_window = window)
shuf_sel <- sample(length(D_PGB), length(D_PGB))
D_PGB_shuf <- D_PGB[shuf_sel]
sample_sel <- rejection_sample(D_PGB)
sample_PGB_DRS <- sample_PGB[sample_sel, ]
colnames(sample_PGB) <- colnames(data)
colnames(sample_PGB_DRS) <- colnames(data)
colnames(sample) <- colnames(data)
colnames(o_DRS) <- colnames(data)
sess$close()
return(
list(
sample = sample,
o_DRS = o_DRS,
sample_MW = sample_PGB,
sample_DRS = sample_PGB_DRS
)
)
}
# Set number of PGB steps
steps <- 400
# Get results with Privacy
res_dp <-
gen_synth_25_gaussians(
dp = T,
nmp = 1.5,
mb = 50,
l2clip = 1,
Z_dim = 32,
n_generators = 200,
steps = steps,
MW_epsilon = 0.199662,
last_model_PGB = 12250,
last_model_GAN = 19000,
n_samples = 2000,
window = NULL,
MW_init = F,
run = 16
)
# Save results for summarizing later
saveRDS(res_dp, "synthetic-output/res_dp.RDS")
# Get results without privacy
res_nodp <-
gen_synth_25_gaussians(
dp = F,
Z_dim = 32,
n_generators = 200,
steps = steps,
last_model_PGB = 10000,
last_model_GAN = 10000,
n_samples = 2000,
window = NULL,
MW_init = F,
run = 16
)
# Save results for summarizing
saveRDS(res_nodp, "synthetic-output/res_nodp.RDS") |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import './IRenovaAvatarBase.sol';
/// @title IRenovaAvatarSatellite
/// @author Victor Ionescu
/// @notice See {IRenovaAvatarBase}
/// @dev Deployed on the satellite chain.
interface IRenovaAvatarSatellite is IRenovaAvatarBase {
/// @notice Emitted when an Avatar is minted from a cross-chain call.
/// @param player The owner of the Avatar.
/// @param faction The faction of the Avatar.
/// @param characterId The Character ID of the Avatar.
/// @param srcWormholeChainId The source chain that minted the Avatar.
event XChainMintIn(
address indexed player,
RenovaFaction faction,
uint256 characterId,
uint16 srcWormholeChainId
);
/// @notice Initializer function.
/// @param renovaCommandDeck The Renova Command Deck.
/// @param wormhole The Wormhole Endpoint. See {IWormholeBaseUpgradeable}.
/// @param wormholeConsistencyLevel The Wormhole Consistency Level. See {IWormholeBaseUpgradeable}.
function initialize(
address renovaCommandDeck,
address wormhole,
uint8 wormholeConsistencyLevel
) external;
/// @notice Mints an Avatar on a satellite chain, via Wormhole.
/// @param vaa The Wormhole VAA.
function wormholeMintReceive(bytes memory vaa) external;
} |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import generics
from .serializers import *
from .models import *
from rest_framework.response import Response
from rest_framework import permissions
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
class TeacherList(generics.ListCreateAPIView):
queryset = Teacher.objects.all()
serializer_class = TeacherSerializers
# permission_classes = [permissions.IsAuthenticated]
class TeacherDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Teacher.objects.all()
serializer_class = TeacherSerializers
@csrf_exempt
def teacher_login(request):
email = request.POST['email']
password = request.POST['password']
try:
teacherData = Teacher.objects.get(email=email, password=password)
except Teacher.DoesNotExist:
teacherData=None
if teacherData:
return JsonResponse ({'bool':True, 'teacher_id':teacherData.id})
else :
return JsonResponse ({'bool':False})
class CategoryList(generics.ListCreateAPIView):
queryset = CourseCategory.objects.all()
serializer_class = CategoryListSerializers
class CourseList(generics.ListCreateAPIView):
queryset = Course.objects.all()
serializer_class = CourseSerializers
class TeacherCourseList(generics.ListCreateAPIView):
serializer_class = CourseSerializers
def get_queryset(self):
teacher_id = self.kwargs['teacher_id']
teacher = Teacher.objects.get(pk=teacher_id)
return Course.objects.filter(teacher=teacher)
class ChapterList(generics.ListCreateAPIView):
queryset = Chapter.objects.all()
serializer_class = ChapterSerializers
class CourseChapterList(generics.ListAPIView):
serializer_class = ChapterSerializers
def get_queryset(self):
course_id = self.kwargs['course_id']
course = Course.objects.get(pk=course_id)
return Chapter.objects.filter(course=course)
class ChapterDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Chapter.objects.all()
serializer_class = ChapterSerializers |
package Deck;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.*;
import ulb.infof307.g02.models.Deck;
import ulb.infof307.g02.models.DeckTable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class DeckTableTest {
private DeckTable deckTable;
@BeforeEach
public void setUp() {
this.deckTable = new DeckTable();
}
@Test
public void testAddDeck() {
Deck deck = new Deck("Deck1", "test");
deckTable.addDeck(deck);
List<Deck> table = deckTable.getTable();
Deck loadedDeck1 = table.get(0);
assertEquals("Deck1", loadedDeck1.getName());
assertEquals("test", loadedDeck1.getCategory());
assertEquals(1, table.size());
assertEquals(deck, table.get(0));
}
@Test
public void testDeleteDeck() {
Deck deck = new Deck("Deck1", "test");
deckTable.addDeck(deck);
assertEquals(1, deckTable.getTable().size());
assertDoesNotThrow(() -> deckTable.deleteDeck(deck));
assertEquals(0, deckTable.getTable().size());
assertFalse(new File("DecksData/Deck1").exists());
}
@Test
public void testSaveDeck() {
Deck deck = new Deck("Deck1","test");
deckTable.addDeck(deck);
assertDoesNotThrow(() -> deckTable.saveDeck(deck));
assertTrue(new File("DecksData/Deck1.txt").exists());
}
@Test
void testLoadDecks() {
// Créez une instance de votre classe qui contient la méthode `loadDecks()`
DeckTable deckTable = new DeckTable();
assertDoesNotThrow(deckTable::loadDecks);
assertFalse(deckTable.getTable().isEmpty(), "Table should not be empty after loading decks");
// Effectuez d'autres vérifications en fonction de vos besoins et de vos attentes
}
@Test
public void testSaveTable() {
Deck deck1 = new Deck("Deck1", "test");
deckTable.addDeck(deck1);
Deck deck2 = new Deck("Deck2", "test");
deckTable.addDeck(deck2);
// Test avec des decks valides
assertDoesNotThrow(() -> deckTable.saveTable());
assertTrue(new File("DecksData/Deck1.txt").exists());
assertTrue(new File("DecksData/Deck2.txt").exists());
}
} |
#include "variadic_functions.h"
#include <stdio.h>
/**
* print_strings - function that prints String
* @separator: tring to be printed
* @n: number of strings
*
* Return: ...
*/
void print_strings(const char *separator, const unsigned int n, ...)
{
va_list args;
unsigned int i;
char *string;
va_start(args, n);
for (i = 0; i < n; i++)
{
string = va_arg(args, char*);
if (string == NULL)
{
printf("(nil)");
}
else
{
printf("%s", string);
}
if (separator != NULL && i != n - 1)
{
printf("%s", separator);
}
}
va_end(args);
printf("\n");
} |
# Border Filter
<!--
@name: Border Filter
@description:
@tags:
@categories:
\-->
Define and add a border filter
## Syntax
**Border Filter** *filterName$, value1, value2, value3, value4*
## Parameters
**filterName$**: Name of the filter to use (see list)
**value1**: First value to use, a percentage or a number of pixels, depending on the filter
**value2**: Second value to use, a number of pixels, only used on drop-shadow filter
**value3**: Third value to use, the blur value, only used on drop-shadow filter
**value4**: Fourth value to use, $RRGGBBAA or $RRGGBB color value, only used on drop-shadow filter
## Description
This instruction applies one of the filters listed below to any borders that are subsequently drawn around shapes or texts.
The name, so the effect of the filter is specified in the first parameter, filterName$, and can be one of the following list, along with the first, second third and fourth parameter, which and type depend on the filter itself.
### Parameter Requirements
|**Filter**|**Description**|
|---|---|
|**Border Filter** *"blur", value1#* | Applies a Gaussian blur to the border. The parameter defines the value of the standard deviation to the Gaussian function, i.e., how many pixels on the screen blend into each other, thus, a larger value will create more blur. A value of 0 leaves the input unchanged.|
|**Border Filter** *"brightness", value1* | Applies a linear multiplier to the border, making it appear brighter or darker. A value under 100% darkens the image, while a value over 100% brightens it. A value of 0% will create an image that is completely black, while a value of 100% leaves the input unchanged.|
|**Border Filter** *"contrast", value1* | Adjusts the contrast of the border. A value of 0% will create a drawing that is completely black. A value of 100% leaves the drawing unchanged.|
|**Border Filter** *"grayscale", value1* | Converts the border to grayscale. A value of 100% is completely grayscale. A value of 0% leaves the drawing unchanged.|
|**Border Filter** *"hue-rotate", value1* | Applies a hue rotation to the border. The value is expressed in degrees. 0 leaves the input unchanged.|
| **Border Filter** *"invert", value1* | Inverts the border. A value of 100% means complete inversion. A value of 0% leaves the drawing unchanged.|
|**Border Filter** *"opacity", value1* | Applies transparency to the screen. A value of 0% means completely transparent. A value of 100% leaves the drawing unchanged.
|**Border Filter** *"saturate", value* | Saturates the screen. A value of 0% means completely un-saturated. A value of 100% leaves the drawing unchanged.
|**Border Filter** *"sepia", value1* | Converts the border to sepia. A value of 100% means completely sepia. A value of 0% leaves the drawing unchanged.|
| **Border Filter** *"drop-shadow", value1, value2, value3, value4* | Applies a drop shadow effect to the drawing. A drop shadow is effectively a blurred, offset version of the drawing|;s alpha mask drawn in a particular color, composited below the drawing.
Multiple filters can be used at the same time. For example, it is possible to display a blurred sepia version of a circle, with two Border Filter instructions before the actual drawing. Use Border Filter Del to remove one or all filters.
Please note that like every complex graphical operation, Filters will slow down the display or the drawing,
specially complex filters like blur or drop-shadows. It is suggested to only use filters at key points, or
key graphics of your application and not everywhere.
## Example Code
This example draws three red circles with white borders, the first without any filters, the second with a blur filter applied, and the third with the blur filter and Border First turned on. Note that because the border is drawn first, the blurring of the border doesn|;t cover the third circle.
```basic
ink 6
border on
border ink 1 : colour 1,$5050a0
line width 40
Circle 600,540,300,1
Border Filter "drop-shadow",20,20,10,$ffffff60
border filter "invert",100
Circle 1320,540,300,1
```
<p align="center"><img valign="middle" width="76px" src="https://doc.aoz.studio/assets/images/en/image001.png" /></p>
<!--stackedit_data:
eyJoaXN0b3J5IjpbMTY0MzkyOTM5NCw5MTYyMDc1MDMsMzUxNT
QyNzUyLC00NDM1NjI4NzksLTExNjU4NDQzMjIsLTExNTAxMjU0
MjIsMTE0MTc5MzkwNiwtMjA5NDQ3MTY4NSwxNzc4OTg4ODIyLC
03MTM5Njc0MDNdfQ==
--> |
import { createAsyncThunk } from '@reduxjs/toolkit'
import axiosInstance from '../../axiosInstance'
import request from "axios";
import { setToast } from "../toast/toastSlice";
interface IPagination {
page: number;
limit: number;
searchText?:string;
}
interface ICartProduct {
_id: string;
title: string;
writer: string;
tag: string;
coverImage: string;
points: number;
amount: number;
}
export const fetchProduct = createAsyncThunk(
'/fetchProduct',
async ({page, limit, searchText = ''}: IPagination) => {
try {
const response = await axiosInstance.get(`/books?page=${page}&limit=${limit}&search=${searchText}`);
return { data : response.data, page: page }
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
);
export const addProductToCart = createAsyncThunk(
'/addProductToCart',
async (data:any) => {
try {
return data
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
);
export const decreaseProduct = createAsyncThunk(
'/decreaseProduct',
async (data:any) => {
try {
return data
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
);
export const increaseProduct = createAsyncThunk(
'/increaseProduct',
async (data:any) => {
try {
return data
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
);
export const orderCheckout = createAsyncThunk(
'/orderCheckout',
async (data:any, { dispatch }) => {
try {
const response = await axiosInstance.post(`/orders`, data);
if (!response.data.isCancel) {
dispatch(setToast({ visible: true, message: 'Order Placed Successfully !', type: 'success' }));
}
return response.data;
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
);
export const getOrder = createAsyncThunk(
'/getOrder',
async ({page, limit}: IPagination) => {
try {
const response = await axiosInstance.get(`/orders?page=${page}&limit=${limit}`);
return { data : response.data, page: page }
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
);
export const removeProductFromCart = createAsyncThunk(
'/removeProductFromCart',
async (item:any) => {
try {
return item
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
);
export const cancelOrder = createAsyncThunk(
'/cancelOrder',
async (data:string, { dispatch }) => {
try {
const response = await axiosInstance.get(`/orders/cancel/${data}`);
if (response.data.isCancel) {
dispatch(setToast({ visible: true, message: 'Order Cancelled !', type: 'success' }));
}
return response.data;
} catch (e) {
if (request.isAxiosError(e) && e.response) {
throw new Error(e.response.data.message)
}
}
},
); |
package dev.jason.harmony.slashcommands.general;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.command.SlashCommand;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import com.jagrosh.jdautilities.doc.standard.CommandInfo;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDAInfo;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.ApplicationInfo;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.util.Objects;
@CommandInfo(
name = "ÀPropos",
description = "Affiche des informations sur le bot"
)
public class CommandeAPropos extends SlashCommand {
private final Color couleur;
private final String description;
private final Permission[] perms;
private final String[] fonctionnalites;
private boolean EST_AUTEUR = true;
private String ICONE_REMPLACEMENT = "+";
private String lienOAuth;
public CommandeAPropos(Color couleur, String description, String[] fonctionnalites, Permission... perms) {
this.couleur = couleur;
this.description = description;
this.fonctionnalites = fonctionnalites;
this.name = "apropos";
this.help = "Affiche des informations sur le bot";
this.aliases = new String[]{"about", "info", "botinfo"};
this.guildOnly = false;
this.perms = perms;
this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS};
}
public void setEstAuteur(boolean value) {
this.EST_AUTEUR = value;
}
public void setCaractereRemplacement(String value) {
this.ICONE_REMPLACEMENT = value;
}
@Override
protected void execute(SlashCommandEvent event) {
if (lienOAuth == null) {
try {
ApplicationInfo info = event.getJDA().retrieveApplicationInfo().complete();
lienOAuth = info.isBotPublic() ? info.getInviteUrl(0L, perms) : "";
} catch (Exception e) {
Logger log = LoggerFactory.getLogger("OAuth2");
log.error("Échec de la génération du lien d'invitation ", e);
lienOAuth = "";
}
}
EmbedBuilder builder = new EmbedBuilder();
builder.setColor(event.getGuild() == null ? couleur : event.getGuild().getSelfMember().getColor());
builder.setAuthor(event.getJDA().getSelfUser().getName() + " Informations sur Harmony", null, event.getJDA().getSelfUser().getAvatarUrl());
String proprietaire = "Développé par Jason54.";
String auteur = event.getJDA().getUserById(event.getClient().getOwnerId()) == null ? "<@" + event.getClient().getOwnerId() + ">"
: Objects.requireNonNull(event.getJDA().getUserById(event.getClient().getOwnerId())).getName();
StringBuilder descr = new StringBuilder().append("Bonjour ! Je suis **").append(event.getJDA().getSelfUser().getName()).append("**, ")
.append(description).append(" J'utilise la [bibliothèque JDA](https://github.com/DV8FromTheWorld/JDA) (")
.append(JDAInfo.VERSION).append(") et appartient à ").append((EST_AUTEUR ? proprietaire : auteur + "."))
.append(" Pour toute question concernant le bot, rendez-vous sur [le canal officiel](https://discord.gg/Fpm9qvKbbV).")
.append("\nPour savoir comment utiliser ce bot, tapez `").append("/help")
.append("` pour obtenir de l'aide. \n\nFonctionnalités : ```css");
for (String fonctionnalite : fonctionnalites)
descr.append("\n").append(event.getClient().getSuccess().startsWith("<") ? ICONE_REMPLACEMENT : event.getClient().getSuccess()).append(" ").append(fonctionnalite);
descr.append(" ```");
builder.setDescription(descr);
if (event.getJDA().getShardInfo().getShardTotal() == 1) {
builder.addField("Statut", event.getJDA().getGuilds().size() + " Serveur\n1 Shard", true);
builder.addField("Utilisateurs", event.getJDA().getUsers().size() + " Unique\n" + event.getJDA().getGuilds().stream().mapToInt(g -> g.getMembers().size()).sum() + " total", true);
builder.addField("Canaux", event.getJDA().getTextChannels().size() + " Texte\n" + event.getJDA().getVoiceChannels().size() + " Voix", true);
} else {
builder.addField("Statut", (event.getClient()).getTotalGuilds() + " Serveur\n Shard" + (event.getJDA().getShardInfo().getShardId() + 1)
+ "/" + event.getJDA().getShardInfo().getShardTotal(), true);
builder.addField("", event.getJDA().getUsers().size() + " Fragment de l'utilisateur\n" + event.getJDA().getGuilds().size() + " Serveur", true);
builder.addField("", event.getJDA().getTextChannels().size() + " canaux de texte\n" + event.getJDA().getVoiceChannels().size() + " canaux vocaux", true);
}
builder.setFooter("Dernier redémarrage", null);
builder.setTimestamp(event.getClient().getStartTime());
event.replyEmbeds(builder.build()).queue();
}
@Override
protected void execute(CommandEvent event) {
if (lienOAuth == null) {
try {
ApplicationInfo info = event.getJDA().retrieveApplicationInfo().complete();
lienOAuth = info.isBotPublic() ? info.getInviteUrl(0L, perms) : "";
} catch (Exception e) {
Logger log = LoggerFactory.getLogger("OAuth2");
log.error("Échec de la génération du lien d'invitation ", e);
lienOAuth = "";
}
}
EmbedBuilder builder = new EmbedBuilder();
builder.setColor(event.isFromType(ChannelType.TEXT) ? event.getGuild().getSelfMember().getColor() : couleur);
builder.setAuthor(event.getSelfUser().getName() + " Informations sur Harmony", null, event.getSelfUser().getAvatarUrl());
String proprietaire = "Développé par Jason54.";
String auteur = event.getJDA().getUserById(event.getClient().getOwnerId()) == null ? "<@" + event.getClient().getOwnerId() + ">"
: Objects.requireNonNull(event.getJDA().getUserById(event.getClient().getOwnerId())).getName();
StringBuilder descr = new StringBuilder().append("Bonjour ! Je suis **").append(event.getJDA().getSelfUser().getName()).append("**, ")
.append(description).append(" J'utilise la [bibliothèque JDA](https://github.com/DV8FromTheWorld/JDA) (")
.append(JDAInfo.VERSION).append(") et appartient à ").append((EST_AUTEUR ? proprietaire : auteur + "."))
.append(" Pour toute question concernant le bot, rendez-vous sur [le canal officiel](https://discord.gg/Fpm9qvKbbV).")
.append("\nPour savoir comment utiliser ce bot, tapez `").append("/help")
.append("` pour obtenir de l'aide. \n\nFonctionnalités : ```css");
for (String fonctionnalite : fonctionnalites)
descr.append("\n").append(event.getClient().getSuccess().startsWith("<") ? ICONE_REMPLACEMENT : event.getClient().getSuccess()).append(" ").append(fonctionnalite);
descr.append(" ```");
builder.setDescription(descr);
if (event.getJDA().getShardInfo().getShardTotal() == 1) {
builder.addField("Statut", event.getJDA().getGuilds().size() + " Serveur\n1 Shard", true);
builder.addField("Utilisateurs", event.getJDA().getUsers().size() + " Unique\n" + event.getJDA().getGuilds().stream().mapToInt(g -> g.getMembers().size()).sum() + " total", true);
builder.addField("Canaux", event.getJDA().getTextChannels().size() + " Texte\n" + event.getJDA().getVoiceChannels().size() + " Voix", true);
} else {
builder.addField("Statut", (event.getClient()).getTotalGuilds() + " Serveur\n Shard" + (event.getJDA().getShardInfo().getShardId() + 1)
+ "/" + event.getJDA().getShardInfo().getShardTotal(), true);
builder.addField("", event.getJDA().getUsers().size() + " Fragment de l'utilisateur\n" + event.getJDA().getGuilds().size() + " Serveur", true);
builder.addField("", event.getJDA().getTextChannels().size() + " canaux de texte\n" + event.getJDA().getVoiceChannels().size() + " canaux vocaux", true);
}
builder.setFooter("Dernier redémarrage", null);
builder.setTimestamp(event.getClient().getStartTime());
event.reply(builder.build());
}
} |
package com.example.perfumeshop.data.utils
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.example.perfumeshop.R
import kotlin.math.round
fun Context.showToast(stringId : Int, duration: Int = Toast.LENGTH_SHORT){
val toast = Toast.makeText(this, this.getString(stringId), duration)
toast.show()
}
fun Context.showToast(message: String, duration: Int = Toast.LENGTH_SHORT){
val toast = Toast.makeText(this, message, duration)
toast.show()
}
fun isUserConnected(ctx: Context) : Boolean {
val hasInternet: Boolean
val connectivityManager =
ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
hasInternet = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
hasInternet = try {
if (connectivityManager.activeNetworkInfo == null) {
false
} else {
connectivityManager.activeNetworkInfo?.isConnected!!
}
} catch (e: Exception) {
false
}
}
return hasInternet
}
@Composable
fun Context.getWidthPercent(): Dp {
val displayMetrics = this.resources.displayMetrics
return ((displayMetrics.widthPixels / displayMetrics.density) / 100).dp
}
@Composable
fun Context.getHeightPercent(): Dp {
val displayMetrics = this.resources.displayMetrics
return ((displayMetrics.heightPixels / displayMetrics.density) / 100).dp
}
fun Double.round(decimals: Int): Double {
var multiplier = 1.0
repeat(decimals) { multiplier *= 10 }
return round(this * multiplier) / multiplier
}
fun Float.round(decimals: Int): Float {
var multiplier = 1.0f
repeat(decimals) { multiplier *= 10 }
return round(this * multiplier) / multiplier
}
@Composable
fun <T : Any> rememberSavableMutableStateList(vararg elements : T) : SnapshotStateList<T>{
return rememberSaveable(
saver = listSaver(
save = { stateList ->
if (stateList.isNotEmpty()) {
val first = stateList.first()
if (!canBeSaved(first)) {
throw IllegalStateException("${first::class} cannot be saved. By default only types which can be stored in the Bundle class can be saved.")
}
}
stateList.toList()
},
restore = { it.toMutableStateList() }
)
) {
elements.toList().toMutableStateList()
}
}
fun String.firstLetterToUpperCase() : String {
if (this.isEmpty()) return ""
val firstLetter = this.first().uppercase()
return firstLetter + this.substring(1)
}
fun String.allFirstLettersToUpperCase() : String {
return this.split(" ").joinToString(separator = " "){ it.firstLetterToUpperCase() }
}
fun String.toBrandFormat(defaultValue: String = this) : String {
val rusAlphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
var lastItem = ""
val items = this.split(" ")
items.forEach { item ->
if ((item.toCharArray().any{ ch -> ch in rusAlphabet } ||
item.contains("(") || item.contains(")") || item.contains("ml", true)) && lastItem.isEmpty()) {
lastItem = item
}
}
if (lastItem.isEmpty()) return defaultValue.allFirstLettersToUpperCase()
val lastInd = this.indexOf(lastItem) - 1
val brand = this.substring(0, if (lastInd == -1) 0 else lastInd).trim()
return brand.split(" ").joinToString(separator = " ") { it.firstLetterToUpperCase() }
}
fun generateNumber(
orderId: String?,
userId : String?
) : String {
return if (orderId == null || userId == null) {
val arr = (System.currentTimeMillis() % 1000000).toString().toCharArray()
arr.shuffle()
arr.joinToString("")
}
else {
val finalNumber = mutableListOf<Int>()
// 0-4, 5-9, 10-14, 15-19
for (i in 0..3) {
val sub = orderId.substring(i * 5, (i + 1) * 4 + i)
val digit = sub.map { ch -> ch.code }.sum() % 10
finalNumber.add(digit)
}
finalNumber.add(userId.substring(0, 13).map { it.code }.sum() % 10)
finalNumber.add(userId.substring(14, 28).map { it.code }.sum() % 10)
finalNumber.shuffle()
finalNumber.joinToString("")
}
}
fun composeIntent(context: Context, optionType : OptionType) {
try {
when (optionType){
OptionType.PhoneNumber -> {
ContextCompat.startActivity(context, Intent.createChooser(Intent(Intent.ACTION_DIAL).apply {
data = Uri.parse(context.getString(R.string.phone_number_prefix) + context.getString(
R.string.phone_number))
}, ""), null)
}
OptionType.Gmail -> {
ContextCompat.startActivity(context, Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse(context.getString(R.string.email_prefix) + context.getString(R.string.email))
}, null)
}
OptionType.Telegram -> {
ContextCompat.startActivity(context, Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(context.getString(R.string.telegram_prefix) + context.getString(
R.string.telegram))
}, null)
}
OptionType.WhatsApp -> {
ContextCompat.startActivity(context, Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(context.getString(R.string.whatsapp_prefix) + context.getString(
R.string.whatsapp))
}, null)
}
OptionType.WebSite -> {
ContextCompat.startActivity(context, Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(context.getString(R.string.website_prefix) + context.getString(
R.string.website))
}, null)
}
else -> {}
}
} catch (e : Exception){
context.showToast(R.string.app_not_installed_error)
Log.d("TAG", "composeIntent: ${e.message}")
}
} |
#ifndef IOTEXCRYPT_ENTROPY_H
#define IOTEXCRYPT_ENTROPY_H
#include "build_info.h"
#include <stddef.h>
#if defined(IOTEX_SHA512_C) && !defined(IOTEX_ENTROPY_FORCE_SHA256)
#include "sha512.h"
#define IOTEX_ENTROPY_SHA512_ACCUMULATOR
#else
#if defined(IOTEX_SHA256_C)
#define IOTEX_ENTROPY_SHA256_ACCUMULATOR
#include "sha256.h"
#endif
#endif
/** Critical entropy source failure. */
#define IOTEX_ERR_ENTROPY_SOURCE_FAILED -0x003C
/** No more sources can be added. */
#define IOTEX_ERR_ENTROPY_MAX_SOURCES -0x003E
/** No sources have been added to poll. */
#define IOTEX_ERR_ENTROPY_NO_SOURCES_DEFINED -0x0040
/** No strong sources have been added to poll. */
#define IOTEX_ERR_ENTROPY_NO_STRONG_SOURCE -0x003D
/** Read/write error in file. */
#define IOTEX_ERR_ENTROPY_FILE_IO_ERROR -0x003F
/**
* \name SECTION: Module settings
*
* The configuration options you can set for this module are in this section.
* Either change them in iotex_config.h or define them on the compiler command line.
* \{
*/
#if !defined(IOTEX_ENTROPY_MAX_SOURCES)
#define IOTEX_ENTROPY_MAX_SOURCES 5 /**< Maximum number of sources supported */
#endif
#if !defined(IOTEX_ENTROPY_MAX_GATHER)
#define IOTEX_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */
#endif
/** \} name SECTION: Module settings */
#if defined(IOTEX_ENTROPY_SHA512_ACCUMULATOR)
#define IOTEX_ENTROPY_BLOCK_SIZE 64 /**< Block size of entropy accumulator (SHA-512) */
#else
#define IOTEX_ENTROPY_BLOCK_SIZE 32 /**< Block size of entropy accumulator (SHA-256) */
#endif
#define IOTEX_ENTROPY_MAX_SEED_SIZE 1024 /**< Maximum size of seed we read from seed file */
#define IOTEX_ENTROPY_SOURCE_MANUAL IOTEX_ENTROPY_MAX_SOURCES
#define IOTEX_ENTROPY_SOURCE_STRONG 1 /**< Entropy source is strong */
#define IOTEX_ENTROPY_SOURCE_WEAK 0 /**< Entropy source is weak */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Entropy poll callback pointer
*
* \param data Callback-specific data pointer
* \param output Data to fill
* \param len Maximum size to provide
* \param olen The actual amount of bytes put into the buffer (Can be 0)
*
* \return 0 if no critical failures occurred,
* IOTEX_ERR_ENTROPY_SOURCE_FAILED otherwise
*/
typedef int (*iotex_entropy_f_source_ptr)(void *data, unsigned char *output, size_t len,
size_t *olen);
/**
* \brief Entropy source state
*/
typedef struct iotex_entropy_source_state
{
iotex_entropy_f_source_ptr f_source; /**< The entropy source callback */
void * p_source; /**< The callback data pointer */
size_t size; /**< Amount received in bytes */
size_t threshold; /**< Minimum bytes required before release */
int strong; /**< Is the source strong? */
}
iotex_entropy_source_state;
/**
* \brief Entropy context structure
*/
typedef struct iotex_entropy_context
{
int accumulator_started; /* 0 after init.
* 1 after the first update.
* -1 after free. */
#if defined(IOTEX_ENTROPY_SHA512_ACCUMULATOR)
iotex_sha512_context accumulator;
#elif defined(IOTEX_ENTROPY_SHA256_ACCUMULATOR)
iotex_sha256_context accumulator;
#endif
int source_count; /* Number of entries used in source. */
iotex_entropy_source_state source[IOTEX_ENTROPY_MAX_SOURCES];
#if defined(IOTEX_THREADING_C)
iotex_threading_mutex_t mutex;
#endif
#if defined(IOTEX_ENTROPY_NV_SEED)
int initial_entropy_run;
#endif
}
iotex_entropy_context;
#if !defined(IOTEX_NO_PLATFORM_ENTROPY)
/**
* \brief Platform-specific entropy poll callback
*/
int iotex_platform_entropy_poll( void *data,
unsigned char *output, size_t len, size_t *olen );
#endif
/**
* \brief Initialize the context
*
* \param ctx Entropy context to initialize
*/
void iotex_entropy_init( iotex_entropy_context *ctx );
/**
* \brief Free the data in the context
*
* \param ctx Entropy context to free
*/
void iotex_entropy_free( iotex_entropy_context *ctx );
/**
* \brief Adds an entropy source to poll
* (Thread-safe if IOTEX_THREADING_C is enabled)
*
* \param ctx Entropy context
* \param f_source Entropy function
* \param p_source Function data
* \param threshold Minimum required from source before entropy is released
* ( with iotex_entropy_func() ) (in bytes)
* \param strong IOTEX_ENTROPY_SOURCE_STRONG or
* IOTEX_ENTROPY_SOURCE_WEAK.
* At least one strong source needs to be added.
* Weaker sources (such as the cycle counter) can be used as
* a complement.
*
* \return 0 if successful or IOTEX_ERR_ENTROPY_MAX_SOURCES
*/
int iotex_entropy_add_source( iotex_entropy_context *ctx,
iotex_entropy_f_source_ptr f_source, void *p_source,
size_t threshold, int strong );
/**
* \brief Trigger an extra gather poll for the accumulator
* (Thread-safe if IOTEX_THREADING_C is enabled)
*
* \param ctx Entropy context
*
* \return 0 if successful, or IOTEX_ERR_ENTROPY_SOURCE_FAILED
*/
int iotex_entropy_gather( iotex_entropy_context *ctx );
/**
* \brief Retrieve entropy from the accumulator
* (Maximum length: IOTEX_ENTROPY_BLOCK_SIZE)
* (Thread-safe if IOTEX_THREADING_C is enabled)
*
* \param data Entropy context
* \param output Buffer to fill
* \param len Number of bytes desired, must be at most IOTEX_ENTROPY_BLOCK_SIZE
*
* \return 0 if successful, or IOTEX_ERR_ENTROPY_SOURCE_FAILED
*/
int iotex_entropy_func( void *data, unsigned char *output, size_t len );
/**
* \brief Add data to the accumulator manually
* (Thread-safe if IOTEX_THREADING_C is enabled)
*
* \param ctx Entropy context
* \param data Data to add
* \param len Length of data
*
* \return 0 if successful
*/
int iotex_entropy_update_manual( iotex_entropy_context *ctx,
const unsigned char *data, size_t len );
#if defined(IOTEX_ENTROPY_NV_SEED)
/**
* \brief Trigger an update of the seed file in NV by using the
* current entropy pool.
*
* \param ctx Entropy context
*
* \return 0 if successful
*/
int iotex_entropy_update_nv_seed( iotex_entropy_context *ctx );
#endif /* IOTEX_ENTROPY_NV_SEED */
#if defined(IOTEX_FS_IO)
/**
* \brief Write a seed file
*
* \param ctx Entropy context
* \param path Name of the file
*
* \return 0 if successful,
* IOTEX_ERR_ENTROPY_FILE_IO_ERROR on file error, or
* IOTEX_ERR_ENTROPY_SOURCE_FAILED
*/
int iotex_entropy_write_seed_file( iotex_entropy_context *ctx, const char *path );
/**
* \brief Read and update a seed file. Seed is added to this
* instance. No more than IOTEX_ENTROPY_MAX_SEED_SIZE bytes are
* read from the seed file. The rest is ignored.
*
* \param ctx Entropy context
* \param path Name of the file
*
* \return 0 if successful,
* IOTEX_ERR_ENTROPY_FILE_IO_ERROR on file error,
* IOTEX_ERR_ENTROPY_SOURCE_FAILED
*/
int iotex_entropy_update_seed_file( iotex_entropy_context *ctx, const char *path );
#endif /* IOTEX_FS_IO */
#ifdef __cplusplus
}
#endif
#endif /* entropy.h */ |
const options = {
method: "GET",
headers: {
accept: "application/json",
Authorization:
"Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwNjUyNjg3YTExNzRhMGRhYWM3ODUxYWI0YTdkZDAzMCIsInN1YiI6IjY1NGQxNjk3Mjg2NmZhMTA4ZGMzZTNhMiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.DfEYDnbxHmN78CHi94hN0-2ulU-Ufs3gkXzRmFJOmjM",
},
};
export async function movieData(query, pageParam = 1) {
try {
const response = await fetch(
`https://api.themoviedb.org/3/search/movie?query=${query}&include_adult=false&language=en-US&page=${pageParam}&append_to_response=reviews`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
return data.results;
} catch (error) {
// Handle any errors that occurred during the fetch
console.error("Fetch error:", error);
// throw error; // You can choose to rethrow the error or handle it differently
}
}
export async function movieInfo(id) {
const response1 = await fetch(
`https://api.themoviedb.org/3/movie/${id}?language=en-US`,
options
);
if (!response1.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response1.status}`);
}
// Parse the response as JSON
const data1 = await response1.json();
const response2 = await fetch(
`https://api.themoviedb.org/3/movie/${id}/credits?language=en-US`,
options
);
if (!response2.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response2.status}`);
}
const data2 = await response2.json();
return { data1, data2 };
}
export async function movieThriller(id) {
const response = await fetch(
`https://api.themoviedb.org/3/movie/${id}/videos?language=en-US`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
// Check if data.Response is "False" and throw an error
if (data.Response === "False") {
throw new Error("No video found.");
}
return data.results;
}
export async function trending(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/trending/all/day?language=en-US&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function popular(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/movie/popular?language=en-US&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function all(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/trending/all/week?language=en-US&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function action(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=28&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function adventure(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=12&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function animation(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=16&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function comedy(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=35&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
// throw error; // You can choose to rethrow the error or handle it differently
}
export async function crime(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=80&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function documentary(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=99&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function drama(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=18&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function family(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=10751&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function fantansy(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=14&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function history(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=36&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function horror(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=27&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function music(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=10402&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function mystery(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=9648&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function romance(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=10749&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function scienceFiction(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=878&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function tvMovie(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=10770&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function thriller(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=53&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function war(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=10752&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function western(pageParam = 1) {
const response = await fetch(
`https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc&with_genres=37&page=${pageParam}`,
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data;
}
export async function movies() {
const response = await fetch(
"https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=3&sort_by=popularity.desc",
options
);
if (!response.ok) {
// Check for errors and handle them if the response is not okay
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
const data = await response.json();
if (data.Response === "False") {
throw new Error("No Movie found.");
}
return data.results;
}
/*
{
"genres": [
{
"id": 14,
"name": "Fantasy"
},
{
"id": 36,
"name": "History"
},
{
"id": 27,
"name": "Horror"
},
{
"id": 10402,
"name": "Music"
},
{
"id": 9648,
"name": "Mystery"
},
{
"id": 10749,
"name": "Romance"
},
{
"id": 878,
"name": "Science Fiction"
},
{
"id": 10770,
"name": "TV Movie"
},
{
"id": 53,
"name": "Thriller"
},
{
"id": 10752,
"name": "War"
},
{
"id": 37,
"name": "Western"
}
]
}
*/ |
<!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>Cont</title>
</head>
<body>
<!--Blue is more specific-->
<!-- <style>
div.blue {
color: blue;
}
.green {
color: green;
}
</style>
<div class="green blue">hi</div> -->
<!--green is ordered last so overrides the blue-->
<!-- <style>
.blue {
color: blue;
}
.green {
color: green;
}
</style>
<div class="green blue">hi</div> -->
<!-- <style>
.blue {
color: blue;
color: green;
}
</style>
<h1 class="blue">Green Ordering</h1> -->
<!-- <style>
.blue {
color: blue;
}
</style>
<h1 class="blue" style="color: green;">Green</h1> -->
<!-- <style>
.blue {
color: green !important;
color: blue;
}
</style>
<h1 class="blue">Green Important</h1> -->
<!-- <style>
#nice {
color: blue;
}
.nice {
color: purple;
}
h1 {
color: orange;
}
</style>
<h1 id="nice" class="nice">Multiple CSS Collions (Blue)</h1>
<h1 id="nice">Id (Most Powerful)</h1>
<h1 class="nice">Class, Pseudo</h1>
<h1>HTML Elements (Least Powerful)</h1> -->
</body>
</html> |
//
// DateCalculationModel.swift
// IbarakiUiniversityApp
//
// Created by HiroakiSaito on 2023/01/01.
//
import Foundation
enum DocumentStatus {
case normal
case befor1Week
case befor3Day
case befor1Day
case deadline
case overdue
case none
}
class DateCalculationModel {
private func diffDay(date: Date) -> Int {
// ここは後でよく考える
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
let nowDayString = formatter.string(from: now)
let dateDayString = formatter.string(from: date)
let nowDay = formatter.date(from: nowDayString)
let dateDay = formatter.date(from: dateDayString)
let calendar = Calendar(identifier: .gregorian)
let diff = calendar.dateComponents([.day], from: nowDay ?? now, to: dateDay ?? now)
let diffDay = Int(diff.day!)
return diffDay
}
func diffDate(date: Date) -> String {
let diffDay = diffDay(date: date)
if diffDay > 0 {
return "締め切りまで \(diffDay) 日です"
} else if diffDay == 0 {
return "今日が提出期限です"
} else {
return "提出期限が過ぎています"
}
}
func observeDocumentStatus(date: Date) -> DocumentStatus {
let diffDay = diffDay(date: date)
if diffDay == 1 {
if diffDay > 1 {
if diffDay >= 3 {
if diffDay > 7 {
if diffDay > 14 {
return .none
}
return .normal
}
return .befor1Week
}
return .befor3Day
}
return .befor1Day
} else if diffDay == 0 {
return .deadline
} else if diffDay < 0 {
return .overdue
} else {
return .none
}
}
} |
<!DOCTYPE html>
<html lang="es" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>La ciencia de manera divertida</title>
<meta content="" name="description"/>
<meta content="" name="keywords"/>
<!-- Favicons -->
<link href="/assets/img/icono.ico" rel="icon"/>
<link href="/assets/img/ciencia.png" rel="apple-touch-icon"/>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Jost:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"
rel="stylesheet"/>
<!-- Vendor CSS Files -->
<link href="/assets/vendor/aos/aos.css" rel="stylesheet"/>
<link href="/assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<link href="/assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet"/>
<link href="/assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"/>
<link href="/assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet"/>
<link href="/assets/vendor/remixicon/remixicon.css" rel="stylesheet"/>
<link href="/assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet"/>
<link href="/assets/css/style.css" rel="stylesheet"/>
</head>
<body>
<header id="header" class="fixed-top">
<div class="container d-flex align-items-center">
<h1 class="logo me-auto">
<a th:href="@{/}">La ciencia de manera divertida</a>
</h1>
<nav id="navbar" class="navbar">
<ul>
<li><a class="nav-link scrollto active" href="#hero">Inicio</a></li>
<li><a class="nav-link scrollto" href="#aprende">Aprende</a></li>
<li><a class="nav-link scrollto" href="#experimentos">Experimentos</a></li>
<li>
<a class="nav-link scrollto" href="#team">Nuestro equipo</a>
</li>
<li>
<a class="getstarted scrollto" href="#" th:href="@{/login}">Iniciar sesion</a>
</li>
<!--
<li sec:authorize="hasRole('USER')">
<a th:href="@{/logout}">Cerrar sesion</a>
</li>
-->
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav>
</div>
</header>
<!-- ======= Hero Section ======= -->
<section id="hero" class="d-flex align-items-center">
<div class="container">
<div class="row">
<div class="col-lg-6 d-flex flex-column justify-content-center pt-4 pt-lg-0 order-2 order-lg-1"
data-aos="fade-up" data-aos-delay="200">
<h1>
Aprende experimentos cientificos de forma entretenida e
interactiva
</h1>
<h2>
Este es un espacio en el que podremos aprender acerca del
maravilloso mundo de la ciencia y podemos socializar acerca de ella
</h2>
<div class="d-flex justify-content-center justify-content-lg-start">
<a
href="https://www.youtube.com/watch?v=MjtjksS-7ic"
class="glightbox btn-watch-video"
><i class="bi bi-play-circle"></i><span>Ver Video</span></a
>
</div>
</div>
<div class="col-lg-6 order-1 order-lg-2 hero-img" data-aos="zoom-in" data-aos-delay="200">
<img src="assets/img/fondo.png" class="img-fluid animated" alt=""/>
</div>
</div>
</div>
</section>
<!-- End Hero -->
<main id="main">
<section id="aprende" class="why-us section-bg">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Aprende</h2>
<div class="row">
<div class="col-lg-7 d-flex flex-column justify-content-center align-items-stretch order-2 order-lg-1">
<div class="content">
<h3>
<strong>¿Que son los experimentos cientificos?</strong>
</h3>
<p>
Un experimento es todo aquel proceso complejo en el que se emplean medidas y se realizan pruebas para comprobar y estudiar algún proceso antes de ejecutarlo por completo. En él se realizan todo tipo de estudios, a fin de constatar la funcionalidad del objeto en estudio. Las teorías e hipótesis nacen a partir de los experimentos que se realizan entorno a una premisa. Los experimentos son de vital importancia en el campo científico, son parte esencial de los estudios que se realizan en un laboratorio.
</p>
<br>
</div>
<div class="accordion-list">
<ul>
<li>
<a data-bs-toggle="collapse" class="collapse" data-bs-target="#accordion-list-1">
<span>01</span> Fisica
<i class="bx bx-chevron-down icon-show"></i>
<i class="bx bx-chevron-up icon-close"></i>
</a>
<div id="accordion-list-1" class="collapse show" data-bs-parent=".accordion-list">
<p>
Experimentar es el camino por el cual la ciencia se perfecciona. Hacerlo es poner a prueba las hipótesis más queridas y tal vez comprobar que la idea más arraigada se tenga que transformar. Los siguientes experimentos son unos sencillos que nos demuestran, entre los resultados que son constantes, que la física y la química están presentes en todo nuestro entorno.
</p>
</div>
</li>
<li>
<a data-bs-toggle="collapse" data-bs-target="#accordion-list-2"
class="collapsed"><span>02</span> Quimica
<i class="bx bx-chevron-down icon-show"></i>
<i class="bx bx-chevron-up icon-close"></i>
</a>
<div id="accordion-list-2" class="collapse" data-bs-parent=".accordion-list">
<p>
Un experimento es un procedimiento llevado a cabo para apoyar, refutar, o validar una hipótesis. Los experimentos proporcionan idea sobre causa-y-efecto por la demostración del resultado, que ocurre cuándo un factor particular es manipulado
</p>
</div>
</li>
<li>
<a data-bs-toggle="collapse" data-bs-target="#accordion-list-3"
class="collapsed"><span>03</span> Biologicos
<i class="bx bx-chevron-down icon-show"></i>
<i class="bx bx-chevron-up icon-close"></i>
</a>
<div id="accordion-list-3" class="collapse" data-bs-parent=".accordion-list">
<p>
El aporte de ciertos modelos matemáticos al avance de las ciencias biológicas ha aumentado de forma dramática en la última década. Esto se debe en parte al desarrollo de los métodos computacionales, ya que éstos permiten la resolución aproximada de las ecuaciones en los modelos. Existen muchos fenómenos biológicos en los que una membrana o una fibra elástica interacciona con el fluido que la rodea. Por ejemplo, las venas son estructuras flexibles y elásticas por donde fluye la sangre. El músculo cardíaco está formado por fibras musculares elásticas que promueven el flujo de la sangre en todo el cuerpo. Los flagelos de microorganismos como bacterias y espermatozoides son fibras flexibles que permiten el movimiento del microorganismo. Los modelos matemáticos y las simulaciones numéricas que se presentan en este artículo son ejemplos de herramientas para el estudio y el entendimiento de este tipo de fenómenos.
</p>
</div>
</li>
<li>
<a data-bs-toggle="collapse" data-bs-target="#accordion-list-4"
class="collapsed"><span>04</span> Tecnologico
<i class="bx bx-chevron-down icon-show"></i>
<i class="bx bx-chevron-up icon-close"></i>
</a>
<div id="accordion-list-3" class="collapse" data-bs-parent=".accordion-list">
<p>
Un proyecto tecnológico, también llamado proceso tecnológico, es un proceso, definido en un plan, que se diseña y se lleva a cabo para crear o modificar un producto que sea capaz de cubrir una necesidad o una demanda de los usuarios.
</p>
</div>
</li>
<li>
<a data-bs-toggle="collapse" data-bs-target="#accordion-list-5"
class="collapsed"><span>05</span> Deportivo
<i class="bx bx-chevron-down icon-show"></i>
<i class="bx bx-chevron-up icon-close"></i>
</a>
<div id="accordion-list-3" class="collapse" data-bs-parent=".accordion-list">
<p>
La Metodología de la Investigación constituye una herramienta básica de las ciencias aplicadas al deporte, indispensable para la generación de nuevos conocimientos, así como para la solución de problemas relacionados con el entrenamiento físico y con el logro de óptimos resultados a nivel competitivo. En este sentido, resulta común, que tanto entrenadores como investigadores del deporte, se formulen interrogantes tales como: ¿Cuáles son las causas del bajo rendimiento de mis atletas? ¿Qué efecto tendrá el consumo de una determinada sustancia? ¿Cómo puedo hacer más eficiente la sesión de entrenamiento? Sin embargo, estas preguntas no pueden ser respondidas correctamente sin la ejecución de un riguroso y sistemático proceso de investigación caracterizado por el empleo de una metodología que incluye el uso de diseños, técnicas e instrumentos válidos y confiables. Sólo así, los resultados obtenidos podrán ser generalizables y aplicables en la solución de los problemas científicos del deporte
</p>
</div>
</li>
<li>
<a data-bs-toggle="collapse" data-bs-target="#accordion-list-6"
class="collapsed"><span>06</span> Matemáticas
<i class="bx bx-chevron-down icon-show"></i>
<i class="bx bx-chevron-up icon-close"></i>
</a>
<div id="accordion-list-3" class="collapse" data-bs-parent=".accordion-list">
<p>
Los experimentos matemáticos son considerados como tipos de tareas que pueden ser utilizados para propiciar la elaboración de conjeturas y su comprobación a partir del análisis de situaciones de la vida práctica que exigen al escolar investigar y desarrollar formas de trabajo y de pensamiento matemático.
</p>
</div>
</li>
</ul>
</div>
</div>
<div class="col-lg-5 align-items-stretch order-1 order-lg-2 img"
style="background-image: url('/assets/img/ciencia2.png')" data-aos="zoom-in"
data-aos-delay="150">
</div>
</div>
</div>
</section>
<!-- ======= experimentos Section ======= -->
<section id="experimentos" class="portfolio">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Experimenta!</h2>
<p>
Este es el espacio en el que podemos averiguar cómo experimentar en el mundo de la ciencia, el
espacio donde todo puede salir muy bien o muy mal.
</p>
</div>
<ul id="portfolio-flters" class="d-flex justify-content-center" data-aos="fade-up" data-aos-delay="100">
<li data-filter="*" class="filter-active">Todos</li>
<!--
<li data-filter=".filter-app">Fisica</li>
<li data-filter=".filter-card">Quimica</li>
<li data-filter=".filter-web">Mecanica</li>
-->
</ul>
<div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200" th:each="post : ${posts}">
<div class="col-lg-4 col-md-6 portfolio-item filter-app">
<div class="portfolio-img">
<img th:src="@{'/imagenes/'+ ${post.imagen}}" th:alt="${post.imagen}" class="img-fluid"/>
</div>
<div class="portfolio-info">
<h4 th:text="${post.titulo}">titulo prueba sweet alert</h4>
<p th:text="${post.resumen}">prueba prueba ---p</p>
<a class="details-link" title="Mas información" th:href="@{/entrada/{id}(id=${post.id_publicacion})}">
<button class="bx bx-link"></i></button>
</a>
</div>
</div>
<!--
imagenes de filter app
-->
</div>
</div>
</section>
<!-- End experimentos Section -->
<!-- ======= Team Section ======= -->
<section id="team" class="team section-bg">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Nuestro equipo</h2>
<p>
Desarrolladores del proyecto
</p>
</div>
<div class="row">
<div class="col-lg-6">
<div class="member d-flex align-items-start" data-aos="zoom-in" data-aos-delay="100">
<div class="pic">
<img src="/assets/img/team/team-1.jpg" class="img-fluid" alt=""/>
</div>
<div class="member-info">
<h4>Catalina Vasquez</h4>
<span>Gestora del Proyecto</span>
<p>
</p>
<div class="social">
<a href=""><i class="ri-twitter-fill"></i></a>
<a href=""><i class="ri-facebook-fill"></i></a>
<a href=""><i class="ri-instagram-fill"></i></a>
<a href=""> <i class="ri-linkedin-box-fill"></i> </a>
</div>
</div>
</div>
</div>
<div class="col-lg-6 mt-4 mt-lg-0">
<div class="member d-flex align-items-start" data-aos="zoom-in" data-aos-delay="200">
<div class="pic">
<img src="/assets/img/team/" class="img-fluid" alt=""/>
</div>
<div class="member-info">
<h4>Yoraima Rincon</h4>
<span>Gestora de Bases de datos</span>
<p>
</p>
<div class="social">
<a href=""><i class="ri-twitter-fill"></i></a>
<a href=""><i class="ri-facebook-fill"></i></a>
<a href=""><i class="ri-instagram-fill"></i></a>
<a href=""> <i class="ri-linkedin-box-fill"></i> </a>
</div>
</div>
</div>
</div>
<div class="col-lg-6 mt-4">
<div class="member d-flex align-items-start" data-aos="zoom-in" data-aos-delay="300">
<div class="pic">
<img src="assets/img/team/team-3.jpg" class="img-fluid" alt=""/>
</div>
<div class="member-info">
<h4>Cristian Alvarez</h4>
<span>Desarrollador Frontend</span>
<p>
</p>
<div class="social">
<a href=""><i class="ri-twitter-fill"></i></a>
<a href=""><i class="ri-facebook-fill"></i></a>
<a href=""><i class="ri-instagram-fill"></i></a>
<a href=""> <i class="ri-linkedin-box-fill"></i> </a>
</div>
</div>
</div>
</div>
<div class="col-lg-6 mt-4">
<div class="member d-flex align-items-start" data-aos="zoom-in" data-aos-delay="400">
<div class="pic">
<img src="assets/img/team/team-4.jpg" class="img-fluid" alt=""/>
</div>
<div class="member-info">
<h4>Pablo Agudelo</h4>
<span>Desarrollador Backend</span>
<p>
</p>
<div class="social">
<a href=""><i class="ri-twitter-fill"></i></a>
<a href=""><i class="ri-facebook-fill"></i></a>
<a href=""><i class="ri-instagram-fill"></i></a>
<a href=""> <i class="ri-linkedin-box-fill"></i> </a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-6 mt-4">
<div class="member d-flex align-items-start" data-aos="zoom-in" data-aos-delay="400">
<div class="pic">
<img src="assets/img/team/team-4.jpg" class="img-fluid" alt=""/>
</div>
<div class="member-info">
<h4>William Vasquez</h4>
<span>Tester</span>
<p></p>
<div class="social">
<a href=""><i class="ri-twitter-fill"></i></a>
<a href=""><i class="ri-facebook-fill"></i></a>
<a href=""><i class="ri-instagram-fill"></i></a>
<a href=""> <i class="ri-linkedin-box-fill"></i> </a>
</div>
</div>
</div>
</div>
</div>
</section>
</main>
<div th:replace="fragments/footer :: footer">
</div>
<div id="preloader"></div>
<a href="#" class="back-to-top d-flex align-items-center justify-content-center">
<i class="bi bi-arrow-up-short"></i>
</a>
<!-- Vendor JS Files -->
<script src="/assets/vendor/aos/aos.js"></script>
<script src="/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="/assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="/assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="/assets/vendor/waypoints/noframework.waypoints.js"></script>
<script src="/assets/vendor/php-email-form/validate.js"></script>
<!-- Template Main JS File -->
<script src="/assets/js/main.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</body>
</html>
<!--
<div class="col-lg-4 col-md-6 portfolio-item filter-app">
<div class="portfolio-img">
<img src="/assets/img/portfolio/electromagnetismo.jpg" class="img-fluid" alt=""/>
</div>
<div class="portfolio-info">
<h4>Electromagnetismo</h4>
<p>App</p>
<a class="details-link" title="Mas información">
<button onclick="Swal.fire({
title: '<h4 th:text=${post.titulo}></h4>',
html: '<p th:text=${post.descripcion}></p>',
imageUrl: '/assets/img/portfolio/mecanica.jpg',
imageWidth: 400,
imageHeight: 200,
imageAlt: 'Custom image'})"
class="bx bx-link"></i>
</button>
</a>
</div>
</div>
<div class="col-lg-4 col-md-6 portfolio-item filter-app">
<div class="portfolio-img">
<img src="/assets/img/portfolio/energia.png" class="img-fluid" alt=""/>
</div>
<div class="portfolio-info">
<h4>Energia</h4>
<p>App</p>
<a class="details-link" title="Mas información">
<button onclick="Swal.fire({
title: 'Experimento 3',
text: 'Texto sobre el experimento',
imageUrl: '/assets/img/portfolio/energia.png',
imageWidth: 400,
imageHeight: 200,
imageAlt: 'Custom image'})"
class="bx bx-link"></i>
</button>
</a>
</div>
</div>
<div class="col-lg-4 col-md-6 portfolio-item filter-app">
<div class="portfolio-img">
<img src="/assets/img/portfolio/relatividad.jpg" class="img-fluid" alt=""/>
</div>
<div class="portfolio-info">
<h4>Relatividad</h4>
<p>App</p>
<a class="details-link" title="Mas información">
<button onclick="Swal.fire({
title: 'Experimento 4',
text: 'Texto sobre el experimento',
imageUrl: '/assets/img/portfolio/relatividad.jpg',
imageWidth: 400,
imageHeight: 200,
imageAlt: 'Custom image'})"
class="bx bx-link"></i>
</button>
</a>
</div>
</div>
<div class="col-lg-4 col-md-6 portfolio-item filter-web">
<div class="portfolio-img">
<img src="/assets/img/portfolio/hidraulica.jpg" class="img-fluid" alt=""/>
</div>
<div class="portfolio-info">
<h4>Web 3</h4>
<p>Web</p>
<a class="details-link" title="Mas información">
<button onclick="Swal.fire({
title: 'Experimento 5',
text: 'Texto sobre el experimento',
imageUrl: '/assets/img/portfolio/hidraulica.jpg',
imageWidth: 400,
imageHeight: 200,
imageAlt: 'Custom image'})"
class="bx bx-link"></i>
</button>
</a>
</div>
</div>
<div class="col-lg-4 col-md-6 portfolio-item filter-card">
<div class="portfolio-img">
<img src="../static/assets/img/portfolio/liquidos.jpg" class="img-fluid" alt=""/>
</div>
<div class="portfolio-info">
<h4>Card 2</h4>
<p>Card</p>
<a class="details-link" title="Mas información">
<button onclick="Swal.fire({
title: 'Experimento 6',
text: 'Texto sobre el experimento',
imageUrl: '/assets/img/portfolio/liquidos.jpg',
imageWidth: 400,
imageHeight: 200,
imageAlt: 'Custom image'})"
class="bx bx-link"></i>
</button>
</a>
</div>
</div>
--> |
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:loja_virtual/models/cart_manager.dart';
import 'package:loja_virtual/models/products.dart';
import 'package:loja_virtual/models/usermanager.dart';
import 'package:provider/provider.dart';
import '../products/components/size_widget.dart';
class ProducScreen extends StatelessWidget {
//const ProducScreen({Key? key}) : super(key: key);
const ProducScreen(this.product, {Key? key}) : super(key: key);
final Product product;
@override
Widget build(BuildContext context) {
final primaryColor = Theme.of(context).primaryColor;
return ChangeNotifierProvider.value(
value: product,
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(product.name!),
centerTitle: true,
actions: <Widget>[
Consumer<UserManager>(
builder: (_, userManager, __){
if (userManager.adminEnabled){
return IconButton(
onPressed: (){
Navigator.of(context).pushReplacementNamed(
'/edit_product',
arguments: product,
);
},
icon: const Icon(Icons.edit),
);
} else {
return Container();
}
}
),
],
),
body: ListView(
children: <Widget>[
AspectRatio(
aspectRatio: 1,
child: CarouselSlider(
options: CarouselOptions(
aspectRatio: 1.0,
enlargeCenterPage: true,
viewportFraction: 1,
enableInfiniteScroll: false,
),
items: product.images?.map((url) =>
Center(
child: Image.network(url),
),
).toList(),
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
product.name!,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'A partir de ',
style: TextStyle(
color: Colors.grey[600],
fontSize: 13,
),
),
),
Text(
'R\$ ${product.basePrice!.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.bold,
color: primaryColor
),
),
const Padding(
padding: EdgeInsets.only(top: 16, bottom: 8),
child: Text(
'Descrição',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500
),
),
),
Text(
product.description!,
style: const TextStyle(
fontSize: 16,
),
),
const Padding(
padding: EdgeInsets.only(top: 16, bottom: 8),
child: Text(
'Tamanhos',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500
),
),
),
// Tamanho das peças
Wrap(
spacing: 8,
runSpacing: 8,
children: product.sizes!.map((s){
return SizeWidget(size: s);
}).toList(),
),
const SizedBox(height: 20),
if (product.hasStock)
Consumer2<UserManager, Product>(
builder: (_, userManager, product, __){
return SizedBox(
height: 44,
child: ElevatedButton(
onPressed: product.selectedSize != null ? (){
if ( userManager.isLoggedIn ){
//enviando o produto para o carrinho
context.read<CartManager>().addToCart(product);
Navigator.of(context).pushNamed('/cart');
} else {
Navigator.of(context).pushNamed('/login');
}
} : null,
child: Text(
userManager.isLoggedIn
? 'Adicionar ao carrinho'
: 'Entre para comprar',
style: const TextStyle(
fontSize: 18
),
),
),
);
},
),
],
),
),
],
),
),
);
}
} |
import { createSlice } from "@reduxjs/toolkit";
import appApi from "../services/appApi";
export const userSlice = createSlice({
name: "user",
initialState: null,
reducers: {
addNotifications: (state, { payload }) => {
if (state.newMessages[payload]) {
state.newMessages[payload] = state.newMessages[payload] + 1;
} else {
state.newMessages[payload] = 1;
}
},
resetNotifications: (state, { payload }) => {
delete state.newMessages[payload];
},
},
extraReducers: (builder) => {
// save user after signup
builder.addMatcher(appApi.endpoints.signupUser.matchFulfilled, (state, { payload }) => payload);
// save user after login
builder.addMatcher(appApi.endpoints.loginUser.matchFulfilled, (state, { payload }) => payload);
// logout: destroy user session
builder.addMatcher(appApi.endpoints.logoutUser.matchFulfilled, () => null);
},
});
export const { addNotifications, resetNotifications } = userSlice.actions;
export default userSlice.reducer;
/**
* This code imports the createSlice function from the @reduxjs/toolkit library and the appApi instance from a local file named appApi.js.
It then uses createSlice to define a new Redux slice named user. The initial state of the user slice is set to null, and two reducer functions are defined: addNotifications and resetNotifications.
The addNotifications reducer function takes two arguments: state and payload. When this reducer is called, it checks if the state.newMessages object has a key matching the payload. If it does, it increments the value of that key by 1. If it doesn't, it creates a new key with the value of 1.
The resetNotifications reducer function takes two arguments: state and payload. When this reducer is called, it deletes the key in the state.newMessages object that matches the payload.
The extraReducers property is an object that allows you to define additional reducers that respond to actions dispatched by other parts of the application. In this code, the extraReducers property is defined using the builder function provided by Redux Toolkit.
The builder function defines three additional reducers that respond to actions dispatched by the signupUser, loginUser, and logoutUser endpoints of the appApi instance.
When the signupUser or loginUser endpoint returns a successful response, the addMatcher function is used to add a new reducer that updates the state of the user slice with the user object returned in the response.
When the logoutUser endpoint returns a successful response, the addMatcher function is used to add a new reducer that updates the state of the user slice to null.
Finally, the addNotifications and resetNotifications action creators are exported so that they can be used in other parts of the application. The default export is the user reducer function that can be added to the Redux store using the combineReducers function.
It's a function that deals with everything you need for each slice, do you remember using createAction and createReducer manually? Now it's available in this specific slice function.
The other benefit of using createSlice is our files structure. We can put all of our Redux-related logic for the slice into a single file. You'll see how to do it in our tutorial.
*/ |
from unittest.mock import patch
from django.conf import settings
from django.shortcuts import reverse
from django.test.utils import override_settings
import pytest
from rest_framework.status import (
HTTP_202_ACCEPTED,
HTTP_400_BAD_REQUEST,
HTTP_402_PAYMENT_REQUIRED,
HTTP_404_NOT_FOUND,
)
from baserow.contrib.database.rows.handler import RowHandler
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
def test_generate_ai_field_value_without_license(premium_data_fixture, api_client):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
email="test@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=False,
)
database = premium_data_fixture.create_database_application(
user=user, name="database"
)
table = premium_data_fixture.create_database_table(name="table", database=database)
field = premium_data_fixture.create_ai_field(table=table, name="ai")
rows = RowHandler().create_rows(
user,
table,
rows_values=[{}],
)
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": [rows[0].id]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_402_PAYMENT_REQUIRED
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
def test_generate_ai_field_value_view_field_does_not_exist(
premium_data_fixture, api_client
):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
email="test@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=True,
)
database = premium_data_fixture.create_database_application(
user=user, name="database"
)
table = premium_data_fixture.create_database_table(name="table", database=database)
field = premium_data_fixture.create_ai_field(table=table, name="ai")
rows = RowHandler().create_rows(
user,
table,
rows_values=[{}],
)
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": 0},
),
{"row_ids": [rows[0].id]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_404_NOT_FOUND
assert response.json()["error"] == "ERROR_FIELD_DOES_NOT_EXIST"
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
def test_generate_ai_field_value_view_row_does_not_exist(
premium_data_fixture, api_client
):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
email="test@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=True,
)
database = premium_data_fixture.create_database_application(
user=user, name="database"
)
table = premium_data_fixture.create_database_table(name="table", database=database)
field = premium_data_fixture.create_ai_field(table=table, name="ai")
rows = RowHandler().create_rows(
user,
table,
rows_values=[{}],
)
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": [0]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_404_NOT_FOUND
assert response.json()["error"] == "ERROR_ROW_DOES_NOT_EXIST"
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
def test_generate_ai_field_value_view_user_not_in_workspace(
premium_data_fixture, api_client
):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
email="test@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=True,
)
user_2, token_2 = premium_data_fixture.create_user_and_token(
email="test2@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=True,
)
database = premium_data_fixture.create_database_application(
user=user, name="database"
)
table = premium_data_fixture.create_database_table(name="table", database=database)
field = premium_data_fixture.create_ai_field(table=table, name="ai")
rows = RowHandler().create_rows(
user,
table,
rows_values=[{}],
)
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": [rows[0].id]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token_2}",
)
assert response.status_code == HTTP_400_BAD_REQUEST
assert response.json()["error"] == "ERROR_USER_NOT_IN_GROUP"
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
def test_generate_ai_field_value_view_generative_ai_does_not_exist(
premium_data_fixture, api_client
):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
email="test@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=True,
)
database = premium_data_fixture.create_database_application(
user=user, name="database"
)
table = premium_data_fixture.create_database_table(name="table", database=database)
field = premium_data_fixture.create_ai_field(
table=table, name="ai", ai_generative_ai_type="does_not_exist"
)
rows = RowHandler().create_rows(
user,
table,
rows_values=[{}],
)
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": [rows[0].id]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_400_BAD_REQUEST
assert response.json()["error"] == "ERROR_GENERATIVE_AI_DOES_NOT_EXIST"
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
def test_generate_ai_field_value_view_generative_ai_model_does_not_belong_to_type(
premium_data_fixture, api_client
):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
email="test@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=True,
)
database = premium_data_fixture.create_database_application(
user=user, name="database"
)
table = premium_data_fixture.create_database_table(name="table", database=database)
field = premium_data_fixture.create_ai_field(
table=table, name="ai", ai_generative_ai_model="does_not_exist"
)
rows = RowHandler().create_rows(
user,
table,
rows_values=[
{},
],
)
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": [rows[0].id]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_400_BAD_REQUEST
assert response.json()["error"] == "ERROR_MODEL_DOES_NOT_BELONG_TO_TYPE"
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
@patch("baserow_premium.fields.tasks.generate_ai_values_for_rows.apply")
def test_generate_ai_field_value_view_generative_ai(
patched_generate_ai_values_for_rows, premium_data_fixture, api_client
):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
email="test@test.nl",
password="password",
first_name="Test1",
has_active_premium_license=True,
)
database = premium_data_fixture.create_database_application(
user=user, name="database"
)
table = premium_data_fixture.create_database_table(name="table", database=database)
field = premium_data_fixture.create_ai_field(
table=table, name="ai", ai_prompt="'Hello'"
)
rows = RowHandler().create_rows(
user,
table,
rows_values=[{}],
)
assert patched_generate_ai_values_for_rows.call_count == 0
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": [rows[0].id]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_202_ACCEPTED
assert patched_generate_ai_values_for_rows.call_count == 1
@pytest.mark.django_db
@pytest.mark.field_ai
@override_settings(DEBUG=True)
def test_batch_generate_ai_field_value_limit(api_client, premium_data_fixture):
premium_data_fixture.register_fake_generate_ai_type()
user, token = premium_data_fixture.create_user_and_token(
has_active_premium_license=True
)
table = premium_data_fixture.create_database_table(user=user)
field = premium_data_fixture.create_ai_field(
table=table, name="ai", ai_prompt="'Hello'"
)
rows = RowHandler().create_rows(
user,
table,
rows_values=[{}] * (settings.BATCH_ROWS_SIZE_LIMIT + 1),
)
row_ids = [row.id for row in rows]
# BATCH_ROWS_SIZE_LIMIT rows are allowed
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": row_ids[: settings.BATCH_ROWS_SIZE_LIMIT]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_202_ACCEPTED
# BATCH_ROWS_SIZE_LIMIT + 1 rows are not allowed
response = api_client.post(
reverse(
"api:premium:fields:async_generate_ai_field_values",
kwargs={"field_id": field.id},
),
{"row_ids": row_ids},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_400_BAD_REQUEST
assert response.json()["error"] == "ERROR_REQUEST_BODY_VALIDATION"
assert response.json()["detail"] == {
"row_ids": [
{
"code": "max_length",
"error": f"Ensure this field has no more than"
f" {settings.BATCH_ROWS_SIZE_LIMIT} elements.",
},
],
} |
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:la_mode/core/utils/app_components.dart';
import 'package:la_mode/core/utils/text_styles.dart';
import '../../../../core/utils/app_colors.dart';
import '../widgets/dashed_divider.dart';
class TrackOrderScreen extends StatelessWidget {
final bool placed;
final bool shipped;
final bool pickedUp;
final bool delivered;
final String clock;
final int price;
const TrackOrderScreen({
super.key,
required this.price,
required this.clock,
required this.placed,
required this.shipped,
required this.pickedUp,
required this.delivered,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWithBag(
appBarTitle: "Track Order".tr(),
),
body: Container(
padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
margin: EdgeInsets.symmetric(
horizontal: 10.w,
),
decoration: BoxDecoration(
border: Border.all(
color: AppColors.lightGray,
),
borderRadius: BorderRadius.all(
Radius.circular(
15.sp,
),
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Text(
delivered
? "100%"
: pickedUp
? "75%"
: shipped
? "50%"
: placed
? "25%"
: "",
style: roboto14(weight: FontWeight.w500),
),
SizedBox(
width: 10.w,
),
Expanded(
child: LinearProgressIndicator(
minHeight: 8.h,
value: delivered
? 100 / 100
: pickedUp
? 75 / 100
: shipped
? 50 / 100
: placed
? 25 / 100
: 0 / 100,
color: AppColors.gold,
backgroundColor: AppColors.lightGray,
borderRadius: BorderRadius.all(
Radius.circular(
4.sp,
),
),
),
),
],
),
SizedBox(
height: 15.h,
),
Column(
children: [
///--- Placed ---///
Row(
children: [
CircleAvatar(
backgroundColor: AppColors.gold,
radius: 8.sp,
),
SizedBox(
width: 10.w,
),
Text(
'Order is placed'.tr(),
style: roboto16W500(),
)
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0.w),
child: const DashedDivider(
color: AppColors.gold,
),
),
SizedBox(
width: 10.w,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 5.h),
child: Row(
children: [
Icon(
Icons.watch_later_outlined,
color: AppColors.silverDark,
size: 20.sp,
),
SizedBox(
width: 10.w,
),
Text(
clock,
style: roboto14(
color: AppColors.silverDark,
weight: FontWeight.w400,
),
),
],
),
)
],
),
///--- Shipped ---///
Row(
children: [
CircleAvatar(
backgroundColor:
shipped ? AppColors.gold : AppColors.silverDark,
radius: 8.sp,
),
SizedBox(
width: 10.w,
),
Text(
'Order is Shipped'.tr(),
style: roboto16W500(),
)
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0.w),
child: DashedDivider(
color: placed
? shipped
? AppColors.gold
: AppColors.silverDark
: AppColors.silverM,
),
),
SizedBox(
width: 10.w,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 5.h),
child: Text(
'Captain is picking your order'.tr(),
style: roboto14(
color: AppColors.silverDark,
weight: FontWeight.w400,
),
),
)
],
),
///--- picked Up ---///
Row(
children: [
CircleAvatar(
backgroundColor: shipped
? pickedUp
? AppColors.gold
: AppColors.silverDark
: AppColors.silverM,
radius: 8.sp,
),
SizedBox(
width: 10.w,
),
Text(
'Order is picked up'.tr(),
style: roboto16W500(),
)
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0.w),
child: DashedDivider(
color: pickedUp ? AppColors.gold : AppColors.silverM,
),
),
SizedBox(
width: 10.w,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 5.h),
child: Text(
"Captain is on his way".tr(),
style: roboto14(
color: AppColors.silverDark,
weight: FontWeight.w400,
),
),
),
],
),
///--- Delivered ---///
Row(
children: [
CircleAvatar(
backgroundColor: pickedUp
? delivered
? AppColors.gold
: AppColors.silverDark
: AppColors.silverM,
radius: 8.sp,
),
SizedBox(
width: 10.w,
),
Text(
'Order is Delivered',
style: roboto16W500(),
)
],
),
],
),
Divider(
height: 20.h,
thickness: 1,
color: AppColors.lightGray,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Total",
style: roboto16W500(
color: AppColors.lightColor,
),
),
Text(
"\$$price",
style: roboto16W500(),
),
],
),
],
),
),
);
}
} |
"use client";
import { signIn, signOut, useSession } from "next-auth/react";
import Link from "next/link";
import { FaXTwitter } from "react-icons/fa6";
import { HiHome, HiDotsHorizontal } from "react-icons/hi";
export default function Sidebar() {
const { data: session } = useSession();
return (
<div className="flex flex-col p-3 justify-between h-screen">
<div className="flex flex-col gap-4 ">
<Link href="/">
<FaXTwitter className="w-16 h-16 cursor-pointer p-3 hover:bg-gray-100 rounded-full transition-all duration-200 " />
</Link>
<Link
href="/"
className="flex items-center p-3 hover:bg-gray-100 rounded-full transition-all duration-200 gap-2 w-fit"
>
<HiHome className="w-7 h-7" />
<span className="font-bold hidden xl:inline">Home</span>
</Link>
{!session ? (
<button
onClick={() => signIn()}
className="bg-blue-400 text-white rounded-full hover:brightness-95 transition-all duration-200 w-48 h-9 shadow-md hidden xl:inline font-semibold"
>
Sign In
</button>
) : (
<button
className="bg-blue-400 text-white rounded-full hover:brightness-95 transition-all duration-200 w-48 h-9 shadow-md hidden xl:inline font-semibold"
onClick={() => signOut()}
>
Sign Out
</button>
)}
</div>
{session && (
<div className="text-gray-700 text-sm flex items-center cursor-pointer p-3 hover:bg-gray-100 rounded-full transition-all duration-200">
<img
src={session.user.image}
alt="user-img"
className="h-10 w-10 rounded-full xl:mr-2"
/>
<div className="hidden xl:inline">
<h4 className="font-bold">{session.user.name}</h4>
<p className="text-gray-500">@{session.user.username}</p>
</div>
<HiDotsHorizontal className="h-5 xl:ml-8 hidden xl:inline" />
</div>
)}
</div>
);
} |
# frozen_string_literal: true
module SolutionImports
module Transient
# A transient record to ensure an {Provider} exists.
class ProviderRow < Support::FlexibleStruct
attribute :identifier, Types::Identifier
attribute :name, Types::PresentString
attribute? :url, Types::URL.optional
# Attributes that are provided only when creating an {Provider}
# for the first time. We do not overwrite changes to providers
# through the import process.
#
# @return [Hash]
def attrs_to_create
attributes.without(:identifier).compact_blank
end
end
end
end |
<!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>Document</title>
</head>
<body>
<div id="app">
<h1>差值表达式</h1>
{{msg}}
<h2>实现指令</h2>
<div v-text="msg"></div>
<h2>实现数据的双向绑定</h2>
{{count}}
<input type="text" v-model="count" />
</div>
<script src="./dep.js"></script>
<script src="./watcher.jss"></script>
<script src="./observer.js"></script>
<script src="./compiler.js"></script>
<script src="./miniVue.js"></script>
<script>
let vm = new MiniVue({
el: '#app',
data: {
msg: 'hello',
count: 0,
person: { name: '小黑' },
},
})
vm.msg = '小红'
</script>
</body>
</html> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>项目实战-PC端固定布局(5)</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header id="header">
<div class="center">
<h1 class="logo">飘城旅行社</h1>
<nav class="link">
<ul>
<li class="active"><a href="###">首页</a></li>
<li><a href="###">旅游资讯</a></li>
<li><a href="###">机票订购</a></li>
<li><a href="###">风景欣赏</a></li>
<li><a href="###">公司简介</a></li>
</ul>
</nav>
</div>
</header>
<div id="search">
<div class="search-bg"></div>
<input type="text" class="search-input" placeholder="请输入旅游景点或城市">
<button class="search-btn">搜索</button>
</div>
<div id="tour">
<section class="center">
<h2>热门标题</h2>
<p>国内旅游、国外旅游、自助旅游、自驾旅游、游轮签证、主题旅游等各种最新热门旅游推荐</p>
</section>
<figure>
<img src="img/tour1.jpg" alt="人们旅游">
<figcaption>
<strong class="title"><曼谷-芭提雅6日游></strong>
包团特惠,超丰富景点,升级1晚国五,无自费,更赠送600元/成人自费券
</figcaption>
<div>
<em class="sat">满意度 77%</em>
<span class="price">¥ <strong>2864</strong> 起</span>
</div>
<div class="type">国内旅游</div>
</figure>
<figure>
<img src="img/tour2.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><马尔代夫双鱼岛 Olhuveli4晚6日自助游></strong>
上海出发,机+酒 包含:早晚餐+快艇
</figcaption>
<div>
<em class="sat">满意度 97%</em>
<span class="price">¥ <strong>8039</strong> 起</span>
</div>
<div class="type">出境长线</div>
</figure>
<figure>
<img src="img/tour3.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><海南双飞5日游></strong>
含盐城接送,全程挂牌四星酒店,一价全含,零自费“自费项目”免费送
</figcaption>
<div>
<em class="sat">满意度 90%</em>
<span class="price">¥ <strong>2709</strong> 起</span>
</div>
<div class="type">自助旅游</div>
</figure>
<figure>
<img src="img/tour4.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><富山-大阪-东京8日游></strong>
暑期亲子,2 天自由,无导游安排自费项目,全程不强迫购物
</figcaption>
<div>
<em class="sat">满意度 97%</em>
<span class="price">¥ <strong>9499</strong> 起</span>
</div>
<div class="type">自助旅游</div>
</figure>
<figure>
<img src="img/tour5.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><法瑞意德12日游></strong>
4至5星,金色列车,少女峰,部分 THE MALL
</figcaption>
<div>
<em class="sat">满意度 97%</em>
<span class="price">¥ <strong>9199</strong> 起</span>
</div>
<div class="type">国内短线</div>
</figure>
<figure>
<img src="img/tour6.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><巴厘岛6日半自助游></strong>
蓝梦出海,独栋别墅,悦榕庄下午茶,纯玩
</figcaption>
<div>
<em class="sat">满意度 95%</em>
<span class="price">¥ <strong>6488</strong> 起</span>
</div>
<div class="type">出境长线</div>
</figure>
<figure>
<img src="img/tour7.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><塞舌尔迪拜9日自助游></strong>
一游两国,4晚塞舌尔,2晚迪拜,香港 EK往返
</figcaption>
<div>
<em class="sat">满意度 100%</em>
<span class="price">¥ <strong>9699</strong> 起</span>
</div>
<div class="type">游轮观光</div>
</figure>
<figure>
<img src="img/tour8.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><花样姐姐土耳其9日或10日游></strong>
最高立减3000!中餐六菜一汤+土耳其当地美食满足您挑剔味蕾
</figcaption>
<div>
<em class="sat">满意度 93%</em>
<span class="price">¥ <strong>9999</strong> 起</span>
</div>
<div class="type">出境长线</div>
</figure>
<figure>
<img src="img/tour9.jpg" alt="热门旅游">
<figcaption>
<strong class="title"><大阪-京都-箱根双飞6日游></strong>
盐城直飞,不走回头路,境外无自费,超值之旅
</figcaption>
<div>
<em class="sat">满意度 100%</em>
<span class="price">¥ <strong>5284</strong> 起</span>
</div>
<div class="type">国内短线</div>
</figure>
</div>
<footer id="footer">
<div class="top">
<div class="block left">
<h2>合作伙伴</h2>
<hr>
<ul>
<li>途牛旅游网</li>
<li>驴妈妈旅游网</li>
<li>携程旅游网</li>
<li>中国青年旅行社</li>
</ul>
</div>
<div class="block center">
<h2>旅游 FAQ</h2>
<hr>
<ul>
<li>旅游合同签订方式?</li>
<li>儿童价是基于什么指定的?</li>
<li>旅游的线路品质怎么界定的?</li>
<li>单房差是是什么?</li>
<li>旅游保险有哪些种类?</li>
</ul>
</div>
<div class="block right">
<h2>联系方式</h2>
<hr>
<ul>
<li>微博:weibo.com/ycku</li>
<li>邮件:ycku@ycku.com/li>
<li>地址:江苏盐城无名路123号</li>
</ul>
</div>
</div>
<div class="bottom">
Copyright ©️ YCKU 飘城旅行社 | 苏ICP备 120110119号 | 旅行社经营许可证:L-YC-BK12345
</div>
</footer>
</body>
</html>
<!--
本章主要开始学习使用HTML5和CSS3来构建Web页面,第一个项目采用PC端固定布局来实现。
一、底部区域
本节课,我们将探讨一下首页中最底部的区域。这部分区域由两个部分组成,一个是说明内容,有:合作伙伴、旅游FAQ和联系方式,还有一个就是
版权声明及各种手续证件编号。如图plan.png所示
//底部区域父元素
<footer id="footer">
...
</footer>
//底部父元素CSS
#tour {
height: 1150px;
}
#footer {
height: 360px;
background-color: #222;
}
二、说明区域
<footer id="footer">
<div class="top">
<div class="block left">
<h2>合作伙伴</h2>
<hr>
<ul>
<li>途牛旅游网</li>
<li>驴妈妈旅游网</li>
<li>携程旅游</li>
<li>中国青年旅行社</li>
</ul>
</div>
<div class="block center">
<h2>旅游FAQ</h2>
<hr>
<ul>
<li>旅游合同签订方式?</li>
<li>儿童价是基于什么定制的?</li>
<li>旅游的路线品质是怎么界定的?</li>
<li>单房差是什么?</li>
<li>旅游保险有哪些种类?</li>
</ul>
</div>
<div class="block right">
<h2>联系方式</h2>
<ul>
<li>微博:weibo.com/ycku</li>
<li>邮件:ycku@ycku.com/li>
<li>地址:江苏盐城无名路123号</li>
</ul>
</div>
</div>
</footer>
注:这里block表示三个区块通用的CSS,而left、center、right是每个区块独有的CSS,虽然CSS没有编写,但这里声明了,将在以后可以设置微调。
//说明部分的CSS
#footer .top {
width: 1263px;
height: 280px;
margin: 0 auto;
text-align: center;
}
#footer .block {
width: 410px;
height: 320px;
display: inline-block;
color: #ccc;
text-align: left;
vertical-align: top;
}
#footer h2 {
font-weight: normal;
padding: 20px 0 0 20px;
font-size: 24px;
}
#footer hr {
width: 90%;
border: 1px dashed #333;
}
#footer ul {
color: #666;
font-size: 18px;
text-indent: 20px;
line-height: 2;
}
三、版权及证件区
//版权区
<div class="bottom">
Copyright ©️ YCKU 飘城旅行社 | 苏ICP备 120110119号 | 旅行社经营许可证:L-YC-BK12345
</div>
//版权区CSS
#footer .bottom {
height: 80px;
line-height: 80px;
text-align: center;
color: #777;
background-color: #000;
border-top: 1px solid #444;
}
--> |
import React, { useCallback, useState } from 'react'
import type { FC } from 'react'
import { View, Text, Image, Alert } from 'react-native'
import { MD2Colors as Colors } from 'react-native-paper'
// @ts-ignore
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import moment from 'moment-with-locales-es6'
import * as D from '../data'
import { Avatar, IconText } from '../components'
import { styles } from './Person.style'
moment.locale('ko')
export type PersonProps = {
person: D.IPerson
}
const PersonUsingValueState: FC<PersonProps> = ({ person: initialPerson }) => {
const avatarPressed = useCallback(() => Alert.alert('avatar pressed.'), [])
const deletePressed = useCallback(() => Alert.alert('delete pressed.'), [])
// initialPerson.counts.comment, retweet, heart
const [comment, setComment] = useState<number>(0)
const [retweet, setRetweet] = useState<number>(0)
const [heart, setHeart] = useState<number>(0)
const commentPressed = useCallback(
() => setComment((comment2) => comment2 + 1),
[]
)
const retweetPressed = useCallback(
() => setRetweet((retweet2) => retweet2 + 1),
[]
)
const heartPressed = useCallback(() => setHeart((heart2) => heart2 + 1), [])
return (
<View style={[styles.view]}>
<View style={[styles.leftView]}>
<Avatar
imageStyle={[styles.avatar]}
uri={initialPerson.avatar}
size={50}
onPress={avatarPressed}
/>
</View>
<View style={[styles.rightView]}>
<Text style={[styles.name]}>{initialPerson.name}</Text>
<Text style={[styles.email]}>{initialPerson.email}</Text>
<View style={[styles.dateView]}>
<Text style={[styles.text]}>
{moment(initialPerson.createdDate).startOf('day').fromNow()}
</Text>
<Icon
name="trash-can-outline"
size={26}
color={Colors.lightBlue500}
onPress={deletePressed}
/>
</View>
<Text
numberOfLines={3}
ellipsizeMode="tail"
style={[styles.text, styles.comments]}
>
{initialPerson.comments}
</Text>
<Image style={[styles.image]} source={{ uri: initialPerson.image }} />
<View style={[styles.countsView]}>
<IconText
viewStyle={[styles.touchableIcon]}
onPress={commentPressed}
name="comment"
size={24}
color={Colors.blue500}
textStyle={[styles.iconText]}
text={comment}
/>
<IconText
viewStyle={[styles.touchableIcon]}
onPress={retweetPressed}
name="twitter"
size={24}
color={Colors.purple500}
textStyle={[styles.iconText]}
text={retweet}
/>
<IconText
viewStyle={styles.touchableIcon}
onPress={heartPressed}
name="heart"
size={24}
color={Colors.red500}
textStyle={[styles.iconText]}
text={heart}
/>
</View>
</View>
</View>
)
}
export default PersonUsingValueState |
---
date: 2022-11-17
hide:
- toc
---
# 集群升级
Kubernetes 社区每个季度都会发布一次小版本,每个版本的维护周期大概只有 9 个月。
版本停止维护后就不会再更新一些重大漏洞或安全漏洞。手动升级集群操作较为繁琐,给管理人员带来了极大的工作负担。
本节将介绍如何在通过 Web UI 界面一键式在线升级工作集群 Kubernetes 版本,
如需离线升级工作集群的 kubernetes 版本,请参阅[工作集群离线升级指南](../../best-practice/update-offline-cluster.md)进行升级。
!!! danger
版本升级后将无法回退到之前的版本,请谨慎操作。
!!! note
- Kubernetes 版本以 __x.y.z__ 表示,其中 __x__ 是主要版本, __y__ 是次要版本, __z__ 是补丁版本。
- 不允许跨次要版本对集群进行升级,例如不能从 1.23 直接升级到 1.25。
- __接入集群__ 不支持版本升级。如果左侧导航栏没有 __集群升级__ ,请检查该集群是否为 __接入集群__ 。
- 全局服务集群只能通过终端进行升级。
- 升级工作集群时,该工作集群的[管理集群](cluster-role.md#_3)应该已经接入容器管理模块,并且处于正常运行中。
- 如果需要修改集群参数,可以通过升级相同版本的方式实现,具体操作参考下文。
1. 在集群列表中点击目标集群的名称。

2. 然后在左侧导航栏点击 __集群运维__ -> __集群升级__ ,在页面右上角点击 __版本升级__ 。

3. 选择可升级的版本,输入集群名称进行确认。

!!! note
如果您是想通过升级方式来修改集群参数,请参考以下步骤:
1. 找到集群对应的 ConfigMap,您可以登录控制节点执行如下命令,找到 varsConfRef 中的 ConfigMap 名称。
```shell
kubectl get cluster.kubean.io <clustername> -o yaml
```
2. 根据需要,修改 ConfigMap 中的参数信息。
3. 在此处选择相同版本进行升级操作,升级完成即可成功更新对应的集群参数。
4. 点击 __确定__ 后,可以看到集群的升级进度。

5. 集群升级预计需要 30 分钟,可以点击 __实时日志__ 按钮查看集群升级的详细日志。
 |
<?php
// Register Custom Post Type Service
function create_service_cpt() {
$labels = array(
'name' => _x( 'Services', 'Post Type General Name', 'wplearning' ),
'singular_name' => _x( 'Service', 'Post Type Singular Name', 'wplearning' ),
'menu_name' => _x( 'Services', 'Admin Menu text', 'wplearning' ),
'name_admin_bar' => _x( 'Service', 'Add New on Toolbar', 'wplearning' ),
'archives' => __( 'Service Archives', 'wplearning' ),
'attributes' => __( 'Service Attributes', 'wplearning' ),
'parent_item_colon' => __( 'Parent Service:', 'wplearning' ),
'all_items' => __( 'All Services', 'wplearning' ),
'add_new_item' => __( 'Add New Service', 'wplearning' ),
'add_new' => __( 'Add New', 'wplearning' ),
'new_item' => __( 'New Service', 'wplearning' ),
'edit_item' => __( 'Edit Service', 'wplearning' ),
'update_item' => __( 'Update Service', 'wplearning' ),
'view_item' => __( 'View Service', 'wplearning' ),
'view_items' => __( 'View Services', 'wplearning' ),
'search_items' => __( 'Search Service', 'wplearning' ),
'not_found' => __( 'Not found', 'wplearning' ),
'not_found_in_trash' => __( 'Not found in Trash', 'wplearning' ),
'featured_image' => __( 'Featured Image', 'wplearning' ),
'set_featured_image' => __( 'Set featured image', 'wplearning' ),
'remove_featured_image' => __( 'Remove featured image', 'wplearning' ),
'use_featured_image' => __( 'Use as featured image', 'wplearning' ),
'insert_into_item' => __( 'Insert into Service', 'wplearning' ),
'uploaded_to_this_item' => __( 'Uploaded to this Service', 'wplearning' ),
'items_list' => __( 'Services list', 'wplearning' ),
'items_list_navigation' => __( 'Services list navigation', 'wplearning' ),
'filter_items_list' => __( 'Filter Services list', 'wplearning' ),
);
$args = array(
'label' => __( 'Service', 'wplearning' ),
'description' => __( 'Custom Post Types for Services', 'wplearning' ),
'labels' => $labels,
'menu_icon' => 'dashicons-thumbs-down',
'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'post-formats'),
'taxonomies' => array('category', 'post_tag'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'hierarchical' => false,
'exclude_from_search' => false,
'show_in_rest' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type( 'service', $args );
}
add_action( 'init', 'create_service_cpt', 0 ); |
<script setup lang="ts">
import { onBeforeUnmount, onMounted, reactive } from 'vue'
import { NButton, NCard, NGrid, NGi, NSpace, NTooltip } from 'naive-ui';
import WsClient from '../ws/SensorWebSocketClient';
import authApi from '../api/auth';
import sensorApi from '../api/sensor';
defineProps<{ msg: string }>()
let webSocketClient: WsClient
let webSocketData = reactive({
sensorsReading: {
fsr0: 0,
fsr1: 0,
fsr2: 0,
fsr3: 0,
} as any
})
function getFunction(reading: number) {
if (reading > 900) {
return '#42b883'
} else if (reading > 800) {
return '#42b883e7'
} else if (reading > 700) {
return '#42b883ce'
} else if (reading > 600) {
return '#42b883b5'
} else if (reading > 500) {
return '#42b8839c'
} else if (reading > 400) {
return '#42b88383'
} else if (reading > 300) {
return '#42b8836a'
} else if (reading > 200) {
return '#42b88351'
} else if(reading > 100) {
return '#42b88338'
} else if (reading > 50) {
return '#42b8831f'
} else {
return '#42b88300'
}
}
function handleClickEvent() {
sensorApi.postCalibrate()
}
onMounted(async () => {
let wsToken = await authApi.getAuthToken()
webSocketClient = new WsClient(wsToken, webSocketData)
})
onBeforeUnmount(() => {
webSocketClient.close()
})
</script>
<template>
<n-space justify="center">
<n-button text @click="handleClickEvent()" style="margin-right: 10px;text-decoration:underline">
<h1>
<code>
calibrate
</code>
</h1>
</n-button>
<h1>
<code>
{{ msg }}
</code>
</h1>
</n-space>
<code>
front
</code>
<n-grid responsive="screen" :x-gap="10" :y-gap="10" cols="2">
<n-gi>
<n-space justify="end">
<n-card embedded :style="{ backgroundColor: getFunction(webSocketData.sensorsReading.fsr0), width: '150px', height:'150px'}">
<code>
Sensor 0
<br>
<h2>
{{ webSocketData.sensorsReading.fsr0 < 0 ? 0 : webSocketData.sensorsReading.fsr0 }}
</h2>
</code>
</n-card>
</n-space>
</n-gi>
<n-gi>
<n-card embedded :style="{ backgroundColor: getFunction(webSocketData.sensorsReading.fsr1), width: '150px', height:'150px'}">
<code>
Sensor 1
<br>
<h2>
{{ webSocketData.sensorsReading.fsr1 < 0 ? 0 : webSocketData.sensorsReading.fsr1 }}
</h2>
</code>
</n-card>
</n-gi>
<n-gi>
<n-space justify="end">
<n-card embedded :style="{ backgroundColor: getFunction(webSocketData.sensorsReading.fsr2), width: '150px', height:'150px'}">
<code>
Sensor 2
<br>
<h2>
{{ webSocketData.sensorsReading.fsr2 < 0 ? 0 : webSocketData.sensorsReading.fsr2 }}
</h2>
</code>
</n-card>
</n-space>
</n-gi>
<n-gi>
<n-card embedded :style="{ backgroundColor: getFunction(webSocketData.sensorsReading.fsr3), width: '150px', height:'150px'}">
<code>
Sensor 3
<br>
<h2>
{{ webSocketData.sensorsReading.fsr3 < 0 ? 0 : webSocketData.sensorsReading.fsr3 }}
</h2>
</code>
</n-card>
</n-gi>
</n-grid>
<code>
back
</code>
</template>
<style scoped>
</style> |
import { AssetId } from '@explorer/types'
import { expect } from 'earl'
import { MIN_INT } from '../constants'
import { ByteWriter } from '../encoding/ByteWriter'
import { encodeAssetId } from '../encoding/encodeAssetId'
import { readToDecode } from '../test/readToDecode'
import { DecodingError } from './DecodingError'
import { readFundingIndices } from './readFundingIndices'
describe('readFundingIndices', () => {
const decode = readToDecode(readFundingIndices)
it('fails for empty data', () => {
expect(() => decode('')).toThrow(DecodingError, 'Went out of bounds')
})
it('can read zero indices', () => {
const writer = new ByteWriter().writeNumber(0, 32)
expect(decode(writer.getBytes())).toEqual([])
})
it('can read a single index', () => {
const writer = new ByteWriter()
.writeNumber(1, 32)
.writePadding(17)
.write(encodeAssetId(AssetId('ETH-9')))
.writeNumber(1n - MIN_INT, 32)
expect(decode(writer.getBytes())).toEqual([
{ assetId: AssetId('ETH-9'), value: 1n },
])
})
it('can read a multiple indices', () => {
const writer = new ByteWriter()
.writeNumber(3, 32)
.writePadding(17)
.write(encodeAssetId(AssetId('ETH-9')))
.writeNumber(1n - MIN_INT, 32)
.writePadding(17)
.write(encodeAssetId(AssetId('BTC-10')))
.writeNumber(-50n - MIN_INT, 32)
.writePadding(17)
.write(encodeAssetId(AssetId('ABC-123')))
.writeNumber(456n - MIN_INT, 32)
expect(decode(writer.getBytes())).toEqual([
{ assetId: AssetId('ETH-9'), value: 1n },
{ assetId: AssetId('BTC-10'), value: -50n },
{ assetId: AssetId('ABC-123'), value: 456n },
])
})
}) |
/*
## Objetivo:
Crie uma função que recebe como parâmetro a quantidade de vitórias e derrotas de um jogador,
depois disso retorne o resultado para uma variável, o saldo de Rankeadas deve ser feito através do calculo (vitórias - derrotas)
Se vitórias for menor do que 10 = Ferro
Se vitórias for entre 11 e 20 = Bronze
Se vitórias for entre 21 e 50 = Prata
Se vitórias for entre 51 e 80 = Ouro
Se vitórias for entre 81 e 90 = Diamante
Se vitórias for entre 91 e 100= Lendário
Se vitórias for maior ou igual a 101 = Imortal
## Saída
Ao final deve se exibir uma mensagem:
"O Herói tem de saldo de **{saldoVitorias}** está no nível de **{nivel}**"
*/
function Rank (vitorias, derrotas){
const saldo = vitorias - derrotas;
let nivel;
if (vitorias < 10) {
nivel = "Ferro";
} else if (vitorias >= 11 && vitorias <= 20) {
nivel = "Bronze";
} else if (vitorias >= 21 && vitorias <= 50) {
nivel = "Prata";
} else if (vitorias >= 51 && vitorias <= 80) {
nivel = "Ouro";
} else if (vitorias >= 81 && vitorias <= 90) {
nivel = "Diamante";
} else if (vitorias >= 91 && vitorias <= 100) {
nivel = "Lendário";
} else {
nivel = "Imortal";
}
return { saldo, nivel };
}
const vitoriasJogador = 75;
const derrotasJogador = 20;
const { saldo, nivel } = Rank(vitoriasJogador, derrotasJogador);
console.log(`O Herói tem um saldo de ${saldo} e está no nível de ${nivel}.`); |
package flaxbeard.steamcraft.api;
import flaxbeard.steamcraft.api.book.BookPage;
import flaxbeard.steamcraft.api.book.ICraftingPage;
import flaxbeard.steamcraft.api.enhancement.IEnhancement;
import flaxbeard.steamcraft.api.enhancement.IRocket;
import flaxbeard.steamcraft.api.exosuit.ExosuitPlate;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.commons.lang3.tuple.MutablePair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class SteamcraftRegistry {
/**
* The Items that can be used on the Carving Table.
*/
public static ArrayList<Item> molds = new ArrayList<Item>();
/**
* All of the CrucibleLiquids that the mod knows about.
*/
public static ArrayList<CrucibleLiquid> liquids = new ArrayList<CrucibleLiquid>();
/**
* All of the CrucibleLiquid recipes.
* Key: pair of the item and its metadata, -1 if it does not use metadata.
* Value: pair of the liquid and the amount created.
*/
public static HashMap<MutablePair<Item, Integer>, MutablePair<CrucibleLiquid, Integer>> liquidRecipes = new HashMap<MutablePair<Item, Integer>, MutablePair<CrucibleLiquid, Integer>>();
/**
* All of the Crucible dunking recipes.
* Key: A triplet of the Item, the metadata, and the CrucibleLiquid.
* Value: A pair of the required liquid amount and the output ItemStack.
*/
public static HashMap<Tuple3, MutablePair<Integer, ItemStack>> dunkRecipes = new HashMap<Tuple3, MutablePair<Integer, ItemStack>>();
/**
* The icons for all of the IEnhancements.
* Key: A pair of the item, the item as an enhancement.
* Value: The IIcon for the enhancement.
*/
public static HashMap<MutablePair<Item, IEnhancement>, IIcon> enhancementIcons = new HashMap<MutablePair<Item, IEnhancement>, IIcon>();
/**
* The IEnhancements.
* Key: Enhancement ID
* Value: IEnhancement
*/
public static HashMap<String, IEnhancement> enhancements = new HashMap<String, IEnhancement>();
/**
* All of the rockets that the rocket launcher can use.
*/
public static ArrayList<IRocket> rockets = new ArrayList<IRocket>();
/**
* All of the Esteemed Innovation categories.
*/
public static ArrayList<String> categories = new ArrayList<String >();
/**
* All of the research entries in Esteemed Innovation book. Each entry is a pair of the
*/
public static ArrayList<MutablePair<String, String>> research = new ArrayList<MutablePair<String, String>>();
/**
* All of the research pages. Key is the entry name, and the value is all of the pages in that entry.
*/
public static HashMap<String, BookPage[]> researchPages = new HashMap<String, BookPage[]>();
/**
* All of the research pages showcasing crafting recipes.
* Key: The output item.
* Value: A pair of the entry name and the page number.
*/
public static HashMap<ItemStack, MutablePair<String, Integer>> bookRecipes = new HashMap<ItemStack, MutablePair<String, Integer>>();
/**
* All of the registered Exosuit Plates. Key is the plate ID, which is typically the material's
* name. Value is the actual plate.
*/
public static HashMap<String, ExosuitPlate> plates = new HashMap<String, ExosuitPlate>();
/**
* All of the Exosuit Plate icons. Key is a pair of the exosuit slot and the plate. Value is the
* IIcon for that slot.
*/
public static HashMap<MutablePair<Integer, ExosuitPlate>, IIcon> plateIcons = new HashMap<MutablePair<Integer, ExosuitPlate>, IIcon>();
/**
* All of the custom steaming recipes for the Steam Heater.
* Key: A pair of the input item and its metadata.
* Value: A pair of the output item and its metadata.
*/
public static HashMap<MutablePair<Item, Integer>, MutablePair<Item, Integer>> steamingRecipes = new HashMap<MutablePair<Item, Integer>, MutablePair<Item, Integer>>();
/**
* Adds a steaming recipe.
* @param food1 The input item
* @param i The input item metadata
* @param food2 The output item
* @param j The output item metadata
*/
public static void addSteamingRecipe(Item food1, int i, Item food2, int j) {
steamingRecipes.put(MutablePair.of(food1, i), MutablePair.of(food2, j));
}
/**
* Adds a steaming recipe that does not take metadata.
* @param food1 The input item
* @param food2 The output item
*/
public static void addSteamingRecipe(Item food1, Item food2) {
steamingRecipes.put(MutablePair.of(food1, -1), MutablePair.of(food2, -1));
}
/**
* Removes a steaming recipe.
* @see #addSteamingRecipe(Item, int, Item, int) for params.
*/
public static void removeSteamingRecipe(Item food1, int i) {
steamingRecipes.remove(MutablePair.of(food1, i));
}
/**
* Removes a steaming recipe with no specific metadata.
* @see #addSteamingRecipe(Item, Item) for params.
*/
public static void removeSteamingRecipe(Item food1) {
removeSteamingRecipe(food1, -1);
}
/**
* Registers an ExosuitPlate.
* @param plate The plate.
*/
public static void addExosuitPlate(ExosuitPlate plate) {
plates.put(plate.getIdentifier(), plate);
}
/**
* Allows the mold to be used on the Carving Table.
* @param mold The item
*/
public static void addCarvableMold(Item mold) {
molds.add(mold);
}
/**
* Removes the mold from the list of Items that can be used on the Carving Table.
* @param mold The item
* @return The return value of ArrayList#remove.
* @see ArrayList#remove(Object)
*/
public static boolean removeMold(Item mold) {
return molds.remove(mold);
}
/**
* Adds a research category.
* @param string The name of the category.
*/
public static void addCategory(String string) {
categories.add(string);
}
/**
* Adds a research entry. Typically all of these should be unlocalized, linking up to lang entries.
* @param string The name of the entry.
* @param category The category name.
* @param pages The pages in that entry.
*/
public static void addResearch(String string, String category, BookPage... pages) {
if (!category.substring(0, 1).equals("!")) {
research.add(MutablePair.of(string, category));
researchPages.put(string, pages);
int pageNum = 0;
for (BookPage page : pages) {
if (page instanceof ICraftingPage) {
for (ItemStack craftedItem : ((ICraftingPage) page).getCraftedItem()) {
bookRecipes.put(craftedItem, MutablePair.of(string, pageNum));
}
}
pageNum++;
}
} else {
BookPage[] targetPages = researchPages.get(category.substring(1));
int pageNum = targetPages.length;
for (BookPage page : pages) {
if (page instanceof ICraftingPage) {
for (ItemStack craftedItem : ((ICraftingPage) page).getCraftedItem()) {
bookRecipes.put(craftedItem, MutablePair.of(category.substring(1), pageNum));
}
}
pageNum++;
}
ArrayList<BookPage> pages2 = new ArrayList<BookPage>(Arrays.asList(targetPages));
pages2.addAll(Arrays.asList(pages));
researchPages.put(category.substring(1), pages2.toArray(new BookPage[pages2.size()]));
}
}
/**
* Gets the given CrucibleLiquid from the name.
* @param name The liquid's name.
* @return Null if it cannot find that liquid, otherwise, the liquid.
*/
public static CrucibleLiquid getLiquidFromName(String name) {
for (CrucibleLiquid liquid : liquids) {
if (liquid.name.equals(name)) {
return liquid;
}
}
return null;
}
/**
* Registers a Crucible dunking recipe.
* @param item The input item
* @param meta The input metadata
* @param liquid The input liquid.
* @param liquidAmount The amount of liquid needed.
* @param result The output ItemStack.
*/
public static void registerDunkRecipe(Item item, int meta, CrucibleLiquid liquid, int liquidAmount, ItemStack result) {
dunkRecipes.put(new Tuple3(item, meta, liquid), MutablePair.of(liquidAmount, result));
}
/**
* Registers a Crucible dunking recipe with no input metadata.
* @param item The input item
* @param liquid The input liquid.
* @param liquidAmount The amount of the liquid needed.
* @param result The output ItemStack.
*/
public static void registerDunkRecipe(Item item, CrucibleLiquid liquid, int liquidAmount, ItemStack result) {
registerDunkRecipe(item, -1, liquid, liquidAmount, result);
}
/**
* Removes a dunking recipe.
* @param item The input item.
* @param meta The input item metadata.
* @param liquid The input liquid.
*/
public static void removeDunkRecipe(Item item, int meta, CrucibleLiquid liquid) {
if (dunkRecipes != null) {
for (Map.Entry<Tuple3, MutablePair<Integer, ItemStack>> entry : dunkRecipes.entrySet()) {
Tuple3 tuple = entry.getKey();
if (tuple.first == item && (Integer) tuple.second == meta && tuple.third == liquid) {
dunkRecipes.remove(tuple);
}
}
}
}
/**
* Removes a dunking recipe that does not take metadata.
* @param item The input item.
* @param liquid The input liquid.
*/
public static void removeDunkRecipe(Item item, CrucibleLiquid liquid) {
removeDunkRecipe(item, -1, liquid);
}
/**
* Registers a Crucible dunking recipe using the OreDictionary.
* @param dict The OreDict tag.
* @param liquid The input liquid.
* @param liquidAmount The liquid needed.
* @param result The result ItemStack.
*/
public static void registerOreDictDunkRecipe(String dict, CrucibleLiquid liquid, int liquidAmount, ItemStack result) {
ArrayList<ItemStack> ores = OreDictionary.getOres(dict);
for (ItemStack ore : ores) {
registerDunkRecipe(ore.getItem(), ore.getMetadata(), liquid, liquidAmount, result);
}
}
/**
* Removes a Crucible dunking recipe that uses the OreDictionary.
* @param dict The input OreDict tag.
* @param liquid The input liquid.
*/
public static void removeOreDictDunkRecipe(String dict, CrucibleLiquid liquid) {
ArrayList<ItemStack> ores = OreDictionary.getOres(dict);
for (ItemStack ore : ores) {
removeDunkRecipe(ore.getItem(), ore.getMetadata(), liquid);
}
}
/**
* Registers a Crucible melting recipe.
* @param item The input item.
* @param i The input metadata.
* @param liquid The output liquid.
* @param m The output liquid amount.
*/
public static void registerMeltRecipe(Item item, int i, CrucibleLiquid liquid, int m) {
liquidRecipes.put(MutablePair.of(item, i), MutablePair.of(liquid, m));
}
/**
* Registers a Crucible melting recipe with no input metadata.
* @param item The input item.
* @param liquid The output liquid.
* @param m The amount of liquid.
*/
public static void registerMeltRecipe(Item item, CrucibleLiquid liquid, int m) {
liquidRecipes.put(MutablePair.of(item, -1), MutablePair.of(liquid, m));
}
/**
* Registers a Crucible melting recipe that takes an OreDict entry as input.
* @param dict The OreDict tag.
* @param liquid The output liquid.
* @param m The amount of liquid.
*/
public static void registerMeltRecipeOreDict(String dict, CrucibleLiquid liquid, int m) {
ArrayList<ItemStack> ores = OreDictionary.getOres(dict);
for (ItemStack ore : ores) {
registerMeltRecipe(ore.getItem(), ore.getMetadata(), liquid, m);
}
}
/**
* Registers a Crucible melting recipe for a tool.
* @param item The input item.
* @param liquid The output liquid.
* @param m The amount of liquid.
*/
public static void registerMeltRecipeTool(Item item, CrucibleLiquid liquid, int m) {
for (int i = 0; i < item.getMaxDurability(); i++) {
liquidRecipes.put(MutablePair.of(item, i), MutablePair.of(liquid, MathHelper.floor_double(m * ((float) (item.getMaxDurability() - i) / (float) item.getMaxDurability()))));
}
}
/**
* Removes a melting recipe.
* @param item Input item
* @param meta Input item metadata.
* @param liquid Output liquid.
*/
public static void removeMeltRecipe(Item item, int meta, CrucibleLiquid liquid) {
MutablePair input = MutablePair.of(item, meta);
MutablePair output = liquidRecipes.get(input);
if (output.left == liquid) {
liquidRecipes.remove(input);
}
}
/**
* Removes a melting recipe without metadata.
* @param item Input item.
* @param liquid Output liquid.
*/
public static void removeMeltRecipe(Item item, CrucibleLiquid liquid) {
removeMeltRecipe(item, -1, liquid);
}
/**
* Sets the given CrucibleLiquid as an actual CrucibleLiquid that can be used.
* @param liquid The liquid
*/
public static void registerLiquid(CrucibleLiquid liquid) {
liquids.add(liquid);
}
/**
* Removes the liquid from the list of registered liquids. It also removes all of the liquid's
* recipes.
* @param liquid The item
*/
public static void removeLiquid(CrucibleLiquid liquid) {
liquids.remove(liquid);
if (liquidRecipes != null) {
for (Map.Entry entry : liquidRecipes.entrySet()) {
if (((MutablePair) entry.getValue()).left == liquid) {
liquidRecipes.remove(entry.getKey());
}
}
}
}
/**
* Adds an enhancement to the list of valid enhancements.
* @param enhancement The IEnhancement to add.
*/
public static void registerEnhancement(IEnhancement enhancement) {
enhancements.put(enhancement.getID(), enhancement);
}
/**
* Adds a rocket to the valid rockets for the Rocket Launcher.
* @param rocket The IRocket to add.
*/
public static void registerRocket(IRocket rocket) {
rockets.add(rocket);
}
} |
import React, { useEffect, useState } from "react";
import PokemonList from "./PokemonList";
import axios from "axios";
import Paginations from "./Pagination";
const Pokemon = () => {
const [pokemon,setPokemon] = useState([])
const [currentPageUrl,setCurrentPageUrl] = useState('https://pokeapi.co/api/v2/pokemon')
const [loading,setLoading] = useState(true)
const [nextPageUrl,setNextPageUrl] = useState()
const [prevPageUrl,setPrevPageUrl] = useState()
useEffect(()=>{
setLoading(true)
let cancel
axios
.get(currentPageUrl,{
cancelToken: new axios.CancelToken(c=> cancel=c)
})
.then(res => {
setLoading(false)
setNextPageUrl(res.data.next)
setPrevPageUrl(res.data.previous)
setPokemon(res.data.results.map(p=>p.name))
})
return ()=>cancel()
},[currentPageUrl])
if(loading) return "Loading..."
const gotoNextPage = () => {
setCurrentPageUrl(nextPageUrl)
}
const gotoPrevPage = () => {
setCurrentPageUrl(prevPageUrl)
}
return(
<>
<PokemonList pokemon={pokemon} />
<Paginations
gotoNextPage={nextPageUrl ? gotoNextPage : null}
gotoPrevPage={prevPageUrl ? gotoPrevPage : null}
/>
</>
)
}
export default Pokemon; |
import { TrianglesDriver } from './Triangles.driver';
import Chance from 'chance';
const chance = new Chance();
describe('Triangles', () => {
let driver: TrianglesDriver;
beforeAll(() => {
driver = new TrianglesDriver();
});
it('should render button', () => {
const label = chance.word();
const element = driver.given
.props({
title: label,
})
.when.rendered();
const containerClassName = element.get.containerClassName();
const innerText = element.get.label();
expect(containerClassName).toContain('Triangles-wrapper');
expect(innerText).toBe(label);
});
it('should click button', () => {
const callback = jest.fn();
driver.given
.props({
onClick: callback,
})
.when.rendered()
.when.clicked();
expect(callback).toHaveBeenCalledTimes(1);
});
});
describe('Triangles snapshots', () => {
let driver: TrianglesDriver;
beforeAll(() => {
driver = new TrianglesDriver();
});
it('should match snapshot', () => {
expect(driver.when.snapshot()).toMatchSnapshot();
});
}); |
/**
* CheckoutSummary Component - Created by miguelcanobbio on 03/09/18.
*/
import * as React from 'react'
import PaypalExpressBtn from 'react-paypal-express-checkout-authorize'
import MediaQuery from 'react-responsive'
import { graphql, compose } from 'react-apollo'
import get from 'lodash/get'
import Modal from 'antd/lib/modal'
import messages from './messages'
import {
Container,
PlaceIcon,
ContinueIcon,
ContinueButton,
paypalButtonStyle,
PlaceOrderButton,
CancelButton,
ModalTitle,
cancelButtonStyle,
buttonStyle,
InfoBody
} from './styledComponents'
import { getTaxQuery, isScaPaymentQuery } from './data'
import {
CouponCode,
QueryProps,
NetsuiteTax,
NetsuiteShipping,
AddressObj,
TaxAddressObj,
SimpleCart,
ProductPrice,
SubsidiarySCA
} from '../../../types/common'
import OrderSummary from '../../../components/OrderSummary'
import config from '../../../config/index'
import { COUNTRY_CODE_US, PaymentOptions } from '../constants'
import {
getTaxesAndDiscount,
roundDecimals
} from '../../../utils/utilsCheckout'
const { confirm } = Modal
interface Data extends QueryProps {
taxes: NetsuiteTax
shipping: NetsuiteShipping
}
interface Props {
showOrderButton: boolean
taxShipQuery?: Data
subsidiaryQuery?: SubsidiarySCA
subtotal: number
youthTotal?: number
shipping?: number
totalWithoutDiscount?: number
discount?: number
onlyRead?: boolean
country?: string
weight: number
upgrades?: number
variables?: number
currentStep?: number
shipAddress?: TaxAddressObj
shipAddressCountry?: string
proDesignReview?: number
currencySymbol?: string
showCouponInput?: boolean
paymentMethod: string
currentCurrency: string
showDiscount?: boolean
placingOrder?: boolean
isFixedStore?: boolean
disabledContinue?: boolean
history: any
totalReducer?: number
setTotalReducer: (value: number) => void
formatMessage: (messageDescriptor: any) => string
couponCode?: CouponCode
productsPrices: ProductPrice[]
setCouponCodeAction?: (code: CouponCode) => void
deleteCouponCodeAction?: () => void
handleNextStep?: () => void
onPaypalSuccess: (payment: any) => void
onPaypalCancel: (data: AnalyserNode) => void
onPaypalError: (err: any) => void
onPlaceOrder: (event: any, sca?: boolean) => void
}
const CheckoutSummary = ({
paymentMethod,
subtotal,
youthTotal,
country,
shipAddressCountry,
weight,
formatMessage,
proDesignReview,
currencySymbol,
showDiscount,
upgrades = 0,
variables = 0,
couponCode,
disabledContinue = false,
history,
isFixedStore,
totalWithoutDiscount = 0,
setCouponCodeAction,
deleteCouponCodeAction,
showOrderButton,
onPaypalSuccess,
onPaypalError,
onPaypalCancel,
currentCurrency,
onPlaceOrder,
currentStep,
handleNextStep,
placingOrder = false,
shipping,
subsidiaryQuery,
taxShipQuery,
productsPrices,
totalReducer,
setTotalReducer
}: Props) => {
let paypalClientId
const subsidiarySCA = get(subsidiaryQuery, 'subsidiarySCA', { subsidiary: 1, sca: false })
switch (subsidiarySCA.subsidiary) {
case 1:
paypalClientId = config.paypalClientIdUS
break
case 6:
paypalClientId = config.paypalClientIdCA
break
default:
paypalClientId = config.paypalClientIdUS
break
}
const paypalClient = {
sandbox: paypalClientId,
production: paypalClientId
}
const shippingTotal = get(taxShipQuery, 'shipping.total', shipping) || 0
const taxRates = get(taxShipQuery, 'taxes', undefined)
// countries to compare tax
const countrySubsidiary = (taxRates && taxRates.countrySub) || COUNTRY_CODE_US
const shippingAddressCountry = shipAddressCountry || COUNTRY_CODE_US
// pro design fee
const proDesignFee = proDesignReview || 0
const {
taxGst,
taxPst,
taxFee,
taxVat,
taxVatTotal,
discount: discountValue,
freeShipping
} = getTaxesAndDiscount(
countrySubsidiary,
shippingAddressCountry,
subtotal,
shippingTotal,
proDesignFee,
couponCode,
taxRates,
country,
productsPrices,
upgrades,
variables,
youthTotal
)
const discount =
discountValue > subtotal ? subtotal : discountValue
let totalSum = 0
// calculate totalSum
if (taxVat) {
totalSum =
subtotal / (1 + taxVatTotal) +
taxVat +
(freeShipping ? 0 : shippingTotal) +
upgrades +
variables +
proDesignFee -
discount
} else {
totalSum =
subtotal +
upgrades +
variables +
proDesignFee +
(freeShipping ? 0 : shippingTotal) +
taxFee +
taxGst +
taxPst -
discount
}
totalSum = roundDecimals(totalSum) // round to 2 decimals
const previousDiscount = totalWithoutDiscount - subtotal
const currency = currentCurrency
? currentCurrency.toUpperCase()
: config.defaultCurrency.toUpperCase()
const handleOnPlaceOrder = (event) => onPlaceOrder(event)
// const handleOnPlaceOrder = (event) => onPlaceOrder(event, subsidiarySCA.sca)
const orderButtonComponent =
paymentMethod === PaymentOptions.PAYPAL ? (
<PaypalExpressBtn
env={config.paypalEnv}
client={paypalClient}
shipping={1}
onSuccess={onPaypalSuccess}
onCancel={onPaypalCancel}
onError={onPaypalError}
style={paypalButtonStyle}
paymentOptions={{ intent: 'authorize' }}
total={totalSum}
{...{ currency }}
/>
) : (
<PlaceOrderButton loading={placingOrder} disabled={placingOrder} onClick={handleOnPlaceOrder}>
<PlaceIcon type="check" />
{formatMessage(messages.placeOrder)}
</PlaceOrderButton>
)
const continueButton =
<ContinueButton disabled={disabledContinue} onClick={handleNextStep}>
{formatMessage(messages.continue)}
<ContinueIcon type="right" />
</ContinueButton>
const handleCancel = () => {
confirm({
title: <ModalTitle>{formatMessage(messages.areYouSure)}</ModalTitle>,
icon: ' ',
centered: true,
cancelText: formatMessage(messages.cancel),
okText: formatMessage(messages.yes),
cancelButtonProps: {
style: cancelButtonStyle
},
okButtonProps: {
style: buttonStyle
},
onOk: () => {
history.push('/shopping-cart')
},
content: <InfoBody>{formatMessage(messages.promptReturn)}</InfoBody>
})
}
const orderButton = showOrderButton ? orderButtonComponent : continueButton
return (
<Container>
<MediaQuery maxWidth={480}>
{currentStep === 2 ? orderButton : null}
<CancelButton onClick={handleCancel}>{formatMessage(messages.cancel)}</CancelButton>
</MediaQuery>
<OrderSummary
weight={weight.toString()}
showCouponInput={true}
simpleDesign={true}
youSaved={previousDiscount}
{...{
subtotal,
formatMessage,
proDesignReview,
currencySymbol,
isFixedStore,
showDiscount,
couponCode,
upgrades,
variables,
totalReducer,
setTotalReducer,
totalWithoutDiscount,
setCouponCodeAction,
deleteCouponCodeAction,
taxFee,
shippingTotal,
discount,
taxGst,
taxPst,
taxVat,
totalSum
}}
/>
<MediaQuery minWidth={481}>
{orderButton}
<CancelButton onClick={handleCancel}>{formatMessage(messages.cancel)}</CancelButton>
</MediaQuery>
</Container>
)
}
interface OwnProps {
country?: string
weight?: string
shipAddress?: AddressObj
simpleCart?: SimpleCart[]
}
const CheckoutSummaryEnhance = compose(
graphql(getTaxQuery, {
name: 'taxShipQuery',
options: ({ country, shipAddress, simpleCart }: OwnProps) => ({
skip: !country || !shipAddress || !simpleCart,
variables: { country, shipAddress, cart: simpleCart },
fetchPolicy: 'network-only'
})
}),
graphql(isScaPaymentQuery, {
name: 'subsidiaryQuery',
options: ({ country }: OwnProps) => ({
skip: !country,
variables: { code: country },
fetchPolicy: 'network-only'
})
})
)(CheckoutSummary)
export default CheckoutSummaryEnhance |
<template>
<div class="fixed z-10 inset-0 overflow-y-auto" :class="{hidden: !authState}" id="modal">
<div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center
sm:block sm:p-0">
<div class="fixed inset-0 transition-opacity">
<div class="absolute inset-0 bg-gray-800 opacity-75"></div>
</div>
<!-- This element is to trick the browser into centering the modal contents. -->
<span class="hidden sm:inline-block sm:align-middle sm:h-screen">​</span>
<div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden
shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
<!-- Add margin if you want to see some of the overlay behind the modal-->
<div class="py-4 text-left px-6">
<!--Title-->
<div class="flex justify-between items-center pb-4">
<p class="text-2xl font-bold">Your Account</p>
<!-- Modal Close Button -->
<div class="modal-close cursor-pointer z-50" @click="toggleAuthState">
<i class="fas fa-times"></i>
</div>
</div>
<!-- Tabs -->
<ul class="flex flex-wrap mb-4">
<li class="flex-auto text-center">
<a class="block rounded py-3 px-4 transition hover:text-white"
:class="[formTab? 'bg-blue-600 text-white' : 'text-black']" href="#" @click="toggleFormTab">Login</a>
</li>
<li class="flex-auto text-center">
<a class="block rounded py-3 px-4 transition hover:text-white"
:class="[!formTab ? 'bg-blue-600 text-white' : '' ]" href="#" @click="toggleFormTab">Register</a>
</li>
</ul>
<!-- Login Form -->
<form v-show="formTab">
<!-- Email -->
<div class="mb-3">
<label class="inline-block mb-2">Email</label>
<input type="email"
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded"
placeholder="Enter Email" />
</div>
<!-- Password -->
<div class="mb-3">
<label class="inline-block mb-2">Password</label>
<input type="password"
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded"
placeholder="Password" />
</div>
<button type="submit"
class="block w-full bg-purple-600 text-white py-1.5 px-3 rounded transition
hover:bg-purple-700">
Submit
</button>
</form>
<!-- Registration Form -->
<form v-show="!formTab">
<!-- Name -->
<div class="mb-3">
<label class="inline-block mb-2">Name</label>
<input type="text"
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded"
placeholder="Enter Name" />
</div>
<!-- Email -->
<div class="mb-3">
<label class="inline-block mb-2">Email</label>
<input type="email"
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded"
placeholder="Enter Email" />
</div>
<!-- Age -->
<div class="mb-3">
<label class="inline-block mb-2">Age</label>
<input type="number"
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded" />
</div>
<!-- Password -->
<div class="mb-3">
<label class="inline-block mb-2">Password</label>
<input type="password"
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded"
placeholder="Password" />
</div>
<!-- Confirm Password -->
<div class="mb-3">
<label class="inline-block mb-2">Confirm Password</label>
<input type="password"
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded"
placeholder="Confirm Password" />
</div>
<!-- Country -->
<div class="mb-3">
<label class="inline-block mb-2">Country</label>
<select
class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition
duration-500 focus:outline-none focus:border-black rounded">
<option value="USA">USA</option>
<option value="Mexico">Mexico</option>
<option value="Germany">Germany</option>
</select>
</div>
<!-- TOS -->
<div class="mb-3 pl-6">
<input type="checkbox" class="w-4 h-4 float-left -ml-6 mt-1 rounded" />
<label class="inline-block">Accept terms of service</label>
</div>
<button type="submit"
class="block w-full bg-purple-600 text-white py-1.5 px-3 rounded transition
hover:bg-purple-700">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
export default {
name: 'AppAuth',
data() {
return {
formTab: true
}
},
component: {
},
computed: {
...mapState(["authState"])
},
methods: {
...mapMutations(["toggleAuthState"]),
// toggleForm from registration to login
toggleFormTab(){
this.formTab = !this.formTab
}
}
}
</script>
<style>
</style> |
import { RouteNftResponse, NftItem, VennNftItem} from "@/types";
const apiKey = process.env.SEPOLIA_ALCHEMY_API_KEY;
function bigintReplacer(key: string, value: any) {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
}
function getNftsFromData (alchemyResponse: any, address: string) {
let nfts : VennNftItem[] | null = [];
if (alchemyResponse.totalCount > 0 && alchemyResponse.ownedNfts) {
for (let nft of alchemyResponse.ownedNfts) {
const image : string | null = nft.image.originalUrl ?? null;
const cachedImage : string | null = nft.image.cachedUrl ?? null;
nfts.push({
contractAddress: nft.contract?.address as string,
owner: address,
tokenId: nft.tokenId as string,
name: nft.name as string,
description: nft.description as string,
tokenUri: nft.tokenUri,
image: image,
imageCached: cachedImage,
isRental: null
})
}
}
return nfts;
}
function processApiData (apiData: any, address: string): RouteNftResponse {
const nftItems = getNftsFromData(apiData, address);
const validAt = apiData.validAt;
return {
nfts: nftItems,
validAt
}
}
export async function fetchAddressDataAlchemy (network: string, address: string) {
console.log('alchemy apikey', apiKey)
const options = {method: 'GET', headers: {accept: 'application/json'}};
try {
const response = await fetch(`https://${network}.g.alchemy.com/nft/v3/${apiKey}/getNFTsForOwner?owner=${address}&withMetadata=true&pageSize=100`, options)
const responseJson = await response.json();
const apiData = processApiData(responseJson, address);
// console.log(apiData)
const data = JSON.stringify(apiData, bigintReplacer);
return JSON.parse(data);
} catch (error) {
console.error(error);
throw new Error('Error fetching NFT data');
}
} |
import { Test, TestingModule } from '@nestjs/testing';
import { PostsService } from './posts.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Board } from '../boards/model/boards.entity';
import { Reply } from '../replies/models/replies.entity';
import { RepliesService } from '../replies/replies.service';
import { User } from '../users/models/users.entity';
import { DeleteResult, Repository, UpdateResult } from 'typeorm';
import { Post } from './models/posts.entity';
import { CreatePostDto } from './dtos';
const expectedBoard: Board = {
id: 1,
name: expect.any(String),
description: expect.any(String),
createdAt: expect.any(Date),
posts: [],
};
const expectedUser: User = {
id: 1,
role: expect.any(String),
username: expect.any(String),
hash: expect.any(String),
email: expect.any(String),
imageURL: expect.any(String),
createdAt: expect.any(Date),
updatedAt: expect.any(Date),
posts: [],
replies: [],
confimationCode: expect.any(String),
status: expect.any(String),
};
describe('PostsService', () => {
let service: PostsService;
let replyRepository: Repository<Reply>;
let postRepository: Repository<Post>;
let boardRepository: Repository<Board>;
let userRepository: Repository<User>;
const REPLY_REPOSITORY_TOKEN = getRepositoryToken(Reply);
const POST_REPOSITORY_TOKEN = getRepositoryToken(Post);
const BOARD_REPOSITORY_TOKEN = getRepositoryToken(Board);
const USER_REPOSITORY_TOKEN = getRepositoryToken(User);
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
PostsService,
RepliesService,
{
provide: REPLY_REPOSITORY_TOKEN,
useValue: {},
},
{
provide: POST_REPOSITORY_TOKEN,
useValue: {
find: jest.fn(),
create: jest.fn(),
save: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
},
{
provide: BOARD_REPOSITORY_TOKEN,
useValue: {
findOneBy: jest.fn(),
},
},
{
provide: USER_REPOSITORY_TOKEN,
useValue: {
findOneBy: jest.fn(),
},
},
],
}).compile();
service = module.get<PostsService>(PostsService);
replyRepository = module.get<Repository<Reply>>(REPLY_REPOSITORY_TOKEN);
postRepository = module.get<Repository<Post>>(POST_REPOSITORY_TOKEN);
boardRepository = module.get<Repository<Board>>(BOARD_REPOSITORY_TOKEN);
userRepository = module.get<Repository<User>>(USER_REPOSITORY_TOKEN);
service = module.get<PostsService>(PostsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('fetchPostsByBoardId', () => {
it('should return an array of Post objects using the board id', async () => {
const expectedResult: Post[] = [];
const findSpy = jest
.spyOn(postRepository, 'find')
.mockResolvedValue(expectedResult);
const result: Post[] = await service.fetchPostsByBoardId(1);
expect(findSpy).toBeCalledWith({
where: { board: { id: expect.any(Number) } },
});
expect(result).toEqual(expectedResult);
});
});
describe('fetchPostsByUserId', () => {
it("should return an array of Post objects using the user's id", async () => {
const expectedResult: Post[] = [];
const findSpy = jest
.spyOn(postRepository, 'find')
.mockResolvedValue(expectedResult);
const result: Post[] = await service.fetchPostsByUserId(1);
expect(findSpy).toBeCalledWith({
where: { user: { id: expect.any(Number) } },
});
expect(result).toEqual(expectedResult);
});
});
describe('createPost', () => {
it('should create a post and return a post object', async () => {
const postDetails: CreatePostDto = {
title: 'something random',
content: 'somethind wild stuff',
};
const expectedPost: Post = {
id: expect.any(Number),
title: 'something random',
content: 'somethind wild stuff',
createdAt: expect.any(Date),
updatedAt: expect.any(Date),
edited: expect.any(Boolean),
board: expect.any(Board),
user: expect.any(User),
replies: [],
};
const boardFindByOneSpy = jest
.spyOn(boardRepository, 'findOneBy')
.mockResolvedValue(expectedBoard);
const userFindByOneSpy = jest
.spyOn(userRepository, 'findOneBy')
.mockResolvedValue(expectedUser);
const createSpy = jest
.spyOn(postRepository, 'create')
.mockReturnValue(expectedPost);
const saveSpy = jest
.spyOn(postRepository, 'save')
.mockResolvedValue(expectedPost);
const result: Post = await service.createPost(postDetails, 1, 1);
expect(boardFindByOneSpy).toBeCalledWith({ id: 1 });
expect(userFindByOneSpy).toBeCalledWith({ id: 1 });
expect(createSpy).toBeCalled();
expect(saveSpy).toBeCalled();
expect(result).toEqual(expectedPost);
});
});
describe('updatePost', () => {
it('should update a post and return an UpdateResult object', async () => {
const expectedResult: UpdateResult = {
raw: [],
generatedMaps: [],
affected: 1,
};
const postDetails: CreatePostDto = {
title: 'something random',
content: 'somethind wild stuff',
};
const boardFindByOneSpy = jest
.spyOn(boardRepository, 'findOneBy')
.mockResolvedValue(expectedBoard);
const userFindByOneSpy = jest
.spyOn(userRepository, 'findOneBy')
.mockResolvedValue(expectedUser);
jest.spyOn(service, 'checkUserOwnership').mockResolvedValue(true);
const updateSpy = jest
.spyOn(postRepository, 'update')
.mockResolvedValue(expectedResult);
const result: UpdateResult = await service.updatePost(
1,
postDetails,
1,
1,
);
expect(boardFindByOneSpy).toBeCalledWith({ id: 1 });
expect(userFindByOneSpy).toBeCalledWith({ id: 1 });
expect(updateSpy).toBeCalled();
expect(result).toEqual(expectedResult);
});
});
describe('deletePost', () => {
it('should delete a post and return a DeleteResult object', async () => {
const expectedResult: DeleteResult = {
raw: [],
affected: 1,
};
const deleteSpy = jest
.spyOn(postRepository, 'delete')
.mockResolvedValue(expectedResult);
jest.spyOn(service, 'checkUserOwnership').mockResolvedValue(true);
const result: DeleteResult = await service.deletePost(1, 1);
expect(deleteSpy).toBeCalled();
expect(result).toEqual(expectedResult);
});
});
}); |
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate } from "react-router-dom";
import globalStyles from "./GlobalStyles.module.css";
import localStyles from "./Packages.module.css";
import { orderActions } from "../store/orderSlice";
import { formatAmount } from "../helpers/formatAmount";
import useLoadLocation from "../hooks/useLoadLocation";
import useLoadPackages from "../hooks/useLoadPackages";
const schema = z.object({
packageSelection: z.string(),
});
export let CURRENCY = "";
const Packages = () => {
const { data: locationResponse } = useLoadLocation();
const { data: packageResponse, error, isLoading } = useLoadPackages();
const packages = packageResponse?.data;
CURRENCY = locationResponse?.data.currency;
const order = useSelector((state) => state.order);
const navigate = useNavigate();
const defaultFormValue = order.packageId;
const { register, handleSubmit, formState } = useForm({
resolver: zodResolver(schema),
});
const { errors } = formState;
const dispatch = useDispatch();
const selectPackage = (formValues) => {
if (!error) {
const selectedPackage = packages.find(
(item) => formValues.packageSelection === item.id
);
dispatch(
orderActions.updatePackage({
packageId: formValues.packageSelection,
amount: selectedPackage.price.amount,
})
);
navigate("/user-details");
}
};
if (isLoading) {
return <h2 className={globalStyles.header}>Loading package data</h2>;
}
return (
<div>
{error ? (
<h2 className={globalStyles.header}>Error! {error.message}</h2>
) : (
<>
<h2 className={globalStyles.header}>Select a package</h2>
<form onSubmit={handleSubmit(selectPackage)}>
{packages?.map((item, index) => {
return (
<div key={item.id} className={globalStyles.content}>
<div>
<label htmlFor={item.id}>
<input
type="radio"
id={item.id}
name="packageSelection"
value={item.id}
defaultChecked={item.id === defaultFormValue}
{...register("packageSelection")}
/>
{item.title} (
<span>
{item.reportCount}{" "}
{item.reportCount === 1 ? "report" : "reports"}
</span>
)
</label>
</div>
<div>
{index !== 0 && (
<span className={localStyles.priceOld}>
{formatAmount(packages[0].price.amount * (index + 1))}
</span>
)}
<span>{formatAmount(item.price.amount)}</span>
</div>
</div>
);
})}
{errors.packageSelection && (
<p className={globalStyles.error}>Please select a package</p>
)}
<button className={globalStyles.button}>Next</button>
</form>
</>
)}
</div>
);
};
export default Packages; |
## 2564. Substring XOR Queries
📎 Link: [Substring XOR Queries](https://leetcode.com/problems/substring-xor-queries/description/)<br>
🟠 Difficulty: Medium<br>
👩🏻💻 Topics: Array, Hash Table, String, Bit Manipulation<br>
You are given a binary string s, and a 2D integer array queries where queries[i] = [firsti, secondi].<br>
For the ith query, find the shortest substring of s whose decimal value, val, yields secondi when bitwise XORed with firsti. In other words, val ^ firsti == secondi.<br>
The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum lefti.<br>
Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query.<br>
A substring is a contiguous non-empty sequence of characters within a string.<br>
Example 1:<br>
Input: s = "101101", queries = [[0,5],[1,2]]<br>
Output: [[0,2],[2,3]]<br>
Explanation: For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query.<br>
Example 2:<br>
Input: s = "0101", queries = [[12,8]]<br>
Output: [[-1,-1]]
Explanation: In this example <br>there is no substring that answers the query, hence [-1,-1] is returned.<br>
Example 3:<br>
Input: s = "1", queries = [[4,5]]<br>
Output: [[0,0]]<br>
Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].<br>
<br>
Constraints:<br>
- 1 <= nums.length <= 105<br>
- 0 <= nums[i] <= 105<br>
### UMPIRE Method:
#### Understand
> - Ask clarifying questions and use examples to understand what the interviewer wants out of this problem.
> - Choose a “happy path” test input, different than the one provided, and a few edge case inputs.
> - Verify that you and the interviewer are aligned on the expected inputs and outputs.
1. Any requirement on time/space complexity?
- No
### Match
> - See if this problem matches a problem category (e.g. Strings/Arrays) and strategies or patterns within the category
1. Array<br>
- **Prefix Sum(cumulative sum) is a technique use in array processing**. It involves generating an auxiliary array where each element represents the sum of all elements from the beginning of the input array up to that element.
- The intuition behind this approach is that it allows for efficient computation of subarray sums. This technique is particularly useful in scenarios where we need to repeatedly query the sum of subarrays, such as in range sum queries or finding subarrays with a specific sum.
2. String<br>
3. Bit Manipulation<br>
### Plan
> - Sketch visualizations and write pseudocode
> - Walk through a high level implementation with an existing diagram
General Idea: Use Prefix Sum to pre calculate a total sum and quickly calculate the sum of any subarray by simply subtracting two cumulative sums. Calculate the absolute differences and replace the minimum each time.
1. Pre calculate the total:
- Initiate a for-loop to calculate sum of the entire Array and assign to a variable.
2. Calculate sum of subarrays:
- Initiate another for-loop to calculate the subarrays. Calculate the left subarray starting far left and move towards the right. Each time calculate the right subarray utilizing the pre-calculated total.
3. Handle when divisor is zero:
- The divisor(rightCount) for calculating the right subarray will always end up being zero. Handle the case with ternary operator (i == length - 1 ? 1 : rightCount).
- The expression to evaluate when the condition is true could be any number, since the rightSum would be zero as well.
4. Calculate absolute difference:
- After computing both left and right average, calculate the abosulte difference.
5. Replace the minimum difference:
- Compare the current difference with the stored minimum difference each time and replace with the smaller one.
- Keep track of the index and return.
### Implement
> - Implement the solution (make sure to know what level of detail the interviewer wants)
see solution.py
### Review
> - Re-check that your algorithm solves the problem by running through important examples
> - Go through it as if you are debugging it, assuming there is a bug
### Evaluate
> - Finish by giving space and run-time complexity
> - Discuss any pros and cons of the solution
- Time Complexity: O(N)
- Space Complexity: O(1) |
---
title: New In 2024, Cloud Stop Motion 101 Getting Started with Software, Guidelines, and Alternatives
date: 2024-05-19T13:04:14.374Z
updated: 2024-05-20T13:04:14.374Z
tags:
- video editing software
- video editing
categories:
- ai
- video
description: This Article Describes New In 2024, Cloud Stop Motion 101 Getting Started with Software, Guidelines, and Alternatives
excerpt: This Article Describes New In 2024, Cloud Stop Motion 101 Getting Started with Software, Guidelines, and Alternatives
keywords: animate in the cloud stop motion software features guidelines and alternatives compared,cloud stop motion software features guidelines and alternatives,ai animation cloud stop motion software features guidelines and alternatives,stop motion made easy cloud software guidelines and alternatives,cloud stop motion software guidelines and alternatives,ai animation cloud stop motion software guidelines and alternatives,cloud stop motion 101 getting started with software guidelines and alternatives
thumbnail: https://www.lifewire.com/thmb/J824Ra8KQFbLaWC_ATGxX22EzOA=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/trends_MontyRakusen_Getty-5a4aa079482c5200362b0987.jpg
---
## Cloud Stop Motion 101: Getting Started with Software, Guidelines, and Alternatives
Creating a stop motion video is a fascinating process. If you use the right software and know the basics of making videos, you can create fantastic animations. While creating a stop motion video, there are things to keep in mind, like keeping the cameras steady and using the proper audio effects. Cloud Stop motion is well-known software with the tools to create unique video projects on your smartphone, laptop, desktop, Chromebook, or even tablet.
## Part 1\. Introduction- Cloud Stop Motion
It is easy to create stop motion animation with this web-based app. To use cloud stop motion you must first create an account and grant the app permission to your computer's webcam. Then you can start a new project and start taking pictures.
Each image is displayed on the timeline to know all photos that are going to be included in the stop motion video. On Cloud Stop Motion, you have the option to either record or import audio files from the sound library or your device. You can add additional things, like opening titles, end credits, speech bubbles, and text overlays. It functions directly in the browser on any modern device.
You do not have to install anything. It is all saved to the cloud. You can work with your animation on a zoomable, scrollable timeline.
Features -
* Easy to use, powerful, and intuitive software to create animations.
* The Interface has a modern design.
* It is equipped with a rich audio library, backgrounds and styles included.
* You can switch devices seamlessly at any point.
## Part 2\. How to Use Cloud Stop Motion to Create Animation Videos?
Cloud Stop Motion is a great browser-based app that one can use to create fun animation videos. You can use Cloud Stop Motion even when you have not created your account. But consider creating an account to enjoy additional features.

Before you open Cloud Stop Motion and start clicking pictures of your subject for your video, it is important to have a story in mind. So, create a storyboard to break down your stop motion video. You can sketch your plan frame by frame or write bulleted list of your frames. It will help you create your project efficiently, ensuring that you have taken pictures of all the frames that you need to tell your story.

Step 1: Once you have created your storyboard, open the app to go to the Cloud Stop Motion dashboard. Click on the new project button. Cloud Stop Motion needs access to your camera for capturing images. So, allow camera access.

On the dashboard, go to the taking picture menu. Now place the subject at the center of your frame. Capture a few test shots to find the composition that you like. You can see the picture at the bottom of the timeline. If needed, adjust the position of your subject. Make sure that the location you choose has plenty of light. If not, you also use a lamp for good light.
Tip: Keeping your phone or camera steady while making your stop-motion project is the key. You can use a tripod, a selfie stick, or a gimbal to keep your device as still as possible. If you don't own any of these, keep your device on something sturdy and make sure that you do not change its place until you capture all the images needed for your project. This way all your shots will be consistent.
Step 2: Move your subject or change its position and take a picture. Repeat the process until you complete your story. To make your stop-motion smooth, make small changes to the position of your subject between shots.

You can also add more frames per second. Generally, you should add 10 frames per second. But you can go for 25 frames per second to make a smoother video. All the pictures you snap are automatically added to the editor in chronological order.
Step 3: Once you have captured images for your project, add sound by going to the sound menu in the top left of the dashboard. You can record sounds, upload sounds, or select sounds from Cloud Stop Motion's gallery. You can also add text to your Cloud Stop Motion project if you want.
Step 4: Click on play button to preview your project and see if your motion picture turned out as per your liking or not. If you do not like something, go back and make changes. Once done, download your video from cloudstop motion.
Part 3\. 3 Alternatives for Cloud Stop Motion
Are you ready to turn your video clips and images into a stop motion movie? Have a look at all these software that can create animations wonderfully well. You can share the animations with your friends on social media platforms. The stop motion effect is ideal for action videos.
### 1\. Stop Motion Animator
It is a simple tool for creating stop motion animation sequences using a webcam. You can save the animation as a video file in the widely-supported webm format. The videos previously saved can be loaded into the app and extended. Stop Motion Animator is free software that lets you create fantastic stop motion videos. It is an open-source, non-commercial app.
It does not collect any data, and it does not connect to the internet at all.

### 2\. Kapwig
Whether you're a beginner video creator or advanced, Kapwing is the right tool to create stop motion animation. It is an all-in-one online video studio as it has an intuitive timeline, advanced editor, and plugin ecosystem that will help you make next-level videos.
Kapwing Studio supports many different file types like MP4, MOV, AVI, 3GP. Record video clips, add voiceovers and add images and texts to create a fresh stop motion video. Then you can edit them in the browser from any device. If you like how the final video looks, click "Export." Download the MP4 file directly, publish the video on social media, or share the link with your friends.
You can customize the output video size in 1:1, 9:16, 16:9, 4:5, or 5:4\. Sign in to the Kapwing account to remove the watermark.

### 3\. Clideo
Clideo is a high-speed stop motion maker with an easy-to-use dashboard and instant download. It is compatible with almost all the video formats such as AVI, MPG, VOB, WMV, MOV, and more. When creating a stop motion, you can choose from various frame and clip rates available. They slow down, speed up or maintain the same speed for your video. The interface is intuitive, so you don't have to have experience using the stop motion editor.
Just upload a video file from your device- whether it's a computer, iPhone, or android phone. Apply the effects that go with your movie. You can watch the final result and click the "Download" button.

### Closing Word
Recording and editing stop motion animation has never been easier. You can thousands of images and create video projects quickly on Cloud stop motion.
Each software we include in this article grants you access to all the necessary tools you'll need while creating a stop motion animation. Are you impressed with cloud stop motion or one of the alternatives? Leave a comment and let us know.[](https://tools.techidaily.com/wondershare/filmora/download/)
Part 2\. How to Use Cloud Stop Motion to Create Animation Videos?
Cloud Stop Motion is a great browser-based app that one can use to create fun animation videos. You can use Cloud Stop Motion even when you have not created your account. But consider creating an account to enjoy additional features.

Before you open Cloud Stop Motion and start clicking pictures of your subject for your video, it is important to have a story in mind. So, create a storyboard to break down your stop motion video. You can sketch your plan frame by frame or write bulleted list of your frames. It will help you create your project efficiently, ensuring that you have taken pictures of all the frames that you need to tell your story.

Step 1: Once you have created your storyboard, open the app to go to the Cloud Stop Motion dashboard. Click on the new project button. Cloud Stop Motion needs access to your camera for capturing images. So, allow camera access.

On the dashboard, go to the taking picture menu. Now place the subject at the center of your frame. Capture a few test shots to find the composition that you like. You can see the picture at the bottom of the timeline. If needed, adjust the position of your subject. Make sure that the location you choose has plenty of light. If not, you also use a lamp for good light.
Tip: Keeping your phone or camera steady while making your stop-motion project is the key. You can use a tripod, a selfie stick, or a gimbal to keep your device as still as possible. If you don't own any of these, keep your device on something sturdy and make sure that you do not change its place until you capture all the images needed for your project. This way all your shots will be consistent.
Step 2: Move your subject or change its position and take a picture. Repeat the process until you complete your story. To make your stop-motion smooth, make small changes to the position of your subject between shots.

You can also add more frames per second. Generally, you should add 10 frames per second. But you can go for 25 frames per second to make a smoother video. All the pictures you snap are automatically added to the editor in chronological order.
Step 3: Once you have captured images for your project, add sound by going to the sound menu in the top left of the dashboard. You can record sounds, upload sounds, or select sounds from Cloud Stop Motion's gallery. You can also add text to your Cloud Stop Motion project if you want.
Step 4: Click on play button to preview your project and see if your motion picture turned out as per your liking or not. If you do not like something, go back and make changes. Once done, download your video from cloudstop motion.
Part 3\. 3 Alternatives for Cloud Stop Motion
Are you ready to turn your video clips and images into a stop motion movie? Have a look at all these software that can create animations wonderfully well. You can share the animations with your friends on social media platforms. The stop motion effect is ideal for action videos.
### 1\. Stop Motion Animator
It is a simple tool for creating stop motion animation sequences using a webcam. You can save the animation as a video file in the widely-supported webm format. The videos previously saved can be loaded into the app and extended. Stop Motion Animator is free software that lets you create fantastic stop motion videos. It is an open-source, non-commercial app.
It does not collect any data, and it does not connect to the internet at all.

### 2\. Kapwig
Whether you're a beginner video creator or advanced, Kapwing is the right tool to create stop motion animation. It is an all-in-one online video studio as it has an intuitive timeline, advanced editor, and plugin ecosystem that will help you make next-level videos.
Kapwing Studio supports many different file types like MP4, MOV, AVI, 3GP. Record video clips, add voiceovers and add images and texts to create a fresh stop motion video. Then you can edit them in the browser from any device. If you like how the final video looks, click "Export." Download the MP4 file directly, publish the video on social media, or share the link with your friends.
You can customize the output video size in 1:1, 9:16, 16:9, 4:5, or 5:4\. Sign in to the Kapwing account to remove the watermark.

### 3\. Clideo
Clideo is a high-speed stop motion maker with an easy-to-use dashboard and instant download. It is compatible with almost all the video formats such as AVI, MPG, VOB, WMV, MOV, and more. When creating a stop motion, you can choose from various frame and clip rates available. They slow down, speed up or maintain the same speed for your video. The interface is intuitive, so you don't have to have experience using the stop motion editor.
Just upload a video file from your device- whether it's a computer, iPhone, or android phone. Apply the effects that go with your movie. You can watch the final result and click the "Download" button.

### Closing Word
Recording and editing stop motion animation has never been easier. You can thousands of images and create video projects quickly on Cloud stop motion.
Each software we include in this article grants you access to all the necessary tools you'll need while creating a stop motion animation. Are you impressed with cloud stop motion or one of the alternatives? Leave a comment and let us know.[](https://tools.techidaily.com/wondershare/filmora/download/)
Part 2\. How to Use Cloud Stop Motion to Create Animation Videos?
Cloud Stop Motion is a great browser-based app that one can use to create fun animation videos. You can use Cloud Stop Motion even when you have not created your account. But consider creating an account to enjoy additional features.

Before you open Cloud Stop Motion and start clicking pictures of your subject for your video, it is important to have a story in mind. So, create a storyboard to break down your stop motion video. You can sketch your plan frame by frame or write bulleted list of your frames. It will help you create your project efficiently, ensuring that you have taken pictures of all the frames that you need to tell your story.

Step 1: Once you have created your storyboard, open the app to go to the Cloud Stop Motion dashboard. Click on the new project button. Cloud Stop Motion needs access to your camera for capturing images. So, allow camera access.

On the dashboard, go to the taking picture menu. Now place the subject at the center of your frame. Capture a few test shots to find the composition that you like. You can see the picture at the bottom of the timeline. If needed, adjust the position of your subject. Make sure that the location you choose has plenty of light. If not, you also use a lamp for good light.
Tip: Keeping your phone or camera steady while making your stop-motion project is the key. You can use a tripod, a selfie stick, or a gimbal to keep your device as still as possible. If you don't own any of these, keep your device on something sturdy and make sure that you do not change its place until you capture all the images needed for your project. This way all your shots will be consistent.
Step 2: Move your subject or change its position and take a picture. Repeat the process until you complete your story. To make your stop-motion smooth, make small changes to the position of your subject between shots.

You can also add more frames per second. Generally, you should add 10 frames per second. But you can go for 25 frames per second to make a smoother video. All the pictures you snap are automatically added to the editor in chronological order.
Step 3: Once you have captured images for your project, add sound by going to the sound menu in the top left of the dashboard. You can record sounds, upload sounds, or select sounds from Cloud Stop Motion's gallery. You can also add text to your Cloud Stop Motion project if you want.
Step 4: Click on play button to preview your project and see if your motion picture turned out as per your liking or not. If you do not like something, go back and make changes. Once done, download your video from cloudstop motion.
Part 3\. 3 Alternatives for Cloud Stop Motion
Are you ready to turn your video clips and images into a stop motion movie? Have a look at all these software that can create animations wonderfully well. You can share the animations with your friends on social media platforms. The stop motion effect is ideal for action videos.
### 1\. Stop Motion Animator
It is a simple tool for creating stop motion animation sequences using a webcam. You can save the animation as a video file in the widely-supported webm format. The videos previously saved can be loaded into the app and extended. Stop Motion Animator is free software that lets you create fantastic stop motion videos. It is an open-source, non-commercial app.
It does not collect any data, and it does not connect to the internet at all.

### 2\. Kapwig
Whether you're a beginner video creator or advanced, Kapwing is the right tool to create stop motion animation. It is an all-in-one online video studio as it has an intuitive timeline, advanced editor, and plugin ecosystem that will help you make next-level videos.
Kapwing Studio supports many different file types like MP4, MOV, AVI, 3GP. Record video clips, add voiceovers and add images and texts to create a fresh stop motion video. Then you can edit them in the browser from any device. If you like how the final video looks, click "Export." Download the MP4 file directly, publish the video on social media, or share the link with your friends.
You can customize the output video size in 1:1, 9:16, 16:9, 4:5, or 5:4\. Sign in to the Kapwing account to remove the watermark.

### 3\. Clideo
Clideo is a high-speed stop motion maker with an easy-to-use dashboard and instant download. It is compatible with almost all the video formats such as AVI, MPG, VOB, WMV, MOV, and more. When creating a stop motion, you can choose from various frame and clip rates available. They slow down, speed up or maintain the same speed for your video. The interface is intuitive, so you don't have to have experience using the stop motion editor.
Just upload a video file from your device- whether it's a computer, iPhone, or android phone. Apply the effects that go with your movie. You can watch the final result and click the "Download" button.

### Closing Word
Recording and editing stop motion animation has never been easier. You can thousands of images and create video projects quickly on Cloud stop motion.
Each software we include in this article grants you access to all the necessary tools you'll need while creating a stop motion animation. Are you impressed with cloud stop motion or one of the alternatives? Leave a comment and let us know.[](https://tools.techidaily.com/wondershare/filmora/download/)
Part 2\. How to Use Cloud Stop Motion to Create Animation Videos?
Cloud Stop Motion is a great browser-based app that one can use to create fun animation videos. You can use Cloud Stop Motion even when you have not created your account. But consider creating an account to enjoy additional features.

Before you open Cloud Stop Motion and start clicking pictures of your subject for your video, it is important to have a story in mind. So, create a storyboard to break down your stop motion video. You can sketch your plan frame by frame or write bulleted list of your frames. It will help you create your project efficiently, ensuring that you have taken pictures of all the frames that you need to tell your story.

Step 1: Once you have created your storyboard, open the app to go to the Cloud Stop Motion dashboard. Click on the new project button. Cloud Stop Motion needs access to your camera for capturing images. So, allow camera access.

On the dashboard, go to the taking picture menu. Now place the subject at the center of your frame. Capture a few test shots to find the composition that you like. You can see the picture at the bottom of the timeline. If needed, adjust the position of your subject. Make sure that the location you choose has plenty of light. If not, you also use a lamp for good light.
Tip: Keeping your phone or camera steady while making your stop-motion project is the key. You can use a tripod, a selfie stick, or a gimbal to keep your device as still as possible. If you don't own any of these, keep your device on something sturdy and make sure that you do not change its place until you capture all the images needed for your project. This way all your shots will be consistent.
Step 2: Move your subject or change its position and take a picture. Repeat the process until you complete your story. To make your stop-motion smooth, make small changes to the position of your subject between shots.

You can also add more frames per second. Generally, you should add 10 frames per second. But you can go for 25 frames per second to make a smoother video. All the pictures you snap are automatically added to the editor in chronological order.
Step 3: Once you have captured images for your project, add sound by going to the sound menu in the top left of the dashboard. You can record sounds, upload sounds, or select sounds from Cloud Stop Motion's gallery. You can also add text to your Cloud Stop Motion project if you want.
Step 4: Click on play button to preview your project and see if your motion picture turned out as per your liking or not. If you do not like something, go back and make changes. Once done, download your video from cloudstop motion.
Part 3\. 3 Alternatives for Cloud Stop Motion
Are you ready to turn your video clips and images into a stop motion movie? Have a look at all these software that can create animations wonderfully well. You can share the animations with your friends on social media platforms. The stop motion effect is ideal for action videos.
### 1\. Stop Motion Animator
It is a simple tool for creating stop motion animation sequences using a webcam. You can save the animation as a video file in the widely-supported webm format. The videos previously saved can be loaded into the app and extended. Stop Motion Animator is free software that lets you create fantastic stop motion videos. It is an open-source, non-commercial app.
It does not collect any data, and it does not connect to the internet at all.

### 2\. Kapwig
Whether you're a beginner video creator or advanced, Kapwing is the right tool to create stop motion animation. It is an all-in-one online video studio as it has an intuitive timeline, advanced editor, and plugin ecosystem that will help you make next-level videos.
Kapwing Studio supports many different file types like MP4, MOV, AVI, 3GP. Record video clips, add voiceovers and add images and texts to create a fresh stop motion video. Then you can edit them in the browser from any device. If you like how the final video looks, click "Export." Download the MP4 file directly, publish the video on social media, or share the link with your friends.
You can customize the output video size in 1:1, 9:16, 16:9, 4:5, or 5:4\. Sign in to the Kapwing account to remove the watermark.

### 3\. Clideo
Clideo is a high-speed stop motion maker with an easy-to-use dashboard and instant download. It is compatible with almost all the video formats such as AVI, MPG, VOB, WMV, MOV, and more. When creating a stop motion, you can choose from various frame and clip rates available. They slow down, speed up or maintain the same speed for your video. The interface is intuitive, so you don't have to have experience using the stop motion editor.
Just upload a video file from your device- whether it's a computer, iPhone, or android phone. Apply the effects that go with your movie. You can watch the final result and click the "Download" button.

### Closing Word
Recording and editing stop motion animation has never been easier. You can thousands of images and create video projects quickly on Cloud stop motion.
Each software we include in this article grants you access to all the necessary tools you'll need while creating a stop motion animation. Are you impressed with cloud stop motion or one of the alternatives? Leave a comment and let us know.[](https://tools.techidaily.com/wondershare/filmora/download/)
<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>
## Best Free Video Special Effects Apps [iOS & Android]
# FREE Best Video Special Effects Apps

##### Ollie Mattison
Mar 27, 2024• Proven solutions
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
Every movie clip that you see on a big or small screen has been decorated using a [professional **video special effects app**](https://tools.techidaily.com/wondershare/filmora/download/). Since special effects are added to the footages to make them look more lively and happening, it is important that only highly skilled professionals should do the job.
However, because of the advanced technologies and the robust applications that the developers are coming up with these days, no special training is required to seamlessly [add special effects to the videos](https://tools.techidaily.com/wondershare/filmora/download/), and even a novice user can produce professional-level outputs on their smartphone with the help of all the options and features that these latest software programs offer.
With that said, here you will get to know about some of the best iOS and Android programs that you can use to add special effects to your videos. In addition to this, you will also learn about another most admired and widely used **movie effects app** that is equipped with plethora of templates that you can apply to your clips to make them look more professional.
* [Part 1: Best Free Video Special Effects Apps \[iOS & Android Devices\]](#for%5Fios%5Fandroid)
* [Part 2: 6 Best VFX Apps for iOS](#for%5Fios)
* [Part 3: 4 Best Video Special Effects Apps for Android](#for%5Fandroid)
* [Part 4: Add Video Effects on Desktop \[Bonus\] ](#add%5Feffects%5Ffilmora9)
## Part 1: Best Video Special Effects Apps for Both iPhone and Android: FxGuru
We’ve find FxGuru: Movie FX Director is a special effect app which is available on both iPhone, iPad and Android devices, this **video special effects app for Android** **and iOS** has almost everything you may need in order to give your recorded videos a professional touch. From ghosts to werewolves, UFOs to dragons, and even tornadoes, earthquakes, and meteors, FxGuru has every special effect under one umbrella.
Simply put, with this app on your phone, you only have to use the device’s camera to capture video footage, and then sail away with your imagination to produce industry-standard clips for commercial promotions and/or for fun.

Click to get the [Android](https://play.google.com/store/apps/details?id=com.picadelic.fxguru&hl=en%5FUS) version of this special effect app from the App Store or Google Play.
## Part 2: Best VFX Video Effects Editor Apps for iPhone & iPad
If you are a proud owner of an iOS device, the following **iPhone and iPad video special effects** apps are something you would definitely love to try:
### 1\. Enlight Videoleap Video Editor
With built-in video editor and easy-to-use interface, this **iPhone special effects app** could be the program you have been looking for all along. The software allows keyframe-based [animations](https://tools.techidaily.com/wondershare/filmora/download/), chroma compositing, practically limitless redo and undo iterations, and even non-destructive video editing to make your post-production tasks simple and fun.
With all these features and options, and several more to explore, Enlight Vdeoleap Video Editor leaves no stone unturned to help you produce industry-standard outputs right on your iDevice.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/enlight-videoleap-video-editor/id1255135442)
### 2\. Action Movie FX
With around 4.5-star rating on Apple App Store, this **movie effects app** called Action Movie FX has several Hollywood-style effects templates that let you give more dramatic look to the videos you record from your iDevice. Since the program is a mobile app, you can apply all the VFX right on your iPhone or iPad without transferring the footages to a computer for post-production treatments.
All the built-in effects that Action Movie FX is enriched with such as ALIEN BURST, CAR SMASH, BB-8 Spark, etc. have been designed by some of the most famous artists with ample amount of experience in the field of film production.
[Click to get this app on App Store >>](https://apps.apple.com/au/app/action-movie-fx/id489321253)
### 3\. Movie FX Maker
This **video special effects app** is helpful to apply FX on the images to use them as stickers. Although the program is free to use, the in-app purchases give you access to more advanced movie stickers that would allow you to bring life to the still images without having you to transfer them to your PC and/or using an expensive and complex apps like Photoshop.
All you need to do in order to apply special FX to the images is, capture photos on your iDevice, and add the effects Movie FX Maker has. Post modifications, the images can be shared on your favorite social networking site instantaneously.

#### 4\. Effects Cam – Visual Effects
Yet another **video special effects app**, Effects Cam allows you to add special effects like fire, blasts, explosions, etc. to your images in order to make them look live. The images can be captured right from your device’s camera, or imported from other sources like your PC, phone’s memory, etc. Once imported, you can pick any of the available special FX from the app’s library, and apply it to the photo(s).

[Click to get this app on App Store >>](https://apps.apple.com/au/app/effects-cam-visual-effects/id1123449586)
### 5\. Videorama Text & Video Editor
Videorama Text & Video Editor is an **iPhone video special effects** app that lets you do various tasks such as trim videos, split them, remove unwanted segments, etc. In addition to this, the tool is also capable of adding and animating texts that can be used as captions for the images or motion clips for information.
Apart from the above, adding special video and sound effects is another lucrative feature that Videorama has because of which the app is most admired and used by majority of people across the globe.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/videorama-text-video-editor/id1049690233)
### 6\. LumaFX
Although LumaFX is a paid **video special effects app** for iOS devices, it is worth investing. The software has many features that are mostly found in professional post-production tools. These features include color correction, slow motion effect, frame-by-frame animation using the keyframes, and much more.
In addition to all the above, LumaFX also allows you to add audio effects, thus making the videos more interesting and informative that could be broadcasted for commercial gains or shared among your known ones for fun.

### Watch Video! Best Free Video Special Effects Apps on Apple Store
## Part 2: Best VFX Video Effects Editor Apps for Android
If you are an Android lover and prefer using non-Apple devices, you have plenty of options when it comes to selecting the best **movie effects app** that could enable you to apply special effects to the videos your smart device has or captures using its camera.
In case you are looking for an efficient **video special effects app for Android**, those listed below are worth your attention:
### 1\. Movie Booth FX Free
While using [Movie Booth FX Free](https://play.google.com/store/apps/details?id=bizomobile.actionmovie.free&hl=en%5FUS), all you need to do is, record a footage from your camera, and add special effects to it. The three main categories that this **video special effects app** ships along with include Action, Sci-Fi, and Horror. Depending on the type of footage you captured, and the kind of output you want to have, you can pick any of these categories, and apply your favorite effect that is available within it.

Although the program is free to install, various other options and features can be unlocked by paying for them with in-app purchases.
### 2\. MovieRide FX
[This video special effects app for Android](https://play.google.com/store/apps/details?id=tv.waterston.movieridefx&hl=en%5FUS) has several templates that allow you to apply various VFX to the footages you record using your Android device. With the effects like Space Wars, Space Walk, Thunder Bolt, Storms, etc., you can virtually live in the movies, and act like a character. Although some of the effects that MovieRide FX has are paid, you definitely won’t regret buying them considering the precision and ease at which you can decorate your clips.

### 3\. Movie Effects Maker

Movie Effects Maker, as the name suggests, allows you to add special effects to the images you click with your smartphone. With all the VFX options this **movie effects app** has, you can be virtually anyone you want. For instance, with the sci-fi and horror elements, you can create stickers out of your photos portraying yourself as a hero, add animated effects to your images to make them look live, and much more.
### 4\. Extreme VFX

With this **video special effects app**, all you need to do is, record a footage using your Android smart device, and begin applying special effects to them until you are satisfied with the results. Since the app allows you to add multiple VFX to the clips, nothing seems impossible when it comes to decorating the videos, and making them more engaging and entertaining, especially with you playing as the main character.
[Get this special video effect app from Google Play>>](https://play.google.com/store/apps/details?id=com.kaushal.extremevfx&hl=en%5FUS)
### Watch Video! Best VFX Video Effects Editor Apps for Android
## Part 4: How to Add Special Effects to Videos in Filmora?
Although all the apps listed above are good, when it comes to creating movies with special effects for commercial usage and public broadcasting, nothing can beat the efficiency and robustness of a **movie effects app** that has been designed to run on desktop computers.
Even though there are many [post-production professional applications](https://tools.techidaily.com/wondershare/filmora/download/) by different vendors, [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) has the simplest UI, and follows the most straightforward approach that allows even the novice users to add VFX to their videos.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
The steps given below explain **how to add special effects to your recorded footages with Wondershare Filmora:**
### 1\. Import Video and Add to Timeline
Launch Wondershare Filmora, click anywhere inside the **Media Bin** at the upper-left section, use the **Open** box to import the video you want to add VFX to, hover mouse to the thumbnail of the clip, click the **+** icon from the middle, and click **MATCH TO MEDIA** from the **Project Setting** box when/if it appears.

### 2\. Add Effects and Elements
Place the Playhead (Skimmer) in the Timeline you want to apply effects from, click **Effects** from the standard toolbar at the top, select your preferred category from the left pane, hover mouse to the effect you want to add in the right window, and click the **+** icon from the center.

Optionally you can drag the effect in the Timeline to manage its duration. Next, go to **Elements** from the top, and repeat the process to add your preferred element to the footage.
Besides the included effects and elements in Filmora, you can find our more video effects on Filmstock effects store, including blockbuster, effects for holidays and vacations. Click to [check the free video effects](https://tools.techidaily.com/wondershare/filmora/download/) that you can get for free in Filmstock for Filmora.

### 3\. Export the Output
Click **EXPORT** from the top-center section, go to the **Local** tab from the top of the **Export** box that opens up next, choose your preferred extension from the **Format** list in the left pane, select a destination location in the **Save to** field in the right window, click **SETTINGS** and make necessary adjustments (optional), and click **EXPORT** from the bottom-right corner of the box to begin rendering and to produce the video with the special effects applied to it.

**Conclusion**
With all the programs listed above, selecting the best video special effects app could be a challenging task. Thanks to Wondershare Filmora that not only enables you to add effects and elements to the videos, it is also fast, lightweight, and offers simple and easy-to-use interface that can be exploited to create professional-level outputs in comparatively less time.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
Every movie clip that you see on a big or small screen has been decorated using a [professional **video special effects app**](https://tools.techidaily.com/wondershare/filmora/download/). Since special effects are added to the footages to make them look more lively and happening, it is important that only highly skilled professionals should do the job.
However, because of the advanced technologies and the robust applications that the developers are coming up with these days, no special training is required to seamlessly [add special effects to the videos](https://tools.techidaily.com/wondershare/filmora/download/), and even a novice user can produce professional-level outputs on their smartphone with the help of all the options and features that these latest software programs offer.
With that said, here you will get to know about some of the best iOS and Android programs that you can use to add special effects to your videos. In addition to this, you will also learn about another most admired and widely used **movie effects app** that is equipped with plethora of templates that you can apply to your clips to make them look more professional.
* [Part 1: Best Free Video Special Effects Apps \[iOS & Android Devices\]](#for%5Fios%5Fandroid)
* [Part 2: 6 Best VFX Apps for iOS](#for%5Fios)
* [Part 3: 4 Best Video Special Effects Apps for Android](#for%5Fandroid)
* [Part 4: Add Video Effects on Desktop \[Bonus\] ](#add%5Feffects%5Ffilmora9)
## Part 1: Best Video Special Effects Apps for Both iPhone and Android: FxGuru
We’ve find FxGuru: Movie FX Director is a special effect app which is available on both iPhone, iPad and Android devices, this **video special effects app for Android** **and iOS** has almost everything you may need in order to give your recorded videos a professional touch. From ghosts to werewolves, UFOs to dragons, and even tornadoes, earthquakes, and meteors, FxGuru has every special effect under one umbrella.
Simply put, with this app on your phone, you only have to use the device’s camera to capture video footage, and then sail away with your imagination to produce industry-standard clips for commercial promotions and/or for fun.

Click to get the [Android](https://play.google.com/store/apps/details?id=com.picadelic.fxguru&hl=en%5FUS) version of this special effect app from the App Store or Google Play.
## Part 2: Best VFX Video Effects Editor Apps for iPhone & iPad
If you are a proud owner of an iOS device, the following **iPhone and iPad video special effects** apps are something you would definitely love to try:
### 1\. Enlight Videoleap Video Editor
With built-in video editor and easy-to-use interface, this **iPhone special effects app** could be the program you have been looking for all along. The software allows keyframe-based [animations](https://tools.techidaily.com/wondershare/filmora/download/), chroma compositing, practically limitless redo and undo iterations, and even non-destructive video editing to make your post-production tasks simple and fun.
With all these features and options, and several more to explore, Enlight Vdeoleap Video Editor leaves no stone unturned to help you produce industry-standard outputs right on your iDevice.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/enlight-videoleap-video-editor/id1255135442)
### 2\. Action Movie FX
With around 4.5-star rating on Apple App Store, this **movie effects app** called Action Movie FX has several Hollywood-style effects templates that let you give more dramatic look to the videos you record from your iDevice. Since the program is a mobile app, you can apply all the VFX right on your iPhone or iPad without transferring the footages to a computer for post-production treatments.
All the built-in effects that Action Movie FX is enriched with such as ALIEN BURST, CAR SMASH, BB-8 Spark, etc. have been designed by some of the most famous artists with ample amount of experience in the field of film production.
[Click to get this app on App Store >>](https://apps.apple.com/au/app/action-movie-fx/id489321253)
### 3\. Movie FX Maker
This **video special effects app** is helpful to apply FX on the images to use them as stickers. Although the program is free to use, the in-app purchases give you access to more advanced movie stickers that would allow you to bring life to the still images without having you to transfer them to your PC and/or using an expensive and complex apps like Photoshop.
All you need to do in order to apply special FX to the images is, capture photos on your iDevice, and add the effects Movie FX Maker has. Post modifications, the images can be shared on your favorite social networking site instantaneously.

#### 4\. Effects Cam – Visual Effects
Yet another **video special effects app**, Effects Cam allows you to add special effects like fire, blasts, explosions, etc. to your images in order to make them look live. The images can be captured right from your device’s camera, or imported from other sources like your PC, phone’s memory, etc. Once imported, you can pick any of the available special FX from the app’s library, and apply it to the photo(s).

[Click to get this app on App Store >>](https://apps.apple.com/au/app/effects-cam-visual-effects/id1123449586)
### 5\. Videorama Text & Video Editor
Videorama Text & Video Editor is an **iPhone video special effects** app that lets you do various tasks such as trim videos, split them, remove unwanted segments, etc. In addition to this, the tool is also capable of adding and animating texts that can be used as captions for the images or motion clips for information.
Apart from the above, adding special video and sound effects is another lucrative feature that Videorama has because of which the app is most admired and used by majority of people across the globe.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/videorama-text-video-editor/id1049690233)
### 6\. LumaFX
Although LumaFX is a paid **video special effects app** for iOS devices, it is worth investing. The software has many features that are mostly found in professional post-production tools. These features include color correction, slow motion effect, frame-by-frame animation using the keyframes, and much more.
In addition to all the above, LumaFX also allows you to add audio effects, thus making the videos more interesting and informative that could be broadcasted for commercial gains or shared among your known ones for fun.

### Watch Video! Best Free Video Special Effects Apps on Apple Store
## Part 2: Best VFX Video Effects Editor Apps for Android
If you are an Android lover and prefer using non-Apple devices, you have plenty of options when it comes to selecting the best **movie effects app** that could enable you to apply special effects to the videos your smart device has or captures using its camera.
In case you are looking for an efficient **video special effects app for Android**, those listed below are worth your attention:
### 1\. Movie Booth FX Free
While using [Movie Booth FX Free](https://play.google.com/store/apps/details?id=bizomobile.actionmovie.free&hl=en%5FUS), all you need to do is, record a footage from your camera, and add special effects to it. The three main categories that this **video special effects app** ships along with include Action, Sci-Fi, and Horror. Depending on the type of footage you captured, and the kind of output you want to have, you can pick any of these categories, and apply your favorite effect that is available within it.

Although the program is free to install, various other options and features can be unlocked by paying for them with in-app purchases.
### 2\. MovieRide FX
[This video special effects app for Android](https://play.google.com/store/apps/details?id=tv.waterston.movieridefx&hl=en%5FUS) has several templates that allow you to apply various VFX to the footages you record using your Android device. With the effects like Space Wars, Space Walk, Thunder Bolt, Storms, etc., you can virtually live in the movies, and act like a character. Although some of the effects that MovieRide FX has are paid, you definitely won’t regret buying them considering the precision and ease at which you can decorate your clips.

### 3\. Movie Effects Maker

Movie Effects Maker, as the name suggests, allows you to add special effects to the images you click with your smartphone. With all the VFX options this **movie effects app** has, you can be virtually anyone you want. For instance, with the sci-fi and horror elements, you can create stickers out of your photos portraying yourself as a hero, add animated effects to your images to make them look live, and much more.
### 4\. Extreme VFX

With this **video special effects app**, all you need to do is, record a footage using your Android smart device, and begin applying special effects to them until you are satisfied with the results. Since the app allows you to add multiple VFX to the clips, nothing seems impossible when it comes to decorating the videos, and making them more engaging and entertaining, especially with you playing as the main character.
[Get this special video effect app from Google Play>>](https://play.google.com/store/apps/details?id=com.kaushal.extremevfx&hl=en%5FUS)
### Watch Video! Best VFX Video Effects Editor Apps for Android
## Part 4: How to Add Special Effects to Videos in Filmora?
Although all the apps listed above are good, when it comes to creating movies with special effects for commercial usage and public broadcasting, nothing can beat the efficiency and robustness of a **movie effects app** that has been designed to run on desktop computers.
Even though there are many [post-production professional applications](https://tools.techidaily.com/wondershare/filmora/download/) by different vendors, [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) has the simplest UI, and follows the most straightforward approach that allows even the novice users to add VFX to their videos.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
The steps given below explain **how to add special effects to your recorded footages with Wondershare Filmora:**
### 1\. Import Video and Add to Timeline
Launch Wondershare Filmora, click anywhere inside the **Media Bin** at the upper-left section, use the **Open** box to import the video you want to add VFX to, hover mouse to the thumbnail of the clip, click the **+** icon from the middle, and click **MATCH TO MEDIA** from the **Project Setting** box when/if it appears.

### 2\. Add Effects and Elements
Place the Playhead (Skimmer) in the Timeline you want to apply effects from, click **Effects** from the standard toolbar at the top, select your preferred category from the left pane, hover mouse to the effect you want to add in the right window, and click the **+** icon from the center.

Optionally you can drag the effect in the Timeline to manage its duration. Next, go to **Elements** from the top, and repeat the process to add your preferred element to the footage.
Besides the included effects and elements in Filmora, you can find our more video effects on Filmstock effects store, including blockbuster, effects for holidays and vacations. Click to [check the free video effects](https://tools.techidaily.com/wondershare/filmora/download/) that you can get for free in Filmstock for Filmora.

### 3\. Export the Output
Click **EXPORT** from the top-center section, go to the **Local** tab from the top of the **Export** box that opens up next, choose your preferred extension from the **Format** list in the left pane, select a destination location in the **Save to** field in the right window, click **SETTINGS** and make necessary adjustments (optional), and click **EXPORT** from the bottom-right corner of the box to begin rendering and to produce the video with the special effects applied to it.

**Conclusion**
With all the programs listed above, selecting the best video special effects app could be a challenging task. Thanks to Wondershare Filmora that not only enables you to add effects and elements to the videos, it is also fast, lightweight, and offers simple and easy-to-use interface that can be exploited to create professional-level outputs in comparatively less time.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
Every movie clip that you see on a big or small screen has been decorated using a [professional **video special effects app**](https://tools.techidaily.com/wondershare/filmora/download/). Since special effects are added to the footages to make them look more lively and happening, it is important that only highly skilled professionals should do the job.
However, because of the advanced technologies and the robust applications that the developers are coming up with these days, no special training is required to seamlessly [add special effects to the videos](https://tools.techidaily.com/wondershare/filmora/download/), and even a novice user can produce professional-level outputs on their smartphone with the help of all the options and features that these latest software programs offer.
With that said, here you will get to know about some of the best iOS and Android programs that you can use to add special effects to your videos. In addition to this, you will also learn about another most admired and widely used **movie effects app** that is equipped with plethora of templates that you can apply to your clips to make them look more professional.
* [Part 1: Best Free Video Special Effects Apps \[iOS & Android Devices\]](#for%5Fios%5Fandroid)
* [Part 2: 6 Best VFX Apps for iOS](#for%5Fios)
* [Part 3: 4 Best Video Special Effects Apps for Android](#for%5Fandroid)
* [Part 4: Add Video Effects on Desktop \[Bonus\] ](#add%5Feffects%5Ffilmora9)
## Part 1: Best Video Special Effects Apps for Both iPhone and Android: FxGuru
We’ve find FxGuru: Movie FX Director is a special effect app which is available on both iPhone, iPad and Android devices, this **video special effects app for Android** **and iOS** has almost everything you may need in order to give your recorded videos a professional touch. From ghosts to werewolves, UFOs to dragons, and even tornadoes, earthquakes, and meteors, FxGuru has every special effect under one umbrella.
Simply put, with this app on your phone, you only have to use the device’s camera to capture video footage, and then sail away with your imagination to produce industry-standard clips for commercial promotions and/or for fun.

Click to get the [Android](https://play.google.com/store/apps/details?id=com.picadelic.fxguru&hl=en%5FUS) version of this special effect app from the App Store or Google Play.
## Part 2: Best VFX Video Effects Editor Apps for iPhone & iPad
If you are a proud owner of an iOS device, the following **iPhone and iPad video special effects** apps are something you would definitely love to try:
### 1\. Enlight Videoleap Video Editor
With built-in video editor and easy-to-use interface, this **iPhone special effects app** could be the program you have been looking for all along. The software allows keyframe-based [animations](https://tools.techidaily.com/wondershare/filmora/download/), chroma compositing, practically limitless redo and undo iterations, and even non-destructive video editing to make your post-production tasks simple and fun.
With all these features and options, and several more to explore, Enlight Vdeoleap Video Editor leaves no stone unturned to help you produce industry-standard outputs right on your iDevice.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/enlight-videoleap-video-editor/id1255135442)
### 2\. Action Movie FX
With around 4.5-star rating on Apple App Store, this **movie effects app** called Action Movie FX has several Hollywood-style effects templates that let you give more dramatic look to the videos you record from your iDevice. Since the program is a mobile app, you can apply all the VFX right on your iPhone or iPad without transferring the footages to a computer for post-production treatments.
All the built-in effects that Action Movie FX is enriched with such as ALIEN BURST, CAR SMASH, BB-8 Spark, etc. have been designed by some of the most famous artists with ample amount of experience in the field of film production.
[Click to get this app on App Store >>](https://apps.apple.com/au/app/action-movie-fx/id489321253)
### 3\. Movie FX Maker
This **video special effects app** is helpful to apply FX on the images to use them as stickers. Although the program is free to use, the in-app purchases give you access to more advanced movie stickers that would allow you to bring life to the still images without having you to transfer them to your PC and/or using an expensive and complex apps like Photoshop.
All you need to do in order to apply special FX to the images is, capture photos on your iDevice, and add the effects Movie FX Maker has. Post modifications, the images can be shared on your favorite social networking site instantaneously.

#### 4\. Effects Cam – Visual Effects
Yet another **video special effects app**, Effects Cam allows you to add special effects like fire, blasts, explosions, etc. to your images in order to make them look live. The images can be captured right from your device’s camera, or imported from other sources like your PC, phone’s memory, etc. Once imported, you can pick any of the available special FX from the app’s library, and apply it to the photo(s).

[Click to get this app on App Store >>](https://apps.apple.com/au/app/effects-cam-visual-effects/id1123449586)
### 5\. Videorama Text & Video Editor
Videorama Text & Video Editor is an **iPhone video special effects** app that lets you do various tasks such as trim videos, split them, remove unwanted segments, etc. In addition to this, the tool is also capable of adding and animating texts that can be used as captions for the images or motion clips for information.
Apart from the above, adding special video and sound effects is another lucrative feature that Videorama has because of which the app is most admired and used by majority of people across the globe.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/videorama-text-video-editor/id1049690233)
### 6\. LumaFX
Although LumaFX is a paid **video special effects app** for iOS devices, it is worth investing. The software has many features that are mostly found in professional post-production tools. These features include color correction, slow motion effect, frame-by-frame animation using the keyframes, and much more.
In addition to all the above, LumaFX also allows you to add audio effects, thus making the videos more interesting and informative that could be broadcasted for commercial gains or shared among your known ones for fun.

### Watch Video! Best Free Video Special Effects Apps on Apple Store
## Part 2: Best VFX Video Effects Editor Apps for Android
If you are an Android lover and prefer using non-Apple devices, you have plenty of options when it comes to selecting the best **movie effects app** that could enable you to apply special effects to the videos your smart device has or captures using its camera.
In case you are looking for an efficient **video special effects app for Android**, those listed below are worth your attention:
### 1\. Movie Booth FX Free
While using [Movie Booth FX Free](https://play.google.com/store/apps/details?id=bizomobile.actionmovie.free&hl=en%5FUS), all you need to do is, record a footage from your camera, and add special effects to it. The three main categories that this **video special effects app** ships along with include Action, Sci-Fi, and Horror. Depending on the type of footage you captured, and the kind of output you want to have, you can pick any of these categories, and apply your favorite effect that is available within it.

Although the program is free to install, various other options and features can be unlocked by paying for them with in-app purchases.
### 2\. MovieRide FX
[This video special effects app for Android](https://play.google.com/store/apps/details?id=tv.waterston.movieridefx&hl=en%5FUS) has several templates that allow you to apply various VFX to the footages you record using your Android device. With the effects like Space Wars, Space Walk, Thunder Bolt, Storms, etc., you can virtually live in the movies, and act like a character. Although some of the effects that MovieRide FX has are paid, you definitely won’t regret buying them considering the precision and ease at which you can decorate your clips.

### 3\. Movie Effects Maker

Movie Effects Maker, as the name suggests, allows you to add special effects to the images you click with your smartphone. With all the VFX options this **movie effects app** has, you can be virtually anyone you want. For instance, with the sci-fi and horror elements, you can create stickers out of your photos portraying yourself as a hero, add animated effects to your images to make them look live, and much more.
### 4\. Extreme VFX

With this **video special effects app**, all you need to do is, record a footage using your Android smart device, and begin applying special effects to them until you are satisfied with the results. Since the app allows you to add multiple VFX to the clips, nothing seems impossible when it comes to decorating the videos, and making them more engaging and entertaining, especially with you playing as the main character.
[Get this special video effect app from Google Play>>](https://play.google.com/store/apps/details?id=com.kaushal.extremevfx&hl=en%5FUS)
### Watch Video! Best VFX Video Effects Editor Apps for Android
## Part 4: How to Add Special Effects to Videos in Filmora?
Although all the apps listed above are good, when it comes to creating movies with special effects for commercial usage and public broadcasting, nothing can beat the efficiency and robustness of a **movie effects app** that has been designed to run on desktop computers.
Even though there are many [post-production professional applications](https://tools.techidaily.com/wondershare/filmora/download/) by different vendors, [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) has the simplest UI, and follows the most straightforward approach that allows even the novice users to add VFX to their videos.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
The steps given below explain **how to add special effects to your recorded footages with Wondershare Filmora:**
### 1\. Import Video and Add to Timeline
Launch Wondershare Filmora, click anywhere inside the **Media Bin** at the upper-left section, use the **Open** box to import the video you want to add VFX to, hover mouse to the thumbnail of the clip, click the **+** icon from the middle, and click **MATCH TO MEDIA** from the **Project Setting** box when/if it appears.

### 2\. Add Effects and Elements
Place the Playhead (Skimmer) in the Timeline you want to apply effects from, click **Effects** from the standard toolbar at the top, select your preferred category from the left pane, hover mouse to the effect you want to add in the right window, and click the **+** icon from the center.

Optionally you can drag the effect in the Timeline to manage its duration. Next, go to **Elements** from the top, and repeat the process to add your preferred element to the footage.
Besides the included effects and elements in Filmora, you can find our more video effects on Filmstock effects store, including blockbuster, effects for holidays and vacations. Click to [check the free video effects](https://tools.techidaily.com/wondershare/filmora/download/) that you can get for free in Filmstock for Filmora.

### 3\. Export the Output
Click **EXPORT** from the top-center section, go to the **Local** tab from the top of the **Export** box that opens up next, choose your preferred extension from the **Format** list in the left pane, select a destination location in the **Save to** field in the right window, click **SETTINGS** and make necessary adjustments (optional), and click **EXPORT** from the bottom-right corner of the box to begin rendering and to produce the video with the special effects applied to it.

**Conclusion**
With all the programs listed above, selecting the best video special effects app could be a challenging task. Thanks to Wondershare Filmora that not only enables you to add effects and elements to the videos, it is also fast, lightweight, and offers simple and easy-to-use interface that can be exploited to create professional-level outputs in comparatively less time.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
Every movie clip that you see on a big or small screen has been decorated using a [professional **video special effects app**](https://tools.techidaily.com/wondershare/filmora/download/). Since special effects are added to the footages to make them look more lively and happening, it is important that only highly skilled professionals should do the job.
However, because of the advanced technologies and the robust applications that the developers are coming up with these days, no special training is required to seamlessly [add special effects to the videos](https://tools.techidaily.com/wondershare/filmora/download/), and even a novice user can produce professional-level outputs on their smartphone with the help of all the options and features that these latest software programs offer.
With that said, here you will get to know about some of the best iOS and Android programs that you can use to add special effects to your videos. In addition to this, you will also learn about another most admired and widely used **movie effects app** that is equipped with plethora of templates that you can apply to your clips to make them look more professional.
* [Part 1: Best Free Video Special Effects Apps \[iOS & Android Devices\]](#for%5Fios%5Fandroid)
* [Part 2: 6 Best VFX Apps for iOS](#for%5Fios)
* [Part 3: 4 Best Video Special Effects Apps for Android](#for%5Fandroid)
* [Part 4: Add Video Effects on Desktop \[Bonus\] ](#add%5Feffects%5Ffilmora9)
## Part 1: Best Video Special Effects Apps for Both iPhone and Android: FxGuru
We’ve find FxGuru: Movie FX Director is a special effect app which is available on both iPhone, iPad and Android devices, this **video special effects app for Android** **and iOS** has almost everything you may need in order to give your recorded videos a professional touch. From ghosts to werewolves, UFOs to dragons, and even tornadoes, earthquakes, and meteors, FxGuru has every special effect under one umbrella.
Simply put, with this app on your phone, you only have to use the device’s camera to capture video footage, and then sail away with your imagination to produce industry-standard clips for commercial promotions and/or for fun.

Click to get the [Android](https://play.google.com/store/apps/details?id=com.picadelic.fxguru&hl=en%5FUS) version of this special effect app from the App Store or Google Play.
## Part 2: Best VFX Video Effects Editor Apps for iPhone & iPad
If you are a proud owner of an iOS device, the following **iPhone and iPad video special effects** apps are something you would definitely love to try:
### 1\. Enlight Videoleap Video Editor
With built-in video editor and easy-to-use interface, this **iPhone special effects app** could be the program you have been looking for all along. The software allows keyframe-based [animations](https://tools.techidaily.com/wondershare/filmora/download/), chroma compositing, practically limitless redo and undo iterations, and even non-destructive video editing to make your post-production tasks simple and fun.
With all these features and options, and several more to explore, Enlight Vdeoleap Video Editor leaves no stone unturned to help you produce industry-standard outputs right on your iDevice.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/enlight-videoleap-video-editor/id1255135442)
### 2\. Action Movie FX
With around 4.5-star rating on Apple App Store, this **movie effects app** called Action Movie FX has several Hollywood-style effects templates that let you give more dramatic look to the videos you record from your iDevice. Since the program is a mobile app, you can apply all the VFX right on your iPhone or iPad without transferring the footages to a computer for post-production treatments.
All the built-in effects that Action Movie FX is enriched with such as ALIEN BURST, CAR SMASH, BB-8 Spark, etc. have been designed by some of the most famous artists with ample amount of experience in the field of film production.
[Click to get this app on App Store >>](https://apps.apple.com/au/app/action-movie-fx/id489321253)
### 3\. Movie FX Maker
This **video special effects app** is helpful to apply FX on the images to use them as stickers. Although the program is free to use, the in-app purchases give you access to more advanced movie stickers that would allow you to bring life to the still images without having you to transfer them to your PC and/or using an expensive and complex apps like Photoshop.
All you need to do in order to apply special FX to the images is, capture photos on your iDevice, and add the effects Movie FX Maker has. Post modifications, the images can be shared on your favorite social networking site instantaneously.

#### 4\. Effects Cam – Visual Effects
Yet another **video special effects app**, Effects Cam allows you to add special effects like fire, blasts, explosions, etc. to your images in order to make them look live. The images can be captured right from your device’s camera, or imported from other sources like your PC, phone’s memory, etc. Once imported, you can pick any of the available special FX from the app’s library, and apply it to the photo(s).

[Click to get this app on App Store >>](https://apps.apple.com/au/app/effects-cam-visual-effects/id1123449586)
### 5\. Videorama Text & Video Editor
Videorama Text & Video Editor is an **iPhone video special effects** app that lets you do various tasks such as trim videos, split them, remove unwanted segments, etc. In addition to this, the tool is also capable of adding and animating texts that can be used as captions for the images or motion clips for information.
Apart from the above, adding special video and sound effects is another lucrative feature that Videorama has because of which the app is most admired and used by majority of people across the globe.

[Click to get this app on App Store >>](https://apps.apple.com/us/app/videorama-text-video-editor/id1049690233)
### 6\. LumaFX
Although LumaFX is a paid **video special effects app** for iOS devices, it is worth investing. The software has many features that are mostly found in professional post-production tools. These features include color correction, slow motion effect, frame-by-frame animation using the keyframes, and much more.
In addition to all the above, LumaFX also allows you to add audio effects, thus making the videos more interesting and informative that could be broadcasted for commercial gains or shared among your known ones for fun.

### Watch Video! Best Free Video Special Effects Apps on Apple Store
## Part 2: Best VFX Video Effects Editor Apps for Android
If you are an Android lover and prefer using non-Apple devices, you have plenty of options when it comes to selecting the best **movie effects app** that could enable you to apply special effects to the videos your smart device has or captures using its camera.
In case you are looking for an efficient **video special effects app for Android**, those listed below are worth your attention:
### 1\. Movie Booth FX Free
While using [Movie Booth FX Free](https://play.google.com/store/apps/details?id=bizomobile.actionmovie.free&hl=en%5FUS), all you need to do is, record a footage from your camera, and add special effects to it. The three main categories that this **video special effects app** ships along with include Action, Sci-Fi, and Horror. Depending on the type of footage you captured, and the kind of output you want to have, you can pick any of these categories, and apply your favorite effect that is available within it.

Although the program is free to install, various other options and features can be unlocked by paying for them with in-app purchases.
### 2\. MovieRide FX
[This video special effects app for Android](https://play.google.com/store/apps/details?id=tv.waterston.movieridefx&hl=en%5FUS) has several templates that allow you to apply various VFX to the footages you record using your Android device. With the effects like Space Wars, Space Walk, Thunder Bolt, Storms, etc., you can virtually live in the movies, and act like a character. Although some of the effects that MovieRide FX has are paid, you definitely won’t regret buying them considering the precision and ease at which you can decorate your clips.

### 3\. Movie Effects Maker

Movie Effects Maker, as the name suggests, allows you to add special effects to the images you click with your smartphone. With all the VFX options this **movie effects app** has, you can be virtually anyone you want. For instance, with the sci-fi and horror elements, you can create stickers out of your photos portraying yourself as a hero, add animated effects to your images to make them look live, and much more.
### 4\. Extreme VFX

With this **video special effects app**, all you need to do is, record a footage using your Android smart device, and begin applying special effects to them until you are satisfied with the results. Since the app allows you to add multiple VFX to the clips, nothing seems impossible when it comes to decorating the videos, and making them more engaging and entertaining, especially with you playing as the main character.
[Get this special video effect app from Google Play>>](https://play.google.com/store/apps/details?id=com.kaushal.extremevfx&hl=en%5FUS)
### Watch Video! Best VFX Video Effects Editor Apps for Android
## Part 4: How to Add Special Effects to Videos in Filmora?
Although all the apps listed above are good, when it comes to creating movies with special effects for commercial usage and public broadcasting, nothing can beat the efficiency and robustness of a **movie effects app** that has been designed to run on desktop computers.
Even though there are many [post-production professional applications](https://tools.techidaily.com/wondershare/filmora/download/) by different vendors, [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) has the simplest UI, and follows the most straightforward approach that allows even the novice users to add VFX to their videos.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)
The steps given below explain **how to add special effects to your recorded footages with Wondershare Filmora:**
### 1\. Import Video and Add to Timeline
Launch Wondershare Filmora, click anywhere inside the **Media Bin** at the upper-left section, use the **Open** box to import the video you want to add VFX to, hover mouse to the thumbnail of the clip, click the **+** icon from the middle, and click **MATCH TO MEDIA** from the **Project Setting** box when/if it appears.

### 2\. Add Effects and Elements
Place the Playhead (Skimmer) in the Timeline you want to apply effects from, click **Effects** from the standard toolbar at the top, select your preferred category from the left pane, hover mouse to the effect you want to add in the right window, and click the **+** icon from the center.

Optionally you can drag the effect in the Timeline to manage its duration. Next, go to **Elements** from the top, and repeat the process to add your preferred element to the footage.
Besides the included effects and elements in Filmora, you can find our more video effects on Filmstock effects store, including blockbuster, effects for holidays and vacations. Click to [check the free video effects](https://tools.techidaily.com/wondershare/filmora/download/) that you can get for free in Filmstock for Filmora.

### 3\. Export the Output
Click **EXPORT** from the top-center section, go to the **Local** tab from the top of the **Export** box that opens up next, choose your preferred extension from the **Format** list in the left pane, select a destination location in the **Save to** field in the right window, click **SETTINGS** and make necessary adjustments (optional), and click **EXPORT** from the bottom-right corner of the box to begin rendering and to produce the video with the special effects applied to it.

**Conclusion**
With all the programs listed above, selecting the best video special effects app could be a challenging task. Thanks to Wondershare Filmora that not only enables you to add effects and elements to the videos, it is also fast, lightweight, and offers simple and easy-to-use interface that can be exploited to create professional-level outputs in comparatively less time.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
 Secure Download
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.14 or later
 Secure Download
[Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/)
or Try Filmora App for mobile >>>
[download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t)

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## Video Editors with the Best Soundtracks and Effects (2024 Edition)
'Movies are 50 % visual and 50 % sound,' remarked famed movie director David Lynch. Even though creating a well-crafted soundtrack is just as vital as having a flawlessly shot movie, most novice filmmakers and video producers overlook the fact that sound may assist them in creating a fuller and dramatic visual output. The reality is that these software applications enable artists to create cutting-edge videos.
These tools are adept at everything from PIP to audio addition and effects addition to general video control, with a low-cost means of creating music. When all of these effects are combined, music makers become a must-have for everyone. Continue reading this article to learn about the best **Video Editor with Music** that makes it easier to incorporate music into your videos!
## Part 1: Best Video Editors with Music on Windows and Mac
Whether it's a personal video, a promo, or a cinematic trailer, the audio or song in a video may have a significant impact on our impression of it.
But what if you just have muted footage or a cracked and damaged audio file that has to be repaired, and you would like to add audio to the movie right now? In such a case, you may make things easy for yourself by using the applications listed below!
### 1 Windows 10 Photos App
**Supported System**: Windows 10 and Windows 11
**Pricing:** Free
Microsoft or Windows Photo App, a free photo viewer and editor bundled with Windows 10, provides capable image editing and photo improvements, as well as capabilities for managing and editing video, all in a touch-friendly interface.
You may doodle on photographs, add background music and 3D effects to films, and use automated object tagging to make searching easier. Microsoft Photos is a wonderful tool for working with digital photographs, and for certain users, it may even replace third-party photo applications.
The Windows 10 Photos application's artificial intelligence function allows you to create a video with music automatically with the [**Automatic Video feature**](https://tools.techidaily.com/wondershare/filmora/download/). It's simple to accomplish, what’s more, there are some music track presets in the Photos app, so you can change the background music and edit it further manually.
Besides that, you can also create a new video project from scratch and choose music from its background music library.
**Step 1:** Launch the Photos app, go to **New video** and then click **New Video Project** button at the top of the screen, and then rename the video accordingly.

**Step 2:** Click on the **+Add** option to import photos or videos to the project from your PC or collection, and then drop and place them to the storyboard.

**Step 3:** Next, from the top-right, press the **Background music** menu, pick one from the list. And the music track will fit to the length of the video automatically. You can enable [**Sync your video to the music’s beat**](https://tools.techidaily.com/wondershare/filmora/download/) to sync music to the beat of a video.

**Step 4:** Then press the **Done** button. This is how you can use the Windows Photos App and add a soundtrack from its background music library to videos. Windows 10 has several benefits, and with the correct tools, you can get the most out of it.
### 2 Apple iMovie
**Supported System**: macOS, iOS
**Pricing:** Free
Apple's entry-level desktop video editing software can transform your video and photographs into professional-looking creations. However, [Apple's video editing software](https://tools.techidaily.com/wondershare/filmora/download/) hasn't evolved much in the last several years.
Nevertheless, it still outperforms what you will get with Windows 10, which would be limited to the (albeit increasing) video capabilities integrated within Windows' Photos app.
In your digital films, Apple iMovie contains superb capabilities for media management, color grading, speed, green-screen effects, narration, and music.
It isn't always the first to support new formats—[360-degree video](https://tools.techidaily.com/wondershare/filmora/download/) is currently unavailable, but it supports 4K. [Trailers](https://tools.techidaily.com/wondershare/filmora/download/) and Movies are two of the greatest storyboard-based movie-making features for beginners in iMovie.
For beginner-level video editing, Apple iMovie is an excellent choice. For background sound, the iMovie creator integrates with iTunes and GarageBand, and you may choose from a good range of background soundtracks and audio effects, such as four pitch levels, cosmic, and robot.
The Reduce Background Noise option, on the other hand, is controlled by a slider. Follow these steps to add music to your videos using iMovie:
**Step 1:** Click the **Add Media** button while your application is visible in the timeline.
**Step 2:** To access the built-in music, go to **Audio**, then **Soundtracks**.
**Step 3:** To hear a sample of a soundtrack, press it. If a soundtrack is muted, press it to download it first, then tap it again to listen to it.
**Step 4:** Tap the **Add Audio** button near a soundtrack to include it in your composition. iMovie sets the music at the start of the project and instantly adjusts it to the project's duration.

### 3 Wondershare Filmora
**Supported System:** [Windows](https://tools.techidaily.com/wondershare/filmora/download/), [macOS](https://tools.techidaily.com/wondershare/filmora/download/)
**Pricing**: Free trial
Filmora video editor is among the most advanced and cutting-edge systems for [making music videos](https://tools.techidaily.com/wondershare/filmora/download/). This music video creator free download is likewise available for everybody to benefit from. It is a must-have for everyone, with the greatest UI and top-notch support.
Among the most popular features that Filmora has related to adding music are the **amazing audio library** and the audio editing features it has. The audio library includes different genres of music, such as tender and sentimental, rock, folk, electronic, and young and bright. Some of these audio features include fade in and fade out, audio ducking, adjust level, etc. to enhance your videos after adding the audio of your desire.
Filmora can immediately detect audio beats, evaluate music rhythm, and apply editing marks as a superb music video producer. You may quickly and smartly create your music video this way. This approach is made easier by the project's user-friendly interface.
[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
**Step 1:** To begin the procedure, launch Filmora and select **Import Media Files** to load photos and videos.
**Step 2:** Place the video in the timeline by dragging and dropping it. And now go to the Audio library to choose a music track to fit the video file.

**Step 3:** Double click the music track in the timeline, you can change the volume, speed, and other settings here.
and then you can add fade-in or fade-out effects to the audio.

**Step 4:** After you've finished editing, you may export the video in any of the 50+ codecs that the application supports.
### 4 Cyberlink PowerDirector 365
**Supported System**: Windows, MacOS
**Pricing:** Free trial for 30 days
The video editing program PowerDirector from CyberLink bridges the gap between professional editing and user-friendliness. It has frequently been ahead of the curve in terms of support for new formats and techniques.
It also comes with several features that will assist you in creating a great digital movie, complete with transitions, music, and titles. Best of all, it's simple to use and renders quickly. PowerDirector is the best video editing program on the market.
The new **Smart Fit Audio Duration tool** allows you to change the length of background music in your movie while keeping the style and tempo of the music. When you're down in the woods of fine-tuning video and audio features, the application's user interface is about as plain and easy as a tool with such a massive amount of options can be, but it can still be intimidating.
**Step 1:** To import audio clips, go to **Import Media Files** and choose to import audio clips straight from your portable hard drive.
**Step 2:** Right-click on the song and select **Add to Music Track** or drag the music onto the playlist.
**Step 3:** You may choose from a large range of unique background music recordings. Click on the **Media category** in the Media Room to open a drop-down menu, where you'll discover the **Background Music** selection.

### 5 Movavi Video Editor
**Supported System**: Window, macOS
**Pricing:** Free trial
Movavi is a video editing program with a straightforward, user-friendly interface. PiP, chroma-key, titling, adding music to video, basic keyframing, and motion tracking are all included. It isn't as feature-rich or speedy as some competitors, but it allows you to create appealing work quickly.
It's time to begin the post-production procedure when your video capture is finished, and your newly obtained film has been safely transferred from your camcorder to a hard disk. You may alter the audio file of your short video in any manner you like with the Movavi video editor.
**Step 1:** From the welcome box, choose to **Create a projec**t in full feature mode. When you're in the editor, click the **Add Media Files** button to incorporate the video and audio files you want to utilize in your new project.
**Step 2:** Every file you choose will be instantly placed on the Movavi timeline, with video files will appear on the Video Track and audio files on the **Audio Track**. To eliminate the unnecessary section of the audio file, click the **Split** option.
**Step 3**: Simply press **Start** and wait for your movie to be exported after selecting the correct video format and setting the destination folder by deciding on the **Save to** section.
**Conclusion**
Any video without some background soundtrack or any music, in general, appears to be at its 50% percent. Users tend to lose interest soon if they don't have something playing in the background all the time.
This is why the best Video Editor with Music reviewed in this article will ultimately do everything for you. From editing your videos and pictures, these apps are tailored to provide excellent functionality to any user. Decide on the one you liked based on the features and treat yourself to the best!
**Step 2:** Click on the **+Add** option to import photos or videos to the project from your PC or collection, and then drop and place them to the storyboard.

**Step 3:** Next, from the top-right, press the **Background music** menu, pick one from the list. And the music track will fit to the length of the video automatically. You can enable [**Sync your video to the music’s beat**](https://tools.techidaily.com/wondershare/filmora/download/) to sync music to the beat of a video.

**Step 4:** Then press the **Done** button. This is how you can use the Windows Photos App and add a soundtrack from its background music library to videos. Windows 10 has several benefits, and with the correct tools, you can get the most out of it.
### 2 Apple iMovie
**Supported System**: macOS, iOS
**Pricing:** Free
Apple's entry-level desktop video editing software can transform your video and photographs into professional-looking creations. However, [Apple's video editing software](https://tools.techidaily.com/wondershare/filmora/download/) hasn't evolved much in the last several years.
Nevertheless, it still outperforms what you will get with Windows 10, which would be limited to the (albeit increasing) video capabilities integrated within Windows' Photos app.
In your digital films, Apple iMovie contains superb capabilities for media management, color grading, speed, green-screen effects, narration, and music.
It isn't always the first to support new formats—[360-degree video](https://tools.techidaily.com/wondershare/filmora/download/) is currently unavailable, but it supports 4K. [Trailers](https://tools.techidaily.com/wondershare/filmora/download/) and Movies are two of the greatest storyboard-based movie-making features for beginners in iMovie.
For beginner-level video editing, Apple iMovie is an excellent choice. For background sound, the iMovie creator integrates with iTunes and GarageBand, and you may choose from a good range of background soundtracks and audio effects, such as four pitch levels, cosmic, and robot.
The Reduce Background Noise option, on the other hand, is controlled by a slider. Follow these steps to add music to your videos using iMovie:
**Step 1:** Click the **Add Media** button while your application is visible in the timeline.
**Step 2:** To access the built-in music, go to **Audio**, then **Soundtracks**.
**Step 3:** To hear a sample of a soundtrack, press it. If a soundtrack is muted, press it to download it first, then tap it again to listen to it.
**Step 4:** Tap the **Add Audio** button near a soundtrack to include it in your composition. iMovie sets the music at the start of the project and instantly adjusts it to the project's duration.

### 3 Wondershare Filmora
**Supported System:** [Windows](https://tools.techidaily.com/wondershare/filmora/download/), [macOS](https://tools.techidaily.com/wondershare/filmora/download/)
**Pricing**: Free trial
Filmora video editor is among the most advanced and cutting-edge systems for [making music videos](https://tools.techidaily.com/wondershare/filmora/download/). This music video creator free download is likewise available for everybody to benefit from. It is a must-have for everyone, with the greatest UI and top-notch support.
Among the most popular features that Filmora has related to adding music are the **amazing audio library** and the audio editing features it has. The audio library includes different genres of music, such as tender and sentimental, rock, folk, electronic, and young and bright. Some of these audio features include fade in and fade out, audio ducking, adjust level, etc. to enhance your videos after adding the audio of your desire.
Filmora can immediately detect audio beats, evaluate music rhythm, and apply editing marks as a superb music video producer. You may quickly and smartly create your music video this way. This approach is made easier by the project's user-friendly interface.
[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
**Step 1:** To begin the procedure, launch Filmora and select **Import Media Files** to load photos and videos.
**Step 2:** Place the video in the timeline by dragging and dropping it. And now go to the Audio library to choose a music track to fit the video file.

**Step 3:** Double click the music track in the timeline, you can change the volume, speed, and other settings here.
and then you can add fade-in or fade-out effects to the audio.

**Step 4:** After you've finished editing, you may export the video in any of the 50+ codecs that the application supports.
### 4 Cyberlink PowerDirector 365
**Supported System**: Windows, MacOS
**Pricing:** Free trial for 30 days
The video editing program PowerDirector from CyberLink bridges the gap between professional editing and user-friendliness. It has frequently been ahead of the curve in terms of support for new formats and techniques.
It also comes with several features that will assist you in creating a great digital movie, complete with transitions, music, and titles. Best of all, it's simple to use and renders quickly. PowerDirector is the best video editing program on the market.
The new **Smart Fit Audio Duration tool** allows you to change the length of background music in your movie while keeping the style and tempo of the music. When you're down in the woods of fine-tuning video and audio features, the application's user interface is about as plain and easy as a tool with such a massive amount of options can be, but it can still be intimidating.
**Step 1:** To import audio clips, go to **Import Media Files** and choose to import audio clips straight from your portable hard drive.
**Step 2:** Right-click on the song and select **Add to Music Track** or drag the music onto the playlist.
**Step 3:** You may choose from a large range of unique background music recordings. Click on the **Media category** in the Media Room to open a drop-down menu, where you'll discover the **Background Music** selection.

### 5 Movavi Video Editor
**Supported System**: Window, macOS
**Pricing:** Free trial
Movavi is a video editing program with a straightforward, user-friendly interface. PiP, chroma-key, titling, adding music to video, basic keyframing, and motion tracking are all included. It isn't as feature-rich or speedy as some competitors, but it allows you to create appealing work quickly.
It's time to begin the post-production procedure when your video capture is finished, and your newly obtained film has been safely transferred from your camcorder to a hard disk. You may alter the audio file of your short video in any manner you like with the Movavi video editor.
**Step 1:** From the welcome box, choose to **Create a projec**t in full feature mode. When you're in the editor, click the **Add Media Files** button to incorporate the video and audio files you want to utilize in your new project.
**Step 2:** Every file you choose will be instantly placed on the Movavi timeline, with video files will appear on the Video Track and audio files on the **Audio Track**. To eliminate the unnecessary section of the audio file, click the **Split** option.
**Step 3**: Simply press **Start** and wait for your movie to be exported after selecting the correct video format and setting the destination folder by deciding on the **Save to** section.
**Conclusion**
Any video without some background soundtrack or any music, in general, appears to be at its 50% percent. Users tend to lose interest soon if they don't have something playing in the background all the time.
This is why the best Video Editor with Music reviewed in this article will ultimately do everything for you. From editing your videos and pictures, these apps are tailored to provide excellent functionality to any user. Decide on the one you liked based on the features and treat yourself to the best!
**Step 2:** Click on the **+Add** option to import photos or videos to the project from your PC or collection, and then drop and place them to the storyboard.

**Step 3:** Next, from the top-right, press the **Background music** menu, pick one from the list. And the music track will fit to the length of the video automatically. You can enable [**Sync your video to the music’s beat**](https://tools.techidaily.com/wondershare/filmora/download/) to sync music to the beat of a video.

**Step 4:** Then press the **Done** button. This is how you can use the Windows Photos App and add a soundtrack from its background music library to videos. Windows 10 has several benefits, and with the correct tools, you can get the most out of it.
### 2 Apple iMovie
**Supported System**: macOS, iOS
**Pricing:** Free
Apple's entry-level desktop video editing software can transform your video and photographs into professional-looking creations. However, [Apple's video editing software](https://tools.techidaily.com/wondershare/filmora/download/) hasn't evolved much in the last several years.
Nevertheless, it still outperforms what you will get with Windows 10, which would be limited to the (albeit increasing) video capabilities integrated within Windows' Photos app.
In your digital films, Apple iMovie contains superb capabilities for media management, color grading, speed, green-screen effects, narration, and music.
It isn't always the first to support new formats—[360-degree video](https://tools.techidaily.com/wondershare/filmora/download/) is currently unavailable, but it supports 4K. [Trailers](https://tools.techidaily.com/wondershare/filmora/download/) and Movies are two of the greatest storyboard-based movie-making features for beginners in iMovie.
For beginner-level video editing, Apple iMovie is an excellent choice. For background sound, the iMovie creator integrates with iTunes and GarageBand, and you may choose from a good range of background soundtracks and audio effects, such as four pitch levels, cosmic, and robot.
The Reduce Background Noise option, on the other hand, is controlled by a slider. Follow these steps to add music to your videos using iMovie:
**Step 1:** Click the **Add Media** button while your application is visible in the timeline.
**Step 2:** To access the built-in music, go to **Audio**, then **Soundtracks**.
**Step 3:** To hear a sample of a soundtrack, press it. If a soundtrack is muted, press it to download it first, then tap it again to listen to it.
**Step 4:** Tap the **Add Audio** button near a soundtrack to include it in your composition. iMovie sets the music at the start of the project and instantly adjusts it to the project's duration.

### 3 Wondershare Filmora
**Supported System:** [Windows](https://tools.techidaily.com/wondershare/filmora/download/), [macOS](https://tools.techidaily.com/wondershare/filmora/download/)
**Pricing**: Free trial
Filmora video editor is among the most advanced and cutting-edge systems for [making music videos](https://tools.techidaily.com/wondershare/filmora/download/). This music video creator free download is likewise available for everybody to benefit from. It is a must-have for everyone, with the greatest UI and top-notch support.
Among the most popular features that Filmora has related to adding music are the **amazing audio library** and the audio editing features it has. The audio library includes different genres of music, such as tender and sentimental, rock, folk, electronic, and young and bright. Some of these audio features include fade in and fade out, audio ducking, adjust level, etc. to enhance your videos after adding the audio of your desire.
Filmora can immediately detect audio beats, evaluate music rhythm, and apply editing marks as a superb music video producer. You may quickly and smartly create your music video this way. This approach is made easier by the project's user-friendly interface.
[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
**Step 1:** To begin the procedure, launch Filmora and select **Import Media Files** to load photos and videos.
**Step 2:** Place the video in the timeline by dragging and dropping it. And now go to the Audio library to choose a music track to fit the video file.

**Step 3:** Double click the music track in the timeline, you can change the volume, speed, and other settings here.
and then you can add fade-in or fade-out effects to the audio.

**Step 4:** After you've finished editing, you may export the video in any of the 50+ codecs that the application supports.
### 4 Cyberlink PowerDirector 365
**Supported System**: Windows, MacOS
**Pricing:** Free trial for 30 days
The video editing program PowerDirector from CyberLink bridges the gap between professional editing and user-friendliness. It has frequently been ahead of the curve in terms of support for new formats and techniques.
It also comes with several features that will assist you in creating a great digital movie, complete with transitions, music, and titles. Best of all, it's simple to use and renders quickly. PowerDirector is the best video editing program on the market.
The new **Smart Fit Audio Duration tool** allows you to change the length of background music in your movie while keeping the style and tempo of the music. When you're down in the woods of fine-tuning video and audio features, the application's user interface is about as plain and easy as a tool with such a massive amount of options can be, but it can still be intimidating.
**Step 1:** To import audio clips, go to **Import Media Files** and choose to import audio clips straight from your portable hard drive.
**Step 2:** Right-click on the song and select **Add to Music Track** or drag the music onto the playlist.
**Step 3:** You may choose from a large range of unique background music recordings. Click on the **Media category** in the Media Room to open a drop-down menu, where you'll discover the **Background Music** selection.

### 5 Movavi Video Editor
**Supported System**: Window, macOS
**Pricing:** Free trial
Movavi is a video editing program with a straightforward, user-friendly interface. PiP, chroma-key, titling, adding music to video, basic keyframing, and motion tracking are all included. It isn't as feature-rich or speedy as some competitors, but it allows you to create appealing work quickly.
It's time to begin the post-production procedure when your video capture is finished, and your newly obtained film has been safely transferred from your camcorder to a hard disk. You may alter the audio file of your short video in any manner you like with the Movavi video editor.
**Step 1:** From the welcome box, choose to **Create a projec**t in full feature mode. When you're in the editor, click the **Add Media Files** button to incorporate the video and audio files you want to utilize in your new project.
**Step 2:** Every file you choose will be instantly placed on the Movavi timeline, with video files will appear on the Video Track and audio files on the **Audio Track**. To eliminate the unnecessary section of the audio file, click the **Split** option.
**Step 3**: Simply press **Start** and wait for your movie to be exported after selecting the correct video format and setting the destination folder by deciding on the **Save to** section.
**Conclusion**
Any video without some background soundtrack or any music, in general, appears to be at its 50% percent. Users tend to lose interest soon if they don't have something playing in the background all the time.
This is why the best Video Editor with Music reviewed in this article will ultimately do everything for you. From editing your videos and pictures, these apps are tailored to provide excellent functionality to any user. Decide on the one you liked based on the features and treat yourself to the best!
**Step 2:** Click on the **+Add** option to import photos or videos to the project from your PC or collection, and then drop and place them to the storyboard.

**Step 3:** Next, from the top-right, press the **Background music** menu, pick one from the list. And the music track will fit to the length of the video automatically. You can enable [**Sync your video to the music’s beat**](https://tools.techidaily.com/wondershare/filmora/download/) to sync music to the beat of a video.

**Step 4:** Then press the **Done** button. This is how you can use the Windows Photos App and add a soundtrack from its background music library to videos. Windows 10 has several benefits, and with the correct tools, you can get the most out of it.
### 2 Apple iMovie
**Supported System**: macOS, iOS
**Pricing:** Free
Apple's entry-level desktop video editing software can transform your video and photographs into professional-looking creations. However, [Apple's video editing software](https://tools.techidaily.com/wondershare/filmora/download/) hasn't evolved much in the last several years.
Nevertheless, it still outperforms what you will get with Windows 10, which would be limited to the (albeit increasing) video capabilities integrated within Windows' Photos app.
In your digital films, Apple iMovie contains superb capabilities for media management, color grading, speed, green-screen effects, narration, and music.
It isn't always the first to support new formats—[360-degree video](https://tools.techidaily.com/wondershare/filmora/download/) is currently unavailable, but it supports 4K. [Trailers](https://tools.techidaily.com/wondershare/filmora/download/) and Movies are two of the greatest storyboard-based movie-making features for beginners in iMovie.
For beginner-level video editing, Apple iMovie is an excellent choice. For background sound, the iMovie creator integrates with iTunes and GarageBand, and you may choose from a good range of background soundtracks and audio effects, such as four pitch levels, cosmic, and robot.
The Reduce Background Noise option, on the other hand, is controlled by a slider. Follow these steps to add music to your videos using iMovie:
**Step 1:** Click the **Add Media** button while your application is visible in the timeline.
**Step 2:** To access the built-in music, go to **Audio**, then **Soundtracks**.
**Step 3:** To hear a sample of a soundtrack, press it. If a soundtrack is muted, press it to download it first, then tap it again to listen to it.
**Step 4:** Tap the **Add Audio** button near a soundtrack to include it in your composition. iMovie sets the music at the start of the project and instantly adjusts it to the project's duration.

### 3 Wondershare Filmora
**Supported System:** [Windows](https://tools.techidaily.com/wondershare/filmora/download/), [macOS](https://tools.techidaily.com/wondershare/filmora/download/)
**Pricing**: Free trial
Filmora video editor is among the most advanced and cutting-edge systems for [making music videos](https://tools.techidaily.com/wondershare/filmora/download/). This music video creator free download is likewise available for everybody to benefit from. It is a must-have for everyone, with the greatest UI and top-notch support.
Among the most popular features that Filmora has related to adding music are the **amazing audio library** and the audio editing features it has. The audio library includes different genres of music, such as tender and sentimental, rock, folk, electronic, and young and bright. Some of these audio features include fade in and fade out, audio ducking, adjust level, etc. to enhance your videos after adding the audio of your desire.
Filmora can immediately detect audio beats, evaluate music rhythm, and apply editing marks as a superb music video producer. You may quickly and smartly create your music video this way. This approach is made easier by the project's user-friendly interface.
[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
**Step 1:** To begin the procedure, launch Filmora and select **Import Media Files** to load photos and videos.
**Step 2:** Place the video in the timeline by dragging and dropping it. And now go to the Audio library to choose a music track to fit the video file.

**Step 3:** Double click the music track in the timeline, you can change the volume, speed, and other settings here.
and then you can add fade-in or fade-out effects to the audio.

**Step 4:** After you've finished editing, you may export the video in any of the 50+ codecs that the application supports.
### 4 Cyberlink PowerDirector 365
**Supported System**: Windows, MacOS
**Pricing:** Free trial for 30 days
The video editing program PowerDirector from CyberLink bridges the gap between professional editing and user-friendliness. It has frequently been ahead of the curve in terms of support for new formats and techniques.
It also comes with several features that will assist you in creating a great digital movie, complete with transitions, music, and titles. Best of all, it's simple to use and renders quickly. PowerDirector is the best video editing program on the market.
The new **Smart Fit Audio Duration tool** allows you to change the length of background music in your movie while keeping the style and tempo of the music. When you're down in the woods of fine-tuning video and audio features, the application's user interface is about as plain and easy as a tool with such a massive amount of options can be, but it can still be intimidating.
**Step 1:** To import audio clips, go to **Import Media Files** and choose to import audio clips straight from your portable hard drive.
**Step 2:** Right-click on the song and select **Add to Music Track** or drag the music onto the playlist.
**Step 3:** You may choose from a large range of unique background music recordings. Click on the **Media category** in the Media Room to open a drop-down menu, where you'll discover the **Background Music** selection.

### 5 Movavi Video Editor
**Supported System**: Window, macOS
**Pricing:** Free trial
Movavi is a video editing program with a straightforward, user-friendly interface. PiP, chroma-key, titling, adding music to video, basic keyframing, and motion tracking are all included. It isn't as feature-rich or speedy as some competitors, but it allows you to create appealing work quickly.
It's time to begin the post-production procedure when your video capture is finished, and your newly obtained film has been safely transferred from your camcorder to a hard disk. You may alter the audio file of your short video in any manner you like with the Movavi video editor.
**Step 1:** From the welcome box, choose to **Create a projec**t in full feature mode. When you're in the editor, click the **Add Media Files** button to incorporate the video and audio files you want to utilize in your new project.
**Step 2:** Every file you choose will be instantly placed on the Movavi timeline, with video files will appear on the Video Track and audio files on the **Audio Track**. To eliminate the unnecessary section of the audio file, click the **Split** option.
**Step 3**: Simply press **Start** and wait for your movie to be exported after selecting the correct video format and setting the destination folder by deciding on the **Save to** section.
**Conclusion**
Any video without some background soundtrack or any music, in general, appears to be at its 50% percent. Users tend to lose interest soon if they don't have something playing in the background all the time.
This is why the best Video Editor with Music reviewed in this article will ultimately do everything for you. From editing your videos and pictures, these apps are tailored to provide excellent functionality to any user. Decide on the one you liked based on the features and treat yourself to the best!
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## MOD Video Editing Without the Cost: Top 5 Free Editors
# Top 5 Best Free MOD Video Editors

##### Ollie Mattison
Mar 27, 2024• Proven solutions
Are you looking for a MOD editing tool? Well, in this era of high-tech communication and online technology, finding nothing is impossible. However, the dilemma is that various video editing tools are available and it is quite difficult to judge which one is good and which is bad. Moreover, you should find a tool, which would match your requirements precisely, providing the output that you exactly desired. So, how to find such a tool or software? Read this article to get a fair and unbiased guide on the top five MOD editors. The article will illustrate the features, pros, and cons of each of the tools.
* [Recommended: Wondershare Filmora](#tab%5F06)
* [Avidemux](#tab%5F01)
* [Free Video Dub](#tab%5F02)
* [MPEG Streamclip](#tab%5F03)
* [Any Video Converter](#tab%5F04)
* [VSDC Video Editor](#tab%5F05)
#### Recommended: Wondershare Filmora (originally Wondershare Video Editor)
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a more powerful video editing tool. It has an interactive interface and use-friendly options to endorse to the users: options or features are easy to understand and the interface is simplified for providing ease of operations to the users. Now download and try it out yourself.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
#### 1\. [Avidemux](http://avidemux-mswin.sourceforge.net/)
Avidemux is a popular video editing tool which is around the internet for a few years. It supports a wide range of video formats and provides excellent features and seamless options to offer to the users. The software has three compatible versions for Windows, Mac OS and Linux.

**Pros:**
* Basic video editing functions;
* Simple to use.
**Cons:**
* Outdated interface.
#### 2\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)
Free Video Dub is lightweight and user-friendly video editing tool. It supports a number of video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. With it, you can easily edit your video files by simply deleting off the unwanted sections. The best part about this tool is that you don't need to re-encode anything, which keeps the original quality of your video.

**Pros:**
* Multi-lingual interface which makes it easy to use;
* Several video formats supported.
**Cons:**
* May be difficult to add visual effects.
#### 3\. [MPEG Streamclip](http://www.squared5.com/)
MPEG Streamclip is not only a powerful video conversion tool, but also comes with a lot of features to offer to the users. It supports various video formats VOB, PS, M2P, MOD, VRO, DAT, MOV, DV, AVI, MP4, TS, M2T, MMV and more. It also includes simple nonlinear editing, cropping and scaling functions, which make it a great tool for editing your videos, especially if your project uses video from many different sources that need to fit in the same sequence.

**Pros:**
* Can convert a range of other video files;
* Has a glitched button and window.
**Cons:**
* Restricts your file sizes to 600MB.
#### 4\. [Any Video Converter](http://www.any-video-converter.com/products/for%5Fvideo%5Ffree/)
Any Video Converter is a popular file conversion tool, which easily convert MOD files and beside that it features loads of conversion options from one video file to another. It can also be marked as a video editing tool, which can serve multiple purposes with precision.

**Pros:**
* Supports many video formats;
* Easy to use interface.
**Cons:**
* Can't convert audio files.
#### 5\. [VSDC Video Editor](http://vsdc-free-video-editor.software.informer.com/)
VSDC Free Video Editor is powerful video editing tool, which is completely free and quite popular. It supports a wide range of video formats including MOD, AVI, MP4, MKV, MPG, WMV, 3GP, FLV. Besides the very basic video editing functions, a bunch of filters can turn even a commonplace video sequence into a classy pro-quality movie, while thousands of video and audio effects conveniently grouped into four categories help you making your video to look and sound more dynamic.

**Pros:**
* Many useful options provided;
* Can also be used as a video converter.
**Cons:**
* Computer resources (CPU and RAM) are required at a high level.

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
Are you looking for a MOD editing tool? Well, in this era of high-tech communication and online technology, finding nothing is impossible. However, the dilemma is that various video editing tools are available and it is quite difficult to judge which one is good and which is bad. Moreover, you should find a tool, which would match your requirements precisely, providing the output that you exactly desired. So, how to find such a tool or software? Read this article to get a fair and unbiased guide on the top five MOD editors. The article will illustrate the features, pros, and cons of each of the tools.
* [Recommended: Wondershare Filmora](#tab%5F06)
* [Avidemux](#tab%5F01)
* [Free Video Dub](#tab%5F02)
* [MPEG Streamclip](#tab%5F03)
* [Any Video Converter](#tab%5F04)
* [VSDC Video Editor](#tab%5F05)
#### Recommended: Wondershare Filmora (originally Wondershare Video Editor)
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a more powerful video editing tool. It has an interactive interface and use-friendly options to endorse to the users: options or features are easy to understand and the interface is simplified for providing ease of operations to the users. Now download and try it out yourself.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
#### 1\. [Avidemux](http://avidemux-mswin.sourceforge.net/)
Avidemux is a popular video editing tool which is around the internet for a few years. It supports a wide range of video formats and provides excellent features and seamless options to offer to the users. The software has three compatible versions for Windows, Mac OS and Linux.

**Pros:**
* Basic video editing functions;
* Simple to use.
**Cons:**
* Outdated interface.
#### 2\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)
Free Video Dub is lightweight and user-friendly video editing tool. It supports a number of video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. With it, you can easily edit your video files by simply deleting off the unwanted sections. The best part about this tool is that you don't need to re-encode anything, which keeps the original quality of your video.

**Pros:**
* Multi-lingual interface which makes it easy to use;
* Several video formats supported.
**Cons:**
* May be difficult to add visual effects.
#### 3\. [MPEG Streamclip](http://www.squared5.com/)
MPEG Streamclip is not only a powerful video conversion tool, but also comes with a lot of features to offer to the users. It supports various video formats VOB, PS, M2P, MOD, VRO, DAT, MOV, DV, AVI, MP4, TS, M2T, MMV and more. It also includes simple nonlinear editing, cropping and scaling functions, which make it a great tool for editing your videos, especially if your project uses video from many different sources that need to fit in the same sequence.

**Pros:**
* Can convert a range of other video files;
* Has a glitched button and window.
**Cons:**
* Restricts your file sizes to 600MB.
#### 4\. [Any Video Converter](http://www.any-video-converter.com/products/for%5Fvideo%5Ffree/)
Any Video Converter is a popular file conversion tool, which easily convert MOD files and beside that it features loads of conversion options from one video file to another. It can also be marked as a video editing tool, which can serve multiple purposes with precision.

**Pros:**
* Supports many video formats;
* Easy to use interface.
**Cons:**
* Can't convert audio files.
#### 5\. [VSDC Video Editor](http://vsdc-free-video-editor.software.informer.com/)
VSDC Free Video Editor is powerful video editing tool, which is completely free and quite popular. It supports a wide range of video formats including MOD, AVI, MP4, MKV, MPG, WMV, 3GP, FLV. Besides the very basic video editing functions, a bunch of filters can turn even a commonplace video sequence into a classy pro-quality movie, while thousands of video and audio effects conveniently grouped into four categories help you making your video to look and sound more dynamic.

**Pros:**
* Many useful options provided;
* Can also be used as a video converter.
**Cons:**
* Computer resources (CPU and RAM) are required at a high level.

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
Are you looking for a MOD editing tool? Well, in this era of high-tech communication and online technology, finding nothing is impossible. However, the dilemma is that various video editing tools are available and it is quite difficult to judge which one is good and which is bad. Moreover, you should find a tool, which would match your requirements precisely, providing the output that you exactly desired. So, how to find such a tool or software? Read this article to get a fair and unbiased guide on the top five MOD editors. The article will illustrate the features, pros, and cons of each of the tools.
* [Recommended: Wondershare Filmora](#tab%5F06)
* [Avidemux](#tab%5F01)
* [Free Video Dub](#tab%5F02)
* [MPEG Streamclip](#tab%5F03)
* [Any Video Converter](#tab%5F04)
* [VSDC Video Editor](#tab%5F05)
#### Recommended: Wondershare Filmora (originally Wondershare Video Editor)
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a more powerful video editing tool. It has an interactive interface and use-friendly options to endorse to the users: options or features are easy to understand and the interface is simplified for providing ease of operations to the users. Now download and try it out yourself.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
#### 1\. [Avidemux](http://avidemux-mswin.sourceforge.net/)
Avidemux is a popular video editing tool which is around the internet for a few years. It supports a wide range of video formats and provides excellent features and seamless options to offer to the users. The software has three compatible versions for Windows, Mac OS and Linux.

**Pros:**
* Basic video editing functions;
* Simple to use.
**Cons:**
* Outdated interface.
#### 2\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)
Free Video Dub is lightweight and user-friendly video editing tool. It supports a number of video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. With it, you can easily edit your video files by simply deleting off the unwanted sections. The best part about this tool is that you don't need to re-encode anything, which keeps the original quality of your video.

**Pros:**
* Multi-lingual interface which makes it easy to use;
* Several video formats supported.
**Cons:**
* May be difficult to add visual effects.
#### 3\. [MPEG Streamclip](http://www.squared5.com/)
MPEG Streamclip is not only a powerful video conversion tool, but also comes with a lot of features to offer to the users. It supports various video formats VOB, PS, M2P, MOD, VRO, DAT, MOV, DV, AVI, MP4, TS, M2T, MMV and more. It also includes simple nonlinear editing, cropping and scaling functions, which make it a great tool for editing your videos, especially if your project uses video from many different sources that need to fit in the same sequence.

**Pros:**
* Can convert a range of other video files;
* Has a glitched button and window.
**Cons:**
* Restricts your file sizes to 600MB.
#### 4\. [Any Video Converter](http://www.any-video-converter.com/products/for%5Fvideo%5Ffree/)
Any Video Converter is a popular file conversion tool, which easily convert MOD files and beside that it features loads of conversion options from one video file to another. It can also be marked as a video editing tool, which can serve multiple purposes with precision.

**Pros:**
* Supports many video formats;
* Easy to use interface.
**Cons:**
* Can't convert audio files.
#### 5\. [VSDC Video Editor](http://vsdc-free-video-editor.software.informer.com/)
VSDC Free Video Editor is powerful video editing tool, which is completely free and quite popular. It supports a wide range of video formats including MOD, AVI, MP4, MKV, MPG, WMV, 3GP, FLV. Besides the very basic video editing functions, a bunch of filters can turn even a commonplace video sequence into a classy pro-quality movie, while thousands of video and audio effects conveniently grouped into four categories help you making your video to look and sound more dynamic.

**Pros:**
* Many useful options provided;
* Can also be used as a video converter.
**Cons:**
* Computer resources (CPU and RAM) are required at a high level.

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
Are you looking for a MOD editing tool? Well, in this era of high-tech communication and online technology, finding nothing is impossible. However, the dilemma is that various video editing tools are available and it is quite difficult to judge which one is good and which is bad. Moreover, you should find a tool, which would match your requirements precisely, providing the output that you exactly desired. So, how to find such a tool or software? Read this article to get a fair and unbiased guide on the top five MOD editors. The article will illustrate the features, pros, and cons of each of the tools.
* [Recommended: Wondershare Filmora](#tab%5F06)
* [Avidemux](#tab%5F01)
* [Free Video Dub](#tab%5F02)
* [MPEG Streamclip](#tab%5F03)
* [Any Video Converter](#tab%5F04)
* [VSDC Video Editor](#tab%5F05)
#### Recommended: Wondershare Filmora (originally Wondershare Video Editor)
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a more powerful video editing tool. It has an interactive interface and use-friendly options to endorse to the users: options or features are easy to understand and the interface is simplified for providing ease of operations to the users. Now download and try it out yourself.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
#### 1\. [Avidemux](http://avidemux-mswin.sourceforge.net/)
Avidemux is a popular video editing tool which is around the internet for a few years. It supports a wide range of video formats and provides excellent features and seamless options to offer to the users. The software has three compatible versions for Windows, Mac OS and Linux.

**Pros:**
* Basic video editing functions;
* Simple to use.
**Cons:**
* Outdated interface.
#### 2\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)
Free Video Dub is lightweight and user-friendly video editing tool. It supports a number of video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. With it, you can easily edit your video files by simply deleting off the unwanted sections. The best part about this tool is that you don't need to re-encode anything, which keeps the original quality of your video.

**Pros:**
* Multi-lingual interface which makes it easy to use;
* Several video formats supported.
**Cons:**
* May be difficult to add visual effects.
#### 3\. [MPEG Streamclip](http://www.squared5.com/)
MPEG Streamclip is not only a powerful video conversion tool, but also comes with a lot of features to offer to the users. It supports various video formats VOB, PS, M2P, MOD, VRO, DAT, MOV, DV, AVI, MP4, TS, M2T, MMV and more. It also includes simple nonlinear editing, cropping and scaling functions, which make it a great tool for editing your videos, especially if your project uses video from many different sources that need to fit in the same sequence.

**Pros:**
* Can convert a range of other video files;
* Has a glitched button and window.
**Cons:**
* Restricts your file sizes to 600MB.
#### 4\. [Any Video Converter](http://www.any-video-converter.com/products/for%5Fvideo%5Ffree/)
Any Video Converter is a popular file conversion tool, which easily convert MOD files and beside that it features loads of conversion options from one video file to another. It can also be marked as a video editing tool, which can serve multiple purposes with precision.

**Pros:**
* Supports many video formats;
* Easy to use interface.
**Cons:**
* Can't convert audio files.
#### 5\. [VSDC Video Editor](http://vsdc-free-video-editor.software.informer.com/)
VSDC Free Video Editor is powerful video editing tool, which is completely free and quite popular. It supports a wide range of video formats including MOD, AVI, MP4, MKV, MPG, WMV, 3GP, FLV. Besides the very basic video editing functions, a bunch of filters can turn even a commonplace video sequence into a classy pro-quality movie, while thousands of video and audio effects conveniently grouped into four categories help you making your video to look and sound more dynamic.

**Pros:**
* Many useful options provided;
* Can also be used as a video converter.
**Cons:**
* Computer resources (CPU and RAM) are required at a high level.

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
<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://video-creation-software.techidaily.com/new-speech-to-text-made-easy-conversion-methods-revealed/"><u>New Speech to Text Made Easy Conversion Methods Revealed</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-2024-approved-best-video-invitation-apps-for-ios-and-android/"><u>Updated 2024 Approved Best Video Invitation Apps for iOS and Android</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/2024-approved-stabilize-your-videos-for-free-8-best-online-tools-and-a-step-by-step-guide/"><u>2024 Approved Stabilize Your Videos for Free 8 Best Online Tools and a Step-by-Step Guide</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-cutting-edge-video-editing-without-the-cost-top-free-open-source-options-for-2024/"><u>New Cutting-Edge Video Editing Without the Cost Top Free Open-Source Options for 2024</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-unleash-your-inner-animator-top-animation-software-for-every-skill-level/"><u>New Unleash Your Inner Animator Top Animation Software for Every Skill Level</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-in-2024-master-vlc-how-to-play-videos-in-slow-motion-on-desktop-and-mobile/"><u>Updated In 2024, Master VLC How to Play Videos in Slow Motion on Desktop and Mobile</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-in-2024-the-ultimate-guide-to-filmora-discounts-4-expert-approved-methods/"><u>New In 2024, The Ultimate Guide to Filmora Discounts 4 Expert-Approved Methods</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-2024-approved-fcpx-video-accessibility-adding-subtitles-and-captions/"><u>Updated 2024 Approved FCPX Video Accessibility Adding Subtitles and Captions</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-split-screen-video-editing-made-easy-free-online-and-offline-solutions/"><u>New Split Screen Video Editing Made Easy Free Online and Offline Solutions</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-mac-video-editing-software-alternatives-to-pinnacle-studio-for-2024/"><u>Updated Mac Video Editing Software Alternatives to Pinnacle Studio for 2024</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-2024-approved-bring-your-photos-to-life-the-best-animation-tools/"><u>New 2024 Approved Bring Your Photos to Life The Best Animation Tools</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-in-2024-best-free-video-editing-software-for-splitting-wmv-files/"><u>New In 2024, Best Free Video Editing Software for Splitting WMV Files</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-in-2024-best-free-gif-loop-makers/"><u>New In 2024, Best Free GIF Loop Makers</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-2024-approved-loop-repeat-and-relax-top-10-free-video-looping-services/"><u>Updated 2024 Approved Loop, Repeat, and Relax Top 10 Free Video Looping Services</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/2024-approved-replace-virtualdub-with-these-powerful-video-editing-solutions/"><u>2024 Approved Replace VirtualDub with These Powerful Video Editing Solutions</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-online-facebook-mp3-conversion-top-8-services/"><u>New Online Facebook MP3 Conversion Top 8 Services</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-2024-approved-effortless-soundcloud-to-mp3-conversion-insider-secrets-revealed/"><u>New 2024 Approved Effortless Soundcloud to MP3 Conversion Insider Secrets Revealed</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/in-2024-picture-in-picture-made-easy-a-beginners-guide-to-fcp-video-editing/"><u>In 2024, Picture-in-Picture Made Easy A Beginners Guide to FCP Video Editing</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-the-ultimate-guide-to-splitting-videos-in-windows-live-movie-maker-for-beginners-for-2024/"><u>New The Ultimate Guide to Splitting Videos in Windows Live Movie Maker for Beginners for 2024</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-in-2024-top-5-free-video-editors-that-support-avi-format/"><u>Updated In 2024, Top 5 Free Video Editors That Support AVI Format</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-the-visual-advantage-how-to-use-aspect-ratios-to-boost-your-social-media-presence-for-2024/"><u>Updated The Visual Advantage How to Use Aspect Ratios to Boost Your Social Media Presence for 2024</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-mastering-video-pace-in-camtasia-tips-and-tricks/"><u>Updated Mastering Video Pace in Camtasia Tips and Tricks</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-speech-to-text-made-easy-conversion-methods-revealed/"><u>Updated Speech to Text Made Easy Conversion Methods Revealed</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-3-ways-to-add-transitions-in-final-cut-pro-for-2024/"><u>New 3 Ways To Add Transitions In Final Cut Pro for 2024</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/updated-2024-approved-quicktime-video-editing-for-mac-users-a-step-by-step-tutorial/"><u>Updated 2024 Approved QuickTime Video Editing for Mac Users A Step-by-Step Tutorial</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-5-best-free-video-rotation-apps-for-iphone-users-for-2024/"><u>New 5 Best Free Video Rotation Apps for iPhone Users for 2024</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/new-in-2024-combine-mov-videos-without-watermarks-top-5-free-tools/"><u>New In 2024, Combine MOV Videos without Watermarks Top 5 Free Tools</u></a></li>
<li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-iphone-12-without-passcode-drfone-by-drfone-ios/"><u>In 2024, How to Unlock iPhone 12 Without Passcode? | Dr.fone</u></a></li>
<li><a href="https://android-location-track.techidaily.com/in-2024-9-best-phone-monitoring-apps-for-vivo-y77t-drfone-by-drfone-virtual-android/"><u>In 2024, 9 Best Phone Monitoring Apps for Vivo Y77t | Dr.fone</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/overview-of-the-best-vivo-x-fold-2-screen-mirroring-app-drfone-by-drfone-android/"><u>Overview of the Best Vivo X Fold 2 Screen Mirroring App | Dr.fone</u></a></li>
<li><a href="https://unlock-android.techidaily.com/remove-the-lock-screen-fingerprint-of-your-vivo-y28-5g-by-drfone-android/"><u>Remove the Lock Screen Fingerprint Of Your Vivo Y28 5G</u></a></li>
<li><a href="https://android-location-track.techidaily.com/in-2024-two-ways-to-track-my-boyfriends-vivo-x-fold-2-without-him-knowing-drfone-by-drfone-virtual-android/"><u>In 2024, Two Ways to Track My Boyfriends Vivo X Fold 2 without Him Knowing | Dr.fone</u></a></li>
<li><a href="https://fix-guide.techidaily.com/proven-ways-to-fix-there-was-a-problem-parsing-the-package-on-realme-v30-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Proven Ways to Fix There Was A Problem Parsing the Package on Realme V30 | Dr.fone</u></a></li>
<li><a href="https://howto.techidaily.com/4-ways-to-fix-android-blue-screen-of-death-on-realme-c51-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>4 Ways to Fix Android Blue Screen of Death On Realme C51 | Dr.fone</u></a></li>
<li><a href="https://apple-account.techidaily.com/in-2024-how-to-fix-when-apple-account-locked-from-apple-iphone-6-by-drfone-ios/"><u>In 2024, How to Fix when Apple Account Locked From Apple iPhone 6?</u></a></li>
<li><a href="https://fix-guide.techidaily.com/how-to-fix-part-of-the-touch-screen-not-working-on-vivo-y27-4g-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>How To Fix Part of the Touch Screen Not Working on Vivo Y27 4G | Dr.fone</u></a></li>
<li><a href="https://ai-editing-video.techidaily.com/updated-2024-approved-deep-learning-of-ai-video-recognition/"><u>Updated 2024 Approved Deep Learning of AI Video Recognition</u></a></li>
<li><a href="https://android-location-track.techidaily.com/top-6-appsservices-to-trace-any-oppo-find-x7-location-by-mobile-number-drfone-by-drfone-virtual-android/"><u>Top 6 Apps/Services to Trace Any Oppo Find X7 Location By Mobile Number | Dr.fone</u></a></li>
<li><a href="https://howto.techidaily.com/7-solutions-to-fix-chrome-crashes-or-wont-open-on-oppo-find-x6-pro-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>7 Solutions to Fix Chrome Crashes or Wont Open on Oppo Find X6 Pro | Dr.fone</u></a></li>
<li><a href="https://sim-unlock.techidaily.com/in-2024-three-ways-to-sim-unlock-samsung-galaxy-f15-5g-by-drfone-android/"><u>In 2024, Three Ways to Sim Unlock Samsung Galaxy F15 5G</u></a></li>
<li><a href="https://easy-unlock-android.techidaily.com/in-2024-everything-you-need-to-know-about-lock-screen-settings-on-your-poco-by-drfone-android/"><u>In 2024, Everything You Need to Know about Lock Screen Settings on your Poco</u></a></li>
<li><a href="https://fake-location.techidaily.com/read-this-guide-to-find-a-reliable-alternative-to-fake-gps-on-apple-iphone-7-drfone-by-drfone-virtual-ios/"><u>Read This Guide to Find a Reliable Alternative to Fake GPS On Apple iPhone 7 | Dr.fone</u></a></li>
<li><a href="https://activate-lock.techidaily.com/how-to-remove-find-my-iphone-without-apple-id-from-your-apple-iphone-xs-by-drfone-ios/"><u>How to Remove Find My iPhone without Apple ID From your Apple iPhone XS?</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/how-to-mirror-your-huawei-p60-screen-to-pc-with-chromecast-drfone-by-drfone-android/"><u>How to Mirror Your Huawei P60 Screen to PC with Chromecast | Dr.fone</u></a></li>
<li><a href="https://location-social.techidaily.com/how-to-change-gps-location-on-realme-note-50-easily-and-safely-drfone-by-drfone-virtual-android/"><u>How to Change GPS Location on Realme Note 50 Easily & Safely | Dr.fone</u></a></li>
<li><a href="https://fake-location.techidaily.com/how-to-fix-life360-shows-wrong-location-on-itel-p40-drfone-by-drfone-virtual-android/"><u>How to Fix Life360 Shows Wrong Location On Itel P40? | Dr.fone</u></a></li>
<li><a href="https://review-topics.techidaily.com/in-2024-fake-the-location-to-get-around-the-mlb-blackouts-on-realme-gt-3-drfone-by-drfone-virtual-android/"><u>In 2024, Fake the Location to Get Around the MLB Blackouts on Realme GT 3 | Dr.fone</u></a></li>
<li><a href="https://android-location-track.techidaily.com/in-2024-top-4-ways-to-trace-samsung-galaxy-a05-location-drfone-by-drfone-virtual-android/"><u>In 2024, Top 4 Ways to Trace Samsung Galaxy A05 Location | Dr.fone</u></a></li>
<li><a href="https://fix-guide.techidaily.com/simple-solutions-to-fix-android-systemui-has-stopped-error-for-poco-m6-pro-5g-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Simple Solutions to Fix Android SystemUI Has Stopped Error For Poco M6 Pro 5G | Dr.fone</u></a></li>
<li><a href="https://ios-unlock.techidaily.com/how-to-change-country-on-app-store-for-apple-iphone-6s-plus-with-7-methods-by-drfone-ios/"><u>How To Change Country on App Store for Apple iPhone 6s Plus With 7 Methods</u></a></li>
</ul></div> |
<template>
<div class="home">
<div class="sidebar left-sidebar">
<h1>Koraci</h1>
<div v-for="(button, index) in buttons" :key="index" class="button-container">
<Button
label="Primary"
raised
@click="openComponent(index)"
class="button-item"
size="small"
>
<span class="label">{{ button.label }}</span>
<span class="circle">
<i class="pi pi-check" style="color: green"></i>
</span>
</Button>
<hr v-if="index !== buttons.length - 1" class="button-separator" />
<br />
</div>
</div>
<div class="content">
<div class="sidebar middle-sidebar">
<div class="heading">
<div v-if="selectedComponentIndex !== null">
<component :is="selectedComponent"></component>
</div>
</div>
</div>
</div>
<div class="sidebar right-sidebar">
<h1>Trenutni status</h1>
<div class="display-flex">
<Avatar icon="pi pi-user" class="mr-2" size="large" shape="circle" />
<p class="paragraph">{{ store.user.firstName }} {{ store.user.lastName }}</p>
<p class="paragraph">{{ store.user.roleName }}</p>
</div>
<div class="display-flex-w">
<p><b>Tema završnog rada: </b></p>
<p> Tema</p>
</div>
<div class="display-flex">
<p><b>Mentor: </b></p>
<p> Marko Marić</p>
</div>
<div class="display-flex">
<p><b> Status završnog rada: </b></p>
<p> U izradi</p>
</div>
<div class="display-flex">
<p><b> Dužnosti: </b></p>
<p> Knjižnica</p>
</div>
<div class="display-flex-w">
<h2>Obrana završnog rada</h2>
</div>
<div class="display-flex-w">
<i class="pi pi-calendar" style="font-size: 2.5rem"></i>
<p class="paragraph">15.07.2023.</p>
</div>
<div class="display-flex-w">
<i class="pi pi-clock" style="font-size: 2.5rem"></i>
<p class="paragraph">16.30h</p>
</div>
<div class="display-flex">
<i class="pi pi-building" style="font-size: 2.5rem"></i>
<p class="paragraph">Veleučilište u Rijeci - predavaonica 429</p>
</div>
<div class="display-flex-c">
<Calendar v-model="selectedDate" inline :showWeek="false" />
</div>
</div>
</div>
</template>
<script>
import { useUserStore } from '@/store/store'
import { ref } from 'vue'
import moment from 'moment'
import userController from '@/controllerEndpoints/userController'
import OdabirMentora from '@/views/HomePageViews/OdabirMentora.vue'
import OdabirTeme from '@/views/HomePageViews/OdabirTeme.vue'
// import MentorITemaPrihvaceni from '@/views/HomePageViews/MentorITemaPrihvaceni.vue'
// import Obrada from '@/views/HomePageViews/Obrada.vue'
import Duznosti from '@/views/HomePageViews/Duznosti.vue'
import ObranaRada from '@/views/HomePageViews/ObranaRada.vue'
const events = ref([
{
status: 'Odabir teme',
date: '15/10/2020 10:30',
icon: 'pi pi-shopping-cart',
color: '#9C27B0'
},
{ status: 'Odabir mentora', date: '15/10/2020 14:00', icon: 'pi pi-cog', color: '#673AB7' },
{
status: 'Mentor i tema prihvaćeni',
date: '15/10/2020 16:15',
icon: 'pi pi-shopping-cart',
color: '#FF9800'
},
{
status: 'U obradi: Izrada završnog rada u tijeku.',
date: '16/10/2020 10:00',
icon: 'pi pi-check',
color: '#607D8B'
},
{ status: 'Dužnosti', date: '15/10/2020 16:15', icon: 'pi pi-shopping-cart', color: '#FF9800' },
{ status: 'Obrana rada', date: '15/10/2020 16:15', icon: 'pi pi-shopping-cart', color: '#FF9800' }
])
export default {
name: 'HomeView',
data() {
return {
store: useUserStore(),
events,
selectedDate: moment().add(1, 'days').format('YYYY-MM-DD'),
currentDate: moment().format('YYYY-MM-DD'),
buttons: [
{ label: 'Odabir Mentora', component: OdabirMentora },
{ label: 'Odabir Teme', component: OdabirTeme },
// { label: 'Mentor I Tema Prihvaceni', component: MentorITemaPrihvaceni },
// { label: 'U obradi', component: Obrada },
{ label: 'Dužnosti', component: Duznosti },
{ label: 'Obrana Rada', component: ObranaRada }
],
selectedComponentIndex: null
}
},
methods: {
async log() {
const response = await userController.getTest()
console.log(response)
},
openComponent(index) {
this.selectedComponentIndex = index
}
},
computed: {
selectedComponent() {
if (this.selectedComponentIndex !== null) {
return this.buttons[this.selectedComponentIndex].component
}
return null
}
}
}
</script>
<style scoped>
.home {
display: flex;
flex-direction: row;
height: 100vh;
max-height: 60px;
}
.sidebar {
padding: 10px;
overflow-y: auto;
height: 100vh;
}
.left-sidebar {
width: 220px;
background-color: #f5f5f5;
border-right: 1px solid #ccc;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.right-sidebar {
padding-top: 40px;
padding-left: 10px;
width: 400px;
background-color: #f5f5f5;
border-left: 1px solid #ccc;
}
.content {
flex: 1;
padding: 30px;
}
.paragraph {
padding-left: 2em;
}
.display-flex {
display: flex;
padding-bottom: 15px;
padding-left: 20px;
border-bottom: 1px solid #ccc;
}
.display-flex-w {
padding-left: 20px;
display: flex;
padding-bottom: 5px;
}
.display-flex-c {
padding-top: 10px;
display: flex;
padding-bottom: 15px;
padding-left: 20px;
border-bottom: 1px solid #ccc;
}
.home h1 {
text-align: left;
font-size: 1.5rem;
font-weight: bold;
margin: 0;
padding: 20px;
}
.button-item {
background-color: #2196f3;
color: white;
padding: 10px 20px;
border: none;
border-radius: 10px;
margin-bottom: 10px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
text-transform: uppercase;
transition: background-color 0.3s ease;
position: relative;
width: 150px;
display: flex;
justify-content: center;
align-items: center;
}
.button-item:hover {
background-color: #1976d2;
}
.button-item i {
margin-right: 5px;
}
.circle {
position: absolute;
left: 1px;
top: 50%;
transform: translateY(-50%);
width: 18px;
height: 18px;
border-radius: 50%;
background-color: white;
margin-left: 5px;
margin-right: 5px;
}
.label {
padding-left: 2px;
margin-left: 5px;
}
.button-item {
margin-bottom: 5px;
display: flex;
align-items: center;
}
.button-separator {
border: none;
border-top: 1px solid #ccc;
margin-top: 15px;
}
</style> |
---
title: Azure Database for MySQLモニタリング統合
tags:
- Integrations
- Microsoft Azure integrations
- Azure integrations list
metaDescription: 'New Relic''s Microsoft Azure Database for MySQL integration: what data it reports and how to enable it.'
freshnessValidatedDate: never
translationType: machine
---
[New Relic の統合](/docs/infrastructure/integrations-getting-started/getting-started/introduction-infrastructure-integrations) には、 [Microsoft Azure Database for MySQL](https://azure.microsoft.com/en-us/services/mysql/) メトリクスなどのデータを New Relic に報告するための統合があります。このドキュメントでは、統合を有効にする方法と、報告されるデータについて説明します。
## 特徴
New Relicは、Azure Database for MySQLサービスからデータベースデータを収集します。Azure Database for MySQLサービスは、完全に管理されたエンタープライズ対応のMySQL Communityデータベースをサービスとして提供します。このサービスでは、高可用性、弾力的なスケーリング、自動バックアップ、および静止時と移動時のデータ保護が提供されています。
New Relicを使うと、以下のことができます。
* Azure Database for MySQLのデータを事前に作成されたダッシュボードで表示します。
* [カスタムクエリを実行し、データを視覚化します](/docs/infrastructure/integrations-getting-started/getting-started/use-integration-data-new-relic-insights)。
* データの変化を通知するアラート条件を作成します。
## 統合をアクティブ化する [#activate]
[標準的な手順に従って、New Relic](/docs/infrastructure/microsoft-azure-integrations/getting-started/activate-azure-integrations) で Azure サービスを有効化してください。
## 構成とポーリング [#polling]
[構成オプション](/docs/integrations/new-relic-integrations/getting-started/configure-polling-frequency-data-collection-cloud-integrations)を使用して、ポーリング頻度とフィルターデータを変更できます。
New Relic は、デフォルトの [ポーリング](/docs/integrations/microsoft-azure-integrations/getting-started/azure-integration-polling) の間隔に従って、Azure Database サービスに問い合わせを行いますが、これはインテグレーションによって異なります。Azure Database for MySQL の統合の場合。
* ポーリングの間隔5分(推奨最大ポーリング頻度:1時間)
* 解像度は1データポイント/分
## データを見つけて使用する [#find-and-use]
[統合データを探索する](/docs/infrastructure/integrations/find-use-infrastructure-integration-data)には、 **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Infrastructure > Azure > (統合を選択)**に移動します。
単一のデータベースに関するデータは、プロバイダー値`AzureMySqlServer`で`AzureMySqlServerSample`イベントタイプに関連付けられます。
## メトリックデータ [#metrics]
この統合により、次の [メトリック データ](/docs/infrastructure/integrations-getting-started/getting-started/understand-integration-data-data-types#metric)が収集されます。
### データベースサンプルのメトリクス [#database-sample]
<table>
<thead>
<tr>
<th style={{ width: "300px" }}>
メトリック
</th>
<th>
説明
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
`activeConnections`
</td>
<td>
アクティブな接続の数。
</td>
</tr>
<tr>
<td>
`backupStorageUsedBytes`
</td>
<td>
使用されたバックアップストレージ(バイト)。
</td>
</tr>
<tr>
<td>
`connectionsFailed`
</td>
<td>
接続に失敗した回数。
</td>
</tr>
<tr>
<td>
`cpuPercent`
</td>
<td>
CPUの使用率。
</td>
</tr>
<tr>
<td>
`memoryPercent`
</td>
<td>
使用されているメモリの割合。
</td>
</tr>
<tr>
<td>
`networkEgressBytes`
</td>
<td>
アクティブな接続におけるネットワークアウト(単位:バイト)。
</td>
</tr>
<tr>
<td>
`networkIngressBytes`
</td>
<td>
アクティブな接続のネットワークイン(単位:バイト)。
</td>
</tr>
<tr>
<td>
`secondsBehindMaster`
</td>
<td>
レプリケーション・ラグ(単位:秒)。
</td>
</tr>
<tr>
<td>
`serverlogStorageLimitBytes`
</td>
<td>
サーバーログの保存容量の上限(単位:バイト)。
</td>
</tr>
<tr>
<td>
`serverlogStoragePercent`
</td>
<td>
サーバーログストレージの使用率。
</td>
</tr>
<tr>
<td>
`serverlogStorageUsageBytes`
</td>
<td>
使用されているサーバーログのストレージ容量(単位:バイト)。
</td>
</tr>
<tr>
<td>
`storageLimitBytes`
</td>
<td>
利用可能なストレージの量をバイト単位で表します。
</td>
</tr>
<tr>
<td>
`storagePercent`
</td>
<td>
利用可能なストレージの使用率。
</td>
</tr>
<tr>
<td>
`storageUsedBytes`
</td>
<td>
使用されたストレージの量(バイト)。
</td>
</tr>
</tbody>
</table> |
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* 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/. */
#include "nsUnicodeProperties.h"
#include "nsUnicodePropertyData.cpp"
#include "mozilla/ArrayUtils.h"
#include "nsCharTraits.h"
#if ENABLE_INTL_API
#include "unicode/uchar.h"
#include "unicode/uscript.h"
#endif
#define UNICODE_BMP_LIMIT 0x10000
#define UNICODE_LIMIT 0x110000
#ifndef ENABLE_INTL_API
static const nsCharProps1&
GetCharProps1(uint32_t aCh)
{
if (aCh < UNICODE_BMP_LIMIT) {
return sCharProp1Values[sCharProp1Pages[0][aCh >> kCharProp1CharBits]]
[aCh & ((1 << kCharProp1CharBits) - 1)];
}
if (aCh < (kCharProp1MaxPlane + 1) * 0x10000) {
return sCharProp1Values[sCharProp1Pages[sCharProp1Planes[(aCh >> 16) - 1]]
[(aCh & 0xffff) >> kCharProp1CharBits]]
[aCh & ((1 << kCharProp1CharBits) - 1)];
}
// Default values for unassigned
static const nsCharProps1 undefined = {
0, // Index to mirrored char offsets
0, // Hangul Syllable type
0 // Combining class
};
return undefined;
}
#endif
const nsCharProps2&
GetCharProps2(uint32_t aCh)
{
if (aCh < UNICODE_BMP_LIMIT) {
return sCharProp2Values[sCharProp2Pages[0][aCh >> kCharProp2CharBits]]
[aCh & ((1 << kCharProp2CharBits) - 1)];
}
if (aCh < (kCharProp2MaxPlane + 1) * 0x10000) {
return sCharProp2Values[sCharProp2Pages[sCharProp2Planes[(aCh >> 16) - 1]]
[(aCh & 0xffff) >> kCharProp2CharBits]]
[aCh & ((1 << kCharProp2CharBits) - 1)];
}
NS_NOTREACHED("Getting CharProps for codepoint outside Unicode range");
// Default values for unassigned
using namespace mozilla::unicode;
static const nsCharProps2 undefined = {
#if ENABLE_INTL_API
PAIRED_BRACKET_TYPE_NONE,
VERTICAL_ORIENTATION_R,
XIDMOD_NOT_CHARS
#else
uint8_t(Script::UNKNOWN),
PAIRED_BRACKET_TYPE_NONE,
HB_UNICODE_GENERAL_CATEGORY_UNASSIGNED,
eCharType_LeftToRight,
XIDMOD_NOT_CHARS,
-1, // Numeric Value
VERTICAL_ORIENTATION_R
#endif
};
return undefined;
}
namespace mozilla {
namespace unicode {
/*
To store properties for a million Unicode codepoints compactly, we use
a three-level array structure, with the Unicode values considered as
three elements: Plane, Page, and Char.
Space optimization happens because multiple Planes can refer to the same
Page array, and multiple Pages can refer to the same Char array holding
the actual values. In practice, most of the higher planes are empty and
thus share the same data; and within the BMP, there are also many pages
that repeat the same data for any given property.
Plane is usually zero, so we skip a lookup in this case, and require
that the Plane 0 pages are always the first set of entries in the Page
array.
The division of the remaining 16 bits into Page and Char fields is
adjusted for each property (by experiment using the generation tool)
to provide the most compact storage, depending on the distribution
of values.
*/
const nsIUGenCategory::nsUGenCategory sDetailedToGeneralCategory[] = {
/*
* The order here corresponds to the HB_UNICODE_GENERAL_CATEGORY_* constants
* of the hb_unicode_general_category_t enum in gfx/harfbuzz/src/hb-unicode.h.
*/
/* CONTROL */ nsIUGenCategory::kOther,
/* FORMAT */ nsIUGenCategory::kOther,
/* UNASSIGNED */ nsIUGenCategory::kOther,
/* PRIVATE_USE */ nsIUGenCategory::kOther,
/* SURROGATE */ nsIUGenCategory::kOther,
/* LOWERCASE_LETTER */ nsIUGenCategory::kLetter,
/* MODIFIER_LETTER */ nsIUGenCategory::kLetter,
/* OTHER_LETTER */ nsIUGenCategory::kLetter,
/* TITLECASE_LETTER */ nsIUGenCategory::kLetter,
/* UPPERCASE_LETTER */ nsIUGenCategory::kLetter,
/* COMBINING_MARK */ nsIUGenCategory::kMark,
/* ENCLOSING_MARK */ nsIUGenCategory::kMark,
/* NON_SPACING_MARK */ nsIUGenCategory::kMark,
/* DECIMAL_NUMBER */ nsIUGenCategory::kNumber,
/* LETTER_NUMBER */ nsIUGenCategory::kNumber,
/* OTHER_NUMBER */ nsIUGenCategory::kNumber,
/* CONNECT_PUNCTUATION */ nsIUGenCategory::kPunctuation,
/* DASH_PUNCTUATION */ nsIUGenCategory::kPunctuation,
/* CLOSE_PUNCTUATION */ nsIUGenCategory::kPunctuation,
/* FINAL_PUNCTUATION */ nsIUGenCategory::kPunctuation,
/* INITIAL_PUNCTUATION */ nsIUGenCategory::kPunctuation,
/* OTHER_PUNCTUATION */ nsIUGenCategory::kPunctuation,
/* OPEN_PUNCTUATION */ nsIUGenCategory::kPunctuation,
/* CURRENCY_SYMBOL */ nsIUGenCategory::kSymbol,
/* MODIFIER_SYMBOL */ nsIUGenCategory::kSymbol,
/* MATH_SYMBOL */ nsIUGenCategory::kSymbol,
/* OTHER_SYMBOL */ nsIUGenCategory::kSymbol,
/* LINE_SEPARATOR */ nsIUGenCategory::kSeparator,
/* PARAGRAPH_SEPARATOR */ nsIUGenCategory::kSeparator,
/* SPACE_SEPARATOR */ nsIUGenCategory::kSeparator
};
#ifdef ENABLE_INTL_API
const hb_unicode_general_category_t sICUtoHBcategory[U_CHAR_CATEGORY_COUNT] = {
HB_UNICODE_GENERAL_CATEGORY_UNASSIGNED, // U_GENERAL_OTHER_TYPES = 0,
HB_UNICODE_GENERAL_CATEGORY_UPPERCASE_LETTER, // U_UPPERCASE_LETTER = 1,
HB_UNICODE_GENERAL_CATEGORY_LOWERCASE_LETTER, // U_LOWERCASE_LETTER = 2,
HB_UNICODE_GENERAL_CATEGORY_TITLECASE_LETTER, // U_TITLECASE_LETTER = 3,
HB_UNICODE_GENERAL_CATEGORY_MODIFIER_LETTER, // U_MODIFIER_LETTER = 4,
HB_UNICODE_GENERAL_CATEGORY_OTHER_LETTER, // U_OTHER_LETTER = 5,
HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK, // U_NON_SPACING_MARK = 6,
HB_UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK, // U_ENCLOSING_MARK = 7,
HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK, // U_COMBINING_SPACING_MARK = 8,
HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER, // U_DECIMAL_DIGIT_NUMBER = 9,
HB_UNICODE_GENERAL_CATEGORY_LETTER_NUMBER, // U_LETTER_NUMBER = 10,
HB_UNICODE_GENERAL_CATEGORY_OTHER_NUMBER, // U_OTHER_NUMBER = 11,
HB_UNICODE_GENERAL_CATEGORY_SPACE_SEPARATOR, // U_SPACE_SEPARATOR = 12,
HB_UNICODE_GENERAL_CATEGORY_LINE_SEPARATOR, // U_LINE_SEPARATOR = 13,
HB_UNICODE_GENERAL_CATEGORY_PARAGRAPH_SEPARATOR, // U_PARAGRAPH_SEPARATOR = 14,
HB_UNICODE_GENERAL_CATEGORY_CONTROL, // U_CONTROL_CHAR = 15,
HB_UNICODE_GENERAL_CATEGORY_FORMAT, // U_FORMAT_CHAR = 16,
HB_UNICODE_GENERAL_CATEGORY_PRIVATE_USE, // U_PRIVATE_USE_CHAR = 17,
HB_UNICODE_GENERAL_CATEGORY_SURROGATE, // U_SURROGATE = 18,
HB_UNICODE_GENERAL_CATEGORY_DASH_PUNCTUATION, // U_DASH_PUNCTUATION = 19,
HB_UNICODE_GENERAL_CATEGORY_OPEN_PUNCTUATION, // U_START_PUNCTUATION = 20,
HB_UNICODE_GENERAL_CATEGORY_CLOSE_PUNCTUATION, // U_END_PUNCTUATION = 21,
HB_UNICODE_GENERAL_CATEGORY_CONNECT_PUNCTUATION, // U_CONNECTOR_PUNCTUATION = 22,
HB_UNICODE_GENERAL_CATEGORY_OTHER_PUNCTUATION, // U_OTHER_PUNCTUATION = 23,
HB_UNICODE_GENERAL_CATEGORY_MATH_SYMBOL, // U_MATH_SYMBOL = 24,
HB_UNICODE_GENERAL_CATEGORY_CURRENCY_SYMBOL, // U_CURRENCY_SYMBOL = 25,
HB_UNICODE_GENERAL_CATEGORY_MODIFIER_SYMBOL, // U_MODIFIER_SYMBOL = 26,
HB_UNICODE_GENERAL_CATEGORY_OTHER_SYMBOL, // U_OTHER_SYMBOL = 27,
HB_UNICODE_GENERAL_CATEGORY_INITIAL_PUNCTUATION, // U_INITIAL_PUNCTUATION = 28,
HB_UNICODE_GENERAL_CATEGORY_FINAL_PUNCTUATION, // U_FINAL_PUNCTUATION = 29,
};
#endif
uint8_t GetGeneralCategory(uint32_t aCh) {
#if ENABLE_INTL_API
return sICUtoHBcategory[u_charType(aCh)];
#else
return GetCharProps2(aCh).mCategory;
#endif
}
nsCharType GetBidiCat(uint32_t aCh) {
#if ENABLE_INTL_API
return nsCharType(u_charDirection(aCh));
#else
return nsCharType(GetCharProps2(aCh).mBidiCategory);
#endif
}
int8_t GetNumericValue(uint32_t aCh) {
#if ENABLE_INTL_API
UNumericType type =
UNumericType(u_getIntPropertyValue(aCh, UCHAR_NUMERIC_TYPE));
return type == U_NT_DECIMAL || type == U_NT_DIGIT
? int8_t(u_getNumericValue(aCh))
: -1;
#else
return GetCharProps2(aCh).mNumericValue;
#endif
}
uint32_t
GetMirroredChar(uint32_t aCh)
{
#if ENABLE_INTL_API
return u_charMirror(aCh);
#else
return aCh + sMirrorOffsets[GetCharProps1(aCh).mMirrorOffsetIndex];
#endif
}
bool
HasMirroredChar(uint32_t aCh)
{
#if ENABLE_INTL_API
return u_isMirrored(aCh);
#else
return GetCharProps1(aCh).mMirrorOffsetIndex != 0;
#endif
}
uint8_t
GetCombiningClass(uint32_t aCh)
{
#if ENABLE_INTL_API
return u_getCombiningClass(aCh);
#else
return GetCharProps1(aCh).mCombiningClass;
#endif
}
uint8_t
GetLineBreakClass(uint32_t aCh)
{
#if ENABLE_INTL_API
return u_getIntPropertyValue(aCh, UCHAR_LINE_BREAK);
#else
return GetCharProps2(aCh).mLineBreak;
#endif
}
Script
GetScriptCode(uint32_t aCh)
{
#if ENABLE_INTL_API
UErrorCode err = U_ZERO_ERROR;
return Script(uscript_getScript(aCh, &err));
#else
return Script(GetCharProps2(aCh).mScriptCode);
#endif
}
uint32_t
GetScriptTagForCode(Script aScriptCode)
{
#if ENABLE_INTL_API
const char* tag = uscript_getShortName(UScriptCode(aScriptCode));
return HB_TAG(tag[0], tag[1], tag[2], tag[3]);
#else
// this will safely return 0 for negative script codes, too :)
if (static_cast<uint32_t>(aScriptCode) > ArrayLength(sScriptCodeToTag)) {
return 0;
}
return sScriptCodeToTag[static_cast<uint32_t>(aScriptCode)];
#endif
}
PairedBracketType GetPairedBracketType(uint32_t aCh)
{
#if ENABLE_INTL_API
return PairedBracketType
(u_getIntPropertyValue(aCh, UCHAR_BIDI_PAIRED_BRACKET_TYPE));
#else
return PairedBracketType(GetCharProps2(aCh).mPairedBracketType);
#endif
}
uint32_t GetPairedBracket(uint32_t aCh)
{
#if ENABLE_INTL_API
return u_getBidiPairedBracket(aCh);
#else
return GetPairedBracketType(aCh) != PAIRED_BRACKET_TYPE_NONE
? GetMirroredChar(aCh) : aCh;
#endif
}
static inline uint32_t
GetCaseMapValue(uint32_t aCh)
{
if (aCh < UNICODE_BMP_LIMIT) {
return sCaseMapValues[sCaseMapPages[0][aCh >> kCaseMapCharBits]]
[aCh & ((1 << kCaseMapCharBits) - 1)];
}
if (aCh < (kCaseMapMaxPlane + 1) * 0x10000) {
return sCaseMapValues[sCaseMapPages[sCaseMapPlanes[(aCh >> 16) - 1]]
[(aCh & 0xffff) >> kCaseMapCharBits]]
[aCh & ((1 << kCaseMapCharBits) - 1)];
}
return 0;
}
uint32_t
GetUppercase(uint32_t aCh)
{
uint32_t mapValue = GetCaseMapValue(aCh);
if (mapValue & (kLowerToUpper | kTitleToUpper)) {
return aCh ^ (mapValue & kCaseMapCharMask);
}
if (mapValue & kLowerToTitle) {
return GetUppercase(aCh ^ (mapValue & kCaseMapCharMask));
}
return aCh;
}
uint32_t
GetLowercase(uint32_t aCh)
{
uint32_t mapValue = GetCaseMapValue(aCh);
if (mapValue & kUpperToLower) {
return aCh ^ (mapValue & kCaseMapCharMask);
}
if (mapValue & kTitleToUpper) {
return GetLowercase(aCh ^ (mapValue & kCaseMapCharMask));
}
return aCh;
}
uint32_t
GetTitlecaseForLower(uint32_t aCh)
{
uint32_t mapValue = GetCaseMapValue(aCh);
if (mapValue & (kLowerToTitle | kLowerToUpper)) {
return aCh ^ (mapValue & kCaseMapCharMask);
}
return aCh;
}
uint32_t
GetTitlecaseForAll(uint32_t aCh)
{
uint32_t mapValue = GetCaseMapValue(aCh);
if (mapValue & (kLowerToTitle | kLowerToUpper)) {
return aCh ^ (mapValue & kCaseMapCharMask);
}
if (mapValue & kUpperToLower) {
return GetTitlecaseForLower(aCh ^ (mapValue & kCaseMapCharMask));
}
return aCh;
}
#if 0 // currently unused - bug 857481
HanVariantType
GetHanVariant(uint32_t aCh)
{
// In the sHanVariantValues array, data for 4 successive characters
// (2 bits each) is packed in to each uint8_t entry, with the value
// for the lowest character stored in the least significant bits.
uint8_t v = 0;
if (aCh < UNICODE_BMP_LIMIT) {
v = sHanVariantValues[sHanVariantPages[0][aCh >> kHanVariantCharBits]]
[(aCh & ((1 << kHanVariantCharBits) - 1)) >> 2];
} else if (aCh < (kHanVariantMaxPlane + 1) * 0x10000) {
v = sHanVariantValues[sHanVariantPages[sHanVariantPlanes[(aCh >> 16) - 1]]
[(aCh & 0xffff) >> kHanVariantCharBits]]
[(aCh & ((1 << kHanVariantCharBits) - 1)) >> 2];
}
// extract the appropriate 2-bit field from the value
return HanVariantType((v >> ((aCh & 3) * 2)) & 3);
}
#endif
#define DEFINE_BMP_1PLANE_MAPPING_GET_FUNC(prefix_) \
uint32_t Get##prefix_(uint32_t aCh) \
{ \
if (aCh >= UNICODE_BMP_LIMIT) { \
return aCh; \
} \
auto page = s##prefix_##Pages[aCh >> k##prefix_##CharBits]; \
auto index = aCh & ((1 << k##prefix_##CharBits) - 1); \
uint32_t v = s##prefix_##Values[page][index]; \
return v ? v : aCh; \
}
// full-width mappings only exist for BMP characters; all others are
// returned unchanged
DEFINE_BMP_1PLANE_MAPPING_GET_FUNC(FullWidth)
DEFINE_BMP_1PLANE_MAPPING_GET_FUNC(FullWidthInverse)
bool
IsClusterExtender(uint32_t aCh, uint8_t aCategory)
{
return ((aCategory >= HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK &&
aCategory <= HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK) ||
(aCh >= 0x200c && aCh <= 0x200d) || // ZWJ, ZWNJ
(aCh >= 0xff9e && aCh <= 0xff9f)); // katakana sound marks
}
enum HSType {
#if ENABLE_INTL_API
HST_NONE = U_HST_NOT_APPLICABLE,
HST_L = U_HST_LEADING_JAMO,
HST_V = U_HST_VOWEL_JAMO,
HST_T = U_HST_TRAILING_JAMO,
HST_LV = U_HST_LV_SYLLABLE,
HST_LVT = U_HST_LVT_SYLLABLE
#else
HST_NONE = 0x00,
HST_L = 0x01,
HST_V = 0x02,
HST_T = 0x04,
HST_LV = 0x03,
HST_LVT = 0x07
#endif
};
static HSType
GetHangulSyllableType(uint32_t aCh)
{
#if ENABLE_INTL_API
return HSType(u_getIntPropertyValue(aCh, UCHAR_HANGUL_SYLLABLE_TYPE));
#else
return HSType(GetCharProps1(aCh).mHangulType);
#endif
}
void
ClusterIterator::Next()
{
if (AtEnd()) {
NS_WARNING("ClusterIterator has already reached the end");
return;
}
uint32_t ch = *mPos++;
if (NS_IS_HIGH_SURROGATE(ch) && mPos < mLimit &&
NS_IS_LOW_SURROGATE(*mPos)) {
ch = SURROGATE_TO_UCS4(ch, *mPos++);
} else if ((ch & ~0xff) == 0x1100 ||
(ch >= 0xa960 && ch <= 0xa97f) ||
(ch >= 0xac00 && ch <= 0xd7ff)) {
// Handle conjoining Jamo that make Hangul syllables
HSType hangulState = GetHangulSyllableType(ch);
while (mPos < mLimit) {
ch = *mPos;
HSType hangulType = GetHangulSyllableType(ch);
switch (hangulType) {
case HST_L:
case HST_LV:
case HST_LVT:
if (hangulState == HST_L) {
hangulState = hangulType;
mPos++;
continue;
}
break;
case HST_V:
if ((hangulState != HST_NONE) && (hangulState != HST_T) &&
(hangulState != HST_LVT)) {
hangulState = hangulType;
mPos++;
continue;
}
break;
case HST_T:
if (hangulState != HST_NONE && hangulState != HST_L) {
hangulState = hangulType;
mPos++;
continue;
}
break;
default:
break;
}
break;
}
}
while (mPos < mLimit) {
ch = *mPos;
// Check for surrogate pairs; note that isolated surrogates will just
// be treated as generic (non-cluster-extending) characters here,
// which is fine for cluster-iterating purposes
if (NS_IS_HIGH_SURROGATE(ch) && mPos < mLimit - 1 &&
NS_IS_LOW_SURROGATE(*(mPos + 1))) {
ch = SURROGATE_TO_UCS4(ch, *(mPos + 1));
}
if (!IsClusterExtender(ch)) {
break;
}
mPos++;
if (!IS_IN_BMP(ch)) {
mPos++;
}
}
NS_ASSERTION(mText < mPos && mPos <= mLimit,
"ClusterIterator::Next has overshot the string!");
}
uint32_t
CountGraphemeClusters(const char16_t* aText, uint32_t aLength)
{
ClusterIterator iter(aText, aLength);
uint32_t result = 0;
while (!iter.AtEnd()) {
++result;
iter.Next();
}
return result;
}
} // end namespace unicode
} // end namespace mozilla |
import {Checkbox, Grid, IconButton} from "@mui/material";
import {Delete} from "@mui/icons-material";
import {EditableSpan} from "../EditableSpan/EditableSpan";
import {ChangeEvent, FC} from "react";
import {changeTaskStatusAC, changeTaskAC} from "../../store/tasksReducer";
import {useDispatch} from "react-redux";
import Box from "@mui/material/Box";
import {ITasks} from "../../models/ITasks";
import {v1} from "uuid";
type TodoTaskType = {
todoListsId: string,
task: ITasks,
removeTask: (todoListId: string, taskId: string) => void,
}
export const TodoTask: FC<TodoTaskType> = ({todoListsId, task, removeTask}) => {
const dispatch = useDispatch()
const onClickHandler = () => removeTask(todoListsId, task.id)
const onChangeHandler = (e: ChangeEvent<HTMLInputElement>) => {
let newIsDoneValue = e.currentTarget.checked;
dispatch(changeTaskStatusAC(todoListsId, task.id, newIsDoneValue))
}
const onTitleChangeHandler = (newValue: string) => {
dispatch(changeTaskAC(todoListsId, task.id, newValue, task.tags))
}
return(
<>
<Grid
container
direction="row"
width='100%'
border='1px solid gray'
borderRadius='5px'
margin='5px 0'
>
<Checkbox
checked={task.isDone}
color="primary"
onChange={onChangeHandler}
/>
<Grid
container
direction="column"
justifyContent="flex-start"
alignItems="flex-start"
width='76%'
padding='10px 0'
>
<EditableSpan todoListsId={todoListsId} id={task.id} value={task.task} onChange={onTitleChangeHandler} />
<Box component='div' sx={{display: 'flex'}}>Tags:
{task.tags.map((tag,index) =>
<Box key={index} component='span' sx={{padding: '0 3px'}}> {tag} </Box>)}
</Box>
</Grid>
<IconButton onClick={onClickHandler}>
<Delete />
</IconButton>
</Grid>
</>
)
} |
from abc import ABC, abstractmethod
# Define an abstract base class (ABC) for Bird with two abstract methods
class WalkAble(ABC):
@abstractmethod
def fly(self):
pass
class FlyAble(ABC):
def fly(self):
pass
class EatAble:
def eat(self):
print(f"Їсти! {self.__class__.__name__}")
class Ostriche(WalkAble, EatAble):
def walk(self):
print("Ostriche is walking")
class Eagle(WalkAble, FlyAble, EatAble):
def fly(self):
print("Eagle is flying")
def walk(self):
print("Eagle is walking")
try:
obj = Eagle()
obj.fly()
obj.walk()
obj.eat()
obj2 = Ostriche()
obj2.walk()
obj2.eat()
# Will raise an exception as ostriches can't fly
obj2.fly()
except Exception as e:
# Print the exception message
print(e) |
1) Написати ф-ю яка приймає в себе 2 параметра (обєкт замовлення і обєкт з цінами товару)
Ця ф-я має повернути ціну замовлення
const productsPrice = {
apple: 20,
orange: 5,
cheese: 12,
pork: 45,
bread: 23
}
const orderA = {
apple: 5,
cheese: 1,
bread: 3
}
const orderB = {
orange: 10,
pork: 2,
bread: 1
}
2) Написати ф-ю яка буде показувати статус вашої бібліотеки на основі данних масива
libraryStatus(arr) має вивести такий результат :
// Already read 'Bill Gates' by The Road Ahead.
//Already read 'Steve Jobs' by Walter Isaacson.
//You still need to read 'Mockingjay: The Final Book of The Hunger Games' by Suzanne Collins.
const library = [
{
title: 'Bill Gates',
author: 'The Road Ahead',
readingStatus: true
},
{
title: 'Steve Jobs',
author: 'Walter Isaacson',
readingStatus: true
},
{
title: 'Mockingjay: The Final Book of The Hunger Games',
author: 'Suzanne Collins',
readingStatus: false
}];
3) Написати ф-ю isObjectEmpty яка перевіряє чи обєкт пустий чи ні. Якщо обєкт пустий то повернути true інакше false
isObjectEmpty({}) // true
isObjectEmpty({name: 'user, age: {21}}) // false
4) Створити обєкт піци з полями і методами
В обєкті має бути такі поля і методи:
1) поле для збереження розміру піци
2) поле для збереження списку добавок
3) поле для збереження списку соусів
4) метод для додавання добавки (Можна додати добавку якщо вона відсутня інакше показувати помилку)
5) метод для додавання соусу (Можна додати соус якщо він відсутній інакше показувати, також помилка показувється якщо пробуємо видалити добавку, а там ще жодної немає)
6) метод для видалення добавки (Можна видалити добавку якщо вона присутня в піці інакше показувати помилку, також помилка показувється якщо пробуємо видалити соус, а там ще жодного немає)
7) метод для видалення соусу (Можна видалити соус якщо він присутній в піці інакше показувати помилку)
8) метод для розрахунку загальної ціни піци (розмір + добавки + соуси) (ціна округлена до двох знаків після коми)
9) метод для розрахунку загальної кількості калорій піци (розмір + добавки + соуси)
10 ) метод який показує загальну інформацію про замовлення (ціну, калорії, список добавок і соусів) (Якщо піца валідна інакше показувати помилку)
11) метод вибору розміру піци (Розмір піци можна змінити в будь-який момент)
12) метод що показує час приготуванни в хвилинах в залежності від складності піци
13) Метод валідації піци який поверне true якщо піца відповідає вимогам , а саме (вибраний розмір піци, є мінімум одна добавка, і мінімум один соус) інакше false (І виводить строку чого не вистачає (коржа, добавки, чи соусу))
(використовувати this)
const SIZES = {
BIG: {
price: 25,
cal: 100,
time: 15
},
SMALL : {
price : 15,
cal: 50,
time: 7
},
MEDIUM: {
price : 15,
cal: 50,
time: 7
}
},
const STUFFING = {
CHEESE: {
price : 6.5,
cal: 45,
time: 2
},
BEACON : {
price : 10,
cal: 70,
time: 6
},
TOMATO : {
price : 12.1,
cal: 4,
time: 5
},
CHICKEN : {
price : 9.3,
cal: 30,
time: 5.1
}
}
const SAUCES = {
MUSTARD: {
price : 3,
cal: 5,
time: 1
},
KETCHUP = {
price : 4.2,
cal: 20,
time: 1.5
},
BOLOGNESE = {
price : 7.5,
cal: 50,
time: 3
}
}
Для перевірки роботи програми потрібно:
1) Вибрати розмір піци
2) Додати добавку
3) Додати іншу добавку
4) Додати добавку яка вже існує
5) Додати соус
6) Додати ще один соус
7) Додати соус що існує
8) Порахувати ціну піци
9) Порахувати калорії в піці
10) Порахувати час приготування
11) Видалити одну добавку
12) Видалити соус
13) Змінити розмір піци
14) Порахувати нову ціну
15) Порахувати нову кількість калорій
16) Порахувати новий час приготування
17) Провести валідацію піци
18) Вивести інформацію про сформовану піцу на екран
19) Видалити останій соуси
20) Провести валідацію піци
21) Вивести інформацію про сформовану піцу на екран |
package com.api.gateway.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.api.gateway.dtos.RequestCreatePlayerDto;
import com.api.gateway.dtos.RequestDeletePlayerDto;
import com.api.gateway.dtos.RequestShowPlayerDto;
import com.api.gateway.dtos.RequestUpdatePlayerDto;
import com.api.gateway.producers.PlayerProducer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
@RestController
public class PlayerController {
@Autowired
PlayerProducer playerProducer;
@GetMapping("/info")
public ResponseEntity<String> info(){
return ResponseEntity.status(HttpStatus.OK).body("Version 1.0.0");
}
@PostMapping("/")
public ResponseEntity<Object> createPlayer(
@RequestBody RequestCreatePlayerDto body
){
playerProducer.createPlayer(body);
return ResponseEntity.status(HttpStatus.CREATED).body(null);
}
@GetMapping("/")
public ResponseEntity<Object> listPlayer() throws JsonMappingException, JsonProcessingException{
var response = playerProducer.listPlayer();
return ResponseEntity.status(HttpStatus.OK).body(response);
}
@GetMapping("/{id}")
public ResponseEntity<Object> showPlayer(
@PathVariable("id") String player_id
){
playerProducer.showPlayer(new RequestShowPlayerDto(player_id));
return ResponseEntity.status(HttpStatus.CREATED).body(null);
}
@PutMapping("/{id}")
public ResponseEntity<Object> updatePlayer(
@PathVariable("id") String player_id,
@RequestParam(name = "name") String name
){
playerProducer.updatePlayer(new RequestUpdatePlayerDto(player_id, name));
return ResponseEntity.status(HttpStatus.OK).body(null);
}
@DeleteMapping("/{id}")
public ResponseEntity<Object> deletePlayer(
@PathVariable("id") String player_id
){
playerProducer.deletePlayer(new RequestDeletePlayerDto(player_id));
return ResponseEntity.status(HttpStatus.OK).body(null);
}
} |
<!DOCTYPE html>
<html lang="pt-br">
<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>Blog Post</title>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script type="text/javascript">
jQuery(window).load(function ($) {
atualizaRelogio();
});
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous" />
<style>
body {
padding-top: 50px;
}
</style>
</head>
<script>
function atualizaRelogio() {
var momentoAtual = new Date();
var vhora = momentoAtual.getHours();
var vminuto = momentoAtual.getMinutes();
var vsegundo = momentoAtual.getSeconds();
var vdia = momentoAtual.getDate();
var vmes = momentoAtual.getMonth() + 1;
var vano = momentoAtual.getFullYear();
if (vdia < 10) { vdia = "0" + vdia; }
if (vmes < 10) { vmes = "0" + vmes; }
if (vhora < 10) { vhora = "0" + vhora; }
if (vminuto < 10) { vminuto = "0" + vminuto; }
if (vsegundo < 10) { vsegundo = "0" + vsegundo; }
dataFormat = vdia + " / " + vmes + " / " + vano;
horaFormat = vhora + " : " + vminuto + " : " + vsegundo;
document.getElementById("data").innerHTML = dataFormat;
document.getElementById("hora").innerHTML = horaFormat;
setTimeout("atualizaRelogio()", 1000);
}
</script>
<body class="container">
<header>
<div class="jumbotron">
<h1>Meu primeiro Blog</h1>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<!-- <a href="/" class="navbar-brand">EJS</a> -->
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="./blog-post.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Sobre</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./contactForm.html">Contato</a>
</li>
</ul>
</nav>
</div>
</header>
<main>
<div class="jumbotron">
<h3>Lorem Ipsum</h3><br>
<img src="https://source.unsplash.com/random" alt="" width="300px" height="300px">
<article>
<div class="jumbotron">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea, enim ipsam facilis saepe maxime
quisquam,
quis
quod nostrum hic qui, molestias fugiat quo laborum! Dolorum repellat odio perspiciatis eveniet
inventore!
</p>
</div>
<hr>
<aside>
<div>
<label for="data">Data:</label>
<output id="data"></output>
</div>
<!-- Para mostrar a hora -->
<!-- <div>
<output id="hora" style="font-family: 'arial black', 'avant garde'; font-size: 12px;"></output>
</div> -->
<img src="https://source.unsplash.com/random" alt="" width="150px" height="150px">
<dl>
<dt>Por: Daniel Dantas</dt>
<dd>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae tempora ipsa quisquam ratione
labore eius esse ut nulla a error architecto quod magni, assumenda temporibus distinctio
numquam
similique est saepe?</dd>
</dl>
</aside>
</article>
</div>
</main>
<footer>
<p class="text-center text-muted">©️ Copyright by Daniel Dantas ☠️</p>
</footer>
</body>
</html> |
const mongoose = require('mongoose');
const resizeImage = require("../helpers/resizeImage")
const asyncHandler = require("express-async-handler")
const { itemModel, categoryModel } = require("../models/categoryModel");
const fs = require('fs');
const path = require('path');
/*
desc - get a category
route - GET - /api/categories/:id
access - public
*/
const getCategory = async (req, res, next) => {
try {
const category = await categoryModel.findById(req.params.id);
if (!category) {
res.status(404)
throw new Error("Contact not found");
}
res.status(200).json(category);
} catch (error) {
next(error);
}
}
/*
desc - get all categories
route - GET - /api/categories (http://localhost:5001/api/categories)
access - public
*/
const getAllCategories = asyncHandler(async (req, res) => {
const categories = await categoryModel.find()
if (!categories) {
res.status(404)
throw new Error("No categories found")
}
res.status(200).json(categories)
})
/*
desc - create category
route - POST - /api/categories ( http://localhost:5001/api/categories )
access - public
*/
const createCategory = asyncHandler(async (req, res) => {
try {
let imageSrc = req.file ? `/uploads/${req.file.filename}` : 'https://cdn.vuetifyjs.com/images/cards/cooking.png';
// Resize the uploaded image
if (req.file) {
const resizedImagePath = `uploads/resized_${req.file.filename}`;
await resizeImage(req.file.path, resizedImagePath);
// Delete the original image file
try {
fs.unlinkSync(req.file.path);
} catch (error) {
console.error('Error deleting the original image:', error);
}
// Update the imageSrc to the resized image path
imageSrc = `/uploads/resized_${req.file.filename}`;
}
req.body.imageSrc = imageSrc;
const category = await categoryModel.create(req.body);
res.status(201).json(category);
} catch (error) {
res.status(500).json({ message: 'Internal server error' });
}
});
/*
desc - edit category
route - PUT - /api/categories/:id
access - public
*/
const editCategory = asyncHandler(async (req, res) => {
let updatedCategoryData = req.body;
// Check if a new file is uploaded
if (req.file) {
// Delete previous file if it exists
const previousCategory = await categoryModel.findById(req.params.id);
if (previousCategory && previousCategory.imageSrc) {
const previousImagePath = path.join(__dirname, '..', previousCategory.imageSrc);
try {
// Check if the file exists before attempting to delete it
if (fs.existsSync(previousImagePath)) {
fs.unlinkSync(previousImagePath);
}
} catch (error) {
console.error('Error deleting previous image:', error);
}
}
// Resize the uploaded image
const resizedImagePath = `uploads/resized_${req.file.filename}`;
await resizeImage(req.file.path, resizedImagePath);
// Delete the original image file after resizing
try {
fs.unlinkSync(req.file.path);
} catch (error) {
console.error('Error deleting the original image:', error);
}
// Set imageSrc to the path of the resized file
updatedCategoryData.imageSrc = `/${resizedImagePath}`;
}
// Update the category with the new data
const updatedCategory = await categoryModel.findByIdAndUpdate(
req.params.id,
updatedCategoryData,
{ new: true }
);
res.status(200).json(updatedCategory);
});
/*
desc - delete category
route - DELETE - /api/category/:id
access - public
*/
const deleteCategory = asyncHandler(async (req, res) => {
// Find the category by ID
const category = await categoryModel.findById(req.params.id);
if (!category) {
res.status(404);
throw new Error("Category not found to delete");
}
// Delete images associated with each item in the category
category.totalItems.forEach(item => {
if (item.imageSrc) {
const imagePath = path.join(__dirname, '..', item.imageSrc);
try {
// Check if the file exists before attempting to delete it
if (fs.existsSync(imagePath)) {
fs.unlinkSync(imagePath);
} else {
console.log(`Image file not found: ${imagePath}`);
}
} catch (error) {
console.error('Error deleting item image:', error);
}
}
});
// Also delete the category image if it exists
if (category.imageSrc) {
const categoryImagePath = path.join(__dirname, '..', category.imageSrc);
try {
if (fs.existsSync(categoryImagePath)) {
fs.unlinkSync(categoryImagePath);
} else {
console.log(`Category image file not found: ${categoryImagePath}`);
}
} catch (error) {
console.error('Error deleting category image:', error);
}
}
// Delete the category
const deletedCategory = await categoryModel.findByIdAndDelete(req.params.id);
if (!deletedCategory) {
res.status(404);
throw new Error("Category not found to delete");
}
res.status(200).json(deletedCategory);
});
/*
desc - add item to category
route - POST - /api/categories/:categoryId/items ( http://localhost:5001/api/categories/:categoryId/items )
access - public
*/
const addItemToCategory = asyncHandler(async (req, res) => {
const newItem = req.body;
const categoryId = req.params.id;
// Check if the category exists
const category = await categoryModel.findById(categoryId);
if (!category) {
return res.status(404).json({ message: 'Category not found' });
}
// Handle image upload and resizing
if (req.file) {
const resizedImagePath = `uploads/resized_${req.file.filename}`;
await resizeImage(req.file.path, resizedImagePath);
// Delete the original image file
try {
fs.unlinkSync(req.file.path);
} catch (error) {
console.error('Error deleting the original image:', error);
}
newItem.imageSrc = `/${resizedImagePath}`;
}
// Create a new item instance with the provided data
const item = new itemModel(newItem);
// Add the new item to the category's totalItems array
category.totalItems.push(item);
// Save the category with the new item added
await category.save();
res.status(201).json(category);
});
const editItemInCategory = asyncHandler(async (req, res) => {
const updatedItem = req.body;
const categoryId = req.params.categoryId;
const itemId = req.params.itemId;
// Check if the category exists
const category = await categoryModel.findById(categoryId);
if (!category) {
return res.status(404).json({ message: 'Category not found' });
}
// Find the index of the item in the totalItems array
const index = category.totalItems.findIndex(item => item?._id.toString() === itemId);
if (index === -1) {
return res.status(404).json({ message: 'Item not found' });
}
// Handle image upload and resizing
if (req.file) {
// Delete previous file if it exists
const previousItem = category.totalItems[index];
if (previousItem && previousItem.imageSrc) {
const previousImagePath = path.join(__dirname, '..', previousItem.imageSrc);
try {
// Check if the file exists before attempting to delete it
if (fs.existsSync(previousImagePath)) {
fs.unlinkSync(previousImagePath);
}
} catch (error) {
console.error('Error deleting previous image:', error);
}
}
// Resize the uploaded image
const resizedImagePath = `uploads/resized_${req.file.filename}`;
await resizeImage(req.file.path, resizedImagePath);
// Delete the original image file after resizing
try {
fs.unlinkSync(req.file.path);
} catch (error) {
console.error('Error deleting the original image:', error);
}
updatedItem.imageSrc = `/${resizedImagePath}`;
}
// Update the item at the found index with the new data
category.totalItems[index] = { ...category.totalItems[index]._doc, ...updatedItem, _id: itemId };
// Save the category with the updated item
await category.save();
res.json(category);
});
const deleteItemInCategory = asyncHandler(async (req, res) => {
const categoryId = req.params.categoryId;
const itemId = req.params.itemId;
// Check if the category exists
const category = await categoryModel.findById(categoryId);
if (!category) {
return res.status(404).json({ message: 'Category not found' });
}
// Find the index of the item in the totalItems array
const delIndex = category.totalItems.findIndex(item => item._id.toString() === itemId);
if (delIndex === -1) {
return res.status(404).json({ message: 'Item not found' });
}
// Get the item to be deleted
const itemToDelete = category.totalItems[delIndex];
// Delete the image file if it exists
if (itemToDelete.imageSrc) {
const imagePath = path.join(__dirname, '..', itemToDelete.imageSrc);
try {
// Check if the file exists before attempting to delete it
if (fs.existsSync(imagePath)) {
fs.unlinkSync(imagePath);
}
} catch (error) {
console.error('Error deleting item image:', error);
}
}
// Remove the item from the totalItems array
category.totalItems.splice(delIndex, 1);
// Save the category
await category.save();
res.json(category);
});
module.exports = { getCategory, getAllCategories, createCategory, deleteCategory, editCategory, addItemToCategory, editItemInCategory, deleteItemInCategory } |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Open Maya Utilities.
"""
# System global imports
# mca python imports
import maya.api.OpenMaya as om2
import pymel.core as pm
# mca python imports
def pynode_to_om2_mobject_mdag_path(node):
"""
Convert a pynode into a MDagPath and MObject
:param PyNode node: The PyNode to be converted.
:return: The om equivalent objects.
:rtype MDagPath, MObject:
"""
if isinstance(node, pm.nt.DagNode):
sel = om2.MSelectionList()
sel.add(node.longName())
return sel.getComponent(0)
else:
print('Node type is not a DagNode. {0}, {1}'.format(node, type(node)))
return None, None
def get_closest_joint_to_vertex(vertex, mesh_name, joint_list):
"""
Gets the closest joint to a provided vertex index.
:param int vertex: Vertex index
:param str mesh_name: Name of the mesh
:param list(str) joint_list: List of names of joints to be considered
:return: The name of the closest joint
:rtype: str
"""
closest_joint = None
closest_distance = float('inf')
# Create an empty MSelectionList. This is a wrapper for a list of MObjects (base class for nodes)
selection_list = om2.MSelectionList()
# Add specified node to MSelectionList. You can pass add() MObject or short/long names of nodes
# and it will create an MObject for it if found
selection_list.add(mesh_name)
# getDagPath works by providing it an index to the list above then a reference to the DAG path is
# stored along with the MObject for the node
dag_path = selection_list.getDagPath(0)
# Create MFnMesh to work with mesh
mfn_mesh = om2.MFnMesh(dag_path)
# getPoint uses the vertex index and creates and stores an MPoint which we can get the coordinates
# of the vertex off later
point = mfn_mesh.getPoint(vertex, space=om2.MSpace.kWorld)
for jnt in joint_list:
# Make sure selection list is empty
selection_list.clear()
# Add the joint object to the selection list
selection_list.add(jnt)
# Create MDagPath for joint
dag_path = selection_list.getDagPath(0)
# Create MFnTransform to get translation from joint
jnt_fn = om2.MFnTransform(dag_path)
jnt_pos = jnt_fn.translation(om2.MSpace.kWorld)
# Create MVector obj at vertex position
vertex_pos = om2.MVector(point.x, point.y, point.z)
# Subtract joint and vertex vector components to get distance vector
distance_vector = vertex_pos - jnt_pos
# Use MVector length to get distance
distance = distance_vector.length()
# Check distance to see if closest
if distance < closest_distance:
closest_distance = distance
closest_joint = jnt
return closest_joint
def get_adjacent_vertices(vertex):
"""
Gets adjacent vertex indices for specified vertex index
:param str vertex: Vertex return adjacent vertex indices for
:return: Adjacent vertex indices
:rtype: list(int)
"""
# Create an MSelectionList and add the vertex to it
selection_list = om2.MSelectionList()
selection_list.add(vertex)
# Create an MFnMesh object from the selected mesh and get the DAG path and MObject for the component
dag_path, component = selection_list.getComponent(0)
# Get the adjacent vertices using MItMeshVertex. This is an iterator for vertices so if we don't provide
# it a component it will go over all vertices on specified surface
vertex_iter = om2.MItMeshVertex(dag_path, component)
adjacent_vertices = []
while not vertex_iter.isDone():
# Get indices of vertices around our vertex
connected_vertices = vertex_iter.getConnectedVertices()
adjacent_vertices.extend(connected_vertices)
vertex_iter.next()
return adjacent_vertices |
import { Component, OnInit } from '@angular/core';
import { CartService } from 'src/app/services/cart.service';
import { Carrito, CarritoItem } from 'src/models/carrito.model';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit{
carrito: Carrito = {productos:[
{
id: 1,
productoimg: 'https://via.placeholder.com/150',
nombre: 'Nike AirForce',
precio: 80000,
cantidad: 1,
},
{
id: 2,
productoimg: 'https://via.placeholder.com/150',
nombre: 'Jordan Dunk High',
precio: 120000,
cantidad: 2,
}
]};
datosEntrada: Array<CarritoItem> = [];
displayColumnas:Array<string> = [
'productoimg',
'nombre',
'precio',
'cantidad',
'total',
'accion'
]
constructor(private cartService: CartService){}
ngOnInit():void{
this.datosEntrada = this.carrito.productos;
this.cartService.carrito.subscribe((_carrito:Carrito) => {
this.carrito = _carrito;
this.datosEntrada = this.carrito.productos;
})
}
getTotal(productos: Array<CarritoItem>):number{
return this.cartService.getTotal(productos);
}
limpiarCarrito():void{
this.cartService.limpiarCarrito();
}
eliminarProducto(elemento : CarritoItem):void{
this.cartService.eliminarDelCarrito(elemento);
}
decrementarCarrito(producto: CarritoItem):void{
this.cartService.decrementarCarrito(producto);
}
agregarAlCarrito(producto: CarritoItem):void{
this.cartService.agregarAlCarrito(producto);
}
} |
<mat-drawer-container class="sidenav-container" autosize>
<mat-drawer #drawer class="admin-sidenav" [mode]="_mode" [opened]="_opened">
<div class="menu-items-wrapper" [ngClass]="{ 'collapsed' : collapsed }">
<div class="sidenav-logo">
<div class="sidenav-toggle">
<button type="button" (click)="collapsed = !collapsed" data-test-id="btnToggleSidenav">
<img [src]="getUrl()" alt="">
</button>
</div>
<img src="assets/images/Intelehealth-logo-white.png" alt="" width="100%" *ngIf="!collapsed">
<img src="assets/images/Intelehealth-logo-white2.png" alt="" width="100%" *ngIf="collapsed">
</div>
<ul class="admin-nav">
<li class="nav-item" *ngxPermissionsExcept="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR', 'ORGANIZATIONAL: NURSE']" (click)="toggleSidebar()" data-test-id="listItemDashboard">
<a class="nav-item-link" routerLink="/dashboard" routerLinkActive="active" data-test-id="linkDashboard">
<img src="assets/svgs/menu-home.svg" alt="">
<span>{{'Dashboard' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsExcept="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR', 'ORGANIZATIONAL: NURSE']" (click)="toggleSidebar()" data-test-id="listItemMessages">
<a class="nav-item-link" routerLink="/messages" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" data-test-id="linkMessages">
<img src="assets/svgs/menu-message.svg" alt="">
<span>{{'Messages' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsExcept="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR', 'ORGANIZATIONAL: NURSE']" (click)="toggleSidebar()" data-test-id="listItemAppointments">
<a class="nav-item-link" routerLink="/appointments" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" data-test-id="linkAppointments">
<img src="assets/svgs/menu-video.svg" alt="">
<span>{{'Appointment' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsExcept="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR', 'ORGANIZATIONAL: NURSE']" (click)="toggleSidebar()" data-test-id="listItemCalendar">
<a class="nav-item-link" routerLink="/calendar" routerLinkActive="active" data-test-id="linkCalendar">
<img src="assets/svgs/menu-calendar.svg" alt="">
<span>{{'Calendar' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsExcept="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR', 'ORGANIZATIONAL: NURSE']" (click)="toggleSidebar()" data-test-id="listItemPrescription">
<a class="nav-item-link" routerLink="/prescription" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" data-test-id="linkPrescription">
<img src="assets/svgs/menu-treatment.svg" alt="">
<span>{{'Prescription' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsOnly="['ORGANIZATIONAL: NURSE']" (click)="toggleSidebar()" data-test-id="listItemProfile">
<a class="nav-item-link" routerLink="/dashboard/hw-profile" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" data-test-id="linkProfile">
<img src="assets/svgs/menu-home.svg" alt="">
<span>{{'My Profile'| translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsExcept="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR']" (click)="toggleSidebar()" data-test-id="listItemHelp">
<a class="nav-item-link" routerLink="/help" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" data-test-id="linkHelp">
<img src="assets/svgs/menu-info.svg" alt="">
<span>{{'Help & Support' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsOnly="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR']" (click)="toggleSidebar()" data-test-id="listItemAyu">
<a class="nav-item-link" routerLink="/admin" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" data-test-id="linkAyu">
<img src="assets/svgs/warning.svg" alt="">
<span>{{'Ayu'| translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsOnly="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR']" (click)="toggleSidebar()" data-test-id="listItemSupport">
<a class="nav-item-link" routerLink="/admin/support" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" data-test-id="linkSupport">
<img src="assets/svgs/menu-info.svg" alt="">
<span>{{'Support' | translate}} <div class="dot" *ngIf="adminUnread">{{adminUnread}}</div> </span>
</a>
</li>
<li class="nav-item" *ngxPermissionsOnly="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR']" (click)="toggleSidebar()" data-test-id="listItemSystem">
<a class="nav-item-link" href="{{ baseURLLegacy }}/admin/index.htm" target="_blank" data-test-id="linkSystem">
<img src="assets/svgs/user-settings.svg" alt="">
<span>{{'System Admin' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsOnly="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR']" (click)="toggleSidebar()" data-test-id="listItemUser">
<a class="nav-item-link" href="{{ baseURLLegacy }}/admin/users/users.list" target="_blank" data-test-id="linkUser">
<img src="assets/svgs/add-user.svg" alt="">
<span>{{'User Creation' | translate}}</span>
</a>
</li>
<li class="nav-item" *ngxPermissionsOnly="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR']" (click)="toggleSidebar()" data-test-id="listItemReport">
<a class="nav-item-link" href="{{ baseURLLegacy }}/reportingui/reportsapp/home.page" target="_blank" data-test-id="linkReport">
<img src="assets/svgs/report.svg" alt="">
<span>{{'Report' | translate}}</span>
</a>
</li>
<li class="nav-item" (click)="toggleSidebar()" data-test-id="listItemLogout">
<mat-divider class="mb-2"></mat-divider>
<a class="nav-item-link" href="javascript:void(0)" (click)="logout()" data-test-id="linkLogout">
<img src="assets/svgs/power.svg" alt="">
<span>{{'Log-out' | translate}}</span>
</a>
</li>
</ul>
</div>
</mat-drawer>
<div class="admin-sidenav-content">
<div class="header-main">
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="javascript:void(0)">
<button class="mr-2" mat-icon-button (click)="drawer.toggle()" *ngIf="isMobile" data-test-id="btnToggleDrawer">
<mat-icon>menu</mat-icon>
</button>
<div class="header-title d-flex justify-content-between align-items-center" *ngIf="header?.title">
<ng-container *ngIf="header.title != 'Dashboard'">
<img src="{{header?.imgUrl}}" alt="" width="44px">
<h6 class="mb-0 ml-2">{{header?.title | translate}}</h6>
<mat-icon *ngIf="header?.info" aria-hidden="false" aria-label="help icon">help_outline</mat-icon>
</ng-container>
<ng-container *ngIf="header.title == 'Dashboard'">
<form [formGroup]="searchForm">
<div class="input-group">
<input type="text" class="form-control" formControlName="keyword" placeholder="{{'Search patient'| translate}}" aria-label="Username" aria-describedby="basic-addon1" (keyup.enter)="search()" data-test-id="etSearchPatient">
<div class="input-group-append">
<span class="input-group-text click" id="basic-addon1" (click)="search()" data-test-id="spanSearchPatient">
<img src="assets/svgs/search-icon.svg" alt="" width="20px" height="20px">
</span>
</div>
</div>
</form>
</ng-container>
</div>
<nav aria-label="breadcrumb" *ngIf="!header?.title">
<ol class="breadcrumb">
<ng-container *ngFor="let breadcrumb of breadcrumbs;let x=index; let last=last;">
<li class="breadcrumb-item" *ngIf="!last">
<a [routerLink]="breadcrumb.url" data-test-id="{{'breadcrumb'+x}}">{{ breadcrumb.label | translate}}</a>
</li>
<li class="breadcrumb-item" aria-current="page" *ngIf="last">
{{ breadcrumb.label | translate }}
</li>
</ng-container>
</ol>
</nav>
</a>
<button class="navbar-toggler" type="button" mat-icon-button data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" data-test-id="btnToggleNavbar">
<mat-icon>keyboard_arrow_down</mat-icon>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<div class="d-flex align-items-center justify-content-end">
<button mat-button class="notification-button mr-1" (click)="openHelpMenu()" *ngxPermissionsExcept="['ORGANIZATIONAL: SYSTEM ADMINISTRATOR']" data-test-id="btnHelpMenu">
<mat-icon>help_outline</mat-icon>
</button>
<button mat-button class="notification-button mr-3" (click)="toggleNotification()" data-test-id="btnNotification">
<mat-icon *ngIf="notificationEnabled">notifications_none</mat-icon>
<mat-icon *ngIf="!notificationEnabled">notifications_off</mat-icon>
</button>
<div class="user-info-wrap mr-3" routerLink="/dashboard/profile" data-test-id="navProfile">
<img class="user-img mr-3" src="{{profilePic}}" (error) ="onImgError($event)" alt="">
<h6 class="user-title mb-0">{{'Hello' |translate}}, {{ (user)? user?.person?.display : ('User'|translate) }} <img src="assets/images/Waving-Hand-Emoji.png" alt="" height="100%"></h6>
</div>
<button mat-icon-button [matMenuTriggerFor]="beforeMenu" aria-label="Example icon button with a vertical three dot icon" data-test-id="btnProfileDropdown">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #beforeMenu="matMenu" xPosition="before" class="profile-dropdown">
<button mat-menu-item (click)="changePassword()" data-test-id="btnChangePasswordMain">{{'Change Password' | translate}}</button>
<button mat-menu-item (click)="selectLanguage()" data-test-id="btnSelectLanguageMain">{{'Change Language' | translate}}</button>
<button mat-menu-item routerLink="/dashboard/profile" data-test-id="btnProfileMain">{{'Profile' | translate}}</button>
</mat-menu>
</div>
</li>
</ul>
</div>
</nav>
</div>
<div class="main-container">
<router-outlet></router-outlet>
<div class="help-menu-container d-flex flex-column" *ngIf="routeUrl.includes('/help') && !dialogRef && !dialogRef2">
<div class="menu-item">
<span>{{'Raise a Ticket'| translate}}</span>
<button class="help-btn-2 mr-1" type="button" (click)="openRaiseTicketModal()" data-test-id="btnToggleTicket">
<img src="assets/svgs/note-green.svg" alt="" width="45px" height="45px">
</button>
</div>
<div class="menu-item">
<span>{{'Support Chat'| translate}}</span>
<button class="help-btn-2" type="button" (click)="openHelpMenu()" data-test-id="btnToggleHelpMenu">
<img src="assets/svgs/send_circle_icon.svg" alt="" width="45px" height="45px">
</button>
</div>
</div>
</div>
</div>
</mat-drawer-container> |
@extends('dashboard.layouts.main')
@section('container')
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Update Post</h1>
</div>
<div class="row">
<div class="col-lg-8">
<form action="/dashboard/posts/{{ $post->slug }}" method="post" class="mb-5" enctype="multipart/form-data" >
@method('put')
@csrf
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input value="{{ old('title',$post->title) }}" required autofocus type="text" class="form-control @error('title') is-invalid @enderror" id="title" name="title">
@error('title')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="mb-3">
<label for="slug" class="form-label">Slug</label>
<input id="slug" name="slug" value="{{ old('slug',$post->slug) }}" required type="text" class="form-control @error('slug') is-invalid @enderror">
@error('slug')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="mb-3">
<label for="category" class="form-label">Category</label>
<select class="form-select" name="category_id">
@foreach ($categories as $category)
@if ( old('category_id',$post->category_id) == $category->id)
<option value="{{ $category->id }}" selected>{{ $category->name }}</option>
@else
<option value="{{ $category->id }}">{{ $category->name }}</option>
@endif
@endforeach
</select>
</div>
<div class="mb-3">
<label for="image" class="form-label">Post Image</label>
<input type="hidden" name="oldImage" value="{{ $post->image }}">
@if ($post->image)
<img src="{{ asset('storage/'.$post->image) }}" class="img-preview d-block img-fluid mb-3 col-sm-5">
@else
<img class="img-preview img-fluid mb-3 col-sm-5">
@endif
<input class="form-control @error('image') is-invalid @enderror" type="file" id="image" name="image" onchange="previewImage()">
@error('slug')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="mb-3">
<label for="body" class="form-label">Body</label>
@error('body')
<p class="text-danger">{{ $message }}</p>
@enderror
<input id="body" type="hidden" name="body" value="{{ old('body',$post->body) }}">
<trix-editor input="body"></trix-editor>
</div>
<button type="submit" class="btn btn-primary">Update post</button>
</form>
</div>
</div>
<script>
const title= document.querySelector('#title');
const slug= document.querySelector('#slug');
title.addEventListener('change',function(){
fetch('/dashboard/posts/checkSlug?title='+title.value)
.then(response=> response.json())
.then(data=>slug.value = data.slug)
});
// disable file accept
document.addEventListener('trix-file-accept',function(e){
e.preventDefault();
});
const previewImage=()=>{
const image = document.querySelector('#image');
const imgPreview = document.querySelector('.img-preview');
imgPreview.style.display ='block';
const oFReader= new FileReader();
oFReader.readAsDataURL(image.files[0]);
oFReader.onload = oFRevent =>{
imgPreview.src = oFRevent.target.result;
}
}
</script>
@endsection |
import Image from 'next/image'
import React from 'react'
import { MdEmail } from 'react-icons/md'
import LinkItem from '../MobileMockup/components/LinkItem'
import { platforms } from '../LinkList/LinkList'
import defaultPP from "../../../public/default_pp.png"
const PreviewList = ({userInformation}) => {
return (
<div style={{borderColor:userInformation.profileColor}} className='w-full md:w-2/3 bg-white rounded-lg flex flex-col gap-4 items-center p-6 md:p-8 border-2 '>
<Image className='rounded-full w-32 h-32' alt={userInformation.username} width={360} height={360} src={userInformation.profilePicture ? userInformation.profilePicture : defaultPP} />
<div className='w-full flex items-center justify-center font-bold text-xl'>
{userInformation.firstName}
{" "}
{userInformation.lastName}
</div>
{!userInformation.isHiddenEmail &&
<div className='w-full flex items-center justify-center gap-1 font-bold text-sm'>
<MdEmail />
{userInformation.email}
</div>
}
<ul className=' flex flex-col items-center gap-[20px] w-full px-4 md:px-8'>
{userInformation.links.map((item, index) => (
<LinkItem key={index} platforms={platforms} item={item} />
))}
</ul>
</div>
)
}
export default PreviewList |
# Workflow #1
This workflow example demonstrates how to use DVCLI to perform the following operations:
* Create a new collection in a Dataverse instance
* Create a new dataset in the collection
* Upload a file to the dataset
* Publish the collection and dataset
## Prerequisites
For these commands to work, you need to supply the following environment variables:
* `DVCLI_URL` - The URL of the Dataverse instance
* `DVCLI_TOKEN` - The API token for the Dataverse instance
```bash
export DVCLI_URL="http://localhost:8080"
export DVCLI_TOKEN="<API_TOKEN>"
```
### Files
* `collection.json` - Metadata file to create a collection
* `dataset.json` - Metadata file to create a dataset
* `data.csv` - Sample data file
* `file.json` - Metadata file to create a file
## Steps
### 1. Create a new collection in Dataverse instance
This command creates a new collection in the Dataverse instance with the metadata provided in the `collection.json` file. As demonstrated below, you can also save the JSON output to a file for further processing. This will only save the JSON response and strip all the other fancy messages.
```bash
# Print the JSON output to the terminal
dvcli collection create --parent Root --body collection.json
# You can also save the JSON output
# to a file (which is useful for further processing)
dvcli collection create --parent Root --body collection.json >> collection_output.json
```
```bash
🎉 Success! - Received the following response:
{
"affiliation": "University of Dataverse",
"alias": "dvcli",
"creationDate": "2024-05-17T15:38:28Z",
"dataverseContacts": [
{
"contactEmail": "john@doe.com",
"displayOrder": 0
}
],
"dataverseType": "TEACHING_COURSES",
"description": "This dataverse was created by DVCLI",
"id": 318,
"isReleased": false,
"ownerId": 1,
"permissionRoot": true
}
```
### 2. Create a new dataset in the collection
This command creates a new dataset in the collection `dvcli` with the metadata provided in the `dataset.json` file.
```bash
dvcli dataset create --collection dvcli --body dataset.json >> dataset_output.json
```
```bash
🎉 Success! - Received the following response:
{
"id": 319,
"persistentId": "doi:10.5072/FK2/YNRRF6"
}
```
### 3. Upload a file to the dataset
This command uploads the file `data.csv` to the dataset created in the previous step. Keep in mind, that re-running this command will not overwrite the existing file, but will attach a `-[digit]` to the filename.
```bash
# Use jq to extract the persistent ID from the JSON output dataset_output.json
# and save it to a variable
persistent_id=$(jq -r '.persistentId' dataset_output.json)
# Upload the file to the dataset
dvcli dataset upload files/data.csv --id $persistent_id --body file.json
```
```bash
🎉 Success! - Received the following response:
{
"files": [
{
"categories": [
"Data"
],
"datasetVersionId": 79,
"description": "My description.",
"label": "data.csv",
"restricted": false,
"version": 1
}
]
}
```
### 4. Publish the collection and dataset
These commands publish the collection and dataset, making them publicly accessible.
```bash
dvcli collection publish dvcli
dvcli dataset publish --version major $persistent_id
```
```bash
🎉 Success! - Received the following response:
{
"affiliation": "University of Dataverse",
"alias": "dvcli",
"creationDate": "2024-05-17T15:38:28Z",
"dataverseContacts": [
{
"contactEmail": "john@doe.com",
"displayOrder": 0
}
],
"dataverseType": "TEACHING_COURSES",
"description": "This dataverse was created by DVCLI",
"id": 318,
"isReleased": true,
"ownerId": 1,
"permissionRoot": true
}
🎉 Success! - Received the following response:
{
"authority": "10.5072",
"id": 319,
"identifier": "FK2/YNRRF6",
"persistentUrl": "https://doi.org/10.5072/FK2/YNRRF6",
"protocol": "doi",
"publisher": "Root",
"storageIdentifier": "local://10.5072/FK2/YNRRF6"
}
``` |
// ```js
// // For loop structure
// for(initialization, condition, increment/decrement){
// // code goes here
// }
// ```
// ### while loop
// ```js
// let i = 0
// while (i <= 5) {
// console.log(i)
// i++
// }
// ```js
// let i = 0
// do {
// console.log(i)
// i++
// } while (i <= 5)
// ### for of loop
// We use for of loop for arrays. It is very hand way to iterate through an array if we are not interested in the index of each element in the array.
// ```js
// for (const element of arr) {
// // code goes here
// }
// ``` |
package dev.imrob.carrental.service;
import dev.imrob.carrental.dto.ClienteDTO;
import dev.imrob.carrental.dto.mapper.ClienteMapper;
import dev.imrob.carrental.entity.Cliente;
import dev.imrob.carrental.exceptions.EntityNotFoundException;
import dev.imrob.carrental.repository.ClienteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class ClienteService {
@Autowired
private ClienteRepository repository;
@Autowired
private ClienteMapper mapper;
public ClienteDTO findById(Long id) {
Cliente cliente = repository.findById(id).orElseThrow(
() -> new EntityNotFoundException("Cliente com id " + id + " não foi encontrado"));
return mapper.toDto(cliente);
}
public ClienteDTO findByCpf(String cpf) {
Optional<Cliente> clienteOptional = repository.findByCpf(cpf);
if (clienteOptional.isEmpty()) {
throw new EntityNotFoundException("Cliente com cpf " + cpf + " não foi encontrado");
}
return mapper.toDto(clienteOptional.get());
}
public List<ClienteDTO> findAll() {
List<Cliente> clientes = repository.findAll();
return mapper.toDto(clientes);
}
public Long save(ClienteDTO clienteDTO) {
Cliente cliente = mapper.toEntity(clienteDTO);
cliente = repository.save(cliente);
return cliente.getId();
}
public void update(ClienteDTO clienteDTO) {
Optional<Cliente> clienteOptional = repository.findById(clienteDTO.id());
if (clienteOptional.isEmpty()) {
throw new EntityNotFoundException("Cliente com id " + clienteDTO.id() + " não foi encontrado");
}
Cliente cliente = mapper.toEntity(clienteDTO);
repository.save(cliente);
}
public void delete(Long id) {
Cliente cliente = repository.findById(id).orElseThrow(
() -> new EntityNotFoundException("Cliente com id "+ id +" não foi encontrado"));
repository.delete(cliente);
}
} |
package edu.kh.col.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.kh.col.model.vo.Member;
public class MapService {
// Map : Key와 Value 한 쌍이 데이터가 되어 이를 모아둔 객체
// - key를 모아두면 Set의 특징(중복X)
// - Value를 모아두면 List의 특징(중복O)
public void ex1() {
// HashMap<K,V> : Map의 자식 클래스 중 가장 대표되는 Map
Map<Integer, String>map = new HashMap<Integer,String>();
// Map.put(Integer Key, String Value) : 추가 (put:놓다)
map.put(1, "홍길동");
map.put(2, "고길동");
map.put(3, "이길동");
map.put(4, "댕길동");
map.put(5, "냥길동");
map.put(6, "멍길동");
// Key 중복
map.put(1, "홍홍홍"); // Key값에 중복을 허용하지않음 , 대신 Value를 덮어쓴다
// Value 중복
map.put(7, "최길동"); // 노상관
System.out.println(map); // map.toString() 오버라이딩 되어있음.
}
public void ex2() {
// Map 사용 예제
// VO ( 값 저장용 객체 ) 는 특정 데이터 묶음의 재사용이 많은 경우 주로 사용
// => 재사용이 적은 VO는 오히려 코드 낭비
// => Map을 이용해서 VO와 비슷한 코드를 작성할 수 있다.
// 1) VO버전
Member mem = new Member();
// 값 세팅
mem.setId("user1");
mem.setPw("pass1");
mem.setAge(30);
// 값 출력
System.out.println(mem.getId());
System.out.println(mem.getPw());
System.out.println(mem.getAge());
// 2) Map버전
Map<String, Object> map = new HashMap<String, Object>();
// value가 object 타입 == 어떤 객체든 Value에 들어올 수 있다.
// 값 세팅
map.put("id", "user02");
map.put("pw", "pass02");
map.put("age", 25); // int => Integer(AutoBoxing)
// 값 출력
System.out.println(map.get("id").toString());
// String java.lang.object.toString() => 정적바인딩
// 실행중 확인해보니 String 자식 객체 => 자식
System.out.println(map.get("pw"));
System.out.println(map.get("age"));
// ** Map에 저장된 데이터 순차적으로 접근하는 방법 **
// Map에서 Key만 모아두면 Set의 특징
// => 이를 활용할 수 있도록 Map에서 KeySet() 메서드 제공
// => Key만 모아서 Set으로 반환
Set<String> set = map.keySet(); // id, pw, age 가 저장된 Set을 반환
System.out.println(set);
//향상된 for문
for( String key : set ) {
System.out.println(map.get(key));
}
//map에 저장된 데이터가 많을 때,
//어떤 key가 있는지 불분명 할 때,
//map에 저장된 모든 데이터에 접근 해야할 때
//KeySet() + 향상된 for문 코드를 사용한다.
}
public void ex3() {
// List + Map
// user 10명, user의 id 쭉 뽑는다.
// k : v
// "id : "user1"
// "id : "user1"
// "id : "user1"
// "id : "user1"
/// .....
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i <10; i++) {
//Map생성
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", "user0"+i);
map.put("pw", "pass0"+i);
// Map을 List에 추가
list.add(map);
}
// for문 종료 시점에 List에는 10개의 Map 객체가 추가되어 있다.
// * List에 저장된 Map 에서 key가 "id"인 경우의 value를 모두 출력 *
// 향상된 for문
System.out.println(list);
for ( Map<String, Object> temp : list) {
System.out.println(temp.get("id"));
}
// 구조 잘 생각해보기 : "id" 키의 value user0+i 를 가져옴
}
} |
<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import InputText from "primevue/inputtext";
import Divider from "primevue/divider";
import { useToast } from "primevue/usetoast";
import useCookies from "../../../cloudconLibrary/utilities/useCookies";
import { cookieKeys } from "../../../cloudconLibrary/utilities/useConstants";
import { useRouter } from "vue-router";
import ProgressSpinner from "primevue/progressspinner";
import Button from "primevue/button";
import Dropdown from "primevue/dropdown";
import MenuSidebar from "@/components/sidebar/MenuSidebar.vue";
import plantController from "../../controllers/plantController";
import peopleController from "../../controllers/peopleController";
import jobController from "../../controllers/jobController";
import companyController from "../../controllers/companyController";
import commonController from "../../controllers/commonController";
import {
IRequestPlantCreate,
IRequestPlantUpdate,
} from "../../../cloudconLibrary/api/apiInterfaces";
import InputNumber from "primevue/inputnumber";
import Calendar from "primevue/calendar";
export const AddPlant = /*#__PURE__*/ defineComponent({
name: "AddWorkOrder",
components: {
MenuSidebar,
InputText,
Divider,
ProgressSpinner,
Button,
InputNumber,
Calendar,
Dropdown,
},
setup() {
const controllers = plantController();
const controllers2 = peopleController();
const controllers3 = jobController();
const controllers4 = companyController();
const controllers5 = commonController();
const name = ref();
const street = ref();
const custom = ref("");
const geo = ref("");
const maintenanceUsage = ref();
const manufacturer = ref("");
const model = ref("");
const purchaseDate = ref();
const purchasePrice = ref();
const usage = ref();
const warrantyDate = ref();
const serialNumber = ref("");
const toast = useToast();
const is_loading = ref(true);
const loading = ref(false);
const router = useRouter();
const token = useCookies.get(cookieKeys.AUTH0_ACCESS_TOKEN);
const user_email = String(useCookies.get(cookieKeys.EMAIL_ADDRESS));
const ownerid = ref();
const selectcontact = ref();
const contactSelect: any = ref([]);
const selectcompany = ref();
const companySelect: any = ref([]);
const selectjob = ref();
const jobSelect: any = ref([]);
function add() {
let is_error = false;
if (name.value == "" || name.value == null) {
toast.add({
severity: "error",
summary: "Error Message",
detail: "Name is Required",
life: 10000,
});
if (is_error == false) {
is_error = true;
}
}
if (is_error == false) {
if (token) {
if (!router.currentRoute.value.params.id) {
loading.value = true;
const _requetdata: IRequestPlantCreate = {
name: name.value || null,
address: street.value || null,
custom: null,
geo: geo.value || null,
maintenanceUsage: Number(maintenanceUsage.value) || null,
manufacturer: manufacturer.value || null,
model: model.value || null,
purchaseDate: new Date(purchaseDate.value).getTime() || null,
purchasePrice: purchasePrice.value || null,
serialNumber: serialNumber.value || null,
usage: Number(usage.value) || null,
warrantyDate: new Date(warrantyDate.value).getTime() || null,
companyId: selectcompany.value ? selectcompany.value["id"] : null,
contactId: selectcontact.value ? selectcontact.value["id"] : null,
jobId: selectjob.value ? selectjob.value["id"] : null,
ownerIds: ownerid.value,
};
controllers
.addplant(_requetdata)
.then(() => {
toast.add({
severity: "success",
summary: "Success Message",
detail: "Plant Add Successfully",
life: 10000,
});
loading.value = false;
router.push({
path: "/plant",
});
})
.catch((error: any) => {
if (error.message.AlreadyExists) {
toast.add({
severity: "error",
summary: "Error Message",
detail: error.message.AlreadyExists[0],
life: 10000,
});
}
if (error.message.InvalidField) {
toast.add({
severity: "error",
summary: "Error Message",
detail: error.message.InvalidField[0],
life: 10000,
});
}
if (error.message.CanNotFind) {
toast.add({
severity: "error",
summary: "Error Message",
detail: error.message.CanNotFind[0],
life: 10000,
});
}
loading.value = false;
});
} else {
loading.value = true;
const _requetdata: IRequestPlantUpdate = {
id: Number(router.currentRoute.value.params.id),
name: name.value || null,
address: street.value || null,
custom: null,
geo: geo.value || null,
maintenanceUsage: Number(maintenanceUsage.value) || null,
manufacturer: manufacturer.value || null,
model: model.value || null,
purchaseDate: new Date(purchaseDate.value).getTime() || null,
purchasePrice: purchasePrice.value || null,
serialNumber: serialNumber.value || null,
usage: Number(usage.value) || null,
warrantyDate: new Date(warrantyDate.value).getTime() || null,
companyId: selectcompany.value ? selectcompany.value["id"] : null,
contactId: selectcontact.value ? selectcontact.value["id"] : null,
jobId: selectjob.value ? selectjob.value["id"] : null,
ownerIds: ownerid.value,
};
controllers
.updateplant(_requetdata)
.then(() => {
toast.add({
severity: "success",
summary: "Success Message",
detail: "Plant Update Successfully",
life: 10000,
});
loading.value = false;
router.push({
path: "/plant",
});
})
.catch((error: any) => {
if (error.message.AlreadyExists) {
toast.add({
severity: "error",
summary: "Error Message",
detail: error.message.AlreadyExists[0],
life: 10000,
});
}
if (error.message.InvalidField) {
toast.add({
severity: "error",
summary: "Error Message",
detail: error.message.InvalidField[0],
life: 10000,
});
}
if (error.message.CanNotFind) {
toast.add({
severity: "error",
summary: "Error Message",
detail: error.message.CanNotFind[0],
life: 10000,
});
}
loading.value = false;
});
}
} else {
router.push({
path: "/login",
});
}
} else {
loading.value = false;
}
}
function cancel() {
router.push({
path: "/plant",
});
}
onMounted(async () => {
if (router.currentRoute.value.params.id) {
if (token) {
is_loading.value = true;
const data = JSON.parse(
await controllers.getplantbyid(
Number(router.currentRoute.value.params.id)
)
);
name.value = data.name;
street.value = data.address;
custom.value = data.custom;
geo.value = data.geo;
maintenanceUsage.value = data.maintenanceUsage;
manufacturer.value = data.manufacturer;
model.value = data.model;
purchaseDate.value = controllers5.formatDate(data.purchaseDate);
purchasePrice.value = data.purchasePrice;
serialNumber.value = data.serialNumber;
usage.value = data.usage;
warrantyDate.value = controllers5.formatDate(data.warrantyDate);
selectcontact.value = data.contact;
selectcompany.value = data.company;
selectjob.value = data.job;
is_loading.value = false;
} else {
router.push({
path: "/login",
});
}
}
const data = JSON.parse(await controllers2.getallpeoples());
data.forEach(function (value: any) {
contactSelect.value.push({ id: value.id, name: value.name });
});
controllers
.emaillogin(user_email)
.then((response: any) => {
ownerid.value = [response.user.id];
})
.catch((error: any) => {
console.log(error);
});
const data1 = JSON.parse(await controllers3.getalljobs());
data1.forEach(function (value: any) {
jobSelect.value.push({ id: value.id, name: value.name });
});
const data2 = JSON.parse(await controllers4.getallcompanies());
data2.forEach(function (value: any) {
companySelect.value.push({ id: value.id, name: value.name });
});
});
return {
name,
custom,
street,
geo,
maintenanceUsage,
manufacturer,
model,
purchaseDate,
purchasePrice,
serialNumber,
usage,
warrantyDate,
add,
cancel,
is_loading,
loading,
selectcontact,
contactSelect,
selectcompany,
companySelect,
selectjob,
jobSelect,
ownerid,
};
},
});
export default AddPlant;
</script>
<template>
<MenuSidebar panel="plant" />
<div class="dashboard-wrapper">
<div class="p-text-center" v-if="is_loading && $route.params.id">
<ProgressSpinner />
</div>
<div v-else>
<section class="page-header">
<h2 class="page-hedaer-title">
{{ $route.params.id ? "Update Plant" : "Add Plant" }}
</h2>
<div class="header-btn-wrapper">
<Button
type="button"
label="create Plant"
class="btn btn-primary mr-3"
:loading="loading"
@click="add"
v-if="!$route.params.id"
/>
<Button
type="button"
label="update Plant"
class="btn btn-primary mr-3"
:loading="loading"
@click="add()"
v-else
/>
<button class="btn btn-primary-outline" @click="cancel()">
Cancel
</button>
</div>
</section>
<section class="people-form-wrapper">
<form>
<div>
<h5 class="my-2">Details</h5>
<div class="p-grid pt-4">
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputText class="cm-input" id="name" v-model="name" />
<label for="name">Name</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputText class="cm-input" id="geo" v-model="geo" />
<label for="geo">Geo</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputNumber
class="cm-input-number"
inputId="maintenanceUsage"
id="maintenanceUsage"
v-model="maintenanceUsage"
/>
<label for="maintenanceUsage">Maintenance Usage</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputText
class="cm-input"
id="manufacturer"
v-model="manufacturer"
/>
<label for="manufacturer">Manufacturer</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputText class="cm-input" id="model" v-model="model" />
<label for="model">Model</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<Calendar
class="cm-input-number"
v-model="purchaseDate"
dateFormat="dd M, yy"
id="purchaseDate"
/>
<label for="purchaseDate">Purchase Date</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputNumber
class="cm-input-number"
inputId="purchasePrice"
id="purchasePrice"
v-model="purchasePrice"
/>
<label for="purchasePrice">Purchase Price</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputText
class="cm-input"
id="serialNumber"
v-model="serialNumber"
/>
<label for="serialNumber">Serial Number</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputText class="cm-input" id="usage" v-model="usage" />
<label for="usage">Usage</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<Calendar
class="cm-input-number"
v-model="warrantyDate"
dateFormat="dd M, yy"
id="warrantyDate"
/>
<label for="warrantyDate">Warranty Date</label>
</span>
</div>
<div class="p-col-12 p-lg-6">
<div class="p-float-label">
<Dropdown
v-model="selectcontact"
inputId="contact"
:options="contactSelect"
optionLabel="name"
placeholder="Select Contact"
class="cm-dropdown"
/>
<label for="selectcontact">Select Contact</label>
</div>
</div>
<div class="p-col-12 p-lg-6">
<div class="p-float-label">
<Dropdown
v-model="selectcompany"
inputId="company"
:options="companySelect"
optionLabel="name"
placeholder="Select Company"
class="cm-dropdown"
/>
<label for="selectcompany">Select Company</label>
</div>
</div>
<div class="p-col-12 p-lg-6">
<div class="p-float-label">
<Dropdown
v-model="selectjob"
inputId="job"
:options="jobSelect"
optionLabel="name"
placeholder="Select Job"
class="cm-dropdown"
/>
<label for="job">Select Job</label>
</div>
</div>
<div class="p-col-12 p-lg-6">
<span class="p-float-label">
<InputText class="cm-input" id="custom" v-model="custom" />
<label for="custom">Custom</label>
</span>
</div>
</div>
</div>
<Divider />
<div>
<h5 class="my-2">Address</h5>
<div class="p-grid pt-4">
<div class="p-col-12">
<span class="p-float-label">
<InputText class="cm-input" id="street" v-model="street" />
<label for="street">Street address</label>
</span>
</div>
</div>
</div>
</form>
</section>
</div>
</div>
</template>
<style lang="scss" scoped>
.page-header {
max-width: 750px;
}
.people-form-wrapper {
padding: 40px;
background-color: $white;
border-radius: 15px;
max-width: 750px;
.cm-input,
.cm-textarea,
.cm-dropdown,
.cm-chips,
.cm-input-number,
.cm-input-color-picker {
width: 100%;
}
.cm-label {
font-size: 12px;
line-height: 16px;
color: $grey3;
margin-bottom: 5px;
display: inline-block;
}
.check-label {
font-size: 12px;
line-height: 16px;
color: $grey3;
}
.radio-label {
font-size: 14px;
line-height: 20px;
color: $grey9;
display: inline-block;
}
.p-divider {
&.p-divider-horizontal {
margin: 40px 0;
}
}
.lock-icon {
color: $grey3;
font-size: 14px;
cursor: pointer;
}
.people-add-social {
.p-col {
flex-grow: 0;
}
.outline-icon-btn {
padding: 12px;
.p-inputtext {
border: none;
flex-grow: 1;
padding: 0;
&:focus {
box-shadow: none;
}
}
}
}
::v-deep(.p-checkbox) {
width: 14px;
height: 14px;
.p-checkbox-box {
width: 14px;
height: 14px;
border-color: $grey6;
.p-checkbox-icon {
font-size: 9px;
}
}
}
}
</style> |
/******************************************************************************
* Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
/** \file
** \brief
**/
#pragma once
#include <climits>
#include <limits>
#ifndef __CUDA_ARCH__
#include <base/system/main/platform.h>
#include <base/system/main/i_assert.h>
#include <mi/base/types.h>
#include <algorithm>
#include <cmath>
#endif
namespace MI {
namespace IMAGE {
// usually not needed extra-safe dequantization that forces to use a division instead of a multiplication with (1./(N = (1 << bits) - 1))
// tested with 8,16 and up to 30 bits
// the test did dequantize an unsigned (X bits) to float, then back to unsigned via quantize_unsigned (below) with both variants
// the intermediate float values then obviously differed a bit, but the resulting unsigned from the back and forth conversion was always the same!
/*template <unsigned char bits> // number of bits to map to
MI_HOST_DEVICE_INLINE float dequantize_unsigned(const unsigned int i)
{
#ifndef __CUDA_ARCH__
using std::min;
#endif
enum { N = (1u << bits) - 1 };
return min(precise_divide((float)i, (float)N), 1.f); //!! test: optimize div or does this break precision?
}*/
template <unsigned char bits> // number of bits to map to
MI_HOST_DEVICE_INLINE unsigned quantize_unsigned(const float x)
{
#ifndef __CUDA_ARCH__
MI_ASSERT(!std::isnan(x));
//MI_ASSERT(std::isfinite(x)); // is handled in the second code variant below
MI_ASSERT(x >= 0.f);
using std::min;
static_assert(bits < 31, "bits must be smaller 31");
#endif
enum { N = (1u << bits) - 1, Np1 = (1u << bits) };
//return min((unsigned)(x * (float)Np1),(unsigned)N); // does not handle large values, as these trigger undefined behavior (on x86: 0)
#ifdef __CUDA_ARCH__
return (unsigned)(fminf(x, __uint_as_float(0x3f800000u-1)) * (float)Np1);
#else
return (unsigned)(min(x, mi::base::binary_cast<float>(0x3f800000u-1)) * (float)Np1);
#endif
}
template <typename T>
MI_HOST_DEVICE_INLINE T quantize_unsigned(const float x)
{
#ifndef __CUDA_ARCH__
static_assert(std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed,"can only quantize to unsigned integer types");
#endif
return T(quantize_unsigned<sizeof(T)*CHAR_BIT>(x));
}
template <unsigned char bits> // number of bits to map to, including negative numbers, so mapping just to unsigned: bits+1 (0..255 -> bits = 9)
MI_HOST_DEVICE_INLINE int quantize_signed(const float x)
{
#ifndef __CUDA_ARCH__
MI_ASSERT(!std::isnan(x));
MI_ASSERT(std::isfinite(x));
using std::max;
using std::min;
static_assert(bits < 32, "bits must be smaller 32"); //!! 33?
#endif
enum { N = (1u << (bits - 1)) - 1 };
const float sign = (x >= 0.f) ? 0.5f : -0.5f;
return (int)(min(max(x * (float)((double)N + 0.5) + sign, -(float)N), (float)N));
}
template <typename T>
MI_HOST_DEVICE_INLINE T quantize_signed(const float x)
{
#ifndef __CUDA_ARCH__
static_assert(std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed,"can only quantize to signed integer types");
#endif
return T(quantize_signed<sizeof(T)*CHAR_BIT>(x));
}
namespace DETAIL {
template <bool is_signed>
struct Quantize
{
template <typename T>
MI_HOST_DEVICE_INLINE static T quantize(const float x) { return quantize_signed<T>(x); }
};
template <>
struct Quantize<false>
{
template <typename T>
MI_HOST_DEVICE_INLINE static T quantize(const float x) { return quantize_unsigned<T>(x); }
};
}
template <typename T>
MI_HOST_DEVICE_INLINE T quantize(const float x)
{
return DETAIL::Quantize<std::numeric_limits<T>::is_signed>::template quantize<T>(x);
}
}} |
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/label-has-associated-control */
/** @jsx jsx */
// Note: adding photo functionality is commented out, does not work currently
import { useState, useEffect } from 'react';
import { css, jsx } from '@emotion/react';
import { useRecoilState, useRecoilValue } from 'recoil';
import axios from 'axios';
import PropTypes from 'prop-types';
import { updateQuestionsState } from './atoms';
import currentProductState from '../currentProduct';
function AddAnswer({ question }) {
const product = useRecoilValue(currentProductState);
const [updateQuestions, setUpdateQuestions] = useRecoilState(updateQuestionsState);
const [invalidInput, setInvalidInput] = useState('');
const [answerForm, setAnswerForm] = useState(false);
const [photos, setPhotos] = useState([]);
const [photoURLs, setPhotoURLs] = useState([]);
function handleCloseForm(e) {
e.preventDefault();
const validEmail = /^\S+@\S+\.\S+$/;
if (!validEmail.test(e.target.email.value)) {
e.target.email.value = '';
setInvalidInput('Error: must provide a valid email.');
return;
}
if (photos.length > 5) {
setInvalidInput('Error: maximum of 5 photos per answer.');
return;
}
/*
axios({
method: 'post',
url: 'http://thumbsnap.com/api/upload',
data: { image: formData },
headers: {
'Content-Type': 'multipart/form-data',
},
params: {
key: '00001c532dc1d2ac78866881e1ddee52',
image: formData,
},
}).then((res) => {
console.log(res.data);
}).catch((err) => {
console.error('error posting photo: ', err);
});
*/
axios({
method: 'post',
url: `/qa/questions/${question.question_id}/answers`,
data: {
body: e.target.body.value,
name: e.target.nickname.value,
email: e.target.email.value,
product_id: product.id,
photos: [],
},
}).then(() => {
setUpdateQuestions(updateQuestions + 1);
}).catch((err) => {
console.error('error posting answer: ', err);
});
setAnswerForm(!answerForm);
e.target.nickname.value = '';
e.target.body.value = '';
e.target.filename.value = '';
e.target.email.value = '';
setPhotos([]);
setPhotoURLs([]);
}
function handleAddAnswer(e) {
e.preventDefault();
setAnswerForm(!answerForm);
}
function handleImageUpload(e) {
e.preventDefault();
setPhotos([...e.target.files]);
}
useEffect(() => {
if (photos.length < 1) {
return;
}
const newPhotoURLs = [];
photos.forEach((photo) => {
newPhotoURLs.push(URL.createObjectURL(photo));
});
setPhotoURLs(newPhotoURLs);
}, [photos]);
return (
<span
css={css`
.modal {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
}
.modal-main {
position:fixed;
background: white;
width: 50%;
height: auto;
top:50%;
left:50%;
transform: translate(-50%,-50%);
border: solid black 2px;
text-align: center;
white-space: normal;
word-wrap: break-word;
}
.display-block {
display: block;
}
.error {
color: red;
}
.exit {
float: right;
margin: 5px;
}
img {
border: 1px solid #ddd; /* Gray border */
border-radius: 4px; /* Rounded border */
padding: 5px; /* Some padding */
width: 50px; /* Set a small width */
height: 50px;
}
input[type="text"] {
width: 80%;
}
textarea {
width: 80%;
}
input[type="submit"] {
white-space: normal;
word-wrap: break-word;
font-family: Gill Sans, Verdana;
}
input[type="file"] {
font-family: Gill Sans, Verdana;
}
.display-none {
display: none;
}`}
>
<button onClick={handleAddAnswer} type="button">Add Answer</button>
<div onClick={handleAddAnswer} className={answerForm ? 'modal' : 'display-none'} />
<form onSubmit={handleCloseForm} className={answerForm ? 'display-block modal-main' : 'display-none'}>
<button onClick={handleAddAnswer} className="exit" type="button">X</button>
<br />
<h3>Submit Your Answer</h3>
{`${product.name}: ${question.question_body}`}
<br />
<br />
<label>
{'Your Answer* '}
<br />
<textarea data-testid="a-answer" name="body" type="text" rows="5" cols="50" maxLength="1000" required />
</label>
<br />
<br />
<label>
{'What is your nickname* '}
<br />
<input data-testid="a-name" name="nickname" type="text" maxLength="60" placeholder="Example: jackson11!" required />
</label>
<br />
For privacy reasons, do not use your full name or email address.
<br />
<br />
<label>
{'Your email* '}
<br />
<input data-testid="a-email" name="email" type="text" maxLength="60" placeholder="Why did you like the product or not?" required />
</label>
<br />
For authentication reasons, you will not be emailed.
<br />
<br />
<label>
Upload your photos:
<br />
<input data-testid="a-file" type="file" onChange={handleImageUpload} name="filename" accept="image/*" multiple />
</label>
<br />
{'Hold shift to select multiple photos (up to 5) '}
<br />
{photoURLs.map((photo) => <img key={photo} src={photo} alt="thumbnail" />)}
<br />
<input data-testid="a-submit" type="submit" value="Submit Answer" />
<br />
<br />
<div className="error">
{invalidInput.length > 0 ? invalidInput : null}
</div>
<br />
</form>
</span>
);
}
AddAnswer.propTypes = {
question: PropTypes.shape({
question_id: PropTypes.number,
question_body: PropTypes.string,
question_date: PropTypes.string,
question_helpfulness: PropTypes.number,
reported: PropTypes.bool,
answers: PropTypes.shape({}),
}).isRequired,
};
export default AddAnswer; |
'use client'
// MainComponent.tsx
import React, { useState } from 'react';
import CategoryList from './categoryList';
const Category: React.FC = () => {
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
const categories: string[] = ['Sport', 'Music', 'Education', 'Comedy', 'Hobbies'];
const handleCategoryClick = (category: string) => {
setSelectedCategory(category);
// You can add further logic here, like fetching data based on the selected category
}
return (
<div>
<CategoryList categories={categories} onCategoryClick={handleCategoryClick}/>
{selectedCategory && <p>Selected Category: {selectedCategory}</p>}
</div>
);
}
export default Category; |
import { DataTypes } from "sequelize";
import { sequelize } from "../../config/database.js";
const Cierre = sequelize.define(
"Cierre",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
fecha: {
type: DataTypes.DATEONLY,
allowNull: false,
},
sucursal_id: {
type: DataTypes.BIGINT,
allowNull: false,
},
neto: {
type: DataTypes.DECIMAL(12, 2),
allowNull: false,
},
iva_21: {
type: DataTypes.DECIMAL(12, 2),
allowNull: false,
},
iva_105: {
type: DataTypes.DECIMAL(12, 2),
allowNull: false,
},
total: {
type: DataTypes.DECIMAL(12, 2),
allowNull: false,
},
nro_cierre: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
tableName: "cierre",
timestamps: false, // Evita la creación automática de las columnas 'createdAt' y 'updatedAt'
freezeTableName: true, // Evita que Sequelize pluralice el nombre de la tabla
}
);
export default Cierre; |
import React, { ChangeEvent, useCallback, useEffect, useState } from 'react';
import styles from '../../styles/ResetPassword.module.scss';
import { Button, Input } from '@/components/index';
import { useMutation } from 'react-query';
import { changePasswordApi } from '../../services/user';
import { Router, useRouter } from 'next/router';
const ResetPassword = () => {
const [passwordInfo, setPasswordInfo] = useState({
password: '',
confirm_password: '',
});
const router = useRouter();
const [errorInfo, setErrorInfo] = useState({
password: '',
confirm_password: '',
});
const changePasswordMutation = useMutation(changePasswordApi);
useEffect(() => {}, []);
const onChangePasswordInfo = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
const id = event.target.id;
const value = event.target.value;
setPasswordInfo(prevState => ({
...prevState,
[id]: value,
}));
},
[],
);
const checkValidation = useCallback(() => {
const regPassword =
/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,32}$/;
const temp = {
password: '',
confirm_password: '',
};
if (
passwordInfo.password.length < 8 ||
!regPassword.test(passwordInfo.password)
) {
temp.password =
'Password Must contain 8 or more characters, at least one uppercase, number, and symbol.';
} else if (passwordInfo.password !== passwordInfo.confirm_password) {
temp.confirm_password = 'Password and confirm password must be same.';
}
setErrorInfo(temp);
return temp;
}, [passwordInfo.confirm_password, passwordInfo.password]);
const onPressSubmit = useCallback(() => {
const validation = checkValidation();
if (!validation.confirm_password && !validation.password) {
const payload = {
password: passwordInfo.password,
confirm_password: passwordInfo.confirm_password,
};
const search = window.location.search;
const params = new URLSearchParams(search);
const code = params.get('code');
const finalPayload = {
code: code || '',
payload,
};
if (finalPayload.code && finalPayload.payload) {
changePasswordMutation.mutate(finalPayload, {
onSuccess: () => {
alert('Password reset successfully');
router.push('/');
},
onError: (err: any) => {
console.error('Error in update password', err);
alert('Somethings went wrong');
},
});
}
}
}, [
changePasswordMutation,
checkValidation,
passwordInfo.confirm_password,
passwordInfo.password,
]);
return (
<div className={styles.resetPassword}>
<div className={styles.container}>
<div className={styles.subContainer}>
<h3 className={styles.title}>{`Reset Password`}</h3>
<p
className={
styles.description
}>{`Please enter new password to reset your password.`}</p>
<div className={styles.inputContainer}>
<Input
id={'password'}
label={'New Password'}
onChange={onChangePasswordInfo}
value={passwordInfo.password}
placeholder={'New Password'}
type={'password'}
errorText={errorInfo.password}
/>
</div>
<Input
id={'confirm_password'}
label={'Confirm New Password'}
onChange={onChangePasswordInfo}
value={passwordInfo.confirm_password}
placeholder={'Confirm New Password'}
type={'password'}
errorText={errorInfo.confirm_password}
/>
<div className={styles.buttonContainer}>
<Button
label={'Reset Password'}
id={'reset_password'}
onClick={onPressSubmit}
disabled={
!passwordInfo.password || !passwordInfo.confirm_password
}
/>
</div>
</div>
</div>
</div>
);
};
export default ResetPassword; |
#' Moleculors input file loader.
#'
#' This function take a csv file containing 4 colums:
#' atom symbol, X,Y,Z. Any difference will be detected as
#' an error or warning depending on the situation. NOTE: the input
#' coordinates are supposed to be the optimized coordinates of the
#' target molecule! If this requirement is not fullfilled any descriptor
#' will not be related to the topological property at all.
#'
#'
#' @examples
#' molecular_input()
#'
#'
#' @export
molecular_input = function(){
cartesian_csv = tryCatch({ cartesian_csv = read.csv(file.choose(),
header = FALSE)
},
warning = function(w){
warning(w)
message("csv file doesn't look properly formatted")
},
error = function(e){
message("Input file doesn't look like a csv file")
return(NA)
},
finally = { message("Always use cartesian coordinates as input!")
})
if (ncol(cartesian_csv) != 4) {
return(message("Input file has more/less column than expected"))
}
names(cartesian_csv) = c("Atom", "X", "Y", "Z")
print(cartesian_csv)
Mol_mat$input = cartesian_csv
return(message("Loading successful"))
}
#' Moleculors multiple input file loader.
#'
#' This function take a csv file containing 4 colums:
#' atom symbol, X,Y,Z. Any difference will be detected as
#' an error or warning depending on the situation. NOTE: the input
#' coordinates are supposed to be the optimized coordinates of the
#' target molecule! If this requirement is not fullfilled any descriptor
#' will not be related to the topological property at all.
#'
#' @import tcltk
#'
#' @examples
#' molecular_input_multiple()
#'
#'
#' @export
molecular_input_multiple <- function(){
data_names <- tk_choose.files()
cartesian_coordinates <- list()
for (i in 1:length(data_names)) {
cartesian_coordinates[[i]] <- read.csv(data_names[i], header = FALSE)
names(cartesian_coordinates[[i]]) = c("Atom", "X", "Y", "Z")
}
Mol_mat$input_list = cartesian_coordinates
}
#' prediction matrix loader.
#'
#' This function take as input the prediction vector to be used
#' for the training of the NN for the qsar study and store the information in
#' the prediction matrix
#'
#'
#'
#' @examples
#' prediction_parameter()
#'
#'
#' @export
prediction_parameter <- function(){
prediction_matrix <- read.csv(file.choose(), header = FALSE)
if (ncol(prediction_matrix) > 1) {
return(message("Error in prediction matrix structure. COL > 1"))
} else {
assign("prediction_matrix", prediction_matrix, envir = globalenv())
}
} |
import {expect} from '@playwright/test';
import {test, BaseTest} from '../../BaseTest';
test.describe('Virtual Rooms tests', async () => {
let dateTimePrefix;
let virtualRoomTitle;
test.beforeEach(async ({pageManager, apiManager}) => {
BaseTest.setFeatureSuite.chats();
await CleanConversationsPanel({apiManager});
dateTimePrefix = new Date().getDate().toString() + new Date().getTime().toString();
virtualRoomTitle = dateTimePrefix + ' Autotest Group Topic';
await pageManager.sideMenu.OpenMenuTab(pageManager.sideMenu.SideMenuTabs.Chats);
});
test.afterEach(async ({apiManager, page}) => {
await CleanConversationsPanel({apiManager});
await page.close();
});
async function CleanConversationsPanel({apiManager}) {
const conversations = await apiManager.chatsAPI.GetConversations();
await Promise.all(conversations.map(async (conversation) => {
return apiManager.deleteChatsAPI.DeleteGroup(conversation.id);
}));
};
async function CreateVirtualRoom({pageManager}, title) {
await pageManager.sideSecondaryChatsMenu.Buttons.CreateVirtualRoom.click();
await pageManager.newVirtualRoomsModal.CreateVirtualRoom(title);
};
async function CreateVirtualRoomAndOpenDetails({apiManager, pageManager}) {
await apiManager.createChatsAPI.CreateVirtualRoom(virtualRoomTitle);
await pageManager.sideSecondaryChatsMenu.OpenTab.VirtualRooms();
await pageManager.sideSecondaryChatsMenu.Elements.VirtualRoomItem.click();
};
// Virtual room does not appear in Virtual Rooms Tab, Virtual room tab does not appear
test('TC419. Create virtual room. Virtual room should be visible in Virtual Rooms Tab. @smoke', async ({pageManager}) => {
BaseTest.setSuite.smoke();
test.fail(true, 'Virtual room does not appear in Virtual Rooms Tab, Virtual room tab does not appear');
await CreateVirtualRoom({pageManager}, virtualRoomTitle);
await pageManager.sideSecondaryChatsMenu.OpenTab.VirtualRooms();
await expect(pageManager.sideSecondaryChatsMenu.Elements.ConversationsItem.locator(`"${virtualRoomTitle}"`)).toBeVisible();
});
test('TC420. Copy Virtual room link. Virtual room link should be in clipboard.', async ({page, pageManager, apiManager, browserName}) => {
test.skip(browserName === 'webkit' || browserName === 'firefox', 'A bug related to permissions.');
await CreateVirtualRoomAndOpenDetails({apiManager, pageManager});
await pageManager.virtualRoomField.Buttons.VirtualRoomLink.click();
const clipboardContent = await page.evaluate(() => navigator.clipboard.readText());
const [meetingPage] = await Promise.all([
page.context().waitForEvent('page'),
pageManager.virtualRoomField.Buttons.JoinVirtualRoom.click(),
]);
expect(clipboardContent).toBe(meetingPage.url());
});
test('TC427. Delete Virtual room. Virtual room should not be visible in Virtual Rooms Tab.', async ({pageManager, apiManager}) => {
await CreateVirtualRoomAndOpenDetails({apiManager, pageManager});
await pageManager.virtualRoomField.Buttons.DeleteVirtualRoom.click();
await pageManager.chatsActionsModal.Buttons.Delete.click();
await expect(pageManager.sideSecondaryChatsMenu.Elements.VirtualRoomItem.locator(`"${virtualRoomTitle}"`)).not.toBeVisible();
});
}); |
"use client";
import Link from "next/link";
import React from "react";
import {useState} from "react";
import NavLink from "./NavLink";
import {Bars3Icon, XMarkIcon} from "@heroicons/react/24/solid";
import MenuOverlay from "./MenuOverlay";
const navLinks = [
{
title: "About",
path: "#about",
},
{
title: "Projects",
path: "#projects",
},
{
title: "Contact",
path: "#contact",
},
];
const Navbar = () => {
const [navbarOpen, setNavbarOpen] = useState(false);
return (
<nav className="fixed top-0 left-0 right-0 z-10 bg-[#121212] bg-opacity-100">
<div className="flex flex-wrap items-center justify-between mx-auto px-4 py-2">
<Link href={"/"} className="text-2xl md:text-5xl text-white font-semibold">
DMHQ
</Link>
<div className="mobile-menu block md:hidden">
{!navbarOpen ? (
<button
onClick={() => setNavbarOpen(true)}
className="flex items-center py-2 border rounded border-slate-200 text-slate-200 hover:text-white hover:border-white">
<Bars3Icon className="h-5 w-5" />
</button>
) : (
<button
onClick={() => setNavbarOpen(false)}
className="flex items-center py-2 border rounded border-slate-200 text-slate-200 hover:text-white hover:border-white">
<XMarkIcon className="h-5 w-5" />
</button>
)}
</div>
<div className="menu hidden md:block md:w-auto " id="navbar">
<ul className="flex p-4 -md:p-0 md:flex-row md:space-x-8 mt-0">
{navLinks.map((link, index) => (
<li key={index}>
<NavLink href={link.path} title={link.title} />
</li>
))}
</ul>
</div>
</div>
{navbarOpen ? <MenuOverlay links={navLinks} /> : null}
</nav>
);
};
export default Navbar; |
---
title: Getting started
---
import LaracastsBanner from "@components/LaracastsBanner.astro"
## Overview
<LaracastsBanner
title="Layouts"
description="Watch the Rapid Laravel Development with Filament series on Laracasts - it will teach you the basics of customizing the layout of a Filament form."
url="https://laracasts.com/series/rapid-laravel-development-with-filament/episodes/6"
series="rapid-laravel-development"
/>
Filament forms are not limited to just displaying fields. You can also use "layout components" to organize them into an infinitely nestable structure.
Layout component classes can be found in the `Filament\Forms\Components` namespace. They reside within the schema of your form, alongside any [fields](fields/getting-started).
Components may be created using the static `make()` method. Usually, you will then define the child component `schema()` to display inside:
```php
use Filament\Forms\Components\Grid;
Grid::make(2)
->schema([
// ...
])
```
## Available layout components
Filament ships with some layout components, suitable for arranging your form fields depending on your needs:
- [Grid](grid)
- [Fieldset](fieldset)
- [Tabs](tabs)
- [Wizard](wizard)
- [Section](section)
- [Split](split)
- [Placeholder](placeholder)
You may also [create your own custom layout components](custom) to organize fields however you wish.
## Setting an ID
You may define an ID for the component using the `id()` method:
```php
use Filament\Forms\Components\Section;
Section::make()
->id('main-section')
```
## Adding extra HTML attributes
You can pass extra HTML attributes to the component, which will be merged onto the outer DOM element. Pass an array of attributes to the `extraAttributes()` method, where the key is the attribute name and the value is the attribute value:
```php
use Filament\Forms\Components\Group;
Section::make()
->extraAttributes(['class' => 'custom-section-style'])
```
Classes will be merged with the default classes, and any other attributes will override the default attributes.
## Global settings
If you wish to change the default behavior of a component globally, then you can call the static `configureUsing()` method inside a service provider's `boot()` method, to which you pass a Closure to modify the component using. For example, if you wish to make all section components have [2 columns](grid) by default, you can do it like so:
```php
use Filament\Forms\Components\Section;
Section::configureUsing(function (Section $section): void {
$section
->columns(2);
});
```
Of course, you are still able to overwrite this on each field individually:
```php
use Filament\Forms\Components\Section;
Section::make()
->columns(1)
``` |
# Example 1
Consider the following git diff:
```
apiVersion: rabbitmq.com/v1beta1
kind: RabbitmqCluster
metadata:
name: test-cluster
namespace: rabbitmq-system
spec:
- affinity:
- podAntiAffinity:
- requiredDuringSchedulingIgnoredDuringExecution:
- - labelSelector:
- matchExpressions:
- - key: app.kubernetes.io/name
- operator: In
- values:
- - test-cluster
- topologyKey: kubernetes.io/hostname
- podAffinity:
- requiredDuringSchedulingIgnoredDuringExecution: null
image: null
imagePullSecrets: null
+ persistence:
+ storage: "50Gi"
rabbitmq:
additionalConfig: |
cluster_partition_handling = pause_minority
vm_memory_high_watermark_paging_ratio = 0.99
disk_free_limit.relative = 1.0
collect_statistics_interval = 10000
- replicas: 2
+ replicas: 3
resources:
requests:
cpu: 1
memory: 4Gi
limits:
cpu: 1
memory: 4Gi
secretBackend: null
service:
type: ClusterIP
skipPostDeploySteps: false
terminationGracePeriodSeconds: 1024
tls:
caSecretName: null
disableNonTLSListeners: false
secretName: null
tolerations: null
```
Format note: The lines beginning with `-` have been deleted, and the lines beginning with `+` have been added. Other lines were not changed.
Here's an English description of the changes being made in this diff:
```
- The Anti-affinity constraint is now removed from the config.
- The cluster is now configured to use 50Gi of persistence storage
- The number of replicas is being increased from 2 to 3
No other changes have been made.
```
In imperative form:
```
- Remove the Anti-affinity constraint from the config.
- Configure the cluster to use 50Gi of persistence storage
- Increase the number of replicas from 2 to 3
```
<<END>>
----
# Example 2
Consider the following git diff:
```
$diff_goes_here
```
Format note: The lines beginning with `-` have been deleted, and the lines beginning with `+` have been added. Other lines were not changed.
Here's an English description of the changes being made in this diff:
``` |
import React from 'react';
import { Button } from './Button';
import Check from '../assets/images/check.svg';
import '../assets/css/CustomCard.css';
export const CustomCard = ({ className, offer, title, price, description, terms, features }) => {
let titleClassName = '';
if (className === 'card1') {
titleClassName = 'special-desc';
}
return (
<div className='card'>
<div>
<div className='offer-container'>
{offer && <p className='offer'>{offer}</p>}
<p className='tag'>One-time plans available</p>
<p className='title'>{title}</p>
<p className='price'>{price}</p>
<p className={`desc ${titleClassName}`}>{description}</p>
</div>
<div className='features'>
{features.map((feature, index) => (
<p className='feature' key={index}>
<img src={Check} alt="Check Free Icon" />
<p className='texts'>{feature}</p>
</p>
))}
{className === 'card1' && (
<React.Fragment>
<br />
<br />
<br />
<br />
</React.Fragment>
)}
{className === 'card2' && (
<React.Fragment>
<br />
<br />
<br />
</React.Fragment>
)}
<Button link="#/plans">VIEW PLANS</Button>
</div>
</div>
<p className='terms'><u>Terms and conditions apply.</u> {terms}</p>
</div>
);
}; |
pragma solidity ^0.4.3;
/**
* @title ECCMath
*
* Functions for working with integers, curve-points, etc.
*
* @author Andreas Olofsson (androlo1980@gmail.com)
*/
library ECCMath {
/// @dev Modular inverse of a (mod p) using euclid.
/// "a" and "p" must be co-prime.
/// @param a The number.
/// @param p The mmodulus.
/// @return x such that ax = 1 (mod p)
function invmod(uint a, uint p) internal constant returns (uint) {
if (a == 0 || a == p || p == 0)
revert();
//throw;
if (a > p)
a = a % p;
int t1;
int t2 = 1;
uint r1 = p;
uint r2 = a;
uint q;
while (r2 != 0) {
q = r1 / r2;
(t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2);
}
if (t1 < 0)
return (p - uint(-t1));
return uint(t1);
}
/// @dev Modular exponentiation, b^e % m
/// Basically the same as can be found here:
/// https://github.com/ethereum/serpent/blob/develop/examples/ecc/modexp.se
/// @param b The base.
/// @param e The exponent.
/// @param m The modulus.
/// @return x such that x = b**e (mod m)
function expmod(uint b, uint e, uint m) internal constant returns (uint r) {
if (b == 0)
return 0;
if (e == 0)
return 1;
if (m == 0)
revert();
//throw;
r = 1;
uint bit = 2 ** 255;
bit = bit;
assembly {
loop:
jumpi(end, iszero(bit))
r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, bit)))), m)
r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, div(bit, 2))))), m)
r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, div(bit, 4))))), m)
r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, div(bit, 8))))), m)
bit := div(bit, 16)
jump(loop)
end:
}
}
/// @dev Converts a point (Px, Py, Pz) expressed in Jacobian coordinates to (Px", Py", 1).
/// Mutates P.
/// @param P The point.
/// @param zInv The modular inverse of "Pz".
/// @param z2Inv The square of zInv
/// @param prime The prime modulus.
/// @return (Px", Py", 1)
function toZ1(uint[3] memory P, uint zInv, uint z2Inv, uint prime) internal constant {
P[0] = mulmod(P[0], z2Inv, prime);
P[1] = mulmod(P[1], mulmod(zInv, z2Inv, prime), prime);
P[2] = 1;
}
/// @dev See _toZ1(uint[3], uint, uint).
/// Warning: Computes a modular inverse.
/// @param PJ The point.
/// @param prime The prime modulus.
/// @return (Px", Py", 1)
function toZ1(uint[3] PJ, uint prime) internal constant {
uint zInv = invmod(PJ[2], prime);
uint zInv2 = mulmod(zInv, zInv, prime);
PJ[0] = mulmod(PJ[0], zInv2, prime);
PJ[1] = mulmod(PJ[1], mulmod(zInv, zInv2, prime), prime);
PJ[2] = 1;
}
}
library Secp256k1 {
// Field size
uint constant pp = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// Base point (generator) G
uint constant Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint constant Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Order of G
uint constant nn = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
// Cofactor
// uint constant hh = 1;
// Maximum value of s
uint constant lowSmax = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;
// For later
// uint constant lambda = "0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72";
// uint constant beta = "0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee";
/// @dev See Curve.onCurve
function onCurve(uint[2] P) internal constant returns (bool) {
uint p = pp;
if (0 == P[0] || P[0] == p || 0 == P[1] || P[1] == p)
return false;
uint LHS = mulmod(P[1], P[1], p);
uint RHS = addmod(mulmod(mulmod(P[0], P[0], p), P[0], p), 7, p);
return LHS == RHS;
}
/// @dev See Curve.isPubKey
function isPubKey(uint[2] memory P) internal constant returns (bool isPK) {
isPK = onCurve(P);
}
/// @dev See Curve.isPubKey
function isPubKey(uint[3] memory P) internal constant returns (bool isPK) {
uint[2] memory a_P;
a_P[0] = P[0];
a_P[1] = P[1];
isPK = onCurve(a_P);
}
/// @dev See Curve.validateSignature
function validateSignature(bytes32 message, uint[2] rs, uint[2] Q) internal constant returns (bool) {
uint n = nn;
uint p = pp;
if(rs[0] == 0 || rs[0] >= n || rs[1] == 0 || rs[1] > lowSmax)
return false;
if (!isPubKey(Q))
return false;
uint sInv = ECCMath.invmod(rs[1], n);
uint[3] memory u1G = _mul(mulmod(uint(message), sInv, n), [Gx, Gy]);
uint[3] memory u2Q = _mul(mulmod(rs[0], sInv, n), Q);
uint[3] memory P = _add(u1G, u2Q);
if (P[2] == 0)
return false;
uint Px = ECCMath.invmod(P[2], p); // need Px/Pz^2
Px = mulmod(P[0], mulmod(Px, Px, p), p);
return Px % n == rs[0];
}
/// @dev See Curve.compress
function compress(uint[2] P) internal constant returns (uint8 yBit, uint x) {
x = P[0];
yBit = P[1] & 1 == 1 ? 1 : 0;
}
/// @dev See Curve.decompress
function decompress(uint8 yBit, uint x) internal constant returns (uint[2] P) {
uint p = pp;
var y2 = addmod(mulmod(x, mulmod(x, x, p), p), 7, p);
var y_ = ECCMath.expmod(y2, (p + 1) / 4, p);
uint cmp = yBit ^ y_ & 1;
P[0] = x;
P[1] = (cmp == 0) ? y_ : p - y_;
}
// Point addition, P + Q
// inData: Px, Py, Pz, Qx, Qy, Qz
// outData: Rx, Ry, Rz
function _add(uint[3] memory P, uint[3] memory Q) internal constant returns (uint[3] memory R) {
if(P[2] == 0)
return Q;
if(Q[2] == 0)
return P;
uint p = pp;
uint[4] memory zs; // Pz^2, Pz^3, Qz^2, Qz^3
zs[0] = mulmod(P[2], P[2], p);
zs[1] = mulmod(P[2], zs[0], p);
zs[2] = mulmod(Q[2], Q[2], p);
zs[3] = mulmod(Q[2], zs[2], p);
uint[4] memory us = [
mulmod(P[0], zs[2], p),
mulmod(P[1], zs[3], p),
mulmod(Q[0], zs[0], p),
mulmod(Q[1], zs[1], p)
]; // Pu, Ps, Qu, Qs
if (us[0] == us[2]) {
if (us[1] != us[3])
return;
else {
return _double(P);
}
}
uint h = addmod(us[2], p - us[0], p);
uint r = addmod(us[3], p - us[1], p);
uint h2 = mulmod(h, h, p);
uint h3 = mulmod(h2, h, p);
uint Rx = addmod(mulmod(r, r, p), p - h3, p);
Rx = addmod(Rx, p - mulmod(2, mulmod(us[0], h2, p), p), p);
R[0] = Rx;
R[1] = mulmod(r, addmod(mulmod(us[0], h2, p), p - Rx, p), p);
R[1] = addmod(R[1], p - mulmod(us[1], h3, p), p);
R[2] = mulmod(h, mulmod(P[2], Q[2], p), p);
}
// Point addition, P + Q. P Jacobian, Q affine.
// inData: Px, Py, Pz, Qx, Qy
// outData: Rx, Ry, Rz
function _addMixed(uint[3] memory P, uint[2] memory Q) internal constant returns (uint[3] memory R) {
if(P[2] == 0)
return [Q[0], Q[1], 1];
if(Q[1] == 0)
return P;
uint p = pp;
uint[2] memory zs; // Pz^2, Pz^3, Qz^2, Qz^3
zs[0] = mulmod(P[2], P[2], p);
zs[1] = mulmod(P[2], zs[0], p);
uint[4] memory us = [
P[0],
P[1],
mulmod(Q[0], zs[0], p),
mulmod(Q[1], zs[1], p)
]; // Pu, Ps, Qu, Qs
if (us[0] == us[2]) {
if (us[1] != us[3]) {
P[0] = 0;
P[1] = 0;
P[2] = 0;
return;
}
else {
_double(P);
return;
}
}
uint h = addmod(us[2], p - us[0], p);
uint r = addmod(us[3], p - us[1], p);
uint h2 = mulmod(h, h, p);
uint h3 = mulmod(h2, h, p);
uint Rx = addmod(mulmod(r, r, p), p - h3, p);
Rx = addmod(Rx, p - mulmod(2, mulmod(us[0], h2, p), p), p);
R[0] = Rx;
R[1] = mulmod(r, addmod(mulmod(us[0], h2, p), p - Rx, p), p);
R[1] = addmod(R[1], p - mulmod(us[1], h3, p), p);
R[2] = mulmod(h, P[2], p);
}
// Same as addMixed but params are different and mutates P.
function _addMixedM(uint[3] memory P, uint[2] memory Q) internal constant {
if(P[1] == 0) {
P[0] = Q[0];
P[1] = Q[1];
P[2] = 1;
return;
}
if(Q[1] == 0)
return;
uint p = pp;
uint[2] memory zs; // Pz^2, Pz^3, Qz^2, Qz^3
zs[0] = mulmod(P[2], P[2], p);
zs[1] = mulmod(P[2], zs[0], p);
uint[4] memory us = [
P[0],
P[1],
mulmod(Q[0], zs[0], p),
mulmod(Q[1], zs[1], p)
]; // Pu, Ps, Qu, Qs
if (us[0] == us[2]) {
if (us[1] != us[3]) {
P[0] = 0;
P[1] = 0;
P[2] = 0;
return;
}
else {
_doubleM(P);
return;
}
}
uint h = addmod(us[2], p - us[0], p);
uint r = addmod(us[3], p - us[1], p);
uint h2 = mulmod(h, h, p);
uint h3 = mulmod(h2, h, p);
uint Rx = addmod(mulmod(r, r, p), p - h3, p);
Rx = addmod(Rx, p - mulmod(2, mulmod(us[0], h2, p), p), p);
P[0] = Rx;
P[1] = mulmod(r, addmod(mulmod(us[0], h2, p), p - Rx, p), p);
P[1] = addmod(P[1], p - mulmod(us[1], h3, p), p);
P[2] = mulmod(h, P[2], p);
}
// Point doubling, 2*P
// Params: Px, Py, Pz
// Not concerned about the 1 extra mulmod.
function _double(uint[3] memory P) internal constant returns (uint[3] memory Q) {
uint p = pp;
if (P[2] == 0)
return;
uint Px = P[0];
uint Py = P[1];
uint Py2 = mulmod(Py, Py, p);
uint s = mulmod(4, mulmod(Px, Py2, p), p);
uint m = mulmod(3, mulmod(Px, Px, p), p);
var Qx = addmod(mulmod(m, m, p), p - addmod(s, s, p), p);
Q[0] = Qx;
Q[1] = addmod(mulmod(m, addmod(s, p - Qx, p), p), p - mulmod(8, mulmod(Py2, Py2, p), p), p);
Q[2] = mulmod(2, mulmod(Py, P[2], p), p);
}
// Same as double but mutates P and is internal only.
function _doubleM(uint[3] memory P) internal constant {
uint p = pp;
if (P[2] == 0)
return;
uint Px = P[0];
uint Py = P[1];
uint Py2 = mulmod(Py, Py, p);
uint s = mulmod(4, mulmod(Px, Py2, p), p);
uint m = mulmod(3, mulmod(Px, Px, p), p);
var PxTemp = addmod(mulmod(m, m, p), p - addmod(s, s, p), p);
P[0] = PxTemp;
P[1] = addmod(mulmod(m, addmod(s, p - PxTemp, p), p), p - mulmod(8, mulmod(Py2, Py2, p), p), p);
P[2] = mulmod(2, mulmod(Py, P[2], p), p);
}
// Multiplication dP. P affine, wNAF: w=5
// Params: d, Px, Py
// Output: Jacobian Q
function _mul(uint d, uint[2] memory P) internal constant returns (uint[3] memory Q) {
uint p = pp;
if (d == 0)
return;
uint dwPtr; // points to array of NAF coefficients.
uint i;
// wNAF
assembly
{
let dm := 0
dwPtr := mload(0x40)
mstore(0x40, add(dwPtr, 512)) // Should lower this.
loop:
jumpi(loop_end, iszero(d))
jumpi(even, iszero(and(d, 1)))
dm := mod(d, 32)
mstore8(add(dwPtr, i), dm) // Don"t store as signed - convert when reading.
d := add(sub(d, dm), mul(gt(dm, 16), 32))
even:
d := div(d, 2)
i := add(i, 1)
jump(loop)
loop_end:
}
dwPtr = dwPtr;
// Pre calculation
uint[3][8] memory PREC; // P, 3P, 5P, 7P, 9P, 11P, 13P, 15P
PREC[0] = [P[0], P[1], 1];
var X = _double(PREC[0]);
PREC[1] = _addMixed(X, P);
PREC[2] = _add(X, PREC[1]);
PREC[3] = _add(X, PREC[2]);
PREC[4] = _add(X, PREC[3]);
PREC[5] = _add(X, PREC[4]);
PREC[6] = _add(X, PREC[5]);
PREC[7] = _add(X, PREC[6]);
uint[16] memory INV;
INV[0] = PREC[1][2]; // a1
INV[1] = mulmod(PREC[2][2], INV[0], p); // a2
INV[2] = mulmod(PREC[3][2], INV[1], p); // a3
INV[3] = mulmod(PREC[4][2], INV[2], p); // a4
INV[4] = mulmod(PREC[5][2], INV[3], p); // a5
INV[5] = mulmod(PREC[6][2], INV[4], p); // a6
INV[6] = mulmod(PREC[7][2], INV[5], p); // a7
INV[7] = ECCMath.invmod(INV[6], p); // a7inv
INV[8] = INV[7]; // aNinv (a7inv)
INV[15] = mulmod(INV[5], INV[8], p); // z7inv
for(uint k = 6; k >= 2; k--) { // z6inv to z2inv
INV[8] = mulmod(PREC[k + 1][2], INV[8], p);
INV[8 + k] = mulmod(INV[k - 2], INV[8], p);
}
INV[9] = mulmod(PREC[2][2], INV[8], p); // z1Inv
for(k = 0; k < 7; k++) {
ECCMath.toZ1(PREC[k + 1], INV[k + 9], mulmod(INV[k + 9], INV[k + 9], p), p);
}
// Mult loop
while(i > 0) {
uint dj;
uint pIdx;
i--;
assembly {
dj := byte(0, mload(add(dwPtr, i)))
}
_doubleM(Q);
if (dj > 16) {
pIdx = (31 - dj) / 2; // These are the "negative ones", so invert y.
_addMixedM(Q, [PREC[pIdx][0], p - PREC[pIdx][1]]);
}
else if (dj > 0) {
pIdx = (dj - 1) / 2;
_addMixedM(Q, [PREC[pIdx][0], PREC[pIdx][1]]);
}
}
}
}
contract owned {
address public owner;
/* Initialise contract creator as owner */
function owned() {
owner = msg.sender;
}
/* Function to dictate that only the designated owner can call a function */
modifier onlyOwner {
if(owner != msg.sender) revert(); //throw;
_;
}
/* Transfer ownership of this contract to someone else */
function transferOwnership(address newOwner) onlyOwner() {
owner = newOwner;
}
}
/*
* @title AnonymousVoteContract
* Borda Count voting
* A self-talling protocol that supports voter privacy.
*
*/
contract AnonymousVoteContract is owned {
// Modulus for public keys
uint constant pp = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// Base point (generator) G
uint constant Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint constant Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Modulus for private keys (sub-group)
uint constant nn = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
uint[2] G;
//Every address has an index
//This makes looping in the program easier.
address[] public addresses;
mapping (address => uint) public addressid; // Address to Counter
mapping (uint => Voter) public voters;
mapping (address => bool) public eligible; // White list of addresses allowed to vote
mapping (address => bool) public registered; // Address registered?
mapping (address => bool) public votecast; // Address voted?
mapping (address => bool) public commitment; // Have we received their commitment?
mapping (address => uint) public refunds; // Have we received their commitment?
struct Voter {
address addr;
uint[2][4] registeredkey;
uint[2][4] reconstructedkey;
bytes32[5] commitment;
uint[2][4] vote;
uint sendtrx;
}
// Work around function to fetch details about a voter
function getVoter() returns (uint[8] _registeredkey, uint[8] _reconstructedkey, bytes32[5] _commitment){
uint index = addressid[msg.sender];
uint i;
for (i=0; i< 8; i ++) {
_registeredkey[i] = voters[index].registeredkey[i/2][i%2];
_reconstructedkey[i] = voters[index].reconstructedkey[i/2][i%2];
}
_commitment = voters[index].commitment;
}
// List of timers that each phase MUST end by an explicit time in UNIX timestamp.
// Ethereum works in SECONDS. Not milliseconds.
uint public finishSignupPhase; // Election Authority to transition to next phase.
uint public endSignupPhase; // Election Authority does not transition to next phase by this time.
uint public endCommitmentPhase; // Voters have not sent their commitments in by this time.
uint public endVotingPhase; // Voters have not submitted their vote by this stage.
uint public endRefundPhase; // Voters must claim their refund by this stage.
uint public totalregistered; //Total number of participants that have submited a voting key
uint public totaleligible;
uint public totalcommitted;
uint public totalvoted;
uint public totalrefunded;
uint public totaltorefund;
string public question;
uint[2][4] public finaltally; // Final tally
uint public finaltallycomp;
bool public commitmentphase; // OPTIONAL phase.
uint public depositrequired;
uint public gap; // Minimum amount of time between time stamps.
address public charity;
uint public totalcomponent;
uint public lostdeposit; // This money is collected from non active voters...
enum State { SETUP, REGISTRATION, COMMITMENT, VOTE, FINISHED }
State public state;
modifier inState(State s) {
if(state != s) {
revert();
//throw;
}
_;
}
// Borda count voting protocol
function AnonymousVoteContract(uint _gap, address _charity) {
G[0] = Gx;
G[1] = Gy;
state = State.SETUP;
question = "No question set";
gap = _gap; // Minimum gap period between stages
charity = _charity;
}
// Owner of contract sets a whitelist of addresses that are eligible to vote.
function setEligible(address[] addr) onlyOwner {
// We can only handle up 50 people at the moment.
if(totaleligible > 50) {
revert();
//throw;
}
// Sign up the addresses
for(uint i=0; i<addr.length; i++) {
if(!eligible[addr[i]]) {
eligible[addr[i]] = true;
addresses.push(addr[i]);
totaleligible += 1;
}
}
}
// Owner of contract declares that eligible addresses begin round 1 of the protocol
// Time is the number of 'blocks' we must wait until we can move onto round 2.
function beginSignUp(string _question, bool enableCommitmentPhase, uint _finishSignupPhase, uint _endSignupPhase, uint _endCommitmentPhase, uint _endVotingPhase, uint _endRefundPhase, uint _depositrequired) inState(State.SETUP) onlyOwner payable returns (bool){
// We have lots of timers. let's explain each one
// _finishSignUpPhase - Voters should be signed up before this timer
// Voter is refunded if any of the timers expire:
// _endSignUpPhase - Election Authority never finished sign up phase
// _endCommitmentPhase - One or more voters did not send their commitments in time
// _endVotingPhase - One or more voters did not send their votes in time
// _endRefundPhase - Provide time for voters to get their money back.
// Why is there no endTally? Because anyone can call it!
// Represented in UNIX time...
// Make sure 3 people are at least eligible to vote..
// Deposit can be zero or more WEI
if(_finishSignupPhase > 0 + gap && addresses.length >= 3 && _depositrequired >= 0) {
// Ensure each time phase finishes in the future...
// Ensure there is a gap of 'x time' between each phase.
if(_endSignupPhase-gap < _finishSignupPhase) {
return false;
}
// We need to check Commitment timestamps if phase is enabled.
if(enableCommitmentPhase) {
// Make sure there is a gap between 'end of registration' and 'end of commitment' phases.
if(_endCommitmentPhase-gap < _endSignupPhase) {
return false;
}
// Make sure there is a gap between 'end of commitment' and 'end of vote' phases.
if(_endVotingPhase-gap < _endCommitmentPhase) {
return false;
}
} else {
// We have no commitment phase.
// Make sure there is a gap between 'end of registration' and 'end of vote' phases.
if(_endVotingPhase-gap < _endSignupPhase) {
return false;
}
}
// Provide time for people to get a refund once the voting phase has ended.
if(_endRefundPhase-gap < _endVotingPhase) {
return false;
}
// Require Election Authority to deposit ether.
if(msg.value != _depositrequired) {
return false;
}
// Store the election authority's deposit
// Note: This deposit is only lost if the
// election authority does not begin the election
// or call the tally function before the timers expire.
refunds[msg.sender] = msg.value;
// All time stamps are reasonable.
// We can now begin the registration phase.
state = State.REGISTRATION;
// All timestamps should be in UNIX..
finishSignupPhase = _finishSignupPhase;
endSignupPhase = _endSignupPhase;
endCommitmentPhase = _endCommitmentPhase;
endVotingPhase = _endVotingPhase;
endRefundPhase = _endRefundPhase;
question = _question;
commitmentphase = enableCommitmentPhase;
depositrequired = _depositrequired; // Deposit required from all voters
return true;
}
return false;
}
// This function determines if one of the deadlines have been missed
// If a deadline has been missed - then we finish the election,
// and allocate refunds to the correct people depending on the situation.
function deadlinePassed() returns (bool){
uint refund = 0;
// Has the Election Authority missed the registration deadline?
// Election Authority will forfeit his deposit.
if(state == State.REGISTRATION && block.timestamp > endSignupPhase) {
// Nothing to do. All voters are refunded.
state = State.FINISHED;
totaltorefund = totalregistered;
// Election Authority forfeits his deposit...
// If 3 or more voters had signed up...
if(addresses.length >= 3) {
// Election Authority forfeits deposit
refund = refunds[owner];
refunds[owner] = 0;
lostdeposit = lostdeposit + refund;
}
return true;
}
// Has a voter failed to send their commitment?
// Election Authority DOES NOT forgeit his deposit.
if(state == State.COMMITMENT && block.timestamp > endCommitmentPhase) {
// Check which voters have not sent their commitment
for(uint i=0; i<totalregistered; i++) {
// Voters forfeit their deposit if failed to send a commitment
if(!commitment[voters[i].addr]) {
refund = refunds[voters[i].addr];
refunds[voters[i].addr] = 0;
lostdeposit = lostdeposit + refund;
} else {
// We will need to refund this person.
totaltorefund = totaltorefund + 1;
}
}
state = State.FINISHED;
return true;
}
// Has a voter failed to send in their vote?
// Eletion Authority does NOT forfeit his deposit.
if(state == State.VOTE && block.timestamp > endVotingPhase) {
// Check which voters have not cast their vote
for(i=0; i<totalregistered; i++) {
// Voter forfeits deposit if they have not voted.
if(!votecast[voters[i].addr]) {
refund = refunds[voters[i].addr];
refunds[voters[i].addr] = 0;
lostdeposit = lostdeposit + refund;
} else {
// Lets make sure refund has not already been issued...
if(refunds[voters[i].addr] > 0) {
// We will need to refund this person.
totaltorefund = totaltorefund + 1;
}
}
}
state = State.FINISHED;
return true;
}
// Has the deadline passed for voters to claim their refund?
// Only owner can call. Owner must be refunded (or forfeited).
// Refund period is over or everyone has already been refunded.
if(state == State.FINISHED && msg.sender == owner && refunds[owner] == 0 && (block.timestamp > endRefundPhase || totaltorefund == totalrefunded)) {
// Collect all unclaimed refunds. We will send it to charity.
for(i=0; i<totalregistered; i++) {
refund = refunds[voters[i].addr];
refunds[voters[i].addr] = 0;
lostdeposit = lostdeposit + refund;
}
uint[2][4] memory empty;
bytes32[5] memory empty1;
for(i=0; i<addresses.length; i++) {
address addr = addresses[i];
eligible[addr] = false; // No longer eligible
registered[addr] = false; // Remove voting registration
voters[i] = Voter({addr: 0, registeredkey: empty, reconstructedkey: empty, vote: empty, commitment: empty1, sendtrx: 0});
addressid[addr] = 0; // Remove index
votecast[addr] = false; // Remove that vote was cast
commitment[addr] = false;
}
// Reset timers.
finishSignupPhase = 0;
endSignupPhase = 0;
endCommitmentPhase = 0;
endVotingPhase = 0;
endRefundPhase = 0;
delete addresses;
// Keep track of voter activity
totalregistered = 0;
totaleligible = 0;
totalcommitted = 0;
totalvoted = 0;
// General values that need reset
question = "No question set";
finaltally[0][0] = 0;
finaltally[0][1] = 0;
finaltally[1][0] = 0;
finaltally[1][1] = 0;
finaltally[2][0] = 0;
finaltally[2][1] = 0;
finaltally[3][0] = 0;
finaltally[3][1] = 0;
/*finaltally[4][0] = 0;
finaltally[4][1] = 0;*/
finaltallycomp = 0;
commitmentphase = false;
depositrequired = 0;
totalrefunded = 0;
totaltorefund = 0;
totalcomponent = 0;
state = State.SETUP;
return true;
}
// No deadlines have passed...
return false;
}
// Called by participants to register their voting public key
// Participant mut be eligible, and can only register the first key sent key.
function register(uint[2][4] xG, uint[3][4] vG, uint[4] r) inState(State.REGISTRATION) payable returns (bool) {
// HARD DEADLINE
if(block.timestamp > finishSignupPhase) {
revert(); //throw; // throw returns the voter's ether, but exhausts their gas.
}
// Make sure the ether being deposited matches what we expect.
if(msg.value != depositrequired) {
return false;
}
// Only white-listed addresses can vote
if(eligible[msg.sender]) {
if(verifyZKP(xG,r,vG) && !registered[msg.sender]) {
// Store deposit
refunds[msg.sender] = msg.value;
// Update voter's registration
uint[2][4] memory empty;
bytes32[5] memory empty1;
addressid[msg.sender] = totalregistered;
voters[totalregistered] = Voter({addr: msg.sender, registeredkey: xG, reconstructedkey: empty, vote: empty, commitment: empty1, sendtrx: 0});
registered[msg.sender] = true;
totalregistered += 1;
return true;
}
}
return false;
}
// Timer has expired - we want to start computing the reconstructed keys
function finishRegistrationPhase(uint comp) inState(State.REGISTRATION) onlyOwner returns(bool) {
// Make sure at least 3 people have signed up...
if(totalregistered < 3) {
return;
}
if (comp > 3) {
return false;
}
// We can only compute the public keys once participants
// have been given an opportunity to register their
// voting public key.
if(block.timestamp < finishSignupPhase) {
return;
}
// Election Authority has a deadline to begin election
if(block.timestamp > endSignupPhase) {
return;
}
uint[2] memory temp;
uint[3] memory yG;
uint[3] memory beforei;
uint[3] memory afteri;
// Step 1 is to compute the index 1 reconstructed key
afteri[0] = voters[1].registeredkey[comp][0];
afteri[1] = voters[1].registeredkey[comp][1];
afteri[2] = 1;
for(uint i=2; i<totalregistered; i++) {
Secp256k1._addMixedM(afteri, voters[i].registeredkey[comp]);
}
ECCMath.toZ1(afteri,pp);
voters[0].reconstructedkey[comp][0] = afteri[0];
voters[0].reconstructedkey[comp][1] = pp - afteri[1];
// Step 2 is to add to beforei, and subtract from afteri.
for(i=1; i<totalregistered; i++) {
if(i==1) {
beforei[0] = voters[0].registeredkey[comp][0];
beforei[1] = voters[0].registeredkey[comp][1];
beforei[2] = 1;
} else {
Secp256k1._addMixedM(beforei, voters[i-1].registeredkey[comp]);
}
// If we have reached the end... just store beforei
// Otherwise, we need to compute a key.
// Counting from 0 to n-1...
if(i==(totalregistered-1)) {
ECCMath.toZ1(beforei,pp);
voters[i].reconstructedkey[comp][0] = beforei[0];
voters[i].reconstructedkey[comp][1] = beforei[1];
} else {
// Subtract 'i' from afteri
temp[0] = voters[i].registeredkey[comp][0];
temp[1] = pp - voters[i].registeredkey[comp][1];
// Grab negation of afteri (did not seem to work with Jacob co-ordinates)
Secp256k1._addMixedM(afteri,temp);
ECCMath.toZ1(afteri,pp);
temp[0] = afteri[0];
temp[1] = pp - afteri[1];
// Now we do beforei - afteri...
yG = Secp256k1._addMixed(beforei, temp);
ECCMath.toZ1(yG,pp);
voters[i].reconstructedkey[comp][0] = yG[0];
voters[i].reconstructedkey[comp][1] = yG[1];
}
}
totalcomponent |= (1<<comp);
if (totalcomponent == 15) { /* 15 = 2^4 - 1 */
// We have computed each voter's special voting key.
// Now we either enter the commitment phase (option) or voting phase.
if(commitmentphase) {
state = State.COMMITMENT;
} else {
state = State.VOTE;
}
}
}
/*
* OPTIONAL STAGE: All voters submit the hash of their vote.
* Why? The final voter that submits their vote gets to see the tally result
* before anyone else. This provides the voter with an additional advantage
* compared to all other voters. To get around this issue; we can force all
* voters to commit to their vote in advance.... and votes are only revealed
* once all voters have committed. This way the final voter has no additional
* advantage as they cannot change their vote depending on the tally.
* However... we cannot enforce the pre-image to be a hash, and someone could
* a commitment that is not a vote. This will break the election, but you
* will be able to determine who did it (and possibly punish them!).
*/
function submitCommitment(bytes32[5] h) inState(State.COMMITMENT) {
//All voters have a deadline to send their commitment
if(block.timestamp > endCommitmentPhase) {
return;
}
if(!commitment[msg.sender]) {
commitment[msg.sender] = true;
uint index = addressid[msg.sender];
voters[index].commitment = h;
totalcommitted = totalcommitted + 1;
// Once we have recorded all commitments... let voters vote!
if(totalcommitted == totalregistered) {
state = State.VOTE;
}
}
}
// Given the 1 out of k ZKP - record the users vote!
function submitVote(uint[16] ab, uint[16] xGyG, uint[8] params, uint comp) inState(State.VOTE) returns (bool) {
// HARD DEADLINE
if(block.timestamp > endVotingPhase) {
return;
}
if (comp > 3) {
return false;
}
uint c = addressid[msg.sender];
// Make sure the sender can vote, and hasn't already voted.
if(registered[msg.sender] && !votecast[msg.sender]) {
// OPTIONAL Phase: Voters need to commit to their vote in advance.
// Time to verify if this vote matches the voter's previous commitment.
if(commitmentphase) {
// Voter has previously committed to the entire zero knowledge proof...
if(voters[c].commitment[0] != sha256(msg.sender, voters[c].reconstructedkey, xGyG)) {
return false;
}
if(voters[c].commitment[comp+1] != sha256(msg.sender, params, ab)) {
return false;
}
}
if(verify1outofkZKP(ab, xGyG, params, comp)) {
voters[c].sendtrx |= (1<<comp);
// Verify the ZKP for the vote being cast
if(voters[c].sendtrx == 15) { /* 15 = 2^4 - 1 */
voters[c].vote[0][0] = xGyG[2];
voters[c].vote[0][1] = xGyG[3];
voters[c].vote[1][0] = xGyG[6];
voters[c].vote[1][1] = xGyG[7];
voters[c].vote[2][0] = xGyG[10];
voters[c].vote[2][1] = xGyG[11];
voters[c].vote[3][0] = xGyG[14];
voters[c].vote[3][1] = xGyG[15];
votecast[msg.sender] = true;
totalvoted += 1;
// Refund the sender their ether..
// Voter has finished their part of the protocol...
uint refund = refunds[msg.sender];
refunds[msg.sender] = 0;
// We can still fail... Safety first.
// If failed... voter can call withdrawRefund()
// to collect their money once the election has finished.
if (!msg.sender.send(refund)) {
refunds[msg.sender] = refund;
}
return true;
}
return true;
}
}
// Either vote has already been cast, or ZKP verification failed.
return false;
}
// Assuming all votes have been submitted. We can leak the tally.
// We assume Election Authority performs this function. It could be anyone.
// Election Authority gets deposit upon tallying.
function computeTally(uint comp) inState(State.VOTE) onlyOwner {
if (comp > 3) {
return;
}
uint[3] memory temp;
uint[2] memory vote;
uint refund;
// Sum all votes
for(uint i=0; i<totalregistered; i++) {
// Confirm all votes have been cast...
if(!votecast[voters[i].addr]) {
revert(); //throw;
}
vote = voters[i].vote[comp];
if(i==0) {
temp[0] = vote[0];
temp[1] = vote[1];
temp[2] = 1;
} else {
Secp256k1._addMixedM(temp, vote);
}
}
finaltallycomp |= (1<<comp);
if (finaltallycomp == 15) { /* 15 = 2^4 - 1 */
// All votes have been accounted for...
// Get tally, and change state to 'Finished'
state = State.FINISHED;
// All voters should already be refunded!
for(i = 0; i<totalregistered; i++) {
// Sanity check.. make sure refunds have been issued..
if(refunds[voters[i].addr] > 0) {
totaltorefund = totaltorefund + 1;
}
}
}
// Each vote is represented by a G.
// If there are no votes... then it is 0G = (0,0)...
if(temp[0] == 0) {
finaltally[comp][0] = 0;
finaltally[comp][1] = totalregistered;
if (finaltallycomp == 15) {
// Election Authority is responsible for calling this....
// He should not fail his own refund...
// Make sure tally is computed before refunding...
refund = refunds[msg.sender];
refunds[msg.sender] = 0;
if (!msg.sender.send(refund)) {
refunds[msg.sender] = refund;
}
}
return;
} else {
// There must be a vote. So lets
// start adding 'G' until we
// find the result.
ECCMath.toZ1(temp,pp);
uint[3] memory tempG;
tempG[0] = G[0];
tempG[1] = G[1];
tempG[2] = 1;
uint totalregistered_1 = 4 * totalregistered;
// Start adding 'G' and looking for a match
for(i=1; i<=totalregistered_1; i++) {
if(temp[0] == tempG[0]) {
finaltally[comp][0] = i;
finaltally[comp][1] = totalregistered;
// Election Authority is responsible for calling this....
// He should not fail his own refund...
// Make sure tally is computed before refunding...
if (finaltallycomp == 15) {
refund = refunds[msg.sender];
refunds[msg.sender] = 0;
if (!msg.sender.send(refund)) {
refunds[msg.sender] = refund;
}
}
return;
}
// If something bad happens and we cannot find the Tally
// Then this 'addition' will be run 1 extra time due to how
// we have structured the for loop.
Secp256k1._addMixedM(tempG, G);
ECCMath.toZ1(tempG,pp);
}
// Something bad happened. /We should never get here....
// This represents an error message... best telling people
// As we cannot recover from it anyway.
finaltally[comp][0] = 0;
finaltally[comp][1] = 0;
finaltallycomp = 0;
// Election Authority is responsible for calling this....
// He should not fail his own refund...
refund = refunds[msg.sender];
refunds[msg.sender] = 0;
if (!msg.sender.send(refund)) {
refunds[msg.sender] = refund;
}
return;
}
}
// There are two reasons why we might be in a finished state
// 1. The tally has been computed
// 2. A deadline has been missed.
// In the former; everyone gets a refund. In the latter; only active participants get a refund
// We can assume if the deadline has been missed - then refunds has ALREADY been updated to
// take that into account. (a transaction is required to indicate a deadline has been missed
// and in that transaction - we can penalise the non-active participants. lazy sods!)
function withdrawRefund() inState(State.FINISHED){
uint refund = refunds[msg.sender];
refunds[msg.sender] = 0;
if (!msg.sender.send(refund)) {
refunds[msg.sender] = refund;
} else {
// Tell everyone we have issued the refund.
// Owner is not included in refund counter.
// This is OK - we cannot reset election until
// the owner has been refunded...
// Counter only concerns voters!
if(msg.sender != owner) {
totalrefunded = totalrefunded + 1;
}
}
}
// Send the lost deposits to a charity. Anyone can call it.
// Lost Deposit increments for each failed election. It is only
// reset upon sending to the charity!
function sendToCharity() {
// Only send this money to the owner
uint profit = lostdeposit;
lostdeposit = 0;
// Try to send money
if(!charity.send(profit)) {
// We failed to send the money. Record it again.
lostdeposit = profit;
}
}
// Parameters xG, r where r = v - xc, and vG.
// Verify that vG = rG + xcG!
function verifyZKP(uint[2][4] xG, uint[4] r, uint[3][4] vG) returns (bool){
uint[2] memory G;
G[0] = Gx;
G[1] = Gy;
uint[2] memory xGG;
uint[3] memory vGG;
uint i;
for (i=0; i<4; i++) {
xGG[0] = xG[i][0];
xGG[1] = xG[i][1];
vGG[0] = vG[i][0];
vGG[1] = vG[i][1];
vGG[2] = vG[i][2];
// Check both keys are on the curve.
if(!Secp256k1.isPubKey(xGG) || !Secp256k1.isPubKey(vGG)) {
return false; //Must be on the curve!
}
// Get c = H(g, g^{x}, g^{v});
bytes32 b_c = sha256(msg.sender, Gx, Gy, xGG, vGG);
uint c = uint(b_c);
// Get g^{r}, and g^{xc}
uint[3] memory rG = Secp256k1._mul(r[i], G);
uint[3] memory xcG = Secp256k1._mul(c, xGG);
// Add both points together
uint[3] memory rGxcG = Secp256k1._add(rG,xcG);
// Convert to Affine Co-ordinates
ECCMath.toZ1(rGxcG, pp);
// Verify. Do they match?
if(rGxcG[0] == vG[i][0] && rGxcG[1] == vG[i][1]) {
if (i==3) {
return true;
}
} else {
return false;
}
}
}
// a - b = c;
function submod(uint a, uint b) returns (uint){
uint a_nn;
if(a>b) {
a_nn = a;
} else {
a_nn = a+nn;
}
uint c = addmod(a_nn - b,0,nn);
return c;
}
// We verify 1-out-of-k ZKP for Borda count protocol.
function verify1outofkZKP(uint[16] ab, uint[16] xGyG, uint[8] params, uint comp ) returns (bool) {
uint k;
uint[2] memory temp1;
uint[3] memory temp2;
uint[3] memory temp3;
// Voter Index
uint[3] memory i;
i[0] = addressid[msg.sender];
// We already have them stored...
uint[2][4] memory yG = voters[i[0]].reconstructedkey;
uint[2][4] memory xG = voters[i[0]].registeredkey;
if (comp > 3) {
return false;
}
if (comp == 0) {
for (k=0; k<4; k++) {
temp1[0] = xGyG[k*4 + 0];
temp1[1] = xGyG[k*4 + 1];
if(!Secp256k1.isPubKey(temp1)) {
return false;
}
temp1[0] = xGyG[k*4 + 2];
temp1[1] = xGyG[k*4 + 3];
if(!Secp256k1.isPubKey(temp1)) {
return false;
}
temp1[0] = xG[k][0];
temp1[1] = xG[k][1];
if(!Secp256k1.isPubKey(temp1)) {
return false;
}
temp1[0] = yG[k][0];
temp1[1] = yG[k][1];
if(!Secp256k1.isPubKey(temp1)) {
return false;
}
}
}
for (k=0; k<4; k++) {
temp1[0] = ab[k*4 + 0];
temp1[1] = ab[k*4 + 1];
if(!Secp256k1.isPubKey(temp1)) {
return false;
}
temp1[0] = ab[k*4 + 2];
temp1[1] = ab[k*4 + 3];
if (!Secp256k1.isPubKey(temp1)) {
return false;
}
}
// Does c =? d1 + d2 (mod n)
k = addmod(params[0],addmod(params[1],params[2],nn),nn);
if(uint(sha256(msg.sender, xGyG, ab)) != addmod(k,params[3],nn)) {
return false;
}
if ((4 - comp) == 2) {
temp3[0] = G[0];
temp3[1] = G[1];
temp3[2] = 1;
temp3 = Secp256k1._double(temp3);
} else if (comp == 0) {
temp3 = Secp256k1._mul((uint)(4 - comp - 1), G);
temp3 = Secp256k1._addMixed(temp3, G);
} else {
temp3 = Secp256k1._mul((uint)(4 - comp), G);
}
ECCMath.toZ1(temp3, pp);
i[1] = temp3[0];
i[2] = pp - temp3[1];
for (k=0; k<4; k++) {
// a1 =? g^{r1} * x^{d1}
temp2 = Secp256k1._mul(params[k + 4], G);
temp3 = Secp256k1._add(temp2, Secp256k1._mul(params[k + 0], xG[k]));
ECCMath.toZ1(temp3, pp);
if((ab[k*4 + 0] != temp3[0]) || (ab[k*4 + 1] != temp3[1])) {
return false;
}
//b1 =? h^{r1} * y^{d1} (temp = affine 'y')
temp3[0] = i[1];
temp3[1] = i[2];
temp3[2] = 1;
// y-g
temp1[0] = xGyG[k*4 + 2];
temp1[1] = xGyG[k*4 + 3];
temp3 = Secp256k1._addMixed(temp3,temp1);
ECCMath.toZ1(temp3, pp);
temp1[0] = temp3[0];
temp1[1] = temp3[1];
temp2 = Secp256k1._mul(params[k + 4],yG[k]);
temp3 = Secp256k1._add(temp2, Secp256k1._mul(params[k + 0], temp1));
ECCMath.toZ1(temp3, pp);
if(ab[k*4 + 2] != temp3[0] || ab[k*4 + 3] != temp3[1]) {
return false;
}
}
return true;
}
} |
$(document).ready(function() {
var games = ["Final Fantasy", "Legend of Zelda", "Fallout", "Super Mario", "Metal Gear Solid", "Pacman", "Tetris", "Call of Duty", "Bowling", "Badminton"];
// This will display the buttons for each game category
function displayGifButtons() {
for (var i = 0; i < games.length; i++) {
var gifButton = $("<button>");
gifButton.addClass("game");
gifButton.addClass("btn btn-primary");
gifButton.attr("data-name", games[i]);
gifButton.text(games[i]);
$("#gifButtonsView").append(gifButton);
}
}
// This section is for adding the new button
function addNewButton() {
$("#addGif").on("click", function() {
var game = $("#game-input").val().trim();
games.push(game);
displayGifButtons();
return false;
});
}
// This section to get gifs from giphy api and then display the gifs
function displayGifs() {
var game = $(this).attr("data-name");
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + game + "&api_key=dc6zaTOxFJmzC&limit=10";
console.log(queryURL);
$.ajax({
url: queryURL,
method: 'GET'
})
.done(function(response) {
console.log(response);
$("#gifsView").empty();
var results = response.data;
for (var i=0; i<results.length; i++){
var gifDiv = $("<div>");
var gifRating = $("<p>").text("Rating: " + results[i].rating);
gifDiv.append(gifRating);
var gifImage = $("<img>");
gifImage.attr("src", results[i].images.fixed_height_small_still.url);
gifImage.attr("data-still",results[i].images.fixed_height_small_still.url);
gifImage.attr("data-animate",results[i].images.fixed_height_small.url);
gifImage.attr("data-state", "still");
gifImage.addClass("image");
gifDiv.append(gifImage);
$("#gifsView").prepend(gifDiv);
}
});
}
$(document).on("click", ".game", displayGifs);
displayGifButtons();
addNewButton();
// This will make the buttons switch between animated or still
$(document).on("click", ".image", function() {
var state = $(this).attr('data-state');
if ( state == 'still'){
$(this).attr('src', $(this).data('animate'));
$(this).attr('data-state', 'animate'); }
else {
$(this).attr('src', $(this).data('still'));
$(this).attr('data-state', 'still');
}
});
}); |
= distinctBy
// * <<distinctby1>>
// * <<distinctby2>>
[[distinctby1]]
===== distinctBy(Array <T>,(item:T,index:Number) - > Any):Array <T>
仅返回数组中可能有重复项的唯一值。
使用两个参数调用lambda:`value`和`index`。
如果这些参数未定义,则默认将该索引定义为`$$`,并将该值定义为`$`。
。转变
[source,DataWeave, linenums]
----
%dw 2.0
output application/json
---
{
book : {
title : payload.title,
year: payload.year,
authors: payload.author distinctBy $
}
}
----
。输入
[source,JSON,linenums]
----
{
"title": "XQuery Kick Start",
"author": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Kurt Cagle",
"Kurt Cagle",
"Kurt Cagle",
"Vaidyanathan Nagarajan"
],
"year":"2000"
}
----
.OUTPUT
[source,JSON,linenums]
----
{
"book": {
"title": "XQuery Kick Start",
"year": "2000",
"authors": [
"James McGovern",
"Per Bothner",
"Kurt Cagle",
"James Linn",
"Vaidyanathan Nagarajan"
]
}
}
----
[[distinctby2]]
===== distinctBy({(K)?:V},(value:V,key:K) - > Any):Object
用不同的键值对返回一个对象。
该函数(lambda)使用两个参数调用:`value`和`key`。
如果这些参数没有定义,则索引默认定义为`$$`
值为`$``。
。转变
[source,DataWeave, linenums]
----
%dw 2.0
output application/xml
---
{
book : {
title : payload.book.title,
authors: payload.book.&author distinctBy $
}
}
----
。输入
[source,XML,linenums]
----
<book>
<title> "XQuery Kick Start"</title>
<author>
James Linn
</author>
<author>
Per Bothner
</author>
<author>
James McGovern
</author>
<author>
James McGovern
</author>
<author>
James McGovern
</author>
</book>
----
.OUTPUT
[source,XML,linenums]
----
<book>
<title> "XQuery Kick Start"</title>
<authors>
<author>
James Linn
</author>
<author>
Per Bothner
</author>
<author>
James McGovern
</author>
</authors>
</book>
---- |
package com.heshan.androidcoroutines
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
// These are ways of creating coroutines
// These act as link between the suspending & non-suspending code
// There are 3 main
fun main() {
// runBlocking is a coroutine builder that blocks the current thread,
// until all tasks of the coroutine it creates.
// usually used in tests, where we need to complete test with out any interference
runBlocking {
launch {
delay(4000)
println("RunBlocking")
}
}
} |
<!DOCTYPE html>
<html data-require="math math-format">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>פיתרון משוואה ריבועית על ידי הוצעת שורש</title>
<script src="../khan-exercise.js"></script>
<style type="text/css">
#answer_area input[type=text] {
width: 50px;
}
</style>
</head>
<body>
<div class="exercise">
<div class="problems">
<div id="solve">
<div class="vars">
<var id="H">randRangeNonZero( -10, 10 )</var>
<var id="CONSTANT">randRange( 1, 9 )</var>
<var id="K">-( CONSTANT * CONSTANT )</var>
</div>
<p class="problem">פתור עבור <code>x</code>:</p>
<p class="question"><code>(x - <var>H</var>)^2 + <var>K</var> = 0</code></p>
<div class="solution" data-type="set">
<div class="set-sol"><var>H + CONSTANT</var></div>
<div class="set-sol"><var>H - CONSTANT</var></div>
<div class="input-format">
<p><code>x = \quad</code><span class="entry"></span><code>\quad \text{or} \quad x = \quad</code><span class="entry"></span></p>
</div>
<p class="example">integers, like <code>6</code></p>
<p class="example"><em>simplified proper</em> fractions, like <code>3/5</code></p>
<p class="example"><em>simplified improper</em> fractions, like <code>7/4</code></p>
<p class="example">and/or <em>exact</em> decimals, like <code>0.75</code></p>
</div>
<div class="hints">
<div>
<p>הוסף <code><var>abs( K )</var></code> כך שנוכל לבודד את <code>x</code> לצד שמאל:</p>
<p><code>\qquad (x - <var>H</var>)^2 = <var>-K</var></code></p>
</div>
<div>
<p>העלו בשורש על שני צדדי המשוואה ככה שנפתר מהחזקה.</p>
<p><code>\qquad \sqrt{(x - <var>H</var>)^2} = \pm \sqrt{<var>-K</var>}</code></p>
</div>
<div>
<p>
היה בטוח להתחשב שהפיתרון הינו <code><var>CONSTANT</var></code> חיובי ושלילי, בגלל שהריבוע מבטל סימן מינוס.
</p>
<p><code>\qquad x - <var>H</var> = \pm <var>CONSTANT</var></code></p>
</div>
<div>
<p>
<span data-if="H > 0">הוסף <code><var>abs( H )</var></code> לשני הצדדים כדי לבודד את <code>x</code> בשמאל :</span>
<span data-else> חסר <code><var>abs( H )</var></code> משני הצדדים כדי לבודד את <code>x</code> בשמאל :</span>
</p>
<p><code>\qquad x = <var>H</var> \pm <var>CONSTANT</var></code></p>
</div>
<div>
<p class="final_answer">והוסף וחסר את <code><var>CONSTANT</var></code> כדי למצוא שני תשובות אפשריות:</p>
<p><code>\qquad x = <var>H + CONSTANT</var> \quad \text{or} \quad x = <var>H - CONSTANT</var></code></p>
</div>
</div>
</div>
<div id="intersect" data-type="solve">
<p class="problem">קבע איפה <code>f(x)</code> נחתך עם ציר ה<code>x</code>.</p>
<p class="question"><code>f(x) = (x - <var>H</var>)^2 + <var>K</var></code></p>
<div class="hints" data-apply="prependContents">
<div>
<p>הפונקציה חותכת עם ציר ה<code>x</code>איפה ש <code>f(x) = 0</code>, אז יש לפתור את המשוואה:</p>
<p><code>\qquad (x - <var>H</var>)^2 + <var>K</var> = 0</code></p>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
abstract class SolicitacaoEmprestimo {
static emprestimos: Array<SolicitacaoEmprestimo> = [];
static add(emprestimo: SolicitacaoEmprestimo) {
this.emprestimos.push(emprestimo);
}
abstract verificarAprovacao(): boolean;
static processarSolicitacoes() {
const aprovados: string[] = [];
const reprovados: string[] = [];
for (const emprestimo of this.emprestimos) {
if (emprestimo.verificarAprovacao()) {
aprovados.push(`${emprestimo.nome} [APROVADO]`);
} else {
reprovados.push(`${emprestimo.nome} [REPROVADO]`);
}
}
console.log("Solicitações Aprovadas:");
console.log(aprovados.join("\n"));
console.log("\nSolicitações Reprovadas:");
console.log(reprovados.join("\n"));
}
constructor(protected nome: string,
protected idade: number,
protected valorEmprestimo: number,
protected quantidadeParcelas: number,
protected valorParcela: number,
protected rendaMensal: number,
protected possuiHabilitacao: boolean,
protected matriculaCursoSuperior: boolean){}
}
export default SolicitacaoEmprestimo; |
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import apiBack from "../../services/apiBack";
import { toast } from "react-toastify";
export default function AlterarProduto() {
const { id } = useParams();
const [listaProduto, setListaProduto] = useState("");
const [alteraNome, setAlteraNome] = useState("");
const [alteraFabricante, setAlteraFabricante] = useState("");
const [alteraQuantidade, setAlteraQuantidade] = useState("");
const [alteraPreco, setAlteraPreco] = useState("");
useEffect(() => {
async function listaProduto() {
const resposta = await apiBack.get(`/ListarProdutoUnico/${id}`);
setListaProduto(resposta.data);
}
listaProduto();
}, []);
useEffect(() => {
setAlteraNome(listaProduto.nome);
setAlteraFabricante(listaProduto.fabricante);
setAlteraQuantidade(listaProduto.quantidade);
setAlteraPreco(listaProduto.preco);
}, [listaProduto]);
async function AlterarProduto(e) {
e.preventDefault();
const resposta = await apiBack.put(`/AlterarProduto`, {
id,
alteraNome,
alteraFabricante,
alteraQuantidade,
alteraPreco,
});
toast.info(resposta.data.dados);
}
return (
<div>
<h1>Alterar Produto</h1>
<div>
<form onSubmit={AlterarProduto}>
<label>Nome: </label>
<input
type="text"
value={alteraNome}
onChange={(e) => setAlteraNome(e.target.value)}
/>
<br />
<label>Fabricante: </label>
<input
type="text"
value={alteraFabricante}
onChange={(e) => setAlteraFabricante(e.target.value)}
/>
<br />
<label>Quantidade: </label>
<input
type="text"
value={alteraQuantidade}
onChange={(e) => setAlteraQuantidade(e.target.value)}
/>
<br />
<label>Preco: </label>
<input
type="text"
value={alteraPreco}
onChange={(e) => setAlteraPreco(e.target.value)}
/>
<button type="submit">Enviar</button>
</form>
</div>
</div>
);
} |
---
title: some_Knowledge_point
date: 2021-12-17 11:33:17
categories:
- JAVA
tags:
- Serializable
- Cloneable
- Comparable
- Comparator
author: Fanrencli
---
### Lambda
- 实现一个接口的方法函数,接口只能有一个函数;
```java
interface IMessage{
public int add(int x, int y);
}
public class Demo{
public static void main(String[] args){
IMessage msg = (s,y) -> a+b;
}
}
```
### 序列化(Serializable)
- `Serializable`作为序列化的标识接口没有实现任何方法
- `transient`关键字作为防止序列化的关键字,能够使数据不被序列化
- `ObjectOutputStream`和 `ObjectInputStream`简易的实现了对象的序列化和反序列化操作
```java
class B implements Serializable{
private transient int a=1;
private String title = "asd";
}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("test.txt")));
oos.writeObject(new B());
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("test.txt")));
Object obj = ois.readObject();
ois.close();
}
}
```
### 克隆(Cloneable)
- `Cloneable`作为标识接口不做任何方法的实现,表示类可以被克隆
```java
class Book implements Cloneable{
private String title;
private double price;
public Book(String title, double price){
this.title = title;
this.price = price;
}
public getTitle() { return title; }
public setTitle(String title) {this.title = title; }
public getPrice() { return price; }
public setPrice(double price) {this.price = price; }
@Override
public object clone() throws ClassNotFoundException{
return super.clone();
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book("java",22.2);
Book book2 = (Book) book1.clone();
}
}
```
### 比较器(Comparable/Comparator)
- `Comparable`是一个接口类,通过在定义类的时候实现接口函数来实现对象的比较,常用于集合中排序
- `Comparator`是一个比较的工具接口,用于对已经实现完成的类进行比较
```java
public interface Comparable<T>{
public itn compareTo(T o);
}
class Book implements Comparable<Book> {
private String title;
private double price;
public Book(String title, double price){
this.title = title;
this.price = price;
}
public getTitle() { return title; }
public setTitle(String title) {this.title = title; }
public getPrice() { return price; }
public setPrice(double price) {this.price = price; }
@Override
public int compare(Book value1, Book value2){
if(value.getPrice() > value2.getPrice()){
return 1;
}else if(value1.getPrice() < value2.getPrice()){
return -1;
}esle{
return 0;
}
}
}
public class Demo{
public static void main(String args[]){
Book books[] = new Book[]{ new Book("java",99.5),new Book("git",99.4),new Book("SVN",55.6)};
Arrays.sort(books)
}
}
```
```java
@FunctionalInterface
public interface Comparator<T>{
public int compare(T value1, T value);
public boolean equals(Object obj);
}
class Book{
private String title;
private double price;
public Book(String title, double price){
this.title = title;
this.price = price;
}
public getTitle() { return title; }
public setTitle(String title) {this.title = title; }
public getPrice() { return price; }
public setPrice(double price) {this.price = price; }
}
class BookComparator implements Comparator<Book>{
@Override
public int compare(Book value1, Book value2){
if(value.getPrice() > value2.getPrice()){
return 1;
}else if(value1.getPrice() < value2.getPrice()){
return -1;
}esle{
return 0;
}
}
}
public class Demo{
public static void main(String args[]){
Book books[] = new Book[]{ new Book("java",99.5),new Book("git",99.4),new Book("SVN",55.6)};
Arrays.sort(books,new BookComparator())
}
}
```
### 方法引用
- 引用静态方法:类名::static方法名称
- 引用某个对象的方法:实例化对象::普通方法
- 引用特定类型的方法:特定类:: 普通方法
- 引用构造方法:类名称:: new
- 方法引用的接收接口只能实现一个方法,这就引出了`@FunctionalInterface`所定义的四种接口
- 功能型接口:`public interface Fcuntion<T,R> {public R apply(T t)}`
- 消费型接口:`public interface Consumer<T> {public void accept(T t)}`
- 供给型接口:`public interface Supplier<T> {public T get()}`
- 断言型接口: `public interface Predicate<T> {public boolean apply(T t)}`
```java
@FunctionalInterface
interface IMessage<P,R>{
public R zhuanhuan(P p);
}
public class Main {
public static void main(String[] args) {
IMessage<Integer,String> msg = String::valueOf;
System.out.println(msg.zhuanhuan(1000));
}
}
```
```java
@FunctionalInterface
interface IMessage<R>{
public R upper();
}
public class Main {
public static void main(String[] args) {
IMessage<String> msg = "hello"::toUpperCase;
System.out.println(msg.upper());
}
}
```
```java
@FunctionalInterface
interface IMessage<P>{
public int compare(P p1, P p2);
}
public class Main {
public static void main(String[] args) {
IMessage<String> msg = String:: compareTo;
System.out.println(msg.compare("A", "B"));
}
}
```
```java
@FunctionalInterface
interface IMessage<P>{
public P create(String title,double price);
}
class Book{
private String title;
private double price;
public Book(String title, double price){
this.title = title;
this.price = price;
}
public getTitle() { return title; }
public setTitle(String title) {this.title = title; }
public getPrice() { return price; }
public setPrice(double price) {this.price = price; }
}
public class Main {
public static void main(String[] args) {
IMessage<Book> msg = Book :: new;
System.out.println(msg.create("java", 20.2));
}
}
```
### 泛型
```java
public class B<T>{
private T b;
// 这个不是泛型方法
public T getB() {
return this.b;
}
public void set(B<? extends > b) {
}
// 这个才是泛型方法
public <S> S get(S str){
return str;
}
}
public class B<T extends Number>{
private T b;
// 这个不是泛型方法
public T getB() {
return this.b;
}
// 这个才是泛型方法
public <S> S get(S str){
return str;
}
}
``` |
package org.meveo.service.notification;
import org.meveo.cache.NotificationCacheContainerProvider;
import org.meveo.commons.utils.ReflectionUtils;
import org.meveo.model.AuditableEntity;
import org.meveo.model.BaseEntity;
import org.meveo.model.BusinessCFEntity;
import org.meveo.model.BusinessEntity;
import org.meveo.model.notification.Notification;
import org.meveo.model.notification.NotificationEventTypeEnum;
import org.meveo.service.base.BusinessService;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
/**
* @author Tyshan Shi(tyshan@manaty.net)
* @author Abdellatif BARI
* @lastModifiedVersion 7.0
*/
@Stateless
public class GenericNotificationService extends BusinessService<Notification> {
@Inject
private NotificationCacheContainerProvider notificationCacheContainerProvider;
static boolean useNotificationCache = true;
@PostConstruct
private void init() {
useNotificationCache = Boolean.parseBoolean(paramBeanFactory.getInstance().getProperty("cache.cacheNotification", "true"));
}
/**
* Get a list of notifications that match event type and entity class. Notifications are looked up from cache or retrieved from DB.
*
* @param eventType Event type
* @param entityOrEvent Entity involved or event containing the entity involved
* @return A list of notifications
*/
public List<Notification> getApplicableNotifications(NotificationEventTypeEnum eventType, Object entityOrEvent) {
if (useNotificationCache) {
List<Notification> notifications = notificationCacheContainerProvider.getApplicableNotifications(eventType, entityOrEvent);
// Populate cache if no record was found in cache
if (notifications == null) {
notifications = getApplicableNotificationsNoCache(eventType, entityOrEvent);
if (notifications.isEmpty()) {
notificationCacheContainerProvider.markNoNotifications(eventType, entityOrEvent);
} else {
notifications.forEach((notification) -> notificationCacheContainerProvider.addNotificationToCache(notification));
}
}
return notifications;
} else {
return getApplicableNotificationsNoCache(eventType, entityOrEvent);
}
}
/**
* Get a list of notifications that match event type and entity class - always do a lookup in DB
*
* @param eventType Event type
* @param entityOrEvent Entity involved or event containing the entity involved
* @return A list of notifications
*/
@SuppressWarnings("unchecked")
public List<Notification> getApplicableNotificationsNoCache(NotificationEventTypeEnum eventType, Object entityOrEvent) {
Object entity = notificationCacheContainerProvider.getEntity(entityOrEvent);
@SuppressWarnings("rawtypes")
Class entityClass = entity.getClass();
List<String> classNames = new ArrayList<>();
while (!entityClass.isAssignableFrom(BusinessCFEntity.class) && !entityClass.isAssignableFrom(BusinessEntity.class) && !entityClass.isAssignableFrom(BaseEntity.class)
&& !entityClass.isAssignableFrom(AuditableEntity.class) && !entityClass.isAssignableFrom(Object.class)) {
classNames.add(ReflectionUtils.getCleanClassName(entityClass.getName()));
entityClass = entityClass.getSuperclass();
}
return getEntityManager().createNamedQuery("Notification.getActiveNotificationsByEventAndClasses", Notification.class).setParameter("eventTypeFilter", eventType)
.setParameter("classNameFilter", classNames).getResultList();
}
/**
* Get a list of notifications to populate a cache
*
* @return A list of active notifications
*/
public List<Notification> getNotificationsForCache() {
return getEntityManager().createNamedQuery("Notification.getNotificationsForCache", Notification.class).getResultList();
}
} |
const db = require("../models");
const Historial = db.Historial;
const Usuario = db.Usuario;
const Carretera = db.Carretera;
const Municipio = db.Municipio;
const Incidente = db.Incidente;
const { Op } = require("sequelize");
exports.obtenerHistorial = async (req, res) => {
try {
const { entidad, accion, fechaInicio, fechaFin, limite = 50, pagina = 1 } = req.query;
const limit = parseInt(limite);
const offset = (parseInt(pagina) - 1) * limit;
const where = {};
if (entidad) {
where.entidad_afectada = entidad;
}
if (accion) {
where.accion = accion;
}
if (fechaInicio && fechaFin) {
where.fecha = {
[Op.between]: [new Date(fechaInicio), new Date(fechaFin)]
};
}
const historial = await Historial.findAndCountAll({
where,
order: [['fecha', 'DESC']],
limit,
offset,
include: [
{
model: Usuario,
as: 'usuario',
attributes: ['nombre'],
}
]
});
const historialConNombreUsuario = historial.rows.map(item => ({
...item.dataValues,
nombre_usuario: item.usuario ? item.usuario.nombre : 'Desconocido'
}));
res.status(200).json({
total: historial.count,
paginas: Math.ceil(historial.count / limit),
pagina: parseInt(pagina),
historial: historialConNombreUsuario
});
} catch (error) {
console.error(`Error en obtenerHistorial: ${error.message}`, error);
res.status(500).json({ msg: "Error interno al obtener el historial." });
}
};
exports.obtenerUsuariosPorCambio = async (req, res) => {
try {
const { entidad } = req.query;
let entidades = [];
if (entidad === 'carretera') {
entidades = await Carretera.findAll({
include: [{
model: Historial,
as: 'historiales',
include: [{
model: Usuario,
as: 'usuario',
attributes: ['nombre']
}],
where: { accion: 'edición' },
order: [['fecha', 'DESC']]
}],
order: [['id_carretera', 'DESC']]
});
} else if (entidad === 'municipio') {
entidades = await Municipio.findAll({
include: [{
model: Historial,
as: 'historiales',
include: [{
model: Usuario,
as: 'usuario',
attributes: ['nombre']
}],
where: { accion: 'edición' },
order: [['fecha', 'DESC']]
}],
order: [['id_municipio', 'DESC']]
});
} else if (entidad === 'incidente') {
entidades = await Incidente.findAll({
include: [{
model: Historial,
as: 'historiales',
include: [{
model: Usuario,
as: 'usuario',
attributes: ['nombre']
}],
where: { accion: 'edición' },
order: [['fecha', 'DESC']]
}],
order: [['id_incidente', 'DESC']]
});
}
const usuariosQueRealizaronCambios = entidades.map(entidad => {
return {
id_entidad: entidad.id_carretera || entidad.id_municipio || entidad.id_incidente,
nombre_usuario: entidad.historiales.length > 0 ? entidad.historiales[0].usuario.nombre : 'Desconocido',
entidad_afectada: entidad.constructor.name.toLowerCase()
};
});
res.status(200).json({
usuarios: usuariosQueRealizaronCambios
});
} catch (error) {
console.error(`Error en obtenerUsuariosPorCambio: ${error.message}`, error);
res.status(500).json({ msg: "Error interno al obtener los usuarios que realizaron cambios." });
}
}; |
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "c8891c90",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"+-------+-----------+-------------------+\n",
"|user_id|device_type|view_time |\n",
"+-------+-----------+-------------------+\n",
"|123 |tablet |01/02/2022 00:00:00|\n",
"|125 |laptop |01/07/2022 00:00:00|\n",
"|128 |laptop |02/09/2022 00:00:00|\n",
"|129 |phone |02/09/2022 00:00:00|\n",
"|145 |tablet |02/24/2022 00:00:00|\n",
"+-------+-----------+-------------------+\n",
"\n"
]
},
{
"data": {
"text/plain": [
"import org.apache.spark.sql.functions._\n",
"import org.apache.spark.sql.types.{StructType, StructField, IntegerType, StringType}\n",
"import org.apache.spark.sql.Row\n",
"import org.apache.spark.sql.expressions.Window\n",
"data: Seq[org.apache.spark.sql.Row] = List([123,tablet,01/02/2022 00:00:00], [125,laptop,01/07/2022 00:00:00], [128,laptop,02/09/2022 00:00:00], [129,phone,02/09/2022 00:00:00], [145,tablet,02/24/2022 00:00:00])\n",
"schema: org.apache.spark.sql.types.StructType = StructType(StructField(user_id,IntegerType,true),StructField(device_type,StringType,true),StructField(view_time,StringType,true))\n",
"rdd: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = ParallelCollectionRDD[0] at parallelize at <console>:64\n",
"df: org.apache.spark.sql.DataFrame = [user_id: int, device_type: string ... 1 more field]\n"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"// Assume you're given the table on user viewership categorised by device type where the three types are laptop, tablet, and phone.\n",
"\n",
"// Write a query that calculates the total viewership for laptops and mobile devices where mobile is defined as the sum of tablet and phone viewership. \n",
"// Output the total viewership for laptops as laptop_reviews and the total viewership for mobile devices as mobile_views.\n",
"\n",
"// Effective 15 April 2023, the solution has been updated with a more concise and easy-to-understand approach.\n",
"\n",
"// Example Output\n",
"// ----------------------------\n",
"// laptop_views | mobile_views\n",
"// -------------|--------------\n",
"// 2 | 3\n",
"// ----------------------------\n",
"\n",
"// Explanation\n",
"// Based on the example input, there are a total of 2 laptop views and 3 mobile views.\n",
"\n",
"// The dataset you are querying against may have different input & output - this is just an example!\n",
"\n",
"\n",
"import org.apache.spark.sql.functions._\n",
"import org.apache.spark.sql.types.{StructType, StructField, IntegerType, StringType}\n",
"import org.apache.spark.sql.Row\n",
"import org.apache.spark.sql.expressions.Window\n",
"\n",
"\n",
"\n",
"val data = Seq(\n",
" Row(123,\"tablet\",\"01/02/2022 00:00:00\"),\n",
" Row(125,\"laptop\",\"01/07/2022 00:00:00\"),\n",
" Row(128,\"laptop\",\"02/09/2022 00:00:00\"),\n",
" Row(129,\"phone\",\"02/09/2022 00:00:00\"),\n",
" Row(145,\"tablet\",\"02/24/2022 00:00:00\")\n",
")\n",
"\n",
"val schema = StructType(Array(\n",
" StructField(\"user_id\", IntegerType),\n",
" StructField(\"device_type\", StringType),\n",
" StructField(\"view_time\", StringType)\n",
"))\n",
"\n",
"val rdd = spark.sparkContext.parallelize(data)\n",
"val df = spark.createDataFrame(rdd, schema)\n",
"\n",
"df.show(false)\n"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "48c0d056",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Using Dataframes -------- \n",
"== Physical Plan ==\n",
"AdaptiveSparkPlan isFinalPlan=false\n",
"+- HashAggregate(keys=[device_type#347], functions=[count(1)])\n",
" +- Exchange hashpartitioning(device_type#347, 200), ENSURE_REQUIREMENTS, [plan_id=865]\n",
" +- HashAggregate(keys=[device_type#347], functions=[partial_count(1)])\n",
" +- Project [CASE WHEN (device_type#4 = tablet) THEN phone WHEN (device_type#4 = phone) THEN phone ELSE laptop END AS device_type#347]\n",
" +- Scan ExistingRDD[user_id#3,device_type#4,view_time#5]\n",
"\n",
"\n",
"+------------+-----+\n",
"|device_type |count|\n",
"+------------+-----+\n",
"|phone_views |3 |\n",
"|laptop_views|2 |\n",
"+------------+-----+\n",
"\n"
]
},
{
"data": {
"text/plain": [
"import org.apache.spark.sql.expressions.Window\n",
"df1: org.apache.spark.sql.DataFrame = [device_type: string, count: bigint]\n"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import org.apache.spark.sql.expressions.Window\n",
"\n",
"println(\"Using Dataframes -------- \")\n",
"\n",
"val df1 = df.withColumn(\"device_type\", when($\"device_type\" === lit(\"tablet\"), lit(\"phone\")\n",
" ).when($\"device_type\" === lit(\"phone\"), lit(\"phone\")).otherwise(\"laptop\")\n",
" ).groupBy($\"device_type\").count().withColumn(\"device_type\", concat($\"device_type\", lit(\"_views\")))\n",
"\n",
"\n",
"df1.explain()\n",
"df1.show(false)\n"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "7ea2be29",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Using Spark SQL -------- \n",
"== Physical Plan ==\n",
"AdaptiveSparkPlan isFinalPlan=false\n",
"+- HashAggregate(keys=[], functions=[sum(CASE WHEN (device_type#289 = laptop) THEN 1 ELSE 0 END), sum(CASE WHEN ((device_type#289 = tablet) OR (device_type#289 = phone)) THEN 1 ELSE 0 END)])\n",
" +- Exchange SinglePartition, ENSURE_REQUIREMENTS, [plan_id=1329]\n",
" +- HashAggregate(keys=[], functions=[partial_sum(CASE WHEN (device_type#289 = laptop) THEN 1 ELSE 0 END), partial_sum(CASE WHEN ((device_type#289 = tablet) OR (device_type#289 = phone)) THEN 1 ELSE 0 END)])\n",
" +- Project [device_type#289]\n",
" +- Scan ExistingRDD[user_id#288,device_type#289,view_time#290]\n",
"\n",
"\n",
"+------------+------------+\n",
"|laptop_views|mobile_views|\n",
"+------------+------------+\n",
"|2 |3 |\n",
"+------------+------------+\n",
"\n"
]
},
{
"data": {
"text/plain": [
"df2: org.apache.spark.sql.DataFrame = [laptop_views: bigint, mobile_views: bigint]\n"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"println(\"Using Spark SQL -------- \")\n",
"\n",
"df.createOrReplaceTempView(\"viewership\")\n",
"\n",
"val df2 = spark.sql(\"\"\"\n",
" SELECT \n",
" SUM(CASE WHEN device_type='laptop' THEN 1 ELSE 0 END) AS laptop_views,\n",
" SUM(CASE WHEN device_type='tablet' OR device_type='phone' THEN 1 ELSE 0 END) AS mobile_views\n",
" FROM viewership\n",
"\"\"\")\n",
"\n",
"df2.explain()\n",
"df2.show(false)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0c52104e",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "spylon-kernel",
"language": "scala",
"name": "spylon-kernel"
},
"language_info": {
"codemirror_mode": "text/x-scala",
"file_extension": ".scala",
"help_links": [
{
"text": "MetaKernel Magics",
"url": "https://metakernel.readthedocs.io/en/latest/source/README.html"
}
],
"mimetype": "text/x-scala",
"name": "scala",
"pygments_lexer": "scala",
"version": "0.4.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:weather_app/cubits/get_weather_cubit/get_weather_cubit.dart';
import 'package:weather_app/cubits/get_weather_cubit/get_weather_states.dart';
import 'package:weather_app/models/weather_model.dart';
import 'package:weather_app/screens/search_view.dart';
import 'package:weather_app/widgets/no_weather_body.dart';
import 'package:weather_app/widgets/weather_info_body.dart';
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocConsumer<GetWeatherCubit, WeatherState>(
listener: (context, state) {
// TODO: implement listener
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(
title: Text(
'Home',
),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
return SearchView();
}),
);
},
icon: Icon(Icons.search),
),
],
),
body: BlocBuilder<GetWeatherCubit, WeatherState>(
builder: (context, state) {
if (state is WeatherFailureState) {
return NoWitherBody();
} else if (state is WeatherSuccessState) {
return WeatherInfoBody();
} else {
return Text('Ops, there was an error !');
}
},
),
);
},
);
}
} |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* based on tcp-socket-impl.cc, Author: Raj Bhattacharjea <raj.b@gatech.edu>
* Author: Florian Westphal <fw@strlen.de>
*/
#define NS_LOG_APPEND_CONTEXT \
if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; }
#include "ns3/node.h"
#include "ns3/inet-socket-address.h"
#include "ns3/log.h"
#include "ns3/ipv4.h"
#include "ipv4-end-point.h"
#include "nsc-tcp-l4-protocol.h"
#include "nsc-tcp-socket-impl.h"
#include "ns3/simulation-singleton.h"
#include "ns3/simulator.h"
#include "ns3/packet.h"
#include "ns3/uinteger.h"
#include "ns3/trace-source-accessor.h"
#include <algorithm>
// for ntohs().
#include <arpa/inet.h>
#include <netinet/in.h>
#include "sim_interface.h"
#include "sim_errno.h"
NS_LOG_COMPONENT_DEFINE ("NscTcpSocketImpl");
using namespace std;
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (NscTcpSocketImpl);
TypeId
NscTcpSocketImpl::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::NscTcpSocketImpl")
.SetParent<TcpSocket> ()
.AddTraceSource ("CongestionWindow",
"The TCP connection's congestion window",
MakeTraceSourceAccessor (&NscTcpSocketImpl::m_cWnd))
;
return tid;
}
NscTcpSocketImpl::NscTcpSocketImpl ()
: m_endPoint (0),
m_node (0),
m_tcp (0),
m_localAddress (Ipv4Address::GetZero ()),
m_localPort (0),
m_peerAddress ("0.0.0.0", 0),
m_errno (ERROR_NOTERROR),
m_shutdownSend (false),
m_shutdownRecv (false),
m_connected (false),
m_state (CLOSED),
m_closeOnEmpty (false),
m_txBufferSize (0),
m_lastMeasuredRtt (Seconds (0.0))
{
NS_LOG_FUNCTION (this);
}
NscTcpSocketImpl::NscTcpSocketImpl(const NscTcpSocketImpl& sock)
: TcpSocket (sock), //copy the base class callbacks
m_delAckMaxCount (sock.m_delAckMaxCount),
m_delAckTimeout (sock.m_delAckTimeout),
m_noDelay (sock.m_noDelay),
m_endPoint (0),
m_node (sock.m_node),
m_tcp (sock.m_tcp),
m_remoteAddress (sock.m_remoteAddress),
m_remotePort (sock.m_remotePort),
m_localAddress (sock.m_localAddress),
m_localPort (sock.m_localPort),
m_peerAddress (sock.m_peerAddress),
m_errno (sock.m_errno),
m_shutdownSend (sock.m_shutdownSend),
m_shutdownRecv (sock.m_shutdownRecv),
m_connected (sock.m_connected),
m_state (sock.m_state),
m_closeOnEmpty (sock.m_closeOnEmpty),
m_txBufferSize (sock.m_txBufferSize),
m_segmentSize (sock.m_segmentSize),
m_rxWindowSize (sock.m_rxWindowSize),
m_advertisedWindowSize (sock.m_advertisedWindowSize),
m_cWnd (sock.m_cWnd),
m_ssThresh (sock.m_ssThresh),
m_initialCWnd (sock.m_initialCWnd),
m_lastMeasuredRtt (Seconds (0.0)),
m_cnTimeout (sock.m_cnTimeout),
m_cnCount (sock.m_cnCount),
m_rxAvailable (0),
m_nscTcpSocket (0),
m_sndBufSize (sock.m_sndBufSize)
{
NS_LOG_FUNCTION_NOARGS ();
NS_LOG_LOGIC ("Invoked the copy constructor");
//copy the pending data if necessary
if(!sock.m_txBuffer.empty () )
{
m_txBuffer = sock.m_txBuffer;
}
//can't "copy" the endpoint just yes, must do this when we know the peer info
//too; this is in SYN_ACK_TX
}
NscTcpSocketImpl::~NscTcpSocketImpl ()
{
NS_LOG_FUNCTION (this);
m_node = 0;
if (m_endPoint != 0)
{
NS_ASSERT (m_tcp != 0);
/**
* Note that this piece of code is a bit tricky:
* when DeAllocate is called, it will call into
* Ipv4EndPointDemux::Deallocate which triggers
* a delete of the associated endPoint which triggers
* in turn a call to the method NscTcpSocketImpl::Destroy below
* will will zero the m_endPoint field.
*/
NS_ASSERT (m_endPoint != 0);
m_tcp->DeAllocate (m_endPoint);
NS_ASSERT (m_endPoint == 0);
}
m_tcp = 0;
}
void
NscTcpSocketImpl::SetNode (Ptr<Node> node)
{
m_node = node;
// Initialize some variables
m_cWnd = m_initialCWnd * m_segmentSize;
m_rxWindowSize = m_advertisedWindowSize;
}
void
NscTcpSocketImpl::SetTcp (Ptr<NscTcpL4Protocol> tcp)
{
m_nscTcpSocket = tcp->m_nscStack->new_tcp_socket ();
m_tcp = tcp;
}
enum Socket::SocketErrno
NscTcpSocketImpl::GetErrno (void) const
{
NS_LOG_FUNCTION_NOARGS ();
return m_errno;
}
enum Socket::SocketType
NscTcpSocketImpl::GetSocketType (void) const
{
return NS3_SOCK_STREAM;
}
Ptr<Node>
NscTcpSocketImpl::GetNode (void) const
{
NS_LOG_FUNCTION_NOARGS ();
return m_node;
}
void
NscTcpSocketImpl::Destroy (void)
{
NS_LOG_FUNCTION_NOARGS ();
m_node = 0;
m_endPoint = 0;
m_tcp = 0;
}
int
NscTcpSocketImpl::FinishBind (void)
{
NS_LOG_FUNCTION_NOARGS ();
if (m_endPoint == 0)
{
return -1;
}
m_endPoint->SetRxCallback (MakeCallback (&NscTcpSocketImpl::ForwardUp, Ptr<NscTcpSocketImpl>(this)));
m_endPoint->SetDestroyCallback (MakeCallback (&NscTcpSocketImpl::Destroy, Ptr<NscTcpSocketImpl>(this)));
m_localAddress = m_endPoint->GetLocalAddress ();
m_localPort = m_endPoint->GetLocalPort ();
return 0;
}
int
NscTcpSocketImpl::Bind (void)
{
NS_LOG_FUNCTION_NOARGS ();
m_endPoint = m_tcp->Allocate ();
return FinishBind ();
}
int
NscTcpSocketImpl::Bind (const Address &address)
{
NS_LOG_FUNCTION (this<<address);
if (!InetSocketAddress::IsMatchingType (address))
{
return ERROR_INVAL;
}
InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
Ipv4Address ipv4 = transport.GetIpv4 ();
uint16_t port = transport.GetPort ();
if (ipv4 == Ipv4Address::GetAny () && port == 0)
{
m_endPoint = m_tcp->Allocate ();
NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
}
else if (ipv4 == Ipv4Address::GetAny () && port != 0)
{
m_endPoint = m_tcp->Allocate (port);
NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
}
else if (ipv4 != Ipv4Address::GetAny () && port == 0)
{
m_endPoint = m_tcp->Allocate (ipv4);
NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
}
else if (ipv4 != Ipv4Address::GetAny () && port != 0)
{
m_endPoint = m_tcp->Allocate (ipv4, port);
NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
}
m_localPort = port;
return FinishBind ();
}
int
NscTcpSocketImpl::ShutdownSend (void)
{
NS_LOG_FUNCTION_NOARGS ();
m_shutdownSend = true;
return 0;
}
int
NscTcpSocketImpl::ShutdownRecv (void)
{
NS_LOG_FUNCTION_NOARGS ();
m_shutdownRecv = true;
return 0;
}
int
NscTcpSocketImpl::Close (void)
{
NS_LOG_FUNCTION (this << m_state);
if (m_state == CLOSED)
{
return -1;
}
if (!m_txBuffer.empty ())
{ // App close with pending data must wait until all data transmitted
m_closeOnEmpty = true;
NS_LOG_LOGIC ("Socket " << this <<
" deferring close, state " << m_state);
return 0;
}
NS_LOG_LOGIC ("NscTcp socket " << this << " calling disconnect(); moving to CLOSED");
m_nscTcpSocket->disconnect ();
m_state = CLOSED;
ShutdownSend ();
return 0;
}
int
NscTcpSocketImpl::Connect (const Address & address)
{
NS_LOG_FUNCTION (this << address);
if (m_endPoint == 0)
{
if (Bind () == -1)
{
NS_ASSERT (m_endPoint == 0);
return -1;
}
NS_ASSERT (m_endPoint != 0);
}
InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
m_remoteAddress = transport.GetIpv4 ();
m_remotePort = transport.GetPort ();
std::ostringstream ss;
m_remoteAddress.Print (ss);
std::string ipstring = ss.str ();
m_nscTcpSocket->connect (ipstring.c_str (), m_remotePort);
m_state = SYN_SENT;
return 0;
}
int
NscTcpSocketImpl::Send (const Ptr<Packet> p, uint32_t flags)
{
NS_LOG_FUNCTION (this << p);
NS_ASSERT (p->GetSize () > 0);
if (m_state == ESTABLISHED || m_state == SYN_SENT || m_state == CLOSE_WAIT)
{
if (p->GetSize () > GetTxAvailable ())
{
m_errno = ERROR_MSGSIZE;
return -1;
}
uint32_t sent = p->GetSize ();
if (m_state == ESTABLISHED)
{
m_txBuffer.push (p);
m_txBufferSize += sent;
SendPendingData ();
}
else
{ // SYN_SET -- Queue Data
m_txBuffer.push (p);
m_txBufferSize += sent;
}
return sent;
}
else
{
m_errno = ERROR_NOTCONN;
return -1;
}
}
int
NscTcpSocketImpl::SendTo (Ptr<Packet> p, uint32_t flags, const Address &address)
{
NS_LOG_FUNCTION (this << address << p);
if (!m_connected)
{
m_errno = ERROR_NOTCONN;
return -1;
}
else
{
return Send (p, flags); //drop the address according to BSD manpages
}
}
uint32_t
NscTcpSocketImpl::GetTxAvailable (void) const
{
NS_LOG_FUNCTION_NOARGS ();
if (m_txBufferSize != 0)
{
NS_ASSERT (m_txBufferSize <= m_sndBufSize);
return m_sndBufSize - m_txBufferSize;
}
else
{
return m_sndBufSize;
}
}
int
NscTcpSocketImpl::Listen (void)
{
NS_LOG_FUNCTION (this);
m_nscTcpSocket->listen (m_localPort);
m_state = LISTEN;
return 0;
}
void
NscTcpSocketImpl::NSCWakeup ()
{
switch (m_state) {
case SYN_SENT:
if (!m_nscTcpSocket->is_connected ())
break;
m_state = ESTABLISHED;
Simulator::ScheduleNow (&NscTcpSocketImpl::ConnectionSucceeded, this);
// fall through to schedule read/write events
case ESTABLISHED:
if (!m_txBuffer.empty ())
Simulator::ScheduleNow (&NscTcpSocketImpl::SendPendingData, this);
Simulator::ScheduleNow (&NscTcpSocketImpl::ReadPendingData, this);
break;
case LISTEN:
Simulator::ScheduleNow (&NscTcpSocketImpl::Accept, this);
break;
case CLOSED: break;
default:
NS_LOG_DEBUG (this << " invalid state: " << m_state);
}
}
Ptr<Packet>
NscTcpSocketImpl::Recv (uint32_t maxSize, uint32_t flags)
{
NS_LOG_FUNCTION_NOARGS ();
if (m_deliveryQueue.empty () )
{
m_errno = ERROR_AGAIN;
return 0;
}
Ptr<Packet> p = m_deliveryQueue.front ();
if (p->GetSize () <= maxSize)
{
m_deliveryQueue.pop ();
m_rxAvailable -= p->GetSize ();
}
else
{
m_errno = ERROR_AGAIN;
p = 0;
}
return p;
}
Ptr<Packet>
NscTcpSocketImpl::RecvFrom (uint32_t maxSize, uint32_t flags,
Address &fromAddress)
{
NS_LOG_FUNCTION (this << maxSize << flags);
Ptr<Packet> packet = Recv (maxSize, flags);
if (packet != 0)
{
SocketAddressTag tag;
bool found;
found = packet->PeekPacketTag (tag);
NS_ASSERT (found);
// cast found to void, to suppress 'found' set but not used
// compiler warning in optimized builds
(void) found;
fromAddress = tag.GetAddress ();
}
return packet;
}
int
NscTcpSocketImpl::GetSockName (Address &address) const
{
NS_LOG_FUNCTION_NOARGS ();
address = InetSocketAddress (m_localAddress, m_localPort);
return 0;
}
uint32_t
NscTcpSocketImpl::GetRxAvailable (void) const
{
NS_LOG_FUNCTION_NOARGS ();
// We separately maintain this state to avoid walking the queue
// every time this might be called
return m_rxAvailable;
}
void
NscTcpSocketImpl::ForwardUp (Ptr<Packet> packet, Ipv4Header header, uint16_t port,
Ptr<Ipv4Interface> incomingInterface)
{
NSCWakeup ();
}
void NscTcpSocketImpl::CompleteFork (void)
{
// The address pairs (m_localAddress, m_localPort, m_remoteAddress, m_remotePort)
// are bogus, but this isn't important at the moment, because
// address <-> Socket handling is done by NSC internally.
// We only need to add the new ns-3 socket to the list of sockets, so
// we use plain Allocate() instead of Allocate(m_localAddress, ... )
struct sockaddr_in sin;
size_t sin_len = sizeof(sin);
if (0 == m_nscTcpSocket->getpeername ((struct sockaddr*) &sin, &sin_len)) {
m_remotePort = ntohs (sin.sin_port);
m_remoteAddress = m_remoteAddress.Deserialize ((const uint8_t*) &sin.sin_addr);
m_peerAddress = InetSocketAddress (m_remoteAddress, m_remotePort);
}
m_endPoint = m_tcp->Allocate ();
//the cloned socket with be in listen state, so manually change state
NS_ASSERT (m_state == LISTEN);
m_state = ESTABLISHED;
sin_len = sizeof(sin);
if (0 == m_nscTcpSocket->getsockname ((struct sockaddr *) &sin, &sin_len))
m_localAddress = m_localAddress.Deserialize ((const uint8_t*) &sin.sin_addr);
NS_LOG_LOGIC ("NscTcpSocketImpl " << this << " accepted connection from "
<< m_remoteAddress << ":" << m_remotePort
<< " to " << m_localAddress << ":" << m_localPort);
//equivalent to FinishBind
m_endPoint->SetRxCallback (MakeCallback (&NscTcpSocketImpl::ForwardUp, Ptr<NscTcpSocketImpl>(this)));
m_endPoint->SetDestroyCallback (MakeCallback (&NscTcpSocketImpl::Destroy, Ptr<NscTcpSocketImpl>(this)));
NotifyNewConnectionCreated (this, m_peerAddress);
}
void NscTcpSocketImpl::ConnectionSucceeded ()
{ // We would preferred to have scheduled an event directly to
// NotifyConnectionSucceeded, but (sigh) these are protected
// and we can get the address of it :(
struct sockaddr_in sin;
size_t sin_len = sizeof(sin);
if (0 == m_nscTcpSocket->getsockname ((struct sockaddr *) &sin, &sin_len)) {
m_localAddress = m_localAddress.Deserialize ((const uint8_t*)&sin.sin_addr);
m_localPort = ntohs (sin.sin_port);
}
NS_LOG_LOGIC ("NscTcpSocketImpl " << this << " connected to "
<< m_remoteAddress << ":" << m_remotePort
<< " from " << m_localAddress << ":" << m_localPort);
NotifyConnectionSucceeded ();
}
bool NscTcpSocketImpl::Accept (void)
{
if (m_state == CLOSED)
{ // Happens if application closes listening socket after Accept() was scheduled.
return false;
}
NS_ASSERT (m_state == LISTEN);
if (!m_nscTcpSocket->is_listening ())
{
return false;
}
INetStreamSocket *newsock;
int res = m_nscTcpSocket->accept (&newsock);
if (res != 0)
{
return false;
}
// We could obtain a fromAddress using getpeername, but we've already
// finished the tcp handshake here, i.e. this is a new connection
// and not a connection request.
// if (!NotifyConnectionRequest(fromAddress))
// return true;
// Clone the socket
Ptr<NscTcpSocketImpl> newSock = Copy ();
newSock->m_nscTcpSocket = newsock;
NS_LOG_LOGIC ("Cloned a NscTcpSocketImpl " << newSock);
Simulator::ScheduleNow (&NscTcpSocketImpl::CompleteFork, newSock);
return true;
}
bool NscTcpSocketImpl::ReadPendingData (void)
{
if (m_state != ESTABLISHED)
{
return false;
}
int len, err;
uint8_t buffer[8192];
len = sizeof(buffer);
m_errno = ERROR_NOTERROR;
err = m_nscTcpSocket->read_data (buffer, &len);
if (err == 0 && len == 0)
{
NS_LOG_LOGIC ("ReadPendingData got EOF from socket");
m_state = CLOSE_WAIT;
return false;
}
m_errno = GetNativeNs3Errno (err);
switch (m_errno)
{
case ERROR_NOTERROR: break; // some data was sent
case ERROR_AGAIN: return false;
default:
NS_LOG_WARN ("Error (" << err << ") " <<
"during read_data, ns-3 errno set to" << m_errno);
m_state = CLOSED;
return false;
}
Ptr<Packet> p = Create<Packet> (buffer, len);
SocketAddressTag tag;
tag.SetAddress (m_peerAddress);
p->AddPacketTag (tag);
m_deliveryQueue.push (p);
m_rxAvailable += p->GetSize ();
NotifyDataRecv ();
return true;
}
bool NscTcpSocketImpl::SendPendingData (void)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("ENTERING SendPendingData");
if (m_txBuffer.empty ())
{
return false;
}
int ret;
size_t size, written = 0;
do {
NS_ASSERT (!m_txBuffer.empty ());
Ptr<Packet> &p = m_txBuffer.front ();
size = p->GetSize ();
NS_ASSERT (size > 0);
m_errno = ERROR_NOTERROR;
uint8_t *buf = new uint8_t[size];
p->CopyData (buf, size);
ret = m_nscTcpSocket->send_data ((const char *)buf, size);
delete[] buf;
if (ret <= 0)
{
break;
}
written += ret;
NS_ASSERT (m_txBufferSize >= (size_t)ret);
m_txBufferSize -= ret;
if ((size_t)ret < size)
{
p->RemoveAtStart (ret);
break;
}
m_txBuffer.pop ();
if (m_txBuffer.empty ())
{
if (m_closeOnEmpty)
{
m_nscTcpSocket->disconnect ();
m_state = CLOSED;
}
break;
}
} while ((size_t) ret == size);
if (written > 0)
{
Simulator::ScheduleNow (&NscTcpSocketImpl::NotifyDataSent, this, ret);
return true;
}
return false;
}
Ptr<NscTcpSocketImpl> NscTcpSocketImpl::Copy ()
{
return CopyObject<NscTcpSocketImpl> (this);
}
void
NscTcpSocketImpl::SetSndBufSize (uint32_t size)
{
m_sndBufSize = size;
}
uint32_t
NscTcpSocketImpl::GetSndBufSize (void) const
{
return m_sndBufSize;
}
void
NscTcpSocketImpl::SetRcvBufSize (uint32_t size)
{
m_rcvBufSize = size;
}
uint32_t
NscTcpSocketImpl::GetRcvBufSize (void) const
{
return m_rcvBufSize;
}
void
NscTcpSocketImpl::SetSegSize (uint32_t size)
{
m_segmentSize = size;
}
uint32_t
NscTcpSocketImpl::GetSegSize (void) const
{
return m_segmentSize;
}
void
NscTcpSocketImpl::SetAdvWin (uint32_t window)
{
m_advertisedWindowSize = window;
}
uint32_t
NscTcpSocketImpl::GetAdvWin (void) const
{
return m_advertisedWindowSize;
}
void
NscTcpSocketImpl::SetSSThresh (uint32_t threshold)
{
m_ssThresh = threshold;
}
uint32_t
NscTcpSocketImpl::GetSSThresh (void) const
{
return m_ssThresh;
}
void
NscTcpSocketImpl::SetInitialCwnd (uint32_t cwnd)
{
m_initialCWnd = cwnd;
}
uint32_t
NscTcpSocketImpl::GetInitialCwnd (void) const
{
return m_initialCWnd;
}
void
NscTcpSocketImpl::SetConnTimeout (Time timeout)
{
m_cnTimeout = timeout;
}
Time
NscTcpSocketImpl::GetConnTimeout (void) const
{
return m_cnTimeout;
}
void
NscTcpSocketImpl::SetConnCount (uint32_t count)
{
m_cnCount = count;
}
uint32_t
NscTcpSocketImpl::GetConnCount (void) const
{
return m_cnCount;
}
void
NscTcpSocketImpl::SetDelAckTimeout (Time timeout)
{
m_delAckTimeout = timeout;
}
Time
NscTcpSocketImpl::GetDelAckTimeout (void) const
{
return m_delAckTimeout;
}
void
NscTcpSocketImpl::SetDelAckMaxCount (uint32_t count)
{
m_delAckMaxCount = count;
}
uint32_t
NscTcpSocketImpl::GetDelAckMaxCount (void) const
{
return m_delAckMaxCount;
}
void
NscTcpSocketImpl::SetTcpNoDelay (bool noDelay)
{
m_noDelay = noDelay;
}
bool
NscTcpSocketImpl::GetTcpNoDelay (void) const
{
return m_noDelay;
}
void
NscTcpSocketImpl::SetPersistTimeout (Time timeout)
{
m_persistTimeout = timeout;
}
Time
NscTcpSocketImpl::GetPersistTimeout (void) const
{
return m_persistTimeout;
}
enum Socket::SocketErrno
NscTcpSocketImpl::GetNativeNs3Errno (int error) const
{
enum nsc_errno err;
if (error >= 0)
{
return ERROR_NOTERROR;
}
err = (enum nsc_errno) error;
switch (err)
{
case NSC_EADDRINUSE: // fallthrough
case NSC_EADDRNOTAVAIL: return ERROR_AFNOSUPPORT;
case NSC_EINPROGRESS: // Altough nsc sockets are nonblocking, we pretend they're not.
case NSC_EAGAIN: return ERROR_AGAIN;
case NSC_EISCONN: // fallthrough
case NSC_EALREADY: return ERROR_ISCONN;
case NSC_ECONNREFUSED: return ERROR_NOROUTETOHOST; // XXX, better mapping?
case NSC_ECONNRESET: // for no, all of these fall through
case NSC_EHOSTDOWN:
case NSC_ENETUNREACH:
case NSC_EHOSTUNREACH: return ERROR_NOROUTETOHOST;
case NSC_EMSGSIZE: return ERROR_MSGSIZE;
case NSC_ENOTCONN: return ERROR_NOTCONN;
case NSC_ESHUTDOWN: return ERROR_SHUTDOWN;
case NSC_ETIMEDOUT: return ERROR_NOTCONN; // XXX - this mapping isn't correct
case NSC_ENOTDIR: // used by eg. sysctl(2). Shouldn't happen normally,
// but is triggered by e.g. show_config().
case NSC_EUNKNOWN: return ERROR_INVAL; // Catches stacks that 'return -1' without real mapping
}
NS_ASSERT_MSG (0, "Unknown NSC error");
return ERROR_INVAL;
}
bool
NscTcpSocketImpl::SetAllowBroadcast (bool allowBroadcast)
{
if (allowBroadcast)
{
return false;
}
return true;
}
bool
NscTcpSocketImpl::GetAllowBroadcast () const
{
return false;
}
} // namespace ns3 |
// This software is free: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License Version 3,
// as published by the Free Software Foundation.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// Version 3 in the file COPYING that came with this distribution.
// If not, see <http://www.gnu.org/licenses/>.
/*!
\file plane_filtering.h
\brief Interface to PlaneFiltering class, to perform plane filtering of
3D point clouds from depth images
\author Joydeep Biswas, (C) 2011
*/
#ifndef PLANE_FILTERING_H
#define PLANE_FILTERING_H
#include <iostream>
#include <vector>
#include <math.h>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Eigenvalues>
#include "plane_polygon.h"
#include "timer.h"
#include "geometry.h"
#include "grahams_scan.h"
using namespace std;
/// Generic Depth Camera Interface
class DepthCam{
public:
float fovH;
float fovV;
int width;
int height;
float minDepth;
float maxDepth;
/// focal point
float f;
DepthCam();
/// Convert pixel specified by (row,col) from provided depth image to a 3D point, and return that 3D point
virtual vector3f depthPixelTo3D(int row, int col, void* depthImage) = 0;
/// Convert pixel specified by index ind from provided depth image to a 3D point, and return that 3D point
virtual vector3f depthPixelTo3D(int ind, void* depthImage) = 0;
/// Returns true if pixel specified by (row,col) has a valid depth value in the provided depth image
virtual bool isValidDepth(int row, int col, void* depthImage) = 0;
/// Returns true if pixel specified by index ind has a valid depth value in the provided depth image
virtual bool isValidDepth(int ind, void* depthImage) = 0;
/// Convert depth value from provided row and column to a 3D point
virtual vector3f depthValueTo3D(int row, int col, void* depthValue) = 0;
/// Convert raw Depth value to a Metric value
virtual float rawDepthToMetricDepth(void* depthValue) = 0;
};
/// Raw Kinect Depth Camera to process raw depth images from libfreenect
class KinectRawDepthCam : public DepthCam{
public:
/// 'a' parameter for conversion of raw depth (d) to metric depth (z) as: z = 1.0/(a+b*d)
float a;
/// 'b' parameter for conversion of raw depth (d) to metric depth (z) as: z = 1.0/(a+b*d)
float b;
/// Maximum valid depth value
uint16_t maxDepthVal;
/// Lookup table to convert from raw depth (11 bit int) to metric depth (float)
float depthLookups[65536];
/// Lookup table for unit vectors for each pixel in the depth image, normalized to unit depth
vector<vector3f> pointCloudLookups;
KinectRawDepthCam();
/// Convert depth value from provided row and column to a 3D point
vector3f depthValueTo3D(int row, int col, void* depthValue);
/// Convert raw Depth value to a Metric value
float rawDepthToMetricDepth(void* depthValue);
/// Convert pixel specified by (row,col) from provided depth image to a 3D point, and return that 3D point
vector3f depthPixelTo3D(int row, int col, void* depthImage);
/// Convert pixel specified by index ind from provided depth image to a 3D point, and return that 3D point
vector3f depthPixelTo3D(int ind, void* depthImage);
/// Returns true if pixel specified by (row,col) has a valid depth value in the provided depth image
bool isValidDepth(int row, int col, void* depthImage);
/// Returns true if pixel specified by index ind has a valid depth value in the provided depth image
bool isValidDepth(int ind, void* depthImage);
/// Generate lookup tables for 3D reconstruction
void initDepthReconstructionLookups();
};
/// Kinect Depth Camera to process depth images from OpenNI
class KinectOpenNIDepthCam : public DepthCam{
public:
/// Maximum valid depth value
float maxDepthVal;
/// Lookup table to convert from raw depth (11 bit int) to metric depth (float)
float depthLookups[65536];
/// Lookup table for unit vectors for each pixel in the depth image, normalized to unit depth
vector<vector3f> pointCloudLookups;
KinectOpenNIDepthCam();
/// Convert depth value from provided row and column to a 3D point
vector3f depthValueTo3D(int row, int col, void* depthValue);
/// Convert raw Depth value to a Metric value
float rawDepthToMetricDepth(void* depthValue);
/// Convert pixel specified by (row,col) from provided depth image to a 3D point, and return that 3D point
vector3f depthPixelTo3D(int row, int col, void* depthImage);
/// Convert pixel specified by index ind from provided depth image to a 3D point, and return that 3D point
vector3f depthPixelTo3D(int ind, void* depthImage);
/// Returns true if pixel specified by (row,col) has a valid depth value in the provided depth image
bool isValidDepth(int row, int col, void* depthImage);
/// Returns true if pixel specified by index ind has a valid depth value in the provided depth image
bool isValidDepth(int ind, void* depthImage);
/// Generate lookup tables for 3D reconstruction
void initDepthReconstructionLookups();
};
class PlaneFilter{
public:
/// Parameters for plane filtering
typedef struct{
// Parameters for vanilla FSPF
unsigned int maxPoints;
unsigned int numSamples;
unsigned int numLocalSamples;
unsigned int planeSize;
float WorldPlaneSize;
float maxError;
float minInlierFraction;
float maxDepthDiff;
unsigned int numRetries;
// Parameters for polygonization
bool runPolygonization;
float minConditionNumber;
//Thresholds for polygon merging
double maxCosineError;
float maxPolygonDist;
float maxOffsetDiff;
float minVisibilityFraction;
bool filterOutliers;
} PlaneFilterParams;
private:
PlaneFilterParams filterParams;
DepthCam* depthCam;
uint32_t lastRand;
/// CPU Performance statistics
AccumulativeTimer planeFilteringTimer;
/// Sampling Performance statistics
int numSampledLocations, numPlanarPoints, numNonPlanarPoints;
public:
PlaneFilter();
PlaneFilter(DepthCam *_depthCam, PlaneFilterParams &_filterParams);
void setDepthCamera(DepthCam *_depthCam){depthCam = _depthCam;}
void setFilterParameters(PlaneFilterParams ¶ms){filterParams = params;}
void setParameters(DepthCam *_depthCam, PlaneFilterParams &_filterParams){setDepthCamera(_depthCam); setFilterParameters(_filterParams);}
/// Sample random location in specified window of depth image. Returns true if succesful, along with the sampled point 'p'. Returns false otherwise.
inline bool sampleLocation(void* depthImage, int& index, int& row, int& col, Vector3f& p, int rMin, int height, int cMin, int width);
/// Accepts a depth image, returns filtered point cloud + normals, outliers, and all sampled points
void GenerateFilteredPointCloud(void* depthImage, vector< vector3f >& filteredPointCloud, vector< vector2i >& pixelLocs, vector< vector3f >& pointCloudNormals, vector< vector3f >& outlierCloud, vector< PlanePolygon >& polygons);
/// Accepts a depth image, returns a complete point cloud with a 3D point for every valid depth pixel
void GenerateCompletePointCloud(void* depthImage, vector<vector3f> & pointCloud, vector<int> &pixelLocs);
/// Accepts a depth image, returns a randomly sampled point cloud with at most numPoints
void GenerateSampledPointCloud(void* depthImage, vector<vector3f> & pointCloud, unsigned int numPoints);
/// Create a color coded image of same size as depth image, labelling each pixel as belonging to a plane or not
void GenerateLabelledDepthImage(void* depthImage, int*& labelledDepth, const std::vector< PlanePolygon >& planes);
/// Returns true of the pixel at index 'ind' corresponds to a plane
bool pointIsPlanar(void* depthImage, vector< PlanePolygon >& planes, int ind, float MaxError);
/// Merges plane polygons belonging to the same plane, and returns a set of unique depth-space planes
vector<PlanePolygon> findUniqueDepthPlanes(vector< PlanePolygon > planes);
/// Returns a point cloud from the points extracted from a single raster in the depth image
void PointCloudFromRaster(void* depthImage, vector< vector3f >& pointCloud, unsigned int raster);
/// Custom implementation of a linear congruential generator - faster than using glibc's version
uint32_t lcgRand();
/// Return performance statistics of plane filtering and depth image sampling
void getPerformanceStats(double& planeFilteringTime, int& numSampledLocations, int& numPlanarPoints, int& numNonPlanarPoints);
/// Clear accumulated performance statistics
void clearPerformanceStats();
};
#endif //PLANE_FILTERING_H |
package com.exclr8.xen4.fragment
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.exclr8.xen4.R
import com.exclr8.xen4.adapter.BaseUrlAdapter
import com.exclr8.xen4.api.AuthInterface
import com.exclr8.xen4.api.LoginInterface
import com.exclr8.xen4.databinding.FragmentLoginBinding
import com.exclr8.xen4.model.*
import com.exclr8.xen4.room.UrlsDatabaseBuilder
import com.exclr8.xen4.service.FirebaseMessagingServiceXen
import com.exclr8.xen4.sharedPref.SharedPreference
import com.exclr8.xen4.url.Urls
import com.exclr8.xen4.viewModel.ViewModelXen
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
private const val TAG = "LoginFragment"
class LoginFragment : androidx.fragment.app.Fragment() {
private lateinit var binding: FragmentLoginBinding
private val vm: ViewModelXen by activityViewModels()
private var appToken = ""
//private val sp: SharedPreference by lazy { SharedPreference(requireContext()) }
private lateinit var fragContext: Context
private lateinit var adapter: BaseUrlAdapter
private lateinit var urlList: List<UrlsData>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
urlList = runBlocking {
UrlsDatabaseBuilder.getInstance(requireContext()).UrlDao().getAllBaseUrls()
}
SharedPreference(requireContext()).save("baseUrl", Urls.baseUrl)
//SharedPreference(requireContext()).save("baseUrl", "http://192.168.1.60:8081/")
val parentActivity = (activity as AppCompatActivity)
parentActivity.findViewById<DrawerLayout>(R.id.dlMain)
.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
val actionBar = parentActivity.supportActionBar
actionBar?.hide()
runBlocking {
authenticateApp()
getFCMToken()
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_login, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentLoginBinding.bind(view)
val sp = SharedPreference(requireContext())
fragContext = requireContext()
//binding.etUsername.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
vm.setForgotPasswordVM(false)
if (!vm.checkForInternet(requireContext())) {
binding.btnLogin.isEnabled = false
binding.btnLogin.isClickable = false
binding.btnLogin.text = getString(R.string.Offline)
binding.tvForgotPassword.isClickable = false
}
//DEBUG MENU STUFF
debugMenu()
//
val userName = sp.getValueString("userName")
val userPassword = sp.getValueString("userPassword")
if (userName != null || userPassword != null && sp.getValueBoolean("signedIn", false)) {
runBlocking { authenticateApp() }
runBlocking { vm.getUserTasks(0, 10, requireContext()) }
login(
LoginDetails(
UserName = userName.toString(),
Password = userPassword.toString()
), sp.getValueString("appToken").toString()
)
}
binding.btnLogin.setOnClickListener {
if (!vm.checkForInternet(requireContext())) {
binding.btnLogin.isEnabled = false
binding.btnLogin.isClickable = false
binding.btnLogin.text = getString(R.string.Offline)
}
if (binding.etUsername.text!!.isEmpty() || binding.etPassword.text!!.isEmpty()) {
Toast.makeText(
requireContext(),
"Username or Password is Empty",
Toast.LENGTH_SHORT
).show()
} else {
binding.btnLogin.isEnabled = false
binding.btnLogin.isClickable = false
login(
LoginDetails(
UserName = binding.etUsername.text.toString(),
Password = binding.etPassword.text.toString()
), sp.getValueString("appToken").toString()
)
sp.save("userName", binding.etUsername.text.toString())
sp.save("userPassword", binding.etPassword.text.toString())
}
}
binding.tvForgotPassword.setOnClickListener {
findNavController().navigate(R.id.action_loginFragment_to_passwordResetFragment)
}
}
//Authenticate
private fun authenticateApp() {
val baseUrl = SharedPreference(requireContext()).getValueString("baseUrl")
val retrofitBuilder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseUrl!!)
.build()
.create(AuthInterface::class.java)
val authObject = AuthRequest(
ApplicationKey = Urls.appKey,
//AppVersion = BuildConfig.VERSION_NAME,
AppVersion = "uat",
OSName = "Android"
)
val retrofitData = retrofitBuilder.authorizeApp(authObject)
Handler(Looper.getMainLooper()).postDelayed(
{
retrofitData.enqueue(object : Callback<AuthResponse> {
override fun onResponse(
call: retrofit2.Call<AuthResponse>,
response: Response<AuthResponse>
) {
val appTokenKey = response.body()?.TokenKey
SharedPreference(fragContext).save("appToken", appTokenKey.toString())
vm.setAppTokenKeyVM(appTokenKey.toString())
Log.i(TAG, response.body().toString())
appToken = appTokenKey.toString()
binding.llLogin2.isVisible = true
binding.clSplash.isVisible = false
}
override fun onFailure(call: retrofit2.Call<AuthResponse>, t: Throwable) {
binding.btnLogin.isEnabled = true
binding.btnLogin.isClickable = true
binding.llLogin2.isVisible = true
binding.clSplash.isVisible = false
Toast.makeText(
requireContext(),
"Authentication Failed",
Toast.LENGTH_SHORT
).show()
Log.i(TAG, t.message.toString())
}
})
}, 1200
)
}
//Login
private fun login(loginDetails: LoginDetails, appTokenKey: String) {
runBlocking { authenticateApp() }
val baseUrl = SharedPreference(requireContext()).getValueString("baseUrl")
val retrofitBuilder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseUrl!!)
.build()
.create(LoginInterface::class.java)
val retrofitData = retrofitBuilder.login(loginDetails, appTokenKey)
retrofitData.enqueue(object : Callback<LoginResponse> {
override fun onResponse(
call: retrofit2.Call<LoginResponse>,
response: Response<LoginResponse>
) {
Log.i(TAG, response.body().toString())
if (response.body() != null) {
if (response.body()!!.Success) {
//SharedPreference(requireContext()).removeValue("userKey")
SharedPreference(requireContext()).save("userKey", response.body()!!.TokenKey)
runBlocking {
runBlocking { vm.getUserTasks(0, 10, requireContext()) }
FirebaseMessagingServiceXen().sendRegistrationToServer(
PushNotificationRequest(
DeviceTypeId = 2,
DeviceUID = Settings.Secure.ANDROID_ID,
DeviceName = Build.BRAND,
DeviceDescription = Build.MODEL,
Token = SharedPreference(requireContext()).getValueString("fcmToken")
.toString()
), response.body()!!.TokenKey,
url = SharedPreference(requireContext()).getValueString("baseUrl")
.toString()
)
}
SharedPreference(requireContext()).save("signedIn", true)
SharedPreference(requireContext()).save("userKey", response.body()!!.TokenKey)
findNavController().navigate(R.id.action_loginFragment_to_homeFragment)
} else {
binding.btnLogin.isEnabled = true
binding.btnLogin.isClickable = true
binding.etUsername.text!!.clear()
binding.etPassword.text!!.clear()
SharedPreference(requireContext()).save("signedIn", false)
Toast.makeText(
requireContext(),
"Error Signing In",
Toast.LENGTH_SHORT
).show()
}
} else {
binding.btnLogin.isEnabled = true
binding.btnLogin.isClickable = true
Toast.makeText(
requireContext(),
"Sign In Failed",
Toast.LENGTH_SHORT
).show()
}
}
override fun onFailure(call: retrofit2.Call<LoginResponse>, t: Throwable) {
Log.i(TAG, t.message.toString())
}
})
}
//FCM Token
private fun getFCMToken() {
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
SharedPreference(requireContext()).save("fcmToken", token)
Log.d(TAG, token)
} else {
Log.i(TAG, "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}
})
}
//Debug
private fun debugMenu() {
val sp = SharedPreference(requireContext())
val urlDb = UrlsDatabaseBuilder.getInstance(requireContext()).UrlDao()
(urlList as MutableList<UrlsData>).reverse()
binding.btnUrlDebug.setOnClickListener {
binding.llLogin2.isVisible = false
binding.clDebug.isVisible = true
}
adapter = BaseUrlAdapter(requireContext(), urlList)
binding.rvBaseUrls.adapter = adapter
adapter.setOnUrlClick(object : BaseUrlAdapter.OnUrlClick {
override fun onUrlClick(position: Int) {
urlList[position]
binding.tvUrlDebug.text = getString(R.string.url, sp.getValueString("baseUrl"))
}
})
binding.rvBaseUrls.layoutManager = LinearLayoutManager(requireContext())
binding.tvUrlDebug.text = getString(R.string.url, sp.getValueString("baseUrl"))
binding.etBase.setText(sp.getValueString("baseUrl"))
binding.etBase.addTextChangedListener {
if (binding.etBase.text.toString().isEmpty()) {
"Url : " + sp.getValueString("baseUrl").toString()
}
}
binding.btnConfirmUrl.setOnClickListener {
if (binding.etBase.text!!.isEmpty()) {
Toast.makeText(requireContext(), "Text is empty", Toast.LENGTH_SHORT).show()
} else {
val url = binding.etBase.text.toString()
sp.save("baseUrl", url)
runBlocking { urlDb.insertUrl(UrlsData(baseUrl = url)) }
urlList = runBlocking {
UrlsDatabaseBuilder.getInstance(requireContext()).UrlDao().getAllBaseUrls()
}
(urlList as MutableList<UrlsData>).reverse()
adapter = BaseUrlAdapter(requireContext(), urlList)
binding.rvBaseUrls.adapter = adapter
binding.rvBaseUrls.layoutManager = LinearLayoutManager(requireContext())
adapter.setOnUrlClick(object : BaseUrlAdapter.OnUrlClick {
override fun onUrlClick(position: Int) {
val currentUrl = urlList[position]
sp.save("baseUrl", currentUrl.baseUrl)
binding.tvUrlDebug.text =
getString(R.string.url, sp.getValueString("baseUrl").toString())
}
})
binding.tvUrlDebug.text =
getString(R.string.url, sp.getValueString("baseUrl").toString())
}
}
binding.btnClear.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
urlDb.deleteAllUrls()
}
(urlList as MutableList<UrlsData>).clear()
adapter = BaseUrlAdapter(requireContext(), urlList)
binding.rvBaseUrls.adapter = adapter
binding.rvBaseUrls.layoutManager = LinearLayoutManager(requireContext())
adapter.setOnUrlClick(object : BaseUrlAdapter.OnUrlClick {
override fun onUrlClick(position: Int) {
val currentUrl = urlList[position]
sp.save("baseUrl", currentUrl.baseUrl)
binding.tvUrlDebug.text =
getString(R.string.url, sp.getValueString("baseUrl").toString())
}
})
SharedPreference(requireContext()).save("baseUrl", Urls.baseUrl)
binding.tvUrlDebug.text =
getString(R.string.url, sp.getValueString("baseUrl").toString())
binding.etBase.text!!.clear()
}
binding.btnCloseDebug.setOnClickListener {
binding.llLogin2.isVisible = true
binding.clDebug.isVisible = false
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view?.windowToken, 0)
}
adapter.setOnUrlClick(object : BaseUrlAdapter.OnUrlClick {
override fun onUrlClick(position: Int) {
val currentUrl = urlList[position]
sp.save("baseUrl", currentUrl.baseUrl)
binding.tvUrlDebug.text =
getString(R.string.url, sp.getValueString("baseUrl").toString())
}
})
}
} |
# %%
import numpy as np
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
from tqdm import tqdm
from scipy.integrate import quad
import pandas as pd
import random
from pyvbmc import VBMC
from V_A_step_jump_fit_utils import PDF_hit_V_A_change, CDF_hit_V_A_change, rho_A_t_fn, cum_A_t_fn
from tqdm import tqdm
# %% [markdown]
# # data
# %%
# read out_LED.csv as dataframe
og_df = pd.read_csv('../out_LED.csv')
# chose non repeat trials - 0 or 2 or missing
df = og_df[ og_df['repeat_trial'].isin([0,2]) | og_df['repeat_trial'].isna() ]
# only session type 7
session_type = 7
df = df[ df['session_type'].isin([session_type]) ]
# training level 16
training_level = 16
df = df[ df['training_level'].isin([training_level]) ]
# find ABL and ILD
ABL_arr = df['ABL'].unique()
ILD_arr = df['ILD'].unique()
# sort ILD arr in ascending order
ILD_arr = np.sort(ILD_arr)
ABL_arr = np.sort(ABL_arr)
print('ABL:', ABL_arr)
print('ILD:', ILD_arr)
# %%
df_to_fit = df[ df['LED_trial'] == 1 ]
# %% [markdown]
# # VBMC
# %%
T_trunc = 0.3
# %%
def compute_loglike(row, base_V_A, new_V_A, theta_A, t_A_aff):
rt = row['timed_fix']
t_stim = row['intended_fix']
t_led = row['intended_fix'] - row['LED_onset_time']
if rt < T_trunc:
likelihood = 0
else:
if t_led == 0: # only new V_A will be used
pdf_trunc_factor = 1 - cum_A_t_fn(T_trunc - t_A_aff, new_V_A, theta_A)
if rt < t_stim:
likelihood = rho_A_t_fn(rt - t_A_aff, new_V_A, theta_A) / pdf_trunc_factor
elif rt > t_stim:
if t_stim < T_trunc:
likelihood = 1
else:
likelihood = ( 1 - cum_A_t_fn(t_stim - t_A_aff, new_V_A, theta_A) ) / pdf_trunc_factor
else: # V_A change in middle
trunc_factor = 1 - CDF_hit_V_A_change(T_trunc - t_A_aff, base_V_A, new_V_A, theta_A, t_led)
if rt < t_stim:
likelihood = PDF_hit_V_A_change(rt-t_A_aff, base_V_A, new_V_A, theta_A, t_led) / trunc_factor
elif rt > t_stim:
if t_stim < T_trunc: # if stim is before truncation, the abort prob = 0
likelihood = 1
else:
likelihood = ( 1 - CDF_hit_V_A_change(t_stim - t_A_aff, base_V_A, new_V_A, theta_A, t_led) ) / trunc_factor
if likelihood <= 0:
likelihood = 1e-50
return np.log(likelihood)
def psiam_tied_loglike_fn(params):
base_V_A, new_V_A, theta_A, t_A_aff = params
all_loglike = Parallel(n_jobs=30)(delayed(compute_loglike)(row, base_V_A, new_V_A, theta_A, t_A_aff)\
for _, row in df_to_fit.iterrows() \
if (not np.isnan(row['timed_fix'] + row['intended_fix'] + row['LED_onset_time'])))
loglike = np.sum(all_loglike)
return loglike
# %% [markdown]
# # bounds
# %%
base_V_A_bounds = [0.1, 5]
new_V_A_bounds = [0.1, 5]
theta_A_bounds = [0.1, 5]
t_A_aff_bounds = [-5, 0.1]
base_V_A_plausible_bounds = [0.5, 3]
new_V_A_plausible_bounds = [0.5, 3]
theta_A_plausible_bounds = [0.5, 3]
t_A_aff_plausible_bounds = [-2, 0.06]
# %% [markdown]
# # prior
# %%
def trapezoidal_logpdf(x, a, b, c, d):
if x < a or x > d:
return -np.inf # Logarithm of zero
area = ((b - a) + (d - c)) / 2 + (c - b)
h_max = 1.0 / area # Height of the trapezoid to normalize the area to 1
if a <= x <= b:
pdf_value = ((x - a) / (b - a)) * h_max
elif b < x < c:
pdf_value = h_max
elif c <= x <= d:
pdf_value = ((d - x) / (d - c)) * h_max
else:
pdf_value = 0.0 # This case is redundant due to the initial check
if pdf_value <= 0.0:
return -np.inf
else:
return np.log(pdf_value)
def vbmc_prior_abort_fn(params):
base_V_A, new_V_A, theta_A, t_A_aff = params
base_V_A_logpdf = trapezoidal_logpdf(base_V_A, base_V_A_bounds[0], base_V_A_plausible_bounds[0], base_V_A_plausible_bounds[1], base_V_A_bounds[1])
new_V_A_logpdf = trapezoidal_logpdf(new_V_A, new_V_A_bounds[0], new_V_A_plausible_bounds[0], new_V_A_plausible_bounds[1], new_V_A_bounds[1])
theta_A_logpdf = trapezoidal_logpdf(theta_A, theta_A_bounds[0], theta_A_plausible_bounds[0], theta_A_plausible_bounds[1], theta_A_bounds[1])
t_A_aff_logpdf = trapezoidal_logpdf(t_A_aff, t_A_aff_bounds[0], t_A_aff_plausible_bounds[0], t_A_aff_plausible_bounds[1], t_A_aff_bounds[1])
return base_V_A_logpdf + new_V_A_logpdf + theta_A_logpdf + t_A_aff_logpdf
# %% [markdown]
# # joint
# %%
def vbmc_joint(params):
return vbmc_prior_abort_fn(params) + psiam_tied_loglike_fn(params)
# %% [markdown]
# # run vbmc
# %%
lb = [base_V_A_bounds[0], new_V_A_bounds[0], theta_A_bounds[0], t_A_aff_bounds[0]]
ub = [base_V_A_bounds[1], new_V_A_bounds[1], theta_A_bounds[1], t_A_aff_bounds[1]]
plb = [base_V_A_plausible_bounds[0], new_V_A_plausible_bounds[0], theta_A_plausible_bounds[0], t_A_aff_plausible_bounds[0]]
pub = [base_V_A_plausible_bounds[1], new_V_A_plausible_bounds[1], theta_A_plausible_bounds[1], t_A_aff_plausible_bounds[1]]
np.random.seed(42)
base_V_A_0 = np.random.uniform(base_V_A_plausible_bounds[0], base_V_A_plausible_bounds[1])
new_V_A_0 = np.random.uniform(new_V_A_plausible_bounds[0], new_V_A_plausible_bounds[1])
theta_A_0 = np.random.uniform(theta_A_plausible_bounds[0], theta_A_plausible_bounds[1])
t_A_aff_0 = np.random.uniform(t_A_aff_plausible_bounds[0], t_A_aff_plausible_bounds[1])
x_0 = np.array([base_V_A_0, new_V_A_0, theta_A_0, t_A_aff_0])
# %%
vbmc = VBMC(vbmc_joint, x_0, lb, ub, plb, pub, options={'display': 'off'})
vp, results = vbmc.optimize()
# %%
# save vbmc
vp.save('V_A_step_jump_LED_on_vbmc.pkl', overwrite=True) |
Sub Test()
Debug.Print RenameSheet("Sheet1")
Debug.Print RenameSheet("Sheet2")
Debug.Print RenameSheet("ABC")
Dim wrkSht As Worksheet
Set wrkSht = Worksheets.Add
wrkSht.Name = RenameSheet("DEF")
End Sub
Public Function RenameSheet(SheetName As String, Optional Book As Workbook) As String
Dim lCounter As Long
Dim wrkSht As Worksheet
If Book Is Nothing Then
Set Book = ThisWorkbook
End If
lCounter = 0
On Error Resume Next
Do
'Try and set a reference to the worksheet.
Set wrkSht = Book.Worksheets(SheetName & IIf(lCounter > 0, "_" & lCounter, ""))
If Err.Number <> 0 Then
'If an error occurs then the sheet name doesn't exist and we can use it.
RenameSheet = SheetName & IIf(lCounter > 0, "_" & lCounter, "")
Exit Do
End If
Err.Clear
'If the sheet name does exist increment the counter and try again.
lCounter = lCounter + 1
Loop
On Error GoTo 0
End Function
Sub RenameSheet()
Dim Sht As Worksheet
Dim NewSht As Worksheet
Dim VBA_BlankBidSheet As Worksheet
Dim newShtName As String
' modify to your sheet's name
Set VBA_BlankBidSheet = Sheets("Sheet1")
VBA_BlankBidSheet.Copy After:=ActiveSheet
Set NewSht = ActiveSheet
' you can change it to your needs, or add an InputBox to select the Sheet's name
newShtName = "New Name"
For Each Sht In ThisWorkbook.Sheets
If Sht.Name = "New Name" Then
newShtName = "New Name" & "_" & ThisWorkbook.Sheets.Count
End If
Next Sht
NewSht.Name = newShtName
End Sub
Private Sub nameNewSheet(sheetName As String, newSheet As Worksheet)
Dim named As Boolean, counter As Long
On Error Resume Next
'try to name the sheet. If name is already taken, start looping
newSheet.Name = sheetName
If Err Then
If Err.Number = 1004 Then 'name already used
Err.Clear
Else 'unexpected error
GoTo nameNewSheet_Error
End If
Else
Exit Sub
End If
named = False
counter = 1
Do
newSheet.Name = sheetName & counter
If Err Then
If Err.Number = 1004 Then 'name already used
Err.Clear
counter = counter + 1 'increment the number until the sheet can be named
Else 'unexpected error
GoTo nameNewSheet_Error
End If
Else
named = True
End If
Loop While Not named
On Error GoTo 0
Exit Sub
nameNewSheet_Error:
'add errorhandler here
End Sub |
import os
import torch
import json
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
from transformers import AutoTokenizer
import tensorflow as tf
from tensorflow.keras.models import Model
from transformers import TFGPT2Model, TFBertModel
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import json
import os
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
from transformers import AutoTokenizer
from transformers import TransformerBlock # Assume an implemented transformer module
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, Dropout, Reshape
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from nstar import AGISystem
from tensorflow.keras.preprocessing.image import ImageDataGenerator
class CustomDataset(Dataset):
def __init__(self, json_path, image_folder, tokenizer_name):
with open(json_path, 'r') as f:
self.data = json.load(f)
self.image_folder = image_folder
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
item = self.data[idx]
image_path = os.path.join(self.image_folder, item['image'])
image = Image.open(image_path).convert('RGB')
image = self.transform(image)
question = item['question']
input_ids = self.tokenizer.encode(question, return_tensors='pt').squeeze(0)
attention_mask = torch.ones_like(input_ids)
# Assuming the answer is a single number or string
answer = item['answer']
answer_type = item['answer_type']
if answer_type == 'float':
label = torch.tensor(float(answer))
elif answer_type == 'integer':
label = torch.tensor(int(answer))
else:
label = torch.tensor(0) # Handle text or list answers as needed
return image, input_ids, attention_mask, label
# Placeholder function for dataset loading
def load_dataset():
# Define paths to your dataset
train_data_path = 'path_to_train_data'
validation_data_path = 'path_to_validation_data'
# Define image generators with data augmentation for training and validation sets
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
validation_datagen = ImageDataGenerator(rescale=1./255)
# Load images from directories and apply transformations
train_generator = train_datagen.flow_from_directory(
train_data_path,
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
validation_generator = validation_datagen.flow_from_directory(
validation_data_path,
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
return train_generator, validation_generator
# Function to preprocess images for CNN input
def preprocess_images(images):
# Assuming 'images' is a batch of images of shape (batch_size, height, width, channels)
# Normalize pixel values and resize if needed for your CNN
processed_images = images / 255.0
return processed_images
# Function to calculate feedback based on predictions and correct answers
def calculate_feedback(predictions, correct_answers):
# Assuming 'predictions' is a batch of model outputs and 'correct_answers' are the ground truth labels
# Calculate accuracy as a simple feedback metric
accuracy = np.mean(np.argmax(predictions, axis=1) == np.argmax(correct_answers, axis=1))
# More sophisticated feedback calculation can be implemented here
return {'accuracy': accuracy}
# Train the AGI System with Q-learning integration
def train_agi_system(agi_system, train_generator, validation_generator, epochs):
for epoch in range(epochs):
for batch_idx, (images, correct_answers) in enumerate(train_generator):
# Convert images to the expected format for AGI system components
processed_images = preprocess_images(images)
# Process data through the EnhancedCNN and AdvancedCEN components
processed_data_cnn = agi_system.get_submodule('CNN')(processed_images)
processed_data_cen = agi_system.get_submodule('CEN')(processed_data_cnn)
# Calculate feedback based on the performance of the AdvancedCEN
feedback = calculate_feedback(processed_data_cen, correct_answers)
# Update MetaLearningController with feedback
agi_system.meta_learning_controller.adapt(feedback)
# Update weights after training
agi_system.get_submodule('CNN').save_model('cnn_model')
agi_system.get_submodule('CEN').save_weights('cen_weights')
agi_system.snn_pathway.save_weights('snn_pathway_weights')
print(f"Epoch {epoch + 1}, Batch {batch_idx + 1} complete. Model weights saved.")
# Evaluate on validation data and print metrics
validation_metrics = evaluate_on_validation_data(agi_system, validation_generator)
print(f"Validation metrics: {validation_metrics}")
if __name__ == "__main__":
main()
# Usage example
dataset = CustomDataset(json_path='path_to_your_json_file.json', image_folder='path_to_images_folder', tokenizer_name='bert-base-uncased')
data_loader = DataLoader(dataset, batch_size=16, shuffle=True)
# Define main training loop
def main():
# Initialize AGI System with Integrated Components
agi_system = AGISystem()
# Load dataset
train_loader = DataLoader(dataset, batch_size=16, shuffle=True)
# Train the AGI System
train_agi_system(agi_system, train_loader, epochs=10)
if __name__ == "__main__":
main() |
# 🌱🌦️ AgriAlert: Agricultural Disaster Prevention and Alert System
<div align="center">
<img src="https://github.com/user-attachments/assets/dfe52d6c-cfc8-441d-a95e-7a225b30ea7d" width="300" alt="AgriAlert Logo">
</div>
This platform enables real-time agricultural risk monitoring based on weather forecasts, providing farmers with timely alerts and actionable recommendations to protect their crops from adverse weather conditions. Using open-source weather APIs and crop-specific threshold analysis, AgriAlert helps prevent agricultural losses through proactive notifications.
## Table of Contents
- [Software Architecture](#software-architecture)
- [Docker Image](#docker-image)
- [Frontend](#frontend)
- [Backend](#backend)
- [Getting Started](#getting-started)
- [Video Demonstration](#video-demonstration)
- [Contributing](#contributing)
- [Improvements](#improvements)
## Software architecture

The application architecture uses Next.js for the web frontend, Kotlin/Swift for mobile clients, Spring Boot for the backend, and Flask for the chatbot service, with communication via RESTful APIs.
## Docker Image
```sh
services:
mysql:
image: mysql:8.0
container_name: mysql-container
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: agrialert
ports:
- "3307:3306"
networks:
- agrialert-network
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
flask-api:
build:
context: ./flask_backend
dockerfile: Dockerfile
container_name: agrialert-flask-api
ports:
- "8086:8086"
depends_on:
mysql:
condition: service_healthy
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://localhost:3306/agrialert
SPRING_DATASOURCE_USERNAME: root
SPRING_DATASOURCE_PASSWORD: password
networks:
- agrialert-network
spring-boot-api:
build:
context: ./springboot_backend
dockerfile: Dockerfile
container_name: agrialert-spring-boot-api
ports:
- "8087:8087"
depends_on:
mysql:
condition: service_healthy
networks:
- agrialert-network
networks:
agrialert-network:
driver: bridge
```
## Frontend
### Technologies Used
- Next.js (Web)
- Kotlin (Android)
- Swift (iOS)
- Tailwind CSS
- TypeScript
## Backend
### Technologies Used
- Spring Boot
- MySQL
- Flask (Chatbot)
## Backend Project Structure
The backend code follows a modular and organized structure, leveraging the power of Spring Boot for building a robust and scalable application.
### 1. com.example.demo
- *Main Application Class:* DemoApplication.java serves as the entry point for the Spring Boot application. It includes the main method to bootstrap and start the application.
### 2. com.example.demo.controller
- *Controller Layer:* This package contains classes responsible for handling incoming HTTP requests. Each controller defines RESTful endpoints for specific features or entities and delegates the request processing to the service layer.
### 3. com.example.demo.model
- *Entity Layer:* The model package includes classes representing data entities in the application. These classes use JPA annotations to define the structure of the corresponding database tables, ensuring seamless ORM mapping.
### 4. com.example.demo.repository
- *Repository Layer:* This package contains interfaces extending Spring Data JPA repository interfaces. These provide built-in methods for CRUD operations and enable interaction with the database without requiring boilerplate code.
### 5. com.example.demo.security
- *Security Configuration:* The security package includes classes for configuring authentication and authorization mechanisms. This might involve defining roles, managing user credentials, and securing endpoints based on roles or permissions.
### 6. com.example.demo.service
- *Service Layer:* This package contains business logic for the application. Services interact with the repository layer to fetch or modify data and provide processed information to the controller layer.
### 7. com.example.demo.utils
- *Utility Classes:* The utils package includes helper or utility classes that provide commonly used functionality across the application. These might include functions for validation, formatting, or other reusable logic.
### Additional Files and Directories:
- **resources Folder:** This contains application configuration files like application.properties or application.yml, along with other static resources.
- **Dockerfile:** Defines the steps to containerize the Spring Boot application for deployment.
- **pom.xml:** The Maven configuration file, managing dependencies and build configurations for the project.
- **.gitignore:** Specifies files and directories to be excluded from version control.
This structured organization ensures the application is scalable, maintainable, and adheres to the separation of concerns principle.
### Dependencies
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
// Other dependencies are in the pom.xml
```
## Getting Started
Here are step-by-step instructions to set up and run AgriAlert locally:
### Prerequisites:
1. **Git:**
- Ensure you have Git installed. If not, download and install it from [git-scm.com](https://git-scm.com/).
2. **MySQL:**
- Install MySQL Server.
- Create a database named `agrialert`.
- Ensure MySQL is running on port 3306.
3. **Node.js:**
- Install Node.js (LTS version) from [nodejs.org](https://nodejs.org/).
### Backend Setup:
1. **Clone the Project:**
- Clone the repository by running the following command:
```bash
git clone https://github.com/SaifeddineDouidy/AgriAlert_backend
cd AgriAlert_backend
```
2. **Install Backend Dependencies:**
- Open a terminal in the backend project folder.
- Run the following command to install dependencies:
```bash
mvn clean install
```
3. **Configure Application Properties:**
- Update the `application.properties` file with your MySQL credentials.
- Configure the OpenMeteo API key if required.
4. **Run Backend:**
- Start your XAMPP Apache and MySQL servers.
- Run the Spring Boot application. The database and entities will be created automatically.
- Verify that the backend is running at [http://localhost:8087](http://localhost:8087).
### Web Frontend Setup:
1. **Install Dependencies:**
- Navigate to the `web-client` directory:
```bash
cd web-client
```
- Install the necessary dependencies by running:
```bash
npm install
```
2. **Run Frontend:**
- Start the development server by running:
```bash
npm run dev
```
3. **Access the Web Interface:**
- Open your browser and navigate to [http://localhost:3000](http://localhost:3000) to access the web interface.
### Mobile Frontend Setup:
1. **Android:**
- Open the Android project in **Android Studio**.
- Update the API endpoint in the configuration files.
- Build and run the application on your device or emulator.
2. **iOS:**
- Open the iOS project in **Xcode**.
- Update the API endpoint in the configuration files.
- Build and run the application on your device or simulator.
### Chatbot Setup:
1. **Install Python Dependencies:**
- Navigate to the `chatbot` directory:
```bash
cd chatbot
```
- Install the required Python dependencies by running:
```bash
pip install -r requirements.txt
```
2. **Run Chatbot Server:**
- Start the chatbot server by running:
```bash
python chat.py
```
3. **Access Chatbot Service:**
- The chatbot service will be available at [http://localhost:5000](http://localhost:5000).
## Video Demonstration
Here' an illustrative video of the android mobile app:
<div align="center">
[See The Video](https://github.com/user-attachments/assets/9bf06c0f-d11e-4906-8102-ea8581ed7989)
</div>
# Contributing
We welcome contributions from everyone, and we appreciate your help to make this project even better! If you would like to contribute, please follow these guidelines:
## Contributors
- Fattouhi Radwa ([GitHub](https://github.com/Radwa-f))
- Douidy Sifeddine ([GitHub](https://github.com/SaifeddineDouidy))
- Mohamed Lachgar ([Researchgate](https://www.researchgate.net/profile/Mohamed-Lachgar))
### Improvements:
- Ensure clean, maintainable, and scalable code through automated reviews.
- Code Quality Maintenance.
- Integrate IoT sensors for more accurate data.
- AI-Based Enhancements.
- Enhance architecture for larger datasets and dynamic alerting systems. |
import { Transition } from "@headlessui/react";
import { useContext, useState } from "react";
import Loading from "../../../components/ui/loading";
import { useSSE } from "../../../contexts/SSEContext";
import { alertContext } from "../../../contexts/alertContext";
import { typesContext } from "../../../contexts/typesContext";
import { postBuildInit } from "../../../controllers/API";
import { FlowType } from "../../../types/flow";
import { TabsContext } from "../../../contexts/tabsContext";
import { parsedDataType } from "../../../types/components";
import { TabsState } from "../../../types/tabs";
import { validateNodes } from "../../../utils/reactflowUtils";
import RadialProgressComponent from "../../RadialProgress";
import IconComponent from "../../genericIconComponent";
export default function BuildTrigger({
open,
flow,
setIsBuilt,
}: {
open: boolean;
flow: FlowType;
setIsBuilt: any;
isBuilt: boolean;
}): JSX.Element {
const { updateSSEData, isBuilding, setIsBuilding, sseData } = useSSE();
const { reactFlowInstance } = useContext(typesContext);
const { setTabsState } = useContext(TabsContext);
const { setErrorData, setSuccessData } = useContext(alertContext);
const [isIconTouched, setIsIconTouched] = useState(false);
const eventClick = isBuilding ? "pointer-events-none" : "";
const [progress, setProgress] = useState(0);
async function handleBuild(flow: FlowType): Promise<void> {
try {
if (isBuilding) {
return;
}
const errors = validateNodes(reactFlowInstance!);
if (errors.length > 0) {
setErrorData({
title: "Oops! Looks like you missed something",
list: errors,
});
return;
}
const minimumLoadingTime = 200; // in milliseconds
const startTime = Date.now();
setIsBuilding(true);
const allNodesValid = await streamNodeData(flow);
await enforceMinimumLoadingTime(startTime, minimumLoadingTime);
setIsBuilt(allNodesValid);
if (!allNodesValid) {
setErrorData({
title: "Oops! Looks like you missed something",
list: [
"Check components and retry. Hover over component status icon 🔴 to inspect.",
],
});
}
if (errors.length === 0 && allNodesValid) {
setSuccessData({
title: "Flow is ready to run",
});
}
} catch (error) {
console.error("Error:", error);
} finally {
setIsBuilding(false);
}
}
async function streamNodeData(flow: FlowType) {
// Step 1: Make a POST request to send the flow data and receive a unique session ID
const response = await postBuildInit(flow);
const { flowId } = response.data;
// Step 2: Use the session ID to establish an SSE connection using EventSource
let validationResults: boolean[] = [];
let finished = false;
const apiUrl = `/api/v1/build/stream/${flowId}`;
const eventSource = new EventSource(apiUrl);
eventSource.onmessage = (event) => {
// If the event is parseable, return
if (!event.data) {
return;
}
const parsedData = JSON.parse(event.data);
// if the event is the end of the stream, close the connection
if (parsedData.end_of_stream) {
// Close the connection and finish
finished = true;
eventSource.close();
return;
} else if (parsedData.log) {
// If the event is a log, log it
setSuccessData({ title: parsedData.log });
} else if (parsedData.input_keys !== undefined) {
//@ts-ignore
setTabsState((old: TabsState) => {
return {
...old,
[flowId]: {
...old[flowId],
formKeysData: parsedData,
},
};
});
} else {
// Otherwise, process the data
const isValid = processStreamResult(parsedData);
setProgress(parsedData.progress);
validationResults.push(isValid);
}
};
eventSource.onerror = (error: any) => {
console.error("EventSource failed:", error);
eventSource.close();
if (error.data) {
const parsedData = JSON.parse(error.data);
setErrorData({ title: parsedData.error });
setIsBuilding(false);
}
};
// Step 3: Wait for the stream to finish
while (!finished) {
await new Promise((resolve) => setTimeout(resolve, 100));
finished = validationResults.length === flow.data!.nodes.length;
}
// Step 4: Return true if all nodes are valid, false otherwise
return validationResults.every((result) => result);
}
function processStreamResult(parsedData: parsedDataType) {
// Process each chunk of data here
// Parse the chunk and update the context
try {
updateSSEData({ [parsedData.id]: parsedData });
} catch (err) {
console.log("Error parsing stream data: ", err);
}
return parsedData.valid;
}
async function enforceMinimumLoadingTime(
startTime: number,
minimumLoadingTime: number
) {
const elapsedTime = Date.now() - startTime;
const remainingTime = minimumLoadingTime - elapsedTime;
if (remainingTime > 0) {
return new Promise((resolve) => setTimeout(resolve, remainingTime));
}
}
const handleMouseEnter = () => {
setIsIconTouched(true);
};
const handleMouseLeave = () => {
setIsIconTouched(false);
};
return (
<Transition
show={!open}
appear={true}
enter="transition ease-out duration-300"
enterFrom="translate-y-96"
enterTo="translate-y-0"
leave="transition ease-in duration-300"
leaveFrom="translate-y-0"
leaveTo="translate-y-96"
>
<div className="fixed bottom-20 right-4">
<div
className={`${eventClick} round-button-form`}
onClick={() => {
handleBuild(flow);
}}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<button>
<div className="round-button-div">
{isBuilding && progress < 1 ? (
// Render your loading animation here when isBuilding is true
<RadialProgressComponent
// ! confirm below works
color={"text-build-trigger"}
value={progress}
></RadialProgressComponent>
) : isBuilding ? (
<Loading
strokeWidth={1.5}
className="build-trigger-loading-icon"
/>
) : (
<IconComponent
name="Zap"
className="sh-6 w-6 fill-build-trigger stroke-build-trigger stroke-1"
/>
)}
</div>
</button>
</div>
</div>
</Transition>
);
} |
import { Bird } from "./Bird";
import { ICanFly } from "./iCanFly";
import { IcanSwin } from "./IcanSwin";
import { ICanWalk } from "./ICanWalk";
class Duck extends Bird implements ICanWalk, ICanFly, IcanSwin{
public color : string
constructor (name : string , lifeTime : number , size : number , weight : number, canFly : boolean,color : string ){
super (name , lifeTime , size , weight , canFly)
this.color = color;
}
public fly(): void {
console.log(`${this.name} starts to fly! `)
}
public swin(): void {
console.log(`${this.name} starts to swin`)
}
public walk(): void {
console.log(`${this.name} starts to walk`)
}
}
export {Duck} |
---
title: Updated Reverse Video in FCP A Step-by-Step Guide for Beginners
date: 2024-05-19T10:32:32.017Z
updated: 2024-05-20T10:32:32.018Z
tags:
- video editing software
- video editing
categories:
- ai
- video
description: This Article Describes Updated Reverse Video in FCP A Step-by-Step Guide for Beginners
excerpt: This Article Describes Updated Reverse Video in FCP A Step-by-Step Guide for Beginners
keywords: tiktok video reversal made easy a beginners guide updated,free video editing for beginners a step by step guide to getting started,the best mac video editors for beginners a step by step guide,gopro video editing made easy a step by step guide for beginners,mastering fcp audio a step by step guide for video editors,reverse engineering a step by step guide to reversing tiktok videos,reverse video in fcp a step by step guide for beginners
thumbnail: https://www.lifewire.com/thmb/eYqxG8EorGAmKcW0zOiG4PnWFkw=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/homeweatherstation-34f9e9a9aaf64446a8f21ff05991c079.jpg
---
## Reverse Video in FCP: A Step-by-Step Guide for Beginners
# How to Reverse A Video in Final Cut Pro

##### Benjamin Arango
Mar 27, 2024• Proven solutions
There are so many situations in our life when we wish to go back in past and change things for better scope; sadly, life does not provide that option in real. But there is an option to rewind or reverse things in the world of video editing as here one can easily make time fly backward and view things for fun. Before you start using the skills and tools for editing videos to create such a beautiful effect, it is good to go through few important terms.
---
The information above provides just basic information about Final Cut Pro X software tool of Apple platform. It serves like a professional editing tool for videos with its incredible features but if you are a beginner to this video editing platform then it is better to use [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). You will be glad to know that Wondershare Filmora contains all quality features for video editing needs with its easy to operate user interface. You can download the trial version of this software tool from official website.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
**You May Also Like:** [How to Reverse videos in Adobe Premiere Pro >>](https://tools.techidaily.com/wondershare/filmora/download/)
#### **Difference between Rewind and Reverse:**
#### **Reverse:**
The word reverse as the name reflects, means that we can play a video from its end towards the initial position. Yes, it is possible to reverse the order of video frames in order to arrange them in such a way that last frame appears first following the reverse sequence so that first frame goes to the last position in the clip.
#### **Rewind:**
On the other side rewind is also an interesting feature for video editing where users simply duplicate the clip in form of a segment or make adjustments over range selection and then rewind that particular segment at a speed many times faster than the original speed of clip. After this they play segment of original clip in normal speed towards forward direction.
Although it is possible to get the rewind effect in videos with simple reverse option but still Apple platform supports both of these as standalone options.
## How to reverse a clip in Final Cut Pro
You might have heard about Retiming effect in videos where we either speed up our clip or slow it down by certain time factor so that a desired effect can be achieved. There are two types of retiming effects: Variable speed type and constant speed format. FCP is capable enough to merge the reverse option with retiming effects so that something innovative can be developed even with simple editing efforts.
#### **Step 1:**
First of all go to timeline and then select the desired clip from your collection that you want to reverse. It is also possible to apply this effect on a group of clips as per need.
#### **Step 2:**
Now you need to go to the pop up menu where an option for reverse the clip is available in form of an arrow pointing towards left direction.

Hit that reverse option.

#### **Step 3:**
In case if you want to customize speed of reversed clip then use retiming handle and drag it to right or left as per need of decreasing or increasing the clip speed.

#### **Step 4:**
Now hit the play option to view video with reverse effect.
## How to Rewind Videos using Final Cut Pro
On Apple platform you can also Rewind videos clips as per need. This option is mostly utilized for action sequences as well as for sports.
#### **Step 1:**
Go to timeline and select clips that you want to rewind.
#### **Step 2:**
Now from pop-up menu select rewind option and choose desired speed limit for this action.

#### **Step 3:**
Drag the retiming handler to adjust the speed as per need.

#### **Step 4:**
Play the clip to view editing effects.
## An Easier Way to Reverse A Video in Filmora
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a free video editing program for reversing videos that is simple to use. It lets users publish their movies to the internet, as well as produce new ones and modify old ones. The procedures for reversing films in Filmora are simple and straightforward, so you may follow them without difficulty.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**Step 1**: To upload a video, first click "Import." You may also simply drag and drop media files into the Media Library, and they will display on the preview/program monitor. You may see your videos in waveform display and Vectorscope format after you've added them to the timeline. You may also watch a live filmstrip preview to see what's going on in the video.

**Step 2**: Place the video on the video track by dragging and dropping it. You may select Speed and Duration by right-clicking it on the track. Then, on the Custom Speed panel, enable the Reverse Speed option. You may also select Reverse by clicking the Speed symbol in the toolbar.


**Step 3**: Click “Export” to save your file.


Benjamin Arango
Benjamin Arango is a writer and a lover of all things video.
Follow @Benjamin Arango
##### Benjamin Arango
Mar 27, 2024• Proven solutions
There are so many situations in our life when we wish to go back in past and change things for better scope; sadly, life does not provide that option in real. But there is an option to rewind or reverse things in the world of video editing as here one can easily make time fly backward and view things for fun. Before you start using the skills and tools for editing videos to create such a beautiful effect, it is good to go through few important terms.
---
The information above provides just basic information about Final Cut Pro X software tool of Apple platform. It serves like a professional editing tool for videos with its incredible features but if you are a beginner to this video editing platform then it is better to use [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). You will be glad to know that Wondershare Filmora contains all quality features for video editing needs with its easy to operate user interface. You can download the trial version of this software tool from official website.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
**You May Also Like:** [How to Reverse videos in Adobe Premiere Pro >>](https://tools.techidaily.com/wondershare/filmora/download/)
#### **Difference between Rewind and Reverse:**
#### **Reverse:**
The word reverse as the name reflects, means that we can play a video from its end towards the initial position. Yes, it is possible to reverse the order of video frames in order to arrange them in such a way that last frame appears first following the reverse sequence so that first frame goes to the last position in the clip.
#### **Rewind:**
On the other side rewind is also an interesting feature for video editing where users simply duplicate the clip in form of a segment or make adjustments over range selection and then rewind that particular segment at a speed many times faster than the original speed of clip. After this they play segment of original clip in normal speed towards forward direction.
Although it is possible to get the rewind effect in videos with simple reverse option but still Apple platform supports both of these as standalone options.
## How to reverse a clip in Final Cut Pro
You might have heard about Retiming effect in videos where we either speed up our clip or slow it down by certain time factor so that a desired effect can be achieved. There are two types of retiming effects: Variable speed type and constant speed format. FCP is capable enough to merge the reverse option with retiming effects so that something innovative can be developed even with simple editing efforts.
#### **Step 1:**
First of all go to timeline and then select the desired clip from your collection that you want to reverse. It is also possible to apply this effect on a group of clips as per need.
#### **Step 2:**
Now you need to go to the pop up menu where an option for reverse the clip is available in form of an arrow pointing towards left direction.

Hit that reverse option.

#### **Step 3:**
In case if you want to customize speed of reversed clip then use retiming handle and drag it to right or left as per need of decreasing or increasing the clip speed.

#### **Step 4:**
Now hit the play option to view video with reverse effect.
## How to Rewind Videos using Final Cut Pro
On Apple platform you can also Rewind videos clips as per need. This option is mostly utilized for action sequences as well as for sports.
#### **Step 1:**
Go to timeline and select clips that you want to rewind.
#### **Step 2:**
Now from pop-up menu select rewind option and choose desired speed limit for this action.

#### **Step 3:**
Drag the retiming handler to adjust the speed as per need.

#### **Step 4:**
Play the clip to view editing effects.
## An Easier Way to Reverse A Video in Filmora
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a free video editing program for reversing videos that is simple to use. It lets users publish their movies to the internet, as well as produce new ones and modify old ones. The procedures for reversing films in Filmora are simple and straightforward, so you may follow them without difficulty.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**Step 1**: To upload a video, first click "Import." You may also simply drag and drop media files into the Media Library, and they will display on the preview/program monitor. You may see your videos in waveform display and Vectorscope format after you've added them to the timeline. You may also watch a live filmstrip preview to see what's going on in the video.

**Step 2**: Place the video on the video track by dragging and dropping it. You may select Speed and Duration by right-clicking it on the track. Then, on the Custom Speed panel, enable the Reverse Speed option. You may also select Reverse by clicking the Speed symbol in the toolbar.


**Step 3**: Click “Export” to save your file.


Benjamin Arango
Benjamin Arango is a writer and a lover of all things video.
Follow @Benjamin Arango
##### Benjamin Arango
Mar 27, 2024• Proven solutions
There are so many situations in our life when we wish to go back in past and change things for better scope; sadly, life does not provide that option in real. But there is an option to rewind or reverse things in the world of video editing as here one can easily make time fly backward and view things for fun. Before you start using the skills and tools for editing videos to create such a beautiful effect, it is good to go through few important terms.
---
The information above provides just basic information about Final Cut Pro X software tool of Apple platform. It serves like a professional editing tool for videos with its incredible features but if you are a beginner to this video editing platform then it is better to use [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). You will be glad to know that Wondershare Filmora contains all quality features for video editing needs with its easy to operate user interface. You can download the trial version of this software tool from official website.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
**You May Also Like:** [How to Reverse videos in Adobe Premiere Pro >>](https://tools.techidaily.com/wondershare/filmora/download/)
#### **Difference between Rewind and Reverse:**
#### **Reverse:**
The word reverse as the name reflects, means that we can play a video from its end towards the initial position. Yes, it is possible to reverse the order of video frames in order to arrange them in such a way that last frame appears first following the reverse sequence so that first frame goes to the last position in the clip.
#### **Rewind:**
On the other side rewind is also an interesting feature for video editing where users simply duplicate the clip in form of a segment or make adjustments over range selection and then rewind that particular segment at a speed many times faster than the original speed of clip. After this they play segment of original clip in normal speed towards forward direction.
Although it is possible to get the rewind effect in videos with simple reverse option but still Apple platform supports both of these as standalone options.
## How to reverse a clip in Final Cut Pro
You might have heard about Retiming effect in videos where we either speed up our clip or slow it down by certain time factor so that a desired effect can be achieved. There are two types of retiming effects: Variable speed type and constant speed format. FCP is capable enough to merge the reverse option with retiming effects so that something innovative can be developed even with simple editing efforts.
#### **Step 1:**
First of all go to timeline and then select the desired clip from your collection that you want to reverse. It is also possible to apply this effect on a group of clips as per need.
#### **Step 2:**
Now you need to go to the pop up menu where an option for reverse the clip is available in form of an arrow pointing towards left direction.

Hit that reverse option.

#### **Step 3:**
In case if you want to customize speed of reversed clip then use retiming handle and drag it to right or left as per need of decreasing or increasing the clip speed.

#### **Step 4:**
Now hit the play option to view video with reverse effect.
## How to Rewind Videos using Final Cut Pro
On Apple platform you can also Rewind videos clips as per need. This option is mostly utilized for action sequences as well as for sports.
#### **Step 1:**
Go to timeline and select clips that you want to rewind.
#### **Step 2:**
Now from pop-up menu select rewind option and choose desired speed limit for this action.

#### **Step 3:**
Drag the retiming handler to adjust the speed as per need.

#### **Step 4:**
Play the clip to view editing effects.
## An Easier Way to Reverse A Video in Filmora
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a free video editing program for reversing videos that is simple to use. It lets users publish their movies to the internet, as well as produce new ones and modify old ones. The procedures for reversing films in Filmora are simple and straightforward, so you may follow them without difficulty.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**Step 1**: To upload a video, first click "Import." You may also simply drag and drop media files into the Media Library, and they will display on the preview/program monitor. You may see your videos in waveform display and Vectorscope format after you've added them to the timeline. You may also watch a live filmstrip preview to see what's going on in the video.

**Step 2**: Place the video on the video track by dragging and dropping it. You may select Speed and Duration by right-clicking it on the track. Then, on the Custom Speed panel, enable the Reverse Speed option. You may also select Reverse by clicking the Speed symbol in the toolbar.


**Step 3**: Click “Export” to save your file.


Benjamin Arango
Benjamin Arango is a writer and a lover of all things video.
Follow @Benjamin Arango
##### Benjamin Arango
Mar 27, 2024• Proven solutions
There are so many situations in our life when we wish to go back in past and change things for better scope; sadly, life does not provide that option in real. But there is an option to rewind or reverse things in the world of video editing as here one can easily make time fly backward and view things for fun. Before you start using the skills and tools for editing videos to create such a beautiful effect, it is good to go through few important terms.
---
The information above provides just basic information about Final Cut Pro X software tool of Apple platform. It serves like a professional editing tool for videos with its incredible features but if you are a beginner to this video editing platform then it is better to use [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). You will be glad to know that Wondershare Filmora contains all quality features for video editing needs with its easy to operate user interface. You can download the trial version of this software tool from official website.
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
**You May Also Like:** [How to Reverse videos in Adobe Premiere Pro >>](https://tools.techidaily.com/wondershare/filmora/download/)
#### **Difference between Rewind and Reverse:**
#### **Reverse:**
The word reverse as the name reflects, means that we can play a video from its end towards the initial position. Yes, it is possible to reverse the order of video frames in order to arrange them in such a way that last frame appears first following the reverse sequence so that first frame goes to the last position in the clip.
#### **Rewind:**
On the other side rewind is also an interesting feature for video editing where users simply duplicate the clip in form of a segment or make adjustments over range selection and then rewind that particular segment at a speed many times faster than the original speed of clip. After this they play segment of original clip in normal speed towards forward direction.
Although it is possible to get the rewind effect in videos with simple reverse option but still Apple platform supports both of these as standalone options.
## How to reverse a clip in Final Cut Pro
You might have heard about Retiming effect in videos where we either speed up our clip or slow it down by certain time factor so that a desired effect can be achieved. There are two types of retiming effects: Variable speed type and constant speed format. FCP is capable enough to merge the reverse option with retiming effects so that something innovative can be developed even with simple editing efforts.
#### **Step 1:**
First of all go to timeline and then select the desired clip from your collection that you want to reverse. It is also possible to apply this effect on a group of clips as per need.
#### **Step 2:**
Now you need to go to the pop up menu where an option for reverse the clip is available in form of an arrow pointing towards left direction.

Hit that reverse option.

#### **Step 3:**
In case if you want to customize speed of reversed clip then use retiming handle and drag it to right or left as per need of decreasing or increasing the clip speed.

#### **Step 4:**
Now hit the play option to view video with reverse effect.
## How to Rewind Videos using Final Cut Pro
On Apple platform you can also Rewind videos clips as per need. This option is mostly utilized for action sequences as well as for sports.
#### **Step 1:**
Go to timeline and select clips that you want to rewind.
#### **Step 2:**
Now from pop-up menu select rewind option and choose desired speed limit for this action.

#### **Step 3:**
Drag the retiming handler to adjust the speed as per need.

#### **Step 4:**
Play the clip to view editing effects.
## An Easier Way to Reverse A Video in Filmora
[Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) is a free video editing program for reversing videos that is simple to use. It lets users publish their movies to the internet, as well as produce new ones and modify old ones. The procedures for reversing films in Filmora are simple and straightforward, so you may follow them without difficulty.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**Step 1**: To upload a video, first click "Import." You may also simply drag and drop media files into the Media Library, and they will display on the preview/program monitor. You may see your videos in waveform display and Vectorscope format after you've added them to the timeline. You may also watch a live filmstrip preview to see what's going on in the video.

**Step 2**: Place the video on the video track by dragging and dropping it. You may select Speed and Duration by right-clicking it on the track. Then, on the Custom Speed panel, enable the Reverse Speed option. You may also select Reverse by clicking the Speed symbol in the toolbar.


**Step 3**: Click “Export” to save your file.


Benjamin Arango
Benjamin Arango is a writer and a lover of all things video.
Follow @Benjamin Arango
<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>
## Beyond Windows 10 Photos: 8 Excellent Image Editing Options
# 8 Best Alternatives to Windows 10 Photos

##### Shanoon Cox
Mar 27, 2024• Proven solutions
While using a Windows computer, we are comfortable viewing the images with [Windows Photo Viewer](https://tools.techidaily.com/wondershare/filmora/download/). The ease of use and being the default program with our system, we tend to rely heavily on it. Now that the tool has been upgraded to Windows 10 Photos with added features, it has been equipped with enhanced functionalities as well.
But, there are people who find it difficult to work around as they find it complex to use. So, if you are one of them, then here we bring the most effective Windows 10 Photos alternatives.
Go through this article to discover more options to work without Windows 10 Photos.
## Best alternative to Windows 10 photos
Here is a collection of the top 8 Windows 10 Photos alternatives for your convenience.
### Recommended: Wondershare Filmora
Being a top notch video editor, [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) offers you photo editing as well. You can create slide shows, memes, GIFs and what not. There are thousands of effects that you can add on to beautify your image. Moreover, you can alter the saturation, photo styles, tune colors and much more. PIP and background blurring is also supported by this amazing Windows 10 Photos alternative.
**Features**:
* It is available for both Mac and Windows computers.
* You get to use advanced filters and overlays, motion elements, 4K editing, GIF creation, text and titles etc.
* You can directly export photos from social media platforms.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
### 1. [XnView](https://www.xnview.com/en/xnview/)
This tool can act as a perfect Windows 10 Photos alternative for viewing images. XnView can work as an image viewer, converter and browser for Windows systems. This intuitive program is quick to learn and costs you nothing for personal use. There are no adware or spywares, as well as it supports 500 plus image formats.
**Features**:
* You can organize, browse, as well as view images using XnView as thumbnails, fullscreen, slideshow, images compare or filmstrip etc.
* You can modify color depth and palette, apply effects and filters, , as well as lossless crop and rotate etc.
* With 70 plus formats, it helps exporting images and creating web pages, slideshow, contact sheets, video thumbnails gallery and image strips.

### 2. [123 Photo Viewer](https://www.microsoft.com/en-us/p/123-photo-viewer/9wzdncrdxfxg?activetab=pivot:overviewtab)
When we talk about Windows 10 Photos alternative, 123 Photo Viewer should not be left behind. It supports DDS, PSD, WEBP, TGA formats, GIF etc. Single click magnifying feature is one of the best ones about this software.
**Features**:
* Fast magnification time.
* It supports batch operations for fulfilling various purposes.
* Offers convenience for switching between previous and next images.

### 3. [ImageGlass](https://imageglass.org/)
Image Glass is one of the most effective programs for image editing and viewing. The interface is a neat and nice one. It supports HEIC, SVG, GIF and RAW images.
**Features**:
* This software is a lightweight one which enables you to switch faster between photos.
* Its versatility makes things easier for users.
* You can easily install new themes and language packages.

### 4. [Honeyview](https://imagine-picture-viewer.en.softonic.com/)
It supports a wide range of image formats including PNG, BMP, JPG, PSD, JXR, DDR, J2K etc. Animated GIFs, WebP, BPG, and PNG are also the supported animation file types. ZIP, TAR, RAR, CBZ, CBR, LZH are the popular archive formats that it supports for image viewing sans any extraction.
**Features**:
* You can edit, view, watch slideshow, copy and bookmark images using this Windows 10 Photos alternative.
* This freeware supports Windows XP/Vista/7/8/10.
* You can view EXIF in JPEG format including GPS information.

### 5. [Imagine Picture Viewer](http://www.faststone.org/FSViewerDetail.htm)
If you are looking for a lightweight Windows 10 Photos alternative, then Imagine Picture Viewer is the right place for you. You also have the facility to browse images without any bulky graphic suites. It allows you to edit your images into black and white ones or add a sepia tone or oil painting effect. Though, it is a bit slow and can undo only the last action you have performed.
**Features**:
* Direct sharing on social media platforms like Picasa, Flickr is possible.
* Basic editing tools like cropping, resizing, adjust contrast, brightness, and rotating or flipping is available.

### 6. [FastStone Viewer](http://en.bandisoft.com/honeyview/、)
This software is a stable, quick and intuitive image converter, browser and editor. You can view, crop, manage, remove red-eye, compare, resize, email, color adjust and retouch images with this tool. Supporting a wide range of graphic formats and animated GIF, popular digital image formats as well as RAW formats this program has a world to offer.
**Features**:
* It has a high-quality magnifier along with a musical slideshow having 150 plus transitional effects.
* Full-screen viewer having an image zoom support with extraordinary fly-out menu panels are there.

### 7. [Imagine](http://www.portablefreeware.com/index.php?id=1819)
Imagine is one of the lightest Windows 10 Photos alternative, which you can use at its best. You can use it to view archive files such as RAR, ZIP, 7Z etc. and convert images in batches, capture screen, browse thumbnail, and see slideshow etc. You can add supported plugins to enhance the features.
**Features**:
* It features a great GIF animator for quick deletion of frames from any GIF animation.
* When you want to show a bug, process or sequence, it helps you crisply record the screens.
* Basic animation and graphics editing features are found here.

### 8. [ACDSee](https://www.acdsee.com/en/index)
With this tool, you can do parametric photo manipulation with layers. You can review photos on your desktop, picture folder, OneDrive etc. You can even browse documents by date and view file types of business documents.
**Features**:
* 100 formats of video, image and audio is supported.
* You can zoom, magnify and use histogram.
* Filters and auto lens view helps preview the final result.

[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Shanoon Cox
Shanoon Cox is a writer and a lover of all things video.
Follow @Shanoon Cox
##### Shanoon Cox
Mar 27, 2024• Proven solutions
While using a Windows computer, we are comfortable viewing the images with [Windows Photo Viewer](https://tools.techidaily.com/wondershare/filmora/download/). The ease of use and being the default program with our system, we tend to rely heavily on it. Now that the tool has been upgraded to Windows 10 Photos with added features, it has been equipped with enhanced functionalities as well.
But, there are people who find it difficult to work around as they find it complex to use. So, if you are one of them, then here we bring the most effective Windows 10 Photos alternatives.
Go through this article to discover more options to work without Windows 10 Photos.
## Best alternative to Windows 10 photos
Here is a collection of the top 8 Windows 10 Photos alternatives for your convenience.
### Recommended: Wondershare Filmora
Being a top notch video editor, [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) offers you photo editing as well. You can create slide shows, memes, GIFs and what not. There are thousands of effects that you can add on to beautify your image. Moreover, you can alter the saturation, photo styles, tune colors and much more. PIP and background blurring is also supported by this amazing Windows 10 Photos alternative.
**Features**:
* It is available for both Mac and Windows computers.
* You get to use advanced filters and overlays, motion elements, 4K editing, GIF creation, text and titles etc.
* You can directly export photos from social media platforms.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
### 1. [XnView](https://www.xnview.com/en/xnview/)
This tool can act as a perfect Windows 10 Photos alternative for viewing images. XnView can work as an image viewer, converter and browser for Windows systems. This intuitive program is quick to learn and costs you nothing for personal use. There are no adware or spywares, as well as it supports 500 plus image formats.
**Features**:
* You can organize, browse, as well as view images using XnView as thumbnails, fullscreen, slideshow, images compare or filmstrip etc.
* You can modify color depth and palette, apply effects and filters, , as well as lossless crop and rotate etc.
* With 70 plus formats, it helps exporting images and creating web pages, slideshow, contact sheets, video thumbnails gallery and image strips.

### 2. [123 Photo Viewer](https://www.microsoft.com/en-us/p/123-photo-viewer/9wzdncrdxfxg?activetab=pivot:overviewtab)
When we talk about Windows 10 Photos alternative, 123 Photo Viewer should not be left behind. It supports DDS, PSD, WEBP, TGA formats, GIF etc. Single click magnifying feature is one of the best ones about this software.
**Features**:
* Fast magnification time.
* It supports batch operations for fulfilling various purposes.
* Offers convenience for switching between previous and next images.

### 3. [ImageGlass](https://imageglass.org/)
Image Glass is one of the most effective programs for image editing and viewing. The interface is a neat and nice one. It supports HEIC, SVG, GIF and RAW images.
**Features**:
* This software is a lightweight one which enables you to switch faster between photos.
* Its versatility makes things easier for users.
* You can easily install new themes and language packages.

### 4. [Honeyview](https://imagine-picture-viewer.en.softonic.com/)
It supports a wide range of image formats including PNG, BMP, JPG, PSD, JXR, DDR, J2K etc. Animated GIFs, WebP, BPG, and PNG are also the supported animation file types. ZIP, TAR, RAR, CBZ, CBR, LZH are the popular archive formats that it supports for image viewing sans any extraction.
**Features**:
* You can edit, view, watch slideshow, copy and bookmark images using this Windows 10 Photos alternative.
* This freeware supports Windows XP/Vista/7/8/10.
* You can view EXIF in JPEG format including GPS information.

### 5. [Imagine Picture Viewer](http://www.faststone.org/FSViewerDetail.htm)
If you are looking for a lightweight Windows 10 Photos alternative, then Imagine Picture Viewer is the right place for you. You also have the facility to browse images without any bulky graphic suites. It allows you to edit your images into black and white ones or add a sepia tone or oil painting effect. Though, it is a bit slow and can undo only the last action you have performed.
**Features**:
* Direct sharing on social media platforms like Picasa, Flickr is possible.
* Basic editing tools like cropping, resizing, adjust contrast, brightness, and rotating or flipping is available.

### 6. [FastStone Viewer](http://en.bandisoft.com/honeyview/、)
This software is a stable, quick and intuitive image converter, browser and editor. You can view, crop, manage, remove red-eye, compare, resize, email, color adjust and retouch images with this tool. Supporting a wide range of graphic formats and animated GIF, popular digital image formats as well as RAW formats this program has a world to offer.
**Features**:
* It has a high-quality magnifier along with a musical slideshow having 150 plus transitional effects.
* Full-screen viewer having an image zoom support with extraordinary fly-out menu panels are there.

### 7. [Imagine](http://www.portablefreeware.com/index.php?id=1819)
Imagine is one of the lightest Windows 10 Photos alternative, which you can use at its best. You can use it to view archive files such as RAR, ZIP, 7Z etc. and convert images in batches, capture screen, browse thumbnail, and see slideshow etc. You can add supported plugins to enhance the features.
**Features**:
* It features a great GIF animator for quick deletion of frames from any GIF animation.
* When you want to show a bug, process or sequence, it helps you crisply record the screens.
* Basic animation and graphics editing features are found here.

### 8. [ACDSee](https://www.acdsee.com/en/index)
With this tool, you can do parametric photo manipulation with layers. You can review photos on your desktop, picture folder, OneDrive etc. You can even browse documents by date and view file types of business documents.
**Features**:
* 100 formats of video, image and audio is supported.
* You can zoom, magnify and use histogram.
* Filters and auto lens view helps preview the final result.

[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Shanoon Cox
Shanoon Cox is a writer and a lover of all things video.
Follow @Shanoon Cox
##### Shanoon Cox
Mar 27, 2024• Proven solutions
While using a Windows computer, we are comfortable viewing the images with [Windows Photo Viewer](https://tools.techidaily.com/wondershare/filmora/download/). The ease of use and being the default program with our system, we tend to rely heavily on it. Now that the tool has been upgraded to Windows 10 Photos with added features, it has been equipped with enhanced functionalities as well.
But, there are people who find it difficult to work around as they find it complex to use. So, if you are one of them, then here we bring the most effective Windows 10 Photos alternatives.
Go through this article to discover more options to work without Windows 10 Photos.
## Best alternative to Windows 10 photos
Here is a collection of the top 8 Windows 10 Photos alternatives for your convenience.
### Recommended: Wondershare Filmora
Being a top notch video editor, [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) offers you photo editing as well. You can create slide shows, memes, GIFs and what not. There are thousands of effects that you can add on to beautify your image. Moreover, you can alter the saturation, photo styles, tune colors and much more. PIP and background blurring is also supported by this amazing Windows 10 Photos alternative.
**Features**:
* It is available for both Mac and Windows computers.
* You get to use advanced filters and overlays, motion elements, 4K editing, GIF creation, text and titles etc.
* You can directly export photos from social media platforms.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
### 1. [XnView](https://www.xnview.com/en/xnview/)
This tool can act as a perfect Windows 10 Photos alternative for viewing images. XnView can work as an image viewer, converter and browser for Windows systems. This intuitive program is quick to learn and costs you nothing for personal use. There are no adware or spywares, as well as it supports 500 plus image formats.
**Features**:
* You can organize, browse, as well as view images using XnView as thumbnails, fullscreen, slideshow, images compare or filmstrip etc.
* You can modify color depth and palette, apply effects and filters, , as well as lossless crop and rotate etc.
* With 70 plus formats, it helps exporting images and creating web pages, slideshow, contact sheets, video thumbnails gallery and image strips.

### 2. [123 Photo Viewer](https://www.microsoft.com/en-us/p/123-photo-viewer/9wzdncrdxfxg?activetab=pivot:overviewtab)
When we talk about Windows 10 Photos alternative, 123 Photo Viewer should not be left behind. It supports DDS, PSD, WEBP, TGA formats, GIF etc. Single click magnifying feature is one of the best ones about this software.
**Features**:
* Fast magnification time.
* It supports batch operations for fulfilling various purposes.
* Offers convenience for switching between previous and next images.

### 3. [ImageGlass](https://imageglass.org/)
Image Glass is one of the most effective programs for image editing and viewing. The interface is a neat and nice one. It supports HEIC, SVG, GIF and RAW images.
**Features**:
* This software is a lightweight one which enables you to switch faster between photos.
* Its versatility makes things easier for users.
* You can easily install new themes and language packages.

### 4. [Honeyview](https://imagine-picture-viewer.en.softonic.com/)
It supports a wide range of image formats including PNG, BMP, JPG, PSD, JXR, DDR, J2K etc. Animated GIFs, WebP, BPG, and PNG are also the supported animation file types. ZIP, TAR, RAR, CBZ, CBR, LZH are the popular archive formats that it supports for image viewing sans any extraction.
**Features**:
* You can edit, view, watch slideshow, copy and bookmark images using this Windows 10 Photos alternative.
* This freeware supports Windows XP/Vista/7/8/10.
* You can view EXIF in JPEG format including GPS information.

### 5. [Imagine Picture Viewer](http://www.faststone.org/FSViewerDetail.htm)
If you are looking for a lightweight Windows 10 Photos alternative, then Imagine Picture Viewer is the right place for you. You also have the facility to browse images without any bulky graphic suites. It allows you to edit your images into black and white ones or add a sepia tone or oil painting effect. Though, it is a bit slow and can undo only the last action you have performed.
**Features**:
* Direct sharing on social media platforms like Picasa, Flickr is possible.
* Basic editing tools like cropping, resizing, adjust contrast, brightness, and rotating or flipping is available.

### 6. [FastStone Viewer](http://en.bandisoft.com/honeyview/、)
This software is a stable, quick and intuitive image converter, browser and editor. You can view, crop, manage, remove red-eye, compare, resize, email, color adjust and retouch images with this tool. Supporting a wide range of graphic formats and animated GIF, popular digital image formats as well as RAW formats this program has a world to offer.
**Features**:
* It has a high-quality magnifier along with a musical slideshow having 150 plus transitional effects.
* Full-screen viewer having an image zoom support with extraordinary fly-out menu panels are there.

### 7. [Imagine](http://www.portablefreeware.com/index.php?id=1819)
Imagine is one of the lightest Windows 10 Photos alternative, which you can use at its best. You can use it to view archive files such as RAR, ZIP, 7Z etc. and convert images in batches, capture screen, browse thumbnail, and see slideshow etc. You can add supported plugins to enhance the features.
**Features**:
* It features a great GIF animator for quick deletion of frames from any GIF animation.
* When you want to show a bug, process or sequence, it helps you crisply record the screens.
* Basic animation and graphics editing features are found here.

### 8. [ACDSee](https://www.acdsee.com/en/index)
With this tool, you can do parametric photo manipulation with layers. You can review photos on your desktop, picture folder, OneDrive etc. You can even browse documents by date and view file types of business documents.
**Features**:
* 100 formats of video, image and audio is supported.
* You can zoom, magnify and use histogram.
* Filters and auto lens view helps preview the final result.

[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Shanoon Cox
Shanoon Cox is a writer and a lover of all things video.
Follow @Shanoon Cox
##### Shanoon Cox
Mar 27, 2024• Proven solutions
While using a Windows computer, we are comfortable viewing the images with [Windows Photo Viewer](https://tools.techidaily.com/wondershare/filmora/download/). The ease of use and being the default program with our system, we tend to rely heavily on it. Now that the tool has been upgraded to Windows 10 Photos with added features, it has been equipped with enhanced functionalities as well.
But, there are people who find it difficult to work around as they find it complex to use. So, if you are one of them, then here we bring the most effective Windows 10 Photos alternatives.
Go through this article to discover more options to work without Windows 10 Photos.
## Best alternative to Windows 10 photos
Here is a collection of the top 8 Windows 10 Photos alternatives for your convenience.
### Recommended: Wondershare Filmora
Being a top notch video editor, [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) offers you photo editing as well. You can create slide shows, memes, GIFs and what not. There are thousands of effects that you can add on to beautify your image. Moreover, you can alter the saturation, photo styles, tune colors and much more. PIP and background blurring is also supported by this amazing Windows 10 Photos alternative.
**Features**:
* It is available for both Mac and Windows computers.
* You get to use advanced filters and overlays, motion elements, 4K editing, GIF creation, text and titles etc.
* You can directly export photos from social media platforms.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
### 1. [XnView](https://www.xnview.com/en/xnview/)
This tool can act as a perfect Windows 10 Photos alternative for viewing images. XnView can work as an image viewer, converter and browser for Windows systems. This intuitive program is quick to learn and costs you nothing for personal use. There are no adware or spywares, as well as it supports 500 plus image formats.
**Features**:
* You can organize, browse, as well as view images using XnView as thumbnails, fullscreen, slideshow, images compare or filmstrip etc.
* You can modify color depth and palette, apply effects and filters, , as well as lossless crop and rotate etc.
* With 70 plus formats, it helps exporting images and creating web pages, slideshow, contact sheets, video thumbnails gallery and image strips.

### 2. [123 Photo Viewer](https://www.microsoft.com/en-us/p/123-photo-viewer/9wzdncrdxfxg?activetab=pivot:overviewtab)
When we talk about Windows 10 Photos alternative, 123 Photo Viewer should not be left behind. It supports DDS, PSD, WEBP, TGA formats, GIF etc. Single click magnifying feature is one of the best ones about this software.
**Features**:
* Fast magnification time.
* It supports batch operations for fulfilling various purposes.
* Offers convenience for switching between previous and next images.

### 3. [ImageGlass](https://imageglass.org/)
Image Glass is one of the most effective programs for image editing and viewing. The interface is a neat and nice one. It supports HEIC, SVG, GIF and RAW images.
**Features**:
* This software is a lightweight one which enables you to switch faster between photos.
* Its versatility makes things easier for users.
* You can easily install new themes and language packages.

### 4. [Honeyview](https://imagine-picture-viewer.en.softonic.com/)
It supports a wide range of image formats including PNG, BMP, JPG, PSD, JXR, DDR, J2K etc. Animated GIFs, WebP, BPG, and PNG are also the supported animation file types. ZIP, TAR, RAR, CBZ, CBR, LZH are the popular archive formats that it supports for image viewing sans any extraction.
**Features**:
* You can edit, view, watch slideshow, copy and bookmark images using this Windows 10 Photos alternative.
* This freeware supports Windows XP/Vista/7/8/10.
* You can view EXIF in JPEG format including GPS information.

### 5. [Imagine Picture Viewer](http://www.faststone.org/FSViewerDetail.htm)
If you are looking for a lightweight Windows 10 Photos alternative, then Imagine Picture Viewer is the right place for you. You also have the facility to browse images without any bulky graphic suites. It allows you to edit your images into black and white ones or add a sepia tone or oil painting effect. Though, it is a bit slow and can undo only the last action you have performed.
**Features**:
* Direct sharing on social media platforms like Picasa, Flickr is possible.
* Basic editing tools like cropping, resizing, adjust contrast, brightness, and rotating or flipping is available.

### 6. [FastStone Viewer](http://en.bandisoft.com/honeyview/、)
This software is a stable, quick and intuitive image converter, browser and editor. You can view, crop, manage, remove red-eye, compare, resize, email, color adjust and retouch images with this tool. Supporting a wide range of graphic formats and animated GIF, popular digital image formats as well as RAW formats this program has a world to offer.
**Features**:
* It has a high-quality magnifier along with a musical slideshow having 150 plus transitional effects.
* Full-screen viewer having an image zoom support with extraordinary fly-out menu panels are there.

### 7. [Imagine](http://www.portablefreeware.com/index.php?id=1819)
Imagine is one of the lightest Windows 10 Photos alternative, which you can use at its best. You can use it to view archive files such as RAR, ZIP, 7Z etc. and convert images in batches, capture screen, browse thumbnail, and see slideshow etc. You can add supported plugins to enhance the features.
**Features**:
* It features a great GIF animator for quick deletion of frames from any GIF animation.
* When you want to show a bug, process or sequence, it helps you crisply record the screens.
* Basic animation and graphics editing features are found here.

### 8. [ACDSee](https://www.acdsee.com/en/index)
With this tool, you can do parametric photo manipulation with layers. You can review photos on your desktop, picture folder, OneDrive etc. You can even browse documents by date and view file types of business documents.
**Features**:
* 100 formats of video, image and audio is supported.
* You can zoom, magnify and use histogram.
* Filters and auto lens view helps preview the final result.

[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Shanoon Cox
Shanoon Cox is a writer and a lover of all things video.
Follow @Shanoon Cox
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## A Swift Review of VN Video Editor's PC Version
If you are keen on video editing and want to use video editing applications, choosing the app will become a daunting task once you have a clear idea about the features you need in your app. This is true for beginners eager to use a video editing app. When you have to record many images or videos as a blogger or photographer, you need something that can make the process faster. It will be better if you have something that can perform various functions simultaneously. It is not easy to find such a tool with this capability; above all, it is free of cost.

#### In this article
01 [VN Video Editor For Laptop/PC - An Overview](#part1)
02 [What Are The Features of VN editor For PC?](#part2)
03 [Best Replacement of VN Video Editor](#part3) \- \[Edit your Video with AI Tech\]
## **VN Video Editor For Laptop/PC - An Overview**
VN video editor is known as the best video editing app. This application comes with the power to provide a user-friendly interface. This app's overall performance is very good compared to other applications of the same category in various aspects. VN Video Editor for PC is all about ease of use and quality. It offers a better interface than most of the apps in the same category, and hence, it can easily cater to the needs of users who are not tech-savvy.
#### Try Other Video Editor than VN
An expert in creating and editing videos with outstanding functions and features. Offers versions for Windows, Mac, and Mobile!
[Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
Previously this video editor was only available on mobile devices. The app's popularity grew with time, so the developers decided to launch a PC version also. Now you can easily download and use vn video editor windows and vn video editor for mac depending upon your operating system and devices. In this article, we will do a detailed review of this video and will take a brief look at its features. In the end, we will let you know if this video editor is worth spending your time on or not.
VN video editor is known as the best video editing software for professionals. People looking for an alternative to Adobe premiere pro for Mac, Windows, or Free Virtual Dub for Windows can use this video editing software and get outstanding results. This is the software used by many famous editors, and you can also learn the tricks of this application by following tutorials on the internet.
It contains a movie maker/editor/slideshow and photo story and [a video editor](https://tools.techidaily.com/wondershare/filmora/download/). A powerful integrated video solution to help you create unique and charming videos, VN Video Editor brings together high quality and ease-of-use for beginners or non-professionals, whether the result is a simple home movie or high definition professional movies and slideshows, from your pc.
## **What Are The Features of VN editor For PC?**
The VN video editor for PC is loaded with features. You can find almost everything that you need to create stunning videos. Below are some of the most prominent features of this video editing software.
### 1.Keyframe Animation
To make video editing easier and the results more impressive, keyframe usage is a great feature to have. The Keyframe tool is effective when used with a camera or panning shots and with cut scenes and graphics. One of the best advantages of this tool is that it enables the user to set specific times for certain actions to be taken place and then have that action take place automatically for you. In traditional video editors, keyframing may have been a challenge. But with the VN Video Editor, you can easily use keyframe animations to transition between clips and perform some unique effects.
Try Filmora Keyframing to Creates Fantastic Visual Animations
[**Filmora keyframing**](https://tools.techidaily.com/wondershare/filmora/download/) can change positions in the hand-drawing pattern, acale subject of the clip with keyframing and customize opacity to make your shot precise and concise.
[Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
### 2.Professional Video Editing
VN video editor has everything you need to create professional-looking videos using your own photos, videos, and music. The video editor takes advantage of new video formats and supports video effects and multi-camera editing to meet professional editing needs. VN video editor comes with a timeline in which multiple images and videos can be inserted for editing. Moreover, you can edit texts with different effects and fonts. This tool is an image editing software that comes with animation templates for creating videos for fashion and photo lovers.
### 3.Lots of Effects and Filters
Are you a creative professional or just a plain fun-loving person? If yes, then VN video editor is an app that can help you get the best out of your creativity. This application is perfect for those who are looking to enhance their videos as well as to add some cool effects. It has an amazing variety of filters, effects, and other amazing features that make video editing a great fun and easy task. With this PC app, you can add stylish text, choose from a broad array of filters and effects, and so much more. All that's left for you to do is insert your photos and videos - and enjoy the final product.
### 4.Audio Tools
This software also has pretty good audio tools. VN Video Editor allows you to add audio files and apply different filter effects directly to them. You can also edit your video clips with the help of this program.
### 5.Exporting Files
Once you are done editing your videos in this amazing software, you can easily export them in your desired format. VN video editor supports a huge list of different formats so, and it will be very useful for the creator. Also, you can directly share your videos to different platforms like Youtube and Facebook.
## **Best Replacement of VN Video Editor - \[Edit your Video with AI Tech\]**
Suppose you are looking for a fully-fledged video editor that is simple to use and can compete with the most advanced video editors in the market. In that case, we recommend you give it a try to [Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/). It is packed with features, and the best thing about this video editor is that you can download it for free and try all of its premium features without paying a penny. You can also learn it quickly as it is quite popular and there are plenty of tutorials available.
[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
## **Final Verdict**
After reading all the features mentioned in this article, you might be looking for "VN video editor for pc free download." But keep in mind that, although this video editor is pretty good and comes with many amazing features, it still needs a lot of improvements and lacks a lot of tools needed in professional video editing. So, it may be good for basic users, but professionals need a better option.
#### In this article
01 [VN Video Editor For Laptop/PC - An Overview](#part1)
02 [What Are The Features of VN editor For PC?](#part2)
03 [Best Replacement of VN Video Editor](#part3) \- \[Edit your Video with AI Tech\]
## **VN Video Editor For Laptop/PC - An Overview**
VN video editor is known as the best video editing app. This application comes with the power to provide a user-friendly interface. This app's overall performance is very good compared to other applications of the same category in various aspects. VN Video Editor for PC is all about ease of use and quality. It offers a better interface than most of the apps in the same category, and hence, it can easily cater to the needs of users who are not tech-savvy.
#### Try Other Video Editor than VN
An expert in creating and editing videos with outstanding functions and features. Offers versions for Windows, Mac, and Mobile!
[Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
Previously this video editor was only available on mobile devices. The app's popularity grew with time, so the developers decided to launch a PC version also. Now you can easily download and use vn video editor windows and vn video editor for mac depending upon your operating system and devices. In this article, we will do a detailed review of this video and will take a brief look at its features. In the end, we will let you know if this video editor is worth spending your time on or not.
VN video editor is known as the best video editing software for professionals. People looking for an alternative to Adobe premiere pro for Mac, Windows, or Free Virtual Dub for Windows can use this video editing software and get outstanding results. This is the software used by many famous editors, and you can also learn the tricks of this application by following tutorials on the internet.
It contains a movie maker/editor/slideshow and photo story and [a video editor](https://tools.techidaily.com/wondershare/filmora/download/). A powerful integrated video solution to help you create unique and charming videos, VN Video Editor brings together high quality and ease-of-use for beginners or non-professionals, whether the result is a simple home movie or high definition professional movies and slideshows, from your pc.
## **What Are The Features of VN editor For PC?**
The VN video editor for PC is loaded with features. You can find almost everything that you need to create stunning videos. Below are some of the most prominent features of this video editing software.
### 1.Keyframe Animation
To make video editing easier and the results more impressive, keyframe usage is a great feature to have. The Keyframe tool is effective when used with a camera or panning shots and with cut scenes and graphics. One of the best advantages of this tool is that it enables the user to set specific times for certain actions to be taken place and then have that action take place automatically for you. In traditional video editors, keyframing may have been a challenge. But with the VN Video Editor, you can easily use keyframe animations to transition between clips and perform some unique effects.
Try Filmora Keyframing to Creates Fantastic Visual Animations
[**Filmora keyframing**](https://tools.techidaily.com/wondershare/filmora/download/) can change positions in the hand-drawing pattern, acale subject of the clip with keyframing and customize opacity to make your shot precise and concise.
[Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
### 2.Professional Video Editing
VN video editor has everything you need to create professional-looking videos using your own photos, videos, and music. The video editor takes advantage of new video formats and supports video effects and multi-camera editing to meet professional editing needs. VN video editor comes with a timeline in which multiple images and videos can be inserted for editing. Moreover, you can edit texts with different effects and fonts. This tool is an image editing software that comes with animation templates for creating videos for fashion and photo lovers.
### 3.Lots of Effects and Filters
Are you a creative professional or just a plain fun-loving person? If yes, then VN video editor is an app that can help you get the best out of your creativity. This application is perfect for those who are looking to enhance their videos as well as to add some cool effects. It has an amazing variety of filters, effects, and other amazing features that make video editing a great fun and easy task. With this PC app, you can add stylish text, choose from a broad array of filters and effects, and so much more. All that's left for you to do is insert your photos and videos - and enjoy the final product.
### 4.Audio Tools
This software also has pretty good audio tools. VN Video Editor allows you to add audio files and apply different filter effects directly to them. You can also edit your video clips with the help of this program.
### 5.Exporting Files
Once you are done editing your videos in this amazing software, you can easily export them in your desired format. VN video editor supports a huge list of different formats so, and it will be very useful for the creator. Also, you can directly share your videos to different platforms like Youtube and Facebook.
## **Best Replacement of VN Video Editor - \[Edit your Video with AI Tech\]**
Suppose you are looking for a fully-fledged video editor that is simple to use and can compete with the most advanced video editors in the market. In that case, we recommend you give it a try to [Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/). It is packed with features, and the best thing about this video editor is that you can download it for free and try all of its premium features without paying a penny. You can also learn it quickly as it is quite popular and there are plenty of tutorials available.
[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
## **Final Verdict**
After reading all the features mentioned in this article, you might be looking for "VN video editor for pc free download." But keep in mind that, although this video editor is pretty good and comes with many amazing features, it still needs a lot of improvements and lacks a lot of tools needed in professional video editing. So, it may be good for basic users, but professionals need a better option.
#### In this article
01 [VN Video Editor For Laptop/PC - An Overview](#part1)
02 [What Are The Features of VN editor For PC?](#part2)
03 [Best Replacement of VN Video Editor](#part3) \- \[Edit your Video with AI Tech\]
## **VN Video Editor For Laptop/PC - An Overview**
VN video editor is known as the best video editing app. This application comes with the power to provide a user-friendly interface. This app's overall performance is very good compared to other applications of the same category in various aspects. VN Video Editor for PC is all about ease of use and quality. It offers a better interface than most of the apps in the same category, and hence, it can easily cater to the needs of users who are not tech-savvy.
#### Try Other Video Editor than VN
An expert in creating and editing videos with outstanding functions and features. Offers versions for Windows, Mac, and Mobile!
[Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
Previously this video editor was only available on mobile devices. The app's popularity grew with time, so the developers decided to launch a PC version also. Now you can easily download and use vn video editor windows and vn video editor for mac depending upon your operating system and devices. In this article, we will do a detailed review of this video and will take a brief look at its features. In the end, we will let you know if this video editor is worth spending your time on or not.
VN video editor is known as the best video editing software for professionals. People looking for an alternative to Adobe premiere pro for Mac, Windows, or Free Virtual Dub for Windows can use this video editing software and get outstanding results. This is the software used by many famous editors, and you can also learn the tricks of this application by following tutorials on the internet.
It contains a movie maker/editor/slideshow and photo story and [a video editor](https://tools.techidaily.com/wondershare/filmora/download/). A powerful integrated video solution to help you create unique and charming videos, VN Video Editor brings together high quality and ease-of-use for beginners or non-professionals, whether the result is a simple home movie or high definition professional movies and slideshows, from your pc.
## **What Are The Features of VN editor For PC?**
The VN video editor for PC is loaded with features. You can find almost everything that you need to create stunning videos. Below are some of the most prominent features of this video editing software.
### 1.Keyframe Animation
To make video editing easier and the results more impressive, keyframe usage is a great feature to have. The Keyframe tool is effective when used with a camera or panning shots and with cut scenes and graphics. One of the best advantages of this tool is that it enables the user to set specific times for certain actions to be taken place and then have that action take place automatically for you. In traditional video editors, keyframing may have been a challenge. But with the VN Video Editor, you can easily use keyframe animations to transition between clips and perform some unique effects.
Try Filmora Keyframing to Creates Fantastic Visual Animations
[**Filmora keyframing**](https://tools.techidaily.com/wondershare/filmora/download/) can change positions in the hand-drawing pattern, acale subject of the clip with keyframing and customize opacity to make your shot precise and concise.
[Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
### 2.Professional Video Editing
VN video editor has everything you need to create professional-looking videos using your own photos, videos, and music. The video editor takes advantage of new video formats and supports video effects and multi-camera editing to meet professional editing needs. VN video editor comes with a timeline in which multiple images and videos can be inserted for editing. Moreover, you can edit texts with different effects and fonts. This tool is an image editing software that comes with animation templates for creating videos for fashion and photo lovers.
### 3.Lots of Effects and Filters
Are you a creative professional or just a plain fun-loving person? If yes, then VN video editor is an app that can help you get the best out of your creativity. This application is perfect for those who are looking to enhance their videos as well as to add some cool effects. It has an amazing variety of filters, effects, and other amazing features that make video editing a great fun and easy task. With this PC app, you can add stylish text, choose from a broad array of filters and effects, and so much more. All that's left for you to do is insert your photos and videos - and enjoy the final product.
### 4.Audio Tools
This software also has pretty good audio tools. VN Video Editor allows you to add audio files and apply different filter effects directly to them. You can also edit your video clips with the help of this program.
### 5.Exporting Files
Once you are done editing your videos in this amazing software, you can easily export them in your desired format. VN video editor supports a huge list of different formats so, and it will be very useful for the creator. Also, you can directly share your videos to different platforms like Youtube and Facebook.
## **Best Replacement of VN Video Editor - \[Edit your Video with AI Tech\]**
Suppose you are looking for a fully-fledged video editor that is simple to use and can compete with the most advanced video editors in the market. In that case, we recommend you give it a try to [Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/). It is packed with features, and the best thing about this video editor is that you can download it for free and try all of its premium features without paying a penny. You can also learn it quickly as it is quite popular and there are plenty of tutorials available.
[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
## **Final Verdict**
After reading all the features mentioned in this article, you might be looking for "VN video editor for pc free download." But keep in mind that, although this video editor is pretty good and comes with many amazing features, it still needs a lot of improvements and lacks a lot of tools needed in professional video editing. So, it may be good for basic users, but professionals need a better option.
#### In this article
01 [VN Video Editor For Laptop/PC - An Overview](#part1)
02 [What Are The Features of VN editor For PC?](#part2)
03 [Best Replacement of VN Video Editor](#part3) \- \[Edit your Video with AI Tech\]
## **VN Video Editor For Laptop/PC - An Overview**
VN video editor is known as the best video editing app. This application comes with the power to provide a user-friendly interface. This app's overall performance is very good compared to other applications of the same category in various aspects. VN Video Editor for PC is all about ease of use and quality. It offers a better interface than most of the apps in the same category, and hence, it can easily cater to the needs of users who are not tech-savvy.
#### Try Other Video Editor than VN
An expert in creating and editing videos with outstanding functions and features. Offers versions for Windows, Mac, and Mobile!
[Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Edit Video Like a Pro](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
Previously this video editor was only available on mobile devices. The app's popularity grew with time, so the developers decided to launch a PC version also. Now you can easily download and use vn video editor windows and vn video editor for mac depending upon your operating system and devices. In this article, we will do a detailed review of this video and will take a brief look at its features. In the end, we will let you know if this video editor is worth spending your time on or not.
VN video editor is known as the best video editing software for professionals. People looking for an alternative to Adobe premiere pro for Mac, Windows, or Free Virtual Dub for Windows can use this video editing software and get outstanding results. This is the software used by many famous editors, and you can also learn the tricks of this application by following tutorials on the internet.
It contains a movie maker/editor/slideshow and photo story and [a video editor](https://tools.techidaily.com/wondershare/filmora/download/). A powerful integrated video solution to help you create unique and charming videos, VN Video Editor brings together high quality and ease-of-use for beginners or non-professionals, whether the result is a simple home movie or high definition professional movies and slideshows, from your pc.
## **What Are The Features of VN editor For PC?**
The VN video editor for PC is loaded with features. You can find almost everything that you need to create stunning videos. Below are some of the most prominent features of this video editing software.
### 1.Keyframe Animation
To make video editing easier and the results more impressive, keyframe usage is a great feature to have. The Keyframe tool is effective when used with a camera or panning shots and with cut scenes and graphics. One of the best advantages of this tool is that it enables the user to set specific times for certain actions to be taken place and then have that action take place automatically for you. In traditional video editors, keyframing may have been a challenge. But with the VN Video Editor, you can easily use keyframe animations to transition between clips and perform some unique effects.
Try Filmora Keyframing to Creates Fantastic Visual Animations
[**Filmora keyframing**](https://tools.techidaily.com/wondershare/filmora/download/) can change positions in the hand-drawing pattern, acale subject of the clip with keyframing and customize opacity to make your shot precise and concise.
[Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Start Keyframing](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/)
### 2.Professional Video Editing
VN video editor has everything you need to create professional-looking videos using your own photos, videos, and music. The video editor takes advantage of new video formats and supports video effects and multi-camera editing to meet professional editing needs. VN video editor comes with a timeline in which multiple images and videos can be inserted for editing. Moreover, you can edit texts with different effects and fonts. This tool is an image editing software that comes with animation templates for creating videos for fashion and photo lovers.
### 3.Lots of Effects and Filters
Are you a creative professional or just a plain fun-loving person? If yes, then VN video editor is an app that can help you get the best out of your creativity. This application is perfect for those who are looking to enhance their videos as well as to add some cool effects. It has an amazing variety of filters, effects, and other amazing features that make video editing a great fun and easy task. With this PC app, you can add stylish text, choose from a broad array of filters and effects, and so much more. All that's left for you to do is insert your photos and videos - and enjoy the final product.
### 4.Audio Tools
This software also has pretty good audio tools. VN Video Editor allows you to add audio files and apply different filter effects directly to them. You can also edit your video clips with the help of this program.
### 5.Exporting Files
Once you are done editing your videos in this amazing software, you can easily export them in your desired format. VN video editor supports a huge list of different formats so, and it will be very useful for the creator. Also, you can directly share your videos to different platforms like Youtube and Facebook.
## **Best Replacement of VN Video Editor - \[Edit your Video with AI Tech\]**
Suppose you are looking for a fully-fledged video editor that is simple to use and can compete with the most advanced video editors in the market. In that case, we recommend you give it a try to [Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/). It is packed with features, and the best thing about this video editor is that you can download it for free and try all of its premium features without paying a penny. You can also learn it quickly as it is quite popular and there are plenty of tutorials available.
[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
## **Final Verdict**
After reading all the features mentioned in this article, you might be looking for "VN video editor for pc free download." But keep in mind that, although this video editor is pretty good and comes with many amazing features, it still needs a lot of improvements and lacks a lot of tools needed in professional video editing. So, it may be good for basic users, but professionals need a better option.
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## Top Free Online Resources to Blur Image Backgrounds
Photos are the best way to express yourself, but when it comes to emphasizing the main object, people often look for ways to blur the background of their photo. When you blur the background, all the focus immediately goes to the main object. Moreover, high-quality photos can drive conversions for brands as well. Customers like to see the photos of the products they are interested in buying, particularly when shopping online.
This is the reason why getting the right shot is easy. And once you have the photos, the next thing that you should think about is editing them to enhance the image quality. Knowing that you want to make your photos look the best, we have accumulated the top ten free tools that will let you **blur** a **photo's background online** conveniently.
## Top 10 Online Photo Background Blur Tools
### 1.BeFunky

BeFunky is an easy-to-use tool that will let you **blur** an **image background online.** It is essentially a robust photo editing tool, which doesn't ask for registration, and since it is available online, you can start blurring a photo right away. Apart from blurring the photo's background, you can use it to crop, insert text, resize, make a collage, and more. In addition, BeFunky provides many features that allow you to beautify your photos.
**How to Use BeFunky to Blur Background?**
Using BeFunky to blur the photo background is easy. There are a few steps that you need to follow, but once you get to know them, you can easily **blur** the **background online** for **free**. Here are the steps you need to follow:
**Step 1:** Visit [BeFunky's website](https://www.befunky.com/) and click on the Create option. Now, click on the Photo Editor option.
**Step 2:** Once the photo editor tool appears, you need to click on the Open option and add the photo you want to work on.
**Step 3:** On the left will be the features panel; scroll down a bit to **Blur & Smooth** option. Now, click on the Blur option and apply the blur amount. Once done, click on the Save option.
### 2.Fotor

Fotor is a dedicated free online tool that lets you blur the background of any photo you want. Unlike other tools, it comes with three different blur effects. You can try circular, linear, or tilt-shift brushes. Along with blurring your photo, you can also use it to crop, rotate, adjust brightness and color, and resize the photo. You don't need to register to use it.
**How to Use Fotor?**
**Step 1:** Visit [Fotor's website](https://www.fotor.com/) and click on the Blur Background Now option.
**Step 2:** When the photo editor appears, upload the photo.
**Step 3:** Adjust the blur size and intensity and click on the Apply option. Now, hit the download option to save the image.
### 3.Raw.Pics.IO

Raw.Pics.io is a new online free blurring tool that lets you blur the background of any image in a jiffy. Using this tool is easy, and you don't need to register to fix your photo. Apart from blurring the background, you can use it to convert the image into multiple photo formats.
**How to Use Raw.Pics.IO?**
**Step 1:** Go to [Raw.Pics.IO's website](https://raw.pics.io/) and click on the Start option.
**Step 2:** Upload the photo; now click on the edit option from the left toolbar.
**Step 3:** Choose the blur option from the right toolbar. Close the edit option and click on the Save As option.
### 4.iPiccy

iPiccy is a free-to-use online tool that enables you to edit your photos seamlessly. Even though this is a free tool, it lets you blur the background, adjust exposure, sharpen, add brightness, rotate, flip, crop, and much more. Since it is easy to use, anyone can try iPiccy to begin blurring the background. Also, you don't need to register.
**How to Use iPiccy?**
**Step 1:** Visit [iPiccy's website](https://ipiccy.com/) and click on the Edit a Photo option.
**Step 2:** Upload a photo from your computer, and from the left toolbar, click on the Blur option.
**Step 3:** The entire photo will be blurred; use the erase option to remove the blur effect from the main object. Click on the apply option and save the image.
### 5.FotoJet

FotoJet is not a free tool, but you can try FotoJet for free for seven days. This tool is a fantastic photo editing tool and lets you blur the background of an image. If you plan to buy FotoJet, you will only have to pay $4.99 per month. You can edit the photos, but you will have to sign up using your Facebook or Google account to save the work.
**How to Use FotoJet?**
**Step 1:** Go to [FotoJet's website](https://www.fotojet.com/) and click on the Open option to add the photo.
**Step 2:** On the left toolbar, you will see the Focus option; click on that and blur the background.
**Step 3:** Sign in using your Facebook or Google account and save the edited photo.
### 6.LunaPic

If you don't want to pay anything to blur your photo, you can try LunaPic. You can use Adjust Focus, Motion blur, or regular blur options to blur your image. Apart from editing, there are many photo editing features available as well.
**How to Use LunaPic?**
**Step 1:** Go to [LunaPic's official website](https://www12.lunapic.com/editor/) and click on the upload option. Now, hit the browse option and add the photo you want to edit.
**Step 2:** Locate the blur effect and add it. To remove the blur effect from the main object, use the eraser.
**Step 3:** Save your photo without registering or signing up.
### 7.Pixomatic

Pixomatic is a professional photo editing online tool that will let you add depth to any photo. Whether you want to blur your image, crop it, add text, and more. It is available for free for seven days. The interface of Pixomatic could be a little difficult to understand, but once you place the cursor on the toolbar, you will figure what it does.
**How to Use Pixomatic?**
**Step 1:** Go to [Pixomatic's website](https://pixomatic.us/) and click on the Edit Photo option. Now, click on the Load Photo option to add the photo you want to edit.
**Step 2:** After the photo is added, from the left-side toolbar, select the blur option.
**Step 3:** Click on the Save option to save the photo.
### 8.Hidebg

This free-to-use online tool lets you remove background objects and blur the background efficiently. This is a very simple tool and doesn't have a lot of features. And the blurring effect will be added automatically, which means you won't be able to do anything about it.
**How to Use Hidebg?**
**Step 1:** Go to the [Hidebg website](https://hidebg.com/), and on the homepage, you will see the Auto Blur Background option; please click on that.
**Step 2:** Blur effect will be added automatically.
**Step 3:** To save, click on the Save option.
### 9.Pixelixe

Bring clarity to your photos by blurring the background of the picture. And to let you easily blur the background of an image, you have Pixelixe, a free online tool that is easy to use. You can choose the focal point, try a range of blur, and share the photo on your social media accounts directly.
**How to Use Pixelixe?**
**Step 1:** Go to [Pixelixe's website](https://pixelixe.com/) and click on Blur Your First Image Now option.
**Step 2:** Upload the photo from your computer and add the blurring effect to the background.
**Step 3:** Once done, click on the Save option.
### 10.MockoFUN

The last free **blur background photo editor online** tool to go for is MockoFUN. There will be a learning curve, and locating the blur effect is slightly complicated. Nevertheless, it is free, and you will have to register to start using it.
**How to Use MockoFUN?**
**Step 1:** Visit [MockoFUN](https://www.mockofun.com/) and register using your Google account.
**Step 2:** Upload the photo you want to edit, and click on the filter option on the top.
**Step 3:** When you see the blur option, choose how much blur you want on the photo and save it.
## Bonus: How to Blur Photo Background for Free with Wondershare Filmora?
Although all the tools that we have mentioned earlier are good to go, if you are looking for a professional tool that will let you blur the background of a photo and edit the image to give it a magical touch, the recommended tool to use is [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[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
Here's what you need to do:
**Step 1:** Download Wondershare Filmora on your computer and launch it. Once done, click on the import your video option and upload the photo you want to work on.
**Step 2:** To blur the background, go to Effects tab and then scroll down to Utility category. Drop the tilt-shift circle or tilt-shift linear effect to the photo. You can double click the effect in the timeline to modify the blur intensity and size. Or drag the handle in the preview window to adjust directly.

**Step 3:** After the background is blurred, click on the camera icon in the preview window to save the picture on the computer as a local file.

**Conclusion**
These are the hand-picked **blur photo background online** tools that one can go for. Please note that some of the tools will ask you to register, while most won't. And if you need a professional tool loaded with impressive photo editing features, try Wondershare Filmora. To download, visit Wondershare Filmora.
BeFunky is an easy-to-use tool that will let you **blur** an **image background online.** It is essentially a robust photo editing tool, which doesn't ask for registration, and since it is available online, you can start blurring a photo right away. Apart from blurring the photo's background, you can use it to crop, insert text, resize, make a collage, and more. In addition, BeFunky provides many features that allow you to beautify your photos.
**How to Use BeFunky to Blur Background?**
Using BeFunky to blur the photo background is easy. There are a few steps that you need to follow, but once you get to know them, you can easily **blur** the **background online** for **free**. Here are the steps you need to follow:
**Step 1:** Visit [BeFunky's website](https://www.befunky.com/) and click on the Create option. Now, click on the Photo Editor option.
**Step 2:** Once the photo editor tool appears, you need to click on the Open option and add the photo you want to work on.
**Step 3:** On the left will be the features panel; scroll down a bit to **Blur & Smooth** option. Now, click on the Blur option and apply the blur amount. Once done, click on the Save option.
### 2.Fotor

Fotor is a dedicated free online tool that lets you blur the background of any photo you want. Unlike other tools, it comes with three different blur effects. You can try circular, linear, or tilt-shift brushes. Along with blurring your photo, you can also use it to crop, rotate, adjust brightness and color, and resize the photo. You don't need to register to use it.
**How to Use Fotor?**
**Step 1:** Visit [Fotor's website](https://www.fotor.com/) and click on the Blur Background Now option.
**Step 2:** When the photo editor appears, upload the photo.
**Step 3:** Adjust the blur size and intensity and click on the Apply option. Now, hit the download option to save the image.
### 3.Raw.Pics.IO

Raw.Pics.io is a new online free blurring tool that lets you blur the background of any image in a jiffy. Using this tool is easy, and you don't need to register to fix your photo. Apart from blurring the background, you can use it to convert the image into multiple photo formats.
**How to Use Raw.Pics.IO?**
**Step 1:** Go to [Raw.Pics.IO's website](https://raw.pics.io/) and click on the Start option.
**Step 2:** Upload the photo; now click on the edit option from the left toolbar.
**Step 3:** Choose the blur option from the right toolbar. Close the edit option and click on the Save As option.
### 4.iPiccy

iPiccy is a free-to-use online tool that enables you to edit your photos seamlessly. Even though this is a free tool, it lets you blur the background, adjust exposure, sharpen, add brightness, rotate, flip, crop, and much more. Since it is easy to use, anyone can try iPiccy to begin blurring the background. Also, you don't need to register.
**How to Use iPiccy?**
**Step 1:** Visit [iPiccy's website](https://ipiccy.com/) and click on the Edit a Photo option.
**Step 2:** Upload a photo from your computer, and from the left toolbar, click on the Blur option.
**Step 3:** The entire photo will be blurred; use the erase option to remove the blur effect from the main object. Click on the apply option and save the image.
### 5.FotoJet

FotoJet is not a free tool, but you can try FotoJet for free for seven days. This tool is a fantastic photo editing tool and lets you blur the background of an image. If you plan to buy FotoJet, you will only have to pay $4.99 per month. You can edit the photos, but you will have to sign up using your Facebook or Google account to save the work.
**How to Use FotoJet?**
**Step 1:** Go to [FotoJet's website](https://www.fotojet.com/) and click on the Open option to add the photo.
**Step 2:** On the left toolbar, you will see the Focus option; click on that and blur the background.
**Step 3:** Sign in using your Facebook or Google account and save the edited photo.
### 6.LunaPic

If you don't want to pay anything to blur your photo, you can try LunaPic. You can use Adjust Focus, Motion blur, or regular blur options to blur your image. Apart from editing, there are many photo editing features available as well.
**How to Use LunaPic?**
**Step 1:** Go to [LunaPic's official website](https://www12.lunapic.com/editor/) and click on the upload option. Now, hit the browse option and add the photo you want to edit.
**Step 2:** Locate the blur effect and add it. To remove the blur effect from the main object, use the eraser.
**Step 3:** Save your photo without registering or signing up.
### 7.Pixomatic

Pixomatic is a professional photo editing online tool that will let you add depth to any photo. Whether you want to blur your image, crop it, add text, and more. It is available for free for seven days. The interface of Pixomatic could be a little difficult to understand, but once you place the cursor on the toolbar, you will figure what it does.
**How to Use Pixomatic?**
**Step 1:** Go to [Pixomatic's website](https://pixomatic.us/) and click on the Edit Photo option. Now, click on the Load Photo option to add the photo you want to edit.
**Step 2:** After the photo is added, from the left-side toolbar, select the blur option.
**Step 3:** Click on the Save option to save the photo.
### 8.Hidebg

This free-to-use online tool lets you remove background objects and blur the background efficiently. This is a very simple tool and doesn't have a lot of features. And the blurring effect will be added automatically, which means you won't be able to do anything about it.
**How to Use Hidebg?**
**Step 1:** Go to the [Hidebg website](https://hidebg.com/), and on the homepage, you will see the Auto Blur Background option; please click on that.
**Step 2:** Blur effect will be added automatically.
**Step 3:** To save, click on the Save option.
### 9.Pixelixe

Bring clarity to your photos by blurring the background of the picture. And to let you easily blur the background of an image, you have Pixelixe, a free online tool that is easy to use. You can choose the focal point, try a range of blur, and share the photo on your social media accounts directly.
**How to Use Pixelixe?**
**Step 1:** Go to [Pixelixe's website](https://pixelixe.com/) and click on Blur Your First Image Now option.
**Step 2:** Upload the photo from your computer and add the blurring effect to the background.
**Step 3:** Once done, click on the Save option.
### 10.MockoFUN

The last free **blur background photo editor online** tool to go for is MockoFUN. There will be a learning curve, and locating the blur effect is slightly complicated. Nevertheless, it is free, and you will have to register to start using it.
**How to Use MockoFUN?**
**Step 1:** Visit [MockoFUN](https://www.mockofun.com/) and register using your Google account.
**Step 2:** Upload the photo you want to edit, and click on the filter option on the top.
**Step 3:** When you see the blur option, choose how much blur you want on the photo and save it.
## Bonus: How to Blur Photo Background for Free with Wondershare Filmora?
Although all the tools that we have mentioned earlier are good to go, if you are looking for a professional tool that will let you blur the background of a photo and edit the image to give it a magical touch, the recommended tool to use is [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[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
Here's what you need to do:
**Step 1:** Download Wondershare Filmora on your computer and launch it. Once done, click on the import your video option and upload the photo you want to work on.
**Step 2:** To blur the background, go to Effects tab and then scroll down to Utility category. Drop the tilt-shift circle or tilt-shift linear effect to the photo. You can double click the effect in the timeline to modify the blur intensity and size. Or drag the handle in the preview window to adjust directly.

**Step 3:** After the background is blurred, click on the camera icon in the preview window to save the picture on the computer as a local file.

**Conclusion**
These are the hand-picked **blur photo background online** tools that one can go for. Please note that some of the tools will ask you to register, while most won't. And if you need a professional tool loaded with impressive photo editing features, try Wondershare Filmora. To download, visit Wondershare Filmora.
BeFunky is an easy-to-use tool that will let you **blur** an **image background online.** It is essentially a robust photo editing tool, which doesn't ask for registration, and since it is available online, you can start blurring a photo right away. Apart from blurring the photo's background, you can use it to crop, insert text, resize, make a collage, and more. In addition, BeFunky provides many features that allow you to beautify your photos.
**How to Use BeFunky to Blur Background?**
Using BeFunky to blur the photo background is easy. There are a few steps that you need to follow, but once you get to know them, you can easily **blur** the **background online** for **free**. Here are the steps you need to follow:
**Step 1:** Visit [BeFunky's website](https://www.befunky.com/) and click on the Create option. Now, click on the Photo Editor option.
**Step 2:** Once the photo editor tool appears, you need to click on the Open option and add the photo you want to work on.
**Step 3:** On the left will be the features panel; scroll down a bit to **Blur & Smooth** option. Now, click on the Blur option and apply the blur amount. Once done, click on the Save option.
### 2.Fotor

Fotor is a dedicated free online tool that lets you blur the background of any photo you want. Unlike other tools, it comes with three different blur effects. You can try circular, linear, or tilt-shift brushes. Along with blurring your photo, you can also use it to crop, rotate, adjust brightness and color, and resize the photo. You don't need to register to use it.
**How to Use Fotor?**
**Step 1:** Visit [Fotor's website](https://www.fotor.com/) and click on the Blur Background Now option.
**Step 2:** When the photo editor appears, upload the photo.
**Step 3:** Adjust the blur size and intensity and click on the Apply option. Now, hit the download option to save the image.
### 3.Raw.Pics.IO

Raw.Pics.io is a new online free blurring tool that lets you blur the background of any image in a jiffy. Using this tool is easy, and you don't need to register to fix your photo. Apart from blurring the background, you can use it to convert the image into multiple photo formats.
**How to Use Raw.Pics.IO?**
**Step 1:** Go to [Raw.Pics.IO's website](https://raw.pics.io/) and click on the Start option.
**Step 2:** Upload the photo; now click on the edit option from the left toolbar.
**Step 3:** Choose the blur option from the right toolbar. Close the edit option and click on the Save As option.
### 4.iPiccy

iPiccy is a free-to-use online tool that enables you to edit your photos seamlessly. Even though this is a free tool, it lets you blur the background, adjust exposure, sharpen, add brightness, rotate, flip, crop, and much more. Since it is easy to use, anyone can try iPiccy to begin blurring the background. Also, you don't need to register.
**How to Use iPiccy?**
**Step 1:** Visit [iPiccy's website](https://ipiccy.com/) and click on the Edit a Photo option.
**Step 2:** Upload a photo from your computer, and from the left toolbar, click on the Blur option.
**Step 3:** The entire photo will be blurred; use the erase option to remove the blur effect from the main object. Click on the apply option and save the image.
### 5.FotoJet

FotoJet is not a free tool, but you can try FotoJet for free for seven days. This tool is a fantastic photo editing tool and lets you blur the background of an image. If you plan to buy FotoJet, you will only have to pay $4.99 per month. You can edit the photos, but you will have to sign up using your Facebook or Google account to save the work.
**How to Use FotoJet?**
**Step 1:** Go to [FotoJet's website](https://www.fotojet.com/) and click on the Open option to add the photo.
**Step 2:** On the left toolbar, you will see the Focus option; click on that and blur the background.
**Step 3:** Sign in using your Facebook or Google account and save the edited photo.
### 6.LunaPic

If you don't want to pay anything to blur your photo, you can try LunaPic. You can use Adjust Focus, Motion blur, or regular blur options to blur your image. Apart from editing, there are many photo editing features available as well.
**How to Use LunaPic?**
**Step 1:** Go to [LunaPic's official website](https://www12.lunapic.com/editor/) and click on the upload option. Now, hit the browse option and add the photo you want to edit.
**Step 2:** Locate the blur effect and add it. To remove the blur effect from the main object, use the eraser.
**Step 3:** Save your photo without registering or signing up.
### 7.Pixomatic

Pixomatic is a professional photo editing online tool that will let you add depth to any photo. Whether you want to blur your image, crop it, add text, and more. It is available for free for seven days. The interface of Pixomatic could be a little difficult to understand, but once you place the cursor on the toolbar, you will figure what it does.
**How to Use Pixomatic?**
**Step 1:** Go to [Pixomatic's website](https://pixomatic.us/) and click on the Edit Photo option. Now, click on the Load Photo option to add the photo you want to edit.
**Step 2:** After the photo is added, from the left-side toolbar, select the blur option.
**Step 3:** Click on the Save option to save the photo.
### 8.Hidebg

This free-to-use online tool lets you remove background objects and blur the background efficiently. This is a very simple tool and doesn't have a lot of features. And the blurring effect will be added automatically, which means you won't be able to do anything about it.
**How to Use Hidebg?**
**Step 1:** Go to the [Hidebg website](https://hidebg.com/), and on the homepage, you will see the Auto Blur Background option; please click on that.
**Step 2:** Blur effect will be added automatically.
**Step 3:** To save, click on the Save option.
### 9.Pixelixe

Bring clarity to your photos by blurring the background of the picture. And to let you easily blur the background of an image, you have Pixelixe, a free online tool that is easy to use. You can choose the focal point, try a range of blur, and share the photo on your social media accounts directly.
**How to Use Pixelixe?**
**Step 1:** Go to [Pixelixe's website](https://pixelixe.com/) and click on Blur Your First Image Now option.
**Step 2:** Upload the photo from your computer and add the blurring effect to the background.
**Step 3:** Once done, click on the Save option.
### 10.MockoFUN

The last free **blur background photo editor online** tool to go for is MockoFUN. There will be a learning curve, and locating the blur effect is slightly complicated. Nevertheless, it is free, and you will have to register to start using it.
**How to Use MockoFUN?**
**Step 1:** Visit [MockoFUN](https://www.mockofun.com/) and register using your Google account.
**Step 2:** Upload the photo you want to edit, and click on the filter option on the top.
**Step 3:** When you see the blur option, choose how much blur you want on the photo and save it.
## Bonus: How to Blur Photo Background for Free with Wondershare Filmora?
Although all the tools that we have mentioned earlier are good to go, if you are looking for a professional tool that will let you blur the background of a photo and edit the image to give it a magical touch, the recommended tool to use is [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[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
Here's what you need to do:
**Step 1:** Download Wondershare Filmora on your computer and launch it. Once done, click on the import your video option and upload the photo you want to work on.
**Step 2:** To blur the background, go to Effects tab and then scroll down to Utility category. Drop the tilt-shift circle or tilt-shift linear effect to the photo. You can double click the effect in the timeline to modify the blur intensity and size. Or drag the handle in the preview window to adjust directly.

**Step 3:** After the background is blurred, click on the camera icon in the preview window to save the picture on the computer as a local file.

**Conclusion**
These are the hand-picked **blur photo background online** tools that one can go for. Please note that some of the tools will ask you to register, while most won't. And if you need a professional tool loaded with impressive photo editing features, try Wondershare Filmora. To download, visit Wondershare Filmora.
BeFunky is an easy-to-use tool that will let you **blur** an **image background online.** It is essentially a robust photo editing tool, which doesn't ask for registration, and since it is available online, you can start blurring a photo right away. Apart from blurring the photo's background, you can use it to crop, insert text, resize, make a collage, and more. In addition, BeFunky provides many features that allow you to beautify your photos.
**How to Use BeFunky to Blur Background?**
Using BeFunky to blur the photo background is easy. There are a few steps that you need to follow, but once you get to know them, you can easily **blur** the **background online** for **free**. Here are the steps you need to follow:
**Step 1:** Visit [BeFunky's website](https://www.befunky.com/) and click on the Create option. Now, click on the Photo Editor option.
**Step 2:** Once the photo editor tool appears, you need to click on the Open option and add the photo you want to work on.
**Step 3:** On the left will be the features panel; scroll down a bit to **Blur & Smooth** option. Now, click on the Blur option and apply the blur amount. Once done, click on the Save option.
### 2.Fotor

Fotor is a dedicated free online tool that lets you blur the background of any photo you want. Unlike other tools, it comes with three different blur effects. You can try circular, linear, or tilt-shift brushes. Along with blurring your photo, you can also use it to crop, rotate, adjust brightness and color, and resize the photo. You don't need to register to use it.
**How to Use Fotor?**
**Step 1:** Visit [Fotor's website](https://www.fotor.com/) and click on the Blur Background Now option.
**Step 2:** When the photo editor appears, upload the photo.
**Step 3:** Adjust the blur size and intensity and click on the Apply option. Now, hit the download option to save the image.
### 3.Raw.Pics.IO

Raw.Pics.io is a new online free blurring tool that lets you blur the background of any image in a jiffy. Using this tool is easy, and you don't need to register to fix your photo. Apart from blurring the background, you can use it to convert the image into multiple photo formats.
**How to Use Raw.Pics.IO?**
**Step 1:** Go to [Raw.Pics.IO's website](https://raw.pics.io/) and click on the Start option.
**Step 2:** Upload the photo; now click on the edit option from the left toolbar.
**Step 3:** Choose the blur option from the right toolbar. Close the edit option and click on the Save As option.
### 4.iPiccy

iPiccy is a free-to-use online tool that enables you to edit your photos seamlessly. Even though this is a free tool, it lets you blur the background, adjust exposure, sharpen, add brightness, rotate, flip, crop, and much more. Since it is easy to use, anyone can try iPiccy to begin blurring the background. Also, you don't need to register.
**How to Use iPiccy?**
**Step 1:** Visit [iPiccy's website](https://ipiccy.com/) and click on the Edit a Photo option.
**Step 2:** Upload a photo from your computer, and from the left toolbar, click on the Blur option.
**Step 3:** The entire photo will be blurred; use the erase option to remove the blur effect from the main object. Click on the apply option and save the image.
### 5.FotoJet

FotoJet is not a free tool, but you can try FotoJet for free for seven days. This tool is a fantastic photo editing tool and lets you blur the background of an image. If you plan to buy FotoJet, you will only have to pay $4.99 per month. You can edit the photos, but you will have to sign up using your Facebook or Google account to save the work.
**How to Use FotoJet?**
**Step 1:** Go to [FotoJet's website](https://www.fotojet.com/) and click on the Open option to add the photo.
**Step 2:** On the left toolbar, you will see the Focus option; click on that and blur the background.
**Step 3:** Sign in using your Facebook or Google account and save the edited photo.
### 6.LunaPic

If you don't want to pay anything to blur your photo, you can try LunaPic. You can use Adjust Focus, Motion blur, or regular blur options to blur your image. Apart from editing, there are many photo editing features available as well.
**How to Use LunaPic?**
**Step 1:** Go to [LunaPic's official website](https://www12.lunapic.com/editor/) and click on the upload option. Now, hit the browse option and add the photo you want to edit.
**Step 2:** Locate the blur effect and add it. To remove the blur effect from the main object, use the eraser.
**Step 3:** Save your photo without registering or signing up.
### 7.Pixomatic

Pixomatic is a professional photo editing online tool that will let you add depth to any photo. Whether you want to blur your image, crop it, add text, and more. It is available for free for seven days. The interface of Pixomatic could be a little difficult to understand, but once you place the cursor on the toolbar, you will figure what it does.
**How to Use Pixomatic?**
**Step 1:** Go to [Pixomatic's website](https://pixomatic.us/) and click on the Edit Photo option. Now, click on the Load Photo option to add the photo you want to edit.
**Step 2:** After the photo is added, from the left-side toolbar, select the blur option.
**Step 3:** Click on the Save option to save the photo.
### 8.Hidebg

This free-to-use online tool lets you remove background objects and blur the background efficiently. This is a very simple tool and doesn't have a lot of features. And the blurring effect will be added automatically, which means you won't be able to do anything about it.
**How to Use Hidebg?**
**Step 1:** Go to the [Hidebg website](https://hidebg.com/), and on the homepage, you will see the Auto Blur Background option; please click on that.
**Step 2:** Blur effect will be added automatically.
**Step 3:** To save, click on the Save option.
### 9.Pixelixe

Bring clarity to your photos by blurring the background of the picture. And to let you easily blur the background of an image, you have Pixelixe, a free online tool that is easy to use. You can choose the focal point, try a range of blur, and share the photo on your social media accounts directly.
**How to Use Pixelixe?**
**Step 1:** Go to [Pixelixe's website](https://pixelixe.com/) and click on Blur Your First Image Now option.
**Step 2:** Upload the photo from your computer and add the blurring effect to the background.
**Step 3:** Once done, click on the Save option.
### 10.MockoFUN

The last free **blur background photo editor online** tool to go for is MockoFUN. There will be a learning curve, and locating the blur effect is slightly complicated. Nevertheless, it is free, and you will have to register to start using it.
**How to Use MockoFUN?**
**Step 1:** Visit [MockoFUN](https://www.mockofun.com/) and register using your Google account.
**Step 2:** Upload the photo you want to edit, and click on the filter option on the top.
**Step 3:** When you see the blur option, choose how much blur you want on the photo and save it.
## Bonus: How to Blur Photo Background for Free with Wondershare Filmora?
Although all the tools that we have mentioned earlier are good to go, if you are looking for a professional tool that will let you blur the background of a photo and edit the image to give it a magical touch, the recommended tool to use is [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[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
Here's what you need to do:
**Step 1:** Download Wondershare Filmora on your computer and launch it. Once done, click on the import your video option and upload the photo you want to work on.
**Step 2:** To blur the background, go to Effects tab and then scroll down to Utility category. Drop the tilt-shift circle or tilt-shift linear effect to the photo. You can double click the effect in the timeline to modify the blur intensity and size. Or drag the handle in the preview window to adjust directly.

**Step 3:** After the background is blurred, click on the camera icon in the preview window to save the picture on the computer as a local file.

**Conclusion**
These are the hand-picked **blur photo background online** tools that one can go for. Please note that some of the tools will ask you to register, while most won't. And if you need a professional tool loaded with impressive photo editing features, try Wondershare Filmora. To download, visit Wondershare Filmora.
<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://smart-video-creator.techidaily.com/new-2024-approved-unlock-custom-aspect-ratios-in-final-cut-pro-expert-techniques-revealed/"><u>New 2024 Approved Unlock Custom Aspect Ratios in Final Cut Pro Expert Techniques Revealed</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/stop-motion-animation-a-step-by-step-guide-to-studio-and-beyond-for-2024/"><u>Stop Motion Animation A Step-by-Step Guide to Studio and Beyond for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-ditch-adobe-10-free-and-paid-linux-video-editors-youll-love-for-2024/"><u>Updated Ditch Adobe 10 Free and Paid Linux Video Editors Youll Love for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-unbeatable-free-mp4-video-editors-top-10-list/"><u>New 2024 Approved Unbeatable Free MP4 Video Editors Top 10 List</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-unleash-the-pro-in-you-turn-everyday-moments-into-breathtaking-films/"><u>Updated Unleash the Pro in You Turn Everyday Moments Into Breathtaking Films</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-in-2024-the-best-free-audio-recording-software-in-depth-reviews/"><u>New In 2024, The Best Free Audio Recording Software In-Depth Reviews</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/in-2024-revolutionize-your-animations/"><u>In 2024, Revolutionize Your Animations</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-ubuntus-best-kept-secrets-top-10-free-video-editing-tools/"><u>Updated 2024 Approved Ubuntus Best Kept Secrets Top 10 Free Video Editing Tools</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-the-only-guide-facebook-video-aspect-ratios-youll-ever-need-to-know/"><u>New The Only Guide Facebook Video Aspect Ratios Youll Ever Need To Know</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/in-2024-the-cloud-animators-handbook-stop-motion-software-and-more/"><u>In 2024, The Cloud Animators Handbook Stop Motion Software and More</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-setting-up-your-dream-machine-for-premiere-pro-a-beginners-guide/"><u>Updated 2024 Approved Setting Up Your Dream Machine for Premiere Pro A Beginners Guide</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-looking-beyond-vegas-pro-10-outstanding-video-editing-software-for-mac/"><u>New Looking Beyond Vegas Pro 10 Outstanding Video Editing Software for Mac</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/mp4-made-easy-converting-and-downloading-4k-videos-simplified/"><u>MP4 Made Easy Converting and Downloading 4K Videos Simplified</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/2024-approved-create-stunning-collages-best-web-based-photo-and-video-editors/"><u>2024 Approved Create Stunning Collages Best Web-Based Photo and Video Editors</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-top-lyric-video-creation-tools-free-and-paid-options-compared/"><u>Updated 2024 Approved Top Lyric Video Creation Tools Free and Paid Options Compared</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-cut-and-edit-videos-easily-with-kapwings-online-tool/"><u>New 2024 Approved Cut and Edit Videos Easily with Kapwings Online Tool</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-ranking-the-best-video-editing-apps-for-iphone-and-android-for-2024/"><u>New Ranking the Best Video Editing Apps for iPhone and Android for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-from-novice-to-pro-mastering-wax-free-video-editor-in-for-2024/"><u>New From Novice to Pro Mastering Wax Free Video Editor In for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-mastering-mobile-how-to-optimize-vertical-video-for-social-media/"><u>Updated Mastering Mobile How to Optimize Vertical Video for Social Media</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/top-video-editing-tools-for-newbies-free-and-paid-options-for-2024/"><u>Top Video Editing Tools for Newbies Free and Paid Options for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-unlock-facebook-video-success-understanding-aspect-ratios-and-dimensions/"><u>Updated Unlock Facebook Video Success Understanding Aspect Ratios and Dimensions</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-in-2024-from-basic-to-advanced-mastering-motion-blur-in-final-cut-pro/"><u>Updated In 2024, From Basic to Advanced Mastering Motion Blur in Final Cut Pro</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/laughter-guaranteed-the-best-meme-generator-apps-for-mobile-devices/"><u>Laughter Guaranteed The Best Meme Generator Apps for Mobile Devices</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-track-your-moves-best-apps-for-android-and-iphone/"><u>Updated 2024 Approved Track Your Moves Best Apps for Android and iPhone</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/2024-approved-free-video-flipper-tools-rotate-your-videos-online/"><u>2024 Approved Free Video Flipper Tools Rotate Your Videos Online</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-top-10-coolest-plugins-for-final-cut-pro-x-freeandpaid/"><u>New 2024 Approved Top 10 Coolest Plugins for Final Cut Pro X Free&Paid</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/in-2024-final-cut-pro-on-a-budget-get-90-days-of-free-access-now/"><u>In 2024, Final Cut Pro on a Budget Get 90 Days of Free Access Now</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/2024-approved-canon-video-editor-a-beginners-guide-to-editing-your-camcorder-footage/"><u>2024 Approved Canon Video Editor A Beginners Guide to Editing Your Camcorder Footage</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/edit-wmv-videos-for-free-top-5-software-options-for-2024/"><u>Edit WMV Videos for Free Top 5 Software Options for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/the-ultimate-guide-to-video-stabilization-in-adobe-premiere-pro-2023-edition-for-2024/"><u>The Ultimate Guide to Video Stabilization in Adobe Premiere Pro (2023 Edition) for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-in-2024-compress-videos-like-a-pro-9-best-free-tools-for-windows-10/"><u>New In 2024, Compress Videos Like a Pro 9 Best Free Tools for Windows 10</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-in-2024-create-hollywood-style-videos-with-these-8-mac-apps/"><u>New In 2024, Create Hollywood-Style Videos with These 8 Mac Apps</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-discover-the-top-rated-explainer-video-platforms-for-20/"><u>Updated 2024 Approved Discover the Top-Rated Explainer Video Platforms for 20</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-in-2024-top-picks-28-best-video-to-gif-converters-for-windows-mac-and-online/"><u>Updated In 2024, Top Picks 28 Best Video to GIF Converters for Windows, Mac, and Online</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/top-rated-gaming-intro-software-free-and-paid-options-for-pc-and-mac-for-2024/"><u>Top-Rated Gaming Intro Software Free and Paid Options for PC and Mac for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-download-windows-movie-maker-free-the-ultimate-installation-guide/"><u>Updated Download Windows Movie Maker Free The Ultimate Installation Guide</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-turn-your-videos-into-treasures-the-best-dvd-creation-software-for-preserving-memories/"><u>New Turn Your Videos Into Treasures The Best DVD Creation Software for Preserving Memories</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/in-2024-dont-miss-out-the-importance-of-reading-about-mp3-converter-for-windows/"><u>In 2024, Dont Miss Out The Importance of Reading About Mp3 Converter for Windows</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/in-2024-in-this-article-i-want-to-show-you-how-to-apply-an-effect-to-a-clip-modify-that-effect-temporarily-turn-that-effect-on-or-off-or-delete-it-entirely./"><u>In 2024, In This Article, I Want to Show You How to Apply an Effect to a Clip, Modify that Effect, Temporarily Turn that Effect on or Off, or Delete It Entirely</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-the-ultimate-list-10-best-intro-video-makers-online/"><u>New 2024 Approved The Ultimate List 10 Best Intro Video Makers Online</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-10-free-video-editing-programs-to-use-instead-of-windows-movie-maker/"><u>New 2024 Approved 10 Free Video Editing Programs to Use Instead of Windows Movie Maker</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-free-and-fabulous-10-online-invitation-video-maker-options-for-2024/"><u>Updated Free and Fabulous 10 Online Invitation Video Maker Options for 2024</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-in-2024-free-and-fabulous-10-video-editing-tools-for-chromebook-enthusiasts/"><u>Updated In 2024, Free and Fabulous 10 Video Editing Tools for Chromebook Enthusiasts</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-bring-your-vision-to-life-8-stellar-mac-movie-makers-for-2024/"><u>Updated Bring Your Vision to Life 8 Stellar Mac Movie Makers for 2024</u></a></li>
<li><a href="https://unlock-android.techidaily.com/in-2024-a-perfect-guide-to-remove-or-disable-google-smart-lock-on-zte-nubia-flip-5g-by-drfone-android/"><u>In 2024, A Perfect Guide To Remove or Disable Google Smart Lock On ZTE Nubia Flip 5G</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/process-of-screen-sharing-motorola-moto-g-stylus-5g-2023-to-pc-detailed-steps-drfone-by-drfone-android/"><u>Process of Screen Sharing Motorola Moto G Stylus 5G (2023) to PC- Detailed Steps | Dr.fone</u></a></li>
<li><a href="https://phone-solutions.techidaily.com/complete-guide-for-recovering-photos-files-on-c51-by-fonelab-android-recover-photos/"><u>Complete guide for recovering photos files on C51.</u></a></li>
<li><a href="https://android-pokemon-go.techidaily.com/best-pokemons-for-pvp-matches-in-pokemon-go-for-motorola-edge-2023-drfone-by-drfone-virtual-android/"><u>Best Pokemons for PVP Matches in Pokemon Go For Motorola Edge 2023 | Dr.fone</u></a></li>
<li><a href="https://location-social.techidaily.com/4-feasible-ways-to-fake-location-on-facebook-for-your-oppo-a78-5g-drfone-by-drfone-virtual-android/"><u>4 Feasible Ways to Fake Location on Facebook For your Oppo A78 5G | Dr.fone</u></a></li>
<li><a href="https://phone-solutions.techidaily.com/3-easy-solutions-to-hard-reset-samsung-galaxy-a24-drfone-by-drfone-reset-android-reset-android/"><u>3 Easy Solutions to Hard Reset Samsung Galaxy A24 | Dr.fone</u></a></li>
<li><a href="https://ai-voice-clone.techidaily.com/top-list-speech-to-speech-voice-cloning-for-2024/"><u>Top List Speech-to-Speech Voice Cloning for 2024</u></a></li>
<li><a href="https://fake-location.techidaily.com/how-to-change-spotify-location-after-moving-to-another-country-on-realme-narzo-60-pro-5g-drfone-by-drfone-virtual-android/"><u>How to Change Spotify Location After Moving to Another Country On Realme Narzo 60 Pro 5G | Dr.fone</u></a></li>
<li><a href="https://ios-pokemon-go.techidaily.com/how-can-i-create-my-pokemon-overworld-maps-on-apple-iphone-se-drfone-by-drfone-virtual-ios/"><u>How Can I Create My Pokemon Overworld Maps On Apple iPhone SE? | Dr.fone</u></a></li>
<li><a href="https://bypass-frp.techidaily.com/a-step-by-step-guide-on-using-adb-and-fastboot-to-remove-frp-lock-on-your-itel-s23-by-drfone-android/"><u>A Step-by-Step Guide on Using ADB and Fastboot to Remove FRP Lock on your Itel S23</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/in-2024-how-can-samsung-galaxy-a15-5gmirror-share-to-pc-drfone-by-drfone-android/"><u>In 2024, How Can Samsung Galaxy A15 5GMirror Share to PC? | Dr.fone</u></a></li>
<li><a href="https://android-pokemon-go.techidaily.com/in-2024-a-working-guide-for-pachirisu-pokemon-go-map-on-oppo-reno-11-5g-drfone-by-drfone-virtual-android/"><u>In 2024, A Working Guide For Pachirisu Pokemon Go Map On Oppo Reno 11 5G | Dr.fone</u></a></li>
<li><a href="https://android-unlock.techidaily.com/best-samsung-galaxy-a54-5g-pattern-lock-removal-tools-remove-android-pattern-lock-without-losing-data-by-drfone-android/"><u>Best Samsung Galaxy A54 5G Pattern Lock Removal Tools Remove Android Pattern Lock Without Losing Data</u></a></li>
<li><a href="https://review-topics.techidaily.com/mkv-stutters-on-14-pro-and-stops-randomly-by-aiseesoft-video-converter-play-mkv-on-android/"><u>MKV stutters on 14 Pro and stops randomly</u></a></li>
<li><a href="https://ai-editing-video.techidaily.com/updated-how-to-got-free-after-effects-templates-slideshow-with-simple-trick/"><u>Updated How to Got Free After Effects Templates Slideshow with Simple Trick</u></a></li>
<li><a href="https://location-social.techidaily.com/how-to-change-your-apple-iphone-6-plus-location-on-life360-without-anyone-knowing-drfone-by-drfone-virtual-ios/"><u>How to Change Your Apple iPhone 6 Plus Location on life360 Without Anyone Knowing? | Dr.fone</u></a></li>
<li><a href="https://android-transfer.techidaily.com/in-2024-how-to-transfer-contacts-from-vivo-v29-to-other-android-devices-devices-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, How to Transfer Contacts from Vivo V29 to Other Android Devices Devices? | Dr.fone</u></a></li>
</ul></div> |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:start_flutter/block_sample/blocs/cart_bloc.dart';
class CartScreen extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sepet"),
backgroundColor: Colors.blueGrey,
),
body: StreamBuilder(
stream: cartBloc.getStream,
initialData: cartBloc.getAll(),
builder: (context, snapshot) {
return snapshot.data.length > 0 ? buildCartProductList(snapshot) : Center(child: Text("Sepet boş"));
},
),
);
}
buildCartProductList(AsyncSnapshot snapshot) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context,index){
final cart = snapshot.data;
return ListTile(
title: Text(cart[index].product.name),
subtitle: Text(cart[index].product.price.toString()),
trailing: IconButton(
icon: Icon(Icons.remove_shopping_cart),
onPressed: (){
cartBloc.removeFromCart(cart[index]);
},
),
);
});
}
} |
import { Operation, xdr } from "@stellar/stellar-sdk";
import { CommonTransactionBuilder } from "./CommonTransactionBuilder";
import { AccountKeypair } from "../Account";
/**
* Used for building transactions that will include a sponsor.
* Do not create this object directly, use the TransactionBuilder class to create.
* @class
*/
export class SponsoringBuilder extends CommonTransactionBuilder<SponsoringBuilder> {
private sponsorAccount: AccountKeypair;
/**
* Creates a new instance of the SponsoringBuilder class.
* @constructor
* @param {string} sponsoredAddress - The address of the account being sponsored.
* @param {AccountKeypair} sponsorAccount - The sponsor account keypair.
* @param {xdr.Operation[]} operations - An array of Stellar operations.
* @param {(builder: SponsoringBuilder) => SponsoringBuilder} buildingFunction - Function for creating the
* operations that will be sponsored.
*/
constructor(
sponsoredAddress: string,
sponsorAccount: AccountKeypair,
operations: Array<xdr.Operation>,
buildingFunction: (builder: SponsoringBuilder) => SponsoringBuilder,
) {
super(sponsoredAddress, operations);
this.sponsorAccount = sponsorAccount;
this.startSponsoring();
buildingFunction(this);
this.stopSponsoring();
}
/**
* Creates a Stellar account with sponsored reserves.
* @param {AccountKeypair} newAccount - The new account's keypair.
* @param {number} [startingBalance=0] - The starting balance for the new account (default is 0 XLM).
* @returns {SponsoringBuilder} The SponsoringBuilder instance.
*/
createAccount(
newAccount: AccountKeypair,
startingBalance: number = 0,
): SponsoringBuilder {
this.operations.push(
Operation.createAccount({
destination: newAccount.publicKey,
startingBalance: startingBalance.toString(),
source: this.sponsorAccount.publicKey,
}),
);
return this;
}
/**
* Start sponsoring the future reserves of an account.
* @returns {void}
*/
startSponsoring() {
this.operations.push(
Operation.beginSponsoringFutureReserves({
sponsoredId: this.sourceAddress,
source: this.sponsorAccount.publicKey,
}),
);
}
/**
* Stop sponsoring the future reserves of an account.
* @returns {void}
*/
stopSponsoring() {
this.operations.push(
Operation.endSponsoringFutureReserves({
source: this.sourceAddress,
}),
);
}
} |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests\IndexRequest;
use App\Http\Requests\CompanyRequest;
use App\Http\Docs\CompanyDocs;
/**
* @OA\Tag(name="Companies", description="Operations related to Companies")
*/
class CompanyController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(IndexRequest $request)
{
$page = $request->query('page', 1);
$data = \CompanyService::all($page);
// Check if a page was requested beyond the limit
if ($page > $data->lastPage()) {
return response()->json(['message' => 'The requested page is beyond the limit'], 400);
}
if ($data->isEmpty()) {
return response()->json(['message' => 'Not found Registries'], 404);
}
return response()->json($data, 200);
}
/**
* Display the specified resource.
*
* @param \App\Models\Company $Company
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$company = \CompanyService::find($id);
//Validation of not exists model $challenge
if($company == null){
return response()->json(['message' => 'No exists company with id : '.$id], 404);
}
return response()->json($company);
}
/*
* Store Company
* @return void
*/
public function store(CompanyRequest $request)
{
//Save companies
$company = \CompanyService::store($request);
$data = [];
if ($company) {
$data['successful'] = true;
$data['message'] = 'Record Entered Successfully';
$data['last_insert_id'] = $company->id;
}else{
$data['successful'] = false;
$data['message'] = 'Record Not Entered Successfully';
}
return response()->json($data);
}
/*
* Update Company
* @return void
*/
public function update($company,CompanyRequest $request)
{
//Update companies
$company = \CompanyService::update($company, $request);
$data = [];
if ($company) {
$data['successful'] = true;
$data['message'] = 'Record Update Successfully';
$data['created_at'] = $company;
}else{
$data['successful'] = false;
$data['message'] = 'Record Not Update Successfully';
}
return response()->json($data);
}
/*
* Delete $company
* @return void
*/
public function destroy($company)
{
//Delete companies
$company = \CompanyService::destroy($company);
$data = [];
if ($company) {
$data['successful'] = true;
$data['message'] = 'Record Delete Successfully';
}else{
$data['successful'] = false;
$data['message'] = 'Record Not Delete Successfully';
}
return response()->json($data);
}
} |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Logging Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Logging
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/general/errors.html
*/
class MY_Log extends CI_Log {
var $_levels = array(
'SEARCH' => '-2',
'MAIL' => '-1',
'ERROR' => '1',
'DEBUG' => '2',
'INFO' => '3',
'ALL' => '4');
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
}
// --------------------------------------------------------------------
/**
* Write Log File
*
* Generally this function will be called using the global log_message() function
*
* @param string the error level
* @param string the error message
* @param bool whether the error is a native PHP error
* @return bool
*/
public function write_log($level = 'error', $msg, $php_error = FALSE)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if ( isset($this->_levels[$level]) && ($this->_levels[$level] > $this->_threshold))
{
return FALSE;
}
$filepath = $this->_log_path.strtolower($level).'-log_'.date('Y-m-d').'.php';
$message = '';
if ( ! file_exists($filepath))
{
$message .= "<"."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
}
if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
{
return FALSE;
}
if (isset($_SERVER['REMOTE_ADDR'])) {
$message .= date($this->_date_fmt)."\t".
$level."\t".
$_SERVER['REMOTE_ADDR']."\t".
$msg."\n";
} else {
$message .= date($this->_date_fmt)."\t".
$level."\t".
'0.0.0.0'."\t".
$msg."\n";
}
flock($fp, LOCK_EX);
fwrite($fp, $message);
flock($fp, LOCK_UN);
fclose($fp);
@chmod($filepath, FILE_WRITE_MODE);
return TRUE;
}
}
// END Log Class
/* End of file Log.php */
/* Location: ./system/libraries/Log.php */ |
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: lightgrey;}
#mainDiv {
position:relative;
width:1350px;
height:629px;
background-image: url("labyrint.png");
padding:0px;
margin:50px auto;
border: solid 2px black;
}
.ball {
position:absolute;
width:50px;
height:50px;
border: solid 2px black;
border-radius:50%;
background-color : blue;
left:650px;
top:-40px;
}
</style>
</head>
<body>
<div id = "mainDiv">
<button id = "btnBall">Ny Ball</button>
</div>
</body>
<script>
var mainDiv = document.getElementById("mainDiv");
var btnBall = document.getElementById("btnBall");
//Array med objekt som inneholder de ulike stegene i animasjonen.
//Vi kan manipulere med Javascript på vanlig måte ved behov
var aniBallSteg = [
{transform:"translate(0px,0px)"},
{transform:"translate(0px,172px)",offset:0.13},
{transform:"translate(-240px,360px)",offset:0.36},
{transform:"translate(-240px,538px)",offset:0.49},
{transform:"translate(496px,534px)",offset:1},
];
//Variabel som definerer timing til animasjon
//Objekt, som vi kan manipulere med javascript
var aniBallTiming = {
duration:4000, //tid i millisekund for hele animasjonen
iterations: 2, //Antall repetisjoner. For uendelig antall antall, sett til Infinity
fill:"forwards",
}
btnBall.onclick = function(){
if (aniBallTiming.iterations>0){
//Generer ny ball, med tilfeldig farge
var nyBall = document.createElement("div");
nyBall.classList.add("ball");
nyBall.style.backgroundColor = getRandomColor();
mainDiv.appendChild(nyBall);
nyBall.animate(aniBallSteg,aniBallTiming);
//Ballen går litt kortere for hver gang.
aniBallTiming.iterations -= 0.04;
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</html> |
import { CssBaseline, ThemeProvider } from "@mui/material";
import { BrowserRouter } from "react-router-dom";
import theme from "./theme";
import Routes from "./routes";
import { ScenarioContextProvider } from "./contexts/ScenarioContextProvider";
import { NotificationContextProvider } from "./contexts/NotificationContextProvider";
import { MessageContextProvider } from "./contexts/MessageContextProvider";
import { UserContextProvider } from "./contexts/UserContextProvider";
function App() {
return (
<UserContextProvider>
<MessageContextProvider>
<NotificationContextProvider>
<ScenarioContextProvider>
<ThemeProvider theme={theme}>
<CssBaseline />
<BrowserRouter>
<Routes />
</BrowserRouter>
</ThemeProvider>
</ScenarioContextProvider>
</NotificationContextProvider>
</MessageContextProvider>
</UserContextProvider>
);
}
export default App; |
/** @odoo-module **/
import {registry} from "@web/core/registry";
import {Component, useState, onWillStart, onWillUnmount} from "@odoo/owl";
import {useService} from "@web/core/utils/hooks";
import {session} from "@web/session";
export class GeneratorRequest extends Component {
setup() {
this.actionService = useService("action");
this.orm = useService("orm");
this.state = useState({
globeExtraClasses: "",
});
onWillStart(async () => {
this.checkRequestStatus();
this.interval = setInterval(() => {
this.checkRequestStatus();
}, 60000);
});
onWillUnmount(() => {
clearInterval(this.interval);
});
}
async goToWaitingView() {
await this.actionService.doAction("website_generator.website_generator_screen");
}
async checkRequestStatus() {
const [scrapRequest] = await this.orm.silent.searchRead(
"website_generator.request",
[],
["status"],
{limit: 1, order: "id DESC"},
);
if (!scrapRequest) {
clearInterval(this.interval);
}
if (["error_request_still_processing", "error_maintenance", "waiting"]
.includes(scrapRequest.status)) {
return;
}
if (scrapRequest.status.includes("error")) {
this.state.globeExtraClasses = "text-danger";
} else {
this.state.globeExtraClasses = "text-success";
}
clearInterval(this.interval);
}
}
GeneratorRequest.template = "website_generator.GeneratorRequest";
const systrayItem = {
Component: GeneratorRequest,
isDisplayed: () => session.show_scraper_systray,
};
registry.category("website_systray").add("GeneratorRequest", systrayItem);
registry.category("systray").add("GeneratorRequest", systrayItem); |
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageSelectMenu, MessageActionRow } = require('discord.js');
const Player = require('../../utils/music/Player');
const { getData } = require('spotify-url-info');
const YouTube = require('youtube-sr').default;
let {
playLiveStreams,
playVideosLongerThan1Hour,
maxQueueLength,
AutomaticallyShuffleYouTubePlaylists,
LeaveTimeOut,
MaxResponseTime,
deleteOldPlayMessage
} = require('../../options.json');
const Member = require('../../utils/models/Member');
const {
joinVoiceChannel,
entersState,
VoiceConnectionStatus,
AudioPlayerStatus
} = require('@discordjs/voice');
const createGuildData = require('../../utils/createGuildData');
const { searchOne } = require('../../utils/music/searchOne');
// Check If Options are Valid
if (typeof playLiveStreams !== 'boolean') playLiveStreams = true;
if (typeof maxQueueLength !== 'number' || maxQueueLength < 1) {
maxQueueLength = 1000;
}
if (typeof LeaveTimeOut !== 'number') {
LeaveTimeOut = 90;
}
if (typeof MaxResponseTime !== 'number') {
MaxResponseTime = 30;
}
if (typeof AutomaticallyShuffleYouTubePlaylists !== 'boolean') {
AutomaticallyShuffleYouTubePlaylists = false;
}
if (typeof playVideosLongerThan1Hour !== 'boolean') {
playVideosLongerThan1Hour = true;
}
if (typeof deleteOldPlayMessage !== 'boolean') {
deleteOldPlayMessage = false;
}
// If the Options are outside of min or max then use the closest number
LeaveTimeOut = LeaveTimeOut > 600 ? 600 : LeaveTimeOut &&
LeaveTimeOut < 2 ? 1 : LeaveTimeOut; // prettier-ignore
MaxResponseTime = MaxResponseTime > 150 ? 150 : MaxResponseTime &&
MaxResponseTime < 5 ? 5 : MaxResponseTime; // prettier-ignore
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Play any song or playlist from YouTube or Spotify!')
.addStringOption(option =>
option
.setName('query')
.setDescription(
'🎶 What song or playlist would you like to listen to? Add -s to shuffle a playlist'
)
.setRequired(true)
),
async execute(interaction) {
if (!interaction.client.guildData.get(interaction.guildId)) {
interaction.client.guildData.set(interaction.guildId, createGuildData());
}
const message = await interaction.deferReply({
fetchReply: true
});
// Make sure that only users present in a voice channel can use 'play'
if (!interaction.member.voice.channel) {
interaction.followUp(
':no_entry: Please join a voice channel and try again!'
);
return;
}
// Make sure there isn't a 'music-trivia' running
if (
interaction.client.guildData.get(interaction.guild.id).triviaData
.isTriviaRunning
) {
interaction.followUp(':x: Please try after the trivia has ended!');
return;
}
let query = interaction.options.get('query').value;
//Parse query to check for flags
var splitQuery = query.split(' ');
var shuffleFlag = splitQuery[splitQuery.length - 1] === '-s';
var reverseFlag = splitQuery[splitQuery.length - 1] === '-r';
var nextFlag = splitQuery[splitQuery.length - 1] === '-n';
var jumpFlag = splitQuery[splitQuery.length - 1] === '-j';
if (shuffleFlag || reverseFlag || nextFlag || jumpFlag) splitQuery.pop();
query = splitQuery.join(' ');
let player = interaction.client.playerManager.get(interaction.guildId);
if (!player) {
player = new Player();
interaction.client.playerManager.set(interaction.guildId, player);
}
if (player.commandLock) {
return interaction.followUp(
'Please wait until the last play call is processed'
);
}
player.commandLock = true;
// Check if the query is actually a saved playlist name
const userData = await Member.findOne({
memberId: interaction.member.id
}).exec(); // Object
if (userData !== null) {
const playlistsArray = userData.savedPlaylists;
const found = playlistsArray.find(playlist => playlist.name === query);
// Found a playlist with a name matching the query and it's not empty
if (found && playlistsArray[playlistsArray.indexOf(found)].urls.length) {
const fields = [
{
label: 'Playlist',
description: 'Select playlist',
value: 'playlist_option',
emoji: '⏩'
},
{
label: 'Shuffle Playlist',
description: 'Select playlist and shuffle',
value: 'shuffle_option',
emoji: '🔀'
},
{
label: 'YouTube',
description: 'Search on YouTube',
value: 'youtube_option',
emoji: '🔍'
},
{
label: 'Cancel',
value: 'cancel_option',
emoji: '❌'
}
];
let hasHistoryField = false;
const index = String(Number(query) - 1);
if (
Number(query) &&
typeof player.queueHistory[index] !== 'undefined'
) {
hasHistoryField = true;
fields.unshift({
name: `play ${player.queueHistory[index].title}`,
description: 'Play last song',
value: 'previous_song_option',
emoji: '🔙'
});
}
const row = new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId('1')
.setPlaceholder('Please select an option')
.addOptions(fields)
);
const clarificationOptions = await message.channel.send({
content: 'Clarify Please',
components: [row]
});
const clarificationCollector = clarificationOptions.createMessageComponentCollector(
{
componentType: 'SELECT_MENU',
time: MaxResponseTime * 1000
}
);
clarificationCollector.on('end', () => {
if (clarificationOptions)
clarificationOptions.delete().catch(console.error);
});
clarificationCollector.on('collect', async i => {
if (i.user.id !== interaction.user.id) {
i.reply({
content: `This element is not for you!`,
ephemeral: true
});
} else {
clarificationCollector.stop();
const value = i.values[0];
switch (value) {
case 'previous_song_option':
if (!hasHistoryField) break;
if (
player.audioPlayer.state.status !== AudioPlayerStatus.Playing
) {
player.queue.unshift(player.queueHistory[index]);
handleSubscription(player.queue, interaction, player);
break;
}
if (nextFlag || jumpFlag) {
player.queue.unshift(player.queueHistory[index]);
if (
jumpFlag &&
player.audioPlayer.state.status == AudioPlayerStatus.Playing
) {
player.loopSong = false;
player.audioPlayer.stop();
}
} else {
player.queue.push(player.queueHistory[index]);
}
player.commandLock = false;
interaction.followUp(
`'${player.queueHistory[index].title}' was added to queue!`
);
break;
// 1: Play the saved playlist
case 'playlist_option':
playlistsArray[playlistsArray.indexOf(found)].urls.map(song =>
player.queue.push(song)
);
player.commandLock = false;
await interaction.followUp('Added playlist to queue');
if (
player.audioPlayer.state.status === AudioPlayerStatus.Playing
) {
// Send a message indicating that the playlist was added to the queue
// interactiveEmbed(interaction)
// .addField(
// 'Added Playlist',
// `:new: **${query}** added ${
// playlistsArray[playlistsArray.indexOf(found)].urls
// .length
// } songs to the queue!`
// )
// .build();
} else {
handleSubscription(player.queue, interaction, player);
}
break;
// 2: Play the shuffled saved playlist
case 'shuffle_option':
shuffleArray(
playlistsArray[playlistsArray.indexOf(found)].urls
).map(song => player.queue.push(song));
if (
player.audioPlayer.state.status === AudioPlayerStatus.Playing
) {
// Send a message indicating that the playlist was added to the queue
// interactiveEmbed(interaction)
// .addField(
// 'Added Playlist',
// `:new: **${query}** added ${
// playlistsArray[playlistsArray.indexOf(found)].urls
// .length
// } songs to the queue!`
// )
// .build();
} else {
handleSubscription(player.queue, interaction, player);
}
break;
// 3: Search for the query on YouTube
case 'youtube_option':
await searchYoutube(
query,
interaction,
player,
interaction.member.voice.channel
);
break;
// 4: Cancel
case 'cancel_option':
player.commandLock = false;
interaction.followUp('Canceled search');
deletePlayerIfNeeded(interaction);
break;
}
}
});
return;
}
}
// check if the user wants to play a song from the history queue
if (Number(query)) {
const index = String(Number(query) - 1);
// continue if there's no index matching the query on the history queue
if (typeof player.queueHistory[index] === 'undefined') {
return;
}
const row = new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId('history-select')
.setPlaceholder('Please select an option')
.addOptions([
{
label: 'History Queue',
description: `Play song number ${query}`,
value: 'history_option',
emoji: '🔙'
},
{
label: 'YouTube',
description: `Search '${query}' on YouTube`,
value: 'youtube_option',
emoji: '🔍'
},
{
label: 'Cancel',
value: 'cancel_option',
emoji: '❌'
}
])
);
const clarificationOptions = await message.channel.send({
content: 'Did you mean to play a song from the history queue?',
components: [row]
});
const clarificationCollector = clarificationOptions.createMessageComponentCollector(
{
componentType: 'SELECT_MENU',
time: MaxResponseTime * 1000
}
);
clarificationCollector.on('collect', async i => {
if (i.user.id !== interaction.user.id) {
i.reply({
content: `This element is not for you!`,
ephemeral: true
});
} else {
clarificationCollector.stop();
const value = i.values[0];
switch (value) {
// 1: Play a song from the history queue
case 'history_option':
if (
player.audioPlayer.state.status !== AudioPlayerStatus.Playing
) {
player.queue.unshift(player.queueHistory[index]);
handleSubscription(player.queue, interaction, player);
break;
}
if (nextFlag || jumpFlag) {
player.queue.unshift(player.queueHistory[index]);
if (
jumpFlag &&
player.audioPlayer.state.status === AudioPlayerStatus.Playing
) {
player.loopSong = false;
player.audioPlayer.stop();
}
} else {
player.queue.push(player.queueHistory[index]);
}
player.commandLock = false;
interaction.followUp(
`'${player.queueHistory[index].title}' was added to queue!`
);
break;
// 2: Search for the query on YouTube
case 'youtube_option':
await searchYoutube(
query,
interaction,
player,
interaction.member.voice.channel
);
break;
// 3: Cancel
case 'cancel_option':
deletePlayerIfNeeded(interaction);
interaction.followUp('Canceled search');
break;
}
}
});
return;
}
if (isSpotifyURL(query)) {
getData(query)
.then(async data => {
// 'tracks' property only exists on a playlist data object
if (data.tracks) {
// handle playlist
const spotifyPlaylistItems = data.tracks.items;
const processingMessage = await interaction.channel.send({
content: 'Processing Playlist...'
});
for (let i = 0; i < spotifyPlaylistItems.length; i++) {
try {
let trackData;
if (data.type == 'album') {
trackData = {
artists: spotifyPlaylistItems[i].artists,
name: spotifyPlaylistItems[i].name
};
} else {
trackData = {
artists: spotifyPlaylistItems[i].track.artists,
name: spotifyPlaylistItems[i].track.name
};
}
const video = await searchOne(trackData);
if (nextFlag || jumpFlag) {
flagLogic(interaction, video, jumpFlag);
} else {
player.queue.push(
constructSongObj(
video,
interaction.member.voice.channel,
interaction.member.user
)
);
}
} catch (err) {
processingMessage.delete();
return interaction.followUp(
'Failed to process playlist, please try again later'
);
}
}
processingMessage.edit('Playlist Processed!');
if (player.audioPlayer.state.status !== AudioPlayerStatus.Playing) {
handleSubscription(player.queue, interaction, player);
return;
}
return;
}
// single track
else {
try {
const video = await searchOne(data);
if (nextFlag || jumpFlag) {
flagLogic(interaction, video, jumpFlag);
} else {
player.queue.push(
constructSongObj(
video,
interaction.member.voice.channel,
interaction.member.user
)
);
player.commandLock = false;
if (
player.audioPlayer.state.status !== AudioPlayerStatus.Playing
) {
handleSubscription(player.queue, interaction, player);
return;
} else {
return interaction.followUp(
`Added **${video.title}** to queue`
);
}
}
} catch (error) {
return interaction.followUp(error);
}
}
})
.catch(error => {
deletePlayerIfNeeded(interaction);
console.error(error);
interaction.followUp(`I couldn't find what you were looking for :(`);
});
return;
}
if (isYouTubePlaylistURL(query)) {
const playlist = await YouTube.getPlaylist(query);
if (!playlist) {
deletePlayerIfNeeded(interaction);
return interaction.followUp(
':x: Playlist is either private or it does not exist!'
);
}
let videosArr = await playlist.fetch();
if (!videosArr) {
player.commandLock = false;
deletePlayerIfNeeded(interaction);
return interaction.followUp(
":x: I hit a problem when trying to fetch the playlist's videos"
);
}
videosArr = videosArr.videos;
if (AutomaticallyShuffleYouTubePlaylists || shuffleFlag) {
videosArr = shuffleArray(videosArr);
}
if (reverseFlag) {
videosArr = videosArr.reverse();
}
if (player.queue.length >= maxQueueLength) {
player.commandLock = false;
return interaction.followUp(
'The queue is full, please try adding more songs later'
);
}
videosArr = videosArr.splice(0, maxQueueLength - player.queue.length);
//variable to know how many songs were skipped because of privacyStatus
var skipAmount = 0;
await videosArr.reduce(async (__, video, key) => {
// don't process private videos
if (video.private) {
skipAmount++;
return;
}
if (nextFlag || jumpFlag) {
player.queue.splice(
key - skipAmount,
0,
constructSongObj(
video,
interaction.member.voice.channel,
interaction.member.user
)
);
} else {
player.queue.push(
constructSongObj(
video,
interaction.member.voice.channel,
interaction.member.user
)
);
}
});
if (
jumpFlag &&
player.audioPlayer.state.status === AudioPlayerStatus.Playing
) {
player.loopSong = false;
player.audioPlayer.stop();
}
if (player.audioPlayer.state.status !== AudioPlayerStatus.Playing) {
handleSubscription(player.queue, interaction, player);
return;
} else {
// interactiveEmbed(interaction)
// .addField('Added Playlist', `[${playlist.title}](${playlist.url})`)
// .build();
player.commandLock = false;
return interaction.followUp('Added playlist to queue!');
}
}
if (isYouTubeVideoURL(query)) {
const timestampRegex = /t=([^#&\n\r]+)/g;
let timestamp = timestampRegex.exec(query);
if (!timestamp) {
timestamp = 0;
} else {
timestamp = timestamp[1];
if (timestamp.endsWith('s')) {
timestamp = timestamp.substring(0, timestamp.indexOf('s'));
}
if (!Number(timestamp)) timestamp = 0;
}
timestamp = Number(timestamp);
const video = await YouTube.searchOne(query).catch(function (e) {
console.error(e);
deletePlayerIfNeeded(interaction);
interaction.followUp(
':x: There was a problem getting the video you provided!'
);
player.commandLock = false;
});
if (!video) return;
if (video.live === 'live' && !playLiveStreams) {
player.commandLock = false;
deletePlayerIfNeeded(interaction);
interaction.followUp(
'Live streams are disabled in this server! Contact the owner'
);
return;
}
if (video.duration.hours !== 0 && !playVideosLongerThan1Hour) {
player.commandLock = false;
deletePlayerIfNeeded(interaction);
interaction.followUp(
'Videos longer than 1 hour are disabled in this server! Contact the owner'
);
return;
}
if (player.length > maxQueueLength) {
player.commandLock = false;
interaction.followUp(
`The queue hit its limit of ${maxQueueLength}, please wait a bit before attempting to play more songs`
);
return;
}
if (nextFlag || jumpFlag) {
flagLogic(interaction, video, jumpFlag);
} else {
player.queue.push(
constructSongObj(
video,
interaction.member.voice.channel,
interaction.member.user,
timestamp
)
);
}
if (player.audioPlayer.state.status !== AudioPlayerStatus.Playing) {
handleSubscription(player.queue, interaction, player);
return;
}
// interactiveEmbed(interaction)
// .addField('Added to Queue', `:new: [${video.title}](${video.url})`)
// .build();
return;
}
// If user provided a song/video name
await searchYoutube(
query,
interaction,
player,
interaction.member.voice.channel,
nextFlag,
jumpFlag
);
}
};
var handleSubscription = async (queue, interaction, player) => {
let voiceChannel = queue[0].voiceChannel;
if (!voiceChannel) {
// happens when loading a saved playlist
voiceChannel = interaction.member.voice.channel;
}
const title = player.queue[0].title;
let connection = player.connection;
if (!connection) {
connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator
});
connection.on('error', console.error);
}
player.textChannel = interaction.channel;
player.passConnection(connection);
try {
await entersState(player.connection, VoiceConnectionStatus.Ready, 10000);
} catch (err) {
player.commandLock = false;
deletePlayerIfNeeded(interaction);
console.error(err);
await interaction.followUp({ content: 'Failed to join your channel!' });
return;
}
player.process(player.queue);
await interaction.followUp(`Enqueued ${title}`);
};
// var playbackBar = data => {
// if (data.nowPlaying.duration === 'Live Stream') return '';
// const formatTime = compose(timeString, millisecondsToTimeObj);
// const passedTimeInMS = data.songDispatcher.streamTime;
// const songLengthFormatted = timeString(data.nowPlaying.rawDuration);
// const songLengthInMS = rawDurationToMilliseconds(data.nowPlaying.rawDuration);
// const playback = Array(11).fill('▬');
// playback[Math.floor((passedTimeInMS / songLengthInMS) * 11)] =
// ':musical_note:';
// return `${formatTime(passedTimeInMS)} ${playback.join(
// ''
// )} ${songLengthFormatted}`;
// };
var searchYoutube = async (
query,
interaction,
player,
voiceChannel,
nextFlag,
jumpFlag
) => {
const videos = await YouTube.search(query, { limit: 5 }).catch(
async function () {
player.commandLock = false;
return interaction.followUp(
':x: There was a problem searching the video you requested!'
);
}
);
if (!videos) {
return interaction.followUp(
`:x: I had some trouble finding what you were looking for, please try again or be more specific.`
);
}
if (videos.length < 5) {
player.commandLock = false;
return interaction.followUp(
`:x: I had some trouble finding what you were looking for, please try again or be more specific.`
);
}
const vidNameArr = [];
for (let i = 0; i < videos.length; i++) {
vidNameArr.push(videos[i].title.slice(0, 99));
}
vidNameArr.push('cancel');
const row = createSelectMenu(vidNameArr);
const playOptions = await interaction.channel.send({
content: 'Pick a video',
components: [row]
});
const playOptionsCollector = playOptions.createMessageComponentCollector({
componentType: 'SELECT_MENU',
time: MaxResponseTime * 1000
});
playOptionsCollector.on('end', async () => {
if (playOptions) {
await playOptions.delete().catch(console.error);
}
});
playOptionsCollector.on('collect', async i => {
if (i.user.id !== interaction.user.id) {
i.reply({
content: 'This element is not for you!',
ephemeral: true
});
} else {
playOptionsCollector.stop();
const value = i.values[0];
if (value === 'cancel_option') {
if (playOptions) {
interaction.followUp('Search canceled');
player.commandLock = false;
return;
}
}
const videoIndex = parseInt(value);
YouTube.searchOne(
`https://www.youtube.com/watch?v=${videos[videoIndex - 1].id}`
)
.then(function (video) {
if (video.live && !playLiveStreams) {
if (playOptions) {
playOptions.delete().catch(console.error);
return;
}
player.commandLock = false;
return interaction.followUp(
'Live streams are disabled in this server! Contact the owner'
);
}
if (video.duration.hours !== 0 && !playVideosLongerThan1Hour) {
if (playOptions) {
playOptions.delete().catch(console.error);
return;
}
player.commandLock = false;
return interaction.followUp(
'Videos longer than 1 hour are disabled in this server! Contact the owner'
);
}
if (
interaction.client.playerManager.get(interaction.guildId).queue
.length > maxQueueLength
) {
if (playOptions) {
playOptions.delete().catch(console.error);
return;
}
player.commandLock = false;
return interaction.followUp(
`The queue hit its limit of ${maxQueueLength}, please wait a bit before attempting to add more songs`
);
}
if (nextFlag || jumpFlag) {
interaction.client.playerManager
.get(interaction.guildId)
.queue.unshift(
constructSongObj(video, voiceChannel, interaction.member.user)
);
if (
jumpFlag &&
interaction.client.playerManager.get(interaction.guildId)
.audioPlayer.state.status === AudioPlayerStatus.Playing
) {
interaction.client.playerManager.get(
interaction.guildId
).loopSong = false;
interaction.client.playerManager
.get(interaction.guildId)
.audioPlayer.stop();
return interaction.followUp('Skipped song!');
}
} else {
interaction.client.playerManager
.get(interaction.guildId)
.queue.push(
constructSongObj(video, voiceChannel, interaction.member.user)
);
}
if (
interaction.client.playerManager.get(interaction.guildId)
.audioPlayer.state.status !== AudioPlayerStatus.Playing
) {
const player = interaction.client.playerManager.get(
interaction.guildId
);
handleSubscription(player.queue, interaction, player);
} else if (
interaction.client.playerManager.get(interaction.guildId)
.audioPlayer.state.status === AudioPlayerStatus.Playing
) {
player.commandLock = false;
return interaction.followUp(`Added **${video.title}** to queue`);
}
return;
})
.catch(error => {
player.commandLock = false;
deletePlayerIfNeeded(interaction);
if (playOptions) playOptions.delete().catch(console.error);
console.error(error);
return interaction.followUp(
'An error has occurred while trying to get the video ID from youtube.'
);
});
}
});
};
// side effects function
var flagLogic = (interaction, video, jumpFlag) => {
const player = interaction.client.playerManager.get(interaction.guildId);
player.queue.splice(
0,
0,
constructSongObj(
video,
interaction.member.voice.channel,
interaction.member.user
)
);
if (
jumpFlag &&
player.audioPlayer.state.status === AudioPlayerStatus.Playing
) {
player.loopSong = false;
player.audioPlayer.stop();
}
};
/********************************** Helper Functions *****************************/
// var compose = (f, g) => x => f(g(x));
var isYouTubeVideoURL = arg =>
arg.match(
/^(http(s)?:\/\/)?(m.)?((w){3}.)?(music.)?youtu(be|.be)?(\.com)?\/.+/
);
var isYouTubePlaylistURL = arg =>
arg.match(
/^https?:\/\/(music.)?(www.youtube.com|youtube.com)\/playlist(.*)$/
);
var isSpotifyURL = arg =>
arg.match(/^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)/);
var shuffleArray = arr => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
};
var constructSongObj = (video, voiceChannel, user, timestamp) => {
let duration = video.durationFormatted;
if (duration === '00:00') duration = 'Live Stream';
// checks if the user searched for a song using a Spotify URL
return {
url: video.url,
title: video.title,
rawDuration: video.duration,
duration,
timestamp,
thumbnail: video.thumbnail.url,
voiceChannel,
memberDisplayName: user.username,
memberAvatar: user.avatarURL('webp', false, 16)
};
};
var createSelectMenu = namesArray =>
new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId('search-yt-menu')
.setPlaceholder('Please select a video')
.addOptions([
{
label: `${namesArray[0]}`,
value: '1'
},
{
label: `${namesArray[1]}`,
value: '2'
},
{
label: `${namesArray[2]}`,
value: '3'
},
{
label: `${namesArray[3]}`,
value: '4'
},
{
label: `${namesArray[4]}`,
value: '5'
},
{
label: 'Cancel',
value: 'cancel_option'
}
])
);
var deletePlayerIfNeeded = interaction => {
const player = interaction.client.playerManager.get(interaction.guildId);
if (player) {
if (
(player.queue.length && !player.nowPlaying) ||
(!player.queue.length && !player.nowPlaying)
)
return;
return interaction.client.playerManager.delete(interaction.guildId);
}
}; |
const express = require('express');
const aposToLexForm = require('apos-to-lex-form');
const natural = require('natural');
const SpellCorrector = require('spelling-corrector');
const SW = require('stopword');
require('dotenv').config();
const AWS = require('aws-sdk');
// Cloud Services Set-up
// Create unique bucket name
const bucketName = '10498745-twitterbucket';
//Create a promise on S3 service object
const bucketPromise = new AWS.S3({apiVersion: '2006-03-01'}).createBucket({Bucket: bucketName}).promise();
bucketPromise.then(function(data) {
console.log("Successfully created " + bucketName);
})
.catch(function(err) {
console.error(err, err.stack);
});
//Redis cache
const redis = require('redis');
const redisClient = redis.createClient();
redisClient.on('error', (err) => {
console.log("Error " + err);
});
const needle = require('needle');
const token = "AAAAAAAAAAAAAAAAAAAAAB6eTgEAAAAA6CoC3oKLa5uVcPHL9w6pKDkORJw%3DXmwiWNlQPV3NM7MTfBNaIsUKuumB8Y2c5DC0UQBMSFEAhzeWfF";
const endpointUrl = " https://api.twitter.com/2/tweets/search/recent";
const router = express.Router();
//const axios= require('axios');
const spellCorrector = new SpellCorrector();
spellCorrector.loadDictionary();
async function TweetAnalysis(search)
{
try{
//Calling twitter API
console.log("in here 1")
let response2;
const params = {
'query': search.trim(),
'max_results': 5,
'tweet.fields': 'lang'
}
response2 = await needle('get', endpointUrl, params, {
headers: {
"User-Agent": "v2RecentSearchJS",
"authorization": `Bearer ${token}`
}
})
//console.log(response2.body)
let json2= await response2.body;
// console.log("in here 2")
//console.log(json2.data)
//MAking key
if (json2.data){
return {
tweets: json2.data,
}
}
else{
return null;
}
}
catch(err){console.error(err);}
}
function Analyser(results) {
let plotAnalysisData = [];
let totalWeight= 0;
//COMMENT FOR TESTING
// for(let j =1; j <= 10; j++ )
// {
for (let i =0; i< results.tweets.length;i++)
{
if(results.tweets[i].lang = "en")
{
//analysis of tweets
// console.log("in here 3")
const tweet = results.tweets[i].text;
const lexedTweet = aposToLexForm(tweet);
const casedTweet = lexedTweet.toLowerCase();
const alphaOnlyTweet = casedTweet.replace(/[^a-zA-Z\s]+/g, '');
const { WordTokenizer } = natural;
const wordToken = new WordTokenizer();
const tokenizedTweet= wordToken.tokenize(alphaOnlyTweet);
tokenizedTweet.forEach((word, index) => {
tokenizedTweet[index] = spellCorrector.correct(word);
})
const filteredTweet = SW.removeStopwords(tokenizedTweet);
const { SentimentAnalyzer, PorterStemmer } = natural;
const analyzeSentiment = new SentimentAnalyzer('English', PorterStemmer, 'afinn');
const analysis = analyzeSentiment.getSentiment(filteredTweet);
// console.log(analysis)
//storing analysis in array for plot
plotAnalysisData.push({x: 0, y: analysis})
//For getting avg emotions
totalWeight = totalWeight+ analysis;
}
// }
}
totalWeight = Math.round(totalWeight);
let avgWeight = totalWeight /((results.tweets.length) );
console.log("avgWeight");
console.log(avgWeight);
//Check Avg Emotion for all the tweets of that topic
let avgEmo = "";
if (avgWeight < 0) {
avgEmo = "Negative"
};
if (avgWeight === 0) {
avgEmo = "Neutral"
}
if (avgWeight > 0) {
avgEmo = "Positive"
}
return { plotAnalysisData: plotAnalysisData , avgEmo: avgEmo };
}
router.post('/', async(req, res) => {
try{
let search = req.body.search;
search = search.replace(/[^a-zA-Z ]/g, "").split(' ').join('%').substring(0,450);
console.log("The search param ",search);
const redisKey = `TweetTopic:${search.trim()}`;
//return from redis
return redisClient.get (redisKey, (err , result) =>
{
if (result) {
// Serve from Cache
const resultJSONRedis = JSON.parse(result);
console.log("result from cache for query ", search);
//Call Analyser
let analysedResults = Analyser(resultJSONRedis);
res.render('tweetSearch', {searchParam: req.body.search, tweets: resultJSONRedis.tweets, analysis: JSON.stringify(analysedResults.plotAnalysisData), avgemotion: analysedResults.avgEmo});
}
else {
// Check S3
const s3Key = `TweetTopic:${search.trim()}`;
console.log("The s3query is: ", s3Key);
const params = { Bucket: bucketName, Key: s3Key};
return new AWS.S3({apiVersion: '2006-03-01'}).getObject(params, (err, resul) => {
if (resul) {
// Serve from S3
const resultJSON = JSON.parse(resul.Body);
redisClient.setex(redisKey, 3600, JSON.stringify(resultJSON) );
console.log("Stored in redis cache returning from S3");
let analysedResults = Analyser(resultJSON);
res.render('tweetSearch', {searchParam: req.body.search, tweets: resultJSON.tweets, analysis: JSON.stringify(analysedResults.plotAnalysisData), avgemotion: analysedResults.avgEmo});
}
else {
TweetAnalysis(search.trim())
.then(results => {
if(results != null || results != undefined){
//Storing results in redis cache and s3 bucket
// console.log("In call");
// console.log(results)
//redis
redisClient.setex(redisKey, 3600, JSON.stringify(results) );
//s3
const body = JSON.stringify(results);
const objectParams = {Bucket: bucketName, Key: s3Key, Body: body};
const uploadPromise = new AWS.S3({apiVersion: '2006-03-01'}).putObject(objectParams).promise();
uploadPromise.then(function(data) {
console.log("Successfully uploaded data to " + bucketName + "/" + s3Key);
});
let analysedResults = Analyser(results);
res.render('tweetSearch', { searchParam: req.body.search, tweets: results.tweets, analysis: JSON.stringify(analysedResults.plotAnalysisData), avgemotion: analysedResults.avgEmo});
}
else{
res.render('tweetSearch', {searchParam: req.body.search, tweets: "No search results found! Try again.",analysis: "No search results found.",avgemotion: "No search results found."});
}
}
).
catch(err => console.error(err));
}
});
}
});
}
catch(err){
console.error(err);
console.log(err.response.data);
}
});
router.get('/', async(req, res) => {
try{
res.render('tweetSearch', {tweets: null});
}
catch(err){
console.error(err);
console.log(err.response.data);
}
});
module.exports = router; |
//给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j !=
//k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
//
// 你返回所有和为 0 且不重复的三元组。
//
// 注意:答案中不可以包含重复的三元组。
//
//
//
//
//
// 示例 1:
//
//
//输入:nums = [-1,0,1,2,-1,-4]
//输出:[[-1,-1,2],[-1,0,1]]
//解释:
//nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
//nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
//nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
//不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
//注意,输出的顺序和三元组的顺序并不重要。
//
//
// 示例 2:
//
//
//输入:nums = [0,1,1]
//输出:[]
//解释:唯一可能的三元组和不为 0 。
//
//
// 示例 3:
//
//
//输入:nums = [0,0,0]
//输出:[[0,0,0]]
//解释:唯一可能的三元组和为 0 。
//
//
//
//
// 提示:
//
//
// 3 <= nums.length <= 3000
// -10⁵ <= nums[i] <= 10⁵
//
//
// Related Topics 数组 双指针 排序 👍 6422 👎 0
package leetcode.editor.cn;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//java:三数之和
class P15ThreeSum{
public static void main(String[] args){
Solution solution = new P15ThreeSum().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for(int k = 0; k < nums.length - 2; k++){
if(nums[k] > 0) break;
if(k > 0 && nums[k] == nums[k - 1]) continue;
int i = k + 1, j = nums.length - 1;
while(i < j){
int sum = nums[k] + nums[i] + nums[j];
if(sum < 0){
while(i < j && nums[i] == nums[++i]);
} else if (sum > 0) {
while(i < j && nums[j] == nums[--j]);
} else {
res.add(new ArrayList<Integer>(Arrays.asList(nums[k], nums[i], nums[j])));
while(i < j && nums[i] == nums[++i]);
while(i < j && nums[j] == nums[--j]);
}
}
}
return res;
}
}
//class Solution {
// //先使用哈希法来操作
// public List<List<Integer>> threeSum(int[] nums) {
//
// //创建二维数组
// List<List<Integer>> result = new ArrayList<>();
// Arrays.sort(nums);
//
// for(int i=0;i<nums.length;i++){
// //如果第一个就大于零,此数组不存在和为零的三位数
// if(nums[i]>0){break;}
// if (i > 0 && nums[i] == nums[i - 1]) {
// continue;
// }
//
// //创建集合,去重
// HashSet<Integer> set = new HashSet<>();
// for (int j=i+1;j<nums.length;j++){
// //j指向i+3,判断三项均不相等才放行,若只判断前两项,那么-1001将无法得出结果,001时候就被排除
// if (j>i+2&&nums[j]==nums[j - 1]&& nums[j - 1] == nums[j - 2]){
// continue;
// }
// int c= 0-(nums[i]+nums[j]);
// //
// if (set.contains(c)){
// result.add(Arrays.asList(nums[i],nums[j],c));
// set.remove(c);
// }else {
// //未找到c,没有组成三元组,将访问到的j加入集合
// set.add(nums[j]);
// }
// }
// }
// // 对每个内部列表进行排序
// for (List<Integer> innerList : result) {
//// Collections.sort(innerList, Collections.reverseOrder());
// Collections.sort(innerList);
// }
// return result;
//
// }
//}
//leetcode submit region end(Prohibit modification and deletion)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.