text stringlengths 184 4.48M |
|---|
import React from "react";
import { Image } from "react-bootstrap";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
import { useRouter } from "next/router";
import axios from "axios";
const Login = () => {
const router = useRouter();
const login = async () => {
try {
const { data } = await axios.post("/api/auth", {
username: "info@mastest.com",
password: "vr@(5C=V",
});
if (data.message === "Authentication successful") {
localStorage.setItem("isLoggedIn", "true"); // Set flag
router.push("/patients");
}
} catch (error) {
if (
error.response &&
error.response.data &&
error.response.data.message
) {
setErrorMessage(error.response.data.message);
} else {
setErrorMessage("An unexpected error occurred");
}
}
};
return (
<>
<section className="login">
<div className="left-wrapper">
<Image src="/img/body-bg.png" alt="" />
</div>
<div className="right-wrapper">
<div className="login-wrapper">
<h3 className="mb-2">Login</h3>
<p className="mb-5">
Welcome back! Please enter your details.
</p>
<Form>
<Form.Group
className="mb-3"
controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
/>
</Form.Group>
<Form.Group
className="mb-3"
controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
/>
</Form.Group>
<Button
variant="dark"
className="mt-4 px-5 py-3"
onClick={login}>
Login
</Button>
</Form>
</div>
</div>
</section>
</>
);
};
export default Login; |
@page "/login"
@using System.ComponentModel.DataAnnotations
@using MudBlazor
@using OrderFlowManagementFrontend.Data;
@inject Blazored.LocalStorage.ILocalStorageService LocalStorage
@inject ElectronicResponse electronicsListResponse;
@inject NavigationManager Navigation
<div class="form-wrapper d-flex align-items-center justify-content-center">
<EditForm Model="@login" OnValidSubmit="OnValidSubmit">
<DataAnnotationsValidator />
<div style="margin-top:30%">
@if (flag1 == true)
{
<MudAlert Severity="Severity.Error" Variant="Variant.Filled">@messageResponse</MudAlert>
}
@if (flag2 == true)
{
<MudAlert Severity="Severity.Success" Variant="Variant.Filled">@messageResponse</MudAlert>
}
<MudItem xs="12" sm="7">
<MudCard Style="width:25vw;">
<MudCardContent>
<MudTextField Label="Email" Class="mt-3"
@bind-Value="login.email" For="@(() => login.email)" />
<MudTextField Label="Password" Class="mt-3"
@bind-Value="login.password" For="@(() => login.password)" />
</MudCardContent>
<MudCardActions>
<MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto" Style="background-color:#85ea2d; color:black">Login</MudButton>
</MudCardActions>
</MudCard>
</MudItem>
<MudItem xs="12" Style="margin-top:20px;">
<MudText Typo="Typo.body2" Align="Align.Center">
Not a Registered User <a href="/" style="color:blue">Sign up here!</a>
</MudText>
</MudItem>
</div>
</EditForm>
</div>
@code {
UserLogin login = new UserLogin();
bool flag1 = false;
bool flag2 = false;
string messageResponse = "skjfh";
HttpClient httpClient = new HttpClient();
private async Task OnValidSubmit(EditContext context)
{
try
{
var response = await httpClient.PostAsJsonAsync("https://localhost:7122/loginuser", login);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<RegistrationResponse>();
messageResponse = "Login successful";
await LocalStorage.SetItemAsync("UserId", result.id);
await LocalStorage.SetItemAsync("JwtToken", result.token);
flag2 = !flag2;
StateHasChanged();
await Task.Delay(3000);
Navigation.NavigateTo("/Products");
}
else
{
messageResponse = "Incorrect Details";
flag1 = !flag1;
StateHasChanged();
await Task.Delay(3000);
flag1 = !flag1;
StateHasChanged();
}
}
catch (Exception ex)
{
// Handle error
Console.Error.WriteLine($"Error during submission: {ex.Message}");
}
StateHasChanged();
}
} |
from dataclasses import dataclass, field
from typing import List
import pandas as pd
@dataclass
class ClientConfig:
file_path_map_supergenres: str = field(default_factory=str)
years_to_search: List[str] = field(default_factory=list)
tracks_to_search: List[str] = field(default_factory=list)
number_tracks_per_genre: int = field(default_factory=int)
market_searched: str = field(default_factory=str)
supergenre_dictionary: dict = field(init=False)
inv_supergenre_dictionary: dict = field(init=False)
def __post_init__(self):
self.supergenre_dictionary, self.inv_supergenre_dictionary = self.__create_supergenre_mapping()
def __create_supergenre_mapping(self) -> dict:
genres_df = pd.read_csv(self.file_path_map_supergenres)
supergenre_dictionary = pd.Series(genres_df.supergenre.values, index=genres_df.genre).to_dict()
super_to_genres = {}
for genre, supergenre in supergenre_dictionary.items():
super_to_genres[supergenre] = super_to_genres.get(supergenre, []) + [genre]
return supergenre_dictionary, super_to_genres |
# webrtc拉流协议介绍
七牛云视频监控产品(qvs)在现有的3种播放协议(hls, http-flv, rtmp)基础上,拓展了第4种播放协议webrtc。该协议实时延迟可达到500毫秒左右,可以满足客户对低延迟场景的需求
# webrtc拉流播放实现架构

# 核心优势
* 95%情况下, 实时监控延迟在300-500毫秒区间内
# 快速体验
* `http`环境: <a href="http://pili-player-demo.qiniu.com">http环境webrtc播放器测试</a>
* `https`环境:`当切仅当`为域名[配置ssl证书](https://developer.qiniu.com/qvs/6925/qvs-https-configuration)后,方能体验 <a href="https://pili-player-demo.qiniu.com">https环境webrtc播放器测试</a>
* webrtc地址如何获取
* 方式1 通过qvs控制台,点击实时预览页面,会返回webrtc播放地址。
* 方式2 <a href="https://developer.qiniu.com/qvs/6740/obtain-flow-address"> 通过API获取webrtc播放地址 </a>
* 最终的地址形式
* 1> 如果是动态接入的空间
* http环境:webrtc://ip:1240/空间id/流id
https环境:无法使用ip的形式进行播放 。
* 2>如果是静态接入的空间
http环境:webrtc://域名:1240/空间id/流id
https环境:webrtc://域名:447/空间id/流id, 前提要[配置https ssl证书](https://developer.qiniu.com/qvs/6925/qvs-https-configuration)
# 前提限制
* 需要使用七牛的播放器进行webrtc拉流播放
* rtmp推流时, 不能含有B帧(webrtc播放不支持B帧),具体情况请参考以下tips
* 1. 使用ffmpeg进行rtmp推流时,务必要携带 -bf 0参数, 例如ffmpeg -re -i xxx.mp4 -c copy -c:v libx264 `-bf 0` -f flv 'rtmp推流地址'
* 2. 使用obs推流时, 如下图所示
<img src="https://dn-odum9helk.qbox.me/FgNBl1S2A0RimDhFuFHM86fA9b17" width = "450" height = "300" alt="obs rtmp推流设置" align=center />
* 3. 小程序rtmp推流不包含B帧,可以跳过该条
* 4. 使用七牛安卓/ios推流sdk,可以通过函数设置BaseProfile, 也可以去除B帧
* 5. 其他第三方rtmp推流工具/sdk, 可以自行查看文档
* 6. 安防行业的摄像头(ipc)或者录像机(nvr),自带的rtmp推流,默认都不包含B帧,可以跳过该条
* 采用gb28181接入的摄像头(ipc)或者录像机(nvr)注意的情况
* 1.建议在摄像头的视频参数配置界面。1>设置可变码率 2> I帧间隔 = 帧率 * 2,3>如果需要开启音频, 设置为 g711-alaw, 采样率8K
<img src="https://dn-odum9helk.qbox.me/Fs0WnLsU25BJzsacWqmuMcX3cUBw" width = "450" height = "300" alt="gb28181视频设置" align=center />
# 正式接入流程
体验了以上流程之后,正式接入步骤参考如下
* 七牛webrtc快直播-低延时播放器SDK 下载
* Android SDK 下载:[QNRTPlayer-Android](https://github.com/pili-engineering/QNRTPlayer-Android)、
* [<低延迟Android SDK使用说明>](https://developer.qiniu.com/pili/7731/geek-android-sdk)
* iOS SDK 下载:[QNRTPlayer-iOS](https://github.com/pili-engineering/QNRTPlayer-iOS)
* [<低延迟iOS SDK使用说明>](https://developer.qiniu.com/pili/7732/geek-ios-sdk)
* Web SDK 下载:[QNRTPlayer-Web](https://github.com/pili-engineering/QNRTPlayer-Web)
* [<低延时 Web SDK使用说明>](https://developer.qiniu.io/pili/7730/geek-web-sdk) 低延迟web sdk需要浏览器支持 RTC 和 H264 解码,目前部分 Android 手机自带浏览器并未支持 RTC。在这种情况下,我们建议更换浏览器或直接使用移动端的 SDK, ios端:[<低延时 iOS SDK>](https://developer.qiniu.com/pili/7732/geek-ios-sdk);安卓端:[<低延时 Android SDK>](https://developer.qiniu.com/pili/7731/geek-android-sdk).
* Demo 体验
Android Demo: [http://fir.qnsdk.com/dun3](http://fir.qnsdk.com/dun3)

iOS Demo: [http://fir.qnsdk.com/reb4](http://fir.qnsdk.com/reb4)
 |
import React, { useCallback, useState } from 'react';
import EncryptedStorage from 'react-native-encrypted-storage';
import { useSignUp } from '@/apis/member';
import { useGetUniversities, useGetUniversity } from '@/apis/university';
import { SignUpEntity } from '@/types/member';
import { useNavigation } from '@react-navigation/native';
import { RootStackScreenProps } from '../Stack/Stack';
import { SignUpPresenter } from './SignUpPresenter';
type Navigation = RootStackScreenProps<'SignUp'>['navigation'];
const initialForm = {
email: '',
password: '',
university: null,
majorId: null,
nickname: '',
};
export const SignUpContainer = () => {
const navigation = useNavigation<Navigation>();
const { mutateAsync: signUp } = useSignUp();
const [form, setForm] = useState<SignUpEntity>(initialForm);
const { universities = [] } = useGetUniversities();
const { universityMajor = [] } = useGetUniversity(form.university);
const onChange = useCallback(
(key: keyof SignUpEntity, value: string) => {
setForm({ ...form, [key]: value });
},
[form]
);
// const fetchMajor = (code: string) => {};
const onPressSignUp = async () => {
if (validate()) {
signUp(form, {
onSuccess: goNavSignUpSuccess,
});
}
};
const validate = () => {
let isValid = true;
// 회원가입 폼이 비어있는 경우를 체크한다.
for (let [, value] of Object.entries(form)) {
if (!value) {
isValid = false;
}
}
return isValid;
};
const goNavSignUpSuccess = () => {
navigation.navigate('SignUpSuccess');
};
const onPressSignIn = () => {
navigation.goBack();
};
const onPressNonMemberSignIn = async () => {
const bookmarks = JSON.parse((await EncryptedStorage.getItem('bookMark')) || '[]');
if (bookmarks.length > 0) {
navigation.navigate('Home');
} else {
navigation.navigate('BookMark');
}
};
const props = {
universities,
universityMajor,
onChange,
onPressSignUp,
onPressSignIn,
onPressNonMemberSignIn,
};
return <SignUpPresenter {...props} />;
}; |
pragma solidity^0.8.7;
library Role {
struct PersonRole {
mapping(address=>bool) isExists;
mapping(address=>string) summarys;
}
function isRole(PersonRole storage _role, address _person) internal view returns (bool) {
if(_person == address(0)) {
return false;
}
return _role.isExists[_person];
}
function addRole(PersonRole storage _role, address _person, string memory _summary) internal returns(bool) {
if(isRole(_role, _person)) {
return false;
}
_role.isExists[_person] = true;
_role.summarys[_person] = _summary;
return true;
}
function removeRole(PersonRole storage _role, address _person) internal returns (bool) {
if(!isRole(_role, _person)) {
return false;
}
delete _role.isExists[_person];
delete _role.summarys[_person];
return true;
}
function resetRole(PersonRole storage _role, address _person, string memory _summary) internal returns(bool) {
if(!isRole(_role, _person)) {
return false;
}
_role.summarys[_person] = _summary;
return true;
}
} |
@using BestMovies.Shared.Dtos.Movies
@using BestMovies.WebApp.Helpers
@using BestMovies.WebApp.Repositories
@using System.Globalization
@using BestMovies.Shared.CustomExceptions
@using BestMovies.Shared.Dtos.Review
@using BestMovies.WebApp.Authorization
@using BestMovies.WebApp.Services
<MudDialog DisableSidePadding="true">
<DialogContent>
<MudContainer MaxWidth="MaxWidth.ExtraLarge" Class="d-flex flex-column justify-start gap-2 px-8 py-4" Style="overflow-y: auto;">
<MudImage Class="rounded" ObjectFit="@ObjectFit.Cover" Height="400" Src="@($"api/movies/{MovieId}/image?size=original")" Alt="Movie Image"/>
<div class="d-flex flex-column justify-start gap-1">
@if (_movieDetails is null)
{
<MudSkeleton Animation="Animation.Wave" Width="80%" Height="60px"/>
<MudSkeleton Animation="Animation.Wave" Width="30%" Height="20px"/>
}
else
{
<MudText Typo="Typo.h3" Align="Align.Center"> @_movieDetails.Title </MudText>
}
</div>
<div class="d-flex flex-row flex-wrap justify-center align-start gap-4">
@if (_movieDetails is not null)
{
<div class="d-flex flex-column justify-center align-center pa-2 mr-12">
<MudText Typo="Typo.button" Align="Align.Start">@_movieDetails.ReleaseDate?.ToString("dd MMM yyyy")</MudText>
<MudText Typo="Typo.overline">Release date</MudText>
</div>
<div class="d-flex flex-column justify-center align-center pa-2">
<MudText Typo="Typo.button">@DisplayHelper.DisplayValue(_movieDetails.VoteAverage, _culture)</MudText>
<MudText Typo="Typo.overline">TMDB Rating</MudText>
</div>
}
@if (_movieStats is not null)
{
<div class="rounded pa-2">
<div class="d-flex flex-column justify-center align-center">
<MudText Typo="Typo.button">@_movieStats.Watched</MudText>
<MudText Typo="Typo.overline">Watched</MudText>
</div>
</div>
<div class="rounded pa-2">
<div class="d-flex flex-column justify-center align-center">
<MudText Typo="Typo.button">@DisplayHelper.DisplayValue(_movieStats.AverageRating, _culture, numberOfDecimals: 1)/5</MudText>
<MudText Typo="Typo.overline">Rating</MudText>
</div>
</div>
<div class="highlight-on-hover rounded pa-2 cursor-pointer" @onclick="OpenReviewsModal">
<div class="d-flex flex-column justify-center align-center">
<MudText Typo="Typo.button">@_movieStats.ReviewsCount </MudText>
<MudText Typo="Typo.overline">Reviews</MudText>
</div>
</div>
}
@if (_userInformation?.ClientPrincipal is not null)
{
<div class="d-flex flex-row justify-center align-center gap-2 ml-12">
@if (_savedMovie is not null && _savedMovie.IsWatched && _review is not null)
{
<MudTooltip Text="Your rating">
<MudChip Icon="@Icons.Material.Filled.Star" IconColor="Color.Warning">@_review.Rating/5</MudChip>
</MudTooltip>
}
else
{
<MudTooltip Text="@(_savedMovie is null ? "Add the movie to your list" : "Remove from your list")">
@if (_isLoading)
{
<MudProgressCircular Indeterminate="true"/>
}
else
{
<MudToggleIconButton Toggled="@(_savedMovie is not null)"
Icon="@Icons.Material.Filled.PlaylistAdd"
ToggledIcon="@Icons.Material.Filled.PlaylistAddCheck"
@onclick="SaveRemoveMovie"/>
}
</MudTooltip>
<MudTooltip Text="Review the movie">
<MudIconButton Icon="@Icons.Material.Filled.ThumbUp" @onclick="OpenAddReviewModal"/>
</MudTooltip>
}
</div>
}
</div>
<MudDivider FlexItem="true"/>
<div class="d-flex flex-column justify-start gap-1">
<MudText Typo="Typo.h6" Align="Align.Start">Description</MudText>
@if (_movieDetails is null)
{
<MudSkeleton Class="rounded" Animation="Animation.Wave" SkeletonType="SkeletonType.Rectangle" Height="200px"/>
}
else
{
<MudText Typo="Typo.body1" Align="Align.Start"> @_movieDetails.Description </MudText>
}
</div>
<MudDivider FlexItem="true"/>
<div class="d-flex flex-column justify-start gap-1">
<MudText Typo="Typo.h6" Align="Align.Start">Genre</MudText>
@if (_movieDetails is null)
{
<MudSkeleton Class="rounded" Animation="Animation.Wave" SkeletonType="SkeletonType.Rectangle" Height="50px"/>
}
else
{
<div class="d-flex flex-row flex-wrap gap-2 justify-center px-4 pb-2" style="overflow-x: auto;">
@foreach (var genre in _movieDetails.Genres)
{
<MudChip>@genre</MudChip>
}
</div>
}
</div>
<div class="d-flex flex-column justify-start gap-1">
<MudText Typo="Typo.h6" Align="Align.Start">Cast</MudText>
<div class="d-flex flex-row gap-2 justify-space-between px-4 pb-2 hide-scrollbar" style="overflow-x: auto; ">
@if (_movieDetails is null)
{
for (var i = 0; i < 5; i++)
{
<MudSkeleton Animation="Animation.Wave" SkeletonType="SkeletonType.Circle" Width="120px" Height="120px"/>
}
}
else
{
@if (_movieDetails.Director is not null)
{
<div class="highlight-on-hover rounded pa-2">
<div class="d-flex flex-column justify-start align-center cursor-pointer" @onclick="() => OpenActorDetails(_movieDetails.Director.Id)">
<MudImage Class="mud-skeleton-circle" ObjectFit="@ObjectFit.Cover" ObjectPosition="ObjectPosition.Center" Height="120" Width="120" Src="@($"api/actors/{_movieDetails.Director.Id}/image?size=w300")" Alt="@_movieDetails.Director.Name"/>
<MudText Align="Align.Center" Typo="Typo.button">@_movieDetails.Director.Name</MudText>
<MudText Align="Align.Center" Typo="Typo.overline">Director</MudText>
</div>
</div>
}
foreach (var actor in _movieDetails.Actors)
{
<div class="highlight-on-hover rounded pa-2">
<div class="d-flex flex-column justify-start align-center cursor-pointer" @onclick="() => OpenActorDetails(actor.Id)">
<MudImage Class="mud-skeleton-circle" ObjectFit="@ObjectFit.Cover" ObjectPosition="ObjectPosition.Center" Height="120" Width="120" Src="@($"api/actors/{actor.Id}/image?size=w300")" Alt="@actor.Name"/>
<MudText Align="Align.Center" Typo="Typo.button">@actor.Name</MudText>
<MudText Align="Align.Center" Typo="Typo.overline">@actor.RoleName</MudText>
</div>
</div>
}
}
</div>
</div>
</MudContainer>
</DialogContent>
</MudDialog>
@code {
[Inject]
protected IMoviesRepository MoviesRepository { get; set; } = default!;
[Inject]
protected ISavedMoviesRepository SavedMoviesRepository { get; set; } = default!;
[Inject]
protected IReviewRepository ReviewRepository { get; set; } = default!;
[Inject]
protected IStatisticsRepository StatisticsRepository { get; set; } = default!;
[Inject]
protected IAuthService AuthService { get; set; } = default!;
[Inject]
protected IDialogService DialogService { get; set; } = default!;
[CascadingParameter]
public MudDialogInstance MudDialog { get; set; } = null!;
[Parameter]
public int MovieId { get; set; }
private readonly CultureInfo _culture = CultureInfo.InvariantCulture;
private MovieDetailsDto? _movieDetails;
private MovieStatsDto? _movieStats;
private UserInformation? _userInformation;
private SavedMovieDto? _savedMovie;
private ReviewDto? _review;
private bool _isLoading;
protected override async Task OnInitializedAsync()
{
var tasks = new[]
{
FetchMovieDetails(),
FetchMovieStats(),
FetchUserInfo(),
FetchSavedMovie(),
FetchMovieReview()
};
await Task.WhenAll(tasks);
}
private async Task FetchMovieDetails()
{
_movieDetails = await MoviesRepository.GetMovieDetails(MovieId);
await InvokeAsync(StateHasChanged);
}
private async Task FetchUserInfo() => _userInformation = await AuthService.RetrieveUserInformation();
private async Task FetchMovieStats() => _movieStats = await StatisticsRepository.GetMovieStatistics(MovieId);
private async Task FetchSavedMovie() => _savedMovie = await SavedMoviesRepository.GetSavedMovie(MovieId);
private async Task FetchMovieReview() => _review = await ReviewRepository.GetMovieReview(MovieId);
private void OpenActorDetails(int actorId)
{
var parameters = new DialogParameters
{
{"ActorId", actorId}
};
var options = new DialogOptions {CloseOnEscapeKey = true, CloseButton = true, FullWidth = true, MaxWidth = MaxWidth.Small};
DialogService.Show<ActorDetailsModal>(string.Empty, parameters, options);
}
private async Task OpenAddReviewModal()
{
var parameters = new DialogParameters
{
{"MovieId", MovieId}
};
var options = new DialogOptions {CloseOnEscapeKey = true, CloseButton = true, FullWidth = true, MaxWidth = MaxWidth.ExtraSmall};
var dialog = await DialogService.ShowAsync<AddReviewModal>(_movieDetails!.Title, parameters, options);
var result = await dialog.Result;
if (!result.Canceled)
{
await FetchMovieStats();
await FetchSavedMovie();
await FetchMovieReview();
}
}
private void OpenReviewsModal()
{
var parameters = new DialogParameters
{
{"MovieId", MovieId}
};
var options = new DialogOptions {CloseOnEscapeKey = true, CloseButton = true, FullWidth = true, MaxWidth = MaxWidth.ExtraSmall};
DialogService.Show<ReviewsModal>(_movieDetails!.Title, parameters, options);
}
private async Task SaveRemoveMovie()
{
_isLoading = true;
await InvokeAsync(StateHasChanged);
try
{
if (_savedMovie is null)
{
var savedMovie = new SavedMovieDto(_movieDetails!.Id, false);
await SavedMoviesRepository.SaveMovie(savedMovie);
}
else if (_savedMovie is not null && !_savedMovie.IsWatched)
{
await SavedMoviesRepository.RemoveMovie(_movieDetails!.Id);
}
await FetchSavedMovie();
}
catch (ApiException) { }
_isLoading = false;
await InvokeAsync(StateHasChanged);
}
} |
<script setup>
import { ref } from "vue";
import FrontLayout from "@/Layouts/FrontLayout.vue";
import MovieCard from "@/Matrials/MovieCard.vue";
import { Link, Head } from "@inertiajs/vue3";
import {
TransitionRoot,
TransitionChild,
Dialog,
DialogOverlay,
DialogTitle,
} from "@headlessui/vue";
defineProps({
movie: Object,
latests: Array,
casts: Array,
tags: Array,
movieGenres: Array,
trailers: Array,
downloads: Array,
});
const isOpen = ref(false);
const modalTrailer = ref({});
function closeModal() {
isOpen.value = false;
}
function openModal(trailer) {
modalTrailer.value = trailer;
isOpen.value = true;
}
</script>
<style></style>
<template>
<Head :title="`Movie`" />
<FrontLayout>
<main v-if="movie" class="my-2">
<section class="bg-gradient-to-r from-indigo-700 to-transparent">
<div class="max-w-6xl mx-auto m-4 p-2">
<div class="flex">
<div class="w-3/12">
<div class="w-full">
<img class="w-full h-full rounded"
:src="`https://www.themoviedb.org/t/p/w220_and_h330_face/${movie.poster_path}`" />
</div>
</div>
<div class="w-8/12">
<div class="m-4 p-6">
<h1 class="flex text-white font-bold text-4xl">
{{ movie.title }}
</h1>
<div class="flex p-3 text-white space-x-4">
<span>{{ movie.release_date }}</span>
<span class="ml-2 space-x-1">
<Link v-for="genre in movieGenres" :key="genre.id" class="font-bold hover:text-blue-500"
:href="`/genres/${genre.slug}`">
{{ genre.title }},
</Link>
</span>
<span class="flex space-x-2">
{{ movie.runtime }}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</span>
</div>
<div class="flex space-x-4">
<button class="
px-4
py-2
text-sm
font-medium
text-white
bg-black
rounded-md
bg-opacity-20
hover:bg-opacity-30
focus:outline-none
focus-visible:ring-2
focus-visible:ring-white
focus-visible:ring-opacity-75
" v-for="trailer in trailers" :key="trailer.id" @click="openModal(trailer)">
{{ trailer.name }}
</button>
</div>
</div>
<div class="p-8 text-white">
<p>{{ movie.overview }}</p>
</div>
</div>
</div>
<div class="mt-4">
<h3 class="text-2xl font-semibold text-white">Download movie</h3>
<div class="flex space-x-4">
<a class="
px-4
py-2
text-sm
font-medium
text-white
bg-black
rounded-md
bg-opacity-20
hover:bg-opacity-30
focus:outline-none
focus-visible:ring-2
focus-visible:ring-white
focus-visible:ring-opacity-75
" v-for="download in downloads" :key="download.id" :href="download.web_url" target="_blank">
{{ download.name }}
</a>
</div>
</div>
</div>
</section>
<section class="max-w-6xl mx-auto bg-gray-200 dark:bg-gray-900 p-2 rounded">
<div class="flex justify-between">
<div class="w-7/12">
<h1 class="flex text-slate-600 dark:text-white font-bold text-xl">
Movie Casts
</h1>
<div class="grid grid-cols-2 md:grid-cols-5 gap-4 mt-4">
<MovieCard v-for="cast in casts" :key="cast.id">
<template #image>
<Link :href="`/casts/${cast.slug}`">
<img class="" :src="`https://www.themoviedb.org/t/p/w220_and_h330_face/${cast.poster_path}`" />
</Link>
</template>
<Link :href="`/casts/${cast.slug}`">
<span class="text-slate-600 dark:text-white">{{
cast.name
}}</span>
</Link>
</MovieCard>
</div>
</div>
<div class="w-4/12">
<h1 class="flex text-slate-600 dark:text-white font-bold text-xl mb-4">
Latest movies
</h1>
<div class="grid grid-cols-3 gap-2" v-if="latests.length">
<Link v-for="lm in latests" :key="lm.id" :href="`/movies/${lm.slug}`">
<img class="w-full h-full rounded-lg"
:src="`https://www.themoviedb.org/t/p/w220_and_h330_face/${lm.poster_path}`" />
</Link>
</div>
</div>
</div>
</section>
<section v-if="movie.tags" class="
max-w-6xl
mx-auto
bg-gradient-to-r
from-indigo-700
to-transparent
mt-6
p-2
">
<span v-for="tag in movie.tags" :key="tag.id" class="font-bold text-white hover:text-indigo-200 cursor-pointer">
<Link :href="`/tags/${tag.slug}`" class="ml-2">#{{ tag.tag_name }}</Link>
</span>
</section>
</main>
</FrontLayout>
<TransitionRoot appear :show="isOpen" as="template">
<Dialog as="div" @close="closeModal">
<div class="fixed inset-0 z-10 overflow-y-auto">
<div class="min-h-screen px-4 text-center">
<TransitionChild as="template" enter="duration-300 ease-out" enter-from="opacity-0" enter-to="opacity-100"
leave="duration-200 ease-in" leave-from="opacity-100" leave-to="opacity-0">
<DialogOverlay class="fixed inset-0" />
</TransitionChild>
<span class="inline-block h-screen align-middle" aria-hidden="true">
​
</span>
<TransitionChild as="template" enter="duration-300 ease-out" enter-from="opacity-0 scale-95"
enter-to="opacity-100 scale-100" leave="duration-200 ease-in" leave-from="opacity-100 scale-100"
leave-to="opacity-0 scale-95">
<div class="
inline-block
w-full
max-w-6xl
p-6
my-8
overflow-hidden
text-left
align-middle
transition-all
transform
bg-white
shadow-xl
rounded-2xl
">
<DialogTitle as="h3" class="text-lg font-medium leading-6 text-gray-900">
</DialogTitle>
<div class="mt-2" v-if="modalTrailer">
<div class="aspect-w-16 aspect-h-9" v-html="modalTrailer.embed_html"></div>
</div>
<div class="mt-4">
<button type="button" class="
inline-flex
justify-center
px-4
py-2
text-sm
font-medium
text-blue-900
bg-blue-100
border border-transparent
rounded-md
hover:bg-blue-200
focus:outline-none
focus-visible:ring-2
focus-visible:ring-offset-2
focus-visible:ring-blue-500
" @click="closeModal">
Close
</button>
</div>
</div>
</TransitionChild>
</div>
</div>
</Dialog>
</TransitionRoot>
</template> |
import React, { useRef, useState } from 'react';
import '../assets/css/Modal.css';
function CustomModal({handlePayment}) {
const modalRef = useRef(null);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [travelers, setTravelers] = useState(1);
const [travelDate, setTravelDate] = useState('');
const [submitted, setSubmitted] = useState(false);
const [emailError, setEmailError] = useState('');
const [nameError, setNameError] = useState('');
const [travelDateError, setTravelDateError] = useState('');
const [globalError, setGlobalError] = useState('');
const handleName = (e) => {
if(!e.target.value.trim()){
setNameError('Please enter your full name.');
} else {
setName(e.target.value);
setNameError('');
}
setSubmitted(false);
};
const handleEmail = (e) => {
if (!e.target.value.includes('@') || !e.target.value.trim()) {
setEmailError('Please enter a valid email address with @.');
setEmail(e.target.value);
} else {
setEmail(e.target.value);
setEmailError('');
}
setSubmitted(false);
};
const handleTravelers = (e) => {
setTravelers(parseInt(e.target.value, 10));
setSubmitted(false);
};
const handleTravelDate = (e) => {
if(!e.target.value){
setTravelDateError('Please Book A Date');
} else {
setTravelDate(e.target.value);
setTravelDateError('');
}
setSubmitted(false);
};
const handleSubmit = (e) => {
e.preventDefault();
if(!name.trim() || !email.trim() || !travelDate.trim()) {
setGlobalError('Fill in all the fields');
setSubmitted(false);
} else {
setSubmitted(true);
setGlobalError('');
handlePayment(40 + 1200 * travelers);
modalRef.current.close();
}
};
return (
<div className="custom-modal-container">
<dialog className="custom-modal" ref={modalRef}>
<h3 className="heading-modal">Book Here</h3>
<span>Required fields are marked by *</span>
<form className="formbox" action="/Confirm" onSubmit={handleSubmit}>
<div className="details">
{globalError && <p className='error-message'>{globalError}</p>}
<label className="modal-name" htmlFor='user-name'>Name: *</label>
<input onChange={handleName} id='user-name' className="inputname" name='username' value={name} type="text" />
{nameError && <p className='error-message'>{nameError}</p>}
<label htmlFor='user-email' className="modal-email">Email: *</label>
<input onChange={handleEmail} className="inputemail" name='useremail' value={email} id='user-email' type="text" />
{emailError && <p className='error-message'>{emailError}</p>}
<label htmlFor='no-travelers' className="modal-travelers">Number of People</label>
<input
onChange={handleTravelers}
className="inputtravelers"
name='unotravelers'
value={travelers}
id='no-travelers'
type="number"
min="1"
/>
<label htmlFor='user-traveldate' className="modal-travelDate"> Date: *</label>
<input onChange={handleTravelDate} className="inputtravelDate" name='usertraveldate' value={travelDate} id='user-traveldate' type="date" />
{travelDateError && <p className='error-message'>{travelDateError}</p>}
<div className='reservation-card'>
<div className="cost">
<span>${1200} x {travelers} {travelers === 1 ? "guest" : "guests"}</span>
<span>${1200 * travelers}</span>
</div>
<div className="cost">
<span>Tax</span>
<span>$ 40</span>
</div>
<hr className="solid" />
<div className="total-cost">
<h3>Total</h3>
<h3>${40 + 1200 * travelers}</h3>
</div>
</div>
</div>
<div className="modal-buttons">
<button type="submit" className="confirm">
Confirm
</button>
<button
onClick={(e) => {
e.preventDefault();
handlePayment(0);
modalRef.current.close();
}}
className="cancel"
>
Cancel
</button>
</div>
</form>
</dialog>
<button
className="open-modal"
onClick={() => {
modalRef.current.showModal();
}}
>
Book a Deal
</button>
</div>
);
}
export default CustomModal; |
package com.woven.challenge;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import com.woven.challenge.exceptions.FileNotFoundException;
import com.woven.challenge.service.FileStorageService;
@AutoConfigureMockMvc
@SpringBootTest
public class FileStorageServiceTests {
@Autowired
private MockMvc mvc;
@MockBean
private FileStorageService storageService;
@Test
public void shouldListAllFiles() throws Exception {
given(this.storageService.loadAll())
.willReturn(Stream.of(Paths.get("first.txt"), Paths.get("second.txt")));
this.mvc.perform(get("/files")).andExpect(status().isOk());
}
@Test
public void shouldSaveUploadedFile() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt",
"text/plain", "Spring Framework".getBytes());
this.mvc.perform(multipart("/files").file(multipartFile))
.andExpect(status().isOk());
then(this.storageService).should().save(multipartFile);
}
} |
package com.librasys.utils;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class JTextFieldWithPlaceholder extends JTextField {
private String placeholder;
public JTextFieldWithPlaceholder(String placeholder) {
this.placeholder = placeholder;
setForeground(Color.GRAY);
setText(placeholder);
addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if (getText().equals(placeholder)) {
setText("");
setForeground(Color.BLACK);
}
}
@Override
public void focusLost(FocusEvent e) {
if (getText().isEmpty()) {
setText(placeholder);
setForeground(Color.GRAY);
}
}
});
}
public String getPlaceholder() {
return placeholder;
}
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
setText(placeholder);
setForeground(Color.GRAY);
}
} |
# Topic 21 - for Loops
# Example Scenario: Checking for a Clean City
city_to_check = "Tucson"
# list of cleanest cities
cleanest_cities = ["Cheyenne", "Santa Fe", "Tucson", "Great Falls", "Honolulu"]
# Without for loop
if city_to_check == cleanest_cities[0]:
print("It's one of the cleanest cities")
elif city_to_check == cleanest_cities[1]:
print("It's one of the cleanest cities")
elif city_to_check == cleanest_cities[2]:
print("It's one of the cleanest cities")
elif city_to_check == cleanest_cities[3]:
print("It's one of the cleanest cities")
elif city_to_check == cleanest_cities[4]:
print("It's one of the cleanest cities")
# Using a for Loop
for a_clean_city in cleanest_cities:
if city_to_check == a_clean_city:
print("It's one of the cleanest cities")
# Optimizing with break
for a_clean_city in cleanest_cities:
if city_to_check == a_clean_city:
print("It's one of the cleanest cities")
break
# Readable Variable Names
for x in y:
if x == z:
print("It's one of the cleanest cities") |
package org.edrdg.jmdict.simplified.conversion
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.*
import java.lang.NumberFormatException
object XrefSerializer : KSerializer<CommonJsonElement.Xref> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Xref")
override fun serialize(encoder: Encoder, value: CommonJsonElement.Xref) {
require(encoder is JsonEncoder)
val array = mutableListOf<JsonPrimitive>()
array.add(JsonPrimitive(value.part1))
if (value.part2 != null) {
array.add(JsonPrimitive(value.part2))
}
if (value.index != null) {
array.add(JsonPrimitive(value.index))
}
encoder.encodeJsonElement(JsonArray(array))
}
override fun deserialize(decoder: Decoder): CommonJsonElement.Xref {
require(decoder is JsonDecoder)
val array = decoder.decodeJsonElement()
val size = array.jsonArray.size
val part1: String = array.jsonArray[0].jsonPrimitive.content
return if (size == 1) {
CommonJsonElement.Xref(part1, null, null)
} else if (size == 2) {
if (array.jsonArray[1].jsonPrimitive.isString) {
CommonJsonElement.Xref(part1, array.jsonArray[1].jsonPrimitive.content, null)
} else {
try {
CommonJsonElement.Xref(part1, null, array.jsonArray[1].jsonPrimitive.content.toInt())
} catch (nfe: NumberFormatException) {
throw Exception(
"Expected to find a string or a number at index 1 in xref, " +
"found ${array.jsonArray[1]}; json: $array",
nfe
)
}
}
} else if (size == 3) {
val part2: String = array.jsonArray[1].jsonPrimitive.content
val index = array.jsonArray[2].jsonPrimitive.content.toInt()
CommonJsonElement.Xref(part1, part2, index)
} else {
throw Exception("Unexpected xref size of $size, expected 1-3")
}
}
} |
import React from "react";
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { View, Text, StyleSheet, TouchableOpacity, Linking } from "react-native";
export default function AboutScreen() {
// Define a function to open Gmail when the email address is pressed
const handleEmailLink = emailAddress => {
// Define the Gmail URL with the "to" parameter pre-filled with the recipient email address
const gmailUrl = `https://mail.google.com/mail/?view=cm&to=${emailAddress}`;
// Open the Gmail URL in the browser
Linking.openURL(gmailUrl);
};
const navigation = useNavigation();
const handleBackNavigation = () => {
navigation.navigate("Profile");
};
return (
<View style={styles.container}>
<View style={styles.backButtonContainer}>
<TouchableOpacity onPress={handleBackNavigation}>
<Ionicons name="arrow-back" size={20} style={styles.icon} />
</TouchableOpacity>
<TouchableOpacity onPress={handleBackNavigation}>
<Text style={styles.backButton}>Back</Text>
</TouchableOpacity>
</View>
<Text style={styles.paragraph}>
This app is designed to provide an interactive platform to connect
readers. This app utilizes the following API:{' '}
<Text
onPress={() =>
Linking.openURL(
'https://developers.google.com/books/docs/v1/getting_started'
)
}
style={styles.link}
>
Google Books API
</Text>
</Text>
<Text> </Text>
{/* Use the Text component to display the email addresses with onPress event handlers */}
<View>
<Text style={styles.heading}>Team</Text>
<Text style={styles.paragraph}>• Manan Patel (Manager/Developer)</Text>
<Text
style={styles.emailLink}
onPress={() => handleEmailLink('mpatel65@vols.utk.edu')}
>
mpatel65@vols.utk.edu
</Text>
<Text style={styles.paragraph}>• Riya Patel (Developer)</Text>
<Text
style={styles.emailLink}
onPress={() => handleEmailLink('rpatel90@vols.utk.edu')}
>
rpatel90@vols.utk.edu
</Text>
<Text style={styles.paragraph}>• Tulsi Tailor (Developer)</Text>
<Text
style={styles.emailLink}
onPress={() => handleEmailLink('ttailor@vols.utk.edu')}
>
ttailor@vols.utk.edu
</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
paddingHorizontal: 20,
paddingVertical: 10,
flex: 1,
backgroundColor: '#FFF',
},
paragraph: {
fontSize: 17,
lineHeight: 24,
marginTop: 35,
marginBottom: 10,
textAlign: 'justify',
},
team: {
fontSize: 17,
lineHeight: 24,
marginBottom: 10,
textAlign: 'left',
},
heading: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 10,
},
link: {
color: '#007AFF',
},
emailLink: {
color: '#007AFF',
marginLeft: 25,
fontSize: 17,
lineHeight: 17,
marginBottom: 7,
},
backButtonContainer: {
position: 'absolute',
top: 20,
left: 20,
flexDirection: 'row',
alignItems: 'center',
},
backButton: {
fontSize: 16,
fontWeight: 'bold',
// color: 'blue',
marginLeft: 5,
marginRight: 5,
},
}); |
// https://www.geeksforgeeks.org/problems/page-faults-in-lru5603/1
// page fault occurs when the page isn't in memory
// when it occurs, we should add page to the memory. If the memory is full we should remove the least recently used page from memory and add it
#include <bits/stdc++.h>
using namespace std;
int ctrPageFaults(vector<int> pages, int capacity)
{
int n = pages.size();
unordered_map<int, int> memory;
// if we want to optimized time in cost of space, we can use a list to do so
int ctr = 0;
for (int i = 0; i <= n - 1; i++)
{
if (memory.find(pages[i]) == memory.end())
{
if (memory.size() == capacity)
{
int mini = 1e9;
for (auto it : memory)
{
mini = min(it.second, mini);
}
memory.erase(memory.find(pages[mini]));
}
memory[pages[i]] = i;
ctr++;
}
else // making the pages[i] recently used
{
memory[pages[i]] = i;
}
}
return ctr;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<int> pages(n);
for (int i = 0; i < n; i++)
{
cin >> pages[i];
}
int capacity;
cin >> capacity;
int faults = ctrPageFaults(pages, capacity);
cout << faults << "\n";
return 0;
} |
import { create } from "zustand";
export interface Conversation {
id?: number;
name?: string;
createdAt?: string; // YYYY-MM-DD HH:mm:ss
updatedAt?: string; // YYYY-MM-DD HH:mm:ss
}
interface UseConversationStoreProps {
conversations: Conversation[];
selectedConversationId: number;
lastInsertId: number;
clickedDeleteButtonId: number;
shouldRefetch: boolean;
isOpen: boolean;
setConversations: (conversations: Conversation[]) => void;
setSelectedConversationId: (conversationId: number) => void;
initSelectedConversationId: () => void;
setLastInsertId: (id: number) => void;
setDeleteButtonId: (id: number) => void;
refetch: () => void;
open: () => void;
close: () => void;
toggle: () => void;
}
const useConversationStore = create<UseConversationStoreProps>()((set) => ({
conversations: [],
selectedConversationId: 0,
lastInsertId: 0,
clickedDeleteButtonId: 0,
shouldRefetch: false,
isOpen: false,
setConversations: (conversations) => {
set((state) => ({
...state,
conversations: conversations,
}));
},
setSelectedConversationId: (conversationId) => {
set((state) => ({
...state,
selectedConversationId: conversationId,
}));
},
initSelectedConversationId: () => {
set((state) => ({
...state,
selectedConversationId: 0,
}));
},
setLastInsertId: (id) => {
set((state) => ({
...state,
lastInsertId: id,
}));
},
setDeleteButtonId: (id) => {
set((state) => ({
...state,
clickedDeleteButtonId: id,
}));
},
refetch: () => {
set((state) => ({
...state,
shouldRefetch: !state.shouldRefetch,
}));
},
open: () => set(() => ({ isOpen: true })),
close: () => set(() => ({ isOpen: false })),
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
}));
export default useConversationStore; |
/*ManabatAljon_BSIT-1C_FinalProject
Quiz Game with 3 Subjects to choose for, inside of that Subject there is also topic to choose.
Rules Option to let the user know what is the rules and Exit Option to Exit the Program.
All of the sytax i used is only Ma'am Memay taught us in Introduction to coding in C++ (IT-111)*/
#include <iostream>
using namespace std;
int main() {
int x, i, choice, lives, subject, topic1, topic2, topic3;
char back, retry;
char ans1e1, ans2e1, ans3e1, ans4e1, ans5e1, ans6e1, ans7e1, ans8e1, ans9e1, ans10e1;
char ans1m1, ans2m1, ans3m1, ans4m1, ans5m1, ans6m1, ans7m1, ans8m1, ans9m1, ans10m1;
char ans1h1, ans2h1, ans3h1, ans4h1, ans5h1, ans6h1, ans7h1, ans8h1, ans9h1, ans10h1;
char ans1sC, ans2sC, ans3sC, ans4sC, ans5sC, ans6sC, ans7sC, ans8sC, ans9sC, ans10sC;
char ans1sP, ans2sP, ans3sP, ans4sP, ans5sP, ans6sP, ans7sP, ans8sP, ans9sP, ans10sP;
char ans1mA, ans2mA, ans3mA, ans4mA, ans5mA, ans6mA, ans7mA, ans8mA, ans9mA, ans10mA;
char ans1mC, ans2mC, ans3mC, ans4mC, ans5mC, ans6mC, ans7mC, ans8mC, ans9mC, ans10mC;
char ans1mS, ans2mS, ans3mS, ans4mS, ans5mS, ans6mS, ans7mS, ans8mS, ans9mS, ans10mS;
do {
cout << "Welcome to Quiz Frenzy! by Aljon Manabat." << endl;
cout << "1. Play the Game" << endl;
cout << "2. View Rules" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == 2) {
do {
cout << "\nRules: You have 3 lives. Answer the questions correctly to win." << endl;
cout << "If you lose all your lives, you can try again." << endl;
cout << "Enter (B) to go back to the main menu: ";
cin >> back;
} while (back != 'b' && back != 'B');
} else if (choice == 1) {
do {
lives = 3;
x = 0;
cout << "\nChoose a subject:" << endl;
cout << "1. Technology" << endl;
cout << "2. Science" << endl;
cout << "3. Mathematics" << endl;
cout << "Enter your choice: ";
cin >> subject;
if (subject == 1) {
cout << "\nPick a topic:" << endl;
cout << "1. IT111" << endl;
cout << "2. IT110" << endl;
cout << "Enter your choice: ";
cin >> topic1;
if (topic1 == 1){
cout << "\nIT111 Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) What is the primary purpose of a programming loop?" << endl;
cout << "a. To repeat a block of code multiple times"<<endl;
cout << "b. To make decisions in the program" << endl;
cout << "c. To declare variables" << endl;
cout << "d. To stop the program" << endl;
cout << "Enter your answer: ";
cin >> ans1e1;
if (ans1e1 == 'a' || ans1e1 == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) What is the role of an if statement in programming?" << endl;
cout << "a. To repeat code" << endl;
cout << "b. To check a condition and execute code if true" << endl;
cout << "c. To define a variable" << endl;
cout << "d. To terminate a program" << endl;
cout << "Enter your answer: ";
cin >> ans2e1;
if (ans2e1 == 'b' || ans2e1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) What happens if the condition in an if statement is false?" << endl;
cout << "a. The program crashes." << endl;
cout << "b. The code inside the if block is skipped." << endl;
cout << "c. The program stops immediately." << endl;
cout << "d. The code inside the if block is still executed." << endl;
cout << "Enter your answer: ";
cin >> ans3e1;
if (ans3e1 == 'b' || ans3e1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) What is the purpose of a for loop?" << endl;
cout << "a. To check conditions and execute code based on them" << endl;
cout << "b. To execute code a specific number of times" << endl;
cout << "c. To stop the program after a condition is met" << endl;
cout << "d. To randomly execute code" << endl;
cout << "Enter your answer: ";
cin >> ans4e1;
if (ans4e1 == 'b' || ans4e1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) Which type of loop will always execute at least once, regardless of the condition?" << endl;
cout << "a. A loop that checks the condition before running" << endl;
cout << "b. A loop that checks the condition after running" << endl;
cout << "c. A loop that runs indefinitely" << endl;
cout << "d. None of the above" << endl;
cout << "Enter your answer: ";
cin >> ans5e1;
if (ans5e1 == 'b' || ans5e1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) In C++, what is the purpose of the else part of an if-else statement?" << endl;
cout << "a.To check a different condition" << endl;
cout << "b. To loop through code" << endl;
cout << "c. To stop the program" << endl;
cout << "d. To execute code when the if condition is false" << endl;
cout << "Enter your answer: ";
cin >> ans6e1;
if (ans6e1 == 'd' || ans6e1 == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) What is a loop condition used for?" << endl;
cout << "a. To declare variables for the loop" << endl;
cout << "b. To check syntax errors in the loop" << endl;
cout << "c. To decide whether the loop should continue or stop" << endl;
cout << "d. To exit the program" << endl;
cout << "Enter your answer: ";
cin >> ans7e1;
if (ans7e1 == 'c' || ans7e1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) What is the syntax for not ?" << endl;
cout << "a. !" << endl;
cout << "b. <not>" << endl;
cout << "c. ?" << endl;
cout << "d. #" << endl;
cout << "Enter your answer: ";
cin >> ans8e1;
if (ans8e1 == 'a' || ans8e1 == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) What or || used for?" << endl;
cout << "a. Nothing" << endl;
cout << "b. To equal" << endl;
cout << "c. If there is atleast one TRUE the answer is still TRUE" << endl;
cout << "d. None of the above" << endl;
cout << "Enter your answer: ";
cin >> ans9e1;
if (ans9e1 == 'c' || ans9e1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.) What happens when a loops condition is never met?"<< endl;
cout << "a. The loop runs once and then stops."<< endl;
cout << "b. The loop is skipped entirely." << endl;
cout << "c. The loop runs indefinitely" << endl;
cout << "d. The program stops with an error." << endl;
cout << "Enter your answer: ";
cin >> ans10e1;
if (ans10e1 == 'b' || ans10e1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
cout << "Quiz Over! Your score is: " << x << "/10." << endl;
}
else if (topic1 == 2) {
cout << "\nIT110 Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) Who is known as the Father of the Computer?" << endl;
cout << "a. Alan Turing" << endl;
cout << "b. Blaise Pascal" << endl;
cout << "c. Charles Babbage" << endl;
cout << "d. John von Neumann " << endl;
cout << "Enter your answer: ";
cin >> ans1m1;
if (ans1m1 == 'c' || ans1m1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) What number system is primarily used by computers to perform calculations?" << endl;
cout << "a. Decimal" << endl;
cout << "b. Binary" << endl;
cout << "c. Octal" << endl;
cout << "d. Hexadecimal" << endl;
cout << "Enter your answer: ";
cin >> ans2m1;
if (ans2m1 == 'b' || ans2m1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) Which of the following is an early mechanical device used for computations?" << endl;
cout << "a. ENIAC" << endl;
cout << "b. Altair 8800 " << endl;
cout << "c. Macintosh" << endl;
cout << "d. Abacus" << endl;
cout << "Enter your answer: ";
cin >> ans3m1;
if (ans3m1 == 'd' || ans3m1 == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) What is the default file extension for a Microsoft Word document in modern versions?" << endl;
cout << "a. .doc" << endl;
cout << "b. .txt" << endl;
cout << "c. .docx " << endl;
cout << "d. .pdf " << endl;
cout << "Enter your answer: ";
cin >> ans4m1;
if (ans4m1 == 'c' || ans4m1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) In Microsoft Excel, what is the purpose of the formula `=SUM(A1:A10)`?" << endl;
cout << "a. To count the number of cells from A1 to A10" << endl;
cout << "b. To add up the values in cells A1 through A10" << endl;
cout << "c. To find the largest value in A1 through A10" << endl;
cout << "d. To display the average of the values in A1 through A10 " << endl;
cout << "Enter your answer: ";
cin >> ans5m1;
if (ans5m1 == 'b' || ans5m1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) Which of the following is an example of an operating system?" << endl;
cout << "a. Linux" << endl;
cout << "b. Microsoft Word" << endl;
cout << "c. C++" << endl;
cout << "d. Excel" << endl;
cout << "Enter your answer: ";
cin >> ans6m1;
if (ans6m1 == 'a' || ans6m1 == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) What was the name of the first widely used personal computer introduced in 1981?" << endl;
cout << "a. IBM PC" << endl;
cout << "b. Altair 8800" << endl;
cout << "c. Commodore 64" << endl;
cout << "d. Macintosh" << endl;
cout << "Enter your answer: ";
cin >> ans7m1;
if (ans7m1 == 'a' || ans7m1 == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) What does Ctrl + S do in most Microsoft Office programs?" << endl;
cout << "a. Opens a new document" << endl;
cout << "b. Deletes the current document" << endl;
cout << "c. Copies the document to the clipboard" << endl;
cout << "d. Saves the current document" << endl;
cout << "Enter your answer: ";
cin >> ans8m1;
if (ans8m1 == 'd' || ans8m1 == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) In Excel, what type of chart is best for comparing parts of a whole?" << endl;
cout << "a. Line Chart" << endl;
cout << "b. Bar Chartr" << endl;
cout << "c. Pie Chart" << endl;
cout << "d. Scatter Plot" << endl;
cout << "Enter your answer: ";
cin >> ans9m1;
if (ans9m1 == 'c' || ans9m1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.) Which of the following best describes an operating system?" << endl;
cout << "a. A database management tool"<< endl;
cout << "b. A program used to browse the internet" << endl;
cout << "c. A document editor" << endl;
cout << "d. A set of programs that manage computer hardware and software resources" << endl;
cout << "Enter your answer: ";
cin >> ans10m1;
if (ans10m1 == 'd' || ans10m1 == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
cout << "Quiz Over! Your score is: " << x << "/10." << endl;
}
}
else if (subject == 2) {
cout << "\nPick a topic:" << endl;
cout << "1. Biology" << endl;
cout << "2. Chemistry" << endl;
cout << "3. Physics" << endl;
cout << "Enter your choice: ";
cin >> topic2;
if (topic2 == 1){
cout << "\nScience (Biology) Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) What is the basic unit of life in all living organisms?" << endl;
cout << "a. Atom" << endl;
cout << "b. Tissue" << endl;
cout << "c. Cell" << endl;
cout << "d. Molecule" << endl;
cout << "Enter your answer: ";
cin >> ans1h1;
if (ans1h1 == 'c' || ans1h1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) Which organelle is known as the powerhouse of the cell?" << endl;
cout << "a. Nucleus" << endl;
cout << "b. Ribosome" << endl;
cout << "c. Golgi apparatus" << endl;
cout << "d. Mitochondria" << endl;
cout << "Enter your answer: ";
cin >> ans2h1;
if (ans2h1 == 'd' || ans2h1 == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) What is the process by which plants make their food using sunlight?" << endl;
cout << "a. Respiration" << endl;
cout << "b. Fermentation" << endl;
cout << "c. Photosynthesis" << endl;
cout << "d. Digestion" << endl;
cout << "Enter your answer: ";
cin >> ans3h1;
if (ans3h1 == 'c' || ans3h1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) Which of the following is a characteristic of prokaryotic cells?" << endl;
cout << "a. They have a nucleus." << endl;
cout << "b. They lack membrane-bound organelles." << endl;
cout << "c. They are always multicellular." << endl;
cout << "d. They contain chloroplasts." << endl;
cout << "Enter your answer: ";
cin >> ans4h1;
if (ans4h1 == 'b' || ans4h1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) What is the primary function of red blood cells in the human body?" << endl;
cout << "a. To carry oxygen" << endl;
cout << "b. To fight infections" << endl;
cout << "c. To transport hormones" << endl;
cout << "d. To digest food" << endl;
cout << "Enter your answer: ";
cin >> ans5h1;
if (ans5h1 == 'a' || ans5h1 == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) Which type of macromolecule is responsible for storing genetic information?" << endl;
cout << "a. Protein" << endl;
cout << "b. Lipid" << endl;
cout << "c. Nucleic acid" << endl;
cout << "d. Carbohydrate" << endl;
cout << "Enter your answer: ";
cin >> ans6h1;
if (ans6h1 == 'c' || ans6h1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) What is the term for animals that maintain a constant body temperature?" << endl;
cout << "a. Ectothermic" << endl;
cout << "b. Endothermic" << endl;
cout << "c. Heterotrophic" << endl;
cout << "d. Autotrophic" << endl;
cout << "Enter your answer: ";
cin >> ans7h1;
if (ans7h1 == 'b' || ans7h1 == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) In the food chain, which organisms are typically at the top of the pyramid?" << endl;
cout << "a. Primary consumers" << endl;
cout << "b. Producers" << endl;
cout << "c. Apex predators" << endl;
cout << "d. Decomposers" << endl;
cout << "Enter your answer: ";
cin >> ans8h1;
if (ans8h1 == 'c' || ans8h1 == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) What is the largest organ in the human body?" << endl;
cout << "a. Skin" << endl;
cout << "b. Heart" << endl;
cout << "c. Liver" << endl;
cout << "d. Brain" << endl;
cout << "Enter your answer: ";
cin >> ans9h1;
if (ans9h1 == 'a' || ans9h1 == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.) Which biome is characterized by very low temperatures and permafrost?" << endl;
cout << "a. Tundra"<< endl;
cout << "b. Desert" << endl;
cout << "c. Tropical rainforest" << endl;
cout << "d. Savanna" << endl;
cout << "Enter your answer: ";
cin >> ans10h1;
if (ans10h1 == 'a' || ans10h1 == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
cout << "Quiz Over! Your score is: " << x << "/10." << endl;
}
else if (topic2 == 2){
cout << "\nScience (Chemistry) Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) What is the smallest unit of an element that retains its properties?" << endl;
cout << "a. Molecule" << endl;
cout << "b. Electron" << endl;
cout << "c. Proton" << endl;
cout << "d. Atom" << endl;
cout << "Enter your answer: ";
cin >> ans1sC;
if (ans1sC == 'd' || ans1sC == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) Which subatomic particle has a negative charge?" << endl;
cout << "a. Proton" << endl;
cout << "b. Neutron" << endl;
cout << "c. Electron" << endl;
cout << "d. Nucleus" << endl;
cout << "Enter your answer: ";
cin >> ans2sC;
if (ans2sC == 'c' || ans2sC == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) What is the chemical symbol for gold?" << endl;
cout << "a. Ag" << endl;
cout << "b. Au" << endl;
cout << "c. Gd" << endl;
cout << "d. Ga" << endl;
cout << "Enter your answer: ";
cin >> ans3sC;
if (ans3sC == 'b' || ans3sC == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) What is the pH of a neutral solution, such as pure water?" << endl;
cout << "a. 10" << endl;
cout << "b. 14" << endl;
cout << "c. 0" << endl;
cout << "d. 7" << endl;
cout << "Enter your answer: ";
cin >> ans4sC;
if (ans4sC == 'd' || ans4sC == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) What type of bond is formed when electrons are shared between atoms?" << endl;
cout << "a. Covalent bond" << endl;
cout << "b. Ionic bond" << endl;
cout << "c. Hydrogen bond" << endl;
cout << "d. Metallic bond" << endl;
cout << "Enter your answer: ";
cin >> ans5sC;
if (ans5sC == 'a' || ans5sC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) Which gas is most abundant in Earth atmosphere?" << endl;
cout << "a. Oxygen" << endl;
cout << "b. Carbon dioxide" << endl;
cout << "c. Hydrogen" << endl;
cout << "d. Nitrogen" << endl;
cout << "Enter your answer: ";
cin >> ans6sC;
if (ans6sC == 'd' || ans6sC == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) What is the term for the amount of matter in an object?" << endl;
cout << "a. Density" << endl;
cout << "b. Mass" << endl;
cout << "c. Weight" << endl;
cout << "d. Volume" << endl;
cout << "Enter your answer: ";
cin >> ans7sC;
if (ans7sC == 'b' || ans7sC == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) What is the name of the chemical process by which a solid changes directly into a gas?" << endl;
cout << "a. Evaporation" << endl;
cout << "b. Melting" << endl;
cout << "c. Condensation" << endl;
cout << "d. Sublimation" << endl;
cout << "Enter your answer: ";
cin >> ans8sC;
if (ans8sC == 'd' || ans8sC == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) What is the main component of table salt?" << endl;
cout << "a. Sodium chloride" << endl;
cout << "b. Potassium iodide" << endl;
cout << "c. Calcium carbonate" << endl;
cout << "d. Magnesium sulfate" << endl;
cout << "Enter your answer: ";
cin >> ans9sC;
if (ans9sC == 'a' || ans9sC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.)Which of the following is a noble gas?" << endl;
cout << "a. Helium"<< endl;
cout << "b. Oxygen" << endl;
cout << "c. Nitrogen" << endl;
cout << "d. Hydrogen" << endl;
cout << "Enter your answer: ";
cin >> ans10sC;
if (ans10sC == 'a' || ans10sC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
}
else if (topic2 == 3){
cout << "\nScience (Physics) Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) What is the unit of force in the SI system?" << endl;
cout << "a. Joule" << endl;
cout << "b. Newton" << endl;
cout << "c. Pascal" << endl;
cout << "d. Watt" << endl;
cout << "Enter your answer: ";
cin >> ans1sP;
if (ans1sP == 'b' || ans1sP == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) Which of the following is an example of potential energy?" << endl;
cout << "a. A moving car" << endl;
cout << "b. Flowing water" << endl;
cout << "c. A spinning wheel" << endl;
cout << "d. A stretched rubber band" << endl;
cout << "Enter your answer: ";
cin >> ans2sP;
if (ans2sP == 'd' || ans2sP == 'D') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) What is the speed of light in a vacuum?" << endl;
cout << "a. 300,000 km/s" << endl;
cout << "b. 150,000 km/s" << endl;
cout << "c. 300,000 m/s" << endl;
cout << "d. 150,000 m/s" << endl;
cout << "Enter your answer: ";
cin >> ans3sP;
if (ans3sP == 'a' || ans3sP == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) What does Newtons First Law of Motion state?" << endl;
cout << "a. Force equals mass times acceleration." << endl;
cout << "b. For every action, there is an equal and opposite reaction." << endl;
cout << "c. An object in motion stays in motion unless acted on by an external force." << endl;
cout << "d. The acceleration of an object depends on its mass and the force applied." << endl;
cout << "Enter your answer: ";
cin >> ans4sP;
if (ans4sP == 'c' || ans4sP == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) What type of wave is sound?" << endl;
cout << "a. Electromagnetic wave" << endl;
cout << "b. Longitudinal wave" << endl;
cout << "c. Transverse wave" << endl;
cout << "d. Standing wave" << endl;
cout << "Enter your answer: ";
cin >> ans5sP;
if (ans5sP == 'b' || ans5sP == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) What happens to the kinetic energy of an object when its speed is doubled?" << endl;
cout << "a. It remains the same." << endl;
cout << "b. It doubles." << endl;
cout << "c. It quadruples." << endl;
cout << "d. It is halved." << endl;
cout << "Enter your answer: ";
cin >> ans6sP;
if (ans6sP == 'c' || ans6sP == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) Which of the following is NOT a fundamental force of nature?" << endl;
cout << "a. Gravity" << endl;
cout << "b. Electromagnetic force" << endl;
cout << "c. Frictional force" << endl;
cout << "d. Nuclear force" << endl;
cout << "Enter your answer: ";
cin >> ans7sP;
if (ans7sP == 'c' || ans7sP == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) What does the term work mean in physics?" << endl;
cout << "a. The transfer of energy through motion" << endl;
cout << "b. The force exerted on an object without motion" << endl;
cout << "c. The effort applied to a task" << endl;
cout << "d. The energy stored in a system" << endl;
cout << "Enter your answer: ";
cin >> ans8sP;
if (ans8sP == 'a' || ans8sP == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) What is the term for the bending of light as it passes from one medium to another?" << endl;
cout << "a. Reflection" << endl;
cout << "b. Refraction" << endl;
cout << "c. Diffraction" << endl;
cout << "d. Dispersion" << endl;
cout << "Enter your answer: ";
cin >> ans9sP;
if (ans9sP == 'b' || ans9sP == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.) What is the property of an object that resists changes in its motion?" << endl;
cout << "a. Velocity"<< endl;
cout << "b. Inertia" << endl;
cout << "c. Momentum" << endl;
cout << "d. Acceleration" << endl;
cout << "Enter your answer: ";
cin >> ans10sP;
if (ans10sP == 'b' || ans10sP == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
}
}
else if (subject == 3) {
cout << "\nPick a topic:" << endl;
cout << "1. Algebra" << endl;
cout << "2. Calculus" << endl;
cout << "3. Statistic" << endl;
cout << "Enter your choice: ";
cin >> topic3;
if (topic3 == 1){
cout << "\nMathematics (Algebra) Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) What is the value of x in the equation 2x + 3 = 7?" << endl;
cout << "a. 1" << endl;
cout << "b. 2" << endl;
cout << "c. 3" << endl;
cout << "d. 4" << endl;
cout << "Enter your answer: ";
cin >> ans1mA;
if (ans1mA == 'b' || ans1mA == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) What is the slope of the line represented by the equation y = 3x + 5 ?" << endl;
cout << "a. 3" << endl;
cout << "b. 5" << endl;
cout << "c. -3" << endl;
cout << "d. -5" << endl;
cout << "Enter your answer: ";
cin >> ans2mA;
if (ans2mA == 'a' || ans2mA == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) Simplify: 3(2x + 4)." << endl;
cout << "a. 2x + 7" << endl;
cout << "b. 6x + 12" << endl;
cout << "c. 6x + 4" << endl;
cout << "d. 3x + 12" << endl;
cout << "Enter your answer: ";
cin >> ans3mA;
if (ans3mA == 'b' || ans3mA == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) If x^2 = 16 , what are the possible values of x ?" << endl;
cout << "a. 4 only" << endl;
cout << "b. -4 only" << endl;
cout << "c. 4 and -4" << endl;
cout << "d. 8 and -8" << endl;
cout << "Enter your answer: ";
cin >> ans4mA;
if (ans4mA == 'c' || ans4mA == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) Solve for y : 3y - 9 = 0." << endl;
cout << "a. 3" << endl;
cout << "b. -3" << endl;
cout << "c. 9" << endl;
cout << "d. -9" << endl;
cout << "Enter your answer: ";
cin >> ans5mA;
if (ans5mA == 'a' || ans5mA == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) What is the value of x in the equation 5x = 25 ?" << endl;
cout << "a. 10" << endl;
cout << "b. 25" << endl;
cout << "c. 5" << endl;
cout << "d. 1" << endl;
cout << "Enter your answer: ";
cin >> ans6mA;
if (ans6mA == 'c' || ans6mA == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) Which of the following is a quadratic equation?" << endl;
cout << "a. y = 3x + -5" << endl;
cout << "b. y = 3x + 5" << endl;
cout << "c. y = 5x" << endl;
cout << "d. y = x + 7" << endl;
cout << "Enter your answer: ";
cin >> ans7mA;
if (ans7mA == 'b' || ans7mA == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) What is the solution to the inequality 2x + 4 > 10 ?" << endl;
cout << "a. x > 3" << endl;
cout << "b. x < 3" << endl;
cout << "c. x > 6" << endl;
cout << "d. x < 6" << endl;
cout << "Enter your answer: ";
cin >> ans8mA;
if (ans8mA == 'a' || ans8mA == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) What is the product of (x + 3)(x - 3) ?" << endl;
cout << "a. x^2 - 6x + 9" << endl;
cout << "b. x^2 + 6x + 9" << endl;
cout << "c. x^2 - 9" << endl;
cout << "d. x^2 + 9" << endl;
cout << "Enter your answer: ";
cin >> ans9mA;
if (ans9mA == 'c' || ans9mA == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.) If y = 2x - 1 , what is y when x = 3 ?" << endl;
cout << "a. 5"<< endl;
cout << "b. 6" << endl;
cout << "c. 7" << endl;
cout << "d. 8" << endl;
cout << "Enter your answer: ";
cin >> ans10mA;
if (ans10mA == 'a' || ans10mA == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
cout << "Quiz Over! Your score is: " << x << "/10." << endl;
}
else if (topic3 == 2){
cout << "\nMathematics (Calculus) Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) What is the derivative of f(x) = 3x^2 + 2x - 5 ?" << endl;
cout << "a. 6x + 2" << endl;
cout << "b. 6x - 2" << endl;
cout << "c. 3x + 2" << endl;
cout << "d. 6x + 5" << endl;
cout << "Enter your answer: ";
cin >> ans1mC;
if (ans1mC == 'a' || ans1mC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) What does the integral of a function represent in terms of geometry?" << endl;
cout << "a. The rate of change of the function" << endl;
cout << "b. The slope of the function" << endl;
cout << "c. The area under the curve of the function" << endl;
cout << "d. The maximum value of the function" << endl;
cout << "Enter your answer: ";
cin >> ans2mC;
if (ans2mC == 'c' || ans2mC == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) What is the limit of 1/x as x to infite?" << endl;
cout << "a. 0" << endl;
cout << "b. 1" << endl;
cout << "c. Infinity" << endl;
cout << "d. Undefined" << endl;
cout << "Enter your answer: ";
cin >> ans3mC;
if (ans3mC == 'a' || ans3mC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) What is the derivative of f(x) = sin(x) ?" << endl;
cout << "a. cos(x)" << endl;
cout << "b. - cos(x)" << endl;
cout << "c. sin(x)" << endl;
cout << "d. - sin(x)" << endl;
cout << "Enter your answer: ";
cin >> ans4mC;
if (ans4mC == 'a' || ans4mC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) What is the integral of int x^2 , dx ?" << endl;
cout << "a. frac{x^3}{3} + C" << endl;
cout << "b. x^3 + C" << endl;
cout << "c. frac{x^3}{2} + C" << endl;
cout << "d. x^2 + C" << endl;
cout << "Enter your answer: ";
cin >> ans5mC;
if (ans5mC == 'a' || ans5mC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) The Fundamental Theorem of Calculus connects which two operations?" << endl;
cout << "a. Addition and subtraction" << endl;
cout << "b. Differentiation and integration" << endl;
cout << "c. Multiplication and division" << endl;
cout << "d. Limits and derivatives" << endl;
cout << "Enter your answer: ";
cin >> ans6mC;
if (ans6mC == 'b' || ans6mC == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) What is the derivative of f(x) = e^x ?" << endl;
cout << "a. e^x" << endl;
cout << "b. x e^x" << endl;
cout << "c. ln(x)" << endl;
cout << "d. 1" << endl;
cout << "Enter your answer: ";
cin >> ans7mC;
if (ans7mC == 'a' || ans7mC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) Which of the following is an application of the derivative?" << endl;
cout << "a. Finding the area under a curve" << endl;
cout << "b. Solving for the roots of a function" << endl;
cout << "c. Determining the slope of a curve at a point" << endl;
cout << "d. Integrating a function over an interval" << endl;
cout << "Enter your answer: ";
cin >> ans8mC;
if (ans8mC == 'c' || ans8mC == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) What is the integral of int cos(x) , dx ?" << endl;
cout << "a. sin(x) + C" << endl;
cout << "b. -sin(x) + C" << endl;
cout << "c. cos(x)" << endl;
cout << "d. -cos(x)" << endl;
cout << "Enter your answer: ";
cin >> ans9mC;
if (ans9mC == 'a' || ans9mC == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.) What does it mean for a function to be continuous at a point x = a ?" << endl;
cout << "a. The derivative exists at x = a"<< endl;
cout << "b. The function value is equal to the limit as x to a" << endl;
cout << "c. The second derivative exists at x = a" << endl;
cout << "d. The function has no local maxima or minima at x = a" << endl;
cout << "Enter your answer: ";
cin >> ans10mC;
if (ans10mC == 'b' || ans10mC == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
cout << "Quiz Over! Your score is: " << x << "/10." << endl;
}
else if (topic3 == 3){
cout << "\nMathematics (Statistic) Quiz" << endl;
for (i = 1; i < 11 && lives > 0; i++) {
if (i == 1) {
cout << "1.) What is the mean of the data set 2, 4, 6, 8, 10 ?" << endl;
cout << "a. 6" << endl;
cout << "b. 5" << endl;
cout << "c. 4" << endl;
cout << "d. 7" << endl;
cout << "Enter your answer: ";
cin >> ans1mS;
if (ans1mS == 'a' || ans1mS == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
} else if (i == 2) {
cout << "2.) What does the median represent in a data set?" << endl;
cout << "a. The most frequent value" << endl;
cout << "b. The average of all values" << endl;
cout << "c. The middle value when the data set is ordered" << endl;
cout << "d. The range between the highest and lowest values" << endl;
cout << "Enter your answer: ";
cin >> ans2mS;
if (ans2mS == 'c' || ans2mS == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 3) {
cout << "3.) What is the mode of the data set 3, 7, 3, 10, 3, 9 ?" << endl;
cout << "a. 7" << endl;
cout << "b. 9" << endl;
cout << "c. 3" << endl;
cout << "d. 10" << endl;
cout << "Enter your answer: ";
cin >> ans3mS;
if (ans3mS == 'c' || ans3mS == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 4) {
cout << "4.) Which of the following measures of central tendency is most affected by extreme values (outliers)?" << endl;
cout << "a. Mean" << endl;
cout << "b. Median" << endl;
cout << "c. Mode" << endl;
cout << "d. Range" << endl;
cout << "Enter your answer: ";
cin >> ans4mS;
if (ans4mS == 'a' || ans4mS == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 5) {
cout << "5.) What is the standard deviation a measure of?" << endl;
cout << "a. The middle value in a data set" << endl;
cout << "b. The spread or dispersion of data points from the mean" << endl;
cout << "c. The average of the data set" << endl;
cout << "d. The difference between the highest and lowest values" << endl;
cout << "Enter your answer: ";
cin >> ans5mS;
if (ans5mS == 'b' || ans5mS == 'B') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 6) {
cout << "6.) In probability, what is the sum of the probabilities of all possible outcomes in a sample space?" << endl;
cout << "a. 1" << endl;
cout << "b. 0" << endl;
cout << "c. 0.5" << endl;
cout << "d. 100" << endl;
cout << "Enter your answer: ";
cin >> ans6mS;
if (ans6mS == 'a' || ans6mS == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 7) {
cout << "7.) What type of data is represented by categories with no inherent order, such as colors or types of fruit?" << endl;
cout << "a. Nominal" << endl;
cout << "b. Ordinal" << endl;
cout << "c. Interval" << endl;
cout << "d. Ratio" << endl;
cout << "Enter your answer: ";
cin >> ans7mS;
if (ans7mS == 'a' || ans7mS == 'A') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 8) {
cout << "8.) Which of the following is a characteristic of a normal distribution?" << endl;
cout << "a. It is skewed to the right." << endl;
cout << "b. It has two peaks." << endl;
cout << "c. It is symmetric and bell-shaped." << endl;
cout << "d. It has a positive skew." << endl;
cout << "Enter your answer: ";
cin >> ans8mS;
if (ans8mS == 'c' || ans8mS == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 9) {
cout << "9.) What does a correlation coefficient of -1 indicate?" << endl;
cout << "a. No correlation" << endl;
cout << "b. A perfect positive correlation" << endl;
cout << "c. A perfect negative correlation" << endl;
cout << "d. A weak correlation" << endl;
cout << "Enter your answer: ";
cin >> ans9mS;
if (ans9mS == 'c' || ans9mS == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
else if (i == 10) {
cout << "10.) What is the probability of flipping a coin and getting heads?" << endl;
cout << "a. 0"<< endl;
cout << "b. 0.25" << endl;
cout << "c. 0.5" << endl;
cout << "d. 1" << endl;
cout << "Enter your answer: ";
cin >> ans10mS;
if (ans10mS == 'c' || ans10mS == 'C') {
cout << "Correct!" << endl << endl;
x++;
} else {
lives--;
cout << "Incorrect! Lives remaining: " << lives << endl << endl;
}
}
}
cout << "Quiz Over! Your score is: " << x << "/10." << endl;
}
}
else {
cout << "\nInvalid Subject or Topic. Returning to main menu." << endl;
break;
}
if (lives == 0) {
cout << "\nYou have lost all lives. Do you want to try again? (y/n): ";
cin >> retry;
} else {
retry = 'n';
}
} while (retry == 'y' || retry == 'Y');
} else if (choice == 3) {
cout <<"\nThank you for playing!"<<endl;
} else {
cout << "\nInvalid choice. Please try again."<<endl;
}
}while (choice != 3);
return 0;
}
//HAPPY 1500 LINES!!!!!
/*ANSWER KEYS:
TECHNOLOGY:
IT111
1. A
2. B
3. B
4. B
5. B
6. D
7. C
8. A
9. C
10. B
IT110
1. C
2. B
3. D
4. C
5. B
6. A
7. A
8. D
9. C
10. D
SCIENCE:
Biology
1. C
2. D
3. C
4. B
5. A
6. C
7. B
8. C
9. A
10. A
Chemistry
1. D
2. C
3. B
4. D
5. A
6. D
7. B
8. D
9. A
10. A
Physics
1. B
2. D
3. A
4. C
5. B
6. C
7. C
8. A
9. B
10. B
MATHEMATICS:
Algebra
1. B
2. A
3. B
4. C
5. A
6. C
7. B
8. A
9. C
10. A
Calculus
1. A
2. C
3. A
4. A
5. A
6. B
7. A
8. C
9. A
10. B
Statistics
1. A
2. C
3. C
4. B
5. B
6. A
7. A
8. C
9. C
10. C*/ |
import { Component, OnInit } from '@angular/core';
import { PhotosService } from "../services/photos.service";
import { Photo } from '../services/photo';
import { Breakpoints, BreakpointObserver, BreakpointState } from '@angular/cdk/layout';
import { SpinnerService } from '../services/spinner.service';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith, tap } from 'rxjs/operators';
import { PageEvent } from '@angular/material/paginator';
import { MatDialog } from '@angular/material/dialog';
import { PhotoModalComponent } from '../photo-modal/photo-modal.component';
// tile grid to display photos
export interface Tile {
cols: number;
rows: number;
}
@Component({
selector: 'app-photo-gallery',
templateUrl: './photo-gallery.component.html',
styleUrls: ['./photo-gallery.component.css']
})
export class PhotoGalleryComponent implements OnInit {
// form control for author search
authorFormControl = new FormControl();
// the filtered authors
filteredAuthors: Observable<string[]>;
// spinner to indicate awaiting on response
showSpinner: boolean;
// selected author to display. Default to Alejandro Escamilla
selectedAuthor: string = "Alejandro Escamilla";
// list of all photos retrieved from API
photos: Photo[] = [];
// list of current photos to display
currentPhotos: Photo[] = [];
// list of all authors
authors: string[] = [];
// list of all current author photos
currentAuthorPhotos: Photo[] = [];
// sizes for tiles
sm: number = 1;
md: number = 2;
lg: number = 6;
// how many photos to display per page with the index
pageSize: number = 10;
pageIndex: number = 0;
// flag to display of no selected author
isEmptyFlag?: boolean;
// the styling objecto of the tiles to define the 10 photos to display
tiles: Tile[] = [
{ cols: this.md, rows: this.md },
{ cols: this.sm, rows: this.sm },
{ cols: this.sm, rows: this.sm },
{ cols: this.md, rows: this.sm },
{ cols: this.md, rows: this.md },
{ cols: this.sm, rows: this.sm },
{ cols: this.sm, rows: this.sm },
{ cols: this.md, rows: this.sm },
{ cols: this.sm, rows: this.sm },
{ cols: this.sm, rows: this.sm }];
constructor(
private photosService: PhotosService,
private breakpointObserver: BreakpointObserver,
public spinnerService: SpinnerService,
public dialog: MatDialog) { }
ngOnInit(): void {
// get list of all photos
this.getPhotos();
// change the state of the tiles when screen size changes
this.breakpointObserver.observe([Breakpoints.Small, Breakpoints.HandsetPortrait])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.tiles = [
{ cols: this.lg, rows: this.md },
{ cols: this.lg, rows: this.sm },
{ cols: this.lg, rows: this.sm },
{ cols: this.lg, rows: this.sm },
{ cols: this.lg, rows: this.md },
{ cols: this.lg, rows: this.sm },
{ cols: this.lg, rows: this.sm },
{ cols: this.lg, rows: this.sm },
{ cols: this.lg, rows: this.sm },
{ cols: this.lg, rows: this.sm }];
} else {
this.tiles = [
{ cols: this.md, rows: this.md },
{ cols: this.sm, rows: this.sm },
{ cols: this.sm, rows: this.sm },
{ cols: this.md, rows: this.sm },
{ cols: this.md, rows: this.md },
{ cols: this.sm, rows: this.sm },
{ cols: this.sm, rows: this.sm },
{ cols: this.md, rows: this.sm },
{ cols: this.sm, rows: this.sm },
{ cols: this.sm, rows: this.sm }];
}
});
// the filtered authors for the autocomplete form
this.filteredAuthors = this.authorFormControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value)),
);
}
/**
* open the selected photo modal.
*
* @param {Photo} thePhoto the photo to send to the modal
*/
openModal(thePhoto: Photo): void {
const dialogRef = this.dialog.open(PhotoModalComponent, {
data: { currentAuthorPhotos: this.currentAuthorPhotos, currentPhoto: thePhoto },
});
dialogRef.afterClosed().subscribe(result => {
// console.log('The dialog was closed');
});
}
/**
* get list of all photos from photoService.
*
*/
getPhotos(): void {
this.photosService.getPhotos().subscribe(
photoResponse => {
this.photos = photoResponse;
this.authors = this.getAuthors(this.photos);
// filter the user after setting current photos
this.authorFormControl.setValue(this.selectedAuthor)
}
);
}
/**
* get list of all unique authors.
*
* @param {Photo[]} photos the list of all photos
*
*/
getAuthors(photos: Photo[]): string[] {
const unique = [...new Set(photos.map(item => item.author))];
return unique;
}
/**
* filter the input from list of all authors.
*
* @param {string} value the value/author of the string
*
*/
private _filter(value: string): string[] {
if (value == "") {
this.isEmptyFlag = false;
} else {
// Filter the list of photos for the value/author
this.isEmptyFlag = true;
this.selectedAuthor = value;
this.currentAuthorPhotos = this.photos.filter(photo => photo.author == value);
this.currentPhotos = this.currentAuthorPhotos.slice(0, 10);
}
// search the list of arrays to see if the value matches and authors name
const filterValue = value.toLowerCase();
return this.authors.filter(option => option.toLowerCase().includes(filterValue));
}
/**
* handle page events when paginating through photos.
*
* @param {PageEvent} event the event triggered when clicking next page
*
*/
handlePageEvent(event: PageEvent) {
this.pageSize = event.pageSize;
this.pageIndex = event.pageIndex;
this.currentPhotos = this.currentAuthorPhotos.slice((this.pageIndex) * this.pageSize, (this.pageIndex + 1) * this.pageSize);
}
} |
# Reference : https://www.youtube.com/watch?v=ZBKpAp_6TGI
# Orginal Code : https://github.com/hkproj/pytorch-stable-diffusion/blob/main/sd/pipeline.py
import torch
import numpy as np
from tqdm import tqdm
from ddpm import DDPMSampler
WIDTH = 512
HEIGHT = 512
LATENTS_WIDTH = WIDTH // 8
LATENTS_HEIGHT = HEIGHT // 8
def generate(prompt: str, uncond_prompt: str, input_image=None, strength=0.0,
do_cfg=True, cfg_scale=7.5, sampler_name="ddpm", n_inference_steps=50,
models={}, seed=None, device=None, idle_device=None, tokenizer=None):
with torch.no_grad():
if not (0 < strength <= 1):
raise ValueError("strength must be in [0, 1]")
if idle_device:
to_idle = lambda x: x.to(idle_device)
else:
to_idle = lambda x: x
generator = torch.Generator(device=device)
if seed is None:
generate.seed()
else:
generator.manual_seed(seed)
clip = models["clip"]
clip.to(device)
if do_cfg:
# Convert the prompt into tokens using the tokenizer
cond_tokens = tokenizer.batch_encode_plus([prompt], padding="max_length", max_length=77).input_ids
# (Batch_Size, Seq_Len)
cond_tokens = torch.tensor(cond_tokens, dtype=torch.long, device=device)
# (Batch_Size, Seq_Len) -> (Batch_Size, Seq_Len, Dim)
cond_context = clip(cond_tokens)
uncond_tokens = tokenizer.batch_encode_plus([uncond_prompt], padding="max_length", max_length=77).input_ids
uncond_tokens = torch.tensor(uncond_tokens, dtype=torch.long, device=device)
# (Batch_Size, Seq_Len) -> (Batch_Size, Seq_Len, Dim)
uncond_context =clip(uncond_tokens)
# (2, Seq_Len, Dim) -> (2, 77, 768)
context = torch.cat([cond_context, uncond_context])
else:
# Convert it into a list of tokens
tokens = tokenizer.batch_encode_plus([prompt], padding="max_length", max_length=77).input_ids
tokens = torch.tensor(tokens, dtype=torch.long, device=device)
# (1, 77, 768)
context = clip(tokens)
to_idle(clip)
if sampler_name == "ddpm":
sampler = DDPMSampler(generator)
sampler.set_inference_timesteps(n_inference_steps)
else:
raise ValueError(f"Unknown sampler {sampler_name}")
latents_shape = (1, 4, LATENTS_HEIGHT, LATENTS_WIDTH)
if input_image:
encoder = models["encoder"]
encoder.to(device)
input_image_tensor = input_image.resize((WIDTH, HEIGHT))
input_image_tensor = np.array(input_image_tensor)
# (Height, Width, Channel)
input_image_tensor = torch.tensor(input_image_tensor, dtype=torch.float32, device=device)
# rescale (0 ~ 255) -> (-1 ~ 1)
input_image_tensor = rescale(input_image_tensor, (0, 255), (-1, 1))
# (Height, Width, Channel) -> (Batch_Size, Height, Width, Channel)
input_image_tensor = input_image_tensor.unsqueeze(0)
# (Batch_Size, Height, Width, Channel) -> (Batch_Size, Channel, Height, Width)
input_image_tensor = input_image_tensor.permute(0, 3, 1, 2)
encoder_noise = torch.randn(latents_shape, generator=generator, device=device)
# run the image through the encoder of the VAE
latents = encoder(input_image_tensor, encoder_noise)
sampler.set_strength(strength=strength)
latents = sampler.add_noise(latents, sampler.timestep[0])
to_idle(encoder)
else:
# If we are doing text-to-image, start with random noise N(0, I)
latents = torch.randn(latents_shape, generator=generator, device=device)
diffusion = models["diffusion"]
diffusion.to(device)
timesteps = tqdm(sampler.timesteps)
for i , timestep in enumerate(timesteps):
# (1, 320)
time_embedding = get_time_embedding(timestep).to(device)
# (Batch_Size, 4, Latents_Height, Latents_Width)
model_input = latents
if do_cfg:
# (Batch_Size, 4, Latent_Height, Latent_Width) -> (2 * Batch_Size, 4, Latent_Height, Latent_Width)
model_input = model_input.repeat(2, 1, 1, 1)
# model_output is the prediected noise by the UNET
model_output = diffusion(model_input, context, time_embedding)
if do_cfg:
output_cond, output_uncond = model_output.chunk(2)
model_output = cfg_scale * (output_cond - output_uncond) + output_uncond
# Remove noise predicted by the UNET
latents = sampler.step(timestep, latents, model_output)
to_idle(diffusion)
decoder = models['decoder']
decoder.to(device)
images = decoder(latents)
to_idle(decoder)
images = rescale(images, (-1, 1), (0, 255), clamp=True)
# (Batch_Size, Channel, Height, Width) -> (Batch_Size, Height, Width, Channel)
images = images.permute(0, 2, 3, 1)
images = images.to("cpu", torch.uint8).numpy()
return images[0]
def rescale(x, old_range, new_range, clamp=False):
old_min, old_max = old_range
new_min, new_max = new_range
x -= old_min
x *= (new_max - new_min) / (old_max - old_min)
x + new_min
if clamp:
x = x.clamp(new_min, new_max)
return x
def get_time_embedding(timestep):
# (160, )
freqs = torch.pow(10000, -torch.arange(start=0, end=160, dtype=torch.float32) / 160)
# (1, 160)
x = torch.tensor([timestep], dtype=torch.float32)[:, None] * freqs[None]
# (1, 320)
return torch.cat([torch.cos(x), torch.sin(x)], dim=-1) |
<script lang="ts">
import { onMount } from 'svelte';
let time = new Date();
const parse_day = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
const parse_month = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
let parse_single_digit = (digit: number) => {
if(digit < 10) {
return "0" + digit;
}
return digit;
}
$: hours = parse_single_digit(time.getHours());
$: minutes = parse_single_digit(time.getMinutes());
$: seconds = parse_single_digit(time.getSeconds());
$: day = parse_day[time.getDay()];
$: month = parse_month[time.getMonth()];
$: date = time.getDate();
$: year = time.getFullYear();
onMount(() => {
const tick = setInterval(() => {
time = new Date();
}, 1000);
return () => {
clearInterval(tick);
};
});
</script>
<div>
<p class="font-bold">{day}, {month} {date} {year}</p>
</div> |
interface Window {
XLSX: any;
}
interface XploreParam {
text?: any,
icon?: string,
classes?: string[],
onclick?: Function;
}
interface XploreParamMenu extends XploreParam {
shortcut?: string;
onclick?: Function;
separator?: boolean;
}
interface XploreParamList extends XploreParam {
buttons?: Xplore[];
}
interface XploreBindParam {
name: string;
object: Object;
}
interface XploreParamCheckbox extends XploreParam {
value?: boolean;
bind?: XploreBindParam;
}
interface XploreParamForm extends XploreParam {
width?: number;
height?: number;
showheader?: boolean;
showfooter?: boolean;
}
interface XploreParamTree extends XploreParam {
data?: any;
}
interface XMenu {
action: Function;
menu?: Xplore.Menu;
}
interface Dictionary<T> {
[Key: string]: T;
}
interface XBind {
object?: Object;
name?: string;
}
interface XTabItem {
button: Xplore;
container: Xplore;
onclick?: Function;
}
interface XTableParam {
columns: XTableParamColumn[];
data: Object[];
showheader?: boolean;
showfooter?: boolean;
}
interface XTableParamColumn {
name: string;
text: string;
readonly?: boolean;
sort?: boolean;
filter?: boolean;
}
interface XCalendarItem {
text: string;
image?: string;
details?: string;
}
enum XORIENTATION {
HORIZONTAL = 1,
VERTICAL = 2
}
enum XPOSITION {
NONE = 0,
TOP = 1,
BOTTOM = 2,
LEFT = 3,
RIGHT = 4
}
enum XINPUTTYPE {
BUTTON = "button",
CHECKBOX = "checkbox",
COLOR = "color",
DATE = "date",
DATETIME = "datetime-local",
EMAIL = "email",
FILE = "file",
HIDDEN = "hidden",
IMAGE = "image",
MONTH = "month",
NUMBER = "number",
PASSWORD = "password",
RADIO = "radio",
RANGE = "range",
RESET = "reset",
SEARCH = "search",
SUBMIT = "submit",
TELEPHONE = "tel",
TEXT = "text",
TEXTAREA = "textarea",
TIME = "time",
URL = "url",
WEEK = "week"
}
enum XMENUTYPE {
DEFAULT = "menu-default",
MINIRIBBON = "menu-mini-ribbon",
RIBBON = "menu-ribbon"
}
class Xplore {
element: string = "div";
object: HTMLElement;
parent: HTMLElement;
children: Xplore[] = [];
parentcontrol: Xplore;
classes: string[];
onclick: Function;
icon: string;
iconcolor: string;
text: string;
enabled: boolean = true;
readonly: boolean = false;
tag: any;
static zindex: number = 100;
static activemenu: Xplore.Menu;
static shortcuts: Dictionary<XMenu> = {};
constructor(param?: XploreParam, classname?: string) {
this.classes = [];
if (param != null) {
this.icon = param.icon;
this.text = param.text;
this.onclick = param.onclick;
if (param.classes) {
this.classes = [...this.classes, ...param.classes];
}
}
if (classname)
this.classes.push(classname);
}
Show(parent?: any): void {
this.object = document.createElement(this.element);
for (let classname of this.classes)
this.object.classList.add(classname);
if (parent instanceof HTMLElement) {
this.parent = parent;
parent.appendChild(this.object);
}
else if (parent instanceof Xplore) {
this.parent = parent.object;
parent.object.appendChild(this.object);
}
else {
this.parent = document.body;
document.body.appendChild(this.object);
}
this.Refresh();
}
Refresh(): void {
this.object.innerHTML = "";
if (this.icon) {
let icon = this.DisplayIcon(this.icon);
this.object.appendChild(icon);
if (this.iconcolor)
icon.style.color = this.iconcolor;
}
if (this.text) {
let text = document.createElement("div");
text.classList.add("text");
text.innerHTML = this.text;
this.object.append(text);
}
this.RefreshChildren();
this.AfterRefresh();
this.Events();
}
RefreshChildren(): void {
//Children
for (let i = 0; i < this.children.length; i++) {
this.children[i].Show(this.object);
}
};
AfterRefresh(): void {
}
Events(): void {
let self = this;
if (this.onclick) {
if (!this.readonly) {
this.object.onclick = function () {
if (self.enabled) {
if (self.onclick)
self.onclick(self);
}
};
}
}
};
Bind(object: Object): void {
for (let prop in object) {
if (object[prop] instanceof Xplore) {
this.Add(object[prop]);
}
}
}
Add(child: Xplore): Xplore {
child.parentcontrol = this;
this.children.push(child);
return child;
}
Clear(): void {
this.children.forEach(element => {
element.Dispose();
});
this.children = [];
}
Dispose(): void {
this.children.forEach(element => {
element.Dispose();
});
if (this.object)
this.object.remove();
}
Resize(): void {
}
DisplayIcon(icon: string): HTMLElement {
if (icon.includes(".jpg") || icon.includes(".png")) {
let element: HTMLImageElement;
element = document.createElement("img");
element.classList.add("icon");
element.src = icon;
return element;
} else {
let element: HTMLElement;
element = document.createElement("i");
element.classList.add("icon");
element.classList.add("mdi");
element.classList.add("mdi-" + icon);
return element;
}
};
//Static functions
static GetJSON(url: string, resolve: Function, reject?: Function) {
let xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (resolve)
resolve(JSON.parse(this.responseText));
} else {
if (reject)
resolve(this.responseText);
}
};
xhttp.send();
}
static POST(url: string, data: any, resolve: Function, reject?: Function) {
let xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (resolve)
resolve(JSON.parse(this.responseText));
} else {
if (reject)
resolve(this.responseText);
}
};
xhttp.send(data);
}
static FormatDate(date: Date): string {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
static SaveFile(data: string, filename: string, type?: string): void {
var file = new Blob([data], { type: type });
var a = document.createElement("a");
var url = URL.createObjectURL(file);
if (type === "image/jpg" || type === "image/jpeg" || type === "image/png")
a.href = data;
else
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
static SaveExcel(filename: string, table: HTMLElement, title: string): void {
let path = filename + ".xlsx";
let wb = window.XLSX.utils.table_to_book(table, { sheet: title });
window.XLSX.writeFile(wb, path);
};
static SaveExcel2(filename: string, table: HTMLElement, info: string[][], title: string, title2: string): void {
let path = filename + ".xlsx";
let ws = window.XLSX.utils.aoa_to_sheet(info);
let wb = window.XLSX.utils.table_to_book(table, { sheet: title });
window.XLSX.utils.book_append_sheet(wb, ws, title2);
window.XLSX.writeFile(wb, path);
};
}
namespace Xplore {
//View
export class AppView extends Xplore {
body: HTMLDivElement;
header: HTMLDivElement;
buttons: Xplore[] = [];
showmenu: boolean = true;
constructor(param?: XploreParam) {
super(param, "view");
}
Refresh(): void {
this.object.innerHTML = "";
//Header
this.header = document.createElement("div");
this.header.classList.add("view-header");
this.object.appendChild(this.header);
this.RefreshHeader();
//Body
this.body = document.createElement("div");
this.body.classList.add("view-body");
this.object.appendChild(this.body);
this.RefreshBody();
this.Events();
};
RefreshHeader(): void {
var self = this;
this.header.innerHTML = "";
if (this.showmenu) {
let menu = new Xplore.Button({
icon: "menu",
onclick: function (): Xplore {
let container = new Xplore.Container();
return container;
}
});
menu.Show(this.header);
}
var text = document.createElement("div");
text.innerHTML = this.text;
text.classList.add("text");
this.header.appendChild(text);
var buttons = document.createElement("div");
buttons.classList.add("buttons");
this.header.appendChild(buttons);
for (var i = 0; i < this.buttons.length; i++) {
this.buttons[i].Show(buttons);
}
};
RefreshBody(): void {
this.body.innerHTML = "";
//Children
for (var i = 0; i < this.children.length; i++) {
this.children[i].Show(this.body);
}
};
}
export class Card extends Xplore {
constructor(param?: XploreParam) {
super(param, "card");
}
Refresh(): void {
this.object.innerHTML = "";
if (this.icon)
this.object.appendChild(this.DisplayIcon(this.icon));
if (this.text) {
let text = document.createElement("div");
text.classList.add("text");
text.append(this.text);
this.object.append(text);
}
}
}
//Container
export class Container extends Xplore {
constructor(param?: XploreParam) {
super(param, "container");
}
}
export class ScrollContainer extends Xplore {
constructor(classes?: string[]) {
super(undefined, "scroll-container");
if (classes)
this.classes = [...this.classes, ...classes];
}
}
export class HorizontalContainer extends Xplore {
body: HTMLDivElement;
constructor(orientation?: XORIENTATION) {
super(undefined, "horizontal-container");
}
Refresh(): void {
this.object.innerHTML = "";
this.body = document.createElement("div");
this.object.appendChild(this.body);
this.RefreshChildren();
this.Events();
}
RefreshChildren(): void {
//Children
for (let i = 0; i < this.children.length; i++) {
this.children[i].Show(this.body);
}
};
}
export class SplitContainer extends Xplore {
panel1: HTMLDivElement;
panel2: HTMLDivElement;
orientation: XORIENTATION;
splittersize: number = 0;
gap: HTMLDivElement;
expanded: boolean = false;
size: number[];
children: Xplore[] = [];
private _splittersize: number;
private _size: number[];
constructor() {
super(undefined, "split-container");
}
Refresh(): void {
this.object.innerHTML = "";
this.panel1 = document.createElement("div");
this.gap = document.createElement("div");
this.panel2 = document.createElement("div");
this.object.appendChild(this.panel1);
this.object.appendChild(this.gap);
this.object.appendChild(this.panel2);
this.Resize();
//Children
for (let i = 0; i < this.children.length && i < 2; i++) {
this.Set(this.children[i], i);
}
let self = this;
window.onresize = function () {
for (let child of self.children) {
child.Resize();
}
};
this.Events();
}
Set(child: Xplore, index: number): Xplore {
let panel = index === 0 ? this.panel1 : this.panel2;
this.children[index] = child;
if (panel) {
panel.innerHTML = "";
child.Show(panel);
}
return child;
};
Resize(): void {
let gap = this.splittersize / 2;
if (this.size) {
if (this.orientation) {
//Vertical
if (this.size[0] !== undefined) {
this.panel1.setAttribute("style", "top: 0; height: " + this.size[0] + "px; left: 0; right: 0 ");
this.panel2.setAttribute("style", "bottom: 0; top: " + (this.size[0] + this.splittersize) + "px; left: 0; right: 0 ");
if (this.splittersize !== 0)
this.gap.setAttribute("style", "top: " + this.size[0] + "px; height: " + this.splittersize + "px; left: 0; right: 0 ");
} else if (this.size[1] !== undefined) {
this.panel1.setAttribute("style", "top: 0; bottom: " + this.size[1] + "px; left: 0; right: 0 ");
this.panel2.setAttribute("style", "bottom: 0; height: " + (this.size[1] + this.splittersize) + "px; left: 0; right: 0 ");
if (this.splittersize !== 0)
this.gap.setAttribute("style", "bottom: " + this.size[1] + "px; height: " + this.splittersize + "px; left: 0; right: 0 ");
}
} else {
//Horizontal
if (this.size[0] !== undefined) {
this.panel1.setAttribute("style", "left: 0; width: " + this.size[0] + "px; top: 0; bottom: 0 ");
this.panel2.setAttribute("style", "right: 0; left: " + (this.size[0] + this.splittersize) + "px; top: 0; bottom: 0 ");
this.gap.setAttribute("style", "left: " + this.size[0] + "px; width: " + this.splittersize + "px; top: 0; bottom: 0 ");
} else if (this.size[1] !== undefined) {
this.panel1.setAttribute("style", "left: 0; right: " + (this.size[1] + this.splittersize) + "px; top: 0; bottom: 0 ");
this.panel2.setAttribute("style", "right: 0; width: " + this.size[1] + "px; top: 0; bottom: 0 ");
this.gap.setAttribute("style", "right: " + this.size[1] + "px; width: " + this.splittersize + "px; top: 0; bottom: 0 ");
}
}
} else {
if (this.orientation) {
//Vertical
this.panel1.setAttribute("style", "top: 0; height: calc(50% - " + gap + "px); left: 0; right: 0 ");
this.panel2.setAttribute("style", "bottom: 0; height: calc(50% - " + gap + "px); left: 0; right: 0 ");
if (this.splittersize !== 0)
this.gap.setAttribute("style", "top: calc(50% - " + gap + "px); height: " + this.splittersize + "px; left: 0; right: 0 ");
} else {
//Horizontal
this.panel1.setAttribute("style", "left: 0; width: calc(50% - " + gap + "px); top: 0; bottom: 0 ");
this.panel2.setAttribute("style", "right: 0; width: calc(50% - " + gap + "px); top: 0; bottom: 0 ");
if (this.splittersize !== 0)
this.gap.setAttribute("style", "left: calc(50% - " + gap + "px); width: " + this.splittersize + "px; top: 0; bottom: 0 ");
}
}
};
Expand(index: number): void {
this._splittersize = this.splittersize;
this._size = this.size;
this.expanded = true;
this.splittersize = 0;
if (index === 0)
this.size = [undefined, 0];
else if (index === 1)
this.size = [0];
this.Resize();
};
Restore(): void {
this.splittersize = this._splittersize;
this.size = this._size;
this.expanded = false;
this.Resize();
};
Events(): void {
let self = this;
let resizing: boolean;
let currentx: number;
let currenty: number;
this.gap.onmousedown = function (e) {
resizing = true;
currentx = e.clientX;
currenty = e.clientY;
self.gap.style.zIndex = "1";
self.gap.style.right = "initial";
document.body.onmousemove = function (e) {
if (resizing) {
self.gap.style.left = (e.clientX) + "px";
currentx = e.clientX;
currenty = e.clientY;
}
};
};
this.gap.onmouseup = function (e) {
resizing = false;
self.size = [e.clientX - self.parent.offsetLeft - self.splittersize / 2, undefined];
self.gap.style.zIndex = "";
document.body.onmousemove = undefined;
self.Resize();
for (let child of self.children) {
child.Resize();
}
};
};
}
export class Form extends Xplore {
width: number = 400;
height: number = 400;
body: HTMLDivElement;
header: HTMLDivElement;
footer: HTMLDivElement;
background: Xplore.Background;
buttons: Xplore[] = [];
modal: boolean = true;
showheader: boolean = true;
showfooter: boolean = true;
showclose: boolean = true;
showcancel: boolean = true;
showok: boolean = true;
onok: Function;
oncancel: Function;
onclose: Function;
oktext = "OK";
canceltext = "Cancel";
constructor(param?: XploreParamForm) {
super(param, "form");
this.element = "form";
param = param || {};
this.width = param.width || 400;
this.height = param.height || 400;
}
Refresh(): void {
let self = this;
if (this.modal) {
this.background = new Xplore.Background({
onclick: () => {
self.Dispose();
}
});
this.background.Show();
}
this.object.innerHTML = "";
if (this.showheader) {
//Header
this.header = document.createElement("div");
this.header.classList.add("form-header");
this.object.appendChild(this.header);
this.RefreshHeader();
}
//Body
this.body = document.createElement("div");
this.body.classList.add("form-body");
this.object.appendChild(this.body);
this.RefreshBody();
if (this.showfooter) {
//Footer
this.footer = document.createElement("div");
this.footer.classList.add("form-footer");
this.object.appendChild(this.footer);
this.RefreshFooter();
} else {
this.object.classList.add("no-footer");
}
this.Resize();
this.Events();
};
RefreshHeader(): void {
let self = this;
this.header.innerHTML = "";
let text = document.createElement("div");
text.innerHTML = this.text;
text.classList.add("text");
this.header.appendChild(text);
let buttons = document.createElement("div");
buttons.classList.add("buttons");
this.header.appendChild(buttons);
for (let i = 0; i < this.buttons.length; i++) {
this.buttons[i].Show(buttons);
}
if (this.showclose) {
let button = new Xplore.Button({
icon: "close",
onclick: function () {
self.Close();
}
});
button.Show(buttons);
}
};
RefreshBody(): void {
this.body.innerHTML = "";
//Children
for (let i = 0; i < this.children.length; i++) {
this.children[i].Show(this.body);
}
};
RefreshFooter(): void {
let self = this;
this.footer.innerHTML = "";
let buttons = document.createElement("div");
buttons.classList.add("buttons");
this.footer.appendChild(buttons);
if (this.showok) {
let button = new Xplore.Input(XINPUTTYPE.SUBMIT, {
onclick: function () {
if (self.onok)
self.onok();
self.Close();
}
});
button.Show(buttons);
}
if (this.showcancel) {
let button = new Xplore.Button({
text: this.canceltext,
classes: ["button-cancel"],
onclick: function () {
if (self.oncancel)
self.oncancel();
self.Close();
}
});
button.Show(buttons);
}
};
Resize(): void {
let w = window.innerWidth;
let h = window.innerHeight;
if (this.width > w)
this.width = w - 32;
if (this.height > h)
this.height = h;
let left = (w - this.width) / 2;
let top = (h - this.height) / 2;
this.object.style.width = this.width + "px";
this.object.style.height = this.height + "px";
this.object.style.left = left + "px";
this.object.style.top = top + "px";
};
SetLocation(left: number, top: number): void {
this.object.style.left = left + "px";
this.object.style.top = top + "px";
}
Events(): void {
let self = this;
let resizing: boolean;
let currentx: number;
let currenty: number;
if (this.showheader) {
this.header.onmousedown = function (e) {
resizing = true;
currentx = e.clientX;
currenty = e.clientY;
document.body.onmousemove = function (e) {
if (resizing) {
if (self.object.classList.value.indexOf(" dock") !== -1) {
if (Math.abs(e.clientX - currentx) > 10 || Math.abs(e.clientY - currenty) > 10) {
let width = self.object.offsetWidth;
self.object.classList.remove("dock");
document.body.appendChild(self.object);
if (e.clientX > width) {
self.object.style.left = (e.clientX - (width - e.offsetX)) + "px";
self.object.style.top = (e.clientY - e.offsetY) + "px";
} else {
self.object.style.left = (e.clientX - e.offsetX) + "px";
self.object.style.top = (e.clientY - e.offsetY) + "px";
}
}
} else {
self.object.style.left = self.object.offsetLeft + (e.clientX - currentx) + "px";
self.object.style.top = self.object.offsetTop + (e.clientY - currenty) + "px";
currentx = e.clientX;
currenty = e.clientY;
}
}
};
};
this.header.onmouseup = function (e) {
resizing = false;
document.body.onmousemove = undefined;
};
}
};
Dispose(): void {
Xplore.zindex = 2;
if (this.object) {
this.object.remove();
delete this.object;
}
for (let child of this.children)
child.Dispose();
if (this.modal)
this.background.Dispose();
};
Close(): void {
this.Dispose();
};
}
export class PropertyGrid extends Xplore {
constructor(param?: XploreParam) {
super(param, "propertygrid");
}
Refresh() {
this.object.innerHTML = "";
let header = document.createElement("div");
header.classList.add("propertygrid-header");
this.object.appendChild(header);
//Show icon
if (this.icon)
header.appendChild(this.DisplayIcon(this.icon));
//Show text
if (this.text)
header.append(this.text);
//Children
this.RefreshChildren();
this.Events();
};
}
export class Grid extends Xplore {
columns: number = 2;
rows: number = 2;
items: Xplore[][] = [];
constructor(param?: XploreParam) {
super(param, "grid");
this.element = "table";
}
Refresh(): void {
for (let i = 0; i < this.rows; i++) {
let row = document.createElement("tr");
this.object.appendChild(row);
for (let j = 0; j < this.columns; j++) {
let column = document.createElement("td");
row.appendChild(column);
if (this.items[i] && this.items[i][j] && this.items[i][j].Show)
this.items[i][j].Show(column);
}
}
}
Set(child: Xplore, rowindex: number, columnindex: number): Xplore {
if (!this.items[rowindex])
this.items[rowindex] = [];
this.items[rowindex][columnindex] = child;
return child;
};
}
export class iFrame extends Xplore {
source: string;
constructor(source: string) {
super(undefined, "iframe");
this.source = source;
}
Refresh(): void {
this.object.innerHTML = "";
let frame = "<iframe src='" + this.source + "'></iframe>";
this.object.innerHTML = frame;
}
}
export class Tab extends Xplore {
body: HTMLDivElement;
header: HTMLDivElement;
footer: HTMLDivElement;
position: XPOSITION = XPOSITION.TOP;
tabs: XTabItem[] = [];
index: number = 0;
constructor(param?: XploreParamForm) {
super(param, "form");
this.classes.push("tab");
}
Refresh(): void {
let self = this;
this.object.innerHTML = "";
if (this.position === XPOSITION.TOP) {
//Header
this.header = document.createElement("div");
this.header.classList.add("form-header");
this.object.appendChild(this.header);
this.RefreshHeader();
} else {
this.object.classList.add("no-header");
}
//Body
this.body = document.createElement("div");
this.body.classList.add("form-body");
this.object.appendChild(this.body);
this.RefreshBody();
if (this.position === XPOSITION.BOTTOM) {
//Footer
this.footer = document.createElement("div");
this.footer.classList.add("form-footer");
this.object.appendChild(this.footer);
this.RefreshFooter();
} else {
this.object.classList.add("no-footer");
}
this.Resize();
this.Events();
};
RefreshHeader(): void {
let self = this;
this.header.innerHTML = "";
let buttons = document.createElement("div");
buttons.classList.add("buttons");
this.header.appendChild(buttons);
for (let i = 0; i < this.tabs.length; i++) {
this.tabs[i].button.Show(buttons);
}
};
RefreshBody(): void {
this.body.innerHTML = "";
for (let i = 0; i < this.tabs.length; i++) {
this.tabs[i].container.Show(this.body);
}
this.RefreshTab();
};
RefreshTab(): void {
let width = this.object.clientWidth;
for (let i = 0; i < this.tabs.length; i++) {
this.tabs[i].container.object.style.left = (i - this.index) * width + "px";
this.tabs[i].container.object.style.right = (this.index - i) * width + "px";
}
this.tabs[this.index].container.Refresh();
}
RefreshFooter(): void {
let self = this;
this.footer.innerHTML = "";
for (let i = 0; i < this.tabs.length; i++) {
this.tabs[i].button.tag = i;
this.tabs[i].button.onclick = function (object: Xplore) {
self.index = object.tag;
if (self.tabs[self.index].onclick)
self.tabs[self.index].onclick();
self.RefreshTab();
};
this.tabs[i].button.Show(this.footer);
}
};
}
export class Expander extends Xplore {
collapsed: boolean = true;
header: HTMLElement;
constructor(param?: XploreParam) {
super(param, "expander");
this.icon = "chevron-down";
}
Refresh(): void {
this.object.innerHTML = "";
this.header = document.createElement("div");
this.header.classList.add("expander-header");
this.object.appendChild(this.header);
if (this.icon) {
let icon = this.DisplayIcon(this.icon);
this.header.appendChild(icon);
if (this.iconcolor)
icon.style.color = this.iconcolor;
}
if (this.text) {
let text = document.createElement("div");
text.classList.add("text");
text.innerHTML = this.text;
this.header.append(text);
}
this.RefreshChildren();
this.AfterRefresh();
this.Events();
}
Events(): void {
let self = this;
this.header.onclick = function () {
self.collapsed = !self.collapsed;
let icon = self.object.querySelector(".icon");
if (!self.collapsed) {
self.object.classList.add("expand");
icon.classList.remove("mdi-chevron-down");
icon.classList.add("mdi-chevron-up");
}
else {
self.object.classList.remove("expand");
icon.classList.remove("mdi-chevron-up");
icon.classList.add("mdi-chevron-down");
}
};
}
}
//Element
export class Text extends Xplore {
constructor(param: XploreParam) {
super(param, "text");
}
Refresh(): void {
this.object.innerHTML = this.text;
}
}
export class TextEditor extends Xplore {
text: string;
buttonclick: string;
value: any;
placeholder: string;
onchange: Function;
constructor(param?: XploreParam) {
super(param, "texteditor");
}
Refresh(): void {
let self = this;
this.object.innerHTML = "";
var buttons = document.createElement("div");
buttons.classList.add("texteditor-buttons");
this.object.appendChild(buttons);
let btnbold = document.createElement("button");
btnbold.appendChild(this.DisplayIcon("format-bold"));
btnbold.classList.add("button");
btnbold.onclick = function () {
self.buttonclick = "bold";
self.RefreshValue();
}
buttons.appendChild(btnbold);
let btnitalic = document.createElement("button");
btnitalic.appendChild(this.DisplayIcon("format-italic"));
btnitalic.classList.add("button");
btnitalic.onclick = function () {
self.buttonclick = "italic";
self.RefreshValue();
}
buttons.appendChild(btnitalic);
let btnunderline = document.createElement("button");
btnunderline.appendChild(this.DisplayIcon("format-underline"));
btnunderline.classList.add("button");
btnunderline.onclick = function () {
self.buttonclick = "underline";
self.RefreshValue();
}
buttons.appendChild(btnunderline);
let btnupper = document.createElement("button");
btnupper.appendChild(this.DisplayIcon("format-letter-case-upper"));
btnupper.classList.add("button");
btnupper.onclick = function () {
self.buttonclick = "upper";
self.RefreshValue();
}
buttons.appendChild(btnupper);
let btnlower = document.createElement("button");
btnlower.appendChild(this.DisplayIcon("format-letter-case-lower"));
btnlower.classList.add("button");
btnlower.onclick = function () {
self.buttonclick = "lower";
self.RefreshValue();
}
buttons.appendChild(btnlower);
let btnparagraph = document.createElement("button");
btnparagraph.appendChild(this.DisplayIcon("format-paragraph"));
btnparagraph.classList.add("button");
btnparagraph.onclick = function () {
self.buttonclick = "paragraph";
self.RefreshValue();
}
buttons.appendChild(btnparagraph);
let btnlink = document.createElement("button");
btnlink.appendChild(this.DisplayIcon("link"));
btnlink.classList.add("button");
btnlink.onclick = function () {
self.buttonclick = "link";
self.RefreshValue();
}
buttons.appendChild(btnlink);
//----------------------
let btnlink1 = document.createElement("button");
btnlink1.appendChild(this.DisplayIcon("link"));
btnlink1.classList.add("button");
btnlink1.onclick = function () {
self.buttonclick = "link";
self.RefreshValue();
}
buttons.appendChild(btnlink1);
let btnlink2 = document.createElement("button");
btnlink2.appendChild(this.DisplayIcon("link"));
btnlink2.classList.add("button");
btnlink2.onclick = function () {
self.buttonclick = "link";
self.RefreshValue();
}
buttons.appendChild(btnlink2);
let btnlink3 = document.createElement("button");
btnlink3.appendChild(this.DisplayIcon("link"));
btnlink3.classList.add("button");
btnlink3.onclick = function () {
self.buttonclick = "link";
self.RefreshValue();
}
buttons.appendChild(btnlink3);
let btnlink4 = document.createElement("button");
btnlink4.appendChild(this.DisplayIcon("link"));
btnlink4.classList.add("button");
btnlink4.onclick = function () {
self.buttonclick = "link";
self.RefreshValue();
}
buttons.appendChild(btnlink4);
let btnlink5 = document.createElement("button");
btnlink5.appendChild(this.DisplayIcon("link"));
btnlink5.classList.add("button");
btnlink5.onclick = function () {
self.buttonclick = "link";
self.RefreshValue();
}
buttons.appendChild(btnlink5);
let btnlink6 = document.createElement("button");
btnlink6.appendChild(this.DisplayIcon("link"));
btnlink6.classList.add("button");
btnlink6.onclick = function () {
self.buttonclick = "link";
self.RefreshValue();
}
buttons.appendChild(btnlink6);
let input = document.createElement("textarea");
if (this.placeholder) {
input.placeholder = this.placeholder;
input.value = "";
}
this.object.appendChild(input);
};
RefreshValue(): void {
let self = this;
let input = this.object.querySelector("textarea");
let text = input.value;
let selectionstart = input.selectionStart;
let selectend = input.selectionEnd;
let addcode;
let replaceval;
let selectendtext = text.substring(selectionstart, selectend);
// let selectendtext = text.slice(0, selectionstart) + "[B]" + text.slice(0, selectend) + "[B]";
switch (self.buttonclick) {
case "bold":
addcode = "[B]" + selectendtext + "[B]";
replaceval = text.replace(selectendtext, addcode)
input.value = replaceval;
break;
case "italic":
addcode = "[I]" + selectendtext + "[I]";
replaceval = text.replace(selectendtext, addcode)
input.value = replaceval;
break;
case "underline":
addcode = "[U]" + selectendtext + "[U]";
replaceval = text.replace(selectendtext, addcode)
input.value = replaceval;
break;
case "upper":
addcode = "[UP]" + selectendtext + "[UP]";
replaceval = text.replace(selectendtext, addcode)
input.value = replaceval;
break;
case "lower":
addcode = "[LOw]" + selectendtext + "[LOw]";
replaceval = text.replace(selectendtext, addcode)
input.value = replaceval;
break;
case "paragraph":
addcode = "[P]" + selectendtext + "[P]";
replaceval = text.replace(selectendtext, addcode)
input.value = replaceval;
break;
case "link":
addcode = "[L]" + selectendtext + "[L]";
replaceval = text.replace(selectendtext, addcode)
input.value = replaceval;
break;
}
self.value = input.value;
};
// Events(): void {
// let input = this.object.querySelector("textarea");
// let self = this;
// input.onchange = function (): any {
// self.value = (<HTMLInputElement>this).value;
// };
// if (self.onchange)
// self.onchange(self);
// };
}
export class TextBlock extends Xplore {
constructor(param: XploreParam) {
super(param, "textblock");
}
}
export class Button extends Xplore {
constructor(param: XploreParam) {
super(param, "button");
}
}
export class Image extends Xplore {
source: string;
constructor(source: string) {
super(undefined, "text");
this.source = source;
}
Refresh(): void {
this.object.innerHTML = "";
let image = document.createElement("img");
image.src = this.source;
this.object.appendChild(image);
}
}
export class List extends Xplore {
buttons: Xplore[] = [];
constructor(param: XploreParamList) {
super(param, "list");
this.buttons = param.buttons;
}
AfterRefresh(): void {
if (this.buttons && this.buttons.length) {
let container = document.createElement("div");
container.classList.add("button-container");
this.object.appendChild(container);
for (let button of this.buttons) {
button.Show(container);
}
}
}
}
//Input
export class Input extends Xplore {
protected input: HTMLInputElement;
type: XINPUTTYPE;
name: string;
value: any;
bind: XBind;
onchange: Function;
constructor(type: XINPUTTYPE = XINPUTTYPE.TEXT, param?: XploreParam) {
super(param, "input");
this.classes.push("inline");
this.classes.push("textbox");
this.type = type;
}
Refresh(): void {
this.object.innerHTML = "";
if (this.text) {
let label = document.createElement("label");
this.object.appendChild(label);
let text = document.createElement("div");
text.innerText = this.text;
label.appendChild(text);
let input = document.createElement("input");
input.type = this.type;
switch (this.type) {
case "checkbox":
if (this.value !== undefined)
input.checked = this.value;
break;
default:
if (this.value !== undefined)
input.value = this.value;
break;
}
if (this.name !== undefined)
input.name = this.name;
label.appendChild(input);
if (this.readonly)
input.setAttribute("disabled", "disabled");
} else {
let input = document.createElement("input");
input.type = this.type;
if (this.value !== undefined)
input.value = this.value;
if (this.name !== undefined)
input.name = this.name;
this.object.appendChild(input);
if (this.readonly)
input.setAttribute("disabled", "disabled");
}
this.Events();
};
Events(): void {
if (!this.readonly) {
let input = this.object.querySelector("input");
let self = this;
switch (this.type) {
case "submit":
input.addEventListener('click', function (e) {
e.preventDefault();
if (self.onclick)
self.onclick();
});
break;
case "checkbox":
input.addEventListener('change', function (e) {
e.preventDefault();
self.value = this.checked;
if (self.bind) {
self.bind.object[self.bind.name] = self.value;
}
if (self.onchange)
self.onchange(self);
});
break;
default:
input.addEventListener('input', function () {
switch (this.type) {
case "checkbox":
self.value = input.checked;
break;
default:
self.value = input.value;
break;
}
self.value = this.value;
if (self.bind) {
self.bind.object[self.bind.name] = self.value;
}
if (self.onchange)
self.onchange(self);
});
break;
}
}
};
}
export class Checkbox extends Input {
constructor(param?: XploreParamCheckbox) {
super(XINPUTTYPE.CHECKBOX, param);
this.value = param.value;
this.bind = param.bind;
}
set checked(value: boolean) {
this.input.checked = value;
}
get checked() {
return this.input.checked;
}
}
export class Combobox extends Xplore {
options: string[] = [];
value: any;
onchange: Function;
constructor(param?: XploreParam) {
super(param, "input");
this.classes.push("inline");
}
Refresh(): void {
this.object.innerHTML = "";
let select;
if (this.text) {
let text = document.createElement("div");
text.innerText = this.text;
this.object.appendChild(text);
let label = document.createElement("label");
this.object.appendChild(label);
select = document.createElement("select");
label.appendChild(select);
if (this.readonly)
select.setAttribute("disabled", "disabled");
} else {
select = document.createElement("select");
this.object.appendChild(select);
if (this.readonly)
select.setAttribute("disabled", "disabled");
}
let option;
if (this.options) {
for (let i = 0; i < this.options.length; i++) {
option = document.createElement("option");
option.value = this.options[i];
option.innerHTML = this.options[i];
select.appendChild(option);
}
select.selectedIndex = this.options.indexOf(this.value);
}
this.Events();
};
Events(): void {
let select = this.object.querySelector("select") as HTMLSelectElement;
let self = this;
select.onchange = function (): any {
self.value = (<HTMLInputElement>this).value;
if (self.onchange)
self.onchange(self);
};
};
}
//Menu
export class MenuContainer extends Xplore {
constructor(type: XMENUTYPE = XMENUTYPE.DEFAULT, param?: XploreParam) {
super(param, "menu-container");
this.classes.push(type);
}
}
export class Menu extends Xplore {
parentmenu: Menu;
shortcut: string;
separator: boolean;
children: Xplore.Menu[] = [];
onmenu: boolean;
constructor(param?: XploreParamMenu) {
super(param, "menu");
this.shortcut = param.shortcut;
this.separator = param.separator;
if (this.shortcut) {
Xplore.shortcuts[param.shortcut] = {
menu: this,
action: param.onclick
};
}
}
Refresh(): void {
this.object.innerHTML = "";
this.object.tabIndex = 1;
if (this.separator)
this.object.classList.add("separator");
let text = document.createElement("div");
if (this.icon)
text.appendChild(this.DisplayIcon(this.icon));
else
text.appendChild(document.createElement("div"));
text.append(this.text);
if (this.shortcut) {
let shortcut = document.createElement("div");
shortcut.innerText = this.shortcut;
text.appendChild(shortcut);
} else if (this.children.length && this.parentmenu) {
let shortcut = document.createElement("div");
shortcut.appendChild(this.DisplayIcon("chevron-right"));
text.appendChild(shortcut);
}
this.object.appendChild(text);
if (this.children.length) {
//Children
let submenu = document.createElement("div");
this.object.appendChild(submenu);
for (let i = 0; i < this.children.length; i++) {
this.children[i].parentmenu = this;
this.children[i].Show(submenu);
}
}
this.Events();
};
Events(): void {
let self = this;
if (this.children.length !== 0) {
this.object.tabIndex = -1;
}
this.object.onclick = function (e) {
e.stopPropagation();
if (self.onclick) {
if (self.parentmenu)
self.parentmenu.Collapse();
self.onclick(self);
}
else if (self.children.length) {
self.object.classList.add("display");
Xplore.activemenu = self;
} else {
if (self.parentmenu) {
console.error("Menu [" + self.parentmenu.text + " -> " + self.text + "] not implemented!");
self.parentmenu.Collapse();
} else
console.error("Menu [" + self.text + "] not implemented!");
}
};
this.object.onmouseenter = function () {
self.onmenu = true;
if (Xplore.activemenu && self.parentmenu !== Xplore.activemenu && self.children.length) {
Xplore.activemenu.Collapse();
self.object.focus();
self.object.classList.add("display");
Xplore.activemenu = self;
}
};
this.object.onmouseleave = function () {
self.onmenu = false;
};
this.object.addEventListener('focusout', function (event) {
if (!self.onmenu) {
self.onmenu = false;
self.object.classList.remove("display");
delete Xplore.activemenu;
}
});
};
Collapse(): void {
this.onmenu = false;
this.object.classList.remove("display");
delete Xplore.activemenu;
};
}
export class MenuSeparator extends Xplore {
constructor(param?: XploreParam) {
super(param, "menu-separator");
}
}
//Toolbar
export class ToolbarContainer extends Xplore {
constructor(param?: XploreParam) {
super(param, "toolbar-container");
}
}
export class Toolbar extends Xplore {
constructor(param?: XploreParam) {
super(param, "toolbar");
}
}
//Tree
export class Tree extends Xplore {
constructor(param: XploreParamTree) {
super(param, "tree");
}
Refresh(): void {
this.object.innerHTML = "";
let header = document.createElement("div");
header.classList.add("tree-header");
this.object.appendChild(header);
//Show icon
if (this.icon)
header.appendChild(this.DisplayIcon(this.icon));
//Show text
if (this.text)
header.append(this.text);
//Children
this.RefreshChildren();
this.Events();
}
}
export class TreeNode extends Xplore {
data: object;
constructor(param: XploreParamTree) {
super(param, "treenode");
this.data = param.data;
}
Refresh(): void {
this.object.innerHTML = "";
if (this.children.length)
this.object.appendChild(this.DisplayIcon("chevron-right"));
// else
// this.object.appendChild(this.DisplayIcon("circle-small"));
if (this.icon)
this.object.appendChild(this.DisplayIcon(this.icon));
if (this.text)
this.object.append(this.text);
this.RefreshChildren();
this.Events();
}
Events(): void {
let self = this;
this.object.onclick = function (e) {
e.stopPropagation();
let inner: HTMLElement = this as HTMLElement;
if (inner.children.length === 1) {
self.onclick(self);
} else {
if (inner.classList.contains("expand")) {
inner.classList.remove("expand");
inner.children[0].classList.remove("mdi-chevron-down");
inner.children[0].classList.add("mdi-chevron-right");
}
else {
inner.classList.add("expand");
inner.children[0].classList.remove("mdi-chevron-right");
inner.children[0].classList.add("mdi-chevron-down");
}
self.onclick(self);
}
};
}
}
//Calendar
export class Calendar extends Xplore {
value = new Date();
todayyear = this.value.getFullYear();
todaymonth = this.value.getMonth();
todaydate = this.value.getDate();
header: Xplore;
calendar: Xplore;
list: Xplore.ScrollContainer;
constructor() {
super(undefined, "calendar");
}
Refresh(): void {
this.header = new Xplore.Container({ classes: ["calendar-header"] });
this.calendar = new Xplore.Container();
this.list = new Xplore.ScrollContainer();
let splitter = new Xplore.SplitContainer();
splitter.orientation = XORIENTATION.VERTICAL;
splitter.size = [52];
splitter.children = [
this.header,
this.calendar
];
splitter.Show(this.object);
let mainsplitter = new Xplore.SplitContainer();
mainsplitter.orientation = XORIENTATION.VERTICAL;
mainsplitter.children = [
splitter,
this.list
];
mainsplitter.Show(this.object);
this.RefreshMonth(this.value);
}
RefreshMonth(value: Date): void {
this.RefreshHeader();
this.RefreshCalendar(value);
this.RefreshList();
}
RefreshCalendar(value: Date): void {
this.RefreshHeader();
let data = [];
let calendar = [];
let year = value.getFullYear();
let month = value.getMonth();
let date = value.getDate();
let day = new Date(value.getFullYear(), value.getMonth(), 1).getDay();
let previousdays = new Date(value.getFullYear(), value.getMonth(), 0).getDate();
let days = new Date(value.getFullYear(), value.getMonth() + 1, 0).getDate();
let cellyear: number;
let cellmonth: number;
let cellday: number;
//Previous Month
for (let i = 0; i < day; i++) {
cellday = previousdays - day + i + 1;
if (month === 0)
cellyear = year - 1;
else
cellyear = year;
if (month === 0)
cellmonth = 12;
else
cellmonth = month;
data.push(this.AddDay(cellyear, cellmonth - 1, cellday, year, month));
if (data.length === 7) {
calendar.push(data);
data = [];
}
}
//Current Month
for (let i = 1; i <= days; i++) {
data.push(this.AddDay(year, month, i, year, month));
if (data.length === 7) {
calendar.push(data);
data = [];
}
}
let j = 1;
//Next Month
for (let i = data.length; i <= 7; i++) {
cellday = j++;
if (month === 11)
cellyear = year + 1;
else
cellyear = year;
if (month === 11)
cellmonth = 0;
else
cellmonth = month;
data.push(this.AddDay(cellyear, cellmonth + 1, cellday, year, month));
if (data.length === 7) {
calendar.push(data);
data = [];
}
}
let table = new Xplore.Table({
columns: [
{ name: "0", text: "Sun" },
{ name: "1", text: "Mon" },
{ name: "2", text: "Tue" },
{ name: "3", text: "Wed" },
{ name: "4", text: "Thu" },
{ name: "5", text: "Fri" },
{ name: "6", text: "Sat" },
],
data: calendar
});
this.calendar.Clear();
table.Show(this.calendar);
}
RefreshHeader(): void {
this.header.Clear();
this.header.Add(new Xplore.Button({ text: "Today", classes: ["calendar-header-today"] }));
this.header.Add(new Xplore.Button({ icon: "chevron-left" }));
this.header.Add(new Xplore.Button({ icon: "chevron-right" }));
this.header.Add(new Xplore.Button({ text: "October 2021" }));
this.header.Refresh();
}
RefreshList(): void {
this.list.Clear();
let events: XCalendarItem[] = [];
events.push({
text: "Holiday"
});
events.push({
text: "Webinar"
});
this.list.Add(new Xplore.CalendarList(new Date(), events));
this.list.Refresh();
}
AddDay(year: number, month: number, day: number, currentyear: number, currentmonth: number): Xplore {
let cellyear: string;
let cellmonth: string;
let cellday: string = day.toString();
let listevent: Xplore.List;
let container = new Xplore.Container({});
let text = container.Add(new Xplore({ text: cellday, classes: ["calendar-day"] }));
if (year !== currentyear || month !== currentmonth)
text.classes.push("disable");
cellyear = year.toString();
if (month < 9)
cellmonth = "0" + (month + 1);
else
cellmonth = (month + 1).toString();
if (day < 10)
cellday = "0" + cellday;
container.tag = cellyear + "-" + cellmonth + "-" + cellday;
//Highlight current date
if (this.todaydate === day && this.todaymonth === month && this.todayyear === year) {
container.classes.push("current");
}
// //Add events
// let icon;
// for (let j = 0; j < this.events.length; j++) {
// event = this.events[j];
// event.index = j;
// if (event.year === year && event.month === (month + 1) && event.day === day) {
// if (event.text && event.text.Show)
// container.Add(event.text);
// else {
// icon = "circle";
// if (event.time)
// icon = new mobiwork({ class: "calendar-event-time", text: event.time });
// listevent = container.Add(new Xplore.List({
// icon: icon,
// data: event,
// text: event.text,
// onclick: function (object) {
// let day = $(this.parent[0].parentElement.parentElement);
// let date = day.attr("data-cell");
// if (self.onclick) {
// self.onclick(object);
// } else if (self.showeditor) {
// self.ShowEditor(new Date(date));
// }
// }
// }));
// }
// if (event.icon) {
// listevent.class += " has-icon";
// listevent.icon = event.icon;
// }
// listevent.Add(new mobiwork({
// class: "tooltip",
// text: event.text
// }));
// listevent.class += " calendar-event";
// //Past events
// if (event.class === "holiday") {
// listevent.class += " calendar-event-holiday";
// } else if (((todaymonth + 1) === event.month && todaydate > event.day) || (todaymonth + 1) > event.month)
// listevent.class += " calendar-event-expired";
// if (event.class)
// container.cellclass = event.class;
// }
// }
return container;
};
}
export class CalendarList extends Xplore {
date: Date;
events: XCalendarItem[];
constructor(date: Date, events: XCalendarItem[]) {
super(undefined, "calendar-list");
this.date = date;
this.events = events;
}
Refresh(): void {
let left = new Xplore.Container();
let date = this.date.getDay();
let week = this.date.getDate();
left.Add(new Xplore.Text({ text: date }));
left.Add(new Xplore.Text({ text: week }));
left.Show(this.object);
}
}
//Table
export class Table extends Xplore {
columns: XTableParamColumn[];
data: Object[];
guid: string;
table: HTMLTableElement;
header: HTMLElement;
body: HTMLElement;
footer: HTMLElement;
fragment: DocumentFragment;
constructor(param: XTableParam) {
super(undefined, "table");
this.columns = param.columns;
this.data = param.data;
}
Refresh(): void {
this.object.innerHTML = "";
this.guid = "table-" + new Date().getTime();
this.object.classList.add(this.guid);
this.fragment = new DocumentFragment();
// Table
this.table = document.createElement("table");
this.fragment.appendChild(this.table);
//Header
this.header = document.createElement("thead");
this.header.classList.add("table-header");
this.table.appendChild(this.header);
this.RefreshHeader();
//Body
this.body = document.createElement("tbody");
this.body.classList.add("table-body");
this.table.appendChild(this.body);
this.RefreshBody();
//Footer
this.footer = document.createElement("div");
this.footer.classList.add("table-footer");
this.fragment.appendChild(this.footer);
this.RefreshFooter();
this.object.appendChild(this.fragment);
}
RefreshHeader(): void {
let th: HTMLTableCellElement;
let tr = document.createElement("tr");
this.header.appendChild(tr);
for (let column of this.columns) {
th = document.createElement("th");
th.innerHTML = column.text;
tr.appendChild(th);
}
}
RefreshBody(): void {
let tr: HTMLTableRowElement;
let td: HTMLTableCellElement;
for (let cell of this.data) {
tr = document.createElement("tr");
this.body.appendChild(tr);
for (let column of this.columns) {
td = document.createElement("td");
if (cell[column.name] instanceof Xplore) {
cell[column.name].Show(td);
} else {
td.innerHTML = cell[column.name];
}
tr.appendChild(td);
}
}
}
RefreshFooter(): void {
}
}
//Others
export class Background extends Xplore {
constructor(param?: XploreParam) {
super(param, "background");
}
Refresh(): void {
this.object.style.zIndex = (++Xplore.zindex).toString();
this.Events();
};
}
}
window.onload = function () {
if (this.Run)
this.Run();
};
document.onkeydown = function (event) {
let key = "";
if (event.ctrlKey) {
key += "ctrl+";
}
if (event.shiftKey)
key += "shift+";
if (event.altKey)
key += "alt+";
key += event.key;
key = key.toLowerCase();
for (let shortcutkey in Xplore.shortcuts)
if (shortcutkey.toLowerCase() === key)
if (Xplore.shortcuts[shortcutkey].action) {
event.preventDefault();
Xplore.shortcuts[shortcutkey].action(Xplore.shortcuts[shortcutkey].menu);
}
}; |
# Copyright 2023 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
import sys
import typing as t
from flask import Flask
from taipy.core import Core
from taipy.gui import Gui
from taipy.rest import Rest
if sys.version_info >= (3, 10):
from typing import TypeGuard
_AppType = t.Union[Gui, Rest, Core]
_AppTypeT = t.TypeVar("_AppTypeT", Gui, Rest, Core)
def _run(*services: _AppType, **kwargs) -> t.Optional[Flask]:
"""Run one or multiple Taipy services.
A Taipy service is an instance of a class that runs code as a Web application.
Parameters:
*services (Union[`Gui^`, `Rest^`, `Core^`]): Services to run, as separate arguments.<br/>
If several services are provided, all the services run simultaneously.<br/>
If this is empty or set to None, this method does nothing.
**kwargs: Other parameters to provide to the services.
"""
gui = __get_app(services, Gui)
rest = __get_app(services, Rest)
core = __get_app(services, Core)
if gui and core:
from taipy.core._core_cli import _CoreCLI
from taipy.gui._gui_cli import _GuiCLI
_CoreCLI.create_parser()
_GuiCLI.create_parser()
if rest or core:
if not core:
core = Core()
core.run()
if not rest and not gui:
return None
if gui and rest:
gui._set_flask(rest._app)
return gui.run(**kwargs)
else:
app = rest or gui
assert app is not None # Avoid pyright typing error
return app.run(**kwargs)
# Avoid black adding too many empty lines
# fmt: off
if sys.version_info >= (3, 10):
def __get_app(apps: t.Tuple[_AppType, ...], type_: t.Type[_AppTypeT]) -> t.Optional[_AppType]:
def filter_isinstance(tl: _AppType) -> TypeGuard[_AppTypeT]:
return isinstance(tl, type_)
return next(filter(filter_isinstance, apps), None)
else:
def __get_app(apps: t.Tuple[_AppType, ...], type_: t.Type[_AppTypeT]) -> t.Optional[_AppType]:
return next(filter(lambda a: isinstance(a, type_), apps), None)
# fmt: on |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity ^0.8.25;
import { Test, console2 } from "forge-std/src/Test.sol";
// import { NFTMarket, BaseERC20, TokenAccessError, ListNFT, InvalidAddressError } from "../src/Week2/NFTMarket.sol";
// import { MyERC2612 } from "../src/Week3/MyERC2612.sol";
// import { TokenBank, BaseERC20 } from "../src/Week2/BaseERC20.sol";
import { MyERC20 } from "../src/Week3/MyERC20.sol";
import { ERC20Factory } from "../src/Week3/ERC20Factory.sol";
import { IERC20Errors } from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
// import "filename";
// import { SigUtils } from "./SigUtils.sol";
// import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// import { MessageHashUtils } from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
contract ERC20FactoryTest is Test {
ERC20Factory erc20Factory;
MyERC20 myERC20;
address alice = makeAddr("alice");
address bob = makeAddr("bob");
address address1 = makeAddr("address1");
address address2 = makeAddr("address2");
function setUp() public {
myERC20 = new MyERC20();
erc20Factory = new ERC20Factory(address(myERC20));
}
function test_init() public {
// newErc20.init("hh", "hh", 1e18);
address clone = erc20Factory.init("hh", 1e18);
MyERC20 newErc20 = MyERC20(clone);
assertEq(newErc20.symbol(), "hh");
assertEq(newErc20.decimals(), 18);
}
function test_deployInscription() public {
// token "hh"
vm.prank(alice);
address tokenAddress = erc20Factory.deployInscription("hh", 1e18, 1e5, 1e5);
assertEq(MyERC20(tokenAddress).balanceOf(address(erc20Factory)), 1e18);
mintFromFactory(bob, tokenAddress, alice, 1e5, 1e5);
// token "gg"
vm.prank(address1);
address anotherTokenAddress = erc20Factory.deployInscription("gg", 1e18, 1e6, 1e6);
assertEq(MyERC20(anotherTokenAddress).balanceOf(address(erc20Factory)), 1e18);
mintFromFactory(address2, anotherTokenAddress, address1, 1e6, 1e6);
}
function testrevertOverSupply() public {
vm.prank(alice);
address tokenAddress = erc20Factory.deployInscription("hh", 1e5, 1e5, 1e5);
assertEq(MyERC20(tokenAddress).balanceOf(address(erc20Factory)), 1e5);
mintFromFactory(bob, tokenAddress, alice, 1e5, 1e5);
vm.expectRevert(
abi.encodeWithSelector(IERC20Errors.ERC20InsufficientBalance.selector, address(erc20Factory), 0, 1e5)
);
vm.deal(address1, 1 ether);
vm.prank(address1);
// mint over the supply will revert ERC20InsufficientBalance
erc20Factory.mintInscription{ value: 1e5 }(tokenAddress);
}
function mintFromFactory(
address _who,
address tokenAddress,
address tokenManager,
uint256 price,
uint256 perMint
)
public
{
uint256 balanceAliceBeforeMint = _who.balance;
uint256 balanceFactoryBeforeMint = address(erc20Factory).balance;
vm.deal(_who, 1 ether);
vm.prank(_who);
// _who mint once, want to get {price} token
erc20Factory.mintInscription{ value: price }(tokenAddress);
assertEq(MyERC20(tokenAddress).balanceOf(address(_who)), perMint);
assertEq(tokenManager.balance, balanceAliceBeforeMint + price / 2); // token manager alice get price / 2 wei
assertEq(address(erc20Factory).balance, balanceFactoryBeforeMint + price / 2); // factory get price / 2 wei as
// fee
}
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body>
<!-- input#input1+button#btn$*4{추가}+#container1 -->
<input type="text" id="input1">
<button id="btn1">#container1 시작태그 전 추가(before)</button>
<button id="btn2">#container1 시작태그 다음 추가(prepend)</button>
<button id="btn3">#container1 종료태그 전 추가(append)</button>
<button id="btn4">#container1 종료태그 다음 추가(after)</button>
<div id="container1"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<script>
document.querySelector("#btn1").addEventListener("click", function() {
let val = document.querySelector("#input1").value;
document.querySelector("#container1")
.before("<p>" + val + "</p>"); //텍스트 자체로 추가 <p>가 보임
});
document.querySelector("#btn2").addEventListener("click", function() {
let val = document.querySelector("#input1").value;
document.querySelector("#container1")
.prepend("<p>" + val + "</p>");
});
document.querySelector("#btn3").addEventListener("click", function() {
let val = document.querySelector("#input1").value;
document.querySelector("#container1")
.append("<p>" + val + "</p>");
});
document.querySelector("#btn4").addEventListener("click", function() {
let val = document.querySelector("#input1").value; // value는 input값을 불러오거나 세팅할때 넣는다.
document.querySelector("#container1")
.after("<p>" + val + "</p>");
});
</script>
</body>
</html> |
package com.occulue.aggregate;
import com.occulue.api.*;
import com.occulue.entity.*;
import com.occulue.exception.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.modelling.command.AggregateMember;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
import org.axonframework.spring.stereotype.Aggregate;
import org.springframework.context.annotation.Profile;
/**
* Aggregate handler for StringMeasurementValue as outlined for the CQRS pattern, all write responsibilities
* related to StringMeasurementValue are handled here.
*
* @author your_name_here
*
*/
@Aggregate
public class StringMeasurementValueAggregate {
// -----------------------------------------
// Axon requires an empty constructor
// -----------------------------------------
public StringMeasurementValueAggregate() {
}
// ----------------------------------------------
// intrinsic command handlers
// ----------------------------------------------
@CommandHandler
public StringMeasurementValueAggregate(CreateStringMeasurementValueCommand command) throws Exception {
LOGGER.info( "Handling command CreateStringMeasurementValueCommand" );
CreateStringMeasurementValueEvent event = new CreateStringMeasurementValueEvent(command.getStringMeasurementValueId(), command.getValue());
apply(event);
}
@CommandHandler
public void handle(UpdateStringMeasurementValueCommand command) throws Exception {
LOGGER.info( "handling command UpdateStringMeasurementValueCommand" );
UpdateStringMeasurementValueEvent event = new UpdateStringMeasurementValueEvent(command.getStringMeasurementValueId(), command.getValue());
apply(event);
}
@CommandHandler
public void handle(DeleteStringMeasurementValueCommand command) throws Exception {
LOGGER.info( "Handling command DeleteStringMeasurementValueCommand" );
apply(new DeleteStringMeasurementValueEvent(command.getStringMeasurementValueId()));
}
// ----------------------------------------------
// association command handlers
// ----------------------------------------------
// single association commands
// multiple association commands
// ----------------------------------------------
// intrinsic event source handlers
// ----------------------------------------------
@EventSourcingHandler
void on(CreateStringMeasurementValueEvent event) {
LOGGER.info( "Event sourcing CreateStringMeasurementValueEvent" );
this.stringMeasurementValueId = event.getStringMeasurementValueId();
this.value = event.getValue();
}
@EventSourcingHandler
void on(UpdateStringMeasurementValueEvent event) {
LOGGER.info( "Event sourcing classObject.getUpdateEventAlias()}" );
this.value = event.getValue();
}
// ----------------------------------------------
// association event source handlers
// ----------------------------------------------
// ------------------------------------------
// attributes
// ------------------------------------------
@AggregateIdentifier
private UUID stringMeasurementValueId;
private String value;
private static final Logger LOGGER = Logger.getLogger(StringMeasurementValueAggregate.class.getName());
} |
package com.example.matthewglausfamilymapclient.userinterface.fragments;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.example.matthewglausfamilymapclient.R;
import com.example.matthewglausfamilymapclient.model.DataCache;
import com.example.matthewglausfamilymapclient.userinterface.activities.PersonActivity;
import com.example.matthewglausfamilymapclient.userinterface.activities.SearchActivity;
import com.example.matthewglausfamilymapclient.userinterface.activities.SettingsActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.joanzapata.iconify.IconDrawable;
import com.joanzapata.iconify.fonts.FontAwesomeIcons;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import model.Event;
import model.Person;
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleMap.OnMapLoadedCallback {
private static final float BIRTH_COLOR = BitmapDescriptorFactory.HUE_BLUE;
private static final float MARRIAGE_COLOR = BitmapDescriptorFactory.HUE_RED;
private static final float DEATH_COLOR = BitmapDescriptorFactory.HUE_GREEN;
private static final float OTHER_EVENT_COLOR = BitmapDescriptorFactory.HUE_YELLOW;
private static final int GOOGLE_COLOR_RED = -65536;
private static final int GOOGLE_COLOR_BLACK = -16777216;
private static final int GOOGLE_COLOR_GRAY = -65281;
private GoogleMap map;
private ImageView genderImage;
private TextView personAssociatedWithEventName;
private TextView eventType;
private TextView eventYear;
private LinearLayout mapView;
private Marker currMarker;
private String passedEventID = null;
private List<Polyline> listOfLines;
private List<Marker> listOfMarkers;
private final DataCache dataCache = DataCache.getInstance();
@Override
public View onCreateView(@NonNull LayoutInflater layoutInflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(layoutInflater, container, savedInstanceState);
View view = layoutInflater.inflate(R.layout.fragment_map, container, false);
setHasOptionsMenu(true);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().
findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Drawable genderIcon = new IconDrawable(getActivity(), FontAwesomeIcons.fa_male).
colorRes(R.color.colorBlack).sizeDp(40);
genderImage = view.findViewById(R.id.genderImage);
genderImage.setImageDrawable(genderIcon);
personAssociatedWithEventName = view.findViewById(R.id.nameOfPersonAssociatedWithEvent);
eventType = view.findViewById(R.id.eventType);
eventYear = view.findViewById(R.id.eventYear);
mapView = view.findViewById(R.id.mapTextView);
listOfLines = new ArrayList<>();
listOfMarkers = new ArrayList<>();
if (getArguments() != null) {
passedEventID = getArguments().getString("EventID");
setHasOptionsMenu(false);
}
return view;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.setOnMapLoadedCallback(this);
generateEvents();
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
eventClicked(marker);
return true;
}
});
mapView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PersonActivity.class);
Event event = (Event)currMarker.getTag();
intent.putExtra("PersonID", event.getPersonID());
startActivity(intent);
}
});
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main_menu, menu);
MenuItem searchMenuItem = menu.findItem(R.id.searchItem);
searchMenuItem.setIcon(new IconDrawable(getActivity(), FontAwesomeIcons.fa_search)
.colorRes(R.color.colorWhite)
.actionBarSize());
MenuItem settingsMenuItem = menu.findItem(R.id.settingsItem);
settingsMenuItem.setIcon(new IconDrawable(getActivity(), FontAwesomeIcons.fa_gear)
.colorRes(R.color.colorWhite)
.actionBarSize());
}
@Override
public boolean onOptionsItemSelected(MenuItem menu) {
Intent intent;
switch(menu.getItemId()) {
case R.id.searchItem:
intent = new Intent(getActivity(), SearchActivity.class);
startActivity(intent);
return true;
case R.id.settingsItem:
intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menu);
}
}
@Override
public void onResume() {
super.onResume();
if(map != null) {
Event currEvent = null;
Boolean hasMarker = false;
if(currMarker != null) {
currEvent = (Event) currMarker.getTag();
}
map.clear();
clearLines();
clearMarkers();
generateEvents();
if(currMarker != null) {
for(Marker marker : listOfMarkers) {
Event event = (Event)marker.getTag();
if(event.equals(currEvent)) {
eventClicked(marker);
hasMarker = true;
}
}
if(!hasMarker) {
Drawable genderIcon = new IconDrawable(getActivity(), FontAwesomeIcons.fa_male).
colorRes(R.color.colorBlack).sizeDp(40);
genderImage.setImageDrawable(genderIcon);
personAssociatedWithEventName.setText(R.string.family_map_default);
eventType.setText("");
eventYear.setText("");
mapView.setClickable(false);
}
}
}
}
@Override
public void onMapLoaded() {}
private void generateEvents() {
Marker marker;
List<Event> filteredEvents = dataCache.getFilteredEvents();
for(Event tempEvent : filteredEvents) {
String eventType = tempEvent.getEventType();
if (eventType.equals("birth")) {
marker = map.addMarker(new MarkerOptions().
position(new LatLng(tempEvent.getLatitude(), tempEvent.getLongitude())).
icon(BitmapDescriptorFactory.defaultMarker(BIRTH_COLOR)));
} else if (eventType.equals("marriage")) {
marker = map.addMarker(new MarkerOptions().
position(new LatLng(tempEvent.getLatitude(), tempEvent.getLongitude())).
icon(BitmapDescriptorFactory.defaultMarker(MARRIAGE_COLOR)));
} else if (eventType.equals("death")) {
marker = map.addMarker(new MarkerOptions().
position(new LatLng(tempEvent.getLatitude(), tempEvent.getLongitude())).
icon(BitmapDescriptorFactory.defaultMarker(DEATH_COLOR)));
} else {
marker = map.addMarker(new MarkerOptions().
position(new LatLng(tempEvent.getLatitude(), tempEvent.getLongitude())).
icon(BitmapDescriptorFactory.defaultMarker(OTHER_EVENT_COLOR)));
}
marker.setTag(tempEvent);
listOfMarkers.add(marker);
if (Objects.equals(tempEvent.getEventID(), passedEventID)) {
map.animateCamera(CameraUpdateFactory.zoomTo(3));
eventClicked(marker);
}
}
}
private void eventClicked(Marker marker) {
currMarker = marker;
Event tempEvent = (Event)currMarker.getTag();
Person tempPerson = dataCache.getPersonByID(tempEvent.getPersonID());
String personName = tempPerson.getFirstName() + " " + tempPerson.getLastName();
String eventInfo = tempEvent.getEventType() + ": " + tempEvent.getCity() + ", " +
tempEvent.getCountry();
String year = "(" + tempEvent.getYear() + ")";
Drawable genderIcon;
if(tempPerson.getGender().equals("m")) {
genderIcon = new IconDrawable(getActivity(), FontAwesomeIcons.fa_male).
colorRes(R.color.colorBlue).sizeDp(40);
}
else {
genderIcon = new IconDrawable(getActivity(), FontAwesomeIcons.fa_female).
colorRes(R.color.colorPink).sizeDp(40);
}
genderImage.setImageDrawable(genderIcon);
personAssociatedWithEventName.setText(personName);
eventType.setText(eventInfo);
eventYear.setText(year);
mapView.setClickable(true);
LatLng eventLocation = new LatLng(tempEvent.getLatitude(), tempEvent.getLongitude());
map.animateCamera(CameraUpdateFactory.zoomTo(3));
map.animateCamera(CameraUpdateFactory.newLatLng(eventLocation));
drawAllLines(tempEvent);
}
private void drawAllLines(Event currEvent) {
clearLines();
Event spousesEarliestEvent = dataCache.getPersonsEarliestEvent(dataCache.getSpouseID(
currEvent.getPersonID()));
if(spousesEarliestEvent != null && dataCache.getShowSpouseLines()) {
drawOneLine(currEvent, spousesEarliestEvent, GOOGLE_COLOR_RED, 10);
}
List<Event> personsLifeEvents = dataCache.getPersonsLifeEvents(currEvent.getPersonID());
if(dataCache.getShowLifeStoryLines()) {
Event startEvent = personsLifeEvents.get(0);
for(Event event : personsLifeEvents) {
if(!event.equals(startEvent)) {
drawOneLine(startEvent, event, GOOGLE_COLOR_BLACK, 10);
startEvent = event;
}
}
}
if(dataCache.getShowFamilyTreeLines()) {
drawFamilyTreeLines(currEvent, 10);
}
}
private void drawOneLine(Event startEvent, Event endEvent, int googleColor, float width) {
LatLng startPoint = new LatLng(startEvent.getLatitude(), startEvent.getLongitude());
LatLng endPoint = new LatLng(endEvent.getLatitude(), endEvent.getLongitude());
PolylineOptions options = new PolylineOptions().add(startPoint).add(endPoint).color(
googleColor).width(width);
Polyline line = map.addPolyline(options);
listOfLines.add(line);
}
private void clearLines() {
for(Polyline polyline : listOfLines) {
polyline.remove();
}
listOfLines = new ArrayList<>();
}
private void clearMarkers() {
for(Marker marker : listOfMarkers) {
marker.remove();
}
listOfMarkers = new ArrayList<>();
}
private void drawFamilyTreeLines(Event currEvent, float width) {
Person currPerson = dataCache.getPersonByID(currEvent.getPersonID());
if(currPerson.getFatherID() != null) {
drawFatherLine(currPerson, currEvent, width);
}
if(currPerson.getMotherID() != null) {
drawMotherLine(currPerson, currEvent, width);
}
}
private void drawFatherLine(Person currPerson, Event currEvent, float width) {
Event fathersEarliestEvent = dataCache.getPersonsEarliestEvent(currPerson.getFatherID());
if(fathersEarliestEvent != null) {
drawOneLine(currEvent, fathersEarliestEvent, GOOGLE_COLOR_GRAY, width);
drawFamilyTreeLines(fathersEarliestEvent, width / 2);
}
}
private void drawMotherLine(Person currPerson, Event currEvent, float width) {
Event mothersEarliestEvent = dataCache.getPersonsEarliestEvent(currPerson.getMotherID());
if(mothersEarliestEvent != null) {
drawOneLine(currEvent, mothersEarliestEvent, GOOGLE_COLOR_GRAY, width);
drawFamilyTreeLines(mothersEarliestEvent, width / 2);
}
}
} |
0,1,···,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字(删除后从下一个数字开始计数)。求出这个圆圈里剩下的最后一个数字。
例如,0、1、2、3、4这5个数字组成一个圆圈,从数字0开始每次删除第3个数字,则删除的前4个数字依次是2、0、4、1,因此最后剩下的数字是3。
示例 1:
输入: n = 5, m = 3
输出:3
示例 2:
输入: n = 10, m = 17
输出:2
限制:
1 <= n<= 10^5
1 <= m <= 10^6
通过次数80,719提交次数124,335
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
````java
//划分子问题
//我们将上述问题建模为函数 f(n, m),该函数的返回值为最终留下的元素的序号。
//首先,长度为 n 的序列会先删除第 m % n 个元素,然后剩下一个长度为 n - 1 的序列。那么,我们可以递归地求解 f(n - 1, m),
//就可以知道对于剩下的 n - 1 个元素,最终会留下第几个元素,我们设答案为 x = f(n - 1, m)。
//由于我们删除了第 m % n 个元素,将序列的长度变为 n - 1。当我们知道了 f(n - 1, m) 对应的答案 x 之后,
//我们也就可以知道,长度为 n 的序列最后一个删除的元素,应当是从 m % n 开始数的第 x 个元素。因此有 f(n, m) = (m % n + x) % n = (m + x) % n。
class Solution {
public int lastRemaining(int n, int m) {
return f(n, m);
}
public int f(int n, int m) {
if (n == 1) {
return 0;
}
int x = f(n - 1, m);
return (m + x) % n;
}
}
//迭代性能更好
class Solution {
public int lastRemaining(int n, int m) {
int f = 0;
for (int i = 2; i != n + 1; ++i) {
f = (m + f) % i;
}
return f;
}
}
```` |
package com.binqr.client;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.*;
import com.journeyapps.barcodescanner.camera.CameraSettings.FocusMode;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class ScanActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {
private DecoratedBarcodeView barcodeView;
private List<CheckBox> checkBoxes;
private Context context = this;
private SplittedFile splittedFile;
private String[] neededPermissions = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
checkAndAskForPermissions();
barcodeView = (DecoratedBarcodeView) findViewById(R.id.barcode_scanner);
DecoderFactory decoderFactory = new DefaultDecoderFactory(
EnumSet.of(BarcodeFormat.QR_CODE),
null,
"ISO-8859-1",
false
);
barcodeView.getBarcodeView().setDecoderFactory(decoderFactory);
barcodeView.getBarcodeView().getCameraSettings().setFocusMode(FocusMode.MACRO);
barcodeView.decodeContinuous(callback);
barcodeView.setStatusText("");
splittedFile = new SplittedFile();
checkBoxes = new ArrayList<>();
}
private BarcodeCallback callback = new BarcodeCallback() {
@Override
public void barcodeResult(BarcodeResult result) {
if(result.getText() == null) {
return;
}
byte[] rawBytes = new byte[0];
try {
rawBytes = result.getText().getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (splittedFile.isPartAdded(rawBytes)) {
Toast.makeText(context, "Ignored: " + String.valueOf(rawBytes[0]), Toast.LENGTH_SHORT).show();
return;
}
QRCode qrCode = splittedFile.addPart(rawBytes);
if (splittedFile.isCompleted()) {
Intent intent = new Intent(getBaseContext(), SaveActivity.class);
intent.putExtra("MERGED_FILE", splittedFile.getMergedFile());
intent.putExtra("FILENAME", splittedFile.getFilename());
startActivity(intent);
finish();
}
if (checkBoxes.size() == 0) {
LinearLayout progress = (LinearLayout) findViewById(R.id.progress);
for (int i = 0; i < splittedFile.getPiecesQuantity(); i++) {
CheckBox checkBox = new CheckBox(context);
checkBox.setText(String.format(Locale.getDefault(), "%d", i + 1));
checkBox.setClickable(false);
progress.addView(checkBox);
checkBoxes.add(checkBox);
}
TextView first_scan_text = (TextView) findViewById(R.id.first_scan_text);
first_scan_text.setVisibility(View.GONE);
}
checkBoxes.get(qrCode.getMetadata().getNumber() - 1).setChecked(true);
}
@Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
private void checkAndAskForPermissions() {
Set<String> ungrantedPermissions = new HashSet<>();
for (String neededPermission : neededPermissions) {
if (ContextCompat.checkSelfPermission(this, neededPermission) != PackageManager.PERMISSION_GRANTED) {
ungrantedPermissions.add(neededPermission);
}
}
if (ungrantedPermissions.size() > 0) {
ActivityCompat.requestPermissions(this, ungrantedPermissions.toArray(new String[]{}), 0);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
for (String neededPermission : neededPermissions) {
if (ContextCompat.checkSelfPermission(this, neededPermission) != PackageManager.PERMISSION_GRANTED) {
finish();
}
}
}
@Override
protected void onResume() {
super.onResume();
barcodeView.resume();
}
@Override
protected void onPause() {
super.onPause();
barcodeView.pause();
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
return barcodeView.onTouchEvent(motionEvent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
} |
import logo from './logo.svg';
import './App.css';
import { useEffect, useState } from 'react';
import { Loading } from './loading';
import { Tours } from './tours';
function App() {
const [loading, setLoading] = useState(false);
const [tours, setTours] = useState([]);
const url = 'https://course-api.com/react-tours-project'
const fetchTours = async () => {
setLoading(true);
try {
const response = await fetch(url);
const tours = await response.json();
setLoading(false);
setTours(tours);
} catch (error) {
setLoading(false);
console.log(error);
}
console.log(tours)
}
const removeTour = (id) => {
const newTours = tours.filter((tour) => tour.id !== id);
setTours(newTours);
}
useEffect(() => {
fetchTours();
}, [])
if (loading) {
return <main>
<Loading />
</main>
}
if (tours.length === 0) {
return (
<main>
<div className="title">
<h2>
no tours left
</h2>
<button className='btn' onClick={fetchTours}>Refresh</button>
</div>
</main>
)
}
return (
<main>
<Tours removeTour={removeTour} tours={tours} />
</main>
);
}
export default App; |
package main
import (
. "github.com/atdiar/particleui"
"github.com/atdiar/particleui/drivers/js"
)
type TodosListElement struct {
*Element
}
func (t TodosListElement) GetList() List {
var tdl List
res, ok := t.AsElement().Get("ui", "todoslist")
if !ok {
tdl = NewList().Commit()
}
tdl, ok = res.(List)
if !ok {
tdl = NewList().Commit()
}
return tdl
}
func (t TodosListElement) SetList(tdl List) TodosListElement {
t.SetDataSetUI("todoslist", tdl)
return t
}
func TodoListFromRef(ref *Element) TodosListElement{
return TodosListElement{ref}
}
func(t TodosListElement) AsViewElement() ViewElement{
return ViewElement{t.AsElement()}
}
func displayWhen(filter string) func(Value) bool{
return func (v Value) bool{
o := v.(Todo)
cplte, _ := o.Get("completed")
complete := cplte.(Bool)
if filter == "active" {
if complete {
return false
}
return true
}
if filter == "completed" {
if !complete {
return false
}
return true
}
return true
}
}
func newTodoListElement(document doc.Document, id string, options ...string) *Element {
t := document.Ul.WithID(id, options...)
doc.AddClass(t.AsElement(), "todo-list")
tview := NewViewElement(t.AsElement(), NewView("all"), NewView("active"), NewView("completed"))
t.OnRouterMounted(func(r *Router){
names:= NewList(String("all"), String("active"), String("completed")).Commit()
links:= NewList(
String(r.NewLink("all").URI()),
String(r.NewLink("active").URI()),
String(r.NewLink("completed").URI()),
).Commit()
filterslist:=NewObject()
filterslist.Set("names",names)
filterslist.Set("urls",links)
t.AsElement().SetUI("filterslist",filterslist.Commit())
})
tview.AsElement().Watch("ui","filter", tview,NewMutationHandler(func(evt MutationEvent)bool{
evt.Origin().TriggerEvent("renderlist")
return false
}))
tview.AsElement().Watch("ui","todoslist", tview,NewMutationHandler(func(evt MutationEvent)bool{
newlist:= evt.NewValue().(List)
for _, v := range newlist.UnsafelyUnwrap() {
o:= v.(Todo)
ntd, ok := FindTodoElement(doc.GetDocument(evt.Origin()),o)
if !ok {
ntd = TodosListElement{evt.Origin()}.NewTodo(o)
}else{
ntd.SetDataSetUI("todo",o) // TODO defer ?
}
}
//TodosListElement{evt.Origin()}.signalUpdate()
evt.Origin().TriggerEvent("renderlist")
return false
}))
tview.OnActivated("all", NewMutationHandler(func(evt MutationEvent) bool {
evt.Origin().SetDataSetUI("filter", String("all"))
doc.GetDocument(evt.Origin()).Window().SetTitle("TODOMVC-all")
return false
}))
tview.OnActivated("active", NewMutationHandler(func(evt MutationEvent) bool {
evt.Origin().SetDataSetUI("filter", String("active"))
doc.GetDocument(evt.Origin()).Window().SetTitle("TODOMVC-active")
return false
}))
tview.OnActivated("completed", NewMutationHandler(func(evt MutationEvent) bool {
evt.Origin().SetDataSetUI("filter", String("completed"))
doc.GetDocument(evt.Origin()).Window().SetTitle("TODOMVC-completed")
return false
}))
t.WatchEvent("renderlist", t, NewMutationHandler(func(evt MutationEvent) bool {
t:= evt.Origin()
doc.DEBUG("rendering list")
// Retrieve current filter
filterval, ok := t.Get("ui", "filter")
var filter string
if !ok {
filter = "all"
} else {
filter = string(filterval.(String))
}
var todos List
tlist, ok:= t.Get("ui", "todoslist")
if ok{
todos = tlist.(List)
} else{
todos = NewList().Commit()
}
length:= len(todos.UnsafelyUnwrap())
var newChildren = make([]*Element, length)
todos.Range(func(i int, v Value) bool {
o:= v.(Todo)
if displayWhen(filter)(o){
ntd, ok := FindTodoElement(doc.GetDocument(evt.Origin()),o)
if !ok {
panic("todo not found for rendering...")
}
newChildren = append(newChildren, ntd.AsElement())
}
return false
})
t.SetChildren(newChildren...)
DEBUG(newChildren)
return false
}))
return t.AsElement()
}
func NewTodoList(d doc.Document, id string, options ...string) TodosListElement {
return TodosListElement{newTodoListElement(d,id, options...)}
}
func(t TodosListElement) NewTodo(o Todo) TodoElement{
ntd := newTodoElement(doc.GetDocument(t.AsElement()),o)
id, _ := o.Get("id")
idstr := id.(String)
t.Watch("ui", "todo", ntd, NewMutationHandler(func(evt MutationEvent) bool { // escalates back to the todolist the data changes issued at the todo Element level
var tdl List
res, ok := t.GetUI("todoslist")
if !ok {
tdl = NewList().Commit()
} else {
tdl = res.(List)
}
newval := evt.NewValue()
rawlist:= tdl.UnsafelyUnwrap()
for i, rawtodo := range rawlist {
todo := rawtodo.(Todo)
oldid, _ := todo.Get("id")
if oldid == idstr {
rawlist[i]=newval
t.SetList(NewListFrom(rawlist))
break
}
}
return false
}))
t.WatchEvent("delete", ntd, NewMutationHandler(func(evt MutationEvent) bool {
var tdl List
res, ok := t.AsElement().GetUI("todoslist")
if !ok {
tdl = NewList().Commit()
} else {
tdl = res.(List)
}
ntdl := NewList()
var i int
for _, rawtodo := range tdl.UnsafelyUnwrap() {
todo := rawtodo.(Todo)
oldid, _ := todo.Get("id")
if oldid == idstr {
t,ok:= FindTodoElement(doc.GetDocument(evt.Origin()),rawtodo.(Todo))
if ok{
Delete(t.AsElement())
}
continue
}
ntdl= ntdl.Append(rawtodo)
i++
}
t.SetList(ntdl.Commit())
return false
}))
return ntd
} |
(* Abstract specification of a concurrent shared memory counter, assuming atomic updates
*)
module Counter
use export int.Int
use export map.Map
use export map.Const
type state = Start | Done
(* threads identified by numbers
*)
type thread = int
val constant n_threads : int
axiom n_threads_pos : n_threads > 0
(* System configurations
*)
type world = { pc : map thread state ; counter : int }
(* Inductive invariant
*)
(* Aux function - counts threads that terminated
*)
let rec function count (w:world) (n:int)
requires { 0 <= n <= n_threads }
ensures { 0 <= result <= n }
ensures { (forall t :thread. 0<=t<n -> w.pc[t]=Start) -> result = 0 }
ensures { (forall t :thread. 0<=t<n -> w.pc[t]=Done) -> result = n }
variant { n }
= if n=0 then 0
else let c = match w.pc[n-1] with | Start -> 0 | Done -> 1 end
in c + count w (n-1)
(* lemma about a pair of configurations
differing only in state of one thread.
Required for proving inductiveness of invariant
*)
let rec lemma count_lm (w1:world) (w2:world) (t:thread) (n:int)
requires { 0 <= n <= n_threads }
requires { 0 <= t < n_threads }
requires { forall t' :thread. 0<=t'<n_threads-> t'<>t -> w2.pc[t'] = w1.pc[t'] }
requires { w1.pc[t]=Start /\ w2.pc[t] = Done }
ensures { t<n -> count w2 n = count w1 n + 1 }
ensures { t>=n -> count w2 n = count w1 n }
variant { n }
= if n=0 then ()
else count_lm w1 w2 t (n-1)
predicate inv (w:world) =
w.counter = count w n_threads
(* System INIT
*)
predicate initWorld_p (w:world) = w.pc = const Start /\ w.counter=0
let ghost predicate initWorld (w:world) = initWorld_p w
(* System action
*)
predicate trans_enbld (w:world) (t:thread) =
0<=t<n_threads /\ w.pc[t] = Start
let ghost function trans (w:world) (t:thread) : world
requires { trans_enbld w t }
ensures { inv w -> inv result }
= { pc = set (w.pc) t Done ; counter = w.counter+1 }
(* Transition relation
*)
inductive stepind world world =
| trans : forall w :world, t :thread.
trans_enbld w t -> stepind w (trans w t )
let ghost predicate step (w1:world) (w2:world) = stepind w1 w2
(* Proof of inductiveness
*)
clone export inductiveness.Inductiveness with
type world,
predicate inv,
val step,
val initWorld
lemma correctness : forall w :world. reachable w ->
(forall t :thread. w.pc[t]=Done) -> w.counter=n_threads
end |
<?php
/**
* @file
* This file holds style plugin for OpenLayers Views
*
* @ingroup openlayers
*/
/**
* @class
* Extension of the Views Plugin Style for OpenLayers
*
* This class extended the default views plugin class to provide
* a style plugin for the Open Layers module.
*/
class openlayers_views_style_data extends views_plugin_style {
/**
* Render the map features.
*
* Overrides views_plugin_style->render
*/
function render($result) {
$grouped_results = $this->render_grouping($result, $this->options['grouping']);
$data = $this->map_features($grouped_results);
// If we are not in preview, just return the data
if (empty($this->view->live_preview)) {
return $data;
}
else {
// If we are in preview mode, dump out some useful information about this data layer
$output = "You can use the following parameters in your styles as dynamic values";
$output .= "\n------------\n";
if (!empty($data)) {
$keys = array_keys($data);
foreach ($data[$keys[0]]['attributes'] as $key => $value) {
$output .= '${'.$key."}\n";
}
}
$output .= "\n------------\n";
$output .= t('The following is a dump of the data that is rendered from this display. It is used for debugging purposes only.') . '
' . var_export($data, TRUE);
return $output;
}
}
/**
* Set default options
*
* Overrides views_plugin_style->option_definition
*/
function option_definition() {
$options = parent::option_definition();
$options['data_source'] = array('default' => 'openlayers_wkt');
return $options;
}
/**
* Options form
*
* Overrides views_plugin_style->options_form
*/
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
// Get list of fields in this view & flag available geodata fields
$handlers = $this->display->handler->get_handlers('field');
// Check for any fields, as the view needs them
if (empty($handlers)) {
$form['error_markup'] = array(
'#value' => t('You need to enable at least one field before you can '
. 'configure your field settings'),
'#prefix' => '<div class="error form-item description">',
'#suffix' => '</div>',
);
return;
}
$fields = array();
foreach ($handlers as $field_id => $handler) {
$fields[$field_id] = $handler->ui_name();
}
$form['data_source'] = array(
'#type' => 'fieldset',
'#tree' => TRUE,
'#title' => t('Data Source'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['data_source']['value'] = array(
'#type' => 'select',
'#title' => t('Map Data Sources'),
'#description' => t('Choose which sources of data that the map will '
. 'provide features for.'),
'#options' => array(
'other_latlon' => t('Lat/Lon Pair'),
'other_boundingbox' => t('Bounding Box'),
'wkt' => t('WKT')
),
'#default_value' => $this->options['data_source']['value'],
);
if (count($fields > 0)) {
$form['data_source']['other_lat'] = array(
'#type' => 'select',
'#title' => t('Latitude Field'),
'#description' => t('Choose a field for Latitude. This should be a '
. 'field that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['other_lat'],
'#states' => $this->datasource_dependent('other_latlon')
);
$form['data_source']['other_lon'] = array(
'#type' => 'select',
'#title' => t('Longitude Field'),
'#description' => t('Choose a field for Longitude. This should be a '
. 'field that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['other_lon'],
'#states' => $this->datasource_dependent('other_latlon')
);
$form['data_source']['wkt'] = array(
'#type' => 'select',
'#title' => t('WKT Field'),
'#description' => t('Choose the OpenLayers WKT field.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['wkt'],
'#states' => $this->datasource_dependent('wkt')
);
$form['data_source']['other_top'] = array(
'#type' => 'select',
'#title' => t('Top Field'),
'#description' => t('Choose a field for Top. This should be a '
. 'field that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['other_top'],
'#states' => $this->datasource_dependent('other_boundingbox')
);
$form['data_source']['other_right'] = array(
'#type' => 'select',
'#title' => t('Right Field'),
'#description' => t('Choose a field for Right. This should be a field '
. 'that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['other_right'],
'#states' => $this->datasource_dependent('other_boundingbox')
);
$form['data_source']['other_bottom'] = array(
'#type' => 'select',
'#title' => t('Bottom Field'),
'#description' => t('Choose a field for Bottom. This should be a '
. 'field that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['other_bottom'],
'#states' => $this->datasource_dependent('other_boundingbox')
);
$form['data_source']['other_left'] = array(
'#type' => 'select',
'#title' => t('Left Field'),
'#description' => t('Choose a field for Left. This should be a field '
. 'that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['other_left'],
'#states' => $this->datasource_dependent('other_boundingbox')
);
}
$form['data_source']['name_field'] = array(
'#type' => 'select',
'#title' => t('Title Field'),
'#description' => t('Choose the field which will appear as a title on '
. 'tooltips.'),
'#options' => array_merge(array('' => ''), $fields),
'#default_value' => $this->options['data_source']['name_field'],
);
$form['data_source']['description_field'] = array(
'#type' => 'select',
'#title' => t('Description Field'),
'#description' => t('Choose the field which will appear as a '
. 'description on tooltips.'),
'#required' => FALSE,
'#options' => array_merge(array('' => '', '#row' => '<' . t('entire row') . '>'), $fields),
'#default_value' => $this->options['data_source']['description_field'],
);
$form['attributes'] = array(
'#type' => 'fieldset',
'#title' => t('Attributes and Styling'),
'#description' => t('Attributes are field data attached to each '
. 'feature. This can be used with styling to create Variable styling.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$variable_fields = array();
if (!empty($this->options['data_source']['name_field'])) {
$variable_fields['name'] = '${name}';
}
if (!empty($this->options['data_source']['description_field'])) {
$variable_fields['description'] = '${description}';
}
foreach ($this->view->display_handler->get_handlers('field') as
$field => $handler) {
if (($field != $this->options['data_source']['name_field']) &&
($field != $this->options['data_source']['description_field'])) {
$variable_fields[$field] = '${' . $field . '}';
$variable_fields[$field . '_rendered'] = '${' . $field . '_rendered}';
}
}
$form['attributes']['styling'] = array(
'#markup' => '
<p>' . t('Any fields that you add to this view will be attached to '
. 'their respective feature (point, line, polygon) as attributes. '
. 'These attributes can then be used to add variable styling to your '
. 'themes. This is accomplished by using the %syntax syntax in the '
. 'values for a style. You can see a list of available variables in '
. 'the view preview; these can be placed right in the style interface. '
. 'The %rendered one means that it has been processed '
. 'by Views and may have a different value.',
array(
'%syntax' => '${field_name}',
'%rendered' => '_rendered'))
. '</p>'
. theme('item_list', array('items' => $variable_fields))
. '<p>'
. t('Please note that this does not apply to Grouped Displays.')
. '</p>',
);
}
/**
* @param $records ...
*
* openlayers_views_style_data specific
*/
function map_features($sets = array()) {
$features = $excluded_fields = array();
$handlers = $this->display->handler->get_handlers('field');
foreach ($sets as $title => $records) {
foreach ($records as $id => $record) {
$this->view->row_index = $id;
$attributes = array();
foreach ($handlers as $hid => $handler) {
if (!empty($handler->options['exclude']) && !in_array($hid, $this->options['data_source'])) {
$excluded_fields[] = $hid;
}
else {
$attributes[$hid . '_rendered'] = $handler->allow_advanced_render() ? $handler->advanced_render($record) : $handler->render($record);
$attributes[$hid] = isset($handler->original_value) ? $handler->original_value : NULL;
}
}
if ($this->options['data_source']['description_field'] === '#row') {
$attributes['#row_rendered'] = $this->row_plugin->render($record);
}
$feature = array(
'projection' => '4326',
'attributes' => $attributes,
'wkt' => $this->get_wkt($attributes, $handlers, $this->options['data_source']),
);
$features = $this->reduce_features($this->options['grouping'], $features, $feature, $title);
}
}
if ($this->options['grouping']) {
$features = $this->coalesce_groups($features, $handlers, $this->options['data_source']);
}
else {
$features = $this->add_title_desc($features, $handlers, $this->options['data_source']);
}
return $features;
}
/**
* Basically a macro because
* #state is rather verbose
*
* openlayers_views_style_data specific
*/
function datasource_dependent($type) {
return array('visible' => array('#edit-style-options-data-source-value' => array('value' => $type)));
}
/**
* Find the data source of an element and pull it into a wkt field
*
* openlayers_views_style_data specific
*/
function get_wkt($feature, $handlers, $datasource) {
$feature['projection'] = '4326';
switch ($datasource['value']) {
case 'wkt':
return strip_tags($feature[$datasource['wkt']]);
break;
case 'other_latlon':
return 'POINT(' . strip_tags($feature[$datasource['other_lon']]) . ' ' . strip_tags($feature[$datasource['other_lat']]) . ')';
break;
}
}
/**
* Coalesce features into single grouped feature when grouping is enabled.
*
* openlayers_views_style_data specific
*/
function coalesce_groups($features, $handlers, $ds) {
// Combine wkt into geometry collections if they are an array
foreach ($features as &$feature) {
if (is_array($feature['wkt'])) {
if (count($feature['wkt']) > 1) {
$feature['wkt'] = $this->get_group_wkt($feature['wkt']);
}
else {
$feature['wkt'] = $feature['wkt'][0];
}
}
}
// Process title and description
foreach ($features as $k => &$feature) {
$feature['attributes']['name'] = $k;
$feature['attributes'] = array_merge($feature['attributes'], $feature['features'][0]['attributes']);
$formatted_features = array();
foreach ($feature['features'] as $subfeature) {
$formatted_features[] = theme('openlayers_views_group_display_item',
array(
'name' => isset($handlers[$ds['name_field']]) ? $subfeature['attributes'][$ds['name_field'] . '_rendered'] : false,
'description' => ($ds['description_field'] === '#row' || isset($handlers[$ds['description_field']])) ? $subfeature['attributes'][$ds['description_field'] . '_rendered'] : false
)
);
// Remove rendered row to keep data size down for JS.
if ($ds['description_field'] === '#row') {
unset($subfeature['attributes'][$ds['description_field'] . '_rendered']);
}
}
$feature['attributes']['description'] = theme('item_list',
array(
'items' => $formatted_features
)
);
}
return $features;
}
/**
* Combine all group wkt into a single geometry collection
*
* openlayers_views_style_data specific
*/
function get_group_wkt($wkt_array) {
//@@TODO: DO this in geoPHP - four lines of code...
$output = 'GEOMETRYCOLLECTION(';
$i = 0;
foreach ($wkt_array as $wkt) {
$wkt = strtoupper($wkt);
if ($i != 0) {
$output .= ',';
}
switch (substr($wkt,0,5)) {
case 'POINT':
case 'LINES':
case 'POLYG':
$output .= $wkt;
break;
case 'MULTI':
$subwkt = str_replace(array('MULTIPOINT','MULTIPOLYGON','MULTILINESTRING'),'',$wkt);
$subwkt = str_replace(', ',',',$subwkt);
$subwkt = trim($subwkt);
switch (substr($wkt,0,10)) {
case 'MULTIPOINT':
$subwkt = str_replace(array('(',')'),'',$subwkt);
$parts = explode(',',$subwkt);
$j = 0;
foreach ($parts as $part) {
if ($j != 0) $output .= ',';
$output .= 'POINT('.$part.')';
$j++;
}
break;
case 'MULTILINES':
$subwkt = str_replace(array('((','))'),'',$subwkt);
$parts = explode('),(',$subwkt);
$j = 0;
foreach ($parts as $part) {
if ($j != 0) $output .= ',';
$output .= 'LINESTRING('.$part.')';
$j++;
}
break;
case 'MULTIPOLYG':
//@@TODO: This does not support polygons with holes
$subwkt = str_replace(array('(((',')))'),'',$subwkt);
$parts = explode(')),((',$subwkt);
$j = 0;
foreach ($parts as $part) {
if ($j != 0) $output .= ',';
$output .= 'POLYGON(('.$part.'))';
$j++;
}
break;
}
break;
case 'GEOME':
$output .= trim(substr($wkt,18,-1));
break;
}
$i++;
}
$output .= ')';
return $output;
}
/**
* Retrieve name and description for individual features when grouping is not enabled.
*
* openlayers_views_style_data specific
*/
function add_title_desc($features, $handlers, $ds) {
foreach ($features as $k => &$f) {
if (isset($handlers[$ds['name_field']])) {
$f['attributes']['name'] = $f['attributes'][$ds['name_field'] . '_rendered'];
}
if ($ds['description_field'] === '#row' || isset($handlers[$ds['description_field']])) {
$f['attributes']['description'] = $f['attributes'][$ds['description_field'] . '_rendered'];
// Remove rendered row to keep data size down for JS.
if ($ds['description_field'] === '#row') {
unset($f['attributes'][$ds['description_field'] . '_rendered']);
}
}
}
return $features;
}
/**
* Split string according to first match of passed regEx index of $regExes
*/
function preg_explode($regEx, $str) {
$matches = array();
preg_match($this->regExes[$regEx], $str, $matches);
return empty($matches)?array(trim($str)):explode($matches[0], trim($str));
}
/**
* Basically an algebraic reduction; given whether to group,
* a feature, a list of features, etc., return a full $features
* array with the element added, either straight non-grouped,
* or within a new or existing group
*
* openlayers_views_style_data specific
*/
function reduce_features($is_grouped, $features, $feature, $group) {
if ($is_grouped) {
if (isset($features[$group])) {
$features[$group]['attributes']['count']++;
$features[$group]['wkt'][] = $feature['wkt'];
$features[$group]['features'][] = $feature;
return $features;
}
else {
$features[$group] = array(
'attributes' => array('count' => 1),
'wkt' => array($feature['wkt']),
'projection' => $feature['projection'],
'features' => array($feature)
);
return $features;
}
}
else {
array_push($features, $feature);
return $features;
}
}
} |
import React, { isValidElement } from 'react';
interface Args {
children: React.ReactNode;
className?: string;
style?: React.CSSProperties;
}
const useRefinedChildren = ({ children, className, style }: Args) => {
return React.Children.map(children, (child, idx) => {
if (isValidElement(child)) {
const clonedChild = React.cloneElement(child, {
...child.props,
key: `${className}-item${idx}`,
'data-testid': `${className}-child-comp`,
style: { ...style, ...child.props.style },
});
return clonedChild;
} else {
return (
<div key={`${className}-item${idx}`} data-testid={`${className}-child-comp`}>
{child}
</div>
);
}
});
};
export default useRefinedChildren; |
<!DOCTYPE html>
<html>
<head>
<title>CSS Assignment</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
body {
background-image: url("https://wallpaper.dog/large/17266458.gif");
background-repeat: no-repeat;
background-size: cover;
background-position: center;
background-attachment: fixed;
background-color: black;
}
.jumbotron {
background-color: rgba(0, 0, 0, 0.6);
color: white;
padding: 2rem;
}
.jumbotron h1 {
font-size: 3rem;
color: greenyellow;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
table {
color: fuchsia;
border: 2px solid deeppink;
}
table th,
table td {
font-weight: bold;
color: fuchsia;
}
table.table {
background-color: transparent;
}
table.table a {
font-weight: bold;
color: fuchsia;
text-decoration: none;
}
table.table a:hover {
color: aqua;
}
.img-card {
border-radius: 10px;
overflow: hidden;
}
.img-card img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.img-card:hover img {
transform: scale(1.1);
}
.animate-icon {
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="jumbotron">
<h1 class="text-center">Roller Skating <i class="fas fa-skating animate-icon"></i></h1>
</div>
<div class="row justify-content-center">
<div class="col-lg-6">
<p style="color: aqua; font-size: 18px;" class="text-center font-weight-bold">Roller skating
is traveling on surfaces with roller skates.<br>
It is a recreational activity and a sport.<br>
Roller rinks and skate parks are built for roller skating, though it also takes place on streets,
sidewalks, and bike paths.<br>
There are different types of skating like Ice Skating, Inline Skating, Roller Skating, Outdoor
Skating.</p>
</div>
</div>
<div class="row justify-content-center">
<div class="col-lg-8">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th><a>Type <i class="fas fa-snowboarding"></i></a></th>
<th><a>Time <i class="fas fa-clock"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="css1.html" target="_self">Ice Skating</a></td>
<td><a href="css1.html" target="_self">30 mins</a></td>
</tr>
<tr>
<td><a href="css2.html" target="_self">Inline Skating</a></td>
<td><a href="css2.html" target="_self">2 hrs</a></td>
</tr>
<tr>
<td><a href="css3.html" target="_self">Roller Skating</a></td>
<td><a href="css3.html" target="_self">1 hr</a></td>
</tr>
<tr>
<td><a href="css4.html" target="_self">Outdoor Skating</a></td>
<td><a href="css4.html" target="_self">3 hrs</a></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row justify-content-center">
<div class="col-lg-3">
<div class="img-card">
<img
src="https://todaysparent.mblycdn.com/tp/resized/2017/01/767x431/what-to-know-when-teac
hing-your-toddler-to-ice-skate-1280x960.jpg" class="img-fluid rounded" alt="Image 1">
</div>
</div>
<div class="col-lg-3">
<div class="img-card">
<img
src="https://s3.amazonaws.com/assets.peterglenn.com/blog/rollerblade-maxxum-edge-125-in
line-skate-couple.png" class="img-fluid rounded" alt="Image 2">
</div>
</div>
<div class="col-lg-3">
<div class="img-card">
<img
src="https://www.gannett-cdn.com/presto/2020/02/05/PIND/928c6ed8-c83e-40ee-b487-3142
324146bd-RollBounce_MM_001.JPG?width=592&format=pjpg&auto=webp&quality=70"
class="img-fluid rounded" alt="Image 3">
</div>
</div>
<div class="col-lg-3">
<div class="img-card">
<img
src="https://d1bv4heaa2n05k.cloudfront.net/user-images/1448275913460/shutterstock-92588
179_main_1448275921902.jpeg" class="img-fluid rounded" alt="Image 4">
</div>
</div>
</div>
</div>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/js/all.min.js"></script>
</body>
</html>
<!--
The following Bootstrap elements are used:
● Bootstrap CSS:
Used to apply Bootstrap's default styling and layout to the entire webpage.
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
● Bootstrap Grid System:
Used to create responsive layout and alignment of elements.
<div class="container mt-5">, <div class="row justify-content-center">, <div
class="col-lg-6">, <div class="col-lg-8">, <div class="col-lg-3">
● Bootstrap Jumbotron:
Used to create a large, prominent header with a background color and padding.
<div class="jumbotron">
● Bootstrap Table:
Used to create a table with borders and striped rows.
<table class="table table-bordered table-hover">
● Bootstrap Buttons (Links):
Used to create clickable links with button-like styling.
<a href="css1.html" target="_self" class="btn btn-link">, <a href="css2.html" target="_self"
class="btn btn-link">, <a href="css3.html" target="_self" class="btn btn-link">, <a
href="css4.html" target="_self" class="btn btn-link">
● Bootstrap Typography:
Used to style the headings and paragraphs.
<h1 class="text-center">, <p style="color: aqua; font-size: 18px;" class="text-center
font-weight-bold">
● Bootstrap Images:
Used to create responsive and rounded images.
<img src="..." class="img-fluid rounded" alt="Image 1">, <img src="..." class="img-fluid
rounded" alt="Image 2">, <img src="..." class="img-fluid rounded" alt="Image 3">, <img
src="..." class="img-fluid rounded" alt="Image 4>" --> |
package net.sf.jabref.model.database;
import net.sf.jabref.model.entry.BibLatexEntryTypes;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.model.entry.EntryType;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class BibDatabaseTypeDetection {
private static final List<EntryType> bibtex = BibtexEntryTypes.ALL;
private static final List<EntryType> biblatex = BibLatexEntryTypes.ALL;
private static final List<EntryType> exclusiveBiblatex = filterEntryTypes(biblatex, isNotIncludedIn(bibtex));
/**
* Tries to infer the database type by examining a BibEntry collection.
*
* All checks are based on the case-insensitive comparison of entry tag names.
* Only standard BibTex and Biblatex entry types are considered in the decision process.
*
* 1. Check if any of the entries is a type exclusive to Biblatex
* 2. Check if any exclusive Biblatex fields are present
* 3. Otherwise return BibTex
*
* @param entries a BibEntry collection
* @return the inferred database type
*/
public static BibDatabaseType inferType(Collection<BibEntry> entries) {
final List<String> entryTypes = getEntryTypes(entries);
// type-based check
if (entryTypes.stream().anyMatch(isIncludedIn(exclusiveBiblatex))) {
return BibDatabaseType.BIBLATEX;
} else {
// field-based check
if(entries.stream().anyMatch(hasBiblatexFields())) {
return BibDatabaseType.BIBLATEX;
}
}
return BibDatabaseType.BIBTEX;
}
private static List<String> exclusiveBiblatexFields(String type) {
final Optional<EntryType> biblatexType = BibLatexEntryTypes.getType(type);
final Optional<EntryType> bibtexType = BibtexEntryTypes.getType(type);
// return empty array if this is no Biblatex or BibTex type
if (!biblatexType.isPresent() || !bibtexType.isPresent()) {
return new ArrayList<>(0);
}
final List<String> bibtexFields = bibtexType.get().getAllFields();
final List<String> biblatexFields = biblatexType.get().getAllFields();
return biblatexFields.stream().filter(f -> !bibtexFields.contains(f)).collect(Collectors.toList());
}
private static List<String> getEntryTypes(Collection<BibEntry> collection) {
return collection.stream().map(BibEntry::getType).collect(Collectors.toList());
}
private static List<EntryType> filterEntryTypes(List<EntryType> types, Predicate<EntryType> predicate) {
return types.stream().filter(predicate).collect(Collectors.toList());
}
private static Predicate<EntryType> isNotIncludedIn(List<EntryType> collection) {
return entry -> collection.stream().noneMatch(c -> c.getName().equalsIgnoreCase(entry.getName()));
}
private static Predicate<String> isIncludedIn(List<EntryType> collection) {
return entry -> collection.stream().anyMatch(c -> c.getName().equalsIgnoreCase(entry));
}
private static Predicate<BibEntry> hasBiblatexFields() {
return e -> e.getFieldNames().stream()
.anyMatch(name -> exclusiveBiblatexFields(e.getType()).stream().anyMatch(c -> c.equalsIgnoreCase(name)));
}
} |
<?php
namespace App\Controller;
use App\Entity\Nationalite;
use App\Form\NationaliteType;
use App\Repository\NationaliteRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route('/nationalite')]
class NationaliteController extends AbstractController
{
#[Route('/', name: 'app_nationalite_index', methods: ['GET'])]
#[IsGranted("ROLE_ADMIN", statusCode:404, message:"Error 404 Page not found")]
public function index(NationaliteRepository $nationaliteRepository): Response
{
return $this->render('nationalite/index.html.twig', [
'nationalites' => $nationaliteRepository->findAll(),
]);
}
#[Route('/new', name: 'app_nationalite_new', methods: ['GET', 'POST'])]
#[IsGranted("ROLE_ADMIN", statusCode:404, message:"Error 404 Page not found")]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$nationalite = new Nationalite();
$form = $this->createForm(NationaliteType::class, $nationalite);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($nationalite);
$entityManager->flush();
return $this->redirectToRoute('app_nationalite_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('nationalite/new.html.twig', [
'nationalite' => $nationalite,
'form' => $form,
]);
}
#[Route('/{id}', name: 'app_nationalite_show', methods: ['GET'])]
#[IsGranted("ROLE_ADMIN", statusCode:404, message:"Error 404 Page not found")]
public function show(Nationalite $nationalite): Response
{
return $this->render('nationalite/show.html.twig', [
'nationalite' => $nationalite,
]);
}
#[Route('/{id}/edit', name: 'app_nationalite_edit', methods: ['GET', 'POST'])]
#[IsGranted("ROLE_ADMIN", statusCode:404, message:"Error 404 Page not found")]
public function edit(Request $request, Nationalite $nationalite, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(NationaliteType::class, $nationalite);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
return $this->redirectToRoute('app_nationalite_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('nationalite/edit.html.twig', [
'nationalite' => $nationalite,
'form' => $form,
]);
}
#[Route('/{id}', name: 'app_nationalite_delete', methods: ['POST'])]
#[IsGranted("ROLE_ADMIN", statusCode:404, message:"Error 404 Page not found")]
public function delete(Request $request, Nationalite $nationalite, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('delete'.$nationalite->getId(), $request->request->get('_token'))) {
$entityManager->remove($nationalite);
$entityManager->flush();
}
return $this->redirectToRoute('app_nationalite_index', [], Response::HTTP_SEE_OTHER);
}
} |
/*
Recreating the border-box as a mixin function
*/
@mixin border-box {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
/*
placeholder selector (%)
The placeholder selector allows us to define whole chunks of style which only
get output when we extend them elsewhere.
*/
%clearfix {
*zoom: 1;
&:before,
&:after {
content: " ";
display: table;
}
&:after {
clear: both;
}
}
/*
Box-shadow takes 2 params, shadow 1 and shadow 2, but shadow 2 is optional.
It takes shadow 1 and passes in everything written and assigns those values.
If shadow 2 is also passed in the $params variable changes accordingly and
the values are assigned all the same.
*/
@mixin box-shadow($shadow1, $shadow2:false) {
$params: $shadow1;
@if $shadow2 {
$params: $shadow1, $shadow2;
}
-webkit-box-shadow: $params;
-moz-box-shadow: $params;
box-shadow: $params;
}
@mixin text-shadow($shadow1, $shadow2:false) {
$params: $shadow1;
@if $shadow2 {
$params: $shadow1, $shadow2;
}
-webkit-text-shadow: $params;
-moz-text-shadow: $params;
text-shadow: $params;
}
@mixin transition($transition) {
-webkit-transition: $transition;
-moz-transition: $transition;
transition: $transition;
}
@mixin transform($transform) {
-webkit-transform: $transform;
-moz-transform: $transform;
-ms-transform: $transform;
transform: $transform;
}
@mixin animation($animation){
-webkit-animation: $animation;
-moz-animation: $animation;
animation: $animation;
}
@mixin perspective($perspective) {
-webkit-perspective: $perspective;
-moz-perspective: $perspective;
-ms-perspective: $perspective;
perspective: $perspective;
}
@function pi() {
@return 3.14159265359;
}
@function rad($angle) {
$unit: unit($angle);
$unitless: $angle / ($angle * 0 + 1);
// If the angle has 'deg' as unit, convert to radians.
@if $unit == deg {
$unitless: $unitless / 180 * pi();
}
@return $unitless;
}
@function sin($angle) {
$sin: 0;
$angle: rad($angle);
// Iterate a bunch of times.
@for $i from 0 through 10 {
$sin: $sin + pow(-1, $i) * pow($angle, (2 * $i + 1)) / fact(2 * $i + 1);
}
@return $sin;
}
@function cos($angle) {
$cos: 0;
$angle: rad($angle);
// Iterate a bunch of times.
@for $i from 0 through 10 {
$cos: $cos + pow(-1, $i) * pow($angle, 2 * $i) / fact(2 * $i);
}
@return $cos;
}
@function tan($angle) {
@return sin($angle) / cos($angle);
} |
import { useState, useEffect } from 'react'
import Map from './components/map'
import Loader from './components/loader.js'
import Header from './components/header.js'
// This is the main component for out application
// This component will render other components
function App() {
const [eventData,setEventData] = useState([]);
const [loading,setLoading] = useState(false);
useEffect (() =>{
const fetchEvents = async ()=> {
setLoading(true);
const res = await fetch('https://eonet.gsfc.nasa.gov/api/v2.1/events')
const { events } = await res.json() //we are only interested in a specific array
setEventData(events);
setLoading(false); // now we are done loading
}
fetchEvents();
// console.log(eventData); debuging
},[]); // in react dev tools we will see the array of the corresponding data
// we want to have some sort of loader when fetching the data
return (
<div> {/*className is for react as we are in the npx style*/}
{!loading ?
<Map eventData={eventData} /> : <Loader />}
<Header />
</div>
);
}
export default App; |
(ns takeflight.pivotal
(:require clojure.xml
[takeflight.pivotal.xml :as xml]
[clj-time.core :as t]
[clj-time.coerce :refer [to-date from-date]]
[clj-http.client :as client])
(:import java.io.ByteArrayInputStream))
(def ^:private per-page 100)
(def ^:private api-url "https://www.pivotaltracker.com/services/v4")
(defn- project-url [id]
(str api-url "/projects/" id))
(defn- request
([method api-token project-id path]
(request method api-token project-id path {}))
([method api-token project-id path params]
(method (str (project-url project-id) path)
{:query-params params
:headers {"X-TrackerToken" api-token}
:as :pivotal-xml})))
(defn projects
[api-token]
(:projects (:body (request client/get api-token nil "/"))))
(defn project
[api-token project-id]
(:body (request client/get api-token project-id "/")))
(defn uncompleted-iterations
[api-token project-id]
(get-in (request client/get api-token project-id "/iterations/current_backlog")
[:body :iterations]))
(defn stories
([api-token project-id] (stories api-token project-id nil))
([api-token project-id filter]
(letfn [(get-page [page]
(lazy-seq
(let [offset (* per-page (dec page))
current-page (get-in
(request client/get
api-token
project-id
"/stories"
{:filter (str filter)
:limit per-page
:offset offset})
[:body :stories])]
(when (not-empty current-page)
(concat current-page (get-page (inc page)))))))]
(get-page 1))))
(defn backlog+current
[api-token project-id]
;; all states except unscheduled (icebox):
(stories api-token project-id "includedone:false state:unstarted,started,delivered,accepted,rejected"))
(defn unfinished-stories
[api-token project-id]
;; all states except unscheduled (icebox):
(stories api-token project-id "includedone:false state:unstarted,started"))
(defn releases
[api-token project-id]
(stories api-token project-id "type:release includedone:true"))
(defn- stories-from-iterations
[iterations]
(for [{:keys [stories] :as iteration} iterations
story stories
:let [iteration (dissoc iteration :stories)]]
(assoc story :iteration iteration)))
(defn- eta-calculator
[weeks-per-iteration
velocity
iteration-start-date
previous-points]
(let [days-per-iteration (* 7 weeks-per-iteration)
average-days-per-point (/ days-per-iteration velocity)
days-till-eta (Math/round (* average-days-per-point (float previous-points)))]
(to-date (t/plus (from-date iteration-start-date)
(t/days days-till-eta)))))
(defn- eta-annotator
[{velocity :current_velocity
weeks-per-iteration :iteration_length}]
(fn [{:keys [points releases] :as accum}
{type :story_type
deadline :deadline
{iteration-start :start iteration :number} :iteration
:as story}]
;; reset iteration points when iteration changes
(let [accum (if (not= iteration (:iteration accum))
(assoc accum :points 0 :iteration iteration)
accum)
estimate (:estimate story 0)]
(cond
;; estimated stories get added to the iteration points
(> estimate 0) (update-in accum [:points] + estimate)
;; Things with deadlines (currently only releases) have an
;; ETA calculated based on the previous points and velocity
deadline (let [eta (or (:accepted_at story)
(eta-calculator
weeks-per-iteration
velocity
iteration-start
(or points 0)))
release (assoc story :eta eta)]
(update-in accum [:releases] conj release))
:else accum))))
(defn releases+projections
[api-token project-id]
(let [project (project api-token project-id)
iterations (uncompleted-iterations api-token project-id)
stories (stories-from-iterations iterations)
cleanup #(-> %
(dissoc :iteration)
(assoc :project project))]
(map cleanup
(:releases
(reduce (eta-annotator project)
{:releases []}
stories))))) |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 20:07:41 2024
@author: sai
"""
######### inheritance in python
'''
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
'''
class vehicle:
def general_usage(self):
print("general use:transporatation")
class car(vehicle):
def __init__(self):
print("I am car")
self.wheels=4
self.has_roof=True
def specific_usage(self):
self.general_usage()
print("vacation with family")
class motorcycle(vehicle):
def __init__(self):
print("i am motorcycle")
self.wheel=2
self.has_roof=False
def specific_usage(self):
self.general_usage()
print("vacation with me only")
c=car()
m=motorcycle()
m.general_usage() #general use:transporatation
c.specific_usage()
#general use:transporatation
#vacation with family
m.specific_usage()
#general use:transporatation
#vacation with me only
print(issubclass(car, motorcycle)) #parameter - issubclass(subclass,superclass)
##############################################################################
#super class
class Person:
def __init__(self,name,age):
self.nm=name
self.ag=age
def myfunc(self):
print("my name",self.nm,"and my age is",self.ag)
class Student(Person):
def __init__(self,name,age):
super().__init__(name,age)
s=Student("ishwari",23)
s.myfunc()
#my name ishwari and my age is 23
##############################################################################
#multiple Inheritance
class Father:
def skills(self): #This is not constructor
print("I like gardening and programmimg")
class Mother:
def skills(self): #This is not constructor
print("I like cooking art")
class child(Father,Mother): #child class
def skills(self):
Father.skills(self)
Mother.skills(self)
print("I like sports")
c=child()
c.skills() |
import sys
import time
import datetime
import pytz
from collections import OrderedDict
from openpyxl import load_workbook
from openpyxl.styles import Font, Color
from openpyxl.styles import colors
from joblib import Parallel, delayed
import nflstatswrapper
from nflstatswrapper import nflstatswrapperfactory
from PlayerStats import PlayerStats
position_rows = {
"QB": [1,2],
"RB": [4,5,6],
"WR": [8,9,10,11],
"TE": [13]#,
#"K": [16],
#"DEF": [19]
}
class KickerStats(PlayerStats):
def __init__(self, statswrapper, player_cell, position, year, week):
super().__init__(statswrapper, player_cell, position, year, week)
self.fg30 = 0
self.fg40 = 0
self.fg50 = 0
self.fg60 = 0
if self.stats.kicking_fgm > 0:
for play in self.plays:
for p in play.players:
if p.kicking_fgm > 0 and p.playerid == self.player.playerid:
if p.kicking_fgm_yds >= 60:
self.fg60 += 1
elif p.kicking_fgm_yds >= 50:
self.fg50 += 1
elif p.kicking_fgm_yds >= 40:
self.fg40 += 1
else:
self.fg30 += 1
break
def print_to_file(self, player_scores):
#super(self.__class__, self).print_to_file(player_scores)
player_scores.write(",XP,0-39 FG,40-49 FG,50-59 FG,60+ FG\n")
player_scores.write(self.player_name)
player_scores.write(",")
player_scores.write(str(self.stats.kicking_xpmade))
player_scores.write(",")
player_scores.write(str(self.fg30))
player_scores.write(",")
player_scores.write(str(self.fg40))
player_scores.write(",")
player_scores.write(str(self.fg50))
player_scores.write(",")
player_scores.write(str(self.fg60))
player_scores.write('\n')
def print_to_spreadsheet(self, player_sheet, year, week):
player_row = player_sheet[self.player_cell.row]
self.update_cell_color(player_row, self.player.team, year, week)
self.print_value_to_spreadsheet(player_row, 1, self.stats.kicking_xpmade)
self.print_value_to_spreadsheet(player_row, 2, self.fg30)
self.print_value_to_spreadsheet(player_row, 3, self.fg40)
self.print_value_to_spreadsheet(player_row, 4, self.fg50)
self.print_value_to_spreadsheet(player_row, 5, self.fg60)
class DefenseStats(PlayerStats):
def __init__(self, statswrapper, player_cell, year, week):
print(player_cell.value)
self.statswrapper = statswrapper
self.player_cell = player_cell
self.print_name = player_cell.value
self.official_name = statswrapper.get_standard_team_name(self.print_name)
self.sacks = 0
self.int = 0
self.fumbles_rec = 0
self.safeties = 0
self.dst_tds = 0
self.two_pts = 0
self.pts_allowed = -1
self.game = self.statswrapper.find_game(self.official_name, year, week)
if self.game is None or self.game == '' or not (self.game.playing() or self.game.game_over()):
print('No game in progress for ' + self.print_name)
return
else:
if self.game.home == self.official_name:
self.pts_allowed = self.game.score_away
elif self.game.away == self.official_name:
self.pts_allowed = self.game.score_home
else:
raise "Team not found in game!"
for drive in self.game.drives:
if drive.team != self.official_name and 'Safety' in drive.result:
self.safeties += 1
for play in drive.plays:
for event in play.events:
if event["team"] == self.official_name and "defense_tds" in event:
self.dst_tds += event["defense_tds"]
if event["team"] == self.official_name and "defense_frec" in event:
self.fumbles_rec += event["defense_frec"]
plays = self.statswrapper.get_game_plays(self.game)
for play in plays:
if play.team == self.official_name:
self.sacks += play.defense_sk
self.int += play.defense_int
self.dst_tds += play.kickret_tds
self.dst_tds += play.puntret_tds
def print_to_file(self, player_scores):
player_scores.write(",Sacks,INT,FR,SFT,TD,Shutout,0-6,7-13.,14-19,20-29,30-39,40-49,50+\n")
player_scores.write(self.print_name)
player_scores.write(",")
player_scores.write(str(self.sacks))
player_scores.write(",")
player_scores.write(str(self.int))
player_scores.write(",")
player_scores.write(str(self.fumbles_rec))
player_scores.write(",")
player_scores.write(str(self.safeties))
player_scores.write(",")
player_scores.write(str(self.dst_tds))
player_scores.write(",")
if (self.pts_allowed == 0):
player_scores.write(str("1"))
player_scores.write(str(","))
if (self.pts_allowed > 0 and self.pts_allowed <= 6):
player_scores.write(str("1"))
player_scores.write(str(","))
if (self.pts_allowed > 6 and self.pts_allowed <= 13):
player_scores.write(str("1"))
player_scores.write(str(","))
if (self.pts_allowed > 13 and self.pts_allowed <= 19):
player_scores.write(str("1"))
player_scores.write(str(","))
if (self.pts_allowed > 19 and self.pts_allowed <= 29):
player_scores.write(str("1"))
player_scores.write(str(","))
if (self.pts_allowed > 29 and self.pts_allowed <= 39):
player_scores.write(str("1"))
player_scores.write(str(","))
if (self.pts_allowed > 39 and self.pts_allowed <= 49):
player_scores.write(str("1"))
player_scores.write(str(","))
if (self.pts_allowed >= 50):
player_scores.write("1")
player_scores.write('\n')
def print_to_spreadsheet(self, player_sheet, year, week):
player_row = player_sheet[self.player_cell.row]
self.update_cell_color(player_row, self.print_name, year, week)
self.print_value_to_spreadsheet(player_row, 1, self.sacks)
self.print_value_to_spreadsheet(player_row, 2, self.int)
self.print_value_to_spreadsheet(player_row, 3, self.fumbles_rec)
self.print_value_to_spreadsheet(player_row, 4, self.safeties)
self.print_value_to_spreadsheet(player_row, 5, self.dst_tds)
if self.game is not None and self.game != '' and (self.game.playing() or self.game.game_over()):
if (self.pts_allowed == 0):
self.print_value_to_spreadsheet(player_row, 6, 1)
elif (self.pts_allowed > 0 and self.pts_allowed <= 6):
self.print_value_to_spreadsheet(player_row, 7, 1)
elif (self.pts_allowed > 6 and self.pts_allowed <= 13):
self.print_value_to_spreadsheet(player_row, 8, 1)
elif (self.pts_allowed > 13 and self.pts_allowed <= 19):
self.print_value_to_spreadsheet(player_row, 9, 1)
elif (self.pts_allowed > 19 and self.pts_allowed <= 29):
self.print_value_to_spreadsheet(player_row, 10, 1)
elif (self.pts_allowed > 29 and self.pts_allowed <= 39):
self.print_value_to_spreadsheet(player_row, 11, 1)
elif (self.pts_allowed > 39 and self.pts_allowed <= 49):
self.print_value_to_spreadsheet(player_row, 12, 1)
elif (self.pts_allowed >= 50):
self.print_value_to_spreadsheet(player_row, 13, 1)
class Team:
def __init__(self, statswrapper, team_name, player_columns, year, week):
self.team_name = team_name
self.player_columns = []
self.player_index = OrderedDict()
for player_cell, position in player_columns:
self.player_columns.append(player_cell)
if position == "DEF":
defense = DefenseStats(statswrapper, player_cell, year, week)
self.player_index[0] = defense
elif position == "K":
kicker = KickerStats(statswrapper, player_cell, position, year, week)
self.player_index[kicker.player.playerid] = kicker
else:
player = PlayerStats(statswrapper, player_cell, position, year, week)
self.player_index[player.player.playerid] = player
for playerid, player in self.player_index.items():
if not isinstance(player, DefenseStats) and player.stats.receiving_tds > 0:
for play in player.plays:
if play.receiving_tds > 0:
for p in play.players:
if p.passing_tds > 0 and p.playerid != playerid and p.playerid in self.player_index.keys():
player.hookup_tds += 1
self.player_index[p.playerid].hookup_tds += 1
break
def print_players(self, player_scores):
for index, player in enumerate(self.player_index.values()):
player.print_to_file(player_scores)
if index == 1 or index == 4 or index == 8 or index == 9 or index == 10:
player_scores.write("\n")
def print_to_spreadsheet(self, roster_book, year, week):
team_sheet = roster_book[self.team_name]
for row_num, player_cell in enumerate(self.player_columns):
if row_num != 14 and row_num != 17:
player_row = team_sheet[player_cell.row]
for col in range(1, 17):
player_row[col].value = None
for player in self.player_index.values():
player.print_to_spreadsheet(team_sheet, year, week)
def calculate_scores(statswrapper, team_name, team_col, year, week):
print("****" + team_name + "****")
players = []
for position in position_rows:
for row_num in position_rows[position]:
if team_col[row_num].value is not None:
players.append((team_col[row_num], position))
team = Team(statswrapper, team_name, players, year, week)
return team
if __name__ == '__main__':
team_names = set(['Don', 'Dean', 'Joe', 'Marc', 'Josh', 'Michael', 'Pat', 'Nick'])
filename = 'Rosters.xlsx'
#team_names = set(['Joe'])
#if len(sys.argv) > 1:
# if sys.argv[1] == '-co':
# team_names = set(['Marc', 'Josh'])
# filename = 'Rosters_autoScored.xlsx'
access_token = None
if (len(sys.argv) > 1):
access_token = {'access_token': sys.argv[1]}
statswrapper = nflstatswrapperfactory.nflstatswrapperfactory.create(nflstatswrapperfactory.nflstatswrapperfactory.nflapi, access_token)
if (len(sys.argv) == 3):
year = int(sys.argv[1])
week = int(sys.argv[2])
else:
(year, week) = statswrapper.current_year_and_week()
print("Scores for {0} Week {1}".format(str(year), str(week)))
roster_book = load_workbook('C:\\Users\\joshw\\OneDrive\\WKFFL\\\\' + filename)
roster_sheet = roster_book['Cap']
sheet_ranges = {
'Don': roster_sheet['B'],
'Dean': roster_sheet['D'],
'Joe': roster_sheet['F'],
'Marc': roster_sheet['H'],
'Josh': roster_sheet['J'],
'Michael': roster_sheet['L'],
'Pat': roster_sheet['N'],
'Nick': roster_sheet['P'],
}
#teams = Parallel(n_jobs=2, backend="threading")(delayed(calculate_scores)(team_name, team_col, year, week) for team_name, team_col in sheet_ranges.items() if team_name in team_names)
teams = [calculate_scores(statswrapper, team_name, team_col, year, week) for team_name, team_col in sheet_ranges.items() if team_name in team_names]
for team in teams:
team.print_to_spreadsheet(roster_book, year, week)
now_time = datetime.datetime.utcnow()
eastern = pytz.timezone('US/Eastern')
time_format_string = 'Last updated: %I:%M %p %a %b %d %Y EST'
#if len(team_names) == 2:
# time_value += ' (Championship Only)'
roster_book['Cap']['A29'].value = pytz.utc.localize(now_time).astimezone(eastern).strftime(time_format_string)
roster_book.save('C:\\Users\\joshw\\Desktop\\Rosters_autoScored.xlsx') |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetcaster.util
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
/**
* Returns a [ViewModelProvider.Factory] which will return the result of [create] when it's
* [ViewModelProvider.Factory.create] function is called.
*
* If the created [ViewModel] does not match the requested class, an [IllegalArgumentException]
* exception is thrown.
*/
inline fun <reified VM : ViewModel> viewModelProviderFactoryOf(
crossinline create: () -> VM
): ViewModelProvider.Factory = viewModelFactory {
initializer {
create()
}
} |
import classNames from "classnames";
import React, { useEffect, useState } from "react";
import Container from "../../layout/Container";
import classes from "./Form.module.scss";
import {
validateName,
validatePhoneContent,
valiDatePhoneNumber,
validateText,
} from "./helper";
const initialData = {
name: "",
tel: "",
text: "",
};
const Form = () => {
const [fields, setFields] = useState(initialData);
const [disabled, setDisabled] = useState(true);
useEffect(() => {
const isValid =
validateName(fields.name) &&
validateText(fields.text) &&
valiDatePhoneNumber(fields.tel);
setDisabled(!isValid);
}, [fields]);
const setValue = (event) => {
if (
event.target.name === "tel" &&
!validatePhoneContent(event.target.value)
)
return;
setFields((prev) => ({ ...prev, [event.target.name]: event.target.value }));
};
const handleSubmit = (event) => {
event.preventDefault();
setFields(initialData);
};
return (
<Container className={classes["container"]}>
<form className={classes["form"]}>
<div className={classes["form__block"]}>
<input
onChange={setValue}
value={fields.name}
name="name"
className={classes["form__input"]}
type="text"
placeholder="Your Name*"
/>
<input
onChange={setValue}
value={fields.tel}
type="tel"
name="tel"
className={classes["form__input"]}
placeholder="Your Number*"
/>
</div>
<textarea
name="text"
onChange={setValue}
value={fields.text}
className={classes["form__text"]}
placeholder="Your Ideas*"
></textarea>
<button
onClick={handleSubmit}
className={classNames(classes["form__button"], {
[classes["form__button_disabled"]]: disabled,
})}
disabled={disabled}
>
send
</button>
</form>
</Container>
);
};
export default Form; |
---
description: 阶段映射的最佳实践 — [!DNL Marketo Measure]
title: 阶段映射的最佳实践
exl-id: 1ed380a1-4a3a-4761-b70f-cdf2e290329d
feature: Tracking, Custom Models
source-git-commit: 1a274c83814f4d729053bb36548ee544b973dff5
workflow-type: tm+mt
source-wordcount: '479'
ht-degree: 0%
---
# 阶段映射的最佳实践 {#best-practices-for-stage-mapping}
## 概述 {#overview}
的Stage Mapping部分 [!DNL Marketo Measure] 帐户概述了以下阶段 [!DNL Marketo Measure] 如果使用自定义归因模型,则会自动从您的CRM和您定义的任何自定义阶段拉取。 您的的有效性 [!DNL Marketo Measure] 数据依赖于这些阶段的正确排序,以便 [!DNL Marketo Measure] 可以准确地了解漏斗以及整个漏斗中记录的进度。
在的“阶段映射”部分中 [!DNL Marketo Measure] 实例中,您将看到CRM中的活动阶段和非活动阶段。 根据您当前的漏斗情况,尽您所能地对所有阶段进行排序。
本节中管理的附加功能是漏斗暂存,它使您能够在不应用归因的情况下向漏斗添加暂存。 漏斗阶段将作为接触点进行跟踪,并将填充到您CRM的接触点位置字段中。 这些漏斗阶段还将在的各个历程展示板中呈现 [!DNL Marketo Measure] 发现。
## 最佳实践 {#best-practices}
无论您是首次评估暂存映射,还是只查看漏斗顺序,请务必牢记以下最佳实践。
* 秩序就是一切!
* 考虑 [!DNL Marketo Measure] 从CRM中提取活动和非活动阶段,确认任何可用于Lead/Contact或Opportunity的阶段都分组在一起并相应地排序
* 定义自定义阶段时,请确保为用于定义阶段的任何字段启用字段历史记录跟踪
* 不要使用公式字段定义自定义阶段
* 布尔字段是最佳实践推荐
* 请注意,“潜在客户”或“联系人”阶段部分分为“丢失”、“打开”和“已转换”;验证阶段是否位于其相应的阶段部分
* 在不正确的阶段分区中设置阶段可能会导致高度不正确 [!DNL Marketo Measure] 数据
* 如果您是Marketo Measure Ultimate客户并将您的默认功能板对象设置为Contact,请不要使用下面两个特定于Lead的字段([了解详情](/help/marketo-measure-ultimate/data-integrity-requirement.md){target="_blank"})。
* b2b.personStatus
* b2b.isConverted
* 请注意, Opportunity阶段部分分为Lost 、 Open和Won ;验证阶段是否位于其相应的阶段部分
* 在不正确的阶段分区中设置阶段可能会导致高度不正确 [!DNL Marketo Measure] 收入或管道收入数据
* 避免使用重复的阶段名称(我们的系统将检测到它们并自动删除一个)。
* 要设置检查NULL值的规则,请将值文本框留空。
## 维护的最佳实践 {#best-practices-for-maintenance}
每年审查一次您的阶段映射,将确保您的Opportunity数据位于 [!DNL Marketo Measure] 准确且为最新。
可能触发阶段映射审阅的其他原因包括……
* 您的营销团队中的人员调整
* 对CRM阶段所做的任何更改
* 组织漏斗的更新
* 在中看到不正确的收入数据 [!DNL Marketo Measure] 报告
>[!MORELIKETHIS]
>
>[漏斗阶段和自定义模型阶段之间的区别](/help/advanced-marketo-measure-features/custom-attribution-models/custom-attribution-model-and-setup.md#the-difference-between-funnel-stages-and-custom-model-stages) |
import { useState } from 'react';
import { ExpensiveComponent } from '../../toolbox/components/ExpensiveComponent.jsx';
import { useOnRenderStyle } from '../../toolbox/hooks/useOnRenderStyle.jsx';
const ScrollComponent = ({ topChildren, children }) => {
const [scroll, setScroll] = useState(0);
return (
<div
style={{ overflowY: 'scroll', height: '500px', paddingTop: '200px' }}
onScroll={(e) => {
setScroll(e.target.scrollTop);
}}
>
<div style={{ height: '800px' }}>
{topChildren}
<p style={{ width: 'fit-content' }}>Hey, you scroll {scroll}</p>
{children}
</div>
</div>
);
};
const SmallComponentTop = () => {
const ref = useOnRenderStyle();
return (
<div ref={ref} style={{ width: '100px', height: '100px' }}>
SmallComponentLeft
</div>
);
};
const App = () => {
return (
<div>
<ScrollComponent topChildren={<SmallComponentTop />}>
<ExpensiveComponent />
</ScrollComponent>
</div>
);
};
export default App; |
/**
* test-utils.ts
*
* Copyright (c) 2017 by General Electric Company. All rights reserved.
*
* The copyright to the computer software herein is the property of
* General Electric Company. The software may be used and/or copied only
* with the written permission of General Electric Company or in accordance
* with the terms and conditions stipulated in the agreement/contract
* under which the software has been supplied.
*
* Created by 212367790 on 6/27/17.
*/
declare global {
interface Window {
GEHC: any;
}
}
import { DebugElement, SimpleChange, getDebugNode } from '@angular/core';
import { GlobalTracking } from '@gehc-ux/eds-core/src/app/components/core/tracking-global';
GlobalTracking.initGlobal();
window.GEHC.EDS.trackingPrefs.trackUsage = false;
// Helper class to use in unit test specs
export class EDSTestUtil {
/**
* @function: getCssStyle
* @description: function that returns the value of property in the element
* @param: element
* @param: property
**/
getCssStyle(element: DebugElement, property: string, pseudoElement?: string): string {
return getComputedStyle(element.nativeElement, pseudoElement).getPropertyValue(property);
}
/**
* @function: getElementAttribute
* @description: function that returns the value of an attribute in the element
* @param: element
* @param: attribute
**/
getElementAttribute(element: DebugElement, attr: string): string {
return element.nativeElement.getAttribute(attr);
}
/**
* @function: getRGBValue
* @description: function that returns the RGB value of property in the element
* @param: element
* @param: property
**/
getRGBValue(element: DebugElement, property: string, pseudoElement?: string): string {
let rgbValue;
const rgbParts = this.getRGBParts(element, property, pseudoElement);
if (rgbParts.length >= 3) {
rgbValue = rgbParts[0] + ',' + rgbParts[1] + ',' + rgbParts[2];
}
return rgbValue;
}
/**
* @function: getOpacityValue
* @description: function that returns the opacity value of property in the element
* @param: element
* @param: property
**/
getOpacityValue(element: DebugElement, property: string, pseudoElement?: string): string {
let opacity;
const rgbParts = this.getRGBParts(element, property, pseudoElement);
opacity = rgbParts.length >= 3 ? rgbParts[3] : '';
return opacity.trim();
}
/**
* @function: getRGBParts
* @description: function that returns RGB parts of property in the element
* @param: element
* @param: property
**/
private getRGBParts(element: DebugElement, property: string, pseudoElement?: string) {
const rgbString = getComputedStyle(element.nativeElement, pseudoElement).getPropertyValue(property),
startIndex = rgbString.indexOf('('),
endIndex = rgbString.indexOf(')'),
rgbvalue = rgbString.substr(startIndex + 1, (endIndex - startIndex - 1)),
rgbParts = rgbvalue.split(',');
return rgbParts;
}
/**
* Triggers a set of changes on an angular component
* @param component the angular component
* @param inputs a set of object with the following format:
* {
* propertyName: {prev: previousValue, current: currentValue, firstChange: true/false}
* }
*/
triggerNgOnChanges(component: any, inputs: any) {
const changes = {};
Object.keys(inputs).forEach(key => {
// build change object to trigger ngOnchanges later
changes[key] = new SimpleChange(inputs[key].prev, inputs[key].current, inputs[key].firstChange);
// actually change value
component[key] = inputs[key].current;
});
component['ngOnChanges'](changes);
}
/**
* Fires a keyup event on an element
*/
fireKeyupEvent = function(elem, key) {
const evt = new CustomEvent('keyup', {detail: {'key': key, 'keyIdentifier': key}});
elem.dispatchEvent(evt);
};
/**
* Switches theme by calling function on the window object
* * @param theme: either 'eds-lights-on' or 'eds-lights-off'
*/
switchTheme = function(theme: string) {
if (window['GEHC']['EDS']['theme']['setTheme']) {
window['GEHC']['EDS']['theme']['setTheme'](theme);
} else {
console.error('setTheme is not found on the window.GEHC.EDS object.');
}
};
/**
* Returns the component instance that is nested within shadow roots of
* the given shadowRoot.
* Given a starting shadow root, navigate down a nested tree of query selectors
* to get to the component instance of the last element in the nestedTree
* @param shadowRoot: ShadowRoot top level shadow root to begin navigation
* @param nestedTree: string[] Array of strings that are valid query selectors
* that represents the hierarchy of nested shadow dom elements.
*/
getNestedComponentInstance = (shadowRoot: ShadowRoot, nestedTree: string[]): any => {
let debugElement: DebugElement;
function getDebugElementFromShadowRoot(_shadowRoot: ShadowRoot, selectorIndex: number): DebugElement {
let nativeElement: Element;
if (selectorIndex === nestedTree.length) {
return debugElement;
} else {
nativeElement = _shadowRoot.querySelector(nestedTree[selectorIndex]);
debugElement = <DebugElement>( getDebugNode(nativeElement) );
return getDebugElementFromShadowRoot(debugElement.nativeElement.shadowRoot, ++selectorIndex);
}
}
return getDebugElementFromShadowRoot(shadowRoot, 0).componentInstance;
}
} |
---
title: Storing and restoring temp body in 3rd party storage using SOLIDWORKS API
caption: Store And Restore Body
description: Storing the temp body in the SOLIDWORKS document stream via 3rd party storage and restoring it on opening using SOLIDWORKS API
image: restored-body.png
labels: [3rd party storage,store body,restore body]
---
这个VBA示例演示了如何将所选实体的副本存储在新文档的流中,并在模型打开时恢复和显示该实体。
实体通过[第三方存储](/solidworks-api/data-storage/third-party/)进行序列化和反序列化。
* 创建新的宏并添加新的窗体。将其命名为*UserForm1*(默认名称)
* 添加按钮。如下图所示,指定标题为*存储实体*,名称为*cmdStoreBody*
{ width=450 }
* 将以下代码粘贴到用户窗体的代码后面:
~~~ vb
Const BODY_STREAM_NAME = "_CodeStackBody_"
Dim WithEvents swApp As SldWorks.SldWorks
Dim swModeler As SldWorks.Modeler
Dim WithEvents swCurPart As SldWorks.PartDoc
Dim swCurBody As SldWorks.Body2
Private Sub UserForm_Initialize()
Set swApp = Application.SldWorks
Set swModeler = swApp.GetModeler
End Sub
Private Function swApp_DocumentLoadNotify(ByVal docTitle As String, ByVal docPath As String) As Long
If docPath <> "" Then
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.GetOpenDocumentByName(docPath)
If TypeOf swModel Is SldWorks.PartDoc Then
Set swCurPart = swModel
End If
End If
End Function
Private Function swCurPart_LoadFromStorageNotify() As Long
DisplayBodyFromStream
swCurPart_LoadFromStorageNotify = 0
End Function
Private Function swCurPart_SaveToStorageNotify() As Long
If Not swCurBody Is Nothing Then
StoreBodyToStream
MsgBox "Body is stored to the model stream. Close and reopen the model to restore the body"
End If
swCurPart_SaveToStorageNotify = 0
End Function
Private Sub cmdStoreBody_Click()
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.ActiveDoc
Dim swSelMgr As SldWorks.SelectionMgr
Set swSelMgr = swModel.SelectionManager
Set swCurBody = swSelMgr.GetSelectedObject6(1, -1)
If Not swCurBody Is Nothing Then
Set swCurBody = swCurBody.Copy
Dim partTemplate As String
partTemplate = swApp.GetUserPreferenceStringValue(swUserPreferenceStringValue_e.swDefaultTemplatePart)
Set swCurPart = swApp.NewDocument(partTemplate, swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0)
MsgBox "Save this document to store the body in its stream"
Else
MsgBox "Please select body"
End If
End Sub
Sub DisplayBodyFromStream()
Dim swModel As SldWorks.ModelDoc2
Set swModel = swCurPart
Dim swStream As Variant
Set swStream = swModel.IGet3rdPartyStorage(BODY_STREAM_NAME, False)
If Not swStream Is Nothing Then
Set swCurBody = swModeler.Restore(swStream)
swModel.IRelease3rdPartyStorage BODY_STREAM_NAME
swCurBody.Display3 swModel, RGB(255, 255, 0), swTempBodySelectOptions_e.swTempBodySelectable
End If
End Sub
Sub StoreBodyToStream()
Dim swModel As SldWorks.ModelDoc2
Set swModel = swCurPart
Dim swStream As Variant
Set swStream = swModel.IGet3rdPartyStorage(BODY_STREAM_NAME, True)
swCurBody.Save swStream
swModel.IRelease3rdPartyStorage BODY_STREAM_NAME
End Sub
~~~
* 将以下代码插入到宏的主模块中:
~~~ vb
Sub main()
UserForm1.Show vbModeless
End Sub
~~~
## 运行宏
* 从主模块启动宏。注意,如果在宏编辑器中激活窗体时运行宏,窗体将显示为模态窗口,并阻止选择和保存操作。
* 打开任何带有任意几何图形的零件文档
* 从树中选择实体,并在用户窗体中点击*存储实体*
* 创建新的零件文档,并显示以下消息:*保存此文档以将实体存储在其流中*
* 保存此文件。在保存文件时,来自不同零件的实体被序列化到新文档的流中,并且不再与原始实体相关联。
* 完成后,显示以下消息:*实体已存储到模型流中。关闭并重新打开模型以恢复实体*
* 现在,关闭所有文档并重新打开最后保存的文件。实体将被反序列化并显示出来。请注意,模型中没有特征树。
{ width=350 }
* 您可以关闭SOLIDWORKS会话并重新打开模型。实体仍将被加载。请注意,在打开模型之前,您需要运行宏。 |
## [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/#/description)
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
```c
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(0);
ListNode* node = head;
while (l1 && l2) {
if (l1->val < l2->val) {
node->next = l1;
l1 = l1->next;
} else {
node->next = l2;
l2 = l2->next;
}
node = node->next;
}
node->next = (l1) ? l1 : l2;
return head->next;
}
};
``` |
#######################################################
# Parliament diagrams. #
#-----------------------------------------------------#
# Author: < Mingjie Wang > from < Ke Yan Mao > #
# Affiliation: Shanghai Hiplot Team #
# Email: customer_service1501@tengyunbio.com #
# Website: hiplot.org #
# #
# Date: 2019-11-28 #
# Version: 0.1 #
#######################################################
# CAUTION #
#-----------------------------------------------------#
# Copyright (C) 2020 by Hiplot Team #
# All rights reserved. #
#######################################################
pkgs <- c("ggpol", "ggplot2")
pacman::p_load(pkgs, character.only = TRUE)
############# Section 1 ##########################
# input options, data and configuration section
##################################################
{
usr_group <- colnames(data)[1]
colnames(data) <- c("group", "value")
}
############# Section 2 #############
# plot section
#####################################
{
# plot
p <- ggplot(data) +
geom_parliament(
alpha = conf$general$alpha,
aes(seats = value, fill = group), color = "black"
) +
coord_fixed() +
theme_void() +
scale_fill_discrete(
name = usr_group,
labels = unique(data$group)
) +
theme(legend.position = "bottom") +
ggtitle(conf$general$title) +
theme(plot.title = element_text(hjust = 0.5))
## add color palette
p <- p + return_hiplot_palette_color(conf$general$palette,
conf$general$paletteCustom) +
return_hiplot_palette(conf$general$palette,
conf$general$paletteCustom)
theme <- conf$general$theme
p <- choose_ggplot_theme(p, theme)
}
############# Section 3 #############
# output section
#####################################
{
export_single(p)
} |
import 'package:faker/faker.dart';
import 'package:nakama/nakama.dart';
import 'package:test/test.dart';
import '../config.dart';
void main() {
group('[REST] Test Account', () {
late final NakamaBaseClient client;
late final Session session;
setUpAll(() async {
client = NakamaRestApiClient.init(
host: kTestHost,
ssl: false,
serverKey: kTestServerKey,
);
session = await client.authenticateDevice(deviceId: faker.guid.guid());
});
test('fetching my account', () async {
final account = await client.getAccount(session);
expect(account, isA<Account>());
});
test('fetch another\'s account', () async {
// create another dummy user
final anotherUser = await client.authenticateDevice(
deviceId: faker.guid.guid(),
);
// fetch this user
final users = await client.getUsers(
session: session,
ids: [anotherUser.userId],
);
expect(users, isA<List<User>>());
expect(users, hasLength(1));
});
test('updating my account', () async {
await client.updateAccount(session: session, displayName: 'name');
});
});
} |
import java.math.BigInteger;
public class MersennePrimes {
public static void main(String[] args) {
BigInteger two = BigInteger.valueOf(2);
for (int p = 2; p <= 100; p++) {
BigInteger mersenne = two.pow(p).subtract(BigInteger.ONE);
if (isPrime(mersenne)) {
System.out.printf("M%d is prime%n", p);
}
}
}
public static boolean isPrime(BigInteger n) {
if (n.compareTo(BigInteger.ONE) <= 0) {
return false;
}
if (n.compareTo(BigInteger.TWO) == 0) {
return true;
}
if (n.mod(BigInteger.TWO).equals(BigInteger.ZERO)) {
return false;
}
BigInteger sqrt = n.sqrt();
for (BigInteger i = BigInteger.valueOf(3); i.compareTo(sqrt) <= 0; i = i.add(BigInteger.TWO)) {
if (n.mod(i).equals(BigInteger.ZERO)) {
return false;
}
}
return true;
}
} |
import React, { useState, useEffect } from "react";
import { View, TouchableOpacity, TextInput, Text, Image } from "react-native";
import "react-native-gesture-handler";
import styles from "./Style";
import { connect } from "react-redux";
import { useNavigation } from "@react-navigation/native";
import {
getloginAction,
logoutAction,
checkvalidateAction,
} from "../redux/actions";
const SignIn = (props: any) => {
const navigation = useNavigation();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const url = "https://dog.ceo/api/breeds/image/random";
const error_message = props.loginReducer.errorMessage;
const storeData = async () => {
if (email != "" && password != "") {
let datasend = { email: email, password: password };
await props.login(datasend);
await navigation.navigate("Details");
} else {
let datasend = { email: email, password: password };
await props.checkvalidate(datasend);
console.log("Email or Password is empty.");
}
};
return (
<View style={styles.container}>
<Image
style={styles.tinyLogo}
source={{
uri: "https://assets-ng.rehome-navi.com/lp_assets/regist/images/logo.png",
}}
/>
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Email"
placeholderTextColor="#003f5c"
onChangeText={(email) => setEmail(email)}
/>
</View>
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Password"
placeholderTextColor="#003f5c"
secureTextEntry={true}
onChangeText={(password) => setPassword(password)}
/>
</View>
<Text style={styles.errorMessage}>{error_message}</Text>
<TouchableOpacity style={styles.loginBtn} onPress={storeData}>
<Text style={styles.loginText}>LOGIN</Text>
</TouchableOpacity>
</View>
);
};
const mapStateToProps = (reducer: any) => ({
loginReducer: reducer.loginReducer,
});
const mapDispatchToProps = (dispatch: Function) => ({
login: getloginAction(dispatch),
logout: logoutAction(dispatch),
checkvalidate: checkvalidateAction(dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(SignIn); |
syntax = "proto3";
package generate.v1;
service TextGenerationService {
/// Model Info
rpc Info (InfoRequest) returns (InfoResponse) {}
/// Service discovery
rpc ServiceDiscovery (ServiceDiscoveryRequest) returns (ServiceDiscoveryResponse) {}
/// Empties batch cache
rpc ClearCache (ClearCacheRequest) returns (ClearCacheResponse);
/// Remove requests from a cached batch
rpc FilterBatch (FilterBatchRequest) returns (FilterBatchResponse);
/// Warmup the model and compute max cache size
rpc Warmup (WarmupRequest) returns (WarmupResponse);
/// Prefill batch and decode first token
rpc Prefill (PrefillRequest) returns (PrefillResponse);
/// Decode token for a list of prefilled batches
rpc Decode (DecodeRequest) returns (DecodeResponse);
/// Health check
rpc Health (HealthRequest) returns (HealthResponse);
}
message HealthRequest {}
message HealthResponse {}
/// Empty request
message InfoRequest {}
message InfoResponse {
bool requires_padding = 1;
string dtype = 2;
string device_type = 3;
}
/// Empty request
message ServiceDiscoveryRequest {}
message ServiceDiscoveryResponse {
/// Other shards urls
repeated string urls = 1;
}
message ClearCacheRequest {
/// Optional batch id
optional uint64 id = 1;
}
/// Empty response
message ClearCacheResponse {}
message NextTokenChooserParameters {
/// exponential scaling output probability distribution
float temperature = 1;
/// restricting to the k highest probability elements
uint32 top_k = 2;
/// restricting to top tokens summing to prob_cut_off <= prob_cut_off
float top_p = 3;
/// restricting to top tokens summing to prob_cut_off <= prob_cut_off
float typical_p = 4;
/// apply sampling on the logits
bool do_sample = 5;
/// random seed for sampling
uint64 seed = 6;
/// repetition penalty
float repetition_penalty = 7;
/// token watermarking using "A Watermark for Large Language Models"
bool watermark = 8;
}
message StoppingCriteriaParameters {
/// Maximum number of generated tokens
uint32 max_new_tokens = 1;
/// Optional stopping sequences
repeated string stop_sequences = 2;
/// Ignore end of sequence token
/// used for benchmarking
bool ignore_eos_token = 3;
}
message Request {
/// Request ID
uint64 id = 1;
/// The generation context
string inputs = 2;
/// Context truncation
uint32 truncate = 3;
/// Next Token Chooser Parameters
NextTokenChooserParameters parameters = 4;
/// Stopping Criteria Parameters
StoppingCriteriaParameters stopping_parameters = 5;
/// Return prefill logprobs
bool prefill_logprobs = 6;
}
message Batch {
/// Batch ID
uint64 id = 1;
/// Individual requests
repeated Request requests = 2;
/// Batch size (==len(requests))
uint32 size = 3;
/// Maximum number of tokens this batch will grow to
uint32 max_tokens = 4;
}
message CachedBatch {
/// Batch ID
uint64 id = 1;
/// Individual requests ids
repeated uint64 request_ids = 2;
/// Batch size (==len(requests))
uint32 size = 3;
/// Maximum number of tokens this batch will grow to
uint32 max_tokens = 4;
}
enum FinishReason {
FINISH_REASON_LENGTH = 0;
FINISH_REASON_EOS_TOKEN = 1;
FINISH_REASON_STOP_SEQUENCE = 2;
}
message GeneratedText {
/// Output
string text = 1;
/// Number of generated tokens
uint32 generated_tokens = 2;
/// Finish reason
FinishReason finish_reason = 3;
/// Seed
optional uint64 seed = 4;
}
message PrefillTokens {
/// Prefill Token IDs
repeated uint32 ids = 1;
/// Prefill Logprobs
repeated float logprobs = 2;
/// Prefill tokens
repeated string texts = 3;
}
message Generation {
/// Request ID
uint64 request_id = 1;
/// Prefill tokens (optional)
PrefillTokens prefill_tokens = 2;
/// Token ID
uint32 token_id = 3;
/// Logprob
float token_logprob = 4;
/// Text
string token_text = 5;
/// Is it a special token
bool token_is_special = 6;
/// Complete generated text
optional GeneratedText generated_text = 7;
}
message FilterBatchRequest {
/// Batch ID
uint64 batch_id = 1;
/// Requests to keep
repeated uint64 request_ids = 2;
}
message FilterBatchResponse {
/// Filtered Batch (cached)
CachedBatch batch = 1;
}
message PrefillRequest {
/// Batch
Batch batch = 1;
}
message PrefillResponse {
/// Generation
repeated Generation generations = 1;
/// Next batch (cached)
optional CachedBatch batch = 2;
}
message DecodeRequest {
/// Cached batches
repeated CachedBatch batches = 1;
}
message DecodeResponse {
/// Decodes
repeated Generation generations = 1;
/// Next batch (cached)
optional CachedBatch batch = 2;
}
message WarmupRequest {
/// Batch to warmup on
Batch batch = 1;
}
/// Empty response
message WarmupResponse {
/// Maximum number of tokens supported by the model
optional uint32 max_supported_total_tokens = 1;
} |
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
@test
@bug 6479820
@summary verify that after Alt+Space resizing/moving the correct event gets generated.
@author Andrei Dmitriev: area=awt.event
@run main/manual SpuriousExitEnter_2
*/
/**
* SpuriousExitEnter_2.java
* There is a JFrame with a JButton in it (Lightweight) and a Frame with a Button in it (Heavyweight).
* Testcases diveded into two similar activities: first with JFrame and second with Frame.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SpuriousExitEnter_2 {
static JFrame frame = new JFrame("SpuriousExitEnter_2(LW)");
static JButton jbutton = new JButton("jbutton");
static Frame frame1 = new Frame("SpuriousExitEnter_2 (HW)");
static Button button1 = new Button("button");
private static void init() {
String[] instructions =
{
"You see a plain JFrame with JButton in it and Frame with Button in it.",
" Following steps should be accomplished for both of them (for Frame and for JFrame).",
" If any of the following ",
" third steps fails, press Fail.",
" Let A area is the area inside Button.",
" Let B area is the area inside Frame but not inside Button.",
" Let C area is the area outside Frame.",
" Stage 1:",
" 1) Put the mouse pointer into A area.",
" 2) Press Alt+Space (or other sequence opening the system menu from the top-left corner) ",
" and resize the Frame so the pointer remains in A.",
" 3) Press Enter key. No event should be fired.",
" Stage 2:",
" Repeat Stage 1 with area B.",
" Stage 3:",
" Repeat Stage 1 with area C.",
" Stage 4:",
" 1) Put the mouse pointer into A area.",
" 2) Press Alt+Space and resize the Frame so the pointer becomes in B.",
" 3) Press Enter key. Exited event on Button and Entered event on Frame should be fired.",
" Stage 5:",
" 1) Put the mouse pointer into A area.",
" 2) Press Alt+Space and resize the Frame so the pointer becomes in C.",
" 3) Press Enter key. Exited event on Button should be fired.",
" Stage 6:",
" 1) Put the mouse pointer into B area.",
" 2) Press Alt+Space and resize the Frame so the pointer becomes in A.",
" 3) Press Enter key. Exited event on Frame and Entered event on Button should be fired.",
" Stage 7:",
" 1) Put the mouse pointer into B area.",
" 2) Press Alt+Space and resize the Frame so the pointer becomes in C.",
" 3) Press Enter key. Exited event on Frame should be fired.",
" Stage 8:",
" 1) Put the mouse pointer into C area.",
" 2) Press Alt+Space and resize the Frame so the pointer becomes in A.",
" 3) Press Enter key. Entered event on Button should be fired.",
" Stage 9:",
" 1) Put the mouse pointer into C area.",
" 2) Press Alt+Space and resize the Frame so the pointer becomes in B.",
" 3) Press Enter key. Entered event on Frame should be fired.",
" Stage 10:",
" Repeat Stages from 4 to 9 with using Move command rather then Resize. ",
" Note, that when the pointer jumps to the titlebar when you select \"Move window\", ",
" it is OK to fire Exited event. Then, if the pointer returns to component back, ",
" it should fire Entered event.",
};
Sysout.createDialog( );
Sysout.printInstructions( instructions );
Sysout.enableNumbering(true);
MouseAdapter enterExitAdapter = new MouseAdapter() {
public void mouseEntered(MouseEvent e){
Sysout.println("Entered on " + e.getSource().getClass().getName());
}
public void mouseExited(MouseEvent e){
Sysout.println("Exited on " + e.getSource().getClass().getName());
}
};
frame.addMouseListener(enterExitAdapter);
jbutton.addMouseListener(enterExitAdapter);
frame.setSize(600, 200);
frame.add(jbutton, BorderLayout.NORTH);
frame.setVisible(true);
frame1.addMouseListener(enterExitAdapter);
button1.addMouseListener(enterExitAdapter);
frame1.setSize(600, 200);
frame1.add(button1, BorderLayout.NORTH);
frame1.setVisible(true);
}//End init()
/*****************************************************
* Standard Test Machinery Section
* DO NOT modify anything in this section -- it's a
* standard chunk of code which has all of the
* synchronisation necessary for the test harness.
* By keeping it the same in all tests, it is easier
* to read and understand someone else's test, as
* well as insuring that all tests behave correctly
* with the test harness.
* There is a section following this for test-defined
* classes
******************************************************/
private static boolean theTestPassed = false;
private static boolean testGeneratedInterrupt = false;
private static String failureMessage = "";
private static Thread mainThread = null;
private static int sleepTime = 300000;
public static void main( String args[] ) throws InterruptedException
{
mainThread = Thread.currentThread();
try
{
init();
}
catch( TestPassedException e )
{
//The test passed, so just return from main and harness will
// interepret this return as a pass
return;
}
//At this point, neither test passed nor test failed has been
// called -- either would have thrown an exception and ended the
// test, so we know we have multiple threads.
//Test involves other threads, so sleep and wait for them to
// called pass() or fail()
try
{
Thread.sleep( sleepTime );
//Timed out, so fail the test
throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
}
catch (InterruptedException e)
{
if( ! testGeneratedInterrupt ) throw e;
//reset flag in case hit this code more than once for some reason (just safety)
testGeneratedInterrupt = false;
if ( theTestPassed == false )
{
throw new RuntimeException( failureMessage );
}
}
}//main
public static synchronized void setTimeoutTo( int seconds )
{
sleepTime = seconds * 1000;
}
public static synchronized void pass()
{
Sysout.println( "The test passed." );
Sysout.println( "The test is over, hit Ctl-C to stop Java VM" );
//first check if this is executing in main thread
if ( mainThread == Thread.currentThread() )
{
//Still in the main thread, so set the flag just for kicks,
// and throw a test passed exception which will be caught
// and end the test.
theTestPassed = true;
throw new TestPassedException();
}
//pass was called from a different thread, so set the flag and interrupt
// the main thead.
theTestPassed = true;
testGeneratedInterrupt = true;
if (mainThread != null){
mainThread.interrupt();
}
}//pass()
public static synchronized void fail()
{
//test writer didn't specify why test failed, so give generic
fail( "it just plain failed! :-)" );
}
public static synchronized void fail( String whyFailed )
{
Sysout.println( "The test failed: " + whyFailed );
Sysout.println( "The test is over, hit Ctl-C to stop Java VM" );
//check if this called from main thread
if ( mainThread == Thread.currentThread() )
{
//If main thread, fail now 'cause not sleeping
throw new RuntimeException( whyFailed );
}
theTestPassed = false;
testGeneratedInterrupt = true;
failureMessage = whyFailed;
mainThread.interrupt();
}//fail()
}// class SpuriousExitEnter_2
//This exception is used to exit from any level of call nesting
// when it's determined that the test has passed, and immediately
// end the test.
class TestPassedException extends RuntimeException
{
}
//*********** End Standard Test Machinery Section **********
//************ Begin classes defined for the test ****************
// make listeners in a class defined here, and instantiate them in init()
/* Example of a class which may be written as part of a test
class NewClass implements anInterface
{
static int newVar = 0;
public void eventDispatched(AWTEvent e)
{
//Counting events to see if we get enough
eventCount++;
if( eventCount == 20 )
{
//got enough events, so pass
ManualMainTest.pass();
}
else if( tries == 20 )
{
//tried too many times without getting enough events so fail
ManualMainTest.fail();
}
}// eventDispatched()
}// NewClass class
*/
//************** End classes defined for the test *******************
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
private static TestDialog dialog;
private static boolean numbering = false;
private static int messageNumber = 0;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
/* Enables message counting for the tester. */
public static void enableNumbering(boolean enable){
numbering = enable;
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
if (numbering) {
messageIn = "" + messageNumber + " " + messageIn;
messageNumber++;
}
dialog.displayMessage( messageIn );
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog implements ActionListener
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
Panel buttonP = new Panel();
Button passB = new Button( "pass" );
Button failB = new Button( "fail" );
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
passB = new Button( "pass" );
passB.setActionCommand( "pass" );
passB.addActionListener( this );
buttonP.add( "East", passB );
failB = new Button( "fail" );
failB.setActionCommand( "fail" );
failB.addActionListener( this );
buttonP.add( "West", failB );
add( "South", buttonP );
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
//catch presses of the passed and failed buttons.
//simply call the standard pass() or fail() static methods of
//ManualMainTest
public void actionPerformed( ActionEvent e )
{
if( e.getActionCommand() == "pass" )
{
SpuriousExitEnter_2.pass();
}
else
{
SpuriousExitEnter_2.fail();
}
}
}// TestDialog class |
<template>
<div class="page-body">
<div class="section">
<div
class="heading animate__animated animate__slideInLeft animate__slow"
>
{{ showDate }}
</div>
<div class="conferenceInfo">
<div class="label">참여한 방 :</div>
<div class="content">{{ state.conferenceTitle }}</div>
</div>
<div class="conferenceInfo">
<div class="label">공부시간 :</div>
<div class="content">{{ state.timeTaken }}</div>
</div>
<div class="scores">
<div>+{{ state.thisConferenceScore }}</div>
<div class="animate__animated animate__fadeIn">
현재 나의 점수 : {{ change_point }}
</div>
</div>
<div class="btns">
<el-button @click="goMain">다른 공부방 가기</el-button>
<el-button @click="goProfile">내 점수 보러가기</el-button>
</div>
</div>
<div class="section image">
<img :src="require(`@/assets/images/${userTier}.png`)" />
<div
class="heading2 animate__animated animate__slideInRight animate__slow"
>
현재 나의 티어
</div>
</div>
</div>
</template>
<script>
import { onBeforeMount, ref, reactive } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
export default {
name: "finish",
setup() {
const route = useRoute();
const router = useRouter();
const store = useStore();
const today = new Date();
const year = today.getFullYear(); // 년도
const month = today.getMonth() + 1; // 월
const date = today.getDate(); // 날짜
const day = today.getDay(); // 요일
const week = new Array(
"일요일",
"월요일",
"화요일",
"수요일",
"목요일",
"금요일",
"토요일"
);
const showDate = `${year}.${month}.${date} ${week[day]}`;
const change_point = ref(0);
const userTier = JSON.parse(localStorage.getItem("userInfo")).userTier;
const state = reactive({
conferenceId: "",
conferenceTitle: {},
timeTaken: "",
thisConferenceScore: 0,
start_point: 0
});
onBeforeMount(() => {
state.conferenceId = route.params.conferenceId;
store
.dispatch("root/getConferenceDetail", state.conferenceId)
.then(function(result) {
state.conferenceTitle = result.data.title;
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!1', state.conferenceTitle)
})
.catch(function(err) {
console.log(err)
});
const myIntId = JSON.parse(localStorage.getItem("userInfo")).id;
store
.dispatch("root/getMyConferenceHistory", myIntId)
.then(function(result) {
console.log("결과입니다요", result);
const insertTime = new Date(
result.data[0].insertTime
);
const outTime = new Date(result.data[0].outTime);
const time =
outTime.getHours() * 60 +
outTime.getMinutes() -
(insertTime.getHours() * 60 + insertTime.getMinutes());
var hours = Math.floor(time / 60);
var minutes = time % 60;
state.timeTaken = hours + "시간 " + minutes + "분";
state.thisConferenceScore =
result.data[0].userScore;
state.start_point = result.data[0].userYetScore;
console.log(result.data[0]);
change_point.value = state.start_point;
const goal = state.thisConferenceScore + state.start_point;
const change_num = function() {
if (goal - change_point.value > 30) {
change_point.value += 10;
} else if (goal - change_point.value > 10) {
change_point.value += 5;
}
};
const change_num2 = function() {
if (goal - change_point.value > 10) {
change_point.value += 2;
}
};
const change_num3 = function() {
if (goal - change_point.value > 0) {
change_point.value += 1;
}
};
setInterval(change_num, 100);
setInterval(change_num2, 200);
setInterval(change_num3, 300);
})
.catch(function(err) {});
});
const goMain = () => {
const MenuItems = store.getters["root/getMenus"];
let keys = Object.keys(MenuItems);
router.push({
name: keys[0]
});
};
const goProfile = () => {
const MenuItems = store.getters["root/getMenus"];
let keys = Object.keys(MenuItems);
router.push({
name: keys[4]
});
};
return {
showDate,
userTier,
state,
change_point,
goMain,
goProfile
};
}
};
</script>
<style>
@media (min-width: 701px) {
.page-body {
padding: 5% 10% 10% 5%;
width: 80%;
margin: 0 auto;
display: flex;
justify-content: space-between;
}
.section {
width: 50%;
}
}
.heading {
text-align: start;
font-size: 3vw;
margin-bottom: 7%;
}
.heading2 {
text-align: end;
font-size: 2.5vw;
margin-bottom: 7%;
margin-top: 7%;
}
.conferenceInfo {
font-size: 2.125vw;
display: flex;
justify-content: space-between;
margin-bottom: 5%;
}
.scores {
padding-top: 5%;
text-align: end;
font-size: 1.5625vw;
margin-bottom: 20%;
}
.btns {
display: flex;
justify-content: space-around;
}
@media only screen and (max-width: 700px) {
.section {
width: 90%;
padding: 5%;
}
.heading {
font-size: 4vw;
}
.conferenceInfo {
font-size: 3vw;
}
.scores {
font-size: 2.5vw;
}
.heading2 {
font-size: 2.5vw;
}
}
.animate__fadeIn {
--animate-duration: 6s;
}
.image {
margin-left: 20%;
}
</style> |
from crewai import Agent, Crew, Process, Task, LLM
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
from pydantic import BaseModel, Field
from typing import List
import os
from src.agentic_content_creator.config import input_vars, llms
class ResearchParagraph(BaseModel):
"""Model for a single research paragraph"""
title: str = Field(..., description="Title or topic of the paragraph")
content: str = Field(..., description="Content of the research paragraph")
sources: List[str] = Field(default_factory=list, description="Sources for this research paragraph")
class ResearchOutput(BaseModel):
"""Model for the complete research output"""
paragraphs: List[ResearchParagraph] = Field(..., description="List of research paragraphs")
summary: str = Field(..., description="Brief summary of the research findings")
class LinkedInPostPlan(BaseModel):
plan: str = Field(..., description="LinkedIn post plan")
class ContentPlan(BaseModel):
plans: List[LinkedInPostPlan]
@CrewBase
class ResearchCrew():
input_variables = input_vars
"""ResearchCrew for LinkedIn content creation"""
agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'
def __post_init__(self):
self.ensure_output_folder_exists()
def ensure_output_folder_exists(self):
"""Ensure the output folder exists."""
output_folder = 'output'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
tools=[SerperDevTool()],
llm=llms['openai']['gpt-4o'],
verbose=True
)
@agent
def planner(self) -> Agent:
return Agent(
config=self.agents_config['planner'],
llm=llms['openai']['gpt-4o'],
verbose=True
)
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'],
output_file='content_research.md',
output_pydantic=ResearchOutput
)
#@task
#def planning_task(self) -> Task:
# return Task(
# config=self.tasks_config['planning_task'],
# output_pydantic=ContentPlan,
# output_file='content_plan.md'
# )
@crew
def crew(self) -> Crew:
"""Creates the ResearchCrew crew"""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
output_pydantic=ContentPlan
) |
package com.huizhi.aianswering.controller;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/capt")
@CrossOrigin
public class CaptureController {
@Resource
private RedisTemplate<String, String> redisTemplate;
@ApiOperation("生成字符组合验证码")
@GetMapping("/captcha")
public void getCaptcha(@RequestParam String userKey, HttpServletRequest request, HttpServletResponse response) throws IOException {
ValueOperations<String, String> redisCapture = redisTemplate.opsForValue();
//png类型,数字加字母,len:字符个数
SpecCaptcha specCaptcha = new SpecCaptcha(135, 33, 5);
specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
//存入redis
try {
redisCapture.set(userKey,specCaptcha.text().toLowerCase(), 60000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
}
// 设置响应类型为图片格式
response.setContentType("image/png");
// 输出验证码图片
try {
CaptchaUtil.out(specCaptcha, request, response);
} catch (IOException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("验证码生成失败");
}
}
@ApiOperation("生成算术验证码")
@GetMapping("/math_captcha")
public void getMathCaptcha(@RequestParam String userKey, HttpServletRequest request, HttpServletResponse response) throws IOException {
ValueOperations<String, String> redisCapture = redisTemplate.opsForValue();
//算术型
ArithmeticCaptcha captcha = new ArithmeticCaptcha(135, 33);
captcha.setLen(4); //几位数运算,默认是两位
captcha.getArithmeticString(); //获取运算的公式
captcha.text(); //获取运算的结果
//存入redis
try {
redisCapture.set(userKey,captcha.text().toLowerCase(), 60000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
}
// 设置响应类型为图片格式
response.setContentType("image/png");
// 输出验证码图片
try {
CaptchaUtil.out(captcha, request, response);
} catch (IOException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("验证码生成失败");
}
}
} |
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
import Header from './components/Header';
import Home from './pages/Home';
import Project from './pages/Project';
import NotFound from './pages/NotFound';
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
clients: {
merge(existing, incoming) {
return incoming;
},
},
projects: {
merge(existing, incoming) {
return incoming;
},
},
},
},
},
});
const client = new ApolloClient({
// uri: 'http://localhost:8080/graphql',
uri: 'https://projectql.onrender.com/graphql',
cache,
});
function App() {
return (
<>
<ApolloProvider client={client}>
<Router>
<Header />
<div className="bg-[#F2F5F6] h-screen">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/projects/:id" element={<Project />} />
<Route path="*" element={<NotFound />} />
</Routes>
</div>
</Router>
</ApolloProvider>
</>
);
}
export default App; |
package com.example.mvvmproducts.AllProducts.View
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mvvmproducts.FavProducts.View.OnProductFavClickListener
import com.example.lec5.DB.ProductDao
import com.example.lec5.DB.ProductDatabase
import com.example.lec5.Product
import com.example.mvvmproducts.AllProducts.ViewModel.AllProductsViewModel
import com.example.mvvmproducts.AllProducts.ViewModel.AllProductsViewModelFactory
import com.example.mvvmproducts.DB.ProductLocalDataSource
import com.example.mvvmproducts.Model.Repo
import com.example.mvvmproducts.Network.APIState
import com.example.mvvmproducts.Network.ProductRemoteDataSource
import com.example.mvvmproducts.Network.RetrofitHelper
import com.example.mvvmproducts.R
import kotlinx.coroutines.launch
class AllProducts : AppCompatActivity(), OnProductFavClickListener {
lateinit var recyclerView: RecyclerView
lateinit var mAdapter: ProductAdapter
lateinit var mLayoutManager: LinearLayoutManager
lateinit var viewModel: AllProductsViewModel
lateinit var products: List<Product>
lateinit var allProductsViewModelFactory: AllProductsViewModelFactory
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_all_products)
recyclerView = findViewById(R.id.rv_prod)
val myProductDao: ProductDao = ProductDatabase.getInstance(this).getproductDao()
val localDataSource = ProductLocalDataSource(myProductDao)
val remoteSource = ProductRemoteDataSource(RetrofitHelper.service)
allProductsViewModelFactory = AllProductsViewModelFactory(Repo.getInstance(localDataSource, remoteSource))
viewModel = ViewModelProvider(this, allProductsViewModelFactory).get(AllProductsViewModel::class.java)
mAdapter = ProductAdapter(this)
mLayoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
recyclerView.apply {
adapter = mAdapter
layoutManager = mLayoutManager
}
lifecycleScope.launch {
viewModel.productsState.collect { state ->
when (state) {
is APIState.Loading -> {
Toast.makeText(this@AllProducts, "Loading...", Toast.LENGTH_SHORT).show()
}
is APIState.Success -> {
mAdapter.submitList(state.data)
}
is APIState.Failure -> {
Toast.makeText(this@AllProducts, "Error: ${state.msg}", Toast.LENGTH_LONG).show()
}
}
}
}
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
override fun onProductClick(product: Product) {
viewModel.insertToFav(product)
Toast.makeText(this, "Product added to favorites", Toast.LENGTH_SHORT).show()
}
} |
package com.example.recipesapp.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.recipesapp.R
import com.example.recipesapp.data.Food
import com.example.recipesapp.databinding.ItemSecretBinding
class FoodAdapter(
private val listener: (Int) -> Unit
): RecyclerView.Adapter<FoodViewHolder>() {
private var foods: ArrayList<Food> = arrayListOf()
inner class MyDiffUtil(
private val newList: ArrayList<Food>,
private val oldList: ArrayList<Food>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].foodName == newList[newItemPosition].foodName
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList == newList
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodViewHolder {
return FoodViewHolder.from(parent, listener)
}
override fun onBindViewHolder(holder: FoodViewHolder, position: Int) {
val imageItem = getItemId(position)
holder.bind(foods[position])
}
override fun getItemCount() = foods.size
fun setFoods(newList: ArrayList<Food>) {
val diffUtil = MyDiffUtil(oldList = foods, newList = newList)
val diffResult = DiffUtil.calculateDiff(diffUtil)
foods = newList
diffResult.dispatchUpdatesTo(this)
}
}
class FoodViewHolder private constructor(
private val binding: ItemSecretBinding,
private val listener: (Int) -> Unit
): RecyclerView.ViewHolder(binding.root){
companion object {
fun from(parent: ViewGroup, listener: (Int) -> Unit): FoodViewHolder {
val binding =
ItemSecretBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return FoodViewHolder(binding, listener)
}
}
fun bind(post: Food) {
with(binding) {
card.setOnClickListener {
listener(absoluteAdapterPosition)
}
Glide.with(imgPostImage.context)
.load(post.url)
.placeholder(R.drawable.ic_replay)
.into(imgPostImage)
tvFoodName.text = post.foodName
}
}
} |
package com.qkl.musicplayer.music;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* 作者:kelingqiu on 16/9/8 11:07
* 邮箱:42747487@qq.com
*/
public class PlayerService extends Service {
private static final String TAG = PlayerService.class.getSimpleName();
private static final int DURATION = 335;
private final IBinder mBinder = new LocalBinder();
private Worker mWorker;
public PlayerService(){
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
if (mWorker != null) {
mWorker.interrupt();
}
return super.onUnbind(intent);
}
public void play() {
if (mWorker == null) {
mWorker = new Worker();
mWorker.start();
} else {
mWorker.doResume();
}
}
public boolean isPlaying() {
return mWorker != null && mWorker.isPlaying();
}
public void pause() {
if (mWorker != null) {
mWorker.doPause();
}
}
public int getPosition() {
if (mWorker != null) {
return mWorker.getPosition();
}
return 0;
}
private static class Worker extends Thread{
boolean paused = false;
int position = 0;
@Override
public void run() {
try{
while (position < DURATION) {
sleep(1000);
if (!paused) {
position++;
}
}
}catch (InterruptedException e){
Log.d(TAG, "Player unbounded");
}
}
void doResume(){
paused = false;
}
void doPause(){
paused = true;
}
boolean isPlaying(){
return !paused;
}
int getPosition(){
return position;
}
}
public class LocalBinder extends Binder {
public PlayerService getService(){
return PlayerService.this;
}
}
} |
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Menu, X } from 'lucide-react';
const Navbar: React.FC = () => {
const [isOpen, setIsOpen] = useState(false);
const [isScrolled, setIsScrolled] = useState(false);
const handleLogoClick = () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
};
useEffect(() => {
const handleScroll = () => {
setIsScrolled(window.scrollY > 20);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
const navItems = [
{ label: 'Features', href: '#features' },
{ label: 'About', href: '#about' },
{ label: 'Pricing', href: '#pricing' },
{ label: 'Contact', href: '#contact' }
];
return (
<nav className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${
isScrolled ? 'bg-primary-900/95 backdrop-blur-md shadow-lg shadow-primary-900/50' : 'bg-transparent'
}`}>
<div className="container-custom">
<div className="flex justify-between h-20 items-center">
<Link
to="/"
onClick={handleLogoClick}
className="text-2xl font-bold text-white hover:text-accent-300 transition-all duration-300 transform hover:scale-105"
>
Brand Matrix
</Link>
<div className="hidden md:flex items-center space-x-8">
{navItems.map((item, index) => (
<a
key={index}
href={item.href}
className="nav-link"
>
{item.label}
</a>
))}
<Link to="/demo">
<button className="btn-primary">
Book Demo
</button>
</Link>
<Link to="/login">
<button className="btn-secondary">
Sign In
</button>
</Link>
</div>
<div className="md:hidden">
<button
onClick={() => setIsOpen(!isOpen)}
className="text-primary-200 hover:text-white transition-colors"
aria-label="Toggle menu"
>
{isOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
</button>
</div>
</div>
{isOpen && (
<div className="md:hidden animate-fade-in">
<div className="px-2 pt-2 pb-3 space-y-1 sm:px-3 bg-primary-800/95 backdrop-blur-md border-b border-primary-700">
{navItems.map((item, index) => (
<a
key={index}
href={item.href}
className="block px-3 py-2 text-primary-200 hover:text-white hover:bg-primary-700/50 rounded-lg transition-all duration-200"
onClick={() => setIsOpen(false)}
>
{item.label}
</a>
))}
<Link to="/demo" className="block" onClick={() => setIsOpen(false)}>
<button className="w-full btn-primary">
Book Demo
</button>
</Link>
<Link to="/login" className="block" onClick={() => setIsOpen(false)}>
<button className="w-full btn-secondary">
Sign In
</button>
</Link>
</div>
</div>
)}
</div>
</nav>
);
};
export default Navbar; |
import 'package:flutter/material.dart';
class Users {
final String uid;
final String email;
final String username;
final String bio;
final String photoUrl;
final List<dynamic> followers;
final List<dynamic> following;
final List<dynamic> posts;
final List<dynamic> saved;
final String searchKey;
Users({
required this.uid,
required this.email,
required this.username,
required this.bio,
required this.photoUrl,
required this.followers,
required this.following,
required this.posts,
required this.saved,
required this.searchKey,
});
static Users fromSnap(DocumentSnapshot snap) {
Map<String, dynamic> snapshot = snap.data() as Map<String, dynamic>;
return Users(
uid: snapshot['uid'],
email: snapshot['email'],
username: snapshot['username'],
bio: snapshot['bio'],
photoUrl: snapshot['photoUrl'],
followers: snapshot['followers'],
following: snapshot['following'],
posts: snapshot['posts'],
saved: snapshot['saved'],
searchKey: snapshot['searchKey'],
);
}
Map<String, dynamic> toJson() {
return {
'uid': uid,
'email': email,
'username': username,
'bio': bio,
'photoUrl': photoUrl,
'followers': followers,
'following': following,
'posts': posts,
'saved': saved,
'searchKey': searchKey,
};
}
} |
import { SignUpController } from '../../sign-up.controller'
import {
MissingParamError,
InvalidParamError,
ServerError
} from '../../../../errors'
import {
type AccountModel,
type AddAccount,
type AddAccountModel,
type EmailValidator
} from '../../sign-up.protocol'
const makeEmailValidadtor = (): EmailValidator => {
class EmailValidatorStub implements EmailValidator {
isValid(email: string): boolean {
return true
}
}
return new EmailValidatorStub()
}
const makeAddAccount = (): AddAccount => {
class AddAccountStub implements AddAccount {
async add(account: AddAccountModel): Promise<AccountModel> {
const fakeAccount = {
id: '123',
name: 'John Doe',
email: 'johh@email.com',
password: '123123213'
}
return await new Promise(resolve => {
resolve(fakeAccount)
})
}
}
return new AddAccountStub()
}
interface SutTypes {
sut: SignUpController
emailValidatorStub: EmailValidator
addAccountStub: AddAccount
}
const makeSut = (): SutTypes => {
const emailValidatorStub = makeEmailValidadtor()
const addAccountStub = makeAddAccount()
const sut = new SignUpController(emailValidatorStub, addAccountStub)
return {
sut,
emailValidatorStub,
addAccountStub
}
}
describe('SignUp controller', () => {
it('should return 400 if no name is provided', async () => {
const { sut } = makeSut()
const httpRequest = {
body: {
email: 'john@email.com',
password: '123123213',
passwordConfirmation: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(400)
expect(httpResponse.body).toEqual(new MissingParamError('name'))
})
it('should return 400 if no email is provided', async () => {
const { sut } = makeSut()
const httpRequest = {
body: {
name: 'John Doe',
password: '123123213',
passwordConfirmation: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(400)
expect(httpResponse.body).toEqual(new MissingParamError('email'))
})
it('should return 400 if no password is provided', async () => {
const { sut } = makeSut()
const httpRequest = {
body: {
name: 'John Doe',
email: 'john@email.com',
passwordConfirmation: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(400)
expect(httpResponse.body).toEqual(new MissingParamError('password'))
})
it('should return 400 if no passwordConfirmation is provided', async () => {
const { sut } = makeSut()
const httpRequest = {
body: {
name: 'John Doe',
email: 'john@email.com',
password: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(400)
expect(httpResponse.body).toEqual(
new MissingParamError('passwordConfirmation')
)
})
it('should return 400 if password confirmation fails', async () => {
const { sut } = makeSut()
const httpRequest = {
body: {
name: 'John Doe',
email: 'john@email.com',
password: '123123213',
passwordConfirmation: '123'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(400)
expect(httpResponse.body).toEqual(
new InvalidParamError('passwordConfirmation')
)
})
it('should return 400 if an invalid email is provided', async () => {
const { sut, emailValidatorStub } = makeSut()
jest.spyOn(emailValidatorStub, 'isValid').mockReturnValueOnce(false)
const httpRequest = {
body: {
name: 'John Doe',
email: 'invalid_email@email.com',
password: '123123213',
passwordConfirmation: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(400)
expect(httpResponse.body).toEqual(new InvalidParamError('email'))
})
it('should call EmailValidator with correct email', async () => {
const { sut, emailValidatorStub } = makeSut()
const isValidSpy = jest.spyOn(emailValidatorStub, 'isValid')
const httpRequest = {
body: {
name: 'John Doe',
email: 'john@email.com',
password: '123123213',
passwordConfirmation: '123123213'
}
}
await sut.handle(httpRequest)
expect(isValidSpy).toHaveBeenCalledWith('john@email.com')
})
it('should return 500 if EmailValidator throws', async () => {
const { sut, emailValidatorStub } = makeSut()
jest.spyOn(emailValidatorStub, 'isValid').mockImplementationOnce(() => {
throw new Error()
})
const httpRequest = {
body: {
name: 'John Doe',
email: 'invalid_email@email.com',
password: '123123213',
passwordConfirmation: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(500)
expect(httpResponse.body).toEqual(new ServerError())
})
it('should call AddAccount with correct values', async () => {
const { sut, addAccountStub } = makeSut()
const addSpy = jest.spyOn(addAccountStub, 'add')
const httpRequest = {
body: {
name: 'John Doe',
email: 'john@email.com',
password: '123123213',
passwordConfirmation: '123123213'
}
}
await sut.handle(httpRequest)
expect(addSpy).toHaveBeenCalledWith({
name: 'John Doe',
email: 'john@email.com',
password: '123123213'
})
})
it('should return 500 if AddAccount throws', async () => {
const { sut, addAccountStub } = makeSut()
jest.spyOn(addAccountStub, 'add').mockImplementationOnce(async () => {
return await new Promise((resolve, reject) => {
reject(new Error())
})
})
const httpRequest = {
body: {
name: 'John Doe',
email: 'invalid_email@email.com',
password: '123123213',
passwordConfirmation: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(500)
expect(httpResponse.body).toEqual(new ServerError())
})
it('should return 200 if valid data is provided', async () => {
const { sut } = makeSut()
const httpRequest = {
body: {
name: 'John Doe',
email: 'johh@email.com',
password: '123123213',
passwordConfirmation: '123123213'
}
}
const httpResponse = await sut.handle(httpRequest)
expect(httpResponse.statusCode).toBe(201)
expect(httpResponse.body).toEqual({
id: '123',
name: 'John Doe',
email: 'johh@email.com',
password: '123123213'
})
})
}) |
setClass("ClosedRange", slots = list(start = "integer", end = "integer"))
is_valid_closed_range <- function(object) {
if (object@start <= object@end) {
TRUE
} else {
"Start must be less than or equal to end."
}
}
setValidity("ClosedRange", is_valid_closed_range)
setMethod("as.character", "ClosedRange", function(x, ...) {
paste("[", as.character(x@start), ", ", as.character(x@end), "]", sep = "")
})
setGeneric("contains", function(r, x) standardGeneric("contains"))
setMethod(
"contains",
signature(r = "ClosedRange", x = "integer"),
function(r, x) {
r@start <= x && x <= r@end
}
)
setMethod(
"Compare",
signature(e1 = "ClosedRange", e2 = "ClosedRange"),
function(e1, e2) {
e1@start == e2@start && e1@end == e2@end
}
)
setGeneric("includes", function(r1, r2) standardGeneric("includes"))
setMethod(
"includes",
signature(r1 = "ClosedRange", r2 = "ClosedRange"),
function(r1, r2) {
r1@start <= r2@start && r2@end <= r1@end
}
)
testthat::test_that("Can create ClosedRange when start is less than end", {
closed_range <- new("ClosedRange", start = 1L, end = 2L)
testthat::expect_true(!is.null(closed_range))
})
testthat::test_that("Can create ClosedRange when start is equal to end", {
closed_range <- new("ClosedRange", start = 2L, end = 2L)
testthat::expect_true(!is.null(closed_range))
})
testthat::test_that("Error occurs when start is larger than end", {
testthat::expect_error(new("ClosedRange", start = 2L, end = 1L))
})
testthat::test_that("Can show range", {
cr <- new("ClosedRange", start = 1L, end = 2L)
testthat::expect_equal(as.character(cr), "[1, 2]")
})
testthat::test_that("Value is in range", {
cr <- new("ClosedRange", start = 1L, end = 2L)
testthat::expect_true(contains(cr, 1L))
})
testthat::test_that("Value is out of range", {
cr <- new("ClosedRange", start = 1L, end = 2L)
testthat::expect_false(contains(cr, 3L))
})
testthat::test_that("Equal range", {
cr1 <- new("ClosedRange", start = 1L, end = 2L)
cr2 <- new("ClosedRange", start = 1L, end = 2L)
testthat::expect_true(cr1 == cr2)
})
testthat::test_that("Not equal range", {
cr1 <- new("ClosedRange", start = 1L, end = 2L)
cr2 <- new("ClosedRange", start = 1L, end = 3L)
testthat::expect_false(cr1 == cr2)
})
testthat::test_that("Include range", {
cr1 <- new("ClosedRange", start = 1L, end = 2L)
cr2 <- new("ClosedRange", start = 1L, end = 2L)
testthat::expect_true(includes(cr1, cr2))
})
testthat::test_that("Not include range1", {
cr1 <- new("ClosedRange", start = 1L, end = 2L)
cr2 <- new("ClosedRange", start = 1L, end = 3L)
testthat::expect_false(includes(cr1, cr2))
})
testthat::test_that("Not include range2", {
cr1 <- new("ClosedRange", start = 1L, end = 2L)
cr2 <- new("ClosedRange", start = 0L, end = 1L)
testthat::expect_false(includes(cr1, cr2))
}) |
---
import { getCollection } from "astro:content";
import SocialIcon from "../components/SocialIcon.astro";
const bio = await getCollection("bio");
const socials = await getCollection("socials");
const posts = await getCollection("posts");
const profile = bio[0];
---
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>LTree | {profile.data.name}</title>
</head>
<body>
<main class="flex flex-col items-center justify-center p-4 pt-10">
<img src={profile.data.avatar} alt="avatar" class="w-32 h-32 rounded-full" />
<h1 class="text-2xl mt-4">{profile.data.name}</h1>
<nav>
<ul class="flex divide-x divide-blue-700 p-2">
<li class="text-lg"><a class="block px-2 text-blue-500" href="/">Links</a></li>
<li class="text-lg"><a class="block px-2 text-blue-500" href="/postlinks">Posts</a></li>
</ul>
</nav>
<ul class="flex gap-4 items-center justify-center flex-wrap pt-10">
{
socials.sort((a, b) => {
if (a.data.order < b.data.order) {
return -1;
}
if (a.data.order > b.data.order) {
return 1;
}
return 0;
}).map((social) => (
<li class="border border-black border-2 rounded-full">
<a href={social.data.url} class="block p-4">
<SocialIcon id={social.data.icon[0]}>
</a>
</li>
))
}
</ul>
<ul class="grid grid-cols-3 gap-1 pt-20 max-w-[640px] w-full">
{
posts.sort((a, b) => {
if (a.data.date < b.data.date) {
return 1;
}
if (a.data.date > b.data.date) {
return -1;
}
return 0;
}).map((p) =>
<li>
<a href={p.data.url}>
<img src={p.data.image} alt={p.data.title} class="aspect-square col-span-1 object-cover" />
</a>
</li>
)
}
</ul>
</main>
</body>
</html> |
import React, { useState, useEffect } from 'react';
import { FaBell, FaCalendarAlt, FaDollarSign, FaExclamationCircle } from 'react-icons/fa';
const Notifications = () => {
// Dummy data for demonstration. In production, this data would come from an API.
const [notifications, setNotifications] = useState([
{
id: 1,
type: 'exam',
message: 'Math exam is scheduled for 20th September.',
date: '2024-09-08',
read: false,
},
{
id: 2,
type: 'fee',
message: 'Your school fee for the month of September is due.',
date: '2024-09-01',
read: false,
},
{
id: 3,
type: 'attendance',
message: 'Your child is absent today.',
date: '2024-09-05',
read: false,
},
{
id: 4,
type: 'event',
message: 'Parent-teacher meeting is scheduled for 25th September.',
date: '2024-09-15',
read: true,
},
]);
// Mark notification as read
const markAsRead = (id) => {
const updatedNotifications = notifications.map((notification) =>
notification.id === id ? { ...notification, read: true } : notification
);
setNotifications(updatedNotifications);
};
// Determine the icon based on the type of notification
const getIcon = (type) => {
switch (type) {
case 'exam':
return <FaCalendarAlt className="text-blue-500" />;
case 'fee':
return <FaDollarSign className="text-green-500" />;
case 'attendance':
return <FaExclamationCircle className="text-red-500" />;
case 'event':
return <FaBell className="text-yellow-500" />;
default:
return <FaBell className="text-gray-500" />;
}
};
return (
<div className="min-h-screen bg-gray-100 p-6">
<div className="bg-white shadow-lg rounded-lg p-8 max-w-4xl mx-auto">
<h2 className="text-2xl font-bold mb-6">Notifications</h2>
<div className="space-y-4">
{notifications.map((notification) => (
<div
key={notification.id}
className={`p-4 rounded-lg shadow flex items-center justify-between ${
notification.read ? 'bg-gray-100' : 'bg-blue-50'
}`}
>
<div className="flex items-center space-x-4">
{/* Notification Icon */}
<div className="text-2xl">
{getIcon(notification.type)}
</div>
{/* Notification Message */}
<div>
<p className="font-medium">{notification.message}</p>
<p className="text-gray-500 text-sm">{new Date(notification.date).toLocaleDateString()}</p>
</div>
</div>
{/* Mark as read button */}
{!notification.read && (
<button
onClick={() => markAsRead(notification.id)}
className="text-blue-500 hover:text-blue-700"
>
Mark as Read
</button>
)}
</div>
))}
</div>
</div>
</div>
);
};
export default Notifications; |
import torch
from torch import nn
import torch.optim as optim
import torch.nn.functional as F
def training(batch_size, n_epoch, lr, model_dir, train, valid, model, device):
total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print('\nstart training, parameter total:{}, trainable:{}\n'.format(total, trainable))
model.train()
criterion = nn.BCELoss()
t_batch = len(train)
v_batch = len(valid)
optimizer = optim.Adam(model.parameters(), lr=lr)
total_loss, total_acc, best_acc = 0, 0, 0
for epoch in range(n_epoch):
total_loss, total_acc = 0, 0
# 這段做training
for i, (inputs, labels) in enumerate(train):
inputs = inputs.to(device, dtype=torch.long) #input->torch.cuda.LongTensor
labels = labels.to(device, dtype=torch.float) # label->torch.cuda.FloatTensor,in order to fed to cri
optimizer.zero_grad()
outputs = model(inputs)
outputs = outputs.squeeze()
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
correct = evaluation(outputs, labels)
total_acc += (correct / batch_size)
total_loss += loss.item()
print('[ Epoch{}: {}/{} ] loss:{:.3f} acc:{:.3f} '.format(
epoch+1, i+1, t_batch, loss.item(), correct*100/batch_size), end='\r')
print('\nTrain | Loss:{:.5f} Acc: {:.3f}'.format(total_loss/t_batch, total_acc/t_batch*100))
# validation
model.eval()
with torch.no_grad():
total_loss, total_acc = 0, 0
for i, (inputs, labels) in enumerate(valid):
inputs = inputs.to(device, dtype=torch.long)
labels = labels.to(device, dtype=torch.float)
outputs = model(inputs)
outputs = outputs.squeeze()
loss = criterion(outputs, labels) #
correct = evaluation(outputs, labels)
total_acc += (correct / batch_size)
total_loss += loss.item()
print("Valid | Loss:{:.5f} Acc: {:.3f} ".format(total_loss/v_batch, total_acc/v_batch*100))
if total_acc > best_acc:
best_acc = total_acc
#torch.save(model, "{}/val_acc_{:.3f}.model".format(model_dir,total_acc/v_batch*100))
torch.save(model, "{}/ckpt.model".format(model_dir))
print('saving model with acc {:.3f}'.format(total_acc/v_batch*100))
print('-----------------------------------------------')
model.train()
def testing(batch_size, test_loader, model, device):
model.eval()
ret_output = []
with torch.no_grad():
for i, inputs in enumerate(test_loader):
inputs = inputs.to(device, dtype=torch.long)
outputs = model(inputs)
outputs = outputs.squeeze()
outputs[outputs >= 0.5] = 1
outputs[outputs < 0.5] = 0
ret_output += outputs.int().tolist()
return ret_output |
<!DOCTYPE html>
<html>
<head>
<!-- meta block -->
<title>Localization - DHTMLX Form</title>
<meta name="description" content="Check interactive samples of DHTMLX Form to explore its initialization and other details.">
<!-- end meta block -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
<script type="text/javascript" src="../../../codebase/suite.js?v=7.0.0"></script>
<link rel="stylesheet" href="../../../codebase/suite.css?v=7.0.0">
<link rel="stylesheet" href="../../common/index.css?v=7.0.0">
<link rel="stylesheet" href="../common/form.css?v=7.0.0">
<!-- custom sample head -->
<style>
.dhx_sample-container__widget {
padding: 0 50px;
height: 100%;
}
</style>
</head>
<body>
<header class="dhx_sample-header">
<div class="dhx_sample-header__main">
<nav class="dhx_sample-header__breadcrumbs">
<ul class="dhx_sample-header-breadcrumbs">
<li class="dhx_sample-header-breadcrumbs__item">
<a href="../../index.html" class="dhx_sample-header-breadcrumbs__link">Suite samples</a>
</li>
<li class="dhx_sample-header-breadcrumbs__item">
<a href="../index.html" class="dhx_sample-header-breadcrumbs__link">Form samples</a>
</li>
<li class="dhx_sample-header-breadcrumbs__item">
<a href="./index.html" class="dhx_sample-header-breadcrumbs__link">Initialization</a>
</li>
<li class="dhx_sample-header-breadcrumbs__item">
<span class="dhx_sample-header-breadcrumbs__link">Localization</span>
</li>
</ul>
</nav>
<h1 class="dhx_sample-header__title">
<div class="dhx_sample-header__content">
Localization.
</div>
</h1>
</div>
</header>
<section class="dhx_sample-controls">
<label class="dhx_form-group dhx_radiobutton dhx_form-group--inline dhx_form-group--no-message-holder dhx_sample-input__wrapper--pl-16">
<input type="radio" checked name="lang" id="english" class="dhx_radiobutton__input">
<span class="dhx_radiobutton__visual-input"></span>
<span class="dhx_sample-label">English </span>
</label>
<label class="dhx_form-group dhx_radiobutton dhx_form-group--inline dhx_form-group--no-message-holder dhx_sample-input__wrapper--pl-16">
<input type="radio" name="lang" id="deutsch" class="dhx_radiobutton__input">
<span class="dhx_radiobutton__visual-input"></span>
<span class="dhx_sample-label">Deutsch</span>
</label>
</section>
<section class="dhx_sample-container">
<form class="dhx_sample-container__widget" id="form-sample"></form>
</section>
<script>
var locale = {
en: {
fname: "First Name",
lname: "Last Name",
title: "Upload your CV",
position: "Position",
positionItems: {
front: "Frontend developer",
back: "Backend developer",
ux: "UX designer"
},
simpleVaultText: "Drag & drop files or folders here or",
simpleVaultLabel: "browse files",
send: "Send",
},
de: {
fname: "Voornaam",
lname: "Achternaam",
title: "Upload je CV",
position: "Positie",
positionItems: {
front: "Frontend ontwikkelaar",
back: "Backend ontwikkelaar",
ux: "UX-ontwerper"
},
simpleVaultText: "Drag & drop dateien oder odner hier oder",
simpleVaultLabel: "Suchen Sie Dateien durch",
send: "Sturen",
}
};
function getDate(currentLocale) {
return {
css: "dhx_widget--bordered",
padding: 20,
title: locale[currentLocale].title,
rows: [
{
type: "input",
placeholder: locale[currentLocale].fname,
name: "firstname"
},
{
type: "input",
placeholder: locale[currentLocale].lname,
name: "lastname"
},
{
type: "combo",
placeholder: locale[currentLocale].position,
name: "position",
data: [
{
value: locale[currentLocale].positionItems.front,
label: locale[currentLocale].positionItems.front,
},
{
value: locale[currentLocale].positionItems.back,
label: locale[currentLocale].positionItems.back,
},
{
value: locale[currentLocale].positionItems.ux,
label: locale[currentLocale].positionItems.ux,
},
]
},
{
type: "simpleVault",
name: "vault"
},
{
align: "end",
cols: [
{
type: "button",
submit: true,
text: locale[currentLocale].send
}
]
}
]
}
};
var form;
function createForm (locate) {
if (form) {
form.destructor();
}
form = new dhx.Form("form-sample", getDate(locate));
}
document.querySelector("#english").addEventListener("change", function(){
dhx.i18n.setLocale("form", locale["en"]);
currentLocale = "en";
createForm("en");
});
document.querySelector("#deutsch").addEventListener("change", function(){
dhx.i18n.setLocale("form", locale["de"]);
currentLocale = "de";
createForm("de");
});
createForm("en");
</script>
</body>
</html> |
#include <iostream>
#include <unordered_map>
using namespace std;
class HashTable {
private:
unordered_map<int, int> table;
public:
void insert(int key, int value) {
table[key] = value;
}
int search(int key) {
if (table.find(key) != table.end()) {
return table[key];
}
else {
return -1;
}
}
void remove(int key) {
if (table.find(key) != table.end()) {
cout << "Removing key: " << key << ", Value: " << table[key] << endl;
table.erase(key);
}
else {
cout << "Key " << key << " not found for deletion." << endl;
}
}
void removeRandom() {
if (table.empty()) {
cout << "Table is empty. Cannot remove." << endl;
return;
}
auto it = next(begin(table), rand() % table.size());
int key = it->first;
int value = it->second;
cout << "Removing key: " << key << ", Value: " << value << endl;
table.erase(key);
}
void printTable() {
for (const auto& pair : table) {
cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
}
}
};
int main() {
srand(time(NULL));
HashTable ht;
for (int i = 0; i < 10; ++i) {
int key = rand() % 100;
int value = rand() % 1000;
ht.insert(key, value);
}
cout << "Table Contents:" << endl;
ht.printTable();
int keyToFind = 5;
int result = ht.search(keyToFind);
if (result != -1) {
cout << "Found value for the key " << keyToFind << ": " << result << endl;
}
else {
cout << "Key value " << keyToFind << " not found." << endl;
}
for (int i = 0; i < 3; ++i) {
ht.removeRandom();
}
cout << "Table contents after deletion:" << endl;
ht.printTable();
return 0;
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A4 Lab</title>
<link href="../../../Vendors/Bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<link href="../../a3/css/index.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet"/>
</head>
<body>
<a href="../../index.html">Back</a>
<div class="container">
<h1>Bootstrap</h1>
<p>Welcome to Bootstrap!</p>
</div>
<h2><a href="https://getbootstrap.com/docs/5.1/layout/grid/">Grid system</a></h2>
<div class="row">
<div class="col bg-color-red">
<h3>Left half</h3>
</div>
<div class="col bg-color-blue fg-color-white">
<h3>Right half</h3>
</div>
</div>
<div class="row">
<div class="col-4 bg-color-yellow">
<h3>One thirds</h3>
</div>
<div class="col-8 bg-color-red">
<h3>Two thirds</h3>
</div>
</div>
<div class="row">
<div class="col-2 bg-color-blue fg-color-white">
<h3>Sidebar</h3>
</div>
<div class="col-8 bg-color-yellow">
<h3>Main content</h3>
</div>
<div class="col-2 bg-color-red">
<h3>Sidebar</h3>
</div>
</div>
<h2>Responsive grid system</h2>
<div class="row">
<div class="col-12 col-md-6 col-xl-3">
<h3>Column A</h3>
</div>
<div class="col-12 col-md-6 col-xl-3">
<h3>Column B</h3>
</div>
<div class="col-12 col-md-6 col-xl-3">
<h3>Column C</h3>
</div>
<div class="col-12 col-md-6 col-xl-3">
<h3>Column D</h3>
</div>
</div>
<h2>Responsive grid system</h2>
<div class="row">
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>1</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>2</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>3</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>4</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>5</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>6</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>7</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>8</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>9</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>10</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>11</h4>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 col-xxl-1">
<h4>12</h4>
</div>
</div>
<h2><a href="https://getbootstrap.com/docs/5.1/content/tables/">Tables</a></h2>
<table class="table">
<thead>
<tr>
<th>Quiz</th>
<th>Topic</th>
<th>Date</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>Q1</td>
<td>HTML</td>
<td>2/3/21</td>
<td>85</td>
</tr>
<tr>
<td>Q2</td>
<td>CSS</td>
<td>2/10/21</td>
<td>90</td>
</tr>
<tr>
<td>Q3</td>
<td>JavaScript</td>
<td>2/17/21</td>
<td>90</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Average</td>
<td>90</td>
</tr>
</tfoot>
</table>
<h2>
<a href="https://getbootstrap.com/docs/5.1/content/tables/#responsive-tables">
Responsive tables</a></h2>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Very</th>
<th>long</th>
<th>set</th>
<th>of</th>
<th>columns</th>
<th>Very</th>
<th>long</th>
<th>set</th>
<th>of</th>
<th>columns</th>
<th>Very</th>
<th>long</th>
<th>set</th>
<th>of</th>
<th>columns</th>
</tr>
</thead>
<tbody>
<tr>
<td>Very</td>
<td>long</td>
<td>set</td>
<td>of</td>
<td>columns</td>
<td>Very</td>
<td>long</td>
<td>set</td>
<td>of</td>
<td>columns</td>
<td>Very</td>
<td>long</td>
<td>set</td>
<td>of</td>
<td>columns</td>
</tr>
</tbody>
</table>
</div>
<h2>
<a href="https://getbootstrap.com/docs/5.1/components/list-group/">
Favorite movies
</a>
</h2>
<ul class="list-group">
<li class="list-group-item active">Aliens</li>
<li class="list-group-item">Terminator</li>
<li class="list-group-item">Blade Runner</li>
<li class="list-group-item">Lord of the Ring</li>
<li class="list-group-item disabled">Star Wars</li>
</ul>
<h3>
<a href="https://getbootstrap.com/docs/5.1/components/list-group/#links-and-buttons">
Favorite books
</a>
</h3>
<div class="list-group">
<a href="https://en.wikipedia.org/wiki/Dune_(novel)" class="list-group-item list-group-item-action active" aria-current="true">
Dune </a>
<a href="https://en.wikipedia.org/wiki/The_Lord_of_the_Rings" class="list-group-item list-group-item-action">
Lord of the Rings</a>
<a href="https://en.wikipedia.org/wiki/The_Forever_War" class="list-group-item list-group-item-action">
The Forever War</a>
<a href="https://en.wikipedia.org/wiki/2001:_A_Space_Odyssey_(novel)" class="list-group-item list-group-item-action">
2001 A Space Odyssey</a>
<a href="https://en.wikipedia.org/wiki/Ender%27s_Game" class="list-group-item list-group-item-action disabled" tabindex="-1" aria-disabled="true">Ender's Game</a>
</div>
<h2><a href="https://getbootstrap.com/docs/5.1/forms/form-control/">Forms</a></h2>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Email address</label>
<input type="email"
class="form-control"
id="exampleFormControlInput1"
placeholder="name@example.com">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Example textarea</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<h3><a href="https://getbootstrap.com/docs/5.1/forms/select/">Dropdowns</a></h3>
<select class="form-select">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<h3><a href="https://getbootstrap.com/docs/5.1/forms/checks-radios/#switches">Switches</a></h3>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="switch1">
<label class="form-check-label" for="switch1">Default switch checkbox input</label>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="switch2" checked>
<label class="form-check-label" for="switch2">Checked switch checkbox input</label>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="switch3" disabled>
<label class="form-check-label" for="switch3">Disabled switch checkbox input</label>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="switch4" checked disabled>
<label class="form-check-label" for="switch4">Disabled checked switch checkbox input</label>
</div>
<h3><a href="https://getbootstrap.com/docs/5.1/forms/range/#steps">Range</a></h3>
<div>
<label for="range1" class="form-label">Example range</label>
<input type="range" class="form-range" min="0" max="5" step="0.5" id="range1">
</div>
<h3><a href="https://getbootstrap.com/docs/5.1/forms/input-group/">Addons</a></h3>
<div class="input-group mb-3">
<span class="input-group-text">$</span>
<span class="input-group-text">0.00</span>
<input type="text" class="form-control">
</div>
<div class="input-group">
<input type="text" class="form-control">
<span class="input-group-text">$</span>
<span class="input-group-text">0.00</span>
</div>
<h3><a href="https://getbootstrap.com/docs/5.1/forms/layout/#horizontal-form">Responsive forms</a></h3>
<div class="mb-3 row">
<label for="email1" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="text"
class="form-control"
id="email1"
value="email@example.com">
</div>
</div>
<div class="mb-3 row">
<label for="password1" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password"
class="form-control"
id="password1">
</div>
</div>
<div class="mb-3 row">
<label for="textarea1" class="col-sm-2 col-form-label">Bio</label>
<div class="col-sm-10">
<textarea class="form-control"
id="textarea1"
rows="3"></textarea>
</div>
</div>
<h3><a href="https://getbootstrap.com/docs/5.1/forms/layout/#horizontal-form">Responsive forms</a></h3>
<form>
<div class="row mb-3">
<label for="r1" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="r1">
</div>
</div>
<div class="row mb-3">
<label for="r2" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="r2">
</div>
</div>
<fieldset class="row mb-3">
<legend class="col-form-label col-sm-2 pt-0">Radios</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio"
name="gridRadios" id="r3" value="option1" checked>
<label class="form-check-label" for="r3">First radio</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio"
name="gridRadios" id="r4" value="option2">
<label class="form-check-label" for="r4">Second radio</label>
</div>
<div class="form-check disabled">
<input class="form-check-input" type="radio"
name="gridRadios" id="r5" value="option3" disabled>
<label class="form-check-label" for="r5">Third disabled radio</label>
</div>
</div>
</fieldset>
<div class="row mb-3">
<div class="col-sm-10 offset-sm-2">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="r6">
<label class="form-check-label" for="r6">Example checkbox</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
<h2><a href="https://getbootstrap.com/docs/5.1/components/card/">Cards</a></h2>
<div class="card" style="width: 18rem;">
<img src="../../../tuiter/images/jupiter.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">
Some quick example text to build on the card title and
make up the bulk of the card's content.
</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<h2><a href="https://getbootstrap.com/docs/5.1/components/navs-tabs/">Tabs</a></h2>
<ul class="nav nav-tabs">
<li class="nav-item"><a class="nav-link active" href="#">Active</a></li>
<li class="nav-item"><a class="nav-link" href="#">Link</a></li>
<li class="nav-item"><a class="nav-link" href="#">Link</a></li>
<li class="nav-item"><a class="nav-link disabled" href="#" tabindex="-1">Disabled</a></li>
</ul>
<h3><a href="https://getbootstrap.com/docs/5.1/components/navs-tabs/#pills">Pills</a></h3>
<ul class="nav nav-pills">
<li class="nav-item"><a class="nav-link active" href="#">Active</a></li>
<li class="nav-item"><a class="nav-link" href="#">Link</a></li>
<li class="nav-item"><a class="nav-link" href="#">Link</a></li>
<li class="nav-item"><a class="nav-link disabled" href="#" tabindex="-1">Disabled</a>
</li>
</ul>
<h3>Overriding Bootstrap style</h3>
<button class="btn btn-primary">Regular Bootstrap Button</button>
<br/>
<br/>
<button class="btn btn-primary override-bs">Overriden Button</button>
<!--Fontawesome Starts Here!-->
<h2>Simple icons</h2>
<i class="fa fa-cog"></i>
<i class="fa fa-heart"></i>
<i class="fa fa-share"></i>
<i class="fa fa-comment"></i>
<br/>
<i class="fa fa-image"></i>
<i class="fa fa-chart-bar"></i>
<i class="fa fa-calendar"></i>
<i class="fa fa-smile"></i>
<h2>Resizing icons</h2>
<i class="fa fa-cog fa-2x"></i>
<i class="fa fa-heart fa-2x"></i>
<i class="fa fa-share fa-3x"></i>
<i class="fa fa-comment fa-3x"></i>
<br/>
<i class="fa fa-image fa-3x"></i>
<i class="fa fa-chart-bar fa-4x"></i>
<i class="fa fa-calendar" style="font-size: 5em"></i>
<i class="fa fa-smile" style="font-size: 3.5em"></i>
<h2>Coloring icons</h2>
<i class="fa fa-cog fa-2x" style="color: tomato"></i>
<i class="fa fa-heart fa-2x" style="color: tomato"></i>
<i class="fa fa-share fa-3x" style="color: #5ec15b"></i>
<br/>
<i class="fa fa-comment fa-3x" style="color: #19d49e"></i>
<i class="fa fa-image fa-3x" style="color: rgb(234,123,12)"></i>
<i class="fa fa-chart-bar fa-4x" style="color: rgb(123,234,123)"></i>
<h2>Brand icons</h2>
<i class="fab fa-twitter fa-2x"></i><br/>
<i class="fab fa-facebook fa-2x"></i><br/>
<i class="fab fa-apple fa-2x"></i><br/>
<h2>Stacking icons</h2>
<span class="fa-stack fa-2x">
<i class="fas fa-square fa-stack-2x"></i>
<i class="fab fa-twitter fa-stack-1x fa-inverse"></i>
</span>
<br/>
<span class="fa-stack fa-2x">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fas fa-flag fa-stack-1x fa-inverse"></i>
</span>
<br/>
<span class="fa-stack fa-2x">
<i class="fas fa-camera fa-stack-1x"></i>
<i class="fas fa-ban fa-stack-2x" style="color:Tomato"></i>
</span>
<br/>
<h2>Rotating icons</h2>
<div class="fa-4x">
<i class="fas fa-snowboarding"></i>
<i class="fas fa-snowboarding fa-rotate-90"></i>
<i class="fas fa-snowboarding fa-rotate-180"></i>
<br/>
<i class="fas fa-snowboarding fa-rotate-270"></i>
<i class="fas fa-snowboarding fa-flip-horizontal"></i>
<i class="fas fa-snowboarding fa-flip-vertical"></i>
<br/>
<i class="fas fa-snowboarding fa-flip-both"></i>
<br/>
</div>
<h2>Animating icons</h2>
<div class="fa-3x">
<i class="fas fa-spinner fa-spin"></i>
<i class="fas fa-circle-notch fa-spin"></i>
<i class="fas fa-sync fa-spin"></i><br/>
<i class="fas fa-cog fa-spin"></i>
<i class="fas fa-spinner fa-pulse"></i>
<i class="fas fa-stroopwafel fa-spin"></i>
</div>
<h2>Hiding and showing responsive content</h2>
<a href="https://getbootstrap.com/docs/5.1/utilities/display/">Bootstrap Display</a>
<div class="d-block d-sm-none fa-2x">XS</div>
<div class="d-none d-sm-block d-md-none fa-2x">S</div>
<div class="d-none d-md-block d-lg-none fa-2x">M</div>
<div class="d-none d-lg-block d-xl-none fa-2x">L</div>
<div class="d-none d-xl-block d-xxl-none fa-2x">XL</div>
<div class="d-none d-xxl-block fa-2x">XXL</div>
</body>
</html> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
<title>Movie List</title>
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Movie List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item active">
<a class="nav-link" href="#">
Home
<span class="visually-hidden">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Favorite</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- card+grid system -->
<div class="container mt-5">
<div class="row">
<!-- Search Bar -->
<!-- inline forms被歸類在layout -->
<div class="container mt-5">
<form class="row row-cols-lg-auto g-3 align-items-center mb-2" id="search-form">
<div class="col-12">
<label class="visually-hidden" for="search-input">
Search Keyword
</label>
<input type="text" class="form-control" id="search-input" placeholder="Keyword..." />
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary" id="search-submit-button">
Search
</button>
</div>
</form>
</div>
<div class="row" id="data-panel">
<!-- Render Movie List -->
</div>
</div>
</div>
<!-- paginator -->
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center" id="paginator">
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
</ul>
</nav>
<!-- Movie Modal -->
<div class="modal fade" id="movie-modal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="movie-modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="movie-modal-body">
<!-- row會有兩個division,一個是圖片,一個是文字 -->
<div class="row">
<div class="col-sm-8" id="movie-modal-image">
<img src="https://github.com/ALPHACamp/movie-list-api/blob/master/public/posters/c9XxwwhPHdaImA2f1WEfEsbhaFB.jpg?raw=true" alt="movie-poster" class="img-fuid"/>
</div>
<div class="col-sm-4">
<p><em id="movie-modal-date">vcrwvwwec</em></p>
<p id="movie-modal-description">This is a movie.</p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
<!-- 先引用axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- 載入bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"
integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"
integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13"
crossorigin="anonymous"></script>
<!-- 載入自己寫的js -->
<script src="./index.js"> </script>
</body>
</html> |
#
# (C) Tenable Network Security, Inc.
#
include("compat.inc");
if (description)
{
script_id(81743);
script_version("1.10");
script_cvs_date("Date: 2018/11/15 20:50:31");
script_cve_id("CVE-2015-0076");
script_bugtraq_id(72918);
script_xref(name:"MSFT", value:"MS15-029");
script_xref(name:"MSKB", value:"3035126");
script_xref(name:"IAVB", value:"2015-B-0034");
script_name(english:"MS15-029: Vulnerability in Windows Photo Decoder Component Could Allow Information Disclosure (3035126)");
script_summary(english:"Checks the file versions.");
script_set_attribute(attribute:"synopsis", value:
"The remote Windows host is affected by an information disclosure
vulnerability.");
script_set_attribute(attribute:"description", value:
"The version of Microsoft's Photo Decoder Component installed on the
remote Windows host is affected by an information disclosure
vulnerability due to improperly handled uninitialized memory when
parsing specially crafted JPEG XR (.JXR) image format files. A remote
attacker can exploit this vulnerability by convincing a user to visit
a website containing specially crafted JPEG image content, resulting
in the disclosure of information.");
script_set_attribute(attribute:"see_also", value:"https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/2015/ms15-029");
script_set_attribute(attribute:"solution", value:
"Microsoft has released a set of patches for Windows 2003, Vista, 2008,
7, 2008 R2, 8, 2012, 8.1, and 2012 R2.");
script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:P/I:N/A:N");
script_set_cvss_temporal_vector("CVSS2#E:H/RL:OF/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available");
script_set_attribute(attribute:"exploit_available", value:"true");
script_set_attribute(attribute:"exploited_by_malware", value:"true");
script_set_attribute(attribute:"vuln_publication_date", value:"2015/03/10");
script_set_attribute(attribute:"patch_publication_date", value:"2015/03/10");
script_set_attribute(attribute:"plugin_publication_date", value:"2015/03/10");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"cpe:/o:microsoft:windows");
script_set_attribute(attribute:"stig_severity", value:"II");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_family(english:"Windows : Microsoft Bulletins");
script_copyright(english:"This script is Copyright (C) 2015-2018 Tenable Network Security, Inc.");
script_dependencies("smb_hotfixes.nasl", "ms_bulletin_checks_possible.nasl");
script_require_keys("SMB/MS_Bulletin_Checks/Possible");
script_require_ports(139, 445, "Host/patch_management_checks");
exit(0);
}
include("audit.inc");
include("smb_hotfixes_fcheck.inc");
include("smb_hotfixes.inc");
include("smb_func.inc");
include("misc_func.inc");
get_kb_item_or_exit("SMB/MS_Bulletin_Checks/Possible");
bulletin = 'MS15-029';
kb = "3035126";
kbs = make_list(kb);
if (get_kb_item("Host/patch_management_checks")) hotfix_check_3rd_party(bulletin:bulletin, kbs:kbs, severity:SECURITY_WARNING);
get_kb_item_or_exit("SMB/Registry/Enumerated");
get_kb_item_or_exit("SMB/WindowsVersion", exit_code:1);
if (hotfix_check_sp_range(vista:'2', win7:'1', win8:'0', win81:'0') <= 0) audit(AUDIT_OS_SP_NOT_VULN);
if (
# Vista / Windows Server 2008
hotfix_is_vulnerable(os:"6.0", sp:2, file:"wmphoto.dll", version:"7.0.6002.23609", min_version:"7.0.6002.23000", dir:"\system32", bulletin:bulletin, kb:kb) ||
hotfix_is_vulnerable(os:"6.0", sp:2, file:"wmphoto.dll", version:"7.0.6002.19299", min_version:"7.0.6002.18000", dir:"\system32", bulletin:bulletin, kb:kb) ||
# Windows 7 / Server 2008 R2
hotfix_is_vulnerable(os:"6.1", sp:1, file:"wmphoto.dll", version:"6.2.9200.21371", min_version:"6.2.9200.20000", dir:"\system32", bulletin:bulletin, kb:kb) ||
hotfix_is_vulnerable(os:"6.1", sp:1, file:"wmphoto.dll", version:"6.2.9200.17254", min_version:"6.2.9200.16000", dir:"\system32", bulletin:bulletin, kb:kb) ||
hotfix_is_vulnerable(os:"6.1", sp:1, file:"wmphoto.dll", version:"6.1.7601.22949", min_version:"6.1.7601.22000", dir:"\system32", bulletin:bulletin, kb:kb) ||
hotfix_is_vulnerable(os:"6.1", sp:1, file:"wmphoto.dll", version:"6.1.7601.18742", min_version:"6.1.7600.18000", dir:"\system32", bulletin:bulletin, kb:kb) ||
# Windows 8 / Windows Server 2012
hotfix_is_vulnerable(os:"6.2", sp:0, file:"wmphoto.dll", version:"6.2.9200.21364", min_version:"6.2.9200.20000", dir:"\system32", bulletin:bulletin, kb:kb) ||
hotfix_is_vulnerable(os:"6.2", sp:0, file:"wmphoto.dll", version:"6.2.9200.17247", min_version:"6.2.9200.16000", dir:"\system32", bulletin:bulletin, kb:kb) ||
# Windows 8.1 / Windows Server 2012 R2
hotfix_is_vulnerable(os:"6.3", sp:0, file:"wmphoto.dll", version:"6.3.9600.17668", min_version:"6.3.9600.16000", dir:"\system32", bulletin:bulletin, kb:kb)
)
{
set_kb_item(name:'SMB/Missing/'+bulletin, value:TRUE);
hotfix_security_warning();
hotfix_check_fversion_end();
exit(0);
}
else
{
hotfix_check_fversion_end();
audit(AUDIT_HOST_NOT, 'affected');
} |
import React, { useEffect } from "react";
import { useParams } from "react-router-dom";
import { fetchRecipeInformation } from "../../features/detailsSlice";
import { useDispatch, useSelector } from "react-redux";
import "./RecipeDetails.css";
function RecipeDetails() {
const dispatch = useDispatch();
const selectedRecipe = useSelector((state) => state.details.selectedRecipe);
const { id } = useParams();
useEffect(() => {
dispatch(fetchRecipeInformation(id));
}, [dispatch, id]);
return (
<div className="details-container">
<div className="img-container">
<img src={selectedRecipe.image} alt={selectedRecipe.title} />
</div>
<div className="recipe-details">
<h2>{selectedRecipe.title}</h2>
<p>
<span>Cooking Time:</span>
{selectedRecipe.readyInMinutes} minutes
</p>
<p>
<span>Servings :</span>
{selectedRecipe.servings}
</p>
<div>
<span>Ingredients :</span>
{selectedRecipe?.extendedIngredients?.map((ingredient, index) => (
<div key={index}>
<p>{ingredient.name}</p>
</div>
))}
</div>
<p>
<span>instructions : </span>
{selectedRecipe.instructions}
</p>
</div>
</div>
);
}
export default RecipeDetails; |
# Prerequisites
- [MongoDB](https://www.mongodb.com/try/download/community), [MongoDB Tutorial](https://github.com/Grasscutters/Grasscutter/wiki/Resources#mongodb-tutorial)
- [Java SE Development Kits - 17](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html)
# Starting the Server
**If you haven't already, download `grasscutter.jar` from [actions](https://github.com/Grasscutters/Grasscutter/actions/workflows/build.yml)/[4benj](https://jenkins.4benj.com/job/Grasscutters/job/Grasscutter/lastSuccessfulBuild/) or [build the server by yourself](https://github.com/Grasscutters/Grasscutter/wiki/Building)**.
1. Download the whole repository and download/build your `grasscutter.jar` and put it inside the grasscutter folder.
2. Copy the following files to the following directories: (file source -> `destination`)
- [yukiz](https://gitlab.com/yukiz/GrasscutterResources/) or [Koko-boya](https://github.com/Koko-boya/Grasscutter_Resources) -> `resources`
3. Run `java -jar grasscutter.jar`
- This will create additional directories in your working directory.
4. Run `java -jar grasscutter.jar -handbook`
- This is required for using `names -> IDs` in commands.
- This setup is optional and can be skipped.
**Note:** Make sure to setup your operating system firewall settings
- Windows: Make sure to allow their port on Windows Firewall Settings (80, 443, 8888, and 22102)
- Linux: Make sure to write `sudo ufw allow 22102`, `sudo ufw allow 443`, `sudo ufw allow 80`, and `sudo ufw allow 8888` .
5. Continue to [Connecting](#connecting)
# Connecting
**Note**: This works for connecting to external servers as well.
## Prerequisites
- [mitmproxy](https://mitmproxy.org/), [Fiddler Classic](https://telerik-fiddler.s3.amazonaws.com/fiddler/FiddlerSetup.exe), [Hosts file](https://github.com/Grasscutters/Grasscutter/wiki/Resources#hosts-file) (or another proxy to redirect web traffic)
1. Run your choosen web traffic proxy.
2. Route all traffic going to HoYoVerse/MiHoYo servers using [mitmproxy](https://github.com/Grasscutters/Grasscutter#:~:text=mitmdump:), [Fiddler](https://github.com/Grasscutters/Grasscutter#:~:text=Fiddler%20Classic:) or [Hosts file](https://github.com/Grasscutters/Grasscutter/wiki/Resources#hosts-file) to the server host.
3. Launch Genshin Impact and have fun!
## Startup Sequence
- Start MongoDB -> Start Grasscutter -> Start your choosen Proxy Daemon -> Patch your Metadata / UserAssembly -> Start Game
## [Traffic Route Map](https://github.com/Grasscutters/Grasscutter/issues/1447)
```
dispatchosglobal.yuanshen.com -> (redirect to the server host)
dispatchcnglobal.yuanshen.com -> (redirect to the server host)
osusadispatch.yuanshen.com -> (redirect to the server host)
oseurodispatch.yuanshen.com -> (redirect to the server host)
osasiadispatch.yuanshen.com -> (redirect to the server host)
hk4e-api-os-static.mihoyo.com -> (redirect to the server host)
hk4e-api-static.mihoyo.com -> (redirect to the server host)
hk4e-api-os.mihoyo.com -> (redirect to the server host)
hk4e-api.mihoyo.com -> (redirect to the server host)
hk4e-sdk-os.mihoyo.com -> (redirect to the server host)
hk4e-sdk.mihoyo.com -> (redirect to the server host)
account.mihoyo.com -> (redirect to the server host)
api-os-takumi.mihoyo.com -> (redirect to the server host)
api-takumi.mihoyo.com -> (redirect to the server host)
sdk-os-static.mihoyo.com -> (redirect to the server host)
sdk-static.mihoyo.com -> (redirect to the server host)
webstatic-sea.mihoyo.com -> (redirect to the server host)
webstatic.mihoyo.com -> (redirect to the server host)
uploadstatic-sea.mihoyo.com -> (redirect to the server host)
uploadstatic.mihoyo.com -> (redirect to the server host)
api-os-takumi.hoyoverse.com -> (redirect to the server host)
sdk-os-static.hoyoverse.com -> (redirect to the server host)
sdk-os.hoyoverse.com -> (redirect to the server host)
webstatic-sea.hoyoverse.com -> (redirect to the server host)
uploadstatic-sea.hoyoverse.com -> (redirect to the server host)
api-takumi.hoyoverse.com -> (redirect to the server host)
sdk-static.hoyoverse.com -> (redirect to the server host)
sdk.hoyoverse.com -> (redirect to the server host)
webstatic.hoyoverse.com -> (redirect to the server host)
uploadstatic.hoyoverse.com -> (redirect to the server host)
account.hoyoverse.com -> (redirect to the server host)
api-account-os.hoyoverse.com -> (redirect to the server host)
api-account.hoyoverse.com -> (redirect to the server host)
hk4e-api-os.hoyoverse.com -> (redirect to the server host)
hk4e-api-os-static.hoyoverse.com -> (redirect to the server host)
hk4e-sdk-os.hoyoverse.com -> (redirect to the server host)
hk4e-sdk-os-static.hoyoverse.com -> (redirect to the server host)
hk4e-api.hoyoverse.com -> (redirect to the server host)
hk4e-api-static.hoyoverse.com -> (redirect to the server host)
hk4e-sdk.hoyoverse.com -> (redirect to the server host)
hk4e-sdk-static.hoyoverse.com -> (redirect to the server host)
log-upload.mihoyo.com -> (redirect to 0.0.0.0)
log-upload-os.mihoyo.com -> (redirect to 0.0.0.0)
log-upload-os.hoyoverse.com -> (redirect to 0.0.0.0)
devlog-upload.mihoyo.com -> (redirect to 0.0.0.0)
overseauspider.yuanshen.com -> (redirect to 0.0.0.0)
``` |
<template>
<view>
<mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ use: true }" :up="upOption"
@up="upCallback">
<u-sticky bgColor="#fff">
<u-tabs :list="tabs" :is-scroll="false" :current="curTab" active-color="#571fb2" :duration="0.2"
@change="onChangeTab" />
</u-sticky>
<view v-if="curTab ==0" class="a-mx-3 a-pb-3">
<view v-for="(item,index) in list.data" :key="index" class="a-flex a-align-center a-justify-between a-rounded-1-5 a-bg-gradual-red-LR a-p-2 a-mt-2">
<view class="a-flex a-flex-1 a-align-center">
<view class="a-w-120 a-h-120 a-rounded-1-5 a-overflow-hidden a-mr-2">
<image class="a-w-120 a-h-120 a-rounded-1-5" src="/static/images/lo-redEnvelop.png"></image>
</view>
<view class="a-flex-1 a-flex-column">
<text class="a-font-lg a-text-yellow">{{$t('user.openRedEnvelope')}}</text>
<text class="a-font-sm a-text-yellow">{{item.time_label}}</text>
</view>
</view>
<view @click="openRed(item.order_no)" class="a-bg-gradual-yellow-LR a-right-0 a-py-1 a-px-3 a-rounded-circle a-ml-2">
<text class="a-text-red">{{$t('button.OPEN')}}</text>
</view>
</view>
</view>
<view v-else class="a-mx-3 a-pb-3">
<view v-for="(item,index) in list.data" :key="index" class="a-bg-orange-light a-rounded-1-5 a-mt-2 a-px-3 a-py-3">
<view class="a-flex a-align-center a-justify-between">
<text class="a-font a-text-brown-light">{{$t('user.redEnvelope')}}</text>
<view class="a-flex a-align-end">
<text class="a-font-lg a-text-red">{{item.amount}}</text>
<text class="a-font a-text-red a-ml">Rs</text>
</view>
</view>
<view class="a-flex a-align-center a-justify-between a-mt-2">
<text class="a-font-sm a-text-gray">{{item.add_time}}</text>
</view>
</view>
</view>
</mescroll-body>
<u-popup v-model="showPopup" mode="center" :closeable="true" :border-radius="26">
<view class="a-w-600 a-rounded-1-5 a-p-5">
<view class="a-w-500 a-h-400 a-position-relative a-mb-3">
<image class="a-w-500 a-h-400 a-position-absolute" src="/static/images/lo-redEnvelope.png"></image>
<view class="a-flex a-align-end a-justify-center a-position-relative a-pt-5" style="z-index:1">
<text class="a-font-lg a-text-red a-font-weight-bold a-mb-1">₹</text>
<text class="a-font-max-five a-text-red a-font-weight-bold">{{amount}}</text>
</view>
</view>
<view class="a-flex a-align-center a-justify-center a-pb-3">
<view @click="closeShowPopup" class="a-bg-yellow a-h-90 a-w-480 a-rounded-circle a-flex a-align-center a-justify-center">
<text class="a-font-lg a-text-brown">{{$t('button.determine')}}</text>
</view>
</view>
</view>
</u-popup>
</view>
</template>
<script>
import MescrollBody from '@/components/mescroll-uni/mescroll-body.vue'
import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins'
import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
import * as Api from '@/api/user'
const pageSize = 1
export default {
components: {
MescrollBody,
},
mixins: [MescrollMixin],
data() {
return {
// tab栏数据
tabs:[{
name: this.$t('user.redEnvelope'),
value: '0'
}, {
name: this.$t('user.record'),
value: '1'
}],
// 当前标签索引
curTab: 0,
list: getEmptyPaginateObj(),
// 上拉加载配置
upOption: {
// 首次自动执行
auto: true,
// 每页数据的数量; 默认10
page: { size: pageSize },
// 数量要大于4条才显示无更多数据
noMoreSize: 4,
// 空布局
empty: { tip: '' }
},
amount:null,
showPopup:false,
}
},
methods: {
openShowPopup() {
this.showPopup = true
},
closeShowPopup() {
this.showPopup = false
},
// 切换标签项
onChangeTab(index) {
const app = this
// 设置当前选中的标签
app.curTab = index
this.onRefreshList()
},
// 刷新订单列表
onRefreshList() {
this.list = getEmptyPaginateObj()
setTimeout(() => {
this.mescroll.resetUpScroll()
}, 120)
},
/**
* 上拉加载的回调 (页面初始化时也会执行一次)
* 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
* @param {Object} page
*/
upCallback(page) {
const app = this
var count = app.list.data.length
if(count){
var index = count-1
var id = app.list.data[index].id
}else{
var id = null
}
// 设置列表数据
app.getList(id).then(list => {
const curPageLen = list.data.length
const totalSize = list.count
app.mescroll.endBySize(curPageLen, totalSize)
})
.catch(() => app.mescroll.endErr())
},
// 获取订单列表
getList(id) {
const that = this
return new Promise((resolve, reject) => {
var data={
next_id:id
};
if(that.curTab == 0){
Api.redList(data).then(result =>{
const newList = result.data
newList.data = result.data.list
that.list.data = getMoreListData(newList, that.list)
resolve(newList)
})
}else{
Api.redRecordList(data).then(result =>{
const newList = result.data
newList.data = result.data.list
that.list.data = getMoreListData(newList, that.list)
resolve(newList)
})
}
})
},
openRed(order_no){
const that = this
var params = {
order_no:order_no
}
Api.redReceive({form:params}).then(result =>{
if(result.status =='200'){
that.amount = result.data.amount
that.openShowPopup()
that.onRefreshList()
}
})
}
}
}
</script>
<style lang="scss">
page{
background-color: #F8F8F8;
}
</style> |
;;; This code snippet is an example of a function in LISP that recursively calculates the factorial of a given number
(defun factorial (n) ;;; define the function with parameter n
(if (<= n 1) 1 ;;; if n is less than or equal to 1, return 1 as base case
(* n (factorial (- n 1))) ;;; otherwise, multiply n by the factorial of n-1
)
)
(factorial 5) ;;; call the factorial function with input 5, output: 120 |
#%NASL_MIN_LEVEL 70300
#
# (C) Tenable Network Security, Inc.
#
include('deprecated_nasl_level.inc');
include('compat.inc');
if (description)
{
script_id(62468);
script_version("1.16");
script_set_attribute(attribute:"plugin_modification_date", value:"2022/04/11");
script_cve_id("CVE-2012-2552");
script_bugtraq_id(55783);
script_xref(name:"MSFT", value:"MS12-070");
script_xref(name:"MSKB", value:"983814");
script_xref(name:"MSKB", value:"2716427");
script_xref(name:"MSKB", value:"2716429");
script_xref(name:"MSKB", value:"2716433");
script_xref(name:"MSKB", value:"2716434");
script_xref(name:"MSKB", value:"2716435");
script_xref(name:"MSKB", value:"2716436");
script_xref(name:"MSKB", value:"2716439");
script_xref(name:"MSKB", value:"2716440");
script_xref(name:"MSKB", value:"2716441");
script_xref(name:"MSKB", value:"2716442");
script_xref(name:"MSKB", value:"2754849");
script_name(english:"MS12-070: Vulnerability in SQL Server Could Allow Elevation of Privilege (2754849) (uncredentialed check)");
script_set_attribute(attribute:"synopsis", value:
"A cross-site scripting vulnerability in SQL Server could allow
elevation of privilege.");
script_set_attribute(attribute:"description", value:
"The remote host has a version of Microsoft SQL Server installed. This
version of SQL Server is running SQL Server Reporting Services (SRSS),
which is affected by a cross-site scripting (XSS) vulnerability that
could allow elevation of privileges. Successful exploitation could
allow an attacker to execute arbitrary commands on the SSRS site in
the context of the targeted user. An attacker would need to entice a
user to visit a specially crafted link in order to exploit the
vulnerability.");
# https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/2012/ms12-070
script_set_attribute(attribute:"see_also", value:"http://www.nessus.org/u?70fa5df5");
script_set_attribute(attribute:"solution", value:
"Microsoft has released a set of patches for SQL Server 2000, 2005,
2008, 2008 R2, and 2012.");
script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:N/I:P/A:N");
script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C");
script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:N/I:L/A:N");
script_set_cvss3_temporal_vector("CVSS:3.0/E:U/RL:O/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available");
script_set_attribute(attribute:"exploit_available", value:"false");
script_cwe_id(20, 74, 79, 442, 629, 711, 712, 722, 725, 750, 751, 800, 801, 809, 811, 864, 900, 928, 931, 990);
script_set_attribute(attribute:"vuln_publication_date", value:"2012/10/09");
script_set_attribute(attribute:"patch_publication_date", value:"2012/10/09");
script_set_attribute(attribute:"plugin_publication_date", value:"2012/10/10");
script_set_attribute(attribute:"plugin_type", value:"remote");
script_set_attribute(attribute:"cpe", value:"cpe:/a:microsoft:sql_server");
script_set_attribute(attribute:"thorough_tests", value:"true");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_family(english:"Windows");
script_copyright(english:"This script is Copyright (C) 2012-2022 and is owned by Tenable, Inc. or an Affiliate thereof.");
script_dependencies("mssqlserver_detect.nasl");
script_require_keys("Settings/ParanoidReport");
script_require_ports(1433, "Services/mssql");
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("misc_func.inc");
if (report_paranoia < 2)
audit(AUDIT_PARANOID);
port = get_service(svc:"mssql", exit_on_fail:TRUE);
pcidss = get_kb_item("Settings/PCI_DSS");
ver = get_kb_item("MSSQL/" + port + "/Version");
if (!ver) audit(AUDIT_SERVICE_VER_FAIL,"MSSQL", port);
v = split(ver, sep:".", keep:FALSE);
if (
# 2000 SP2
# (int(v[0]) == 8 && int(v[1]) == 0 && (int(v[2]) >= 1038 && int(v[2]) < 1077)) ||
# 2005 < SP4
(pcidss && (int(v[0]) == 9 && int(v[1]) == 0 && int(v[2]) < 5000)) ||
# 2005 SP4 GDR
(int(v[0]) == 9 && int(v[1]) == 0 && (int(v[2]) >= 5000 && int(v[2]) < 5069)) ||
# 2005 SP4 QFE
(int(v[0]) == 9 && int(v[1]) == 0 && (int(v[2]) >= 5200 && int(v[2]) < 5324)) ||
# 2008 < SP2
(pcidss && (int(v[0]) == 10 && int(v[1]) == 0 && int(v[2]) < 4000)) ||
# 2008 SP2 GDR
(int(v[0]) == 10 && int(v[1]) == 0 && (int(v[2]) >= 4000 && int(v[2]) < 4067)) ||
# 2008 SP2 QFE
(int(v[0]) == 10 && int(v[1]) == 0 && (int(v[2]) >= 4260 && int(v[2]) < 4371)) ||
# 2008 SP3 QFE
(int(v[0]) == 10 && int(v[1]) == 0 && (int(v[2]) >= 5500 && int(v[2]) < 5512)) ||
# 2008 SP3 GDR
(int(v[0]) == 10 && int(v[1]) == 0 && (int(v[2]) >= 5750 && int(v[2]) < 5825)) ||
# 2008 R2 < SP1
(pcidss && (int(v[0]) == 10 && int(v[1]) == 50 && int(v[2]) < 2500)) ||
# 2008 R2 SP1 GDR
(int(v[0]) == 10 && int(v[1]) == 50 && (int(v[2]) >= 2500 && int(v[2]) < 2550)) ||
# 2008 R2 SP1 QFE
(int(v[0]) == 10 && int(v[1]) == 50 && (int(v[2]) >= 2750 && int(v[2]) < 2861)) ||
# 2012 GDR
(int(v[0]) == 11 && int(v[1]) == 0 && (int(v[2]) >= 2100 && int(v[2]) < 2218)) ||
# 2012 QFE
(int(v[0]) == 11 && int(v[1]) == 0 && (int(v[2]) >= 2300 && int(v[2]) < 2376))
)
{
set_kb_item(name:"www/0/XSS", value:TRUE);
version = get_kb_item("MSSQL/" + port + "/Version");
instance = get_kb_item("MSSQL/" + port + "/InstanceName");
if(!isnull(version) || !empty_or_null(instance))
{
report = '';
if(version) report += '\n SQL Server Version : ' + version;
if(!empty_or_null(instance)) report += '\n SQL Server Instance : ' + instance;
}
security_report_v4(port:port, extra:report, severity:SECURITY_WARNING);
exit(0);
}
audit(AUDIT_INST_VER_NOT_VULN, "MSSQL", ver); |
---
title: Premiere on Linux? No Problem! 10 Alternative Video Editors
date: 2024-05-19T11:46:49.598Z
updated: 2024-05-20T11:46:49.598Z
tags:
- video editing software
- video editing
categories:
- ai
- video
description: This Article Describes Premiere on Linux? No Problem! 10 Alternative Video Editors
excerpt: This Article Describes Premiere on Linux? No Problem! 10 Alternative Video Editors
keywords: video editing on linux made easy top 10 adobe premiere alternatives,linux loves video editing 10 alternatives to adobe premiere pro,premiere on linux no problem top 10 alternative video editors,linux premiere pro alternatives top picks for video editors,linux premiere pro alternatives top 10 video editors you need to know,linux video editing top alternatives to adobe premiere pro,premiere on linux no problem 10 alternative video editors
thumbnail: https://www.lifewire.com/thmb/koSaGJ5iVSnQrrvXh53lyy1rSZM=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/podcasts-safeforkids-5b2f3dd4eb97de0036d9f87b.jpg
---
## Premiere on Linux? No Problem! 10 Alternative Video Editors
Undoubtedly, Adobe products are being used worldwide commercially, but for people with smaller budgets, several high-quality products are available for Linux. Different Adobe Premiere Alternatives for Linux are available, which have a relatively lower cost or are free of charge.
This article will discuss the best alternatives to Adobe Premiere for Linux, which are listed below. Before going through each of them, let’s first check if we can install Premiere Pro on Linux System.
**Can I Install Premiere Pro On My Linux System?**
No, Adobe Premiere Pro is not available to install on Linux systems. You have to go for its different alternatives,
1. [DaVinci Resolve](#part1-1)
2. [OpenShot](#part1-2)
3. [Pitivi](#part1-3)
4. [Shotcut](#part1-4)
5. [Avidemux](#part1-5)
6. [Cinelerra](#part1-6)
7. [Kdenlive](#part1-7)
8. [Lightworks](#part1-8)
9. [Flowblade](#part1-9)
10. [Open Movie Editor](#part1-10)
* [How to Choose an Alternative to Adobe Premiere Pro for Linux?](#part2)
## Best 10 Alternatives to Adobe Premiere Pro for Linux
### 1\. [DaVinci Resolve](https://www.blackmagicdesign.com/products/davinciresolve)
DaVinci Resolve, a tool being used as an alternative to Adobe Premiere Pro for Linux, provides features like color correction, editing, motion graphics, and audio post-production.
It is easy to learn and use, yet a handy tool for professionals. Using DaVinci Resolve, you can build your multi-user post-production studio.
DaVinci Resolve interface is divided into different pages, providing you with a dedicated workspace for a specific task. You must buy the paid version to get access to all features.

**Main features:**
* Multi-user collaboration
* Color correction
* All-in-one software for post-production
Pros
* Multiple resolutions and formats are available.
* Quick processing
* Advanced audio processing
Cons
* Some features are limited only to the paid version
* Confusing interface
* Requires much CPU capacity
**Supported OS: [Linux](https://www.linux.org/), Windows (version 8 and 10+), OSX (11+)**
**Best for:**
DaVinci Resolve is best for professionals as well as for day-to-day use. It has all the basic as well as professional working programs.
**Price:** 295$ for DaVinci Resolve Studio
**Ratings:** 4.1/5
According to [TrustRadius Ratings](https://www.trustradius.com/products/davinci-resolve/reviews#overview), DaVinci Resolve has almost 75% of 9-10 reviews. A total of 18 positive and two negative reviews.
**Summary & user review**
DaVinci Resolve is the software that can solve most of your editing-related problems. With many editing options, it is the tool for all your projects. Both free and paid versions are available. A [TrustRadius Ratings and Reviews](https://www.trustradius.com/reviews/davinci-resolve-2022-06-10-23-18-24) review states, “ None like it out there.”
### 2\. [OpenShot](https://www.openshot.org/)
OpenShot is an easy-to-use, simple-to-understand, and surprisingly powerful video editing tool designed to make video editing straightforward. OpenShot is an alternative to Adobe Premiere Pro for Linux, and its features make it a valuable and handy video editing software.
It is available in 70+ languages. It might be lacking some features for professional use, but it contains all the essential video editing tools for daily use.

**Main features:**
* Unlimited tracks
* 3D Animation
* Trim and Cut
* Title Editing
* Different video effects
Pros
* Completely free
* It can be used as a video editing learning tool
* Easy to use
Cons
* Keeps crashing
* Time-consuming tool
* Can’t create good quality animations
**Supported OS: [Linux](https://www.linux.org/), Windows (version 7,8 and 10+), OSX (10.15+)**
**Best for:**
It is best for most users for day-to-day use, but it is not recommended for professional use. You should use other video editing tools for professional and advanced video editing.
**Price:** Free
**Ratings:** 4.5/5
According to [G2 Ratings](https://www.g2.com), OpenShot has almost 85% of 9-10 reviews. A total of 27 positive and one negative review.
**Summary & user review**
OpenShot video editor is a free and easy-to-use tool for beginners and primary users. With many features and editing options, such as removing the background from the video, inverting color, adjusting brightness, slowing down or speeding up, and reversing the video, it can help create a good-quality video. A review regarding OpenShot on [G2 Ratings and Reviews](https://www.g2.com/products/openshot-video-editor/reviews#reviews) states: “Easy to use even for beginners.”
### 3\. [Pitivi](https://www.pitivi.org/)
Pitivi video editor is an alternative to Adobe Premiere Pro for Linux. It is a simple and unique video editor, that is free and comes with a lot of video editing and transforming features.
It is software designed for beginners and is suitable for creating simple and basic videos for social media platforms like Facebook and TikTok. Its easy user interface makes it a user-friendly tool.

**Main features:**
* Automatic backups
* Enhanced audio effects
* Framerate independent timeline
* Background processing of video being edited
* Animations, filters, and different transitions
Pros
* Completely free
* Easy to use
* Audio can be edited precisely
* Changes in the video can be seen in real-time
* Automatic backup
* Background processing of thumbnails
Cons
* Only basic editing can be done
* Not recommended for professional use
* Lagging issues
* Compatible with Linux only
**Supported OS: [Linux](https://www.linux.org/)**
**Best for:**
Best for beginners and people with primary use. Day-to-day videos for social media use can easily be edited.
**Price:** Free
**Ratings:** 4.3/5
According to [Slant Ratings](https://www.slant.co/), Pitivi has almost 75% of 04-05 ratings. A total of 13 positive and 03 negative reviews.
**Summary & user review**
It is a simple, unique, and free video editor for beginners. Casual and basic editing can be done using Pitivi.
A review on [Slant Ratings and reviews states](https://www.slant.co/options/7478/~pitivi-review),” Free, open source, and easy to use.” and this sums it all up.
### 4\. [Shotcut](https://shotcut.org/)
Shotcut is a free, regularly updated video editing software, with powerful features and an easy user interface. It can be used as an alternative to Adobe Premiere Pro for Linux.
It offers a simple, user-friendly UI. Shotcut, in contrast to most free video editors, provides features like chroma key and color correction. It contains all the basic and some advanced video editing options but is not recommended for professional use.

**Main features:**
* Incredibly easy keyframing
* Editing and transitions
* Exporting
* Sleek, user-friendly interface
Pros
* Easy to use
* Regular updates
* Advanced effects
* High-quality input/output support
Cons
* A bit frustrating because of lag
* No preview for effects and transitions
* No stock music
* Can't upload external subtitles
**Supported OS: [Linux](https://www.linux.org/), Mac, Windows**
**Best for:**
ShotCut is best for beginners and professionals with basic editing needs. It is your go-to editor for editing Youtube or Facebook videos.
**Price:** 9.79$ at Microsoft US
**Ratings:** 4.3/5
According to [G2 Ratings](https://www.g2.com), ShotCut has almost 85% of 04-05 ratings. A total of 33 positive and 04 negative reviews. A review on [G2 Ratings and Reviews](https://www.g2.com/products/shotcut/reviews) states,” [Amazing Lightweight Free Basic](https://www.g2.com/survey%5Fresponses/shotcut-review-6512378)[Video Editor.”](https://www.g2.com/survey%5Fresponses/shotcut-review-6512378)
**Summary & user review**
Shotcut can be used to produce both basic and advanced-level videos. It can be very helpful and handy for professionals in their editing.
### 5\. [Avidemux](http://avidemux.sourceforge.net/)
Avidemux is a perfect tool for simple edits. With limited editing options, it is a very easy-to-use editor for beginners. You can cut, crop, copy or delete parts of your video. 2 or more video clips can also be merged by using Avidemux.
It can render and export at high speeds. Avidemux contains advanced features like a green screen, audio editing, and change speed.

**Main features:**
* Audio filters
* Video filters and transitions
* Advanced interlacing
* Open source
* Container format
* Encoder
Pros
* Free
* Easy interface
* Standard editing formats available
Cons
* No updates
* No customer support
* No timeline
**Supported OS: Linux**
**Best for:**
Avidemux is best for editing, cutting, resizing, and encoding multiple video formats, including MPEG, AVI, MP4, and DVD.
**Price:** Free
**Ratings:** 4.5/5
According to [G2 Ratings](https://www.g2.com), Avidemux has almost 90% of 4-5 ratings. A total of 8 positive and one negative review.
**Summary & user review**
Avidemux is a handy video editing software for day-to-day use and it can edit your videos in no time. It is easy to use even for beginners. A review on [G2 Ratings and reviews](https://www.g2.com/products/sourceforge-avidemux/reviews) states, “ Avidemux is best for beginners.”
### 6\. [Cinelerra](http://cinelerra.org/)
Cinelerra is a free video editing tool that you can use to edit your video and make it look wonderful with different transitions, effects, and texts. Cinelerra is free and open-source software and is considered one of the most used editing softwares for Linux.
It can edit videos of any quality you want and provides you with a perfect video according to your demands. It is helpful for beginners and also handy for professionals.

**Main features:**
* Video and audio editing
* Different transitions and effects
* Floating point imaging
* Color correction
* Video stabilization
* Motion tracking
* 400 plus decoders and 150 plus encoders
Pros
* Contains all professional features
* It has 3D editing tools
* Real-time processing of the video
* User friendly
Cons
* Only available for Linux
* Some codecs are not supported
* Four windows might get confusing sometimes
**Supported OS: Linux**
**Best for:**
It is the best free editing tool for professional and non-professional use. With a lot of video effects and transitions, it makes your video look like a movie.
**Price:** Free
**Ratings:** 4.2/5
According to [Slant Ratings](https://www.slant.co/), Cinelerra has almost 90% of 04-05 ratings. A total of 19 positive and 02 negative reviews.
**Summary & user review**
Cinelerra is a user-friendly software that has some advanced features like 3D video editing and is free of cost. A review on [VideoHelp ratings and reviews](https://www.videohelp.com/software/Cinelerra/reviews) states, “The GG version has many professional features. Easy to install too.”
### 7\. Kdenlive
Kdenlive is a free and open-source video editor that can be used in place of Adobe Premiere Pro on Linux. Its best features include multi-track video editing, audio/video formatting, configurable interface and shortcuts, many effects and transitions, audio and video scopes, proxy editing, automatic backup, timeline preview, keyframeable effects, a simple interface, and much more.
Kdenlive lets you use and mix many audio and video tracks, each of which can be locked or muted as needed.

**Main features:**
* Multi tracks editing
* It supports almost all audio and video formats
* Many shortcuts available
* Titler
* Multiple effects and transitions
* Automatic backup
* Timeline preview
* Keyframing
* Online resources available
Pros
* Automatic backup
* Dozens of transitions and effects
* User-friendly interface
* Fast and stable performance
* Supports 420 plus formats
Cons
* Basic editing
* Not recommended for professional use
* It crashes if you have a slow computer
**Supported OS: [Linux](https://www.linux.org/), Windows, Mac, [FreeBSD](https://www.freebsd.org/), [Ubuntu](https://ubuntu.com/)**
**Best for:**
Kdenlive is best for casual video editing for social media platforms. Good videos with multiple effects and transitions can be created using this software.
**Price:** Free
**Ratings:** 4.1/5
According to [Slant Ratings](https://www.slant.co/), Kdenlive has almost 70% of 04-05 ratings. A total of 228 positive and 53 negative reviews.
**Summary & user review**
Kdenlive is a free and open-source editing software that is free and easy to use.
A review on [AlternativeTo Ratings and Reviews](https://alternativeto.net/software/kdenlive/about/#post-23629) states, “This is so much more awesome and I worked on it for over 2 hours, and it didn't crash or lag even once.”
### 8\. [Lightworks](https://lwks.com/)
Lightworks is a video editing software that is used to enhance the content of videos by both film industry experts and social media marketers. Its free version can satisfy most of its users but if you want more advanced features, you'll need to pay for this. It is a video editing tool with multi-track editing capabilities and is also powerful, and customizable.

**Main features:**
* Drag and drop interface
* Color correction
* Blend modes
* Rendering effects
* Applying chromakeys
* Video routing
* Keyframing
* Export to Youtube directly
Pros
* Multiplatform
* Audio/Video editing
* Tutorials available
* Active user forum
* Good performance
Cons
* Export option limited to only 720p
* Difficult for beginners
* You've to pay for advanced features
**Supported OS: [Linux](https://www.linux.org/), Mac, Windows**
**Best for:**
Its paid version is best for professionals to create videos with multiple effects and transitions. The free version can also be used for casual video editing.
**Price:** Lightworks pro is available at 9.99$/month. Its free version is also available.
**Ratings:** 4.3/5
According to [G2 Ratings](https://www.g2.com), Lightworks has almost 75% of 4-5 ratings. A total of 22 positive and 05 negative reviews.
**Summary & user review**
It is an easy-to-use, advanced, and paid video editing software for Linux for people with a low budget. A review on [G2 Ratings and Reviews](https://www.g2.com/products/lightworks/reviews) states, “Good editing platform for intermediate users.”
### 9\. [Flowblade](https://jliljebl.github.io/flowblade/)
Flowblade is a very famous, easy-to-use, simple, and fast video editor which can be used as an alternative to Adobe Premiere Pro for Linux. Flowblade is an open-source editor that offers all basic editing options.
It has constantly amazed its users with the smoothness of its playback. There is an inbuilt render UI, which makes the process of delivering your work pretty innocuous.

**Main features:**
* Editing tool (Insert, Move, Trim, Roll)
* Audio/Video filters
* Proxy editing
* Audio mixer
* Inbuilt rendering
* Titler (Multiple text layers)
Pros
* Powerful
* Multifunctional
* Open source
* Stable
Cons
* For Linux only
* Lack of advanced editing features
* Requires higher display resolutions
**Supported OS: [Linux](https://www.linux.org/)**
**Best for:**
It provides a fast, precise, and robust editing experience. It is best for normal day-to-day use.
**Price:** 24.99$/month; 174.99$/year
**Ratings:** 4.5/5
According to [Slant Ratings](https://www.slant.co/), Flowblade has almost 90% of 04-05 ratings. A total of 61 positive and 05 negative reviews.
**Summary & user review**
Flowblade is advanced, paid, fast, and precise video editing software for people with a low budget. A review on [Slant Ratings and Reviews](https://www.slant.co/options/7480/~flowblade-review) states, “Power, lightweight and multifunctional.”
### 10\. [Open Movie Editor](http://www.openmovieeditor.org/)
Open Movie Editor is a free and open-source video editing application for generating basic movies. It aspires to be powerful enough for the inexperienced filmmaker while being simple to use. It can be used as an alternative to Adobe Premiere Pro for Linux.
It helps to create titles in Inkscape. The Open Movie Editor supports a variety of file formats, frame rates, frame sizes, video codecs, and video containers. The Open Movie Editor provides a range of Tools and Filters for adjusting colors and improving the appearance of your videos.

**Main features:**
* Color grading
* Filter effects
* Different Audio/Video formats
* 3D video editing
* Text overlay
* HD resolution
Pros
* Simple
* Free
* 70 plus languages
* Export your project in 4K, 60FPS
Cons
* Crashes very often
* Rendering speed is slow
* Hard to control video effects
**Supported OS: [Linux](https://www.linux.org/), OS X, Windows**
**Best for:**
It is best for casual use and video editing with limited features. For professional work, you should opt another video editor.
**Price:** Free
**Ratings:** 4.0/5
According to [Slant Ratings](https://www.slant.co/), Open Movie Editor has almost 60% of 04-05 ratings. A total of 25 positive and 16 negative reviews.
**Summary & user review**
It is a simple, free, and easy-to-use video editor that can edit and export videos in high resolutions.
A review on [Slant Ratings and Reviews](https://www.slant.co/) states,” An easy to use and powerful video editor.”
## How to Choose an Alternative to Adobe Premiere Pro for Linux?
Out of these 10 software discussed above, which software you want to use is still a bit confusing. If you need basic editing software that is free and open source, you should go for Kdenlive
DaVinci Resolve provides advanced editing features such as color correction, and multi-track editing. This can be your choice if you have a good budget.
Lightworks and Flowblade are the best options if you have got a low budget and need advanced editing options. They provide a good value for money experience.
Open Movie Editor, Cinelerra, Avidemux, OpenShot, and Pitivi are free and easy-to-use software that are the best options for beginners.
Besides, if you are going to switch from Linux to Windows or MacOS. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) can be your good choice to go. It owns built-in stock media and features that are not so complicated as compared to other software.
## Final Words
It has been discussed in detail that there are many free as well as paid editing software that can be used for Linux. Adobe premiere pro is not available for Linux, so one must go with any of these above-mentioned editing products. Free versions are for beginners as they contain basic editing features but paid versions can fulfill the demands of professional moviemakers too.
You can download and install any software according to your demands very easily as they are available on the app store. In the absence of adobe premiere pro, these products add such effects and transitions to your videos/films that make them amazing and thrilling to watch.
[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
Best 10 Alternatives to Adobe Premiere Pro for Linux
### 1\. [DaVinci Resolve](https://www.blackmagicdesign.com/products/davinciresolve)
DaVinci Resolve, a tool being used as an alternative to Adobe Premiere Pro for Linux, provides features like color correction, editing, motion graphics, and audio post-production.
It is easy to learn and use, yet a handy tool for professionals. Using DaVinci Resolve, you can build your multi-user post-production studio.
DaVinci Resolve interface is divided into different pages, providing you with a dedicated workspace for a specific task. You must buy the paid version to get access to all features.

**Main features:**
* Multi-user collaboration
* Color correction
* All-in-one software for post-production
Pros
* Multiple resolutions and formats are available.
* Quick processing
* Advanced audio processing
Cons
* Some features are limited only to the paid version
* Confusing interface
* Requires much CPU capacity
**Supported OS: [Linux](https://www.linux.org/), Windows (version 8 and 10+), OSX (11+)**
**Best for:**
DaVinci Resolve is best for professionals as well as for day-to-day use. It has all the basic as well as professional working programs.
**Price:** 295$ for DaVinci Resolve Studio
**Ratings:** 4.1/5
According to [TrustRadius Ratings](https://www.trustradius.com/products/davinci-resolve/reviews#overview), DaVinci Resolve has almost 75% of 9-10 reviews. A total of 18 positive and two negative reviews.
**Summary & user review**
DaVinci Resolve is the software that can solve most of your editing-related problems. With many editing options, it is the tool for all your projects. Both free and paid versions are available. A [TrustRadius Ratings and Reviews](https://www.trustradius.com/reviews/davinci-resolve-2022-06-10-23-18-24) review states, “ None like it out there.”
### 2\. [OpenShot](https://www.openshot.org/)
OpenShot is an easy-to-use, simple-to-understand, and surprisingly powerful video editing tool designed to make video editing straightforward. OpenShot is an alternative to Adobe Premiere Pro for Linux, and its features make it a valuable and handy video editing software.
It is available in 70+ languages. It might be lacking some features for professional use, but it contains all the essential video editing tools for daily use.

**Main features:**
* Unlimited tracks
* 3D Animation
* Trim and Cut
* Title Editing
* Different video effects
Pros
* Completely free
* It can be used as a video editing learning tool
* Easy to use
Cons
* Keeps crashing
* Time-consuming tool
* Can’t create good quality animations
**Supported OS: [Linux](https://www.linux.org/), Windows (version 7,8 and 10+), OSX (10.15+)**
**Best for:**
It is best for most users for day-to-day use, but it is not recommended for professional use. You should use other video editing tools for professional and advanced video editing.
**Price:** Free
**Ratings:** 4.5/5
According to [G2 Ratings](https://www.g2.com), OpenShot has almost 85% of 9-10 reviews. A total of 27 positive and one negative review.
**Summary & user review**
OpenShot video editor is a free and easy-to-use tool for beginners and primary users. With many features and editing options, such as removing the background from the video, inverting color, adjusting brightness, slowing down or speeding up, and reversing the video, it can help create a good-quality video. A review regarding OpenShot on [G2 Ratings and Reviews](https://www.g2.com/products/openshot-video-editor/reviews#reviews) states: “Easy to use even for beginners.”
### 3\. [Pitivi](https://www.pitivi.org/)
Pitivi video editor is an alternative to Adobe Premiere Pro for Linux. It is a simple and unique video editor, that is free and comes with a lot of video editing and transforming features.
It is software designed for beginners and is suitable for creating simple and basic videos for social media platforms like Facebook and TikTok. Its easy user interface makes it a user-friendly tool.

**Main features:**
* Automatic backups
* Enhanced audio effects
* Framerate independent timeline
* Background processing of video being edited
* Animations, filters, and different transitions
Pros
* Completely free
* Easy to use
* Audio can be edited precisely
* Changes in the video can be seen in real-time
* Automatic backup
* Background processing of thumbnails
Cons
* Only basic editing can be done
* Not recommended for professional use
* Lagging issues
* Compatible with Linux only
**Supported OS: [Linux](https://www.linux.org/)**
**Best for:**
Best for beginners and people with primary use. Day-to-day videos for social media use can easily be edited.
**Price:** Free
**Ratings:** 4.3/5
According to [Slant Ratings](https://www.slant.co/), Pitivi has almost 75% of 04-05 ratings. A total of 13 positive and 03 negative reviews.
**Summary & user review**
It is a simple, unique, and free video editor for beginners. Casual and basic editing can be done using Pitivi.
A review on [Slant Ratings and reviews states](https://www.slant.co/options/7478/~pitivi-review),” Free, open source, and easy to use.” and this sums it all up.
### 4\. [Shotcut](https://shotcut.org/)
Shotcut is a free, regularly updated video editing software, with powerful features and an easy user interface. It can be used as an alternative to Adobe Premiere Pro for Linux.
It offers a simple, user-friendly UI. Shotcut, in contrast to most free video editors, provides features like chroma key and color correction. It contains all the basic and some advanced video editing options but is not recommended for professional use.

**Main features:**
* Incredibly easy keyframing
* Editing and transitions
* Exporting
* Sleek, user-friendly interface
Pros
* Easy to use
* Regular updates
* Advanced effects
* High-quality input/output support
Cons
* A bit frustrating because of lag
* No preview for effects and transitions
* No stock music
* Can't upload external subtitles
**Supported OS: [Linux](https://www.linux.org/), Mac, Windows**
**Best for:**
ShotCut is best for beginners and professionals with basic editing needs. It is your go-to editor for editing Youtube or Facebook videos.
**Price:** 9.79$ at Microsoft US
**Ratings:** 4.3/5
According to [G2 Ratings](https://www.g2.com), ShotCut has almost 85% of 04-05 ratings. A total of 33 positive and 04 negative reviews. A review on [G2 Ratings and Reviews](https://www.g2.com/products/shotcut/reviews) states,” [Amazing Lightweight Free Basic](https://www.g2.com/survey%5Fresponses/shotcut-review-6512378)[Video Editor.”](https://www.g2.com/survey%5Fresponses/shotcut-review-6512378)
**Summary & user review**
Shotcut can be used to produce both basic and advanced-level videos. It can be very helpful and handy for professionals in their editing.
### 5\. [Avidemux](http://avidemux.sourceforge.net/)
Avidemux is a perfect tool for simple edits. With limited editing options, it is a very easy-to-use editor for beginners. You can cut, crop, copy or delete parts of your video. 2 or more video clips can also be merged by using Avidemux.
It can render and export at high speeds. Avidemux contains advanced features like a green screen, audio editing, and change speed.

**Main features:**
* Audio filters
* Video filters and transitions
* Advanced interlacing
* Open source
* Container format
* Encoder
Pros
* Free
* Easy interface
* Standard editing formats available
Cons
* No updates
* No customer support
* No timeline
**Supported OS: Linux**
**Best for:**
Avidemux is best for editing, cutting, resizing, and encoding multiple video formats, including MPEG, AVI, MP4, and DVD.
**Price:** Free
**Ratings:** 4.5/5
According to [G2 Ratings](https://www.g2.com), Avidemux has almost 90% of 4-5 ratings. A total of 8 positive and one negative review.
**Summary & user review**
Avidemux is a handy video editing software for day-to-day use and it can edit your videos in no time. It is easy to use even for beginners. A review on [G2 Ratings and reviews](https://www.g2.com/products/sourceforge-avidemux/reviews) states, “ Avidemux is best for beginners.”
### 6\. [Cinelerra](http://cinelerra.org/)
Cinelerra is a free video editing tool that you can use to edit your video and make it look wonderful with different transitions, effects, and texts. Cinelerra is free and open-source software and is considered one of the most used editing softwares for Linux.
It can edit videos of any quality you want and provides you with a perfect video according to your demands. It is helpful for beginners and also handy for professionals.

**Main features:**
* Video and audio editing
* Different transitions and effects
* Floating point imaging
* Color correction
* Video stabilization
* Motion tracking
* 400 plus decoders and 150 plus encoders
Pros
* Contains all professional features
* It has 3D editing tools
* Real-time processing of the video
* User friendly
Cons
* Only available for Linux
* Some codecs are not supported
* Four windows might get confusing sometimes
**Supported OS: Linux**
**Best for:**
It is the best free editing tool for professional and non-professional use. With a lot of video effects and transitions, it makes your video look like a movie.
**Price:** Free
**Ratings:** 4.2/5
According to [Slant Ratings](https://www.slant.co/), Cinelerra has almost 90% of 04-05 ratings. A total of 19 positive and 02 negative reviews.
**Summary & user review**
Cinelerra is a user-friendly software that has some advanced features like 3D video editing and is free of cost. A review on [VideoHelp ratings and reviews](https://www.videohelp.com/software/Cinelerra/reviews) states, “The GG version has many professional features. Easy to install too.”
### 7\. Kdenlive
Kdenlive is a free and open-source video editor that can be used in place of Adobe Premiere Pro on Linux. Its best features include multi-track video editing, audio/video formatting, configurable interface and shortcuts, many effects and transitions, audio and video scopes, proxy editing, automatic backup, timeline preview, keyframeable effects, a simple interface, and much more.
Kdenlive lets you use and mix many audio and video tracks, each of which can be locked or muted as needed.

**Main features:**
* Multi tracks editing
* It supports almost all audio and video formats
* Many shortcuts available
* Titler
* Multiple effects and transitions
* Automatic backup
* Timeline preview
* Keyframing
* Online resources available
Pros
* Automatic backup
* Dozens of transitions and effects
* User-friendly interface
* Fast and stable performance
* Supports 420 plus formats
Cons
* Basic editing
* Not recommended for professional use
* It crashes if you have a slow computer
**Supported OS: [Linux](https://www.linux.org/), Windows, Mac, [FreeBSD](https://www.freebsd.org/), [Ubuntu](https://ubuntu.com/)**
**Best for:**
Kdenlive is best for casual video editing for social media platforms. Good videos with multiple effects and transitions can be created using this software.
**Price:** Free
**Ratings:** 4.1/5
According to [Slant Ratings](https://www.slant.co/), Kdenlive has almost 70% of 04-05 ratings. A total of 228 positive and 53 negative reviews.
**Summary & user review**
Kdenlive is a free and open-source editing software that is free and easy to use.
A review on [AlternativeTo Ratings and Reviews](https://alternativeto.net/software/kdenlive/about/#post-23629) states, “This is so much more awesome and I worked on it for over 2 hours, and it didn't crash or lag even once.”
### 8\. [Lightworks](https://lwks.com/)
Lightworks is a video editing software that is used to enhance the content of videos by both film industry experts and social media marketers. Its free version can satisfy most of its users but if you want more advanced features, you'll need to pay for this. It is a video editing tool with multi-track editing capabilities and is also powerful, and customizable.

**Main features:**
* Drag and drop interface
* Color correction
* Blend modes
* Rendering effects
* Applying chromakeys
* Video routing
* Keyframing
* Export to Youtube directly
Pros
* Multiplatform
* Audio/Video editing
* Tutorials available
* Active user forum
* Good performance
Cons
* Export option limited to only 720p
* Difficult for beginners
* You've to pay for advanced features
**Supported OS: [Linux](https://www.linux.org/), Mac, Windows**
**Best for:**
Its paid version is best for professionals to create videos with multiple effects and transitions. The free version can also be used for casual video editing.
**Price:** Lightworks pro is available at 9.99$/month. Its free version is also available.
**Ratings:** 4.3/5
According to [G2 Ratings](https://www.g2.com), Lightworks has almost 75% of 4-5 ratings. A total of 22 positive and 05 negative reviews.
**Summary & user review**
It is an easy-to-use, advanced, and paid video editing software for Linux for people with a low budget. A review on [G2 Ratings and Reviews](https://www.g2.com/products/lightworks/reviews) states, “Good editing platform for intermediate users.”
### 9\. [Flowblade](https://jliljebl.github.io/flowblade/)
Flowblade is a very famous, easy-to-use, simple, and fast video editor which can be used as an alternative to Adobe Premiere Pro for Linux. Flowblade is an open-source editor that offers all basic editing options.
It has constantly amazed its users with the smoothness of its playback. There is an inbuilt render UI, which makes the process of delivering your work pretty innocuous.

**Main features:**
* Editing tool (Insert, Move, Trim, Roll)
* Audio/Video filters
* Proxy editing
* Audio mixer
* Inbuilt rendering
* Titler (Multiple text layers)
Pros
* Powerful
* Multifunctional
* Open source
* Stable
Cons
* For Linux only
* Lack of advanced editing features
* Requires higher display resolutions
**Supported OS: [Linux](https://www.linux.org/)**
**Best for:**
It provides a fast, precise, and robust editing experience. It is best for normal day-to-day use.
**Price:** 24.99$/month; 174.99$/year
**Ratings:** 4.5/5
According to [Slant Ratings](https://www.slant.co/), Flowblade has almost 90% of 04-05 ratings. A total of 61 positive and 05 negative reviews.
**Summary & user review**
Flowblade is advanced, paid, fast, and precise video editing software for people with a low budget. A review on [Slant Ratings and Reviews](https://www.slant.co/options/7480/~flowblade-review) states, “Power, lightweight and multifunctional.”
### 10\. [Open Movie Editor](http://www.openmovieeditor.org/)
Open Movie Editor is a free and open-source video editing application for generating basic movies. It aspires to be powerful enough for the inexperienced filmmaker while being simple to use. It can be used as an alternative to Adobe Premiere Pro for Linux.
It helps to create titles in Inkscape. The Open Movie Editor supports a variety of file formats, frame rates, frame sizes, video codecs, and video containers. The Open Movie Editor provides a range of Tools and Filters for adjusting colors and improving the appearance of your videos.

**Main features:**
* Color grading
* Filter effects
* Different Audio/Video formats
* 3D video editing
* Text overlay
* HD resolution
Pros
* Simple
* Free
* 70 plus languages
* Export your project in 4K, 60FPS
Cons
* Crashes very often
* Rendering speed is slow
* Hard to control video effects
**Supported OS: [Linux](https://www.linux.org/), OS X, Windows**
**Best for:**
It is best for casual use and video editing with limited features. For professional work, you should opt another video editor.
**Price:** Free
**Ratings:** 4.0/5
According to [Slant Ratings](https://www.slant.co/), Open Movie Editor has almost 60% of 04-05 ratings. A total of 25 positive and 16 negative reviews.
**Summary & user review**
It is a simple, free, and easy-to-use video editor that can edit and export videos in high resolutions.
A review on [Slant Ratings and Reviews](https://www.slant.co/) states,” An easy to use and powerful video editor.”
## How to Choose an Alternative to Adobe Premiere Pro for Linux?
Out of these 10 software discussed above, which software you want to use is still a bit confusing. If you need basic editing software that is free and open source, you should go for Kdenlive
DaVinci Resolve provides advanced editing features such as color correction, and multi-track editing. This can be your choice if you have a good budget.
Lightworks and Flowblade are the best options if you have got a low budget and need advanced editing options. They provide a good value for money experience.
Open Movie Editor, Cinelerra, Avidemux, OpenShot, and Pitivi are free and easy-to-use software that are the best options for beginners.
Besides, if you are going to switch from Linux to Windows or MacOS. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) can be your good choice to go. It owns built-in stock media and features that are not so complicated as compared to other software.
## Final Words
It has been discussed in detail that there are many free as well as paid editing software that can be used for Linux. Adobe premiere pro is not available for Linux, so one must go with any of these above-mentioned editing products. Free versions are for beginners as they contain basic editing features but paid versions can fulfill the demands of professional moviemakers too.
You can download and install any software according to your demands very easily as they are available on the app store. In the absence of adobe premiere pro, these products add such effects and transitions to your videos/films that make them amazing and thrilling to watch.
[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
<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>
## Top VirtualDub Replacements for Video Editing
# Similar Software or Alternatives to VirtualDub

##### Ollie Mattison
Mar 27, 2024• Proven solutions
VirtualDub is a free and powerful video capture and processing software for Windows platform. For those who have previously used VirtualDub for editing or recording their videos files, are you looking for an alternative that runs on different platforms (Windows, Mac and Linux)? In this article, we introduce top 10 VirtualDub alternatives. Read on and find the best one that fits your needs.
## Best Alternatives to VirtualDub
#### 1\. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Wondershare Filmora is an ideal VirtualDub alternative. It virtually supports much more formats than VirtualDub and includes almost all the common video editing functions VirtualDub provides. Although it doesn't support plug-ins, you can easily easily retouch your video with effects like jump cut, tilt-shift and much more and share your works with the world.
[](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/)
### Main features of Wondershare Filmora Video Editor
* Intuitive interface
It provides a nice organized work space that allows for video, text and audio layering. The drag-n-drop feature enables you to easily access everything. The preview window is also included in the main interface so that you're able to see the real-time effect immediately.
* Powerful editing functions
You can adjust your video using Contrast, Brightness and Saturation options with just one-click. An array of video effects like video filters, transitions, intro/credits, tilt shift, mosaic, face off, jump cut and more are also provided to enhance your video instantly.
* Various output selections
When the editing process is over, you can easily save or share the creation. Different output methods include encoding the video into a specific file format that's compatible with mobile devices; direct uploading onto YouTube or Facebook or burning a DVD
#### 2\. [Video Converter](https://tools.techidaily.com/wondershare/videoconverter/download/)
Video Converter supports the processing and conversion of almost all of the popular file types that's currently used. It has less editing options provided by VirtualDub, but the built-in video editor also provides several basic video editing functions such as crop, trim, rotate, add filters and more. On top of that, you can download videos directly from the online sites or create and burn your own videos onto a DVD. The preset of best video settings for playback on a variety of portable devices makes it even more convenient.
#### 3\. [Virtual VCR](http://sourceforge.net/projects/virtualvcr/?source=directory)

Virtual VCR is a DirectShow video capture application for Windows. It works together with video capture cards to capture audio and video to your hard drive in the AVI file format. It also digitizes audio/video content from sources like webcams, camcorders, and VCRs (Video Cassette Recorder). However, the editing functions are less powerful compared to VirtualDub.
#### 4\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)

Free Video Dub is lightweight and user-friendly video editing tool for Windows which just like VirtualDub. It supports various video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. The main function is to delete the unwanted parts from video files without re-coding, which means it keeps the original quality of your video, so it may lack of some video editing functions you're looking for.
#### 5[Avidemux](http://fixounet.free.fr/avidemux/)

Avidemux is very close to VirtualDub on the basis of functions. It even runs on more platforms including Linux, Mac OS X and Windows. It's designed for simple video cutting, filtering and encoding tasks. It supports more file types than VirtualdDub, including AVI, DVD compatible MPEG files, MP4 and ASF, using a variety of codecs. Tasks can be automated using projects, job queue and powerful scripting.
#### 6[OpenShot](http://www.openshot.org/)

OpenShot comes with a more user-friendly interface than VirtualDub. It supports different audio, video and image formats and enables you to do some basic video editing tasks such as trim, cut, crop and more. It also let you easily add subtitles, transitions and effects, and then export your video to DVD, YouTube, Vimeo, Xbox 360, and many other common formats.
#### 7[Windows Movie Maker](https://windows-movie-maker.en.softonic.com/)

Windows Movie Maker is a free video editing software for Windows. You can easily edit, edit and share your videos with a few simple drag-n-drops. The editing features include adding video effects, transitions, titles/credits, audio track, narration and more. When the editing is done, you can directly share your video via the web, email or CD.
#### 8[iMovie](http://www.apple.com/mac/imovie/)

iMovie is a great and free video editor for Mac which receives good reputation. It's equipped with many creative features such as movie trailer, one step video and audio effect, PIP function and more. When you finish all the editing process, iMovie enables you to share your video to YouTube or export for your iPad, iPhone, iTunes, etc. But it doesn't support plugins any more.
#### 9[Jahshaka](http://www.jahshaka.com/)

Jahshaka is an advanced video editor currently runs on Linux, Windows and Mac OS X. It has multiple capabilities: make make 2D/3D animations, correct colors and edit video and more. You can also easily manage and share all the elements you need as a part of creating impressive content.
#### 10[Video Toolbox](http://www.videotoolbox.com/)

Video Toolbox is a free online video editing tool to help you convert, edit, cut, record, crop or demux video files. It's very easy to use - you just need to upload your files, select the task you need, do the editing and the site will process the video for you.

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
VirtualDub is a free and powerful video capture and processing software for Windows platform. For those who have previously used VirtualDub for editing or recording their videos files, are you looking for an alternative that runs on different platforms (Windows, Mac and Linux)? In this article, we introduce top 10 VirtualDub alternatives. Read on and find the best one that fits your needs.
## Best Alternatives to VirtualDub
#### 1\. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Wondershare Filmora is an ideal VirtualDub alternative. It virtually supports much more formats than VirtualDub and includes almost all the common video editing functions VirtualDub provides. Although it doesn't support plug-ins, you can easily easily retouch your video with effects like jump cut, tilt-shift and much more and share your works with the world.
[](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/)
### Main features of Wondershare Filmora Video Editor
* Intuitive interface
It provides a nice organized work space that allows for video, text and audio layering. The drag-n-drop feature enables you to easily access everything. The preview window is also included in the main interface so that you're able to see the real-time effect immediately.
* Powerful editing functions
You can adjust your video using Contrast, Brightness and Saturation options with just one-click. An array of video effects like video filters, transitions, intro/credits, tilt shift, mosaic, face off, jump cut and more are also provided to enhance your video instantly.
* Various output selections
When the editing process is over, you can easily save or share the creation. Different output methods include encoding the video into a specific file format that's compatible with mobile devices; direct uploading onto YouTube or Facebook or burning a DVD
#### 2\. [Video Converter](https://tools.techidaily.com/wondershare/videoconverter/download/)
Video Converter supports the processing and conversion of almost all of the popular file types that's currently used. It has less editing options provided by VirtualDub, but the built-in video editor also provides several basic video editing functions such as crop, trim, rotate, add filters and more. On top of that, you can download videos directly from the online sites or create and burn your own videos onto a DVD. The preset of best video settings for playback on a variety of portable devices makes it even more convenient.
#### 3\. [Virtual VCR](http://sourceforge.net/projects/virtualvcr/?source=directory)

Virtual VCR is a DirectShow video capture application for Windows. It works together with video capture cards to capture audio and video to your hard drive in the AVI file format. It also digitizes audio/video content from sources like webcams, camcorders, and VCRs (Video Cassette Recorder). However, the editing functions are less powerful compared to VirtualDub.
#### 4\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)

Free Video Dub is lightweight and user-friendly video editing tool for Windows which just like VirtualDub. It supports various video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. The main function is to delete the unwanted parts from video files without re-coding, which means it keeps the original quality of your video, so it may lack of some video editing functions you're looking for.
#### 5[Avidemux](http://fixounet.free.fr/avidemux/)

Avidemux is very close to VirtualDub on the basis of functions. It even runs on more platforms including Linux, Mac OS X and Windows. It's designed for simple video cutting, filtering and encoding tasks. It supports more file types than VirtualdDub, including AVI, DVD compatible MPEG files, MP4 and ASF, using a variety of codecs. Tasks can be automated using projects, job queue and powerful scripting.
#### 6[OpenShot](http://www.openshot.org/)

OpenShot comes with a more user-friendly interface than VirtualDub. It supports different audio, video and image formats and enables you to do some basic video editing tasks such as trim, cut, crop and more. It also let you easily add subtitles, transitions and effects, and then export your video to DVD, YouTube, Vimeo, Xbox 360, and many other common formats.
#### 7[Windows Movie Maker](https://windows-movie-maker.en.softonic.com/)

Windows Movie Maker is a free video editing software for Windows. You can easily edit, edit and share your videos with a few simple drag-n-drops. The editing features include adding video effects, transitions, titles/credits, audio track, narration and more. When the editing is done, you can directly share your video via the web, email or CD.
#### 8[iMovie](http://www.apple.com/mac/imovie/)

iMovie is a great and free video editor for Mac which receives good reputation. It's equipped with many creative features such as movie trailer, one step video and audio effect, PIP function and more. When you finish all the editing process, iMovie enables you to share your video to YouTube or export for your iPad, iPhone, iTunes, etc. But it doesn't support plugins any more.
#### 9[Jahshaka](http://www.jahshaka.com/)

Jahshaka is an advanced video editor currently runs on Linux, Windows and Mac OS X. It has multiple capabilities: make make 2D/3D animations, correct colors and edit video and more. You can also easily manage and share all the elements you need as a part of creating impressive content.
#### 10[Video Toolbox](http://www.videotoolbox.com/)

Video Toolbox is a free online video editing tool to help you convert, edit, cut, record, crop or demux video files. It's very easy to use - you just need to upload your files, select the task you need, do the editing and the site will process the video for you.

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
VirtualDub is a free and powerful video capture and processing software for Windows platform. For those who have previously used VirtualDub for editing or recording their videos files, are you looking for an alternative that runs on different platforms (Windows, Mac and Linux)? In this article, we introduce top 10 VirtualDub alternatives. Read on and find the best one that fits your needs.
## Best Alternatives to VirtualDub
#### 1\. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Wondershare Filmora is an ideal VirtualDub alternative. It virtually supports much more formats than VirtualDub and includes almost all the common video editing functions VirtualDub provides. Although it doesn't support plug-ins, you can easily easily retouch your video with effects like jump cut, tilt-shift and much more and share your works with the world.
[](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/)
### Main features of Wondershare Filmora Video Editor
* Intuitive interface
It provides a nice organized work space that allows for video, text and audio layering. The drag-n-drop feature enables you to easily access everything. The preview window is also included in the main interface so that you're able to see the real-time effect immediately.
* Powerful editing functions
You can adjust your video using Contrast, Brightness and Saturation options with just one-click. An array of video effects like video filters, transitions, intro/credits, tilt shift, mosaic, face off, jump cut and more are also provided to enhance your video instantly.
* Various output selections
When the editing process is over, you can easily save or share the creation. Different output methods include encoding the video into a specific file format that's compatible with mobile devices; direct uploading onto YouTube or Facebook or burning a DVD
#### 2\. [Video Converter](https://tools.techidaily.com/wondershare/videoconverter/download/)
Video Converter supports the processing and conversion of almost all of the popular file types that's currently used. It has less editing options provided by VirtualDub, but the built-in video editor also provides several basic video editing functions such as crop, trim, rotate, add filters and more. On top of that, you can download videos directly from the online sites or create and burn your own videos onto a DVD. The preset of best video settings for playback on a variety of portable devices makes it even more convenient.
#### 3\. [Virtual VCR](http://sourceforge.net/projects/virtualvcr/?source=directory)

Virtual VCR is a DirectShow video capture application for Windows. It works together with video capture cards to capture audio and video to your hard drive in the AVI file format. It also digitizes audio/video content from sources like webcams, camcorders, and VCRs (Video Cassette Recorder). However, the editing functions are less powerful compared to VirtualDub.
#### 4\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)

Free Video Dub is lightweight and user-friendly video editing tool for Windows which just like VirtualDub. It supports various video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. The main function is to delete the unwanted parts from video files without re-coding, which means it keeps the original quality of your video, so it may lack of some video editing functions you're looking for.
#### 5[Avidemux](http://fixounet.free.fr/avidemux/)

Avidemux is very close to VirtualDub on the basis of functions. It even runs on more platforms including Linux, Mac OS X and Windows. It's designed for simple video cutting, filtering and encoding tasks. It supports more file types than VirtualdDub, including AVI, DVD compatible MPEG files, MP4 and ASF, using a variety of codecs. Tasks can be automated using projects, job queue and powerful scripting.
#### 6[OpenShot](http://www.openshot.org/)

OpenShot comes with a more user-friendly interface than VirtualDub. It supports different audio, video and image formats and enables you to do some basic video editing tasks such as trim, cut, crop and more. It also let you easily add subtitles, transitions and effects, and then export your video to DVD, YouTube, Vimeo, Xbox 360, and many other common formats.
#### 7[Windows Movie Maker](https://windows-movie-maker.en.softonic.com/)

Windows Movie Maker is a free video editing software for Windows. You can easily edit, edit and share your videos with a few simple drag-n-drops. The editing features include adding video effects, transitions, titles/credits, audio track, narration and more. When the editing is done, you can directly share your video via the web, email or CD.
#### 8[iMovie](http://www.apple.com/mac/imovie/)

iMovie is a great and free video editor for Mac which receives good reputation. It's equipped with many creative features such as movie trailer, one step video and audio effect, PIP function and more. When you finish all the editing process, iMovie enables you to share your video to YouTube or export for your iPad, iPhone, iTunes, etc. But it doesn't support plugins any more.
#### 9[Jahshaka](http://www.jahshaka.com/)

Jahshaka is an advanced video editor currently runs on Linux, Windows and Mac OS X. It has multiple capabilities: make make 2D/3D animations, correct colors and edit video and more. You can also easily manage and share all the elements you need as a part of creating impressive content.
#### 10[Video Toolbox](http://www.videotoolbox.com/)

Video Toolbox is a free online video editing tool to help you convert, edit, cut, record, crop or demux video files. It's very easy to use - you just need to upload your files, select the task you need, do the editing and the site will process the video for you.

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
VirtualDub is a free and powerful video capture and processing software for Windows platform. For those who have previously used VirtualDub for editing or recording their videos files, are you looking for an alternative that runs on different platforms (Windows, Mac and Linux)? In this article, we introduce top 10 VirtualDub alternatives. Read on and find the best one that fits your needs.
## Best Alternatives to VirtualDub
#### 1\. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Wondershare Filmora is an ideal VirtualDub alternative. It virtually supports much more formats than VirtualDub and includes almost all the common video editing functions VirtualDub provides. Although it doesn't support plug-ins, you can easily easily retouch your video with effects like jump cut, tilt-shift and much more and share your works with the world.
[](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/)
### Main features of Wondershare Filmora Video Editor
* Intuitive interface
It provides a nice organized work space that allows for video, text and audio layering. The drag-n-drop feature enables you to easily access everything. The preview window is also included in the main interface so that you're able to see the real-time effect immediately.
* Powerful editing functions
You can adjust your video using Contrast, Brightness and Saturation options with just one-click. An array of video effects like video filters, transitions, intro/credits, tilt shift, mosaic, face off, jump cut and more are also provided to enhance your video instantly.
* Various output selections
When the editing process is over, you can easily save or share the creation. Different output methods include encoding the video into a specific file format that's compatible with mobile devices; direct uploading onto YouTube or Facebook or burning a DVD
#### 2\. [Video Converter](https://tools.techidaily.com/wondershare/videoconverter/download/)
Video Converter supports the processing and conversion of almost all of the popular file types that's currently used. It has less editing options provided by VirtualDub, but the built-in video editor also provides several basic video editing functions such as crop, trim, rotate, add filters and more. On top of that, you can download videos directly from the online sites or create and burn your own videos onto a DVD. The preset of best video settings for playback on a variety of portable devices makes it even more convenient.
#### 3\. [Virtual VCR](http://sourceforge.net/projects/virtualvcr/?source=directory)

Virtual VCR is a DirectShow video capture application for Windows. It works together with video capture cards to capture audio and video to your hard drive in the AVI file format. It also digitizes audio/video content from sources like webcams, camcorders, and VCRs (Video Cassette Recorder). However, the editing functions are less powerful compared to VirtualDub.
#### 4\. [Free Video Dub](http://www.dvdvideosoft.com/products/dvd/Free-Video-Dub.htm)

Free Video Dub is lightweight and user-friendly video editing tool for Windows which just like VirtualDub. It supports various video formats including AVI, MOV, FLV, MOD, MKV, MTS/M2TS and more. The main function is to delete the unwanted parts from video files without re-coding, which means it keeps the original quality of your video, so it may lack of some video editing functions you're looking for.
#### 5[Avidemux](http://fixounet.free.fr/avidemux/)

Avidemux is very close to VirtualDub on the basis of functions. It even runs on more platforms including Linux, Mac OS X and Windows. It's designed for simple video cutting, filtering and encoding tasks. It supports more file types than VirtualdDub, including AVI, DVD compatible MPEG files, MP4 and ASF, using a variety of codecs. Tasks can be automated using projects, job queue and powerful scripting.
#### 6[OpenShot](http://www.openshot.org/)

OpenShot comes with a more user-friendly interface than VirtualDub. It supports different audio, video and image formats and enables you to do some basic video editing tasks such as trim, cut, crop and more. It also let you easily add subtitles, transitions and effects, and then export your video to DVD, YouTube, Vimeo, Xbox 360, and many other common formats.
#### 7[Windows Movie Maker](https://windows-movie-maker.en.softonic.com/)

Windows Movie Maker is a free video editing software for Windows. You can easily edit, edit and share your videos with a few simple drag-n-drops. The editing features include adding video effects, transitions, titles/credits, audio track, narration and more. When the editing is done, you can directly share your video via the web, email or CD.
#### 8[iMovie](http://www.apple.com/mac/imovie/)

iMovie is a great and free video editor for Mac which receives good reputation. It's equipped with many creative features such as movie trailer, one step video and audio effect, PIP function and more. When you finish all the editing process, iMovie enables you to share your video to YouTube or export for your iPad, iPhone, iTunes, etc. But it doesn't support plugins any more.
#### 9[Jahshaka](http://www.jahshaka.com/)

Jahshaka is an advanced video editor currently runs on Linux, Windows and Mac OS X. It has multiple capabilities: make make 2D/3D animations, correct colors and edit video and more. You can also easily manage and share all the elements you need as a part of creating impressive content.
#### 10[Video Toolbox](http://www.videotoolbox.com/)

Video Toolbox is a free online video editing tool to help you convert, edit, cut, record, crop or demux video files. It's very easy to use - you just need to upload your files, select the task you need, do the editing and the site will process the video for you.

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>
## Calculating Perfection: The Top 5 Things to Know About 16X9 Ratios
##### 5 Facts About 16x9 Ratio Calculator You Didn't Know
An easy yet powerful editor
Numerous effects to choose from
Detailed tutorials provided by the official channel
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
This article explains major concepts about **16x9 ratio calculator** and applies them even if you are a novice.
Read it to conclude the aspect ratio and the type of editing you need for your videos.
#### In this article
01 [What is Aspect Ratio?](#Part 1)
02 [What's 16:9 Ratio Calculator?](#Part 2)
03 [Top 16:9 Resolutions](#Part 3)
04 [How to Calculate 16:9 Aspect Ratios?](#Part 4)
05 [How to Use Aspect Ratio Calculator?](#Part 5)
06 [How to Shift Through Aspect Ratio You Prefer in Filmora?](#Part 6)
## Part 1 **What is aspect ratio?**
Aspect ratio is the proportionality ratio that relates between the width and height of the image. When you set your television screen, you often see something like 16:9 in the aspect ratio. These numbers are not related to the quality of the images whatsoever. They mean that the screen's width will be almost twice as high as its height.
However, most television screens have an aspect ratio that looks like a square. The same does not apply to most cinema screens found in a hall. Thanks to the electricians who made those screens to be rectangular. That makes sure that you don't miss out on any movie clip because of the low aspect ratio.
Initially, the aspect ratio mainly got restricted to Mathematical aspects like geometry. With time, the term got introduced in the films where it was used to relate the width and height of various images on screens, hence the**16\*9 aspect ratio calculator.**
Usually, the aspect ratio refers to the long side concerning the shorter side of the shape. For example, it can be represented by two unknowns, x: y. The values do not mean much because numbers can substitute them.
Perhaps you have encountered these common aspect ratios: IMAX (1.43:1), Academy Film standard (1.43:1), and the famous golden video with an aspect ratio of 1.6180:1.
Having adequate knowledge about aspect ratios is of great importance. You will have to use an aspect ratio calculator when you want to resize your image to fit the specific location without cutting some sections.
## Part 2 **What is the 16:9 aspect ratio calculator?**
The most significant similarity is the aspect ratio of 16:9\. The 16:9 ratio dates back to 2009, when the ratio introduced was declared to be used globally. To prove it, take a minute and check the aspect ratios of your television screen or smartphone. Also, confirm the next time you go to the cinema to watch a movie.
You can take a beautiful photo with a nice image before posting on social media because of the 16:9 aspect ratio. Nowadays, this aspect ratio is a part of most screens and cameras. Even the HD videos always get recorded in the international format ratio.
The**16 \* 9 aspect ratio**calculator will help you operate correctly for high-quality images. It also helps in the conversion of inches to centimeters and vice versa. For a digital device, pixels are the most common units of images.
## Part 3 **Top 16:9 resolutions**
These are the most common resolutions that are available. The units are in pixels, in descending order.
**●** 15360×8640 (16K UHD)
**●** 7680 × 4320 (8K UHD)
**●** 5120 × 2880 (5K)
**●** 3840 × 2160 (4K UHD)
**●** 3200 × 1800 (QHD+)
**●** 2560 × 1440 (QHD)
**●** 1920 × 1080 (Full HD)
**●** 1600 × 900 (HD+)
**●** 1366 × 768 (WXGA)
**●** 1280 × 720 (HD)
**●** 960 × 540 (qHD)
**●** 854 × 480 (FWVGA)
**●** 640 × 360 (nHD)
## Part 4 **How to calculate the 16:9 Aspect ratio?**
First, let's look at the correct pronunciation of the ratio. You can either say it as 16 by 9 or 16 × 9\. It implies 16 units of the longest side for each shortest side. It could also mean 32 by 18 or higher values which can still simplify to 16:9\. We can also represent the ratio differently when simplified. In this case, a decimal point separates the ratios. For example, 16:9 is represented as 1.78:1 after being simplified.
Earlier screens and monitors produced old ratios like the 4:3\. After the recognition of the 16:9 ratios, have made replacements for them. The**16\*9 ratio calculator**is also the most common. Have you heard of 720p HD, 1080p HD, and others? All of them are still under the 16:9 ratios but expressed differently. For example, a screen of 1920 × 1080p. Check it out here: 2920/1080 equals 16:9.
First, here's the formula that we will use in this section.
Width (W) /Height (H) = 1.778
Dividing the width and height gives you 1.778, which is still an aspect ratio of 16:9.
1.778 is a constant in the formula that you can use interchangeably to determine the width or height. Here is a couple of examples to illustrate this.
Example 1:
Ben’s video measures 32 panels wide. Find the number of panels he needs to build a 26:9 display.
W/H = 16/9
32/H = 16/9
H =32 × 9/16
H = 18
Therefore, Ben will need 18 panels to install the display unit.
Example 2
Nancy decides to design an image for a post in the ratio 16:9\. If it has 720 pixels, calculate the width of the image needed.
W/H = 19/6
W/720 = 19/6
W = 730 × 19/6
Nancy will need 1280 pixels for her image.
## Part 5 **How to use an aspect ratio calculator?**
These calculations may be easy when you’re used to them. Not interested in many calculations? Use the online aspect ratio calculator instead. That will make it easier and save on time. You will only need to have the width and height of the image that if needed. The 16 \*9 ratio calculator will give the **remaining distance.**
Using the calculator is the most preferred method because it is very precise. Supposing you don’t have any idea about the width or height of your image, just key in the aspect ratio and wait for an instant answer. The aspect ratio will still give the same answer, but the calculator is convenient.
The better part, this calculator provides calculations for landscape and portrait orientation for images. Follow these steps to use the calculator:
**Step 1:** Go to <https://insaneimpact.com/aspect-ratio-calculator/>
**Step 2:** Enter units of width and height in the respective tabs provided and instantly get your aspect ratio.

## Part 6 **How to shift through aspect ratio you prefer in Filmora?**
As you edit videos, adjust them to ensure they fit in an email as an attachment. That will help you upload them easily after you have used some video editing tools. This article elaborates more by using Wondershare Filmora.
### **Here’s why we recommend [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**
The obvious reason is many features that will help you edit the video like a pro. For instance, you can resize, zoom and highlight the best parts of the video. These are some features of Wondershare Filmora’s video editing capabilities.
**●** Effortlessly resize the sizes of videos and aspect ratios
**●** Cropping the video to highlight an object
**●** Addition of effects and more videos
**●** Uploading edited videos online
**●** Supports diverse operating systems for smartphones and desktops
### **Navigating Through Various Aspect Ratios Using Wondershare Filmora**

#### Wondershare Filmora - Best Video Editor for Mac/Windows
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
5,481,435 people have downloaded it.
Build unique custom animations without breaking a sweat.
Focus on creating epic stories and leave the details to Filmora's auto features.
Start a creative adventure with drag & drop effects and endless possibilities.
Filmora simplifies advanced features to save you time and effort.
Filmora cuts out repetition so you can move on to your next creative breakthrough.
Different social media platforms will only allow users to upload videos of specified sizes. Therefore, it is imperative to know the right size for your videos. Let me take you through ways of changing an aspect ratio for the image to have the required height and width.
**Step 1:** Select your projects' aspect ratio.

Upon opening Wondershare Filmora, a window will pop up on the screen to allow you to select the aspect ratio. There are three options to choose widescreen, standard, and portrait with aspect ratios of 16:9, 4:3, and 1.1, respectively. select the one that you require and click "New Project."
**Step 2:** Set the new aspect ratio for the project

Go to File, choose a new project, and then aspect ratio in the editing panel. Please select the one you wish to use and alter it according to your desired format. For instance, you can select a video of 16:9 and reduce it to 1:1.
**Step 3:** Save the video

Select “**Export**” to export the video and save it in different formats in the Format tab. Do you feel like playing the video on your phone or any other device? Please move to the device tab and ply it on your smartphone or transfer it into a DVD drive format.
Filmora also provides more advanced features for video editing like rotating, cropping, and scaling. You can also match the colors on your videos, include animations, add effects, track the sounds and even record some background sounds for the video to look good. Go ahead and download for a free trial below to start editing your videos!
## Key Takeaways from This Episode
**●** 1 – A detailed overview of the aspect ratio and aspect ratio calculator.
**●** 2 – Understanding how to calculate aspect ratios manually and through an aspect ratio calculator.
**●** 3 – Navigation through different aspect ratios via the wonderful editor, i.e., Wondershare Filmora.
**●** Finally, a**16×9** **aspect ratio calculator**is simple to use, provided you follow the steps given. However, an online calculator will make your videos fit in the equipped area. Use Wondershare Filmora for easy editing and changing of the aspect ratio. It is a pro image and video editor and the easiest to use. Start with its trial version by downloading it for free.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
This article explains major concepts about **16x9 ratio calculator** and applies them even if you are a novice.
Read it to conclude the aspect ratio and the type of editing you need for your videos.
#### In this article
01 [What is Aspect Ratio?](#Part 1)
02 [What's 16:9 Ratio Calculator?](#Part 2)
03 [Top 16:9 Resolutions](#Part 3)
04 [How to Calculate 16:9 Aspect Ratios?](#Part 4)
05 [How to Use Aspect Ratio Calculator?](#Part 5)
06 [How to Shift Through Aspect Ratio You Prefer in Filmora?](#Part 6)
## Part 1 **What is aspect ratio?**
Aspect ratio is the proportionality ratio that relates between the width and height of the image. When you set your television screen, you often see something like 16:9 in the aspect ratio. These numbers are not related to the quality of the images whatsoever. They mean that the screen's width will be almost twice as high as its height.
However, most television screens have an aspect ratio that looks like a square. The same does not apply to most cinema screens found in a hall. Thanks to the electricians who made those screens to be rectangular. That makes sure that you don't miss out on any movie clip because of the low aspect ratio.
Initially, the aspect ratio mainly got restricted to Mathematical aspects like geometry. With time, the term got introduced in the films where it was used to relate the width and height of various images on screens, hence the**16\*9 aspect ratio calculator.**
Usually, the aspect ratio refers to the long side concerning the shorter side of the shape. For example, it can be represented by two unknowns, x: y. The values do not mean much because numbers can substitute them.
Perhaps you have encountered these common aspect ratios: IMAX (1.43:1), Academy Film standard (1.43:1), and the famous golden video with an aspect ratio of 1.6180:1.
Having adequate knowledge about aspect ratios is of great importance. You will have to use an aspect ratio calculator when you want to resize your image to fit the specific location without cutting some sections.
## Part 2 **What is the 16:9 aspect ratio calculator?**
The most significant similarity is the aspect ratio of 16:9\. The 16:9 ratio dates back to 2009, when the ratio introduced was declared to be used globally. To prove it, take a minute and check the aspect ratios of your television screen or smartphone. Also, confirm the next time you go to the cinema to watch a movie.
You can take a beautiful photo with a nice image before posting on social media because of the 16:9 aspect ratio. Nowadays, this aspect ratio is a part of most screens and cameras. Even the HD videos always get recorded in the international format ratio.
The**16 \* 9 aspect ratio**calculator will help you operate correctly for high-quality images. It also helps in the conversion of inches to centimeters and vice versa. For a digital device, pixels are the most common units of images.
## Part 3 **Top 16:9 resolutions**
These are the most common resolutions that are available. The units are in pixels, in descending order.
**●** 15360×8640 (16K UHD)
**●** 7680 × 4320 (8K UHD)
**●** 5120 × 2880 (5K)
**●** 3840 × 2160 (4K UHD)
**●** 3200 × 1800 (QHD+)
**●** 2560 × 1440 (QHD)
**●** 1920 × 1080 (Full HD)
**●** 1600 × 900 (HD+)
**●** 1366 × 768 (WXGA)
**●** 1280 × 720 (HD)
**●** 960 × 540 (qHD)
**●** 854 × 480 (FWVGA)
**●** 640 × 360 (nHD)
## Part 4 **How to calculate the 16:9 Aspect ratio?**
First, let's look at the correct pronunciation of the ratio. You can either say it as 16 by 9 or 16 × 9\. It implies 16 units of the longest side for each shortest side. It could also mean 32 by 18 or higher values which can still simplify to 16:9\. We can also represent the ratio differently when simplified. In this case, a decimal point separates the ratios. For example, 16:9 is represented as 1.78:1 after being simplified.
Earlier screens and monitors produced old ratios like the 4:3\. After the recognition of the 16:9 ratios, have made replacements for them. The**16\*9 ratio calculator**is also the most common. Have you heard of 720p HD, 1080p HD, and others? All of them are still under the 16:9 ratios but expressed differently. For example, a screen of 1920 × 1080p. Check it out here: 2920/1080 equals 16:9.
First, here's the formula that we will use in this section.
Width (W) /Height (H) = 1.778
Dividing the width and height gives you 1.778, which is still an aspect ratio of 16:9.
1.778 is a constant in the formula that you can use interchangeably to determine the width or height. Here is a couple of examples to illustrate this.
Example 1:
Ben’s video measures 32 panels wide. Find the number of panels he needs to build a 26:9 display.
W/H = 16/9
32/H = 16/9
H =32 × 9/16
H = 18
Therefore, Ben will need 18 panels to install the display unit.
Example 2
Nancy decides to design an image for a post in the ratio 16:9\. If it has 720 pixels, calculate the width of the image needed.
W/H = 19/6
W/720 = 19/6
W = 730 × 19/6
Nancy will need 1280 pixels for her image.
## Part 5 **How to use an aspect ratio calculator?**
These calculations may be easy when you’re used to them. Not interested in many calculations? Use the online aspect ratio calculator instead. That will make it easier and save on time. You will only need to have the width and height of the image that if needed. The 16 \*9 ratio calculator will give the **remaining distance.**
Using the calculator is the most preferred method because it is very precise. Supposing you don’t have any idea about the width or height of your image, just key in the aspect ratio and wait for an instant answer. The aspect ratio will still give the same answer, but the calculator is convenient.
The better part, this calculator provides calculations for landscape and portrait orientation for images. Follow these steps to use the calculator:
**Step 1:** Go to <https://insaneimpact.com/aspect-ratio-calculator/>
**Step 2:** Enter units of width and height in the respective tabs provided and instantly get your aspect ratio.

## Part 6 **How to shift through aspect ratio you prefer in Filmora?**
As you edit videos, adjust them to ensure they fit in an email as an attachment. That will help you upload them easily after you have used some video editing tools. This article elaborates more by using Wondershare Filmora.
### **Here’s why we recommend [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**
The obvious reason is many features that will help you edit the video like a pro. For instance, you can resize, zoom and highlight the best parts of the video. These are some features of Wondershare Filmora’s video editing capabilities.
**●** Effortlessly resize the sizes of videos and aspect ratios
**●** Cropping the video to highlight an object
**●** Addition of effects and more videos
**●** Uploading edited videos online
**●** Supports diverse operating systems for smartphones and desktops
### **Navigating Through Various Aspect Ratios Using Wondershare Filmora**

#### Wondershare Filmora - Best Video Editor for Mac/Windows
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
5,481,435 people have downloaded it.
Build unique custom animations without breaking a sweat.
Focus on creating epic stories and leave the details to Filmora's auto features.
Start a creative adventure with drag & drop effects and endless possibilities.
Filmora simplifies advanced features to save you time and effort.
Filmora cuts out repetition so you can move on to your next creative breakthrough.
Different social media platforms will only allow users to upload videos of specified sizes. Therefore, it is imperative to know the right size for your videos. Let me take you through ways of changing an aspect ratio for the image to have the required height and width.
**Step 1:** Select your projects' aspect ratio.

Upon opening Wondershare Filmora, a window will pop up on the screen to allow you to select the aspect ratio. There are three options to choose widescreen, standard, and portrait with aspect ratios of 16:9, 4:3, and 1.1, respectively. select the one that you require and click "New Project."
**Step 2:** Set the new aspect ratio for the project

Go to File, choose a new project, and then aspect ratio in the editing panel. Please select the one you wish to use and alter it according to your desired format. For instance, you can select a video of 16:9 and reduce it to 1:1.
**Step 3:** Save the video

Select “**Export**” to export the video and save it in different formats in the Format tab. Do you feel like playing the video on your phone or any other device? Please move to the device tab and ply it on your smartphone or transfer it into a DVD drive format.
Filmora also provides more advanced features for video editing like rotating, cropping, and scaling. You can also match the colors on your videos, include animations, add effects, track the sounds and even record some background sounds for the video to look good. Go ahead and download for a free trial below to start editing your videos!
## Key Takeaways from This Episode
**●** 1 – A detailed overview of the aspect ratio and aspect ratio calculator.
**●** 2 – Understanding how to calculate aspect ratios manually and through an aspect ratio calculator.
**●** 3 – Navigation through different aspect ratios via the wonderful editor, i.e., Wondershare Filmora.
**●** Finally, a**16×9** **aspect ratio calculator**is simple to use, provided you follow the steps given. However, an online calculator will make your videos fit in the equipped area. Use Wondershare Filmora for easy editing and changing of the aspect ratio. It is a pro image and video editor and the easiest to use. Start with its trial version by downloading it for free.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
This article explains major concepts about **16x9 ratio calculator** and applies them even if you are a novice.
Read it to conclude the aspect ratio and the type of editing you need for your videos.
#### In this article
01 [What is Aspect Ratio?](#Part 1)
02 [What's 16:9 Ratio Calculator?](#Part 2)
03 [Top 16:9 Resolutions](#Part 3)
04 [How to Calculate 16:9 Aspect Ratios?](#Part 4)
05 [How to Use Aspect Ratio Calculator?](#Part 5)
06 [How to Shift Through Aspect Ratio You Prefer in Filmora?](#Part 6)
## Part 1 **What is aspect ratio?**
Aspect ratio is the proportionality ratio that relates between the width and height of the image. When you set your television screen, you often see something like 16:9 in the aspect ratio. These numbers are not related to the quality of the images whatsoever. They mean that the screen's width will be almost twice as high as its height.
However, most television screens have an aspect ratio that looks like a square. The same does not apply to most cinema screens found in a hall. Thanks to the electricians who made those screens to be rectangular. That makes sure that you don't miss out on any movie clip because of the low aspect ratio.
Initially, the aspect ratio mainly got restricted to Mathematical aspects like geometry. With time, the term got introduced in the films where it was used to relate the width and height of various images on screens, hence the**16\*9 aspect ratio calculator.**
Usually, the aspect ratio refers to the long side concerning the shorter side of the shape. For example, it can be represented by two unknowns, x: y. The values do not mean much because numbers can substitute them.
Perhaps you have encountered these common aspect ratios: IMAX (1.43:1), Academy Film standard (1.43:1), and the famous golden video with an aspect ratio of 1.6180:1.
Having adequate knowledge about aspect ratios is of great importance. You will have to use an aspect ratio calculator when you want to resize your image to fit the specific location without cutting some sections.
## Part 2 **What is the 16:9 aspect ratio calculator?**
The most significant similarity is the aspect ratio of 16:9\. The 16:9 ratio dates back to 2009, when the ratio introduced was declared to be used globally. To prove it, take a minute and check the aspect ratios of your television screen or smartphone. Also, confirm the next time you go to the cinema to watch a movie.
You can take a beautiful photo with a nice image before posting on social media because of the 16:9 aspect ratio. Nowadays, this aspect ratio is a part of most screens and cameras. Even the HD videos always get recorded in the international format ratio.
The**16 \* 9 aspect ratio**calculator will help you operate correctly for high-quality images. It also helps in the conversion of inches to centimeters and vice versa. For a digital device, pixels are the most common units of images.
## Part 3 **Top 16:9 resolutions**
These are the most common resolutions that are available. The units are in pixels, in descending order.
**●** 15360×8640 (16K UHD)
**●** 7680 × 4320 (8K UHD)
**●** 5120 × 2880 (5K)
**●** 3840 × 2160 (4K UHD)
**●** 3200 × 1800 (QHD+)
**●** 2560 × 1440 (QHD)
**●** 1920 × 1080 (Full HD)
**●** 1600 × 900 (HD+)
**●** 1366 × 768 (WXGA)
**●** 1280 × 720 (HD)
**●** 960 × 540 (qHD)
**●** 854 × 480 (FWVGA)
**●** 640 × 360 (nHD)
## Part 4 **How to calculate the 16:9 Aspect ratio?**
First, let's look at the correct pronunciation of the ratio. You can either say it as 16 by 9 or 16 × 9\. It implies 16 units of the longest side for each shortest side. It could also mean 32 by 18 or higher values which can still simplify to 16:9\. We can also represent the ratio differently when simplified. In this case, a decimal point separates the ratios. For example, 16:9 is represented as 1.78:1 after being simplified.
Earlier screens and monitors produced old ratios like the 4:3\. After the recognition of the 16:9 ratios, have made replacements for them. The**16\*9 ratio calculator**is also the most common. Have you heard of 720p HD, 1080p HD, and others? All of them are still under the 16:9 ratios but expressed differently. For example, a screen of 1920 × 1080p. Check it out here: 2920/1080 equals 16:9.
First, here's the formula that we will use in this section.
Width (W) /Height (H) = 1.778
Dividing the width and height gives you 1.778, which is still an aspect ratio of 16:9.
1.778 is a constant in the formula that you can use interchangeably to determine the width or height. Here is a couple of examples to illustrate this.
Example 1:
Ben’s video measures 32 panels wide. Find the number of panels he needs to build a 26:9 display.
W/H = 16/9
32/H = 16/9
H =32 × 9/16
H = 18
Therefore, Ben will need 18 panels to install the display unit.
Example 2
Nancy decides to design an image for a post in the ratio 16:9\. If it has 720 pixels, calculate the width of the image needed.
W/H = 19/6
W/720 = 19/6
W = 730 × 19/6
Nancy will need 1280 pixels for her image.
## Part 5 **How to use an aspect ratio calculator?**
These calculations may be easy when you’re used to them. Not interested in many calculations? Use the online aspect ratio calculator instead. That will make it easier and save on time. You will only need to have the width and height of the image that if needed. The 16 \*9 ratio calculator will give the **remaining distance.**
Using the calculator is the most preferred method because it is very precise. Supposing you don’t have any idea about the width or height of your image, just key in the aspect ratio and wait for an instant answer. The aspect ratio will still give the same answer, but the calculator is convenient.
The better part, this calculator provides calculations for landscape and portrait orientation for images. Follow these steps to use the calculator:
**Step 1:** Go to <https://insaneimpact.com/aspect-ratio-calculator/>
**Step 2:** Enter units of width and height in the respective tabs provided and instantly get your aspect ratio.

## Part 6 **How to shift through aspect ratio you prefer in Filmora?**
As you edit videos, adjust them to ensure they fit in an email as an attachment. That will help you upload them easily after you have used some video editing tools. This article elaborates more by using Wondershare Filmora.
### **Here’s why we recommend [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**
The obvious reason is many features that will help you edit the video like a pro. For instance, you can resize, zoom and highlight the best parts of the video. These are some features of Wondershare Filmora’s video editing capabilities.
**●** Effortlessly resize the sizes of videos and aspect ratios
**●** Cropping the video to highlight an object
**●** Addition of effects and more videos
**●** Uploading edited videos online
**●** Supports diverse operating systems for smartphones and desktops
### **Navigating Through Various Aspect Ratios Using Wondershare Filmora**

#### Wondershare Filmora - Best Video Editor for Mac/Windows
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
5,481,435 people have downloaded it.
Build unique custom animations without breaking a sweat.
Focus on creating epic stories and leave the details to Filmora's auto features.
Start a creative adventure with drag & drop effects and endless possibilities.
Filmora simplifies advanced features to save you time and effort.
Filmora cuts out repetition so you can move on to your next creative breakthrough.
Different social media platforms will only allow users to upload videos of specified sizes. Therefore, it is imperative to know the right size for your videos. Let me take you through ways of changing an aspect ratio for the image to have the required height and width.
**Step 1:** Select your projects' aspect ratio.

Upon opening Wondershare Filmora, a window will pop up on the screen to allow you to select the aspect ratio. There are three options to choose widescreen, standard, and portrait with aspect ratios of 16:9, 4:3, and 1.1, respectively. select the one that you require and click "New Project."
**Step 2:** Set the new aspect ratio for the project

Go to File, choose a new project, and then aspect ratio in the editing panel. Please select the one you wish to use and alter it according to your desired format. For instance, you can select a video of 16:9 and reduce it to 1:1.
**Step 3:** Save the video

Select “**Export**” to export the video and save it in different formats in the Format tab. Do you feel like playing the video on your phone or any other device? Please move to the device tab and ply it on your smartphone or transfer it into a DVD drive format.
Filmora also provides more advanced features for video editing like rotating, cropping, and scaling. You can also match the colors on your videos, include animations, add effects, track the sounds and even record some background sounds for the video to look good. Go ahead and download for a free trial below to start editing your videos!
## Key Takeaways from This Episode
**●** 1 – A detailed overview of the aspect ratio and aspect ratio calculator.
**●** 2 – Understanding how to calculate aspect ratios manually and through an aspect ratio calculator.
**●** 3 – Navigation through different aspect ratios via the wonderful editor, i.e., Wondershare Filmora.
**●** Finally, a**16×9** **aspect ratio calculator**is simple to use, provided you follow the steps given. However, an online calculator will make your videos fit in the equipped area. Use Wondershare Filmora for easy editing and changing of the aspect ratio. It is a pro image and video editor and the easiest to use. Start with its trial version by downloading it for free.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
This article explains major concepts about **16x9 ratio calculator** and applies them even if you are a novice.
Read it to conclude the aspect ratio and the type of editing you need for your videos.
#### In this article
01 [What is Aspect Ratio?](#Part 1)
02 [What's 16:9 Ratio Calculator?](#Part 2)
03 [Top 16:9 Resolutions](#Part 3)
04 [How to Calculate 16:9 Aspect Ratios?](#Part 4)
05 [How to Use Aspect Ratio Calculator?](#Part 5)
06 [How to Shift Through Aspect Ratio You Prefer in Filmora?](#Part 6)
## Part 1 **What is aspect ratio?**
Aspect ratio is the proportionality ratio that relates between the width and height of the image. When you set your television screen, you often see something like 16:9 in the aspect ratio. These numbers are not related to the quality of the images whatsoever. They mean that the screen's width will be almost twice as high as its height.
However, most television screens have an aspect ratio that looks like a square. The same does not apply to most cinema screens found in a hall. Thanks to the electricians who made those screens to be rectangular. That makes sure that you don't miss out on any movie clip because of the low aspect ratio.
Initially, the aspect ratio mainly got restricted to Mathematical aspects like geometry. With time, the term got introduced in the films where it was used to relate the width and height of various images on screens, hence the**16\*9 aspect ratio calculator.**
Usually, the aspect ratio refers to the long side concerning the shorter side of the shape. For example, it can be represented by two unknowns, x: y. The values do not mean much because numbers can substitute them.
Perhaps you have encountered these common aspect ratios: IMAX (1.43:1), Academy Film standard (1.43:1), and the famous golden video with an aspect ratio of 1.6180:1.
Having adequate knowledge about aspect ratios is of great importance. You will have to use an aspect ratio calculator when you want to resize your image to fit the specific location without cutting some sections.
## Part 2 **What is the 16:9 aspect ratio calculator?**
The most significant similarity is the aspect ratio of 16:9\. The 16:9 ratio dates back to 2009, when the ratio introduced was declared to be used globally. To prove it, take a minute and check the aspect ratios of your television screen or smartphone. Also, confirm the next time you go to the cinema to watch a movie.
You can take a beautiful photo with a nice image before posting on social media because of the 16:9 aspect ratio. Nowadays, this aspect ratio is a part of most screens and cameras. Even the HD videos always get recorded in the international format ratio.
The**16 \* 9 aspect ratio**calculator will help you operate correctly for high-quality images. It also helps in the conversion of inches to centimeters and vice versa. For a digital device, pixels are the most common units of images.
## Part 3 **Top 16:9 resolutions**
These are the most common resolutions that are available. The units are in pixels, in descending order.
**●** 15360×8640 (16K UHD)
**●** 7680 × 4320 (8K UHD)
**●** 5120 × 2880 (5K)
**●** 3840 × 2160 (4K UHD)
**●** 3200 × 1800 (QHD+)
**●** 2560 × 1440 (QHD)
**●** 1920 × 1080 (Full HD)
**●** 1600 × 900 (HD+)
**●** 1366 × 768 (WXGA)
**●** 1280 × 720 (HD)
**●** 960 × 540 (qHD)
**●** 854 × 480 (FWVGA)
**●** 640 × 360 (nHD)
## Part 4 **How to calculate the 16:9 Aspect ratio?**
First, let's look at the correct pronunciation of the ratio. You can either say it as 16 by 9 or 16 × 9\. It implies 16 units of the longest side for each shortest side. It could also mean 32 by 18 or higher values which can still simplify to 16:9\. We can also represent the ratio differently when simplified. In this case, a decimal point separates the ratios. For example, 16:9 is represented as 1.78:1 after being simplified.
Earlier screens and monitors produced old ratios like the 4:3\. After the recognition of the 16:9 ratios, have made replacements for them. The**16\*9 ratio calculator**is also the most common. Have you heard of 720p HD, 1080p HD, and others? All of them are still under the 16:9 ratios but expressed differently. For example, a screen of 1920 × 1080p. Check it out here: 2920/1080 equals 16:9.
First, here's the formula that we will use in this section.
Width (W) /Height (H) = 1.778
Dividing the width and height gives you 1.778, which is still an aspect ratio of 16:9.
1.778 is a constant in the formula that you can use interchangeably to determine the width or height. Here is a couple of examples to illustrate this.
Example 1:
Ben’s video measures 32 panels wide. Find the number of panels he needs to build a 26:9 display.
W/H = 16/9
32/H = 16/9
H =32 × 9/16
H = 18
Therefore, Ben will need 18 panels to install the display unit.
Example 2
Nancy decides to design an image for a post in the ratio 16:9\. If it has 720 pixels, calculate the width of the image needed.
W/H = 19/6
W/720 = 19/6
W = 730 × 19/6
Nancy will need 1280 pixels for her image.
## Part 5 **How to use an aspect ratio calculator?**
These calculations may be easy when you’re used to them. Not interested in many calculations? Use the online aspect ratio calculator instead. That will make it easier and save on time. You will only need to have the width and height of the image that if needed. The 16 \*9 ratio calculator will give the **remaining distance.**
Using the calculator is the most preferred method because it is very precise. Supposing you don’t have any idea about the width or height of your image, just key in the aspect ratio and wait for an instant answer. The aspect ratio will still give the same answer, but the calculator is convenient.
The better part, this calculator provides calculations for landscape and portrait orientation for images. Follow these steps to use the calculator:
**Step 1:** Go to <https://insaneimpact.com/aspect-ratio-calculator/>
**Step 2:** Enter units of width and height in the respective tabs provided and instantly get your aspect ratio.

## Part 6 **How to shift through aspect ratio you prefer in Filmora?**
As you edit videos, adjust them to ensure they fit in an email as an attachment. That will help you upload them easily after you have used some video editing tools. This article elaborates more by using Wondershare Filmora.
### **Here’s why we recommend [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/)**
The obvious reason is many features that will help you edit the video like a pro. For instance, you can resize, zoom and highlight the best parts of the video. These are some features of Wondershare Filmora’s video editing capabilities.
**●** Effortlessly resize the sizes of videos and aspect ratios
**●** Cropping the video to highlight an object
**●** Addition of effects and more videos
**●** Uploading edited videos online
**●** Supports diverse operating systems for smartphones and desktops
### **Navigating Through Various Aspect Ratios Using Wondershare Filmora**

#### Wondershare Filmora - Best Video Editor for Mac/Windows
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
5,481,435 people have downloaded it.
Build unique custom animations without breaking a sweat.
Focus on creating epic stories and leave the details to Filmora's auto features.
Start a creative adventure with drag & drop effects and endless possibilities.
Filmora simplifies advanced features to save you time and effort.
Filmora cuts out repetition so you can move on to your next creative breakthrough.
Different social media platforms will only allow users to upload videos of specified sizes. Therefore, it is imperative to know the right size for your videos. Let me take you through ways of changing an aspect ratio for the image to have the required height and width.
**Step 1:** Select your projects' aspect ratio.

Upon opening Wondershare Filmora, a window will pop up on the screen to allow you to select the aspect ratio. There are three options to choose widescreen, standard, and portrait with aspect ratios of 16:9, 4:3, and 1.1, respectively. select the one that you require and click "New Project."
**Step 2:** Set the new aspect ratio for the project

Go to File, choose a new project, and then aspect ratio in the editing panel. Please select the one you wish to use and alter it according to your desired format. For instance, you can select a video of 16:9 and reduce it to 1:1.
**Step 3:** Save the video

Select “**Export**” to export the video and save it in different formats in the Format tab. Do you feel like playing the video on your phone or any other device? Please move to the device tab and ply it on your smartphone or transfer it into a DVD drive format.
Filmora also provides more advanced features for video editing like rotating, cropping, and scaling. You can also match the colors on your videos, include animations, add effects, track the sounds and even record some background sounds for the video to look good. Go ahead and download for a free trial below to start editing your videos!
## Key Takeaways from This Episode
**●** 1 – A detailed overview of the aspect ratio and aspect ratio calculator.
**●** 2 – Understanding how to calculate aspect ratios manually and through an aspect ratio calculator.
**●** 3 – Navigation through different aspect ratios via the wonderful editor, i.e., Wondershare Filmora.
**●** Finally, a**16×9** **aspect ratio calculator**is simple to use, provided you follow the steps given. However, an online calculator will make your videos fit in the equipped area. Use Wondershare Filmora for easy editing and changing of the aspect ratio. It is a pro image and video editor and the easiest to use. Start with its trial version by downloading it for free.
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## FCPX Optimization: Tips and Tricks to Reclaim Disk Space
# How to Free Up Disk Space for Final Cut Pro X?

##### Benjamin Arango
Mar 27, 2024• Proven solutions
Whenever you are working on a Mac ensure that 10% of your storage is ideal and free. Without free space, your work is going to get slow. Sometimes you have to erase a portion of things occupying extra storage to work smoothly.
Never ignore and disregard the errors and alerts of the space disk being full. This article is all about how to fix the disk space in the **final cut Pro X.** Moreover, this article will cover the different ways via which you can check mac storage space, and how to free up space in FCPX and Mac.
Quick Guide:
> * [Part 1: How to free up space from Final Cut Pro Library?](#part1)
> * [Part 2: What to do with the “not enough disk space” error](#part2)
> * [Part 3: How much space can FCPX take in Mac?](#part3)
> * [Part 4: How to free up space in Mac?](#part4)
## **Part 1: How to free up space from Final Cut Pro Library?**
It takes three steps, and here are these steps.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
**Step1: Remember to delete unused clips and original medias**
To make room in your final cut pro, delete all the unused clips and original media. Delete the generated library files and delete the render files. Before deleting make sure to check whether to delete unused or used render files.

**Step 2: How to save space with files and transcoding options?**
It happens in final cut pro, that while working, it creates records, proxy files, and rendered files. To save space, you have to delete these files. It is advised to delete the generated rendered files before moving the library to mac Final Cut pro. Moreover, Mac recovers all the files the following time you open the project
**Step 3: How to stop background rendering and how to delete render files in Fcpx?**
Sometimes temporary videos and audios are created in Final cut pro X . Background rendering starts just after 5 seconds you quit working in mac. You can physically control the background rendering in Final cut pro. When you want to have more control, disable rendering in FCP and choose which clip you would like to render. You can change the preferences to disable or enable through the FCPx settings. Once you disable the rendering, it is your choice to select the specific clips to render.
Open the preferences menu in your mac and render the highlighted clips in your Fcpx timeline. Use the control+R shortcut to render the files.
To delete the render files in Fcpx, Delete the generated files. Files> generated files. A window will appear, Click ok on delete render files.
****
## **Part2: What to do with the “not enough disk space” error even with enough space in Mac?**
Sometimes still having a lot of space, Your final cut pro X shows not enough disk space error in FCP X. Help!
Have you ever got the error of not having enough space at available destinations whenever you import anything to FCP X.?
Quick GuideFollow the below steps to solve this problem
1. Click and select the library in FCPX
2. Then go to the File menu and select “Delete generated library file”
3. Next, Select all the render and proxy files
4. You might not be using optimized files, In that case, select optimized files
5. Exit FCPX.
6. To reboot, hold down both option and command keys
7. Delete the preference files
8. If the error persists, run the utility folder that is inside the Application folder.
9. Execute First aid in all the units.
10. If the error persists, obtain a copy of the disk, and repair the directories on all the drives.
## **Part 3: How much space can FCPX take in Mac?**
Today, when we have hard drives and multi-terabytes, many of us have stopped looking at the disk space. Many of you usually don't bother until you get an alert that the disk is full.
Sometimes the largest drives get filled eventually. If you haven't checked your disk space yet, use your Mac and follow the instructions given below. You may be surprised about how much space can FCPX take.
Here is how you will do it:
**Option 1: Checking the mac storage through "About this Mac"**
Now it is a bit easy to check the storage from about the section. You will find this in most of the recent MAC versions.
Click on the mac logo and then click on “About this mac”.
Click on “storage” and you will see a reference chart stacked portraying the capacity of the disk and the absolute amount of storage taken by different categories of information. Moreover, you will find out the space that is yet accessible to you.
**Option 2: Checking the mac storage through “Disk utility”**
If you're a Mac user, you might know that there is a disk utility app. You can easily get a readout of the available space from there.
Open your Finder and click "Applications" on the left side.
Or click the magnifying glass in the upper right to find disk utility.
You will find utilities in Applications. **Applications> utilities**.
After the disk utility opens, you can see the available used spaces. Remember to put your hard drive’s name from the list. The popup window that opens up will also tell you the free space of any device connected to your Mac.

**Option3: Checking the storage from the Finder**
You can get a preview of your storage device by clicking an item in the Finder and pressing the spacebar on your keyboard. Let's suppose you need to check a particular document without opening it.
Select that document and press the spacebar. You will know what's inside without even opening it.
**Quick Guide Here is how you can do it**
1. Go to Finder and select Finder>Preferences, next Click General, modify the settings and you will see the storage device on the desktop.
2. To check the available or remaining space, click the spacebar. As you click it a window popup will show you the remaining space.
3. Press the spacebar again to close the window or you can do it via command. Press Command-W.
4. Turn on the finder status bar on your window. In case you want to check the disk space frequently.
5. Open a Finder window and next open the view menu. As you select the show status bar option, you will see the number of items in the folders. In the other case, if you are viewing the folder you'll get the idea of remaining or free space
If you're looking for a lighter alternative to Final Cut Pro, try Filmora to save more space!
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**So, is your FCPX good to go? Get your [tutorials for FCPX](https://tools.techidaily.com/wondershare/filmora/download/) here!**
## **Part 4: How to free up space in Mac?**
Find out what’s occupying the room in your Mac to save room for final cut pro. Get familiar with how to deal with your Mac’s capacity. Acquaint yourself with the ideal approaches to free up space in Mac.
Nowadays, Macs have limited and restricted capacity due to the SSDs present in them. When there were hard drives in Mac, we had a huge room on them. In recent memory, high-resolution videos, music, and other functional records take up more capacity. When you run out of space, it hampers your work and processing.
**_Quickly clear your mac space._**
If you are in a hurry, you can do the below things to quickly clear up the space in your mac.
1. Select the download folder and open it in the Finder. Now select the folder whose content you don't need and trash it.
2. Move to the home folder and open a new Find window. Press command-F.
3. Click the drop-down menu to choose "other."Look to the box next to "Document size". Press ok. Choose" greater than" in the next dropdown menu. With this choose the unwanted file or the one that is no longer useful to throw in the trash.
4. Another thing that you can do is, move those files in the trash that you haven’t opened in the last year.
5. If your desktop has a lot of unused stuff and is taking space, then delete the folders on the desktop.
**Ways to clean junk on your Mac**
There are many ways to clean garbage records on Mac. You may have different types of garbage in your Mac. Here is a simple solution for the elimination of junk from your Mac. Along with occupying the space, junk slows down your Pc, phone, and Mac.
**Cleaning cache files:** Every Mac has some files stored which are known as cache files. Some temporary files are kept in Mac to speed up the Apple software. It better to clean the files before it gets accumulated and hampers the performance.
* Press command +shift+G after opening the Finder.
* Enter this command in the field box\~/Library/Caches.
* See all the visible files on the appearing window
* Select all files to delete, and you can delete one by one
* Enter the username and password in the popup window
Similarly, you can clean the system log files too from your mac by below steps:
1. Go to the folder. Before selecting Go, enter the /var/log/.
2. All the system files are visible to you. Now, you can easily delete unwanted files.
**Clean with Clean MyMacX**
You can now clean your mac with this application. Download this application for free. After launching it, see the features on left and click on the system junk. Do scanning and check the opposite side of user cache files and delete the items, you want to delete. Lastly, press clean to clean it. Your Mac is now as new as before. Clean MyMacX cleans all the junk and makes your mac clutter-free.
**Conclusion**
Move the unwanted and unused clips from your Mac final cut pro X. Even you can free up the storage by deleting the whole event. A few media files stay in the library as many projects use the same media.

Benjamin Arango
Benjamin Arango is a writer and a lover of all things video.
Follow @Benjamin Arango
##### Benjamin Arango
Mar 27, 2024• Proven solutions
Whenever you are working on a Mac ensure that 10% of your storage is ideal and free. Without free space, your work is going to get slow. Sometimes you have to erase a portion of things occupying extra storage to work smoothly.
Never ignore and disregard the errors and alerts of the space disk being full. This article is all about how to fix the disk space in the **final cut Pro X.** Moreover, this article will cover the different ways via which you can check mac storage space, and how to free up space in FCPX and Mac.
Quick Guide:
> * [Part 1: How to free up space from Final Cut Pro Library?](#part1)
> * [Part 2: What to do with the “not enough disk space” error](#part2)
> * [Part 3: How much space can FCPX take in Mac?](#part3)
> * [Part 4: How to free up space in Mac?](#part4)
## **Part 1: How to free up space from Final Cut Pro Library?**
It takes three steps, and here are these steps.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
**Step1: Remember to delete unused clips and original medias**
To make room in your final cut pro, delete all the unused clips and original media. Delete the generated library files and delete the render files. Before deleting make sure to check whether to delete unused or used render files.

**Step 2: How to save space with files and transcoding options?**
It happens in final cut pro, that while working, it creates records, proxy files, and rendered files. To save space, you have to delete these files. It is advised to delete the generated rendered files before moving the library to mac Final Cut pro. Moreover, Mac recovers all the files the following time you open the project
**Step 3: How to stop background rendering and how to delete render files in Fcpx?**
Sometimes temporary videos and audios are created in Final cut pro X . Background rendering starts just after 5 seconds you quit working in mac. You can physically control the background rendering in Final cut pro. When you want to have more control, disable rendering in FCP and choose which clip you would like to render. You can change the preferences to disable or enable through the FCPx settings. Once you disable the rendering, it is your choice to select the specific clips to render.
Open the preferences menu in your mac and render the highlighted clips in your Fcpx timeline. Use the control+R shortcut to render the files.
To delete the render files in Fcpx, Delete the generated files. Files> generated files. A window will appear, Click ok on delete render files.
****
## **Part2: What to do with the “not enough disk space” error even with enough space in Mac?**
Sometimes still having a lot of space, Your final cut pro X shows not enough disk space error in FCP X. Help!
Have you ever got the error of not having enough space at available destinations whenever you import anything to FCP X.?
Quick GuideFollow the below steps to solve this problem
1. Click and select the library in FCPX
2. Then go to the File menu and select “Delete generated library file”
3. Next, Select all the render and proxy files
4. You might not be using optimized files, In that case, select optimized files
5. Exit FCPX.
6. To reboot, hold down both option and command keys
7. Delete the preference files
8. If the error persists, run the utility folder that is inside the Application folder.
9. Execute First aid in all the units.
10. If the error persists, obtain a copy of the disk, and repair the directories on all the drives.
## **Part 3: How much space can FCPX take in Mac?**
Today, when we have hard drives and multi-terabytes, many of us have stopped looking at the disk space. Many of you usually don't bother until you get an alert that the disk is full.
Sometimes the largest drives get filled eventually. If you haven't checked your disk space yet, use your Mac and follow the instructions given below. You may be surprised about how much space can FCPX take.
Here is how you will do it:
**Option 1: Checking the mac storage through "About this Mac"**
Now it is a bit easy to check the storage from about the section. You will find this in most of the recent MAC versions.
Click on the mac logo and then click on “About this mac”.
Click on “storage” and you will see a reference chart stacked portraying the capacity of the disk and the absolute amount of storage taken by different categories of information. Moreover, you will find out the space that is yet accessible to you.
**Option 2: Checking the mac storage through “Disk utility”**
If you're a Mac user, you might know that there is a disk utility app. You can easily get a readout of the available space from there.
Open your Finder and click "Applications" on the left side.
Or click the magnifying glass in the upper right to find disk utility.
You will find utilities in Applications. **Applications> utilities**.
After the disk utility opens, you can see the available used spaces. Remember to put your hard drive’s name from the list. The popup window that opens up will also tell you the free space of any device connected to your Mac.

**Option3: Checking the storage from the Finder**
You can get a preview of your storage device by clicking an item in the Finder and pressing the spacebar on your keyboard. Let's suppose you need to check a particular document without opening it.
Select that document and press the spacebar. You will know what's inside without even opening it.
**Quick Guide Here is how you can do it**
1. Go to Finder and select Finder>Preferences, next Click General, modify the settings and you will see the storage device on the desktop.
2. To check the available or remaining space, click the spacebar. As you click it a window popup will show you the remaining space.
3. Press the spacebar again to close the window or you can do it via command. Press Command-W.
4. Turn on the finder status bar on your window. In case you want to check the disk space frequently.
5. Open a Finder window and next open the view menu. As you select the show status bar option, you will see the number of items in the folders. In the other case, if you are viewing the folder you'll get the idea of remaining or free space
If you're looking for a lighter alternative to Final Cut Pro, try Filmora to save more space!
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**So, is your FCPX good to go? Get your [tutorials for FCPX](https://tools.techidaily.com/wondershare/filmora/download/) here!**
## **Part 4: How to free up space in Mac?**
Find out what’s occupying the room in your Mac to save room for final cut pro. Get familiar with how to deal with your Mac’s capacity. Acquaint yourself with the ideal approaches to free up space in Mac.
Nowadays, Macs have limited and restricted capacity due to the SSDs present in them. When there were hard drives in Mac, we had a huge room on them. In recent memory, high-resolution videos, music, and other functional records take up more capacity. When you run out of space, it hampers your work and processing.
**_Quickly clear your mac space._**
If you are in a hurry, you can do the below things to quickly clear up the space in your mac.
1. Select the download folder and open it in the Finder. Now select the folder whose content you don't need and trash it.
2. Move to the home folder and open a new Find window. Press command-F.
3. Click the drop-down menu to choose "other."Look to the box next to "Document size". Press ok. Choose" greater than" in the next dropdown menu. With this choose the unwanted file or the one that is no longer useful to throw in the trash.
4. Another thing that you can do is, move those files in the trash that you haven’t opened in the last year.
5. If your desktop has a lot of unused stuff and is taking space, then delete the folders on the desktop.
**Ways to clean junk on your Mac**
There are many ways to clean garbage records on Mac. You may have different types of garbage in your Mac. Here is a simple solution for the elimination of junk from your Mac. Along with occupying the space, junk slows down your Pc, phone, and Mac.
**Cleaning cache files:** Every Mac has some files stored which are known as cache files. Some temporary files are kept in Mac to speed up the Apple software. It better to clean the files before it gets accumulated and hampers the performance.
* Press command +shift+G after opening the Finder.
* Enter this command in the field box\~/Library/Caches.
* See all the visible files on the appearing window
* Select all files to delete, and you can delete one by one
* Enter the username and password in the popup window
Similarly, you can clean the system log files too from your mac by below steps:
1. Go to the folder. Before selecting Go, enter the /var/log/.
2. All the system files are visible to you. Now, you can easily delete unwanted files.
**Clean with Clean MyMacX**
You can now clean your mac with this application. Download this application for free. After launching it, see the features on left and click on the system junk. Do scanning and check the opposite side of user cache files and delete the items, you want to delete. Lastly, press clean to clean it. Your Mac is now as new as before. Clean MyMacX cleans all the junk and makes your mac clutter-free.
**Conclusion**
Move the unwanted and unused clips from your Mac final cut pro X. Even you can free up the storage by deleting the whole event. A few media files stay in the library as many projects use the same media.

Benjamin Arango
Benjamin Arango is a writer and a lover of all things video.
Follow @Benjamin Arango
##### Benjamin Arango
Mar 27, 2024• Proven solutions
Whenever you are working on a Mac ensure that 10% of your storage is ideal and free. Without free space, your work is going to get slow. Sometimes you have to erase a portion of things occupying extra storage to work smoothly.
Never ignore and disregard the errors and alerts of the space disk being full. This article is all about how to fix the disk space in the **final cut Pro X.** Moreover, this article will cover the different ways via which you can check mac storage space, and how to free up space in FCPX and Mac.
Quick Guide:
> * [Part 1: How to free up space from Final Cut Pro Library?](#part1)
> * [Part 2: What to do with the “not enough disk space” error](#part2)
> * [Part 3: How much space can FCPX take in Mac?](#part3)
> * [Part 4: How to free up space in Mac?](#part4)
## **Part 1: How to free up space from Final Cut Pro Library?**
It takes three steps, and here are these steps.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
**Step1: Remember to delete unused clips and original medias**
To make room in your final cut pro, delete all the unused clips and original media. Delete the generated library files and delete the render files. Before deleting make sure to check whether to delete unused or used render files.

**Step 2: How to save space with files and transcoding options?**
It happens in final cut pro, that while working, it creates records, proxy files, and rendered files. To save space, you have to delete these files. It is advised to delete the generated rendered files before moving the library to mac Final Cut pro. Moreover, Mac recovers all the files the following time you open the project
**Step 3: How to stop background rendering and how to delete render files in Fcpx?**
Sometimes temporary videos and audios are created in Final cut pro X . Background rendering starts just after 5 seconds you quit working in mac. You can physically control the background rendering in Final cut pro. When you want to have more control, disable rendering in FCP and choose which clip you would like to render. You can change the preferences to disable or enable through the FCPx settings. Once you disable the rendering, it is your choice to select the specific clips to render.
Open the preferences menu in your mac and render the highlighted clips in your Fcpx timeline. Use the control+R shortcut to render the files.
To delete the render files in Fcpx, Delete the generated files. Files> generated files. A window will appear, Click ok on delete render files.
****
## **Part2: What to do with the “not enough disk space” error even with enough space in Mac?**
Sometimes still having a lot of space, Your final cut pro X shows not enough disk space error in FCP X. Help!
Have you ever got the error of not having enough space at available destinations whenever you import anything to FCP X.?
Quick GuideFollow the below steps to solve this problem
1. Click and select the library in FCPX
2. Then go to the File menu and select “Delete generated library file”
3. Next, Select all the render and proxy files
4. You might not be using optimized files, In that case, select optimized files
5. Exit FCPX.
6. To reboot, hold down both option and command keys
7. Delete the preference files
8. If the error persists, run the utility folder that is inside the Application folder.
9. Execute First aid in all the units.
10. If the error persists, obtain a copy of the disk, and repair the directories on all the drives.
## **Part 3: How much space can FCPX take in Mac?**
Today, when we have hard drives and multi-terabytes, many of us have stopped looking at the disk space. Many of you usually don't bother until you get an alert that the disk is full.
Sometimes the largest drives get filled eventually. If you haven't checked your disk space yet, use your Mac and follow the instructions given below. You may be surprised about how much space can FCPX take.
Here is how you will do it:
**Option 1: Checking the mac storage through "About this Mac"**
Now it is a bit easy to check the storage from about the section. You will find this in most of the recent MAC versions.
Click on the mac logo and then click on “About this mac”.
Click on “storage” and you will see a reference chart stacked portraying the capacity of the disk and the absolute amount of storage taken by different categories of information. Moreover, you will find out the space that is yet accessible to you.
**Option 2: Checking the mac storage through “Disk utility”**
If you're a Mac user, you might know that there is a disk utility app. You can easily get a readout of the available space from there.
Open your Finder and click "Applications" on the left side.
Or click the magnifying glass in the upper right to find disk utility.
You will find utilities in Applications. **Applications> utilities**.
After the disk utility opens, you can see the available used spaces. Remember to put your hard drive’s name from the list. The popup window that opens up will also tell you the free space of any device connected to your Mac.

**Option3: Checking the storage from the Finder**
You can get a preview of your storage device by clicking an item in the Finder and pressing the spacebar on your keyboard. Let's suppose you need to check a particular document without opening it.
Select that document and press the spacebar. You will know what's inside without even opening it.
**Quick Guide Here is how you can do it**
1. Go to Finder and select Finder>Preferences, next Click General, modify the settings and you will see the storage device on the desktop.
2. To check the available or remaining space, click the spacebar. As you click it a window popup will show you the remaining space.
3. Press the spacebar again to close the window or you can do it via command. Press Command-W.
4. Turn on the finder status bar on your window. In case you want to check the disk space frequently.
5. Open a Finder window and next open the view menu. As you select the show status bar option, you will see the number of items in the folders. In the other case, if you are viewing the folder you'll get the idea of remaining or free space
If you're looking for a lighter alternative to Final Cut Pro, try Filmora to save more space!
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**So, is your FCPX good to go? Get your [tutorials for FCPX](https://tools.techidaily.com/wondershare/filmora/download/) here!**
## **Part 4: How to free up space in Mac?**
Find out what’s occupying the room in your Mac to save room for final cut pro. Get familiar with how to deal with your Mac’s capacity. Acquaint yourself with the ideal approaches to free up space in Mac.
Nowadays, Macs have limited and restricted capacity due to the SSDs present in them. When there were hard drives in Mac, we had a huge room on them. In recent memory, high-resolution videos, music, and other functional records take up more capacity. When you run out of space, it hampers your work and processing.
**_Quickly clear your mac space._**
If you are in a hurry, you can do the below things to quickly clear up the space in your mac.
1. Select the download folder and open it in the Finder. Now select the folder whose content you don't need and trash it.
2. Move to the home folder and open a new Find window. Press command-F.
3. Click the drop-down menu to choose "other."Look to the box next to "Document size". Press ok. Choose" greater than" in the next dropdown menu. With this choose the unwanted file or the one that is no longer useful to throw in the trash.
4. Another thing that you can do is, move those files in the trash that you haven’t opened in the last year.
5. If your desktop has a lot of unused stuff and is taking space, then delete the folders on the desktop.
**Ways to clean junk on your Mac**
There are many ways to clean garbage records on Mac. You may have different types of garbage in your Mac. Here is a simple solution for the elimination of junk from your Mac. Along with occupying the space, junk slows down your Pc, phone, and Mac.
**Cleaning cache files:** Every Mac has some files stored which are known as cache files. Some temporary files are kept in Mac to speed up the Apple software. It better to clean the files before it gets accumulated and hampers the performance.
* Press command +shift+G after opening the Finder.
* Enter this command in the field box\~/Library/Caches.
* See all the visible files on the appearing window
* Select all files to delete, and you can delete one by one
* Enter the username and password in the popup window
Similarly, you can clean the system log files too from your mac by below steps:
1. Go to the folder. Before selecting Go, enter the /var/log/.
2. All the system files are visible to you. Now, you can easily delete unwanted files.
**Clean with Clean MyMacX**
You can now clean your mac with this application. Download this application for free. After launching it, see the features on left and click on the system junk. Do scanning and check the opposite side of user cache files and delete the items, you want to delete. Lastly, press clean to clean it. Your Mac is now as new as before. Clean MyMacX cleans all the junk and makes your mac clutter-free.
**Conclusion**
Move the unwanted and unused clips from your Mac final cut pro X. Even you can free up the storage by deleting the whole event. A few media files stay in the library as many projects use the same media.

Benjamin Arango
Benjamin Arango is a writer and a lover of all things video.
Follow @Benjamin Arango
##### Benjamin Arango
Mar 27, 2024• Proven solutions
Whenever you are working on a Mac ensure that 10% of your storage is ideal and free. Without free space, your work is going to get slow. Sometimes you have to erase a portion of things occupying extra storage to work smoothly.
Never ignore and disregard the errors and alerts of the space disk being full. This article is all about how to fix the disk space in the **final cut Pro X.** Moreover, this article will cover the different ways via which you can check mac storage space, and how to free up space in FCPX and Mac.
Quick Guide:
> * [Part 1: How to free up space from Final Cut Pro Library?](#part1)
> * [Part 2: What to do with the “not enough disk space” error](#part2)
> * [Part 3: How much space can FCPX take in Mac?](#part3)
> * [Part 4: How to free up space in Mac?](#part4)
## **Part 1: How to free up space from Final Cut Pro Library?**
It takes three steps, and here are these steps.
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)
**Step1: Remember to delete unused clips and original medias**
To make room in your final cut pro, delete all the unused clips and original media. Delete the generated library files and delete the render files. Before deleting make sure to check whether to delete unused or used render files.

**Step 2: How to save space with files and transcoding options?**
It happens in final cut pro, that while working, it creates records, proxy files, and rendered files. To save space, you have to delete these files. It is advised to delete the generated rendered files before moving the library to mac Final Cut pro. Moreover, Mac recovers all the files the following time you open the project
**Step 3: How to stop background rendering and how to delete render files in Fcpx?**
Sometimes temporary videos and audios are created in Final cut pro X . Background rendering starts just after 5 seconds you quit working in mac. You can physically control the background rendering in Final cut pro. When you want to have more control, disable rendering in FCP and choose which clip you would like to render. You can change the preferences to disable or enable through the FCPx settings. Once you disable the rendering, it is your choice to select the specific clips to render.
Open the preferences menu in your mac and render the highlighted clips in your Fcpx timeline. Use the control+R shortcut to render the files.
To delete the render files in Fcpx, Delete the generated files. Files> generated files. A window will appear, Click ok on delete render files.
****
## **Part2: What to do with the “not enough disk space” error even with enough space in Mac?**
Sometimes still having a lot of space, Your final cut pro X shows not enough disk space error in FCP X. Help!
Have you ever got the error of not having enough space at available destinations whenever you import anything to FCP X.?
Quick GuideFollow the below steps to solve this problem
1. Click and select the library in FCPX
2. Then go to the File menu and select “Delete generated library file”
3. Next, Select all the render and proxy files
4. You might not be using optimized files, In that case, select optimized files
5. Exit FCPX.
6. To reboot, hold down both option and command keys
7. Delete the preference files
8. If the error persists, run the utility folder that is inside the Application folder.
9. Execute First aid in all the units.
10. If the error persists, obtain a copy of the disk, and repair the directories on all the drives.
## **Part 3: How much space can FCPX take in Mac?**
Today, when we have hard drives and multi-terabytes, many of us have stopped looking at the disk space. Many of you usually don't bother until you get an alert that the disk is full.
Sometimes the largest drives get filled eventually. If you haven't checked your disk space yet, use your Mac and follow the instructions given below. You may be surprised about how much space can FCPX take.
Here is how you will do it:
**Option 1: Checking the mac storage through "About this Mac"**
Now it is a bit easy to check the storage from about the section. You will find this in most of the recent MAC versions.
Click on the mac logo and then click on “About this mac”.
Click on “storage” and you will see a reference chart stacked portraying the capacity of the disk and the absolute amount of storage taken by different categories of information. Moreover, you will find out the space that is yet accessible to you.
**Option 2: Checking the mac storage through “Disk utility”**
If you're a Mac user, you might know that there is a disk utility app. You can easily get a readout of the available space from there.
Open your Finder and click "Applications" on the left side.
Or click the magnifying glass in the upper right to find disk utility.
You will find utilities in Applications. **Applications> utilities**.
After the disk utility opens, you can see the available used spaces. Remember to put your hard drive’s name from the list. The popup window that opens up will also tell you the free space of any device connected to your Mac.

**Option3: Checking the storage from the Finder**
You can get a preview of your storage device by clicking an item in the Finder and pressing the spacebar on your keyboard. Let's suppose you need to check a particular document without opening it.
Select that document and press the spacebar. You will know what's inside without even opening it.
**Quick Guide Here is how you can do it**
1. Go to Finder and select Finder>Preferences, next Click General, modify the settings and you will see the storage device on the desktop.
2. To check the available or remaining space, click the spacebar. As you click it a window popup will show you the remaining space.
3. Press the spacebar again to close the window or you can do it via command. Press Command-W.
4. Turn on the finder status bar on your window. In case you want to check the disk space frequently.
5. Open a Finder window and next open the view menu. As you select the show status bar option, you will see the number of items in the folders. In the other case, if you are viewing the folder you'll get the idea of remaining or free space
If you're looking for a lighter alternative to Final Cut Pro, try Filmora to save more space!
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
**So, is your FCPX good to go? Get your [tutorials for FCPX](https://tools.techidaily.com/wondershare/filmora/download/) here!**
## **Part 4: How to free up space in Mac?**
Find out what’s occupying the room in your Mac to save room for final cut pro. Get familiar with how to deal with your Mac’s capacity. Acquaint yourself with the ideal approaches to free up space in Mac.
Nowadays, Macs have limited and restricted capacity due to the SSDs present in them. When there were hard drives in Mac, we had a huge room on them. In recent memory, high-resolution videos, music, and other functional records take up more capacity. When you run out of space, it hampers your work and processing.
**_Quickly clear your mac space._**
If you are in a hurry, you can do the below things to quickly clear up the space in your mac.
1. Select the download folder and open it in the Finder. Now select the folder whose content you don't need and trash it.
2. Move to the home folder and open a new Find window. Press command-F.
3. Click the drop-down menu to choose "other."Look to the box next to "Document size". Press ok. Choose" greater than" in the next dropdown menu. With this choose the unwanted file or the one that is no longer useful to throw in the trash.
4. Another thing that you can do is, move those files in the trash that you haven’t opened in the last year.
5. If your desktop has a lot of unused stuff and is taking space, then delete the folders on the desktop.
**Ways to clean junk on your Mac**
There are many ways to clean garbage records on Mac. You may have different types of garbage in your Mac. Here is a simple solution for the elimination of junk from your Mac. Along with occupying the space, junk slows down your Pc, phone, and Mac.
**Cleaning cache files:** Every Mac has some files stored which are known as cache files. Some temporary files are kept in Mac to speed up the Apple software. It better to clean the files before it gets accumulated and hampers the performance.
* Press command +shift+G after opening the Finder.
* Enter this command in the field box\~/Library/Caches.
* See all the visible files on the appearing window
* Select all files to delete, and you can delete one by one
* Enter the username and password in the popup window
Similarly, you can clean the system log files too from your mac by below steps:
1. Go to the folder. Before selecting Go, enter the /var/log/.
2. All the system files are visible to you. Now, you can easily delete unwanted files.
**Clean with Clean MyMacX**
You can now clean your mac with this application. Download this application for free. After launching it, see the features on left and click on the system junk. Do scanning and check the opposite side of user cache files and delete the items, you want to delete. Lastly, press clean to clean it. Your Mac is now as new as before. Clean MyMacX cleans all the junk and makes your mac clutter-free.
**Conclusion**
Move the unwanted and unused clips from your Mac final cut pro X. Even you can free up the storage by deleting the whole event. A few media files stay in the library as many projects use the same media.

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-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-get-sound-back-in-avidemux-easy-fixes/"><u>Updated Get Sound Back in Avidemux Easy Fixes</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-vertical-video-mastery-top-editing-apps-for-iphone-and-android/"><u>Updated 2024 Approved Vertical Video Mastery Top Editing Apps for iPhone and Android</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/adobe-premiere-pro-for-mac-is-the-most-popular-professional-video-editor-if-youre-planning-to-try-it-out-for-your-mac-heres-all-you-need-to-know-about-it-fo/"><u>Adobe Premiere Pro for Mac Is the Most Popular Professional Video Editor. If Youre Planning to Try It Out for Your Mac, Heres All You Need to Know About It for 2024</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-discover-the-top-iphone-apps-from-productivity-to-entertainment/"><u>New 2024 Approved Discover the Top iPhone Apps From Productivity to Entertainment</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-vignette-magic-the-best-free-and-paid-apps-for-iphone-and-android-for-2024/"><u>New Vignette Magic The Best Free and Paid Apps for iPhone and Android for 2024</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-unleash-your-creativity-a-comprehensive-guide-to-jaycut-free-video-editing-for-2024/"><u>New Unleash Your Creativity A Comprehensive Guide to Jaycut Free Video Editing for 2024</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-in-2024-top-rated-mp4-video-tagging-tools-for-windows-and-macos/"><u>New In 2024, Top-Rated MP4 Video Tagging Tools for Windows and macOS</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-speed-up-your-storytelling-time-lapse-video-creation-in-final-cut-pro/"><u>Updated 2024 Approved Speed Up Your Storytelling Time Lapse Video Creation in Final Cut Pro</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-extracting-still-images-from-videos-10-reliable-converters/"><u>New Extracting Still Images From Videos 10 Reliable Converters</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-little-directors-big-ideas-teaching-kids-to-make-movies/"><u>Updated Little Directors, Big Ideas Teaching Kids to Make Movies</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-in-2024-top-10-best-avi-joiner-freeware-to-join-avi-video-files/"><u>Updated In 2024, Top 10 Best AVI Joiner Freeware to Join AVI Video Files</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-in-2024-unbiased-review-of-avs-video-editor-features-pricing-and-more/"><u>Updated In 2024, Unbiased Review of AVS Video Editor Features, Pricing, and More</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-bunny-up-your-video-editing-game-wondershare-filmora-easter-sale-mar-2024/"><u>New Bunny Up Your Video Editing Game Wondershare Filmora Easter Sale - Mar 2024</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-easily-combine-photos-and-videos-best-online-collage-generators/"><u>2024 Approved Easily Combine Photos and Videos Best Online Collage Generators</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-free-animation-solutions-top-picks-for-windows-and-mac-computers/"><u>Updated Free Animation Solutions Top Picks for Windows and Mac Computers</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-minitool-movie-maker-review-is-it-the-best-video-editor-for-you-for-2024/"><u>New Minitool Movie Maker Review Is It the Best Video Editor for You for 2024</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-top-10-free-online-subtitle-generators-for-videos/"><u>Updated 2024 Approved Top 10 Free Online Subtitle Generators for Videos</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-best-vsdc-video-editor-replacements-for-mac-users/"><u>Updated Best VSDC Video Editor Replacements for Mac Users</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-get-ready-for-seamless-editing-filmora-x-supports-arm/"><u>New Get Ready for Seamless Editing Filmora X Supports ARM</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/unlocking-the-power-of-chroma-keying-in-final-cut-pro-x-for-2024/"><u>Unlocking the Power of Chroma Keying in Final Cut Pro X for 2024</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-free-to-edit-top-open-source-video-editors/"><u>Updated Free to Edit Top Open-Source Video Editors</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/in-2024-step-by-step-the-top-10-video-players-for-frame-by-frame-analysis/"><u>In 2024, Step-by-Step The Top 10 Video Players for Frame-by-Frame Analysis</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-get-more-done-in-less-time-free-mac-speech-to-text-software-you-need-for-2024/"><u>New Get More Done in Less Time Free Mac Speech-to-Text Software You Need for 2024</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-unlock-efficient-editing-20-adobe-premiere-shortcuts-you-need/"><u>New 2024 Approved Unlock Efficient Editing 20 Adobe Premiere Shortcuts You Need</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-optimize-your-linkedin-videos-the-best-aspect-ratios-for-maximum-engagement/"><u>Updated Optimize Your LinkedIn Videos The Best Aspect Ratios for Maximum Engagement</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-distort-degrade-and-disrupt-the-best-free-online-glitch-tools/"><u>Updated 2024 Approved Distort, Degrade, and Disrupt The Best Free Online Glitch Tools</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/in-2024-gaming-intro-creation-made-easy-top-10-tools-for-windows-and-mac/"><u>In 2024, Gaming Intro Creation Made Easy Top 10 Tools for Windows and Mac</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-mac-users-rejoice-the-ultimate-gopro-video-editing-guide/"><u>New Mac Users Rejoice The Ultimate GoPro Video Editing Guide</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/stream-movies-from-your-device-to-chromecast-windows-mac-android-and-ios-instructions/"><u>Stream Movies From Your Device to Chromecast Windows, Mac, Android, and iOS Instructions</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-nikon-video-post-production-made-easy-tips-and-tricks/"><u>New 2024 Approved Nikon Video Post-Production Made Easy Tips and Tricks</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-unlock-custom-aspect-ratios-in-final-cut-pro-expert-techniques-revealed/"><u>New Unlock Custom Aspect Ratios in Final Cut Pro Expert Techniques Revealed</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-get-ready-to-groove-the-best-lip-sync-video-maker-apps/"><u>New 2024 Approved Get Ready to Groove The Best Lip Sync Video Maker Apps</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/jaw-dropping-4k-videos-that-will-leave-you-speechless/"><u>Jaw-Dropping 4K Videos That Will Leave You Speechless</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/best-slow-mo-to-fast-mo-converters-for-computer/"><u>Best Slow-Mo to Fast-Mo Converters for Computer</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-in-2024-adobe-premiere-2023-a-step-by-step-guide-to-importing-and-exporting-videos/"><u>Updated In 2024, Adobe Premiere 2023 A Step-by-Step Guide to Importing and Exporting Videos</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/in-2024-in-this-article-you-will-find-ten-of-the-best-and-most-trusted-video-editing-applications-that-do-support-4k-videos-including-both-free-4k-and-paid-/"><u>In 2024, In This Article, You Will Find Ten of the Best and Most Trusted Video Editing Applications that Do Support 4K Videos, Including Both Free 4K and Paid 4K Video Editing Software for You to Choose</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-android-and-iphones-finest-video-creators-with-music-integration/"><u>2024 Approved Android and iPhones Finest Video Creators with Music Integration</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/5-best-online-tone-generators-for-you/"><u>5 Best Online Tone Generators for You</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-the-art-of-seamless-audio-transitions-in-final-cut-pro-x/"><u>Updated 2024 Approved The Art of Seamless Audio Transitions in Final Cut Pro X</u></a></li>
<li><a href="https://howto.techidaily.com/4-ways-to-fix-android-blue-screen-of-death-on-tecno-spark-20-proplus-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>4 Ways to Fix Android Blue Screen of Death On Tecno Spark 20 Pro+ | Dr.fone</u></a></li>
<li><a href="https://review-topics.techidaily.com/recover-your-contacts-after-galaxy-xcover-7-has-been-deleted-by-fonelab-android-recover-contacts/"><u>Recover your contacts after Galaxy XCover 7 has been deleted.</u></a></li>
<li><a href="https://phone-solutions.techidaily.com/5-ways-to-restart-nubia-red-magic-8s-pro-without-power-button-drfone-by-drfone-reset-android-reset-android/"><u>5 Ways to Restart Nubia Red Magic 8S Pro Without Power Button | Dr.fone</u></a></li>
<li><a href="https://bypass-frp.techidaily.com/in-2024-a-quick-guide-to-google-pixel-7a-frp-bypass-instantly-by-drfone-android/"><u>In 2024, A Quick Guide to Google Pixel 7a FRP Bypass Instantly</u></a></li>
<li><a href="https://ai-vdieo-software.techidaily.com/add-music-to-your-videos-top-online-video-editors-reviewed-for-2024/"><u>Add Music to Your Videos Top Online Video Editors Reviewed for 2024</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/3-methods-to-mirror-oneplus-ace-2-pro-to-roku-drfone-by-drfone-android/"><u>3 Methods to Mirror OnePlus Ace 2 Pro to Roku | Dr.fone</u></a></li>
<li><a href="https://phone-solutions.techidaily.com/how-do-you-play-mkv-files-on-xiaomi-civi-3-by-aiseesoft-video-converter-play-mkv-on-android/"><u>How do you play MKV files on Xiaomi Civi 3?</u></a></li>
<li><a href="https://fake-location.techidaily.com/how-to-sharefake-gps-on-uber-for-lava-blaze-2-drfone-by-drfone-virtual-android/"><u>How to share/fake gps on Uber for Lava Blaze 2 | Dr.fone</u></a></li>
<li><a href="https://techidaily.com/use-device-manager-to-identify-missing-drivers-with-windows-device-manager-in-windows-11-and-10-by-drivereasy-guide/"><u>Use Device Manager to identify missing drivers with Windows Device Manager in Windows 11 & 10</u></a></li>
<li><a href="https://ai-vdieo-software.techidaily.com/2024-approved-edit-mp4-files-on-mac-mavericks-a-comprehensive-guide/"><u>2024 Approved Edit MP4 Files on Mac Mavericks A Comprehensive Guide</u></a></li>
<li><a href="https://android-frp.techidaily.com/in-2024-how-can-we-bypass-oppo-reno-8t-frp-by-drfone-android/"><u>In 2024, How Can We Bypass Oppo Reno 8T FRP?</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/in-2024-how-to-screen-mirroring-infinix-hot-30-5g-drfone-by-drfone-android/"><u>In 2024, How to Screen Mirroring Infinix Hot 30 5G? | Dr.fone</u></a></li>
<li><a href="https://ai-vdieo-software.techidaily.com/2024-approved-adobe-premiere-pro-cs6-mac-free-download-unleash-your-creativity/"><u>2024 Approved Adobe Premiere Pro CS6 Mac Free Download Unleash Your Creativity</u></a></li>
<li><a href="https://ios-pokemon-go.techidaily.com/in-2024-ultimate-guide-to-catch-the-regional-located-pokemon-for-apple-iphone-13-pro-max-drfone-by-drfone-virtual-ios/"><u>In 2024, Ultimate Guide to Catch the Regional-Located Pokemon For Apple iPhone 13 Pro Max | Dr.fone</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-a-complete-guide-to-oem-unlocking-on-oppo-a38-by-drfone-android/"><u>In 2024, A Complete Guide To OEM Unlocking on Oppo A38</u></a></li>
<li><a href="https://techidaily.com/all-things-you-need-to-know-about-wipe-datafactory-reset-for-samsung-galaxy-z-flip-5-drfone-by-drfone-reset-android-reset-android/"><u>All Things You Need to Know about Wipe Data/Factory Reset For Samsung Galaxy Z Flip 5 | 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-13-pro-drfone-by-drfone-virtual-ios/"><u>How Can I Create My Pokemon Overworld Maps On Apple iPhone 13 Pro? | Dr.fone</u></a></li>
<li><a href="https://android-pokemon-go.techidaily.com/how-to-use-ispoofer-on-motorola-edge-40-pro-drfone-by-drfone-virtual-android/"><u>How to use iSpoofer on Motorola Edge 40 Pro? | Dr.fone</u></a></li>
<li><a href="https://review-topics.techidaily.com/iphone-15-plus-data-recovery-software-to-recover-lost-ios-data-stellar-by-stellar-data-recovery-ios-iphone-data-recovery/"><u>iPhone 15 Plus® Data Recovery Software to Recover Lost iOS® Data | Stellar</u></a></li>
<li><a href="https://pokemon-go-android.techidaily.com/planning-to-use-a-pokemon-go-joystick-on-honor-x9b-drfone-by-drfone-virtual-android/"><u>Planning to Use a Pokemon Go Joystick on Honor X9b? | Dr.fone</u></a></li>
<li><a href="https://techidaily.com/hard-reset-poco-c55-in-3-efficient-ways-drfone-by-drfone-reset-android-reset-android/"><u>Hard Reset Poco C55 in 3 Efficient Ways | Dr.fone</u></a></li>
<li><a href="https://howto.techidaily.com/what-to-do-if-your-realme-12plus-5g-auto-does-not-work-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>What To Do if Your Realme 12+ 5G Auto Does Not Work | Dr.fone</u></a></li>
<li><a href="https://change-location.techidaily.com/why-is-ipogo-not-working-on-vivo-y78t-fixed-drfone-by-drfone-virtual-android/"><u>Why is iPogo not working On Vivo Y78t? Fixed | Dr.fone</u></a></li>
</ul></div> |
import { Link } from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "../Provider/AuthProvider";
import {
FaFilm,
FaTheaterMasks,
FaLaugh,
FaBolt,
FaHeart,
FaGlobe,
} from "react-icons/fa";
const categories = [
{
id: 1,
name: "Action",
icon: FaBolt,
description: "Thrilling action-packed adventures",
color: "bg-red-500",
count: "250+",
},
{
id: 2,
name: "Drama",
icon: FaTheaterMasks,
description: "Compelling dramatic narratives",
color: "bg-blue-500",
count: "180+",
},
{
id: 3,
name: "Comedy",
icon: FaLaugh,
description: "Hilarious comedic entertainment",
color: "bg-yellow-500",
count: "200+",
},
{
id: 4,
name: "Romance",
icon: FaHeart,
description: "Heart-warming love stories",
color: "bg-pink-500",
count: "150+",
},
{
id: 5,
name: "International",
icon: FaGlobe,
description: "Award-winning foreign films",
color: "bg-purple-500",
count: "300+",
},
{
id: 6,
name: "Classics",
icon: FaFilm,
description: "Timeless cinematic masterpieces",
color: "bg-green-500",
count: "120+",
},
];
const PopularCategories = () => {
const { theme } = useContext(AuthContext);
return (
<section className={`py-16 ${theme === "dark" ? "bg-gray-900" : "bg-gray-50"}`}>
<div className="container mx-auto px-4">
<div className="text-center mb-12">
<h2
className={`text-3xl md:text-4xl font-bold mb-4 ${
theme === "dark" ? "text-white" : "text-gray-900"
}`}
>
Popular Categories
</h2>
<p
className={`text-lg ${
theme === "dark" ? "text-gray-300" : "text-gray-600"
}`}
>
Discover movies across your favorite genres
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{categories.map((category) => (
<Link
key={category.id}
to={`/all-movie?category=${category.name.toLowerCase()}`}
className={`group p-6 rounded-xl transition-all duration-300 transform hover:-translate-y-1 ${
theme === "dark"
? "bg-gray-800 hover:bg-gray-700"
: "bg-white hover:bg-gray-50"
} shadow-lg hover:shadow-xl`}
>
<div className="flex items-start space-x-4">
<div
className={`p-3 rounded-lg ${category.color} bg-opacity-10 group-hover:bg-opacity-20 transition-all duration-300`}
>
<category.icon
className={`text-2xl ${category.color} text-opacity-90`}
/>
</div>
<div className="flex-1">
<h3
className={`text-xl font-semibold mb-2 ${
theme === "dark" ? "text-white" : "text-gray-900"
}`}
>
{category.name}
</h3>
<p
className={`mb-3 ${
theme === "dark" ? "text-gray-400" : "text-gray-600"
}`}
>
{category.description}
</p>
<div className="flex items-center justify-between">
<span
className={`text-sm font-medium ${
theme === "dark" ? "text-gray-400" : "text-gray-500"
}`}
>
{category.count} Movies
</span>
<span
className={`text-sm font-medium ${category.color} text-opacity-90`}
>
Explore →
</span>
</div>
</div>
</div>
</Link>
))}
</div>
</div>
</section>
);
};
export default PopularCategories; |

<div align="center">
<font size="6"> A Collaborative Deep Learning Framework for Conservation </font>
<br>
<hr>
<a href="https://pypi.org/project/PytorchWildlife"><img src="https://img.shields.io/pypi/v/PytorchWildlife?color=limegreen" /></a>
<a href="https://pypi.org/project/PytorchWildlife"><img src="https://static.pepy.tech/badge/pytorchwildlife" /></a>
<a href="https://pypi.org/project/PytorchWildlife"><img src="https://img.shields.io/pypi/pyversions/PytorchWildlife" /></a>
<a href="https://huggingface.co/spaces/ai-for-good-lab/pytorch-wildlife"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Demo-blue" /></a>
<a href="https://colab.research.google.com/drive/1rjqHrTMzEHkMualr4vB55dQWCsCKMNXi?usp=sharing"><img src="https://img.shields.io/badge/Colab-Demo-blue?logo=GoogleColab" /></a>
<!-- <a href="https://colab.research.google.com/drive/16-OjFVQ6nopuP-gfqofYBBY00oIgbcr1?usp=sharing"><img src="https://img.shields.io/badge/Colab-Video detection-blue?logo=GoogleColab" /></a> -->
<a href="https://cameratraps.readthedocs.io/en/latest/"><img src="https://img.shields.io/badge/read-docs-yellow?logo=ReadtheDocs" /></a>
<a href="https://github.com/microsoft/CameraTraps/blob/main/LICENSE"><img src="https://img.shields.io/pypi/l/PytorchWildlife" /></a>
<a href="https://discord.gg/TeEVxzaYtm"><img src="https://img.shields.io/badge/any_text-Join_us!-blue?logo=discord&label=Discord" /></a>
<br><br>
</div>
## 🐾 Introduction
At the core of our mission is the desire to create a harmonious space where conservation scientists from all over the globe can unite. Where they're able to share, grow, use datasets and deep learning architectures for wildlife conservation.
We've been inspired by the potential and capabilities of Megadetector, and we deeply value its contributions to the community. As we forge ahead with Pytorch-Wildlife, under which Megadetector now resides, please know that we remain committed to supporting, maintaining, and developing Megadetector, ensuring its continued relevance, expansion, and utility.
Pytorch-Wildlife is pip installable:
```
pip install PytorchWildlife
```
To use the newest version of MegaDetector with all the existing functionalities, you can use our [Hugging Face interface](https://huggingface.co/spaces/ai-for-good-lab/pytorch-wildlife) or simply load the model with **Pytorch-Wildlife**. The weights will be automatically downloaded:
```python
from PytorchWildlife.models import detection as pw_detection
detection_model = pw_detection.MegaDetectorV6()
```
For those interested in accessing the previous MegaDetector repository, which utilizes the same `MegaDetectorV5` model weights and was primarily developed by Dan Morris during his time at Microsoft, please visit the [archive](https://github.com/microsoft/CameraTraps/blob/main/archive) directory, or you can visit this [forked repository](https://github.com/agentmorris/MegaDetector/tree/main) that Dan Morris is actively maintaining.
>[!TIP]
>If you have any questions regarding MegaDetector and Pytorch-Wildlife, please [email us](zhongqimiao@microsoft.com) or join us in our discord channel: [](https://discord.gg/TeEVxzaYtm)
## 📣 Announcements
### 🎉🎉🎉 Pytorch-Wildlife Version 1.1.0 is out!
- MegaDetectorV6 is finally out! Please refer to our [next section](#racing_cardashdash-megadetectorv6-smaller-better-and-faster) and our [release notes](https://github.com/microsoft/CameraTraps/releases/tag/pw_v1.1.0) for more details!
- We have incorporated a point-based overhead animal detection model into our model zoo called [HerdNet (Delplanque et al. 2022)](https://www.sciencedirect.com/science/article/pii/S092427162300031X?via%3Dihub). Two model weights are incorporated in this release, `HerdNet-general` (their default weights) and `HerdNet-ennedi` (their model trained on Ennedi 2019 datasets). More details can be found [here](PytorchWildlife/models/detection/herdnet/Herdnet.md) and in their original [repo](https://github.com/Alexandre-Delplanque/HerdNet). This is the first third-party model in Pytorch-Wildlife and the foundation of our expansion to overhead/aerial animal detection and classification. Please see our [HerdNet demo](demo/image_detection_demo_herdnet.ipynb) on how to use it!
- You can now load custom weights you fine-tuned on your own datasets using the [finetuning module](PW_FT_classification) directly in the Pytorch-Wildlife pipeline! Please see the [demo](demo/custom_weight_loading_v6.ipynb) on how to do it. You can also load it in our Gradio app!
- You can now automatically separate your image detections into folders based on detection results! Please see our [folder separation demo](demo/image_separation_demo_v6.ipynb) on how to do it. You can also test it in our Gradio demo!
- We have also simplified the batch detection pipeline. Now we do not need to define pytorch datasets and dataloaders specifically. Please make sure to change your code and check our [release notes](https://github.com/microsoft/CameraTraps/releases/tag/pw_v1.1.0) and our [new demo](demo/image_demo.py#58) for more details.
<details>
<summary><font size="3">👉 Click for more updates</font></summary>
<li> Issues [#523](https://github.com/microsoft/CameraTraps/issues/523), [#524](https://github.com/microsoft/CameraTraps/issues/524) and [#526](https://github.com/microsoft/CameraTraps/issues/526) have been solved!
<li> PyTorchWildlife is now compatible with Supervision 0.23+ and Python 3.10+!
<li> CUDA 12.x compatibility. <br>
</details>
### :racing_car::dash::dash: MegaDetectorV6: SMALLER, BETTER, and FASTER!
After a few months of public beta testing, we are finally ready to officially release our 6th version of MegaDetector, MegaDetectorV6! In the next generation of MegaDetector, we are focusing on computational efficiency, performance, mordernizing of model architectures, and licensing. We have trained multiple new models using different model architectures, including Yolo-v9, Yolo-v11, and RT-Detr for maximum user flexibility. We have a [rolling release schedule](#mag-model-zoo) for different versions of MegaDetectorV6, and in the first step, we are releasing the compact version of MegaDetectorV6 with Yolo-v9 (MDv6-ultralytics-yolov9-compact, MDv6-c in short). From now on, we encourage our users to use MegaDetectorV6 as their default animal detection model.
This MDv6-c model is optimized for performance and low-budget devices. It has only ***one-sixth (SMALLER)*** of the parameters of the previous MegaDetectorV5 and exhibits ***12% higher recall (BETTER)*** on animal detection in our validation datasets. In other words, MDv6-c has significantly fewer false negatives when detecting animals, making it a more robust animal detection model than MegaDetectorV5. Furthermore, one of our testers reported that the speed of MDv6-c is at least ***5 times FASTER*** than MegaDetectorV5 on their datasets.
|Models|Parameters|Precision|Recall|
|---|---|---|---|
|MegaDetectorV5|121M|0.96|0.73|
|MegaDetectroV6-c|22M|0.92|0.85|
Learn how to use MegaDetectorV6 in our [image demo](demo/image_detection_demo_v6.ipynb) and [video demo](demo/video_detection_demo_v6.ipynb).
### :bangbang: Model licensing `(IMPORTANT!!)`
The **Pytorch-Wildlife** package is under MIT, however some of the models in the model zoo are not. For example, MegaDetectorV5, which is trained using the Ultralytics package, is under AGPL-3.0, and is not for closed-source comercial uses.
> [!IMPORTANT]
> THIS IS TRUE TO ALL EXISTING MEGADETECTORV5 MODELS IN ALL EXISTING FORKS THAT ARE TRAINED USING YOLOV5, AN ULTRALYTICS-DEVELOPED MODEL.
We want to make Pytorch-Wildlife a platform where different models with different licenses can be hosted and want to enable different usecases. To reduce user confusions, in our [model zoo](#mag-model-zoo-and-release-schedules) section, we list all existing and planed future models in our model zoo, their corresponding license, and release schedules.
In addition, since the **Pytorch-Wildlife** package is under MIT, all the utility functions, including data pre-/post-processing functions and model fine-tuning functions in this packages are under MIT as well.
### :mag: Model Zoo and Release Schedules
#### Detection models
|Models|Licence|Release|
|---|---|---|
|MegaDetectorV5|AGPL-3.0|Released|
|MegaDetectroV6-Ultralytics-YoloV9-Compact|AGPL-3.0|Released|
|HerdNet-general|CC BY-NC-SA-4.0|Released|
|HerdNet-ennedi|CC BY-NC-SA-4.0|Released|
|MegaDetectroV6-Ultralytics-YoloV9-Extra|AGPL-3.0|November 2024|
|MegaDetectroV6-Ultralytics-YoloV10-Compact (even smaller and no NMS)|AGPL-3.0|November 2024|
|MegaDetectroV6-Ultralytics-YoloV10-Extra (extra large model and no NMS)|AGPL-3.0|November 2024|
|MegaDetectroV6-MIT-YoloV9-Compact|MIT|December 2024|
|MegaDetectroV6-MIT-YoloV9-Extra|MIT|December 2024|
|MegaDetectroV6-Ultralytics-YoloV11-Compact (better performance)|AGPL-3.0|December 2024|
|MegaDetectroV6-Ultralytics-YoloV11-Extra (better performance)|AGPL-3.0|December 2024|
|MegaDetectroV6-Apache-RTDetr-Compact|Apache|January 2025|
|MegaDetectroV6-Apache-RTDetr-Extra|Apache|January 2025|
#### Classification models
|Models|Licence|Release|
|---|---|---|
|AI4G-Oppossum|MIT|Released|
|AI4G-Amazon|MIT|Released|
|AI4G-Serengeti|MIT|Released|
## 👋 Welcome to Pytorch-Wildlife
**PyTorch-Wildlife** is a platform to create, modify, and share powerful AI conservation models. These models can be used for a variety of applications, including camera trap images, overhead images, underwater images, or bioacoustics. Your engagement with our work is greatly appreciated, and we eagerly await any feedback you may have.
The **Pytorch-Wildlife** library allows users to directly load the `MegaDetector` model weights for animal detection. We've fully refactored our codebase, prioritizing ease of use in model deployment and expansion. In addition to `MegaDetector`, **Pytorch-Wildlife** also accommodates a range of classification weights, such as those derived from the Amazon Rainforest dataset and the Opossum classification dataset. Explore the codebase and functionalities of **Pytorch-Wildlife** through our interactive [HuggingFace web app](https://huggingface.co/spaces/AndresHdzC/pytorch-wildlife) or local [demos and notebooks](https://github.com/microsoft/CameraTraps/tree/main/demo), designed to showcase the practical applications of our enhancements at [PyTorchWildlife](https://github.com/microsoft/CameraTraps/blob/main/INSTALLATION.md). You can find more information in our [documentation](https://cameratraps.readthedocs.io/en/latest/).
👇 Here is a brief example on how to perform detection and classification on a single image using `PyTorch-wildlife`
```python
import numpy as np
from PytorchWildlife.models import detection as pw_detection
from PytorchWildlife.models import classification as pw_classification
img = np.random.randn(3, 1280, 1280)
# Detection
detection_model = pw_detection.MegaDetectorV6() # Model weights are automatically downloaded.
detection_result = detection_model.single_image_detection(img)
#Classification
classification_model = pw_classification.AI4GAmazonRainforest() # Model weights are automatically downloaded.
classification_results = classification_model.single_image_classification(img)
```
## ⚙️ Install Pytorch-Wildlife
```
pip install PytorchWildlife
```
Please refer to our [installation guide](https://github.com/microsoft/CameraTraps/blob/main/INSTALLATION.md) for more installation information.
## 🕵️ Explore Pytorch-Wildlife and MegaDetector with our Demo User Interface
If you want to directly try **Pytorch-Wildlife** with the AI models available, including `MegaDetector`, you can use our [**Gradio** interface](https://github.com/microsoft/CameraTraps/tree/main/demo). This interface allows users to directly load the `MegaDetector` model weights for animal detection. In addition, **Pytorch-Wildlife** also has two classification models in our initial version. One is trained from an Amazon Rainforest camera trap dataset and the other from a Galapagos opossum classification dataset (more details of these datasets will be published soon). To start, please follow the [installation instructions](https://github.com/microsoft/CameraTraps/blob/main/INSTALLATION.md) on how to run the Gradio interface! We also provide multiple [**Jupyter** notebooks](https://github.com/microsoft/CameraTraps/tree/main/demo) for demonstration.

## 🛠️ Core Features
What are the core components of Pytorch-Wildlife?

### 🌐 Unified Framework:
Pytorch-Wildlife integrates **four pivotal elements:**
▪ Machine Learning Models<br>
▪ Pre-trained Weights<br>
▪ Datasets<br>
▪ Utilities<br>
### 👷 Our work:
In the provided graph, boxes outlined in red represent elements that will be added and remained fixed, while those in blue will be part of our development.
### 🚀 Inaugural Model:
We're kickstarting with YOLO as our first available model, complemented by pre-trained weights from `MegaDetector`. We have `MegaDetectorV5`, which is the same `MegaDetector v5` model from the previous repository, and many different versions of `MegaDetectorV6` for different usecases.
### 📚 Expandable Repository:
As we move forward, our platform will welcome new models and pre-trained weights for camera traps and bioacoustic analysis. We're excited to host contributions from global researchers through a dedicated submission platform.
### 📊 Datasets from LILA:
Pytorch-Wildlife will also incorporate the vast datasets hosted on LILA, making it a treasure trove for conservation research.
### 🧰 Versatile Utilities:
Our set of utilities spans from visualization tools to task-specific utilities, many inherited from Megadetector.
### 💻 User Interface Flexibility:
While we provide a foundational user interface, our platform is designed to inspire. We encourage researchers to craft and share their unique interfaces, and we'll list both existing and new UIs from other collaborators for the community's benefit.
Let's shape the future of wildlife research, together! 🙌
## 🖼️ Examples
### Image detection using `MegaDetector`
<img src="https://microsoft.github.io/CameraTraps/assets/animal_det_1.JPG" alt="animal_det_1" width="400"/><br>
*Credits to Universidad de los Andes, Colombia.*
### Image classification with `MegaDetector` and `AI4GAmazonRainforest`
<img src="https://microsoft.github.io/CameraTraps/assets/animal_clas_1.png" alt="animal_clas_1" width="500"/><br>
*Credits to Universidad de los Andes, Colombia.*
### Opossum ID with `MegaDetector` and `AI4GOpossum`
<img src="https://microsoft.github.io/CameraTraps/assets/opossum_det.png" alt="opossum_det" width="500"/><br>
*Credits to the Agency for Regulation and Control of Biosecurity and Quarantine for Galápagos (ABG), Ecuador.*
## 🔥 Future highlights
- [ ] A detection model fine-tuning module to fine-tune your own detection model for Pytorch-Wildlife.
- [ ] Direct LILA connection for more training/validation data.
- [ ] More pretrained detection and classification models to expand the current model zoo.
To check the full version of the roadmap with completed tasks and long term goals, please click [here!](roadmaps.md).
## 🤜🤛 Collaboration with EcoAssist!
We are thrilled to announce our collaboration with [EcoAssist](https://addaxdatascience.com/ecoassist/#spp-models)---a powerful user interface software that enables users to directly load models from the PyTorch-Wildlife model zoo for image analysis on local computers. With EcoAssist, you can now utilize MegaDetectorV5 and the classification models---AI4GAmazonRainforest and AI4GOpossum---for automatic animal detection and identification, alongside a comprehensive suite of pre- and post-processing tools. This partnership aims to enhance the overall user experience with PyTorch-Wildlife models for a general audience. We will work closely to bring more features together for more efficient and effective wildlife analysis in the future.
## :fountain_pen: Cite us!
We have recently published a [summary paper on Pytorch-Wildlife](https://arxiv.org/abs/2405.12930). The paper has been accepted as an oral presentation at the [CV4Animals workshop](https://www.cv4animals.com/) at this CVPR 2024. Please feel free to cite us!
```
@misc{hernandez2024pytorchwildlife,
title={Pytorch-Wildlife: A Collaborative Deep Learning Framework for Conservation},
author={Andres Hernandez and Zhongqi Miao and Luisa Vargas and Rahul Dodhia and Juan Lavista},
year={2024},
eprint={2405.12930},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
```
## 🤝 Contributing
This project is open to your ideas and contributions. If you want to submit a pull request, we'll have some guidelines available soon.
We have adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [us](zhongqimiao@microsoft.com) with any additional questions or comments.
## License
This repository is licensed with the [MIT license](https://github.com/Microsoft/dotnet/blob/main/LICENSE).
## 👥 Existing Collaborators
The extensive collaborative efforts of Megadetector have genuinely inspired us, and we deeply value its significant contributions to the community. As we continue to advance with Pytorch-Wildlife, our commitment to delivering technical support to our existing partners on MegaDetector remains the same.
Here we list a few of the organizations that have used MegaDetector. We're only listing organizations who have given us permission to refer to them here or have posted publicly about their use of MegaDetector.
<details>
<summary><font size="3">👉 Full list of organizations</font></summary>
(Newly Added) [TerrOïko](https://www.terroiko.fr/) ([OCAPI platform](https://www.terroiko.fr/ocapi))
[Arizona Department of Environmental Quality](http://azdeq.gov/)
[Blackbird Environmental](https://blackbirdenv.com/)
[Camelot](https://camelotproject.org/)
[Canadian Parks and Wilderness Society (CPAWS) Northern Alberta Chapter](https://cpawsnab.org/)
[Conservation X Labs](https://conservationxlabs.com/)
[Czech University of Life Sciences Prague](https://www.czu.cz/en)
[EcoLogic Consultants Ltd.](https://www.consult-ecologic.com/)
[Estación Biológica de Doñana](http://www.ebd.csic.es/inicio)
[Idaho Department of Fish and Game](https://idfg.idaho.gov/)
[Island Conservation](https://www.islandconservation.org/)
[Myall Lakes Dingo Project](https://carnivorecoexistence.info/myall-lakes-dingo-project/)
[Point No Point Treaty Council](https://pnptc.org/)
[Ramat Hanadiv Nature Park](https://www.ramat-hanadiv.org.il/en/)
[SPEA (Portuguese Society for the Study of Birds)](https://spea.pt/en/)
[Synthetaic](https://www.synthetaic.com/)
[Taronga Conservation Society](https://taronga.org.au/)
[The Nature Conservancy in Wyoming](https://www.nature.org/en-us/about-us/where-we-work/united-states/wyoming/)
[TrapTagger](https://wildeyeconservation.org/trap-tagger-about/)
[Upper Yellowstone Watershed Group](https://www.upperyellowstone.org/)
[Applied Conservation Macro Ecology Lab](http://www.acmelab.ca/), University of Victoria
[Banff National Park Resource Conservation](https://www.pc.gc.ca/en/pn-np/ab/banff/nature/conservation), Parks Canada(https://www.pc.gc.ca/en/pn-np/ab/banff/nature/conservation)
[Blumstein Lab](https://blumsteinlab.eeb.ucla.edu/), UCLA
[Borderlands Research Institute](https://bri.sulross.edu/), Sul Ross State University
[Capitol Reef National Park](https://www.nps.gov/care/index.htm) / Utah Valley University
[Center for Biodiversity and Conservation](https://www.amnh.org/research/center-for-biodiversity-conservation), American Museum of Natural History
[Centre for Ecosystem Science](https://www.unsw.edu.au/research/), UNSW Sydney
[Cross-Cultural Ecology Lab](https://crossculturalecology.net/), Macquarie University
[DC Cat Count](https://hub.dccatcount.org/), led by the Humane Rescue Alliance
[Department of Fish and Wildlife Sciences](https://www.uidaho.edu/cnr/departments/fish-and-wildlife-sciences), University of Idaho
[Department of Wildlife Ecology and Conservation](https://wec.ifas.ufl.edu/), University of Florida
[Ecology and Conservation of Amazonian Vertebrates Research Group](https://www.researchgate.net/lab/Fernanda-Michalski-Lab-4), Federal University of Amapá
[Gola Forest Programma](https://www.rspb.org.uk/our-work/conservation/projects/scientific-support-for-the-gola-forest-programme/), Royal Society for the Protection of Birds (RSPB)
[Graeme Shannon's Research Group](https://wildliferesearch.co.uk/group-1), Bangor University
[Hamaarag](https://hamaarag.org.il/), The Steinhardt Museum of Natural History, Tel Aviv University
[Institut des Science de la Forêt Tempérée (ISFORT)](https://isfort.uqo.ca/), Université du Québec en Outaouais
[Lab of Dr. Bilal Habib](https://bhlab.in/about), the Wildlife Institute of India
[Mammal Spatial Ecology and Conservation Lab](https://labs.wsu.edu/dthornton/), Washington State University
[McLoughlin Lab in Population Ecology](http://mcloughlinlab.ca/lab/), University of Saskatchewan
[National Wildlife Refuge System, Southwest Region](https://www.fws.gov/about/region/southwest), U.S. Fish & Wildlife Service
[Northern Great Plains Program](https://nationalzoo.si.edu/news/restoring-americas-prairie), Smithsonian
[Quantitative Ecology Lab](https://depts.washington.edu/sefsqel/), University of Washington
[Santa Monica Mountains Recreation Area](https://www.nps.gov/samo/index.htm), National Park Service
[Seattle Urban Carnivore Project](https://www.zoo.org/seattlecarnivores), Woodland Park Zoo
[Serra dos Órgãos National Park](https://www.icmbio.gov.br/parnaserradosorgaos/), ICMBio
[Snapshot USA](https://emammal.si.edu/snapshot-usa), Smithsonian
[Wildlife Coexistence Lab](https://wildlife.forestry.ubc.ca/), University of British Columbia
[Wildlife Research](https://www.dfw.state.or.us/wildlife/research/index.asp), Oregon Department of Fish and Wildlife
[Wildlife Division](https://www.michigan.gov/dnr/about/contact/wildlife), Michigan Department of Natural Resources
Department of Ecology, TU Berlin
Ghost Cat Analytics
Protected Areas Unit, Canadian Wildlife Service
[School of Natural Sciences](https://www.utas.edu.au/natural-sciences), University of Tasmania [(story)](https://www.utas.edu.au/about/news-and-stories/articles/2022/1204-innovative-camera-network-keeps-close-eye-on-tassie-wildlife)
[Kenai National Wildlife Refuge](https://www.fws.gov/refuge/kenai), U.S. Fish & Wildlife Service [(story)](https://www.peninsulaclarion.com/sports/refuge-notebook-new-technology-increases-efficiency-of-refuge-cameras/)
[Australian Wildlife Conservancy](https://www.australianwildlife.org/) [(blog](https://www.australianwildlife.org/cutting-edge-technology-delivering-efficiency-gains-in-conservation/), [blog)](https://www.australianwildlife.org/efficiency-gains-at-the-cutting-edge-of-technology/)
[Felidae Conservation Fund](https://felidaefund.org/) [(WildePod platform)](https://wildepod.org/) [(blog post)](https://abhaykashyap.com/blog/ai-powered-camera-trap-image-annotation-system/)
[Alberta Biodiversity Monitoring Institute (ABMI)](https://www.abmi.ca/home.html) [(WildTrax platform)](https://www.wildtrax.ca/) [(blog post)](https://wildcams.ca/blog/the-abmi-visits-the-zoo/)
[Shan Shui Conservation Center](http://en.shanshui.org/) [(blog post)](https://mp.weixin.qq.com/s/iOIQF3ckj0-rEG4yJgerYw?fbclid=IwAR0alwiWbe3udIcFvqqwm7y5qgr9hZpjr871FZIa-ErGUukZ7yJ3ZhgCevs) [(translated blog post)](https://mp-weixin-qq-com.translate.goog/s/iOIQF3ckj0-rEG4yJgerYw?fbclid=IwAR0alwiWbe3udIcFvqqwm7y5qgr9hZpjr871FZIa-ErGUukZ7yJ3ZhgCevs&_x_tr_sl=auto&_x_tr_tl=en&_x_tr_hl=en&_x_tr_pto=wapp)
[Irvine Ranch Conservancy](http://www.irconservancy.org/) [(story)](https://www.ocregister.com/2022/03/30/ai-software-is-helping-researchers-focus-on-learning-about-ocs-wild-animals/)
[Wildlife Protection Solutions](https://wildlifeprotectionsolutions.org/) [(story](https://customers.microsoft.com/en-us/story/1384184517929343083-wildlife-protection-solutions-nonprofit-ai-for-earth), [story)](https://www.enterpriseai.news/2023/02/20/ai-helps-wildlife-protection-solutions-safeguard-endangered-species/)
[Road Ecology Center](https://roadecology.ucdavis.edu/), University of California, Davis [(Wildlife Observer Network platform)](https://wildlifeobserver.net/)
[The Nature Conservancy in California](https://www.nature.org/en-us/about-us/where-we-work/united-states/california/) [(Animl platform)](https://github.com/tnc-ca-geo/animl-frontend)
[San Diego Zoo Wildlife Alliance](https://science.sandiegozoo.org/) [(Animl R package)](https://github.com/conservationtechlab/animl)
</details><br>
>[!IMPORTANT]
>If you would like to be added to this list or have any questions regarding MegaDetector and Pytorch-Wildlife, please [email us](zhongqimiao@microsoft.com) or join us in our Discord channel: [](https://discord.gg/TeEVxzaYtm) |
package com.SWP391_G5_EventFlowerExchange.LoginAPI.service;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.dto.request.AuthenticationRequest;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.dto.request.GoogleLoginRequest;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.dto.response.AuthenticationResponse;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.dto.request.IntrospectRequest;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.dto.response.GoogleLoginResponse;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.dto.response.IntrospectResponse;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.entity.User;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.enums.Role;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.exception.AppException;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.exception.ErrorCode;
import com.SWP391_G5_EventFlowerExchange.LoginAPI.repository.IUserRepository;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import java.text.ParseException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.StringJoiner;
@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@CrossOrigin("http://localhost:3000")
public class AuthenticationService {
static final Logger log = LoggerFactory.getLogger(AuthenticationService.class);
final GoogleIdTokenVerifier verifier; // Ensure you initialize this verifier properly
final IUserRepository IUserRepository;
private final PasswordEncoder passwordEncoder;
@NonFinal
@Value("${jwt.signerKey}")
protected String SIGNER_KEY;
public IntrospectResponse introspect(IntrospectRequest request) throws JOSEException, ParseException {
var token= request.getToken();
JWSVerifier verifier =new MACVerifier(SIGNER_KEY.getBytes());
SignedJWT signedJWT= SignedJWT.parse(token);
Date expityTime= signedJWT.getJWTClaimsSet().getExpirationTime();
var verified = signedJWT.verify(verifier);
return IntrospectResponse.builder()
.valid(verified && expityTime.after(new Date()))
.build();
}
public AuthenticationResponse authenticate(AuthenticationRequest request) {
var user= IUserRepository.findByEmail(request.getEmail())
.orElseThrow(()-> new AppException(ErrorCode.USER_NOT_EXISTED));
//kiểm tra trang thái user có xác thực email chưa
if(!user.isEmailVerified()){
throw new AppException(ErrorCode.USER_NOT_VERIFIED);
}
// Kiểm tra trạng thái của user (chỉ cho phép đăng nhập nếu status là "available")
if (!"available".equals(user.getAvailableStatus())) {
throw new AppException(ErrorCode.USER_NOT_AVAILABLE);
}
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10);
boolean authenticated= passwordEncoder.matches(request.getPassword(), user.getPassword());
if(!authenticated) {
throw new AppException(ErrorCode.UNAUTHENTICATED);
}
var token= generateToken(user);
return AuthenticationResponse.builder()
.token(token)
.authenticated(true)
.build();
}
public GoogleLoginResponse authenticateWithGoogle(GoogleLoginRequest request) {
// Verify the Google ID token
log.info("Starting Google login authentication");
try {
GoogleIdToken idToken = verifier.verify(request.getToken());
if (idToken == null) {
log.warn("ID token verification failed");
throw new AppException(ErrorCode.UNAUTHENTICATED);
}
// Get user information from the token
GoogleIdToken.Payload payload = idToken.getPayload();
String email = payload.getEmail();
// Check if the user already exists
User user = IUserRepository.findByEmail(email).orElseGet(() -> {
// If the user does not exist, create one
User newUser = new User();
newUser.setEmail(email);
newUser.setUsername(payload.get("name").toString()); // Set username or any other necessary fields
newUser.setAvailableStatus("available");// Set initial status
newUser.setPassword(passwordEncoder.encode("12345"));// default password
newUser.setEmailVerified(true); // Consider that Google verifies the email
Set<String> roles = new HashSet<>();
roles.add(Role.BUYER.name());
newUser.setRoles(roles);
// Set other necessary fields if needed
return IUserRepository.save(newUser);
});
// Check if user is email verified (if applicable)
if (!user.isEmailVerified()) {
throw new AppException(ErrorCode.USER_NOT_VERIFIED);
}
// Check user availability status
if (!"available".equals(user.getAvailableStatus())) {
throw new AppException(ErrorCode.USER_NOT_AVAILABLE);
}
// Generate a JWT token for the user
var token = generateToken(user);
return GoogleLoginResponse.builder()
.token(token)
.authenticated(true)
.build();
} catch (Exception e) {
log.error("Error during Google login authentication", e);
throw new AppException(ErrorCode.UNAUTHENTICATED);
}
}
private String generateToken(User user) {
JWSHeader header = new JWSHeader(JWSAlgorithm.HS512);
JWTClaimsSet jwtClaimSet= new JWTClaimsSet.Builder()
.subject(user.getEmail())
.issuer("EventFlowerExchange")
.issueTime(new Date())
.expirationTime(new Date(
Instant.now().plus(1, ChronoUnit.HOURS).toEpochMilli()
))
.claim("userID", user.getUserID())
.claim("username", user.getUsername())
.claim("email", user.getEmail())
.claim("address", user.getAddress())
.claim("phoneNumber", user.getPhoneNumber())
.claim("roles", user.getRoles())
.claim("scope", buildScope(user))
.build();
Payload payload= new Payload(jwtClaimSet.toJSONObject());
JWSObject jwsObject = new JWSObject(header, payload);
try {
jwsObject.sign(new MACSigner(SIGNER_KEY.getBytes()));
return jwsObject.serialize();
} catch (JOSEException e) {
log.error("Cannot create token", e);
throw new RuntimeException(e);
}
}
private String buildScope(User user) {
StringJoiner stringJoiner= new StringJoiner(" ");
if(!CollectionUtils.isEmpty(user.getRoles())) {
user.getRoles().forEach(stringJoiner::add);
}
return stringJoiner.toString();
}
} |
import {
Column,
CreateDateColumn,
Entity,
OneToMany,
OneToOne,
PrimaryGeneratedColumn,
UpdateDateColumn
} from 'typeorm';
import { ObjectType } from '@nestjs/graphql';
import { PopulateRelation, ResourceEntity } from 'ivy-nestjs/resource';
import { Project } from '@resources/projects/entity';
import { Feature } from '@resources/features/entity';
import { FileColumn } from 'ivy-nestjs';
import { File } from 'ivy-nestjs/storage/entity';
@ObjectType()
@Entity()
export class Plan extends ResourceEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(() => Project, (project) => project.plan)
project?: Project;
@PopulateRelation()
@OneToMany(() => Feature, (feature) => feature.plan, {
cascade: true
})
features?: Feature[];
@FileColumn({ maxSize: 3145728, maxCount: 5, isArray: true })
files?: File[];
@CreateDateColumn()
createdAt?: Date;
@UpdateDateColumn()
updatedAt?: Date;
} |
<h1 align="center">
<!-- <a href="https://github.com/mddunlap924/VHSpy">
<img src="https://raw.githubusercontent.com/mddunlap924/PyVHS/main/doc/imgs/pyvhs.png" width="512" height="256" alt="pyvhs">
</a> -->
Information Retrieval and RAG
</h1>
<p align="center">Richer details and references for NLP-based Information Retrieval and RAG systems.
</p>
<p align="center">
<a href="#prompt-engineering">Prompt Engineering</a> •
<a href="#background">Background</a> •
<a href="#benefits">Benefits</a> •
<a href="#prompt-templates">Prompt Templates</a> •
<a href="#example-notebooks">Example Notebooks</a> •
<a href="#issues">Issues</a> •
<a href="#todos">TODOs</a>
</p>
# Prompt Engineering
- [Prompt Engineering Guide](https://promptingguide.ai/)
- [Generating Synthetic Dataset for RAG](https://www.promptingguide.ai/applications/synthetic_rag)
```
Task: Identify a counter-argument for the given argument.
Argument #1: {insert passage X1 here}
A concise counter-argument query related to the argument #1: {insert manually prepared query Y1 here}
Argument #2: {insert passage X2 here}
A concise counter-argument query related to the argument #2: {insert manually prepared query Y2 here}
<- paste your examples here ->
Argument N: Even if a fine is made proportional to income, you will not get the equality of impact you desire. This is because the impact is not proportional simply to income, but must take into account a number of other factors. For example, someone supporting a family will face a greater impact than someone who is not, because they have a smaller disposable income. Further, a fine based on income ignores overall wealth (i.e. how much money someone actually has: someone might have a lot of assets but not have a high income). The proposition does not cater for these inequalities, which may well have a much greater skewing effect, and therefore the argument is being applied inconsistently.
A concise counter-argument query related to the argument #N:
```
- [Improving Search Ranking with Few-Shot Prompting of LLMs](https://blog.vespa.ai/improving-text-ranking-with-few-shot-prompting/)
```
These are examples of queries with sample relevant documents for
each query. The query must be specific and detailed.
Example 1:
document: $document_example_1
query: $query_example_1
Example 2:
document: #document_example_2
query: $query_example_2
Example 3:
document: $document_example_3
query: $query_example
Example 4:
document: $input_document
query:
```
- [LangChain MultiQueryRetiever](https://python.langchain.com/docs/modules/data_connection/retrievers/MultiQueryRetriever)
```The MultiQueryRetriever automates the process of prompt tuning by using an LLM to generate multiple queries from different perspectives for a given user input query. For each query, it retrieves a set of relevant documents and takes the unique union across all queries to get a larger set of potentially relevant documents. By generating multiple perspectives on the same question, the MultiQueryRetriever might be able to overcome some of the limitations of the distance-based retrieval and get a richer set of results.```
# Consistency Filtering / Query Consistency
- [InPars-v2: Large Language Models as Efficient
Dataset Generators for Information Retrieval](https://arxiv.org/pdf/2301.01820.pdf): refer to Section 2 and the second paragraph.
```Once the synthetic queries are generated, we apply a filtering step to select query-document pairs that are more likely to be relevant to each other. In InPars-v1, this filtering step consisted of selecting the top 10k query-document pairs with the highest log probabilities of generating a query given the 3-shot examples and the document as input. In InPars-v2, we use monoT5-3B [4] already fine tuned on MS MARCO for one epoch1 to estimate a relevancy score for each of the 100k query-document pairs. Then, we keep only the top 10k pairs with the highest scores as our positive query-document pairs for training.```
- Vespa AI
- [Improving Zero-Shot Ranking with Vespa Hybrid Search](https://blog.vespa.ai/improving-zero-shot-ranking-with-vespa/#next-blog-post-in-this-series)
- [Improving Zero-Shot Ranking with Vespa Hybrid Search - part two](https://blog.vespa.ai/improving-zero-shot-ranking-with-vespa-part-two/)
- [Improving Search Ranking with Few-Shot Prompting of LLMs](https://blog.vespa.ai/improving-text-ranking-with-few-shot-prompting/)
```LLMs will hallucinate and sometimes produce fake queries that are too generic or irrelevant. To overcome this, researchers 1 2 3 4 use a ranking model (RM) to test the query quality. One can, for example, rank documents from the corpus for each generated synthetic query using the RM. The synthetic query is only retained for model training if the source document ranks highly. This query consistency check grounds the LLM output and improves the training data. Once the synthetic queries and positive (relevant) document pairs are filtered, one can sample negative (potentially irrelevant) examples and train a ranking model adapted to the domain, the characteristics of the document corpus, and the few-show query examples. We use a robust zero-shot hybrid ranking model for query consistency checking. The generated query is retained for training only if the source document is ranked #1 by the zero-shot model.```
- [Promptagator: Few-shot Dense Retrieval From 8 Examples](https://arxiv.org/pdf/2209.11755v1.pdf) Refer to Section 3.2 describing a retriever model to keep relevant passages...
```The filtering step improves the quality of generated queries by ensuring the round-trip consistency (Alberti et al., 2019): a query should be answered by the passage from which the query was generated. In our retrieval case, the query should retrieve its source passage. Consistency filtering (Alberti et al., 2019; Lewis et al., 2021) has been shown crucial for synthetic question generation on QA tasks.```
# Blogs
- [Zero and Few Shot Text Retrieval and Ranking Using Large Language Models](https://blog.reachsumit.com/posts/2023/03/llm-for-text-ranking/)
- [The ABCs of semantic search in OpenSearch: Architectures, benchmarks, and combination strategies](https://opensearch.org/blog/semantic-science-benchmarks/)
# Tutorials
- [PineCone: Unsupervised Training of Retrievers Using GenQ](https://www.pinecone.io/learn/series/nlp/genq/): This approach to building bi-encoder retrievers uses the latest text generation techniques to synthetically generate training data. In short, all we need are passages of text. The generation model then augments these passages with synthetic queries, giving us the exact format we need to train an effective bi-encoder model.
# GitHub
- [Inquisitive Parrots for Search: InPARs](https://github.com/zetaalphavector/InPars): A toolkit for end-to-end synthetic data generation using LLMs for IR
- [ir_datasets](https://github.com/allenai/ir_datasets): s a python package that provides a common interface to many IR ad-hoc ranking benchmarks, training datasets, etc.
- [BEIR Benchmarking IR](https://github.com/beir-cellar/beir): a heterogeneous benchmark containing diverse IR tasks. It also provides a common and easy framework for evaluation of your NLP-based retrieval models within the benchmark.
- [GitHub: Semantic Retrieval Models](https://github.com/caiyinqiong/Semantic-Retrieval-Models): A curated list of awesome papers for Semantic Retrieval, including some early methods and recent neural models for information retrieval tasks (e.g., ad-hoc retrieval, open-domain QA, community-based QA, and automatic conversation).
# Papers
- [Can Generative LLMs Create Query Variants for Test Collections?](https://www.microsoft.com/en-us/research/uploads/prod/2023/05/srp0313-alaofi.pdf)
- [BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models](https://arxiv.org/pdf/2104.08663.pdf)
- [Questions Are All You Need to Train a Dense Passage Retriever ](https://direct.mit.edu/tacl/article/doi/10.1162/tacl_a_00564/116466/Questions-Are-All-You-Need-to-Train-a-Dense) |
<script lang="ts">
import { onMount } from "svelte";
export let variant:
| "primary"
| "secondary"
| "warning"
| "danger"
| "transparent" = "primary";
export let fontSize: "regular" | "large" = "regular";
export let handleClick: svelte.JSX.MouseEventHandler<
HTMLButtonElement
> = () => {};
</script>
<button
class={`${variant} ${fontSize === "large" ? "text-large" : "text-regular"}`}
on:click|preventDefault={handleClick}
>
<slot />
</button>
<style>
button {
color: var(--pal-text-light);
border-radius: var(--spacing-small);
padding: var(--spacing);
text-align: center;
}
.text-large {
font-size: 1.25rem;
}
.text-regular {
font-size: 1rem;
}
.primary {
background-color: var(--pal-primary);
}
.secondary {
background-color: var(--pal-secondary);
}
.warning {
background-color: var(--pal-warning);
color: var(--pal-text);
}
.danger {
background-color: var(--pal-error);
}
.transparent {
background-color: #ffffffff;
color: var(--pal-text);
}
.transparent:hover {
background-color: #efefef;
}
</style> |
import mongoose from "mongoose";
const placeschema = new mongoose.Schema(
{
placeName: {
type: String,
required: true,
},
placeLocation: {
type: String,
required: true,
},
host: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
image: [
{
type: String,
required: true,
},
],
availablity: {
type: String,
enum: ["available", "booked", "unavailable"],
default: "available",
},
isPopular: {
type: Boolean,
default: false,
},
price: {
type: Number,
required: true,
},
description: {
type: String,
required: true,
},
benefits: {
type: String,
// required: true,
},
amenities: {
type: String,
required: true,
},
rules: {
type: String,
required: true,
},
reviews: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "review",
},
],
},
{
timestamps: true,
}
);
export default mongoose.model("Place", placeschema); |
import React, { useEffect } from 'react'
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from 'react-hook-form';
import useFetch from '@/hooks/use-fetch';
import { addNewCompany } from '@/api/apiCompanies';
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTitle, DrawerTrigger } from './ui/drawer';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { BarLoader } from 'react-spinners';
const schema = z.object({
name: z.string().min(1, { message: "Company name is required" }),
logo: z
.any()
.refine(
(file) =>
file[0] &&
(file[0].type === "image/png" || file[0].type === "image/jpeg"),
{
message: "Only Images are allowed",
}
),
});
function AddCompanyDrawer({ fetchCompanies }) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
});
const {
loading: loadingAddCompany,
error: errorAddCompany,
data: dataAddCompany,
fn: fnAddCompany,
} = useFetch(addNewCompany);
const onSubmit = async (data) => {
fnAddCompany({
...data,
logo: data.logo[0],
});
};
useEffect(() => {
if (dataAddCompany?.length > 0) {
fetchCompanies();
}
}, [loadingAddCompany]);
return (
<Drawer>
<DrawerTrigger>
<Button type="button" size="sm" variant="secondary">
Add Company
</Button>
</DrawerTrigger>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>Add a New Company</DrawerTitle>
</DrawerHeader>
<form className="flex gap-2 p-4 pb-0">
{/* Company Name */}
<Input placeholder="Company name" {...register("name")} />
{/* Company Logo */}
<Input
type="file"
accept="image/*"
className=" file:text-gray-500"
{...register("logo")}
/>
{/* Add Button */}
<Button
type="button"
onClick={handleSubmit(onSubmit)}
variant="destructive"
className="w-40"
>
Add
</Button>
</form>
<DrawerFooter>
{errors.name && <p className="text-red-500">{errors.name.message}</p>}
{errors.logo && <p className="text-red-500">{errors.logo.message}</p>}
{errorAddCompany?.message && (
<p className="text-red-500">{errorAddCompany?.message}</p>
)}
{loadingAddCompany && <BarLoader width={"100%"} color="#36d7b7" />}
<DrawerClose asChild>
<Button type="button" variant="secondary">
Cancel
</Button>
</DrawerClose>
</DrawerFooter>
</DrawerContent>
</Drawer>
);
}
export default AddCompanyDrawer |
#
# (C) Tenable Network Security, Inc.
#
# The descriptive text and package checks in this plugin were
# extracted from SUSE update advisory SUSE-SU-2018:1936-1.
# The text itself is copyright (C) SUSE.
#
include("compat.inc");
if (description)
{
script_id(120041);
script_version("1.3");
script_set_attribute(attribute:"plugin_modification_date", value:"2020/03/20");
script_cve_id("CVE-2018-12882");
script_name(english:"SUSE SLES15 Security Update : php7 (SUSE-SU-2018:1936-1)");
script_summary(english:"Checks rpm output for the updated packages.");
script_set_attribute(
attribute:"synopsis",
value:"The remote SUSE host is missing one or more security updates."
);
script_set_attribute(
attribute:"description",
value:
"This update for php7 fixes the following issues :
- CVE-2018-12882: exif_read_from_impl allowed attackers to
trigger a use-after-free (in exif_read_from_file)
because it closed a stream that it is not responsible
for closing (bsc#1099098).
Note that Tenable Network Security has extracted the preceding
description block directly from the SUSE security advisory. Tenable
has attempted to automatically clean and format it as much as possible
without introducing additional issues."
);
script_set_attribute(
attribute:"see_also",
value:"https://bugzilla.suse.com/show_bug.cgi?id=1099098"
);
script_set_attribute(
attribute:"see_also",
value:"https://www.suse.com/security/cve/CVE-2018-12882/"
);
# https://www.suse.com/support/update/announcement/2018/suse-su-20181936-1/
script_set_attribute(
attribute:"see_also",
value:"http://www.nessus.org/u?422fab0d"
);
script_set_attribute(
attribute:"solution",
value:
"To install this SUSE Security Update use the SUSE recommended
installation methods like YaST online_update or 'zypper patch'.
Alternatively you can run the command listed for your product :
SUSE Linux Enterprise Module for Web Scripting 15:zypper in -t patch
SUSE-SLE-Module-Web-Scripting-15-2018-1317=1"
);
script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:P/I:P/A:P");
script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C");
script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H");
script_set_cvss3_temporal_vector("CVSS:3.0/E:U/RL:O/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:apache2-mod_php7");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:apache2-mod_php7-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-bcmath");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-bcmath-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-bz2");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-bz2-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-calendar");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-calendar-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-ctype");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-ctype-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-curl");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-curl-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-dba");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-dba-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-debugsource");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-devel");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-dom");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-dom-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-enchant");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-enchant-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-exif");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-exif-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-fastcgi");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-fastcgi-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-fileinfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-fileinfo-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-fpm");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-fpm-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-ftp");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-ftp-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-gd");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-gd-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-gettext");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-gettext-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-gmp");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-gmp-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-iconv");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-iconv-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-intl");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-intl-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-json");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-json-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-ldap");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-ldap-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-mbstring");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-mbstring-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-mysql");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-mysql-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-odbc");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-odbc-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-opcache");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-opcache-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-openssl");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-openssl-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-pcntl");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-pcntl-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-pdo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-pdo-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-pgsql");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-pgsql-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-phar");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-phar-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-posix");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-posix-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-shmop");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-shmop-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-snmp");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-snmp-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-soap");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-soap-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sockets");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sockets-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sqlite");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sqlite-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sysvmsg");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sysvmsg-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sysvsem");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sysvsem-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sysvshm");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-sysvshm-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-tokenizer");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-tokenizer-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-wddx");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-wddx-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xmlreader");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xmlreader-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xmlrpc");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xmlrpc-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xmlwriter");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xmlwriter-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xsl");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-xsl-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-zip");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-zip-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-zlib");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:suse_linux:php7-zlib-debuginfo");
script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:suse_linux:15");
script_set_attribute(attribute:"vuln_publication_date", value:"2018/06/26");
script_set_attribute(attribute:"patch_publication_date", value:"2018/07/12");
script_set_attribute(attribute:"plugin_publication_date", value:"2019/01/02");
script_set_attribute(attribute:"generated_plugin", value:"current");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2019-2020 and is owned by Tenable, Inc. or an Affiliate thereof.");
script_family(english:"SuSE Local Security Checks");
script_dependencies("ssh_get_info.nasl");
script_require_keys("Host/local_checks_enabled", "Host/cpu", "Host/SuSE/release", "Host/SuSE/rpm-list");
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("rpm.inc");
if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED);
release = get_kb_item("Host/SuSE/release");
if (isnull(release) || release !~ "^(SLED|SLES)") audit(AUDIT_OS_NOT, "SUSE");
os_ver = pregmatch(pattern: "^(SLE(S|D)\d+)", string:release);
if (isnull(os_ver)) audit(AUDIT_UNKNOWN_APP_VER, "SUSE");
os_ver = os_ver[1];
if (! preg(pattern:"^(SLES15)$", string:os_ver)) audit(AUDIT_OS_NOT, "SUSE SLES15", "SUSE " + os_ver);
if (!get_kb_item("Host/SuSE/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING);
cpu = get_kb_item("Host/cpu");
if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH);
if (cpu !~ "^i[3-6]86$" && "x86_64" >!< cpu && "s390x" >!< cpu) audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "SUSE " + os_ver, cpu);
if (cpu >!< "s390x") audit(AUDIT_ARCH_NOT, "s390x", cpu);
sp = get_kb_item("Host/SuSE/patchlevel");
if (isnull(sp)) sp = "0";
if (os_ver == "SLES15" && (! preg(pattern:"^(0)$", string:sp))) audit(AUDIT_OS_NOT, "SLES15 SP0", os_ver + " SP" + sp);
flag = 0;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"apache2-mod_php7-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"apache2-mod_php7-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-bcmath-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-bcmath-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-bz2-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-bz2-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-calendar-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-calendar-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-ctype-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-ctype-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-curl-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-curl-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-dba-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-dba-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-debugsource-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-devel-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-dom-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-dom-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-enchant-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-enchant-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-exif-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-exif-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-fastcgi-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-fastcgi-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-fileinfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-fileinfo-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-fpm-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-fpm-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-ftp-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-ftp-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-gd-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-gd-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-gettext-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-gettext-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-gmp-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-gmp-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-iconv-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-iconv-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-intl-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-intl-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-json-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-json-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-ldap-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-ldap-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-mbstring-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-mbstring-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-mysql-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-mysql-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-odbc-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-odbc-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-opcache-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-opcache-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-openssl-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-openssl-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-pcntl-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-pcntl-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-pdo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-pdo-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-pgsql-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-pgsql-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-phar-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-phar-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-posix-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-posix-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-shmop-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-shmop-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-snmp-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-snmp-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-soap-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-soap-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sockets-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sockets-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sqlite-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sqlite-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sysvmsg-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sysvmsg-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sysvsem-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sysvsem-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sysvshm-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-sysvshm-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-tokenizer-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-tokenizer-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-wddx-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-wddx-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xmlreader-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xmlreader-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xmlrpc-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xmlrpc-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xmlwriter-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xmlwriter-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xsl-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-xsl-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-zip-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-zip-debuginfo-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-zlib-7.2.5-4.3.1")) flag++;
if (rpm_check(release:"SLES15", sp:"0", cpu:"s390x", reference:"php7-zlib-debuginfo-7.2.5-4.3.1")) flag++;
if (flag)
{
if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get());
else security_hole(0);
exit(0);
}
else
{
tested = pkg_tests_get();
if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested);
else audit(AUDIT_PACKAGE_NOT_INSTALLED, "php7");
} |
"""Utilities for downloading and initializing model weights."""
import fnmatch
import glob
import hashlib
import json
import os
import tempfile
from collections import defaultdict
from typing import (Any, Callable, Dict, Generator, Iterable, List, Optional,
Tuple, Union)
import filelock
import gguf
import huggingface_hub.constants
import numpy as np
import torch
from huggingface_hub import HfFileSystem, hf_hub_download, snapshot_download
from safetensors.torch import load_file, safe_open, save_file
from tqdm.auto import tqdm
from vllm.config import LoadConfig, ModelConfig
from vllm.distributed import get_tensor_model_parallel_rank
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization import (QuantizationConfig,
get_quantization_config)
from vllm.model_executor.layers.quantization.schema import QuantParamSchema
from vllm.platforms import current_platform
from vllm.utils import print_warning_once
logger = init_logger(__name__)
# use system-level temp directory for file locks, so that multiple users
# can share the same lock without error.
# lock files in the temp directory will be automatically deleted when the
# system reboots, so users will not complain about annoying lock files
temp_dir = tempfile.gettempdir()
def enable_hf_transfer():
"""automatically activates hf_transfer
"""
if "HF_HUB_ENABLE_HF_TRANSFER" not in os.environ:
try:
# enable hf hub transfer if available
import hf_transfer # type: ignore # noqa
huggingface_hub.constants.HF_HUB_ENABLE_HF_TRANSFER = True
except ImportError:
pass
enable_hf_transfer()
class DisabledTqdm(tqdm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, disable=True)
def get_lock(model_name_or_path: str, cache_dir: Optional[str] = None):
lock_dir = cache_dir or temp_dir
os.makedirs(os.path.dirname(lock_dir), exist_ok=True)
model_name = model_name_or_path.replace("/", "-")
hash_name = hashlib.sha256(model_name.encode()).hexdigest()
# add hash to avoid conflict with old users' lock files
lock_file_name = hash_name + model_name + ".lock"
# mode 0o666 is required for the filelock to be shared across users
lock = filelock.FileLock(os.path.join(lock_dir, lock_file_name),
mode=0o666)
return lock
def _shared_pointers(tensors):
ptrs = defaultdict(list)
for k, v in tensors.items():
ptrs[v.data_ptr()].append(k)
failing = []
for _, names in ptrs.items():
if len(names) > 1:
failing.append(names)
return failing
def convert_bin_to_safetensor_file(
pt_filename: str,
sf_filename: str,
) -> None:
loaded = torch.load(pt_filename, map_location="cpu")
if "state_dict" in loaded:
loaded = loaded["state_dict"]
shared = _shared_pointers(loaded)
for shared_weights in shared:
for name in shared_weights[1:]:
loaded.pop(name)
# For tensors to be contiguous
loaded = {k: v.contiguous() for k, v in loaded.items()}
dirname = os.path.dirname(sf_filename)
os.makedirs(dirname, exist_ok=True)
save_file(loaded, sf_filename, metadata={"format": "pt"})
# check file size
sf_size = os.stat(sf_filename).st_size
pt_size = os.stat(pt_filename).st_size
if (sf_size - pt_size) / pt_size > 0.01:
raise RuntimeError(f"""The file size different is more than 1%:
- {sf_filename}: {sf_size}
- {pt_filename}: {pt_size}
""")
# check if the tensors are the same
reloaded = load_file(sf_filename)
for k in loaded:
pt_tensor = loaded[k]
sf_tensor = reloaded[k]
if not torch.equal(pt_tensor, sf_tensor):
raise RuntimeError(f"The output tensors do not match for key {k}")
# TODO(woosuk): Move this to other place.
def get_quant_config(model_config: ModelConfig,
load_config: LoadConfig) -> QuantizationConfig:
quant_cls = get_quantization_config(model_config.quantization)
# GGUF doesn't have config file
if model_config.quantization == "gguf":
return quant_cls.from_config({})
# Read the quantization config from the HF model config, if available.
hf_quant_config = getattr(model_config.hf_config, "quantization_config",
None)
# some vision model may keep quantization_config in their text_config
hf_text_config = getattr(model_config.hf_config, "text_config", None)
if hf_quant_config is None and hf_text_config is not None:
hf_quant_config = getattr(hf_text_config, "quantization_config", None)
if hf_quant_config is None:
# compressed-tensors uses a compressions_config
hf_quant_config = getattr(model_config.hf_config, "compression_config",
None)
if hf_quant_config is not None:
return quant_cls.from_config(hf_quant_config)
# In case of bitsandbytes/QLoRA, get quant config from the adapter model.
if model_config.quantization == "bitsandbytes":
if (not load_config.model_loader_extra_config
or "qlora_adapter_name_or_path"
not in load_config.model_loader_extra_config):
return quant_cls.from_config({"adapter_name_or_path": ""})
model_name_or_path = load_config.model_loader_extra_config[
"qlora_adapter_name_or_path"]
else:
model_name_or_path = model_config.model
is_local = os.path.isdir(model_name_or_path)
if not is_local:
# Download the config files.
with get_lock(model_name_or_path, load_config.download_dir):
hf_folder = snapshot_download(
model_name_or_path,
revision=model_config.revision,
allow_patterns="*.json",
cache_dir=load_config.download_dir,
local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
tqdm_class=DisabledTqdm,
)
else:
hf_folder = model_name_or_path
possible_config_filenames = quant_cls.get_config_filenames()
# If the quantization config is not found, use the default config.
if not possible_config_filenames:
return quant_cls()
config_files = glob.glob(os.path.join(hf_folder, "*.json"))
quant_config_files = [
f for f in config_files if any(
f.endswith(x) for x in possible_config_filenames)
]
if len(quant_config_files) == 0:
raise ValueError(
f"Cannot find the config file for {model_config.quantization}")
if len(quant_config_files) > 1:
raise ValueError(
f"Found multiple config files for {model_config.quantization}: "
f"{quant_config_files}")
quant_config_file = quant_config_files[0]
with open(quant_config_file) as f:
config = json.load(f)
if model_config.quantization == "bitsandbytes":
config["adapter_name_or_path"] = model_name_or_path
elif model_config.quantization == "modelopt":
if config["producer"]["name"] == "modelopt":
return quant_cls.from_config(config)
else:
raise ValueError(
f"Unsupported quantization config"
f" found for {model_config.quantization} in {f}.")
return quant_cls.from_config(config)
def download_weights_from_hf(
model_name_or_path: str,
cache_dir: Optional[str],
allow_patterns: List[str],
revision: Optional[str] = None,
ignore_patterns: Optional[Union[str, List[str]]] = None,
) -> str:
"""Download model weights from Hugging Face Hub.
Args:
model_name_or_path (str): The model name or path.
cache_dir (Optional[str]): The cache directory to store the model
weights. If None, will use HF defaults.
allow_patterns (List[str]): The allowed patterns for the
weight files. Files matched by any of the patterns will be
downloaded.
revision (Optional[str]): The revision of the model.
ignore_patterns (Optional[Union[str, List[str]]]): The patterns to
filter out the weight files. Files matched by any of the patterns
will be ignored.
Returns:
str: The path to the downloaded model weights.
"""
if not huggingface_hub.constants.HF_HUB_OFFLINE:
# Before we download we look at that is available:
fs = HfFileSystem()
file_list = fs.ls(model_name_or_path, detail=False, revision=revision)
# depending on what is available we download different things
for pattern in allow_patterns:
matching = fnmatch.filter(file_list, pattern)
if len(matching) > 0:
allow_patterns = [pattern]
break
logger.info("Using model weights format %s", allow_patterns)
# Use file lock to prevent multiple processes from
# downloading the same model weights at the same time.
with get_lock(model_name_or_path, cache_dir):
hf_folder = snapshot_download(
model_name_or_path,
allow_patterns=allow_patterns,
ignore_patterns=ignore_patterns,
cache_dir=cache_dir,
tqdm_class=DisabledTqdm,
revision=revision,
local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
)
return hf_folder
def download_safetensors_index_file_from_hf(
model_name_or_path: str,
index_file: str,
cache_dir: Optional[str],
revision: Optional[str] = None,
) -> None:
"""Download hf safetensors index file from Hugging Face Hub.
Args:
model_name_or_path (str): The model name or path.
cache_dir (Optional[str]): The cache directory to store the model
weights. If None, will use HF defaults.
revision (Optional[str]): The revision of the model.
"""
# Use file lock to prevent multiple processes from
# downloading the same model weights at the same time.
with get_lock(model_name_or_path, cache_dir):
try:
# Download the safetensors index file.
hf_hub_download(
repo_id=model_name_or_path,
filename=index_file,
cache_dir=cache_dir,
revision=revision,
local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
)
# If file not found on remote or locally, we should not fail since
# only some models will have index_file.
except huggingface_hub.utils.EntryNotFoundError:
logger.info("No %s found in remote.", index_file)
except huggingface_hub.utils.LocalEntryNotFoundError:
logger.info("No %s found in local cache.", index_file)
# For models like Mistral-7B-v0.3, there are both sharded
# safetensors files and a consolidated safetensors file.
# Passing both of these to the weight loader functionality breaks.
# So, we use the index_file to
# look up which safetensors files should be used.
def filter_duplicate_safetensors_files(hf_weights_files: List[str],
hf_folder: str,
index_file: str) -> List[str]:
# model.safetensors.index.json is a mapping from keys in the
# torch state_dict to safetensors file holding that weight.
index_file_name = os.path.join(hf_folder, index_file)
if not os.path.isfile(index_file_name):
return hf_weights_files
# Iterate through the weight_map (weight_name: safetensors files)
# to identify weights that we should use.
with open(index_file_name) as f:
weight_map = json.load(f)["weight_map"]
weight_files_in_index = set()
for weight_name in weight_map:
weight_files_in_index.add(
os.path.join(hf_folder, weight_map[weight_name]))
# Filter out any fields that are not found in the index file.
hf_weights_files = [
f for f in hf_weights_files if f in weight_files_in_index
]
return hf_weights_files
def filter_files_not_needed_for_inference(
hf_weights_files: List[str]) -> List[str]:
"""
Exclude files that are not needed for inference.
See https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
"""
blacklist = [
"training_args.bin",
"optimizer.bin",
"optimizer.pt",
"scheduler.pt",
"scaler.pt",
]
hf_weights_files = [
f for f in hf_weights_files
if not any(f.endswith(x) for x in blacklist)
]
return hf_weights_files
# explicitly use pure text format, with a newline at the end
# this makes it impossible to see the animation in the progress bar
# but will avoid messing up with ray or multiprocessing, which wraps
# each line of output with some prefix.
_BAR_FORMAT = "{desc}: {percentage:3.0f}% Completed | {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]\n" # noqa: E501
def np_cache_weights_iterator(
model_name_or_path: str, cache_dir: Optional[str], hf_folder: str,
hf_weights_files: List[str]
) -> Generator[Tuple[str, torch.Tensor], None, None]:
"""Iterate over the weights in the model np files.
Will dump the model weights to numpy files if they are not already dumped.
"""
enable_tqdm = not torch.distributed.is_initialized(
) or torch.distributed.get_rank() == 0
# Convert the model weights from torch tensors to numpy arrays for
# faster loading.
np_folder = os.path.join(hf_folder, "np")
os.makedirs(np_folder, exist_ok=True)
weight_names_file = os.path.join(np_folder, "weight_names.json")
# Use file lock to prevent multiple processes from
# dumping the same model weights to numpy at the same time.
with get_lock(model_name_or_path, cache_dir):
if not os.path.exists(weight_names_file):
weight_names: List[str] = []
for bin_file in tqdm(
hf_weights_files,
desc="Loading np_cache checkpoint shards",
disable=not enable_tqdm,
bar_format=_BAR_FORMAT,
):
state = torch.load(bin_file, map_location="cpu")
for name, param in state.items():
param_path = os.path.join(np_folder, name)
with open(param_path, "wb") as f:
np.save(f, param.cpu().detach().numpy())
weight_names.append(name)
with open(weight_names_file, "w") as f:
json.dump(weight_names, f)
with open(weight_names_file) as f:
weight_names = json.load(f)
for name in weight_names:
param_path = os.path.join(np_folder, name)
with open(param_path, "rb") as f:
param = np.load(f)
yield name, torch.from_numpy(param)
def safetensors_weights_iterator(
hf_weights_files: List[str]
) -> Generator[Tuple[str, torch.Tensor], None, None]:
"""Iterate over the weights in the model safetensor files."""
enable_tqdm = not torch.distributed.is_initialized(
) or torch.distributed.get_rank() == 0
for st_file in tqdm(
hf_weights_files,
desc="Loading safetensors checkpoint shards",
disable=not enable_tqdm,
bar_format=_BAR_FORMAT,
):
with safe_open(st_file, framework="pt") as f:
for name in f.keys(): # noqa: SIM118
param = f.get_tensor(name)
yield name, param
def pt_weights_iterator(
hf_weights_files: List[str]
) -> Generator[Tuple[str, torch.Tensor], None, None]:
"""Iterate over the weights in the model bin/pt files."""
enable_tqdm = not torch.distributed.is_initialized(
) or torch.distributed.get_rank() == 0
for bin_file in tqdm(
hf_weights_files,
desc="Loading pt checkpoint shards",
disable=not enable_tqdm,
bar_format=_BAR_FORMAT,
):
state = torch.load(bin_file, map_location="cpu")
yield from state.items()
del state
torch.cuda.empty_cache()
def get_gguf_extra_tensor_names(
gguf_file: str, gguf_to_hf_name_map: Dict[str, str]) -> List[str]:
reader = gguf.GGUFReader(gguf_file)
expected_gguf_keys = set(gguf_to_hf_name_map.keys())
exact_gguf_keys = set([tensor.name for tensor in reader.tensors])
extra_keys = expected_gguf_keys - exact_gguf_keys
return [gguf_to_hf_name_map[key] for key in extra_keys]
def gguf_quant_weights_iterator(
gguf_file: str, gguf_to_hf_name_map: Dict[str, str]
) -> Generator[Tuple[str, torch.Tensor], None, None]:
"""
Iterate over the quant weights in the model gguf files and convert
them to torch tensors
"""
reader = gguf.GGUFReader(gguf_file)
for tensor in reader.tensors:
if tensor.name in gguf_to_hf_name_map:
weight_type = tensor.tensor_type
name = gguf_to_hf_name_map[tensor.name]
if weight_type.name != "F32":
weight_type_name = name.replace("weight", "qweight_type")
weight_type = torch.tensor(weight_type)
yield weight_type_name, weight_type
for tensor in reader.tensors:
if tensor.name in gguf_to_hf_name_map:
weight = tensor.data
weight_type = tensor.tensor_type
name = gguf_to_hf_name_map[tensor.name]
if weight_type.name != "F32":
name = name.replace("weight", "qweight")
param = torch.tensor(weight)
yield name, param
def kv_cache_scales_loader(
filename: str, tp_rank: int, tp_size: int, num_hidden_layers: int,
model_type: Optional[str]) -> Iterable[Tuple[int, float]]:
"""
A simple utility to read in KV cache scaling factors that have been
previously serialized to disk. Used by the model to populate the appropriate
KV cache scaling factors. The serialization should represent a dictionary
whose keys are the TP ranks and values are another dictionary mapping layers
to their KV cache scaling factors.
Keep this function in sync with the output of examples/fp8/extract_scales.py
"""
try:
with open(filename) as f:
context = {
"model_type": model_type,
"num_hidden_layers": num_hidden_layers,
"tp_rank": tp_rank,
"tp_size": tp_size,
}
schema_dct = json.load(f)
schema = QuantParamSchema.model_validate(schema_dct,
context=context)
layer_scales_map = schema.kv_cache.scaling_factor[tp_rank]
return layer_scales_map.items()
except FileNotFoundError:
logger.error("File or directory '%s' not found.", filename)
except json.JSONDecodeError:
logger.error("Error decoding JSON in file '%s'.", filename)
except Exception:
logger.exception("An error occurred while reading '%s'.", filename)
# This section is reached if and only if any of the excepts are hit
# Return an empty iterable (list) => no KV cache scales are loaded
# which ultimately defaults to 1.0 scales
logger.warning(
"Defaulting to KV cache scaling factors = 1.0 for all "
"layers in TP rank %d as an error occurred during loading.", tp_rank)
return []
def convert_pyslice_to_tensor(x: Any) -> torch.Tensor:
"""convert PySafeSlice object from safetensors to torch.Tensor
PySafeSlice object supports indexing, which is done before loading the
actual tensor and can reduce the amount of memory being read into the
memory. However, it does not support more advanced functionalities
like `.view()` or `.t()`. Therefore, if we need to modify the loaded
tensor with these more complicated operators, we need to convert to
tensor first.
"""
if not isinstance(x, torch.Tensor):
x = x[:]
return x
def default_weight_loader(param: torch.Tensor,
loaded_weight: torch.Tensor) -> None:
"""Default weight loader."""
try:
if param.numel() == 1 and loaded_weight.numel() == 1:
# Sometimes scalar values aren't considered tensors with shapes
# so if both param and loaded_weight are a scalar,
# "broadcast" instead of copy
param.data.fill_(loaded_weight.item())
else:
assert param.size() == loaded_weight.size(), (
f"Attempted to load weight ({loaded_weight.size()}) "
f"into parameter ({param.size()})")
param.data.copy_(loaded_weight)
except Exception:
# NOTE: This exception is added for the purpose of setting breakpoint to
# debug weight loading issues.
raise
def row_parallel_weight_loader(param: torch.Tensor,
loaded_weight: torch.Tensor) -> None:
"""Load weights that are row-parallelized."""
tp_rank = get_tensor_model_parallel_rank()
shard_dim = 0 if param.dim() != 1 else None
if shard_dim is not None:
shard_size = param.data.shape[shard_dim]
start_idx = tp_rank * shard_size
loaded_weight = loaded_weight.narrow(shard_dim, start_idx, shard_size)
return default_weight_loader(param, loaded_weight)
LoaderFunction = Callable[[torch.Tensor, torch.Tensor], torch.Tensor]
def sharded_weight_loader(shard_axis: int) -> LoaderFunction:
"""Create a weight loader that shards the weights along the given axis"""
def loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
tp_rank = get_tensor_model_parallel_rank()
shard_size = param.data.shape[shard_axis]
start_idx = tp_rank * shard_size
loaded_weight = loaded_weight.narrow(shard_axis, start_idx, shard_size)
return default_weight_loader(param, loaded_weight)
return loader
def composed_weight_loader(
loader: LoaderFunction, fn: Callable[[torch.Tensor],
torch.Tensor]) -> LoaderFunction:
"""Create a weight loader that post-processes the weights after loading"""
def composed_loader(param: torch.Tensor,
loaded_weight: torch.Tensor) -> None:
loader(param, loaded_weight)
param.data.copy_(fn(param))
return
return composed_loader
def initialize_dummy_weights(
model: torch.nn.Module,
low: float = -1e-3,
high: float = 1e-3,
seed: int = 1234,
) -> None:
"""Initialize model weights with random values.
The model weights must be randomly initialized for accurate performance
measurements. Additionally, the model weights should not cause NaNs in the
forward pass. We empirically found that initializing the weights with
values between -1e-3 and 1e-3 works well for most models.
We use per-parameter random seed, so that dummy weights are consistent,
even if the model is partitioned across multiple devices. When the seed
is fixed, the random values generated by this function only depends on
the parameter's number of elements and its data type.
"""
for param in model.state_dict().values():
if torch.is_floating_point(param):
if current_platform.is_tpu():
# XLA device does not support torch.Generator()
param.uniform_(low, high)
continue
generator = torch.Generator(device=param.data.device)
generator.manual_seed(seed)
if torch.finfo(param.data.dtype).bits < 16:
# uniform_ doesn't support < 16-bit datatypes (FP8)
dtype = param.data.dtype
tmp_param = param.data.to(torch.float16)
tmp_param = tmp_param.uniform_(low, high,
generator=generator).to(dtype)
param.data.copy_(tmp_param)
else:
param.uniform_(low, high, generator=generator)
def maybe_remap_kv_scale_name(name: str, params_dict: dict) -> Optional[str]:
"""Remap the name of FP8 k/v_scale parameters.
This function handles the remapping of FP8 k/v_scale parameter names.
It detects if the given name ends with a suffix and attempts to remap
it to the expected name format in the model. If the remapped name is not
found in the params_dict, a warning is printed and None is returned.
Args:
name (str): The original loaded checkpoint parameter name.
params_dict (dict): Dictionary containing the model's named parameters.
Returns:
str: The remapped parameter name if successful, or the original name
if no remapping is needed.
None: If the remapped name is not found in params_dict.
"""
if name.endswith(".kv_scale"):
print_warning_once(
"DEPRECATED. Found kv_scale in the checkpoint. "
"This format is deprecated in favor of separate k_scale and "
"v_scale tensors and will be removed in a future release. "
"Functionally, we will remap kv_scale to k_scale and duplicate "
"k_scale to v_scale")
# NOTE: we remap the deprecated kv_scale to k_scale
remapped_name = name.replace(".kv_scale", ".attn.k_scale")
if remapped_name not in params_dict:
print_warning_once(
f"Found kv_scale in the checkpoint (e.g. {name}), "
"but not found the expected name in the model "
f"(e.g. {remapped_name}). kv_scale is "
"not loaded.")
return None
return remapped_name
possible_scale_names = [".k_scale", ".v_scale"]
for scale_name in possible_scale_names:
if name.endswith(scale_name):
remapped_name = name.replace(scale_name, f".attn{scale_name}")
if remapped_name not in params_dict:
print_warning_once(
f"Found {scale_name} in the checkpoint (e.g. {name}), "
"but not found the expected name in the model "
f"(e.g. {remapped_name}). {scale_name} is "
"not loaded.")
return None
return remapped_name
# If there were no matches, return the untouched param name
return name |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Belajar Dasar Ajax</title>
</head>
<body>
<h1>Tutorial Ajax <button id="btn-clear" onclick="clearResult()">Clear</button></h1>
<div id="hasil"></div>
<button id="button" onclick="loadContent()">Load Content</button>
<script>
function loadContent(){
var xhr = new XMLHttpRequest();
var url = "http://localhost/Minggu%2013/Praktikum%202/kode2.json";
xhr.onloadstart = function(){
document.getElementById("button").innerHTML = "Loading...";
}
xhr.onerror = function(){
alert("Gagal mengambil data");
};
xhr.onloadend = function(){
if(this.responseText !== ""){
var data = JSON.parse(this.responseText);
var img = document.createElement("img");
img.src = data.avatar_url;
var name = document.createElement("h3");
name.innerHTML = data.name;
document.getElementById("hasil").append(img, name);
document.getElementById("button").innerHTML = "Done";
setTimeout(function (){
document.getElementById("button").innerHTML = "Load Lagi";
}, 3000);
}
};
xhr.open("GET", url, true);
xhr.send();
}
function clearResult(){
document.getElementById("hasil").innerHTML = "";
}
</script>
</body>
</html> |
const express = require('express')
const sqlite3 = require('sqlite3')
const {open} = require('sqlite')
const path = require('path')
const jwt=require('jsonwebtoken');
const bcrypt=require('bcrypt');
const app = express()
const dbFilePath = path.join(__dirname, 'covid19IndiaPortal.db')
const PORT_NU = 3000
let db = null
const MY_SECRET_TOKEN="nextWave-ccbp";
const authenticateToken=async(req, res, next)=>{
let jwtToken;
const authHeader=req.headers['authorization'];
if(authHeader!==undefined){
jwtToken=authHeader.split(" ")[1];
}
if(jwtToken==undefined){
res.status(401);
res.send("Invalid JWT Token");
}else{
jwt.verify(jwtToken, MY_SECRET_TOKEN, async(err, payload)=>{
if(err){
res.status(401);
res.send("Invalid JWT Token");
}else{
next();
}
});
}
};
app.use(express.json())
let initializedDbAndServer = async () => {
try {
db = await open({
filename: dbFilePath,
driver: sqlite3.Database,
})
app.listen(PORT_NU, () => {
console.log(
'Server is running at https://nitishbfiesnjscpaqlbe.drops.nxtwave.tech',
)
})
} catch (e) {
console.log('Db error: ', e.message)
process.exit(1)
}
}
initializedDbAndServer()
app.post("/login", async(req, res)=>{
const {username, password}=req.body;
const selectQuery=`
SELECT * FROM user where username='${username}';`;
const dbUser=await db.get(selectQuery);
if(dbUser===undefined){
res.status(400);
res.send("Invalid user");
}else{
const isPasswordMatched=await bcrypt.compare(password, dbUser.password);
if(isPasswordMatched===true){
let payload={
username:username
}
let jwtToken=jwt.sign(payload, MY_SECRET_TOKEN);
res.send({jwtToken});
}else{
res.status(400);
res.send("Invalid password");
}
}
});
app.get('/states', authenticateToken, async (req, res) => {
let query = `
select state_id as stateId, state_name as stateName, population
from state;`
let states = await db.all(query)
res.send(states)
})
app.get('/states/:stateId', authenticateToken, async (req, res) => {
const {stateId} = req.params
let query = `select state_id as stateId, state_name as stateName, population
from state where state_id=${stateId}`
let state = await db.get(query)
res.send(state)
})
app.get('/districts/:districtId/', authenticateToken, async (req, res) => {
const {districtId} = req.params
let query = `select district_id as districtId,
district_name as districtName, state_id as stateId, cases, cured, active, deaths
from district where district_id=${districtId};`
let state = await db.get(query)
res.send(state)
})
app.post('/districts', authenticateToken, async (req, res) => {
const {districtName, stateId, cases, cured, active, deaths} = req.body
let query = `
insert into district (district_name, state_id, cases, cured, active, deaths)
values("${districtName}", ${stateId}, ${cases}, ${cured}, ${active}, ${deaths});`
await db.run(query)
res.send('District Successfully Added')
})
app.put('/districts/:districtId', authenticateToken, async (req, res) => {
const {districtName, stateId, cases, cured, active, deaths} = req.body
const {districtId} = req.params
let query = `
update district set
district_name="${districtName}",
state_id=${stateId},
cases=${cases}, cured=${cured},
active=${active}, deaths=${deaths}
where district_id=${districtId};`
await db.run(query)
res.send('District Details Updated')
})
app.delete('/districts/:districtId/', authenticateToken, async (req, res) => {
const {districtId} = req.params
let query = `
delete from district
where district_id=${districtId};`
await db.run(query)
res.send('District Removed')
})
app.get('/states/:stateId/stats/', authenticateToken, async (req, res) => {
const {stateId} = req.params
let query = `
select sum(cases) as totalCases, sum(cured) as totalCured,
sum(active) as totalActive, sum(deaths) as totalDeaths
from district where state_id=${stateId};
`
let dbResponse = await db.get(query)
res.send(dbResponse)
})
app.get('/districts/:districtId/details/', authenticateToken, async (req, res) => {
const {districtId} = req.params
// let query = `
// select state_name as stateName
// from district join state on district.state_id = state.state_id
// where district_id=${districtId}
// `
let query = `
select state_name as stateName
from state where
state_id=(select state_id from district where district_id=${districtId});
`
let state = await db.get(query)
res.send(state)
})
module.exports = app |
package Kaviru.MAD.LAB.MyToDoApp.dao
import androidx.room.*
import kotlinx.coroutines.flow.Flow
import Kaviru.MAD.LAB.MyToDoApp.models.Task
@Dao
interface TaskDao {
@Query("""SELECT * FROM Task ORDER BY
CASE WHEN :isAsc = 1 THEN taskTitle END ASC,
CASE WHEN :isAsc = 0 THEN taskTitle END DESC""")
fun getTaskListSortByTaskTitle(isAsc: Boolean) : Flow<List<Task>>
@Query("""SELECT * FROM Task ORDER BY
CASE WHEN :isAsc = 1 THEN date END ASC,
CASE WHEN :isAsc = 0 THEN date END DESC""")
fun getTaskListSortByTaskDate(isAsc: Boolean) : Flow<List<Task>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertTask(task: Task): Long
@Delete
suspend fun deleteTask(task: Task) : Int
@Query("DELETE FROM Task WHERE taskId == :taskId")
suspend fun deleteTaskUsingId(taskId: String) : Int
@Update
suspend fun updateTask(task: Task): Int
@Query("UPDATE Task SET taskTitle=:title, description = :description WHERE taskId = :taskId")
suspend fun updateTaskPaticularField(taskId:String,title:String,description:String): Int
@Query("SELECT * FROM Task WHERE taskTitle LIKE :query ORDER BY date DESC")
fun searchTaskList(query: String) : Flow<List<Task>>
} |
package com.lagousocket.socketdemo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.util.concurrent.Executors.newCachedThreadPool;
/**
* 〈一句话功能简述〉<br>
* 〈socketf服务端代码实现〉
*
* @author 商玉
* @create 2021/12/7
* @since 1.0.0
*/
public class socketTest {
public static void main(String[] args) throws IOException {
//创建一个线程池,如果有客户端连接就创建一个线程,与之通信
ExecutorService executorService = Executors.newCachedThreadPool();
//创建serverSocket对象
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务器已启动");
while (true) {
Socket accept = serverSocket.accept();
System.out.println("有客户端连接");
executorService.execute(new Runnable() {
@Override
public void run() {
handle(accept);
}
});
}
}
private static void handle(Socket accept) {
try {
System.out.println("线程id:" + Thread.currentThread().getId() + " 线程名称:" + Thread.currentThread().getName());
// 从连接中取出输入流来接收消息
InputStream inputStream = accept.getInputStream();
byte[] bytes = new byte[1024];
int read = inputStream.read(bytes);
System.out.println("客户端:" + new String(bytes, 0, read));
// 连接中取出输出流并回话
OutputStream outputStream = accept.getOutputStream();
outputStream.write("没钱".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
"""
Given graphical information, color maps, and a custom imaginary equation
this program generates fractals.
Source: https://www.geeksforgeeks.org/mandelbrot-fractal-set-visualization-in-python/
12/15/24
"""
import numpy as np
import matplotlib.pyplot as plt
# fractal function
def mandelbrot_set(width, height, bound_value, max_iterations, equation):
# sets up graph
real = np.linspace(-2, 2, width)
imag = np.linspace(-2, 2, height)
complex_array = real[np.newaxis, :] + imag[:, np.newaxis] * 1j
iteration_array = np.zeros((height, width), dtype=int)
# implements geeksforgeeks' algorithm but extended to not just basic mandelbrot equation
for i in range(height):
for j in range(width):
c = complex_array[i, j]
z = 0
iteration = 0
while abs(z) < bound_value and iteration < max_iterations:
try:
z = eval(equation)
except Exception as e:
print(f"Error in equation: {e}")
return None
iteration += 1
iteration_array[i, j] = iteration if iteration < max_iterations else 0
return iteration_array
# get user inputs
width = int(input("Enter the width of the image: "))
height = int(input("Enter the height of the image: "))
bound_value = float(input("Enter the boundary value (Ex: 2): "))
max_iterations = int(input("Enter the maximum number of iterations: "))
print("Enter a custom Mandelbrot equation using 'z' and 'c' (Ex: 'z**2 + c'): ")
equation = input("Equation: ")
# color maps
print("\nAvailable color maps options (choose one):")
colormap_options = plt.colormaps()
print(", ".join(colormap_options)) # Print all colormap options
colormap = input("\nColor Maps: ")
# make sure inputs are correct
if 'z' not in equation or 'c' not in equation:
print("Equation must include both 'z' and 'c'.")
elif colormap not in colormap_options:
print("Invalid colormap. Please choose from the list provided.")
# calls function
else:
mandelbrot_image = mandelbrot_set(width, height, bound_value, max_iterations, equation)
if mandelbrot_image is not None:
# display
plt.figure(figsize=(10, 10))
plt.imshow(mandelbrot_image, extent=(-2, 2, -2, 2), cmap=colormap)
plt.colorbar(label='Iteration Count')
plt.title(f'Custom Mandelbrot Set (Equation: {equation}, Bound={bound_value}, Max Iterations={max_iterations})')
plt.xlabel('Real')
plt.ylabel('Imaginary')
plt.show() |
# Copyright 2023 Iguazio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import inspect
import typing
import orjson
import pydantic.v1
import sqlalchemy.orm
import mlrun.common.schemas
import mlrun.errors
import mlrun.utils.singleton
from mlrun import mlconf
from mlrun.utils import logger
import framework.utils.asyncio
import framework.utils.pagination_cache
def _generate_pydantic_schema_from_method_signature(
method: typing.Callable,
) -> pydantic.v1.BaseModel:
"""
Generate a Pydantic model based on the signature of a method.
This is used to save the given parameters to the method in the pagination cache as a serialized Pydantic
model that can then be deserialized to the correct types and passed back to the method when the cache is used.
"""
class Config:
arbitrary_types_allowed = True
parameters = inspect.signature(method).parameters
fields = {
name: (
parameter.annotation,
# if the parameter has a default value, use it, otherwise use ... placeholder
# to indicate that the parameter is required
parameter.default if parameter.default != inspect.Parameter.empty else ...,
)
for name, parameter in parameters.items()
# ignore the session parameter as the methods get a new session each time
if parameter.annotation != sqlalchemy.orm.Session
}
return pydantic.v1.create_model(
f"{method.__name__}_schema", __config__=Config, **fields
)
class PaginatedMethods(metaclass=mlrun.utils.singleton.Singleton):
_methods: list[typing.Callable] = []
_method_map = {}
@classmethod
def add_method(cls, method: typing.Callable):
cls._methods.append(method)
cls._method_map[method.__name__] = {
"method": method,
"schema": _generate_pydantic_schema_from_method_signature(method),
}
@classmethod
def method_is_supported(cls, method: typing.Union[str, typing.Callable]) -> bool:
method_name = method if isinstance(method, str) else method.__name__
return method_name in cls._method_map
@classmethod
def get_method(cls, method_name: str) -> typing.Callable:
return cls._method_map[method_name]["method"]
@classmethod
def get_method_schema(cls, method_name: str) -> pydantic.v1.BaseModel:
return cls._method_map[method_name]["schema"]
class Paginator(metaclass=mlrun.utils.singleton.Singleton):
def __init__(self):
self._logger = logger.get_child("paginator")
self._pagination_cache = framework.utils.pagination_cache.PaginationCache()
async def paginate_permission_filtered_request(
self,
session: sqlalchemy.orm.Session,
method: typing.Callable,
filter_: typing.Callable,
auth_info: typing.Optional[mlrun.common.schemas.AuthInfo] = None,
token: typing.Optional[str] = None,
page: typing.Optional[int] = None,
page_size: typing.Optional[int] = None,
**method_kwargs,
) -> tuple[typing.Any, dict[str, typing.Union[str, int]]]:
"""
Paginate a request and filter the results based on the provided filter function.
If the result of the filter has fewer items than the page size, the pagination will request more items until
the page size is reached.
There is an option here to overflow and to receive more items than the page size.
And actually the maximum number of items that can be returned is page_size * 2 - 1.
"""
last_pagination_info = mlrun.common.schemas.pagination.PaginationInfo()
current_page = page
result = []
while not page_size or len(result) < page_size:
new_result, pagination_info = await self.paginate_request(
session,
method,
auth_info,
token,
current_page,
page_size,
**method_kwargs,
)
new_result = await framework.utils.asyncio.await_or_call_in_threadpool(
filter_, new_result
)
result.extend(new_result)
if not pagination_info:
# no more results
break
last_pagination_info = pagination_info
current_page = last_pagination_info.page + 1
page_size = last_pagination_info.page_size
return result, last_pagination_info.dict(by_alias=True)
async def paginate_request(
self,
session: sqlalchemy.orm.Session,
method: typing.Callable,
auth_info: typing.Optional[mlrun.common.schemas.AuthInfo] = None,
token: typing.Optional[str] = None,
page: typing.Optional[int] = None,
page_size: typing.Optional[int] = None,
**method_kwargs,
) -> tuple[
typing.Any, typing.Optional[mlrun.common.schemas.pagination.PaginationInfo]
]:
if not PaginatedMethods.method_is_supported(method):
raise NotImplementedError(
f"Pagination is not supported for method {method.__name__}"
)
if page_size is None and token is None:
self._logger.debug(
"No token or page size provided, returning all records",
method=method.__name__,
)
return await framework.utils.asyncio.await_or_call_in_threadpool(
method, session, **method_kwargs
), None
if page is not None and page > mlconf.httpdb.pagination.page_limit:
raise mlrun.errors.MLRunInvalidArgumentError(
f"'page' must be less than or equal to {mlconf.httpdb.pagination.page_limit}"
)
if (
page_size is not None
and page_size > mlconf.httpdb.pagination.page_size_limit
):
raise mlrun.errors.MLRunInvalidArgumentError(
f"'page_size' must be less than or equal to {mlconf.httpdb.pagination.page_size_limit}"
)
page_size = page_size or mlconf.httpdb.pagination.default_page_size
(
token,
page,
page_size,
method,
method_kwargs,
) = self._create_or_update_pagination_cache_record(
session,
method,
auth_info,
token,
page,
page_size,
**method_kwargs,
)
self._logger.debug(
"Retrieving page",
page=page,
page_size=page_size,
method=method.__name__,
)
offset, limit = self._calculate_offset_and_limit(page, page_size)
items = await framework.utils.asyncio.await_or_call_in_threadpool(
method, session, **method_kwargs, offset=offset, limit=limit
)
pagination_info = mlrun.common.schemas.pagination.PaginationInfo(
page=page, page_size=page_size, page_token=token
)
# The following 2 conditions indicate the end of the pagination.
# On the last page, we don't return the token, but we keep it live in the cache
# so the client can access previous pages.
# the token will be revoked after some time of none-usage.
if len(items) == 0:
return [], None
if len(items) < page_size + 1:
# If we got fewer items than the page_size + 1, we know that there are no more items
# and this is the last page.
pagination_info.page_token = None
# truncate the items to the page size
items = items[:page_size]
return items, pagination_info
def _create_or_update_pagination_cache_record(
self,
session: sqlalchemy.orm.Session,
method: typing.Callable,
auth_info: typing.Optional[mlrun.common.schemas.AuthInfo] = None,
token: typing.Optional[str] = None,
page: typing.Optional[int] = None,
page_size: typing.Optional[int] = None,
**method_kwargs,
) -> tuple[str, int, int, typing.Callable, dict]:
if token:
self._logger.debug(
"Token provided, updating pagination cache record", token=token
)
pagination_cache_record = (
self._pagination_cache.get_pagination_cache_record(session, key=token)
)
if pagination_cache_record is None:
raise mlrun.errors.MLRunPaginationEndOfResultsError(
f"Token {token} not found in pagination cache"
)
method = PaginatedMethods.get_method(pagination_cache_record.function)
method_kwargs = orjson.loads(pagination_cache_record.kwargs)
page = page or pagination_cache_record.current_page + 1
page_size = pagination_cache_record.page_size
user = pagination_cache_record.user
if user and (not auth_info or auth_info.user_id != user):
raise mlrun.errors.MLRunAccessDeniedError(
"User is not allowed to access this token"
)
# upsert pagination cache record to update last_accessed time or create a new record
method_schema = PaginatedMethods.get_method_schema(method.__name__)
kwargs_schema = method_schema(**method_kwargs)
kwargs_schema.offset = None
kwargs_schema.limit = None
self._logger.debug(
"Storing pagination cache record",
method=method.__name__,
page=page,
page_size=page_size,
)
token = self._pagination_cache.store_pagination_cache_record(
session,
user=auth_info.user_id if auth_info else None,
method=method,
current_page=page,
page_size=page_size,
kwargs=kwargs_schema.json(exclude_none=True),
)
return token, page, page_size, method, kwargs_schema.dict(exclude_none=True)
@staticmethod
def _calculate_offset_and_limit(
page: typing.Optional[int] = None,
page_size: typing.Optional[int] = None,
) -> tuple[typing.Optional[int], typing.Optional[int]]:
if page is not None:
page_size = page_size or mlconf.httpdb.pagination.default_page_size
if page < 1 or page_size < 1:
raise mlrun.errors.MLRunInvalidArgumentError(
"Page and page size must be greater than 0"
)
# returning the limit with 1 extra record to check if there are more records
# and to know if we should return the token or not
return (page - 1) * page_size, page_size + 1
return None, None |
const { test, expect } = require('@playwright/test');
const { LoginPage } = require('../pageObjects/loginPage');
const { ProductsPage } = require('../pageObjects/productsPage');
const { CartPage } = require('../pageObjects/cartPage');
const username = JSON.parse(JSON.stringify(require('../testData/userNames.json')));
const url = JSON.parse(JSON.stringify(require('../testData/url.json')));
let page;
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
page = await context.newPage();
await page.goto(await url[0].baseUrl);
const title = 'Swag Labs';
await expect(page).toHaveTitle(title);
});
//I used Promise blocks to avoid any possible performance source issues.
test('@UI Login, Back To Products and Back Home Button Validation', async () => {
test.slow();
const products = new ProductsPage(page);
const shoppingCart = new CartPage(page);
const login = new LoginPage(page);
await login.username.type(await username.performanceGlitchUser);
await login.lastname.type('secret_sauce');
// When I click to 'LogIn' on login page I am facing with long wait
await Promise.all([
page.waitForLoadState('load'),
login.logInButton.click()
]);
const itemsCount = await products.items.count();
for(let i = 0; i < itemsCount; i++) {
if(await products.items.nth(i).textContent() === "Sauce Labs Fleece Jacket") {
await products.items.nth(i).click();
// When I click to 'back to products' button on any item's page I am facing with long wait, again I am gonna use Promise blocks to avoid any possible failures because of this issue
await Promise.all([
page.waitForLoadState('load'),
await products.backToProductsButton.click()
]);
};
};
expect(await products.productsHeader).toBeVisible();
await products.sauceLabsBackpackAddToCart.click();
await products.shoppingCart.click();
await shoppingCart.checkoutButton.click();
await products.checkoutFirstName.type('Dustin');
await products.checkoutLastName.type('gozel');
await products.checkoutZipCode.type('22003');
await shoppingCart.continueSubmitButton.click();
await shoppingCart.finishButton.click();
expect( await shoppingCart.successMessage).toBeVisible();
// Added promise becuase when I place my order then I click to 'Back Home' there is a huge waiting.
await Promise.all([
page.waitForLoadState('load'),
shoppingCart.backHomeButton.click()
]);
expect(await products.productsHeader).toBeVisible();
}); |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CDP Support Chatbot</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="container">
<h1>CDP Support Chatbot</h1>
<form id="chatbot-form">
<label for="platform">Platform:</label>
<select id="platform" name="platform">
<option value="segment">Segment</option>
<option value="mparticle">mParticle</option>
<option value="lytics">Lytics</option>
<option value="zeotap">Zeotap</option>
</select>
<label for="question">Question:</label>
<input type="text" id="question" name="question" placeholder="Ask your question..." required>
<button type="submit">Ask</button>
</form>
<div id="response"></div>
</div>
<script>
const form = document.getElementById("chatbot-form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
const platform = document.getElementById("platform").value;
const question = document.getElementById("question").value;
const response = await fetch("/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ platform, question })
});
const result = await response.json();
document.getElementById("response").innerText = result.answer || result.error;
});
</script>
</body>
</html> |
import 'dotenv/config';
import app from './app';
import healthCheck from './infrastructure/routes/health';
import { createServer, Server } from 'http';
import sequelize from './infrastructure/database/index';
class Application {
private readonly server: Server;
private readonly port: string | number;
constructor() {
this.server = createServer(app);
this.port = process.env.PORT!;
healthCheck(this.server);
}
private async syncDatabase(): Promise<void> {
try {
await sequelize.sync();
} catch (error) {
process.exit(1);
}
}
public async start(): Promise<void> {
await this.syncDatabase();
this.server.listen(this.port, () => {
console.log(`Server is running on port ${this.port}`);
});
}
}
const application = new Application();
application.start(); |
/*
* Copyright (C) 2017 ss
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require("@angular/core");
var abs_model_1 = require("../../model/abs.model");
var route_module_1 = require("../../route.module");
var TransportProfileList = (function () {
function TransportProfileList(dataService, dialogService, router) {
this.dataService = dataService;
this.dialogService = dialogService;
this.router = router;
}
;
TransportProfileList.prototype.ngOnInit = function () {
this.loadProfiles();
};
TransportProfileList.prototype.loadProfiles = function () {
var _this = this;
this.dataService.getAll(abs_model_1.ModelClass.TRANSPORT_PROFILE)
.then(function (profiles) { return _this.profiles = profiles; });
};
TransportProfileList.prototype.newProfile = function () {
this.router.navigate([route_module_1.Links.PROFILE_FORM]);
};
TransportProfileList.prototype.editProfile = function (id) {
this.router.navigate([route_module_1.Links.PROFILE_FORM, id]);
};
TransportProfileList.prototype.deleteProfile = function (id) {
var _this = this;
console.log('delete profile [' + id + ']');
this.dialogService.confirm('Delete profile', 'Are you sure that you want delete this profile?').subscribe(function (result) {
if (result) {
_this.dataService.deleteById(id, abs_model_1.ModelClass.TRANSPORT_PROFILE)
.then(function (result) {
if (result) {
_this.loadProfiles();
}
});
}
});
};
TransportProfileList.prototype.openMap = function (id) {
console.log('open profile map [' + id + ']');
this.router.navigate([route_module_1.Links.PROFILE_MAP, id]);
};
return TransportProfileList;
}());
TransportProfileList = __decorate([
core_1.Component({
selector: 'transport-profile-list',
templateUrl: './transport-profile.list.html'
})
], TransportProfileList);
exports.TransportProfileList = TransportProfileList; |
import asyncio
from PyQt6.QtCore import QObject, QRunnable, pyqtSignal
from bleak import BleakScanner
class BLEScannerSignals(QObject):
finished = pyqtSignal(list)
error = pyqtSignal(str)
services = pyqtSignal(list)
running = pyqtSignal(bool)
class BLEScanner(QRunnable):
def __init__(self, device=None):
super().__init__()
self.signals = BLEScannerSignals()
self.device = device
self.running = False
def run(self):
self.running=True
self.signals.running.emit(self.running)
try:
asyncio.run(self.scan_and_emit_devices())
except Exception as e:
print("Error:", e)
self.signals.error.emit(str(e))
finally:
self.running=False
self.signals.running.emit(self.running)
async def scan_and_emit_devices(self):
self.running = True
self.signals.running.emit(self.running)
try:
devices = await self.scan_for_devices()
self.running=False
self.signals.running.emit(self.running)
self.signals.finished.emit(devices)
except Exception as e:
print("Error:", e)
self.signals.error.emit(str(e))
finally:
self.running = False
self.signals.running.emit(self.running)
async def scan_for_devices(self):
try:
scanner = BleakScanner()
devices = await scanner.discover(timeout=2)
return [d for d in devices if d.name is not None]
except Exception as e:
print("Error:", e)
finally:
self.running=False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.