text stringlengths 184 4.48M |
|---|
from random import choice
import re
import json # import json
import requests # import requests
class Bank: # two lines need(PEP8: E302)
colours = ['red', 'blue'] # Missing space after ','
animals = ['dog', 'cat'] # Missing space after ','
topic_names = ['Colours', 'Animals'] # Missing space after ','
topics = {'Colours': colours, 'Animals': animals} # Missing space after ':' and ','
api = 'https://api.api-ninjas.com/v1/randomword'
api_key = 'FRkfTIwrgLLk+4TIMd+NMA==m6isKOfXzCLPgdGz'
def __init__(self):
self.current_topic = ''
self.current_word = ''
self.current_word_display = []
self.letters_guessed_counter = 0
self.not_solved = True
self.letters_already_guessed = []
self.api_response_status = True
def pick_topic(self):
self.current_topic = choice(self.topic_names)
print(f'Topic: {self.current_topic}')
def get_word(self):
response = requests.get(f"{self.api}", headers={'X-Api-Key': f"{self.api_key}"}, params={type: 'noun'}) # ": "
if response.status_code == 200:
word = json.loads(response.text)
self.api_response_status = True
self.current_word = word['word']
for _ in self.current_word: # changing 'i' with '_'
self.current_word_display.append('_')
else:
self.current_word = choice(self.topics[self.current_topic])
self.api_response_status = False
def pick_word(self):
self.current_word = choice(self.topics[self.current_topic])
for _ in self.current_word: # changing 'i' with '_'
self.current_word_display.append('_')
print(f'Word is {len(self.current_word)} letters long.') # adding len method for this
print(self.current_word_display)
def check_solve(self):
self.not_solved = self.letters_guessed_counter < len(self.current_word)
class Player: # two lines need(PEP8: E302)
def __init__(self):
self.lives = 10
self.answer = ''
self.guess_validation_incomplete = True
def guess(self):
self.answer = input('Guess a letter: ')
class Processes:
def __init__(self):
pass
@staticmethod # making def static
def validate_user_input(player):
# regex changed & match changed to findall & if condition changed
expression = re.findall('(?i)[a-z]', player.answer) # missing space around operator & after ','
if len(expression) == 0 or len(expression) > 2: # missing space around operator
print('\nPlease guess a single alphabet')
else:
player.guess_validation_incomplete = False
@staticmethod # def seems to be static
def check_answer_update_lives(bank, player): # missing space after ','
if player.answer in bank.letters_already_guessed:
print('\nLetter already guessed.')
# changing elif condition
elif player.answer not in bank.current_word and not player.guess_validation_incomplete:
player.lives -= 1
print('\nNope!')
print('Lives remaining: {}'.format(player.lives))
bank.letters_already_guessed.append(player.answer)
else:
for i in range(len(bank.current_word)):
if player.answer == bank.current_word[i]:
bank.current_word_display[i] = player.answer
bank.letters_guessed_counter += 1
bank.letters_already_guessed.append(player.answer)
print('\nNice!')
class Main: # two lines need(PEP8: E302)
def __init__(self):
pass
while True:
word_bank = Bank()
player1 = Player()
game = Processes()
word_bank.get_word()
if not word_bank.api_response_status:
word_bank.pick_topic()
word_bank.pick_word()
player1.lives = 3 * len(word_bank.current_word)
while word_bank.not_solved and player1.lives > 0:
while player1.guess_validation_incomplete:
player1.guess()
game.validate_user_input(player1)
game.check_answer_update_lives(word_bank, player1) # missing space after ','
print(word_bank.current_word_display)
player1.guess_validation_incomplete = True
word_bank.check_solve()
if not word_bank.not_solved:
print('\nYou win!')
else:
print('\nYou lose')
print('Word was {}'.format(word_bank.current_word))
replay = input('Press any key to play again, x to quit: ')
print('\n')
if replay.upper() == 'X':
break
Play = Main() # two lines need(PEP8: E302)
del Play
# new line at the end of file |
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.apache.royale.html.beads
{
import org.apache.royale.collections.IArrayList;
import org.apache.royale.core.IBead;
import org.apache.royale.core.IDataProviderItemRendererMapper;
import org.apache.royale.core.IItemRendererClassFactory;
import org.apache.royale.core.IItemRendererOwnerView;
import org.apache.royale.core.IListPresentationModel;
import org.apache.royale.core.IIndexedItemRenderer;
import org.apache.royale.core.IDataProviderModel;
import org.apache.royale.core.IStrand;
import org.apache.royale.core.IStrandWithModelView;
import org.apache.royale.core.SimpleCSSStyles;
import org.apache.royale.core.UIBase;
import org.apache.royale.events.Event;
import org.apache.royale.events.IEventDispatcher;
import org.apache.royale.events.EventDispatcher;
import org.apache.royale.events.ItemRendererEvent;
import org.apache.royale.html.supportClasses.DataItemRenderer;
import org.apache.royale.utils.loadBeadFromValuesManager;
import org.apache.royale.html.beads.IListView;
import org.apache.royale.utils.sendEvent;
import org.apache.royale.utils.sendStrandEvent;
/**
* The DataItemRendererFactoryForArrayList class uses an ArrayList
* and creates an item renderer for every
* item in the collection. Other implementations of
* IDataProviderItemRendererMapper map different data
* structures or manage a virtual set of renderers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public class DataItemRendererFactoryForArrayList extends DataItemRendererFactoryBase
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function DataItemRendererFactoryForArrayList(target:Object=null)
{
super(target);
}
private var dp:IArrayList;
/**
* @private
* @royaleignorecoercion org.apache.royale.collections.IArrayList
*/
override protected function dataProviderChangeHandler(event:Event):void
{
dp = dataProviderModel.dataProvider as IArrayList;
if (!dp)
return;
super.dataProviderChangeHandler(event);
}
override protected function get dataProviderLength():int
{
return dp.length;
}
override protected function getItemAt(i:int):Object
{
return dp.getItemAt(i);
}
}
} |
import TextField from "@mui/material/TextField";
import { GitHub } from "@mui/icons-material";
import FormControl from "@mui/material/FormControl";
import { useState } from "react";
import Box from "@mui/material/Box";
import GitHubTable from "./GitHubTable";
import { LoadingButton } from "@mui/lab";
import { Typography } from "@mui/material";
function AppForm() {
const [username, setUsername] = useState("");
const [userInfo, setUserinfo] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(false);
const hadnleUserInput = (user) => {
setUsername(user);
};
const handleFetchUser = async () => {
setError(false);
setIsLoading(true);
const response = await fetch(
`https://api.github.com/users/${username}/repos`
);
if (!response.ok) {
setIsLoading(false);
setError("Couldn't fetch user from GitHub repo.");
}
const res = await response.json();
if (res.length == 0) {
setError("No repos finded.");
}
setUserinfo(res);
setUsername("");
setIsLoading(false);
};
return (
<>
<Box
sx={{ "& > :not(style)": { m: 1 } }}
style={{
display: "flex",
justifyContent: "center",
marginTop: "50px",
marginLeft: "120px",
}}
>
<FormControl variant="standard">
<Box>
<GitHub sx={{ color: "black", mr: 1, my: 0.9 }} />
<TextField
id="input-with-sx"
label="Username"
variant="outlined"
size="small"
value={username}
onChange={(event) => hadnleUserInput(event.target.value)}
/>
</Box>
</FormControl>
<LoadingButton
size="small"
onClick={handleFetchUser}
loading={isLoading}
variant="outlined"
style={{ marginBottom: "10px" }}
>
<span>Fetch Info</span>
</LoadingButton>
</Box>
{userInfo.length > 0 && (
<GitHubTable
user={userInfo}
username={username}
public_repos={userInfo.length}
name={userInfo.name}
desc={userInfo.description}
url={userInfo.url}
id={userInfo.id}
created={userInfo.created_at}
/>
)}
{error && (
<Typography
variant="h5"
style={{
textAlign: "center",
color: "red",
fontWeight: "bold",
marginLeft: "100px",
marginTop: "20px",
}}
>
{error}
</Typography>
)}
</>
);
}
export default AppForm; |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddOwnerIdToVenuesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('venues', function (Blueprint $table) {
$table->integer('owner_id')->unsigned()->index()->nullable()->after('id');
$table->foreign('owner_id')
->references('id')
->on('owners')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('venues', function (Blueprint $table) {
$table->dropColumn('owner_id');
});
}
} |
Script started on Mon 06 Mar 2017 03:04:25 PM EST
liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ gcc -o lab7 lab7.c
liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ ./lab7 5 8
keyboard event CTRL-C and CTRL-Z were ignored.
I am the parent with pid 14035, start to wait the child 14036
I am the child with pid 14036 of process id 14035
parent process's time to live in 4s.
child process's time to live in 7s
parent process's time to live in 3s.
child process's time to live in 6s
parent process's time to live in 2s.
child process's time to live in 5s
parent process's time to live in 1s.
child process's time to live in 4s
parent process's time to live in 0s.
the parent died or terminated before the child.
child process's time to live in 3s
liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ child process's time to live in 2s
child process's time to live in 1s
child process's time to live in 0s
liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ ./lab7 5 8[K[K[K8 5
keyboard event CTRL-C and CTRL-Z were ignored.
I am the parent with pid 14748, start to wait the child 14751
I am the child with pid 14751 of process id 14748
parent process's time to live in 7s.
child process's time to live in 4s
parent process's time to live in 6s.
child process's time to live in 3s
parent process's time to live in 5s.
child process's time to live in 2s
parent process's time to live in 4s.
child process's time to live in 1s
parent process's time to live in 3s.
child process's time to live in 0s
the child died or terminated before the parent.
parent process's time to live in 2s.
parent process's time to live in 1s.
parent process's time to live in 0s.
liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ exi[K[K[Kcat r[Ksample.txt
liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ cat sample.txt [K[K[K[K[K[K[K[K[K[K[Klab7.c
// 1. The program disables the CTRL-C and CTRL-Z sensitivity. (be careful if your program hands to do the ps command and kill the process)
// 2. The program implements the timer alarm.
// Logic of the program:
// The program will launch a child.
// The child will stay alive for a specified number of seconds between 1 and 10 (by a parameter) and then terminates.
// The parent will stay alive for a specified number of seconds between 1 and 10 (by parameter) and then terminates.
// Each of the child and parent will print a count-down every second to display how many seconds they have to live.
// Consider the cases your program should report:
// if the child dies before the parent dies: parent declares that the child is dead by displaying a message on the screen
// if the child dies after the parent dies: the child declares it is an orphan by displaying a message on the screen
// Test your code under the two circumstances and use a script file to log and submit your output.
#include <sys/signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
void pEvent() {
printf("the parent died or terminated before the child.\n");
}
void cEvent() {
printf("the child died or terminated before the parent.\n");
}
int main(int argc, char *argv[]) {
// process the arguments
if (argc != 3) {
printf("Arguments error!\n");
printf("Usage:\n");
printf("%s [parent TTL] [child TTL]\n",argv[0]);
exit(-1);
}
int pttl,cttl;
if ( (pttl = atoi(argv[1])) == 0 || (cttl = atoi(argv[2])) == 0 ) {
printf("Arguments error! TTL should be integer.\n");
printf("Usage:\n");
printf("%s [parent TTL] [child TTL]\n",argv[0]);
exit(-1);
}
//process the code
int status = -1;
pid_t pid,cpid;
//disable CTL-C and CTL-Z to signal
signal(SIGINT,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
//bind child event
signal(SIGALRM,cEvent);
printf("keyboard event CTRL-C and CTRL-Z were ignored.\n");
//fork child
pid = fork();
if (pid == 0) {
//child process tasks
//bind parent event
signal(SIGALRM,pEvent);
printf("I am the child with pid %d of process id %d\n",getpid(),getppid());
int n = cttl;
while(n--) {
sleep(1);
printf("child process's time to live in %ds\n",n);
}
//send signal to parent before dying and ingnore error.
//if ( kill(getppid(),SIGALRM) == -1 ) printf("the parent process was dead before the child.\n");
kill(getppid(),SIGALRM);
exit(0);
} else if(pid < 0) {
printf("Error to fork new child process.\n");
}
//parents tasks
cpid = pid;
printf("I am the parent with pid %d, start to wait the child %d\n",getpid(),cpid);
waitpid(pid,&status,1);
int m = pttl;
while(m--) {
sleep(1);
printf("parent process's time to live in %ds.\n",m);
}
//send signal to child beofe dying and ignore the error message.
//if ( kill(cpid,SIGALRM) == -1 ) printf("the child process was dead before the parent\n");
kill(cpid,SIGALRM);
exit(0);
}
liu1ee@alpha:~/workspace/AdvancedSystemProgramming/labs/lab7$ exit
exit
Script done on Mon 06 Mar 2017 03:07:47 PM EST |
import { Button } from "@material-ui/core";
import { DataGrid } from "@material-ui/data-grid";
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import Loader from "../Layout/Loader";
import { getAllOrdersOfShop } from "../../redux/actions/order";
import { AiOutlineArrowRight } from "react-icons/ai";
import currency from "currency-formatter";
const AllOrders = () => {
const { orders, isLoading } = useSelector((state) => state.order);
const { seller } = useSelector((state) => state.seller);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getAllOrdersOfShop(seller._id));
}, [dispatch]);
const columns = [
{ field: "id", headerName: "ID đơn hàng", minWidth: 150, flex: 0.7 },
{
field: "status",
headerName: "Trạng thái",
minWidth: 130,
flex: 0.7,
cellClassName: (params) => {
return params.getValue(params.id, "status") === "Delivered"
? "greenColor"
: "redColor";
},
},
{
field: "itemsQty",
headerName: "Số lượng",
type: "number",
minWidth: 130,
flex: 0.7,
},
{
field: "total",
headerName: "Tổng cộng",
type: "number",
minWidth: 130,
flex: 0.8,
},
{
field: " ",
flex: 1,
minWidth: 150,
headerName: "",
type: "number",
sortable: false,
renderCell: (params) => {
return (
<>
<Link to={`/order/${params.id}`}>
<Button>
<AiOutlineArrowRight size={20} />
</Button>
</Link>
</>
);
},
},
];
const row = [];
orders &&
orders.forEach((item) => {
row.push({
id: item._id,
itemsQty: item.cart.length,
total: `${currency.format(item.totalPrice, { code: "VND" })}`,
status: item.status,
});
});
return (
<>
{isLoading ? (
<Loader />
) : (
<div className="w-full mx-8 pt-1 mt-10 bg-white">
<DataGrid
rows={row}
columns={columns}
pageSize={10}
disableSelectionOnClick
autoHeight
/>
</div>
)}
</>
);
};
export default AllOrders; |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SSHConfigurator.Extensions;
namespace SSHConfigurator
{
/// <summary>
/// This class configures services and the app's request pipeline.
/// </summary>
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the DI container.
public void ConfigureServices(IServiceCollection services)
{
services.InstallServicesInAssembly(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseStatusCodePagesWithRedirects("/Error/{0}");
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
} |
---
title: 7주차 강의 복습
categories: [멋쟁이사자처럼, 강의 복습]
tags: [Spring]
pin: false
math: false
mermaid: false
---
<style>s{text-decoration: none;background: #ffd00066;border-radius: 4px;padding: 2px;}</style>
## Spring Security
* <s>스프링 기반 애플리케이션의 인증과 권한을 담당하는 하위 프레임워크</s>
* 관리자 및 사용자 계정 추가, 권한 추가, DB 연동이 복잡하다는 문제점이 있음
* `build.gradle`의 dependencies에 아래 라인을 추가한뒤 동기화하여 적용 가능
```gradle
dependencies {
// ...
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.1.RELEASE'
// ...
}
```
* 적용후 사이트를 들어가면 아래와 같은 화면 뜸

* <s>Spring Security는 기본적으로 인증되지 않은 사용자는 서비스를 사용할 수 없게끔 되어 있음</s>
* 방문한 사용자가 사이트를 원활히 이용하기 위해서는 시큐리티 아래의 파일을 생성해줘야 함
```java
package com.likelion.likelion230626;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration // 환결설정을 의미하는 어노테이션
@EnableWebSecurity // 모든 요청 URL이 스프링 시큐리티의 제어를 받도록 만드는 어노테이션
public class SecurityConfig {
// 내부적으로 URL 필터 적용
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests().requestMatchers(
new AntPathRequestMatcher("/**")).permitAll()
;
return http.build(); // 모든 인증되지 않은 요청을 허락
}
}
```
{: file='src/main/java/com.likelion.likelion-230626/Security.java'}
## Spring Security의 인증 과정

_기본적인 로그인 과정_
* 사용자가 `GET /home` 요청을 할 때 만약 사용자의 인증을 확인할 수 없으면 로그인 페이지로 리다이렉트
* 사용자가 로그인 페이지에서 username과 password를 입력후 `POST` 메서드로 데이터를 전송하면, 해당 유저에 대한 인증 토큰을 생성하고 저장
* 다시 사용자가 `GET /home` 요청을 하면 저장된 인증 토큰으로 접근 허가

_로그인 검증 과정_
* `UsernamePasswordAuthenticationFilter`는 인증처리를 하는 필터로 크게 인증 전과 인증 후의 작업들을 관리함
* `UsernamePasswordAuthenticationFilter`는 `AuthenticationManager`에 인증정보를 넘기면 `AuthenticationProvider`을 통해 인증 성공 유무를 확인함
* 성공한 인증객체를 가지고 `SecurityContext`에 저장후, 핸들러를 통해 인증 성공 후의 후속 작업들을 처리
* 이때 `SecurityContext`는 전역적으로 인증객체를 참조할 수 있도록 설계됨


_로그아웃 과정_
## Spring Security의 세션 보호
### 동시 세션 제어

* <s>같은 사용자 계정이 가질수 있는 최대 세션 수를 초과하는 경우에 대한 두가지의 처리방법을 제공</s>
### 세션 고정 보호

* 공격자가 먼저 세션쿠키를 얻은 후 해당 쿠키를 사용자에게 전달
* 사용자가 받은 세션을 가지고 로그인 시도하고 로그인이 성공하면 <s>공격자는 해당 세션쿠키를 가지고 사용자의 정보 탈취가능</s>
## AWS
* <s>아마존 닷컴에서 개발한 클라우드 컴퓨팅 플랫폼</s>
* 가상 컴퓨터와 스토리지, 네트워크 인프라 등 다양한 서비스 제공
### Amazon EC2
* 가상 인스턴스의 크기를 유동적으로 조정이 가능한 컴퓨팅 파워
* 컴퓨팅 리소스를 고객이 완전히 제어할 수 있음
## 서버 내 배포
### JDK 설치
```bash
sudo apt update
sudo apt install openjdk-17-jdk
java -version # java 설치 확인
```
### 네트워크 상태 확인
```bash
sudo apt install net-tools
netstat -nlpt # 네트워크 상태 확인
```
### 아파치 설치 및 .jar파일 실행
```bash
sudo apt install apache2
nohup java -jar test.jar
``` |
<!DOCTYPE html>
<!--
This is the first test html website while DJ is starting to learn HTML
-->
<html>
<head>
<meta charset= "UTF-8" >
<meta name="description" content="DJ's Thank you Page">
<meta name="author" content="Dylan Jude Bautista">
<meta name="keywords" content= "Dylan, Bautista, Portfolio, DJ">
<meta name="newport" content="width=device width, initial scale=1.0">
<title>DJ Bautista</title>
<!--bootstrap stuff-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!--Playfair Display font Import-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@500&display=swap" rel="stylesheet">
<!--Lato font Import-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato&family=League+Spartan:wght@100&family=Playfair+Display:wght@400;500&display=swap" rel="stylesheet">
<!--
<script src="script.js"></script>
-->
<style>
.opening-text{
color:rgb(188, 192, 196);
font-size: 2.8em;
font-family: 'Playfair Display', serif;
width: 40vw;
line-height: 140%;
text-shadow: 3px 3px 4px rgb(150, 137, 137);
border: 6px;
padding: 1%;
border-style:solid;
border-color:rgb(188, 192, 196);
}
p{
font-size: 18px;
font-family: 'Lato', serif;
color:rgb(30, 33, 37);
line-height: 250%;
text-align: center;
}
.header-image{
width:380px;
border-style: groove;
border-color: azure;
border-width: 5px;
border-radius: 5px;
}
.post-image{
width: 30vw;
height: 40vh;
border-style: ridge;
}
h1{
color: black;
font-size: 2em;
font-family: 'Playfair Display', serif;
}
h2{
font-size: 12px;
font-family: 'Lato', serif;
color:silver;
line-height: 250%;
text-align: center;
font-style:italic ;
}
h3{
color:black;
font-size: 3.5vh;
font-family: 'Playfair Display', serif;
}
.silver-sub{
background-color:rgb(228, 220, 220);
display: flex;
justify-content: center;
align-items: center;
}
footer{
background-color: white;
font-family: 'Playfair Display', serif;
line-height: 125%;
text-align: center;
display: flex;
flex-direction: column;
}
.project-tab{
background-color: rgb(228, 220, 220);
flex-direction: column;
display: flex;
align-items: center;
justify-content: flex-start;
}
.project-description{
width: 45vw;
height: 40vh;
margin-left: 60px;
}
.slideshow-array{
background-color: rgb(228, 220, 220);
display: flex;
justify-content: space-around;
flex-wrap: wrap;
align-content: center;
}
.slideshow{
width: 20vw;
height: 30vh;
}
.caption{
font-size: 18px;
font-family: 'Lato', serif;
color:beige;
line-height: 250%;
text-align: center;
text-shadow: 2px 2px rgb(92, 84, 84);
}
h5{
font-family: 'Playfair Display', serif;
}
.topbar{
box-shadow: 0px 20px 35px rgba(0,0,0,.5);
padding: 4px;
position:fixed;
top:0px;
left: 0px;
width:100%;
background-color: white;
display: flex;
justify-content: space-between;
}
</style>
<script src="contact.js"></script>
</head>
<body style="background-color:whitesmoke";>
<!--Topbar-->
<div class="topbar">
<h3>
Dylan Jude Bautista
</h3>
<div class="dropdown" style="padding-right: 30px">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" style="width:25vw ;" data-bs-toggle="dropdown" aria-expanded="false">
Navigation
</button>
<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" href="index.html">Home</a></li>
<li><a class="dropdown-item" href="about-me.html">About Me</a></li>
<li><a class="dropdown-item" href="project-page.html">Project Page</a></li>
<li><a class="dropdown-item" href="contact-me.html">Contact Me</a></li>
</ul>
</div>
</div>
<!--separator-->
<div style="height: 3vh; background-color:rgb(56, 56, 56);"></div>
<header style=" display:flex; align-items:center; justify-content: center; height: 22vh; background-color: rgb(56, 56, 56)">
<h1 class="opening-text" style="text-align: center;"> Contact Me </h1>
</header>
<main>
<div style="display: flex; justify-content: center; padding-top:1vh; background-color: silver;">
<p style="width: 60vw;">
Thanks so Much for reaching out! I will soon be in contact with you.
</p>
</div>
<div class="d-grid gap-2"><a class="btn btn-dark" role="button" href="index.html">Click Here to return to home page.</a></div>
</main>
<div style="height: 10vh; background-color: silver;"></div>
<footer>
<p style="flex-grow: 1; font-size: 20; font-family: 'Playfair Display', serif;">
Get in touch at <u>dylanjudebautista@icloud.com</u><br>
LinkedIn profile: <a href="https://www.linkedin.com/in/dylan-bautista-a924a1210/" target="_blank">https://www.linkedin.com/in/dylan-bautista-a924a1210 </a><br>
Find me on Handshake as <u>Dylan Bautista</u>
</p>
<h2>
Website Constructed by DJ Bautista using HTML, CSS, JavaScript, <small>w/bootstrap</small>
</h2>
</footer>
<!--bootstrap stuff-->
<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>
</body>
</html> |
import { CardItem } from './CardItem.component';
interface Props {
items: IProspect[];
name: string;
color: string;
isDragging: boolean;
handleDragging: (dragging: boolean) => void;
handleUpdateList: (id: number, status: string) => void;
}
export const ContainerCards = ({ items = [], name, color, isDragging, handleDragging, handleUpdateList }: Props) => {
const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
};
const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
const id = +e.dataTransfer.getData('text');
handleUpdateList(id, name);
handleDragging(false);
};
return (
<div
className={`min-w-[350px] rounded-xl h-full overflow-hidden flex-1 flex flex-col border-2`}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
<p
style={{ backgroundColor: color, color: parseInt(color.replace('#', ''), 16) > 0xffffff / 2 ? '#000' : '#fff' }}
className="border-b-2 border-slate-100 capitalize font-bold p-2 text-center"
>
{name}
</p>
<div className="h-[94%] overflow-y-auto">
{items.map(
(item) =>
name === item.prospect_status?.name && (
<CardItem data={item} key={item.id} handleDragging={handleDragging} />
),
)}
</div>
</div>
);
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GPS Access with Flask</title>
</head>
<body>
<h1>GPS Access with Flask</h1>
<div id = "details"></div>
<script>
var reqcount = 0;
navigator.geolocation.watchPosition(successCallback, errorCallback, options);
function successCallback(position) {
const {accuracy, latitude, longitude, altitude, heading, speed} = position.coords;
reqcount++;
// Update details on the webpage
details.innerHTML = "Accuracy: " + accuracy + "<br>";
details.innerHTML += "Latitude: " + latitude + " | Longitude: " + longitude + "<br>";
details.innerHTML += "Speed: " + speed + "<br>";
// Send latitude and longitude to server-side Python script using AJAX
sendDataToPython(latitude, longitude);
}
function errorCallback(error) {
// Handle errors if needed
}
var options = {
enableHighAccuracy: false,
timeout: 5000,
}
function sendDataToPython(latitude, longitude) {
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Define the POST request endpoint (URL of the Python script)
var url = "http://127.0.0.1:5000/update_location"; // Replace with your server URL
// Prepare the data to be sent as JSON
var data = {
"latitude": latitude,
"longitude": longitude
};
// Convert data to JSON format
var jsonData = JSON.stringify(data);
// Configure the request
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
// Send the request with the data
xhr.send(jsonData);
}
</script>
</body>
</html> |
import { z } from "zod";
import { getYear } from "@/utils/getYear";
import DOMPurify from "isomorphic-dompurify";
export const reviewListSchema = z.array(
z.object({
id: z.string(),
movieId: z.number(),
title: z.string(),
description: z.string(),
rating: z.number(),
user: z.object({
id: z.string(),
name: z.string(),
avatarUrl: z.string(),
}),
})
);
export const createReviewData = z
.object({
title: z
.string({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
description: z
.string({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
rating: z
.string({ errorMap: () => ({ message: "Field required" }) })
.min(1, "Field required"),
userId: z
.string({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
movieId: z
.number({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
})
.transform((review) => {
const cleanDescription = DOMPurify.sanitize(review.description);
return { ...review, description: cleanDescription };
});
export const editReviewData = z
.object({
id: z.string(),
title: z
.string({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
description: z
.string({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
rating: z
.string({ errorMap: () => ({ message: "Field required" }) })
.min(1, "Field required"),
userId: z
.string({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
movieId: z
.number({
errorMap: () => ({ message: "Field required" }),
})
.min(1, "Field required"),
})
.transform((review) => {
const cleanDescription = DOMPurify.sanitize(review.description);
return { ...review, description: cleanDescription };
});
export const reviewSchema = z
.object({
id: z.string(),
title: z.string(),
description: z.string(),
rating: z.number(),
user: z.object({
id: z.string().uuid(),
name: z.string(),
avatarUrl: z.string(),
}),
movie: z.object({
poster: z.object({
src: z.string().nullable(),
base64: z.string(),
}),
title: z.string(),
releaseDate: z.string(),
genres: z.array(
z.object({
id: z.number(),
name: z.string(),
})
),
}),
})
.transform((review) => {
const {
movie: { releaseDate, ...movieRest },
...rest
} = review;
return {
...rest,
movie: {
...movieRest,
releaseYear: getYear(releaseDate),
},
};
}); |
package com.jintin.bundle.key
import io.mockk.every
import io.mockk.verify
import org.junit.Before
import org.junit.Test
class BooleanArrayKeyTest : BaseKeyTest() {
private val key = BooleanArrayKey("Test")
private val expect = BooleanArray(2)
@Before
fun setup() {
every { bundle.getBooleanArray(any()) } returns expect
every { persistableBundle.getBooleanArray(any()) } returns expect
every { intent.getBooleanArrayExtra(any()) } returns expect
}
@Test
fun putTest() {
bundle[key] = expect
verify(exactly = 1) { bundle.putBooleanArray(key.key, expect) }
}
@Test
fun putPersistTest() {
persistableBundle[key] = expect
verify(exactly = 1) { persistableBundle.putBooleanArray(key.key, expect) }
}
@Test
fun putIntentTest() {
intent.putExtra(key, expect)
verify(exactly = 1) { intent.putExtra(key.key, expect) }
}
@Test
fun getTest() {
val result = bundle[key]
verify(exactly = 1) { bundle.getBooleanArray(key.key) }
assert(result.contentEquals(expect))
}
@Test
fun getPersistTest() {
val result = persistableBundle[key]
verify(exactly = 1) { persistableBundle.getBooleanArray(key.key) }
assert(result.contentEquals(expect))
}
@Test
fun getIntentTest() {
val result = intent.getExtra(key)
verify(exactly = 1) { intent.getBooleanArrayExtra(key.key) }
assert(result.contentEquals(expect))
}
} |
import { Sequelize } from 'sequelize';
import { CacheStats } from '../types';
import { SyPersistMixin } from './mixins/SyPersistMixin';
import { SyLogger } from '../../logging/SyLogger';
/**
* @todo persist mixin in clients, so the proper cache can be passed?
*/
export abstract class SyBaseCache<T> {
public cache!: Map<any, any>;
public database: Sequelize;
public readonly logger: SyLogger;
public cacheStats: CacheStats;
public isInitialised: boolean;
public evictionIntervalId?: NodeJS.Timeout;
public declare persistMixin: SyPersistMixin<T>;
constructor(database: Sequelize, logger: SyLogger) {
this.logger = logger;
this.database = database;
this.cacheStats = { hits: 0, misses: 0, evictions: 0 };
this.persistMixin = new SyPersistMixin(this.cache, this.database, this.logger);
this.registerShutdownHandler();
this.isInitialised = false;
}
/**
* Registers a shutdown handler.
*/
private registerShutdownHandler(): void {
process.on('SIGTERM', async () => {
this.logger.info('Process is shutting down...');
await this.close();
process.exit(0);
});
}
/**
* Stops the recurring process started by `startEvictingExpiredItems()` that evicts expired items
* from the cache.
*/
public stopEvictingExpiredItems(): void {
if (this.evictionIntervalId) {
clearInterval(this.evictionIntervalId);
this.evictionIntervalId = undefined;
}
}
/**
* Starts the cache.
* @returns {Promise<void>}
*/
public async start(): Promise<void> {
if (!this.isInitialised) {
try {
this.logger.info('Cache Initiated');
await this.persistMixin.loadCacheFromDatabase();
this.isInitialised = true;
} catch (error: any) {
this.logger.error('Error during cache start:', error);
throw error;
}
}
}
/**
* Closes the cache.
* @returns {Promise<void>}
*/
public async close(): Promise<void> {
try {
this.stopEvictingExpiredItems();
await this.persistMixin.saveCacheToDatabase();
this.isInitialised = false;
} catch (error: any) {
this.logger.error('Error during cache close:', error);
}
}
/**
* Gets the cache stats.
* @returns {{ hits: number; misses: number; evictions: number }} The cache stats.
*/
public getCacheStats(): { hits: number; misses: number; evictions: number } {
return this.cacheStats;
}
/**
* Monitors the performance of the cache.
*/
public monitorCachePerformance(): void {
const hitRatio = this.cacheStats.hits / (this.cacheStats.hits + this.cacheStats.misses);
if (hitRatio < 0.8) {
this.logger.error(`Cache hit ratio dropped below 80%: ${hitRatio}`);
}
if (this.cacheStats.evictions > 100) {
this.logger.error(`Cache evictions exceeded 100: ${this.cacheStats.evictions}`);
}
}
//
public incrementCacheMisses(): void {
this.cacheStats.misses++;
}
//
public incrementCacheHits(): void {
this.cacheStats.hits++;
}
} |
import { View, ScrollView, Image, TouchableOpacity } from 'react-native'
import React, { useEffect, useState } from 'react'
import { colors, defaultStyle } from '../../styles/styles'
import Header from '../../components/Header'
import PageHeading from '../../components/PageHeading'
import ImageCard from '../../components/ImageCard'
import { Avatar, Button } from 'react-native-paper'
import mime from 'mime';
import { useAddProductImageMutation, useDeleteProductImageMutation, useGetProductDetailsQuery } from '../../redux/api/apiSlices/productApiSlice'
import Loader from '../../components/Loader'
import { Toast } from 'react-native-toast-message/lib/src/Toast'
const ProductImages = ({ navigation, route }) => {
const [addImage, { isLoading: isAddImageLoading }] = useAddProductImageMutation();
const [deleteImage, { isLoading: isDeleteImageLoading }] = useDeleteProductImageMutation();
const [images, setImages] = useState(route.params.images);
const [productId] = useState(route.params.id);
const [image, setImage] = useState(null);
const [imageChanged, setImageChanged] = useState(false);
const [productDetailsID] = useState(route.params.productDetailsID);
const { data, isLoading: isProductLoading } = useGetProductDetailsQuery(productDetailsID);
const productImages = data?.product.images;
const deleteHandler = async (imageId) => {
if (images.length < 2) return Toast.show({
type: "error",
text1: 'The product must have at least one image',
});
try {
await deleteImage({productId, imageId}).unwrap();
}
catch {
}
};
const submitHandler = async () => {
const myForm = new FormData();
myForm.append("file", {
uri: image,
type: mime.getType(image),
name: image.split("/").pop(),
});
try {
await addImage({ productId, formData: myForm }).unwrap();
}
catch {
}
};
useEffect(() => {
if (route.params?.image) {
setImage(route.params.image);
setImageChanged(true);
}
}, [route.params]);
useEffect(() => {
setImages(productImages);
}, [productImages]);
return (
<View style={{ ...defaultStyle, backgroundColor: colors.color5 }}>
<Header back={true} />
{/* Heading */}
<PageHeading text={"Manage Product Images"} paddingTopStyle={70} />
{isProductLoading ? <Loader /> : (
<>
<ScrollView style={{ marginBottom: 20 }}>
<View style={{ backgroundColor: colors.color2, padding: 40, minHeight: 400 }}>
{
images.map(i => (
<ImageCard key={i._id} src={i.url} id={i._id} deleteHandler={deleteHandler} />
))
}
</View>
</ScrollView>
<View style={{ padding: 20, borderRadius: 10, backgroundColor: colors.color3 }}>
<Image style={{ backgroundColor: colors.color2, width: 100, height: 100, alignSelf: "center", resizeMode: "contain" }} source={{ uri: image }} />
<View style={{ flexDirection: "row", justifyContent: "center" }}>
<TouchableOpacity TouchableOpacity={0.8} onPress={() => navigation.navigate("camera", { updateProduct: true })}>
<Avatar.Icon icon={"camera"} size={30} color={colors.color3} style={{ backgroundColor: colors.color2, margin: 10 }} />
</TouchableOpacity>
</View>
<Button style={{ backgroundColor: colors.color1, padding: 6 }} textColor={colors.color2} loading={isAddImageLoading} onPress={submitHandler} disabled={!imageChanged}>
Add
</Button>
</View>
</>
)}
</View>
)
}
export default ProductImages |
import { render, screen } from '@testing-library/react';
import { getPeople } from './api/people';
import App from './App';
import data from './data.json';
test('It should show a six characters of the list from API', async () => {
const list = await getPeople();
console.log("Running test async...");
expect(list.results[6].name).toBe("Beru Whitesun lars");
});
describe("StarsWars", () => {
beforeAll(() => jest.spyOn(window, 'fetch'));
test('It should show a list of characters from API', async () => {
window.fetch.mockResolvedValueOnce({
ok: true,
json: async () => data,
});
render(<App />);
expect(window.fetch).toHaveBeenCalledTimes(1)
expect(window.fetch).toHaveBeenCalledWith('https://swapi.dev/api/people/');
for (let character of data.results) {
expect(await screen.findByText(character.name)).toBeInTheDocument();
}
});
test('It should show an error when has a network error', async () => {
window.fetch.mockRejectedValueOnce(new Error('Network error'));
render(<App />);
expect(await screen.findByText("Network error")).toBeInTheDocument();
});
/*test('It should show a list of characters including Luke Skywalker', () => {
render(<App />);
expect(screen.getByText('Luke Skywalker')).toBeInTheDocument();
});
test('It should show a list of characters from json file', () => {
render(<App />);
for (let character of data.results) {
expect(screen.getByText(character.name)).toBeInTheDocument
}
});*/
}); |
---
title: "Top 10 iPhone Lens Capabilities in iOS 11 for 2024"
date: 2024-06-04T10:18:19.287Z
updated: 2024-06-05T10:18:19.287Z
tags:
- screen-recording
- ai video
- ai audio
- ai auto
categories:
- ai
- screen
description: "This Article Describes Top 10 iPhone Lens Capabilities in iOS 11 for 2024"
excerpt: "This Article Describes Top 10 iPhone Lens Capabilities in iOS 11 for 2024"
keywords: "IPhone Lens Features,IOS 11 Camera Enhancements,Top iPhones 10X Zoom,IOS 11 Lens API,ProLens in iOS 11,Macro Photography on iPhone,Wide Angle Zoom in iOS"
thumbnail: https://thmb.techidaily.com/3dd5b17c533ab88ed9cc0f3b00c7a2aa3b7c864b4f9c2a1611133710cbbaabe1.jpg
---
## Top 10 iPhone Lens Capabilities in iOS 11
# 10 iPhone Camera Features You Should Know in iOS 11

##### Ollie Mattison
Mar 27, 2024• Proven solutions
iPhone's camera has been setting the standards for Smartphone cameras since the first model of the device was introduced to the public by Steve Jobs a little over a decade ago. The optics of iPhone cameras are without question powerful, but it is the combination of the software and the hardware that makes these cameras truly unique.
**You may also like:** [Best Camera Apps for iPhone X/10/8 Plus/7 Plus](https://tools.techidaily.com/wondershare/filmora/download/)
Each iPhone photographer has to ask themselves the same question: 'Am I really using the full capacity of my camera?'If the answer is no, maybe these iPhone camera features can help you improve the quality of your photos.
## 10 iPhone Camera Features You Should Know in iOS 11
The quality of your photos is in direct relation to your level of familiarity with the camera's features because the more you know about the camera the better you will be at finding the proper use for those features.
#### 1\. Don't Be Shy to Use the Grid Mode

Image resource: Macworld
If you want to improve your photo taking skills, you must start paying attention to picture composition. Fortunately, the iPhone camera app offers the Grid Mode that divides the screen into nine equal parts. The grid will provide assistance in placing the subjects of your photos at the very center of the picture or when learning how to use the rule of thirds, one of the most basic composition techniques in photography.
#### 2\. Set the Focus and Exposure manually

Image resource: iPhone Photography School
Relying on auto settings will not get you far in the photography world. Even though your iPhone is perfectly capable of setting the exposure or focus automatically, adjusting these values manually will provide you with more control over the process of taking a photo. Choosing where the focal point in your photo will be and finding the perfect exposure by yourself will allow you to highlight the subjects of your pictures and it will enable you to decide how bright or dark your photo is going to be.
#### 3\. HDR Photos Have More Balanced Lightning

Image resource: Gadget Bistro Malaysia
Utilizing the HDR or High Dynamic Range feature is yet another effective way to control the exposure of your pictures. When activated, HDR feature will allow your iPhone to combine three different exposures in a single shot, and the result will be a picture that has a higher amount of detail in its shadows and highlights.
#### 4\. Use the Timer to Stabilize Your Shots

iPhone X weighs only 174 grams, which makes it nearly impossible to hold perfectly still. This complicates things even further in difficult light conditions, but the Timer feature on iPhone X can help you solve this problem. You can compose your shot and set the Timer for 3 or 10 seconds and the device will take ten photos in a row, which will enable you to select the sharpest photo and delete the others.
#### 5\. Edit Live Photos
Taking Live Photos hasn't changed at all on the new model of the iPhone, but now you can also edit live photos in pretty much the same way you would edit a still photo. You can turn off the sound, crop or rotate live photos effortlessly, as well as apply filters, adjust color balance or improve lightning on all of your live photos.
#### 6\. QR Codes Detection

Image resource: 9to5Mac
QR codes are actually quite convenient because they save you the trouble of typing the URL by yourself. The iOS 11 is the first iPhone OS with the ability to read QR codes. All you need to do is open your camera app and point it in the direction of the QR code you want to view, and your iPhone X will do the rest.
#### 7\. Take Selfies in Portrait Mode - Only for iPhone X

Image resource: Tom's Guide
The True Depth camera option that is now available on iPhone X will enable you to use the Portrait mode on your front camera. This iPhone X Portrait mode lets you control the depth of field, which means that objects closest to the lens are going to be crispy sharp, and the rest of the picture is going to have a smooth artistic blur.
#### 8\. Improvements of the Video Features - iPhone X/8
The rear camera on iPhone X is capable of capturing 4K videos at 30 or at 60 fps, and you can also use it to record slow-motion 1080p videos at 120 or at 240 fps. These features are a significant step up from the previous iPhone model both in terms of video image quality and in terms of possibilities they provide to iPhone X owners.
#### 9\. Dual Optical Image Stabilization Lets you Take Better Photos - iPhone X/8

Keeping the moving objects in focus is a major concern regardless of the camera you are using. We were excited about the [dual camera feature in iPhone 7](https://tools.techidaily.com/wondershare/filmora/download/), now the Dual Optical Image Stabilization feature in iOS 11 reduces motion blur and it also decreases the impact the camera shakes have on your photos. iPhone 8's Optical Image Stabilization has been improved on iPhone X and it works alongside the image sensor to ensure that all pictures taken with this device are razor sharp.
#### 10\. Portrait Lighting Lets You Adjust Light to Best Fit Your Subject - iPhone X/8

iPhone 8 Plus and iPhone X offer a new feature, specifically designed to let you find the perfect lighting for the subject of your photos. This feature doesn't work like a filter, but rather like a real-time light meter, that calculates the optimum light values on the face of the person or persons depicted in a photo.
## Post Production Software for iPhone photography
iPhone photographers, who would like to take their photos and videos a step further will unquestionably benefit from using [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/). The editor lets you create 9:16 aspect ratio images, designed to help mobile users who don't want to have the black bars alongside the edges of their vertically oriented photos and videos. Adding blur effects to your photos or videos, enhancing the colors or applying effects to your videos are just a few out of many possibilities provided by the Wondershare's software.
[](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/)

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
##### Ollie Mattison
Mar 27, 2024• Proven solutions
iPhone's camera has been setting the standards for Smartphone cameras since the first model of the device was introduced to the public by Steve Jobs a little over a decade ago. The optics of iPhone cameras are without question powerful, but it is the combination of the software and the hardware that makes these cameras truly unique.
**You may also like:** [Best Camera Apps for iPhone X/10/8 Plus/7 Plus](https://tools.techidaily.com/wondershare/filmora/download/)
Each iPhone photographer has to ask themselves the same question: 'Am I really using the full capacity of my camera?'If the answer is no, maybe these iPhone camera features can help you improve the quality of your photos.
## 10 iPhone Camera Features You Should Know in iOS 11
The quality of your photos is in direct relation to your level of familiarity with the camera's features because the more you know about the camera the better you will be at finding the proper use for those features.
#### 1\. Don't Be Shy to Use the Grid Mode

Image resource: Macworld
If you want to improve your photo taking skills, you must start paying attention to picture composition. Fortunately, the iPhone camera app offers the Grid Mode that divides the screen into nine equal parts. The grid will provide assistance in placing the subjects of your photos at the very center of the picture or when learning how to use the rule of thirds, one of the most basic composition techniques in photography.
#### 2\. Set the Focus and Exposure manually

Image resource: iPhone Photography School
Relying on auto settings will not get you far in the photography world. Even though your iPhone is perfectly capable of setting the exposure or focus automatically, adjusting these values manually will provide you with more control over the process of taking a photo. Choosing where the focal point in your photo will be and finding the perfect exposure by yourself will allow you to highlight the subjects of your pictures and it will enable you to decide how bright or dark your photo is going to be.
#### 3\. HDR Photos Have More Balanced Lightning

Image resource: Gadget Bistro Malaysia
Utilizing the HDR or High Dynamic Range feature is yet another effective way to control the exposure of your pictures. When activated, HDR feature will allow your iPhone to combine three different exposures in a single shot, and the result will be a picture that has a higher amount of detail in its shadows and highlights.
#### 4\. Use the Timer to Stabilize Your Shots

iPhone X weighs only 174 grams, which makes it nearly impossible to hold perfectly still. This complicates things even further in difficult light conditions, but the Timer feature on iPhone X can help you solve this problem. You can compose your shot and set the Timer for 3 or 10 seconds and the device will take ten photos in a row, which will enable you to select the sharpest photo and delete the others.
#### 5\. Edit Live Photos
Taking Live Photos hasn't changed at all on the new model of the iPhone, but now you can also edit live photos in pretty much the same way you would edit a still photo. You can turn off the sound, crop or rotate live photos effortlessly, as well as apply filters, adjust color balance or improve lightning on all of your live photos.
#### 6\. QR Codes Detection

Image resource: 9to5Mac
QR codes are actually quite convenient because they save you the trouble of typing the URL by yourself. The iOS 11 is the first iPhone OS with the ability to read QR codes. All you need to do is open your camera app and point it in the direction of the QR code you want to view, and your iPhone X will do the rest.
#### 7\. Take Selfies in Portrait Mode - Only for iPhone X

Image resource: Tom's Guide
The True Depth camera option that is now available on iPhone X will enable you to use the Portrait mode on your front camera. This iPhone X Portrait mode lets you control the depth of field, which means that objects closest to the lens are going to be crispy sharp, and the rest of the picture is going to have a smooth artistic blur.
#### 8\. Improvements of the Video Features - iPhone X/8
The rear camera on iPhone X is capable of capturing 4K videos at 30 or at 60 fps, and you can also use it to record slow-motion 1080p videos at 120 or at 240 fps. These features are a significant step up from the previous iPhone model both in terms of video image quality and in terms of possibilities they provide to iPhone X owners.
#### 9\. Dual Optical Image Stabilization Lets you Take Better Photos - iPhone X/8

Keeping the moving objects in focus is a major concern regardless of the camera you are using. We were excited about the [dual camera feature in iPhone 7](https://tools.techidaily.com/wondershare/filmora/download/), now the Dual Optical Image Stabilization feature in iOS 11 reduces motion blur and it also decreases the impact the camera shakes have on your photos. iPhone 8's Optical Image Stabilization has been improved on iPhone X and it works alongside the image sensor to ensure that all pictures taken with this device are razor sharp.
#### 10\. Portrait Lighting Lets You Adjust Light to Best Fit Your Subject - iPhone X/8

iPhone 8 Plus and iPhone X offer a new feature, specifically designed to let you find the perfect lighting for the subject of your photos. This feature doesn't work like a filter, but rather like a real-time light meter, that calculates the optimum light values on the face of the person or persons depicted in a photo.
## Post Production Software for iPhone photography
iPhone photographers, who would like to take their photos and videos a step further will unquestionably benefit from using [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/). The editor lets you create 9:16 aspect ratio images, designed to help mobile users who don't want to have the black bars alongside the edges of their vertically oriented photos and videos. Adding blur effects to your photos or videos, enhancing the colors or applying effects to your videos are just a few out of many possibilities provided by the Wondershare's software.
[](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/)

Ollie Mattison
Ollie Mattison is a writer and a lover of all things video.
Follow @Ollie Mattison
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-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://some-guidance.techidaily.com/2024-approved-streamline-conversion-selecting-the-top-10-free-tools/"><u>2024 Approved Streamline Conversion Selecting the Top 10 Free Tools</u></a></li>
<li><a href="https://some-guidance.techidaily.com/in-2024-mastering-gopro-essentials-of-time-lapse-photography/"><u>In 2024, Mastering GoPro Essentials of Time-Lapse Photography</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-troubleshooting-tips-fixing-srt-from-premiere-freeze/"><u>[New] Troubleshooting Tips Fixing SRT From Premiere Freeze</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-unhackable-blueprint-for-inserting-your-tiktok-links/"><u>2024 Approved Unhackable Blueprint for Inserting Your TikTok Links</u></a></li>
<li><a href="https://some-guidance.techidaily.com/updated-neo-theater-narratives-virtual-realms/"><u>[Updated] Neo-Theater Narratives Virtual Realms</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-top-innovators-defining-next-gen-vr-experiences/"><u>2024 Approved Top Innovators Defining Next-Gen VR Experiences</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-unveiling-30-preferred-steadicam-models-for-high-quality-dslr-projects/"><u>2024 Approved Unveiling 30 Preferred Steadicam Models for High-Quality DSLR Projects</u></a></li>
<li><a href="https://some-guidance.techidaily.com/in-2024-the-ultimate-blueprint-for-srt-file-excellence/"><u>In 2024, The Ultimate Blueprint for SRT File Excellence</u></a></li>
<li><a href="https://some-guidance.techidaily.com/in-2024-transforming-srt-a-complete-reference-guide-for-conversion/"><u>In 2024, Transforming SRT A Complete Reference Guide for Conversion</u></a></li>
<li><a href="https://some-guidance.techidaily.com/in-2024-unveiling-ffxp-an-in-depth-guide/"><u>In 2024, Unveiling FFXP An In-Depth Guide</u></a></li>
<li><a href="https://some-guidance.techidaily.com/unlock-the-secrets-of-your-lost-iphone-x-for-2024/"><u>Unlock the Secrets of Your Lost iPhone X for 2024</u></a></li>
<li><a href="https://some-guidance.techidaily.com/in-2024-unlock-social-potential-with-easy-to-follow-tips-for-xbox-and-zoom-users/"><u>In 2024, Unlock Social Potential with Easy-to-Follow Tips for Xbox and Zoom Users</u></a></li>
<li><a href="https://some-guidance.techidaily.com/transform-streams-into-premium-4k-videos-easily-for-2024/"><u>Transform Streams Into Premium 4K Videos Easily for 2024</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-unleash-bright-potential-in-your-android-videos/"><u>[New] Unleash Bright Potential in Your Android Videos</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-unlock-optimal-video-playback-by-tuning-speed-in-snapchat/"><u>[New] Unlock Optimal Video Playback by Tuning Speed in Snapchat</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-top-social-network-sites-for-youtube-growth/"><u>[New] Top Social Network Sites for YouTube Growth</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-the-essence-of-unaltered-audio-ffmpegs-precision/"><u>2024 Approved The Essence of Unaltered Audio FFmpeg’s Precision</u></a></li>
<li><a href="https://some-guidance.techidaily.com/updated-navigating-new-realities-metaverse-meets-omniverse/"><u>[Updated] Navigating New Realities Metaverse Meets Omniverse</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-unveiling-the-art-of-written-visual-narratives-a-guide-on-docuscripts/"><u>2024 Approved Unveiling the Art of Written Visual Narratives A Guide on Docuscripts</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-ultimate-png-alterations-guide/"><u>2024 Approved Ultimate PNG Alterations Guide</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-stream-power-showdown-vmix-clashes-with-wirecast-for-broadcast-excellence/"><u>2024 Approved Stream Power Showdown VMix Clashes with Wirecast for Broadcast Excellence</u></a></li>
<li><a href="https://some-guidance.techidaily.com/2024-approved-unleashing-the-power-of-pip-videos-with-sierras-os-advantages/"><u>2024 Approved Unleashing the Power of PIP Videos with Sierra's OS Advantages</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-the-soundtrack-of-your-phone-classic-tones-download-site-guide/"><u>[New] The Soundtrack of Your Phone Classic Tones Download Site Guide</u></a></li>
<li><a href="https://some-guidance.techidaily.com/in-2024-streamline-your-podcasts-effective-editing-tips-for-garageband-users/"><u>In 2024, Streamline Your Podcasts Effective Editing Tips for GarageBand Users</u></a></li>
<li><a href="https://some-guidance.techidaily.com/updated-utilizing-in-presentation-speech-to-text-functionality-in-powerpoint/"><u>[Updated] Utilizing In-Presentation Speech-to-Text Functionality in PowerPoint</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-tiktok-number-modification-easy-to-follow-steps/"><u>[New] TikTok Number Modification Easy to Follow Steps</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-top-choice-5-image-background-adjuster-apps-ios/"><u>[New] Top Choice 5 Image Background Adjuster Apps (iOS)</u></a></li>
<li><a href="https://some-guidance.techidaily.com/updated-top-8-collaborative-video-collage-apps-for-android-users-freepaid/"><u>[Updated] Top 8 Collaborative Video Collage Apps for Android Users (Free/Paid)</u></a></li>
<li><a href="https://some-guidance.techidaily.com/updated-multimedia-artists-cyber-meeting-room/"><u>[Updated] Multimedia Artists' Cyber Meeting Room</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-tiktoks-best-practices-for-stellar-edits/"><u>[New] TikTok's Best Practices for Stellar Edits</u></a></li>
<li><a href="https://some-guidance.techidaily.com/in-2024-sustaining-system-stability-returning-to-el-capitan/"><u>In 2024, Sustaining System Stability Returning to El Capitan</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-the-metaverse-and-omniverse-a-detailed-breakdown/"><u>[New] The Metaverse & Omniverse A Detailed Breakdown</u></a></li>
<li><a href="https://some-guidance.techidaily.com/periscope-prodigy-from-beginner-to-expert-for-2024/"><u>Periscope Prodigy From Beginner to Expert for 2024</u></a></li>
<li><a href="https://some-guidance.techidaily.com/updated-the-next-wave-of-social-media-top-apps-as-periscope-alternates/"><u>[Updated] The Next Wave of Social Media Top Apps as Periscope Alternates</u></a></li>
<li><a href="https://youtube-video-recordings.techidaily.com/2024-approved-discovering-best-phone-based-asmr-experiences/"><u>2024 Approved Discovering Best Phone-Based ASMR Experiences</u></a></li>
<li><a href="https://extra-resources.techidaily.com/photo-perfection-seamless-text-integration-on-pc-and-mac-systems/"><u>Photo Perfection Seamless Text Integration on PC & Mac Systems</u></a></li>
<li><a href="https://sound-tweaking.techidaily.com/hunt-for-virtual-assorted-digestive-noises-in-sound-libraries-for-2024/"><u>Hunt for Virtual Assorted Digestive Noises in Sound Libraries for 2024</u></a></li>
<li><a href="https://tiktok-clips.techidaily.com/new-in-2024-from-one-self-portrait-to-a-thousand-mastering-the-art-of-repeating-yourself-on-tiktok/"><u>[New] In 2024, From One Self-Portrait to a Thousand Mastering the Art of Repeating Yourself on TikTok</u></a></li>
<li><a href="https://android-unlock.techidaily.com/top-10-fingerprint-lock-apps-to-lock-your-samsung-galaxy-a15-4g-phone-by-drfone-android/"><u>Top 10 Fingerprint Lock Apps to Lock Your Samsung Galaxy A15 4G Phone</u></a></li>
<li><a href="https://screen-recording.techidaily.com/2024-approved-immediate-streams-from-obs-to-insta/"><u>2024 Approved Immediate Streams From OBS to Insta</u></a></li>
<li><a href="https://voice-adjusting.techidaily.com/1714938348202-updated-how-to-record-your-computer-audio-in-audacity-for-2024/"><u>Updated How to Record Your Computer Audio in Audacity for 2024</u></a></li>
<li><a href="https://digital-screen-recording.techidaily.com/2024-approved-in-depth-insights-perfecting-the-craft-of-screen-recording-on-macbooks/"><u>2024 Approved In-Depth Insights Perfecting the Craft of Screen Recording on MacBooks</u></a></li>
<li><a href="https://ai-video-apps.techidaily.com/updated-slow-down-the-action-top-10-video-players-for-smooth-playback-for-2024/"><u>Updated Slow Down the Action Top 10 Video Players for Smooth Playback for 2024</u></a></li>
<li><a href="https://digital-screen-recording.techidaily.com/new-in-2024-premium-4k-screen-capturing-solutions/"><u>[New] In 2024, Premium 4K Screen Capturing Solutions</u></a></li>
<li><a href="https://desktop-recording.techidaily.com/updated-professional-voice-recording-made-easy-with-ipad-for-2024/"><u>[Updated] Professional Voice Recording Made Easy with iPad for 2024</u></a></li>
<li><a href="https://audio-shaping.techidaily.com/updated-tune-infused-photography-link-free-audio-to-images-for-2024/"><u>Updated Tune-Infused Photography Link Free Audio to Images for 2024</u></a></li>
<li><a href="https://techidaily.com/how-to-reset-a-tecno-pova-6-pro-5g-phone-that-is-locked-drfone-by-drfone-reset-android-reset-android/"><u>How to Reset a Tecno Pova 6 Pro 5G Phone That Is Locked | Dr.fone</u></a></li>
<li><a href="https://instagram-video-recordings.techidaily.com/updated-2024-approved-mastering-instagram-video-downloads-pcmac-guide/"><u>[Updated] 2024 Approved Mastering Instagram Video Downloads PC/Mac Guide</u></a></li>
<li><a href="https://techidaily.com/the-way-to-get-back-lost-videos-from-itel-s23-by-fonelab-android-recover-video/"><u>The way to get back lost videos from Itel S23</u></a></li>
<li><a href="https://facebook-video-recording.techidaily.com/2024-approved-online-persona-transformation-rendering-your-cartoon-self/"><u>2024 Approved Online Persona Transformation Rendering Your Cartoon Self</u></a></li>
<li><a href="https://extra-tips.techidaily.com/in-2024-boost-engagement-with-free-intro-templates/"><u>In 2024, Boost Engagement with Free Intro Templates</u></a></li>
<li><a href="https://instagram-videos.techidaily.com/transform-your-reels-6-advanced-applications-for-instagram/"><u>Transform Your Reels 6 Advanced Applications for Instagram</u></a></li>
<li><a href="https://unlock-android.techidaily.com/a-perfect-guide-to-remove-or-disable-google-smart-lock-on-vivo-y100-5g-by-drfone-android/"><u>A Perfect Guide To Remove or Disable Google Smart Lock On Vivo Y100 5G</u></a></li>
</ul></div> |
import React, { useContext } from "react";
import { IoTrashBin, IoThumbsUp, IoPencil, IoClipboardSharp } from "react-icons/io5";
import { EditingVeiculoContext } from "../../context/EditingVeiculoContext";
import { FormModalContext } from "../../context/FormModalContext";
import { MovimentationContext } from "../../context/MovimentationContext";
import { useAxios } from "../../hooks/useAxios";
import api from "../../services/api";
import { Container, ButtonArea, Button } from "./styles";
export default function Veiculo({ id, marca, modelo, placa, ano }) {
const { handleEditMode } = useContext(FormModalContext);
const { handleMovimentationEditMode } = useContext(MovimentationContext);
const { setEditingVeiculo } = useContext(EditingVeiculoContext);
const { data, mutate } = useAxios("veiculos");
function handleMovimento() {
handleMovimentationEditMode(marca, modelo, placa, ano);
}
function handleDelete() {
api.delete(`/veiculos/${id}`);
const updatedVeiculos = {
veiculos: data.veiculos?.filter((veiculo) => veiculo._id !== id),
};
mutate(updatedVeiculos, false);
}
function handleEdit() {
handleEditMode(marca, modelo, placa, ano);
setEditingVeiculo(id);
}
return (
<li key={id}>
<Container>
<h2>{placa}</h2>
<p>{marca}</p>
<p>{modelo}</p>
<p>{ano}</p>
<ButtonArea>
<Button onClick={handleMovimento}>
<IoClipboardSharp />
</Button>
<Button onClick={handleEdit}>
<IoPencil />
</Button>
<Button onClick={handleDelete}>
<IoTrashBin />
</Button>
</ButtonArea>
</Container>
</li>
);
} |
//
// MountedElement.swift
// SwiftAR
//
// Created by Jan Luca Siewert on 04.04.21.
//
// Based on the implementation of Tokamak
import Foundation
import Combine
class MountedElement<R: Renderer>: Hashable {
// MARK: - Initialization
/// Element is the type elements get rendered into
typealias Element = R.TargetType
typealias Mounted = MountedElement<R>
enum ElementType {
case experience(AnyExperience)
case anchor(AnyAnchor)
case model(AnyModel)
}
var mounted: ElementType
var experience: AnyExperience {
get {
guard case .experience(let e) = mounted else {
fatalError("Can't get experience from \(mounted)")
}
return e
}
set {
mounted = .experience(newValue)
}
}
var model: AnyModel {
get {
guard case .model(let m) = mounted else {
fatalError("Can't get model from \(mounted)")
}
return m
}
set {
mounted = .model(newValue)
}
}
var anchor: AnyAnchor {
get {
guard case .anchor(let a) = mounted else {
fatalError("Can't get anchor from \(mounted)")
}
return a
}
set {
mounted = .anchor(newValue)
}
}
var _type: Any.Type {
switch mounted {
case .anchor(let a): return a.type
case .experience(let e): return e.type
case .model(let m): return m.type
}
}
var bodyType: Any.Type {
switch mounted {
case .anchor(let a): return a.bodyType
case .experience(let e): return e.bodyType
case .model(let m): return m.bodyType
}
}
var element: Element?
weak var parent: Mounted?
var children: [Mounted]?
init<M: Model>(model: M, parent: Mounted, environment: EnvironmentValues? = nil) {
self.mounted = .model(AnyModel(erasing: model))
self.parent = parent
self.environmentValues = environment ?? parent.environmentValues
}
init<A: Anchor>(anchor: A, parent: Mounted, environment: EnvironmentValues? = nil) {
self.mounted = .anchor(AnyAnchor(erasing: anchor))
self.parent = parent
self.environmentValues = environment ?? parent.environmentValues
}
init<E: Experience>(experience: E, environment: EnvironmentValues = EnvironmentValues()) {
self.mounted = .experience(AnyExperience(erasing: experience))
self.environmentValues = environment
}
func hash(into hasher: inout Hasher) {
hasher.combine(element)
}
static func == (lhs: MountedElement, rhs: MountedElement) -> Bool {
return lhs.element == rhs.element
}
// MARK: - Mounting
func mount(with reconciler: StackReconciler<R>, to parent: R.TargetType? = nil) {
updateEnvironment()
switch mounted {
case .experience(let e):
children = createChild(for: e, reconciler: reconciler)
case .model(let m):
children = createChild(for: m, reconciler: reconciler)
case .anchor(let a):
children = createChild(for: a, reconciler: reconciler)
}
// Todo: Inject state and environment!
element = reconciler.mount(self, to: parent)
children?.forEach {
$0.mount(with: reconciler, to: element)
}
}
func createChild(for experience: AnyExperience, reconciler: StackReconciler<R>) -> [MountedElement] {
print("Creating child for \(String(describing: experience.type)) of type \(String(describing: type(of: experience.bodyType.self)))")
let body = reconciler.render(mountedExperience: self)
let element = MountedElement(anchor: body, parent: self)
return [element]
}
func createChild(for anchor: AnyAnchor, reconciler: StackReconciler<R>) -> [MountedElement] {
print("Creating child for \(String(describing: anchor.type)) of type \(String(describing: type(of: anchor.bodyType.self)))")
let body = reconciler.render(mountedAnchor: self)
let element = MountedElement(model: body, parent: self)
return [element]
}
func createChild(for model: AnyModel, reconciler: StackReconciler<R>) -> [MountedElement] {
if let m = model.model as? ChildProvidingModel {
print("Creating Child for ChildProvidingModel \(model.type)")
return m.children.map { MountedElement(model: $0, parent: self) }
}
print("Creating child for \(String(describing: model.type))")
guard model.bodyType != Never.Type.self else {
print("Skipping child for \(model.type)")
return []
}
print("Mounting children for \(model.type)")
let body = reconciler.render(mountedModel: self)
let child = MountedElement<R>(model: body, parent: self)
return [child]
}
func update(with reconciler: StackReconciler<R>) {
guard let element = element else { return }
updateEnvironment()
switch mounted {
case .experience(let e): self.update(experience: e, with: reconciler, element: element)
case .anchor(let a): self.update(anchor: a, with: reconciler, element: element)
case .model(let m): self.update(model: m, with: reconciler, element: element)
}
}
private func update(experience: AnyExperience, with reconciler: StackReconciler<R>, element target: R.TargetType) {
let element = reconciler.render(mountedExperience: self)
reconciler.reconcile(
self,
with: element,
getElementType: { $0.type },
updateChild: {
$0.environmentValues = environmentValues
$0.anchor = AnyAnchor(erasing: element)
},
mountChild: {
let child = MountedElement(anchor: $0, parent: self)
// child.mount(with: reconciler, to: target)
return child
}
)
}
private func update(anchor: AnyAnchor, with reconciler: StackReconciler<R>, element target: R.TargetType) {
let element = reconciler.render(mountedAnchor: self)
reconciler.reconcile(
self,
with: element,
getElementType: { $0.type },
updateChild: {
$0.environmentValues = environmentValues
$0.model = AnyModel(erasing: element)
reconciler.updateWithRenderer(self)
},
mountChild: {
let child = MountedElement(model: $0, parent: self)
// child.mount(with: reconciler, to: target)
return child
}
)
}
private func update(model: AnyModel, with reconciler: StackReconciler<R>, element target: R.TargetType) {
guard model.bodyType != Never.Type.self else {
reconciler.updateWithRenderer(self)
let newChildren = (model.model as? ChildProvidingModel)?.children
switch (children, newChildren) {
case (nil, nil):
break // Nothing to do
case (nil, .some(let newChildren)):
let newElements = newChildren.map { Mounted(model: $0, parent: self) }
self.children = newElements
newElements.forEach { $0.mount(with: reconciler, to: target) }
case (.some, nil):
children?.forEach({ $0.update(with: reconciler) })
case (.some(let children), .some(let newChildren)):
for i in 0..<children.count {
guard i < newChildren.count else {
// Some childs were removed, unmount them later after the loop
break
}
let oldChild = children[i]
let newChild = newChildren[i]
let oldChildType = TypeInfo.typeConstructorName(oldChild._type)
let newChildType = TypeInfo.typeConstructorName(newChild.type)
if oldChildType == newChildType {
oldChild.environmentValues = environmentValues
oldChild.updateEnvironment()
oldChild.model = newChild
oldChild.update(with: reconciler)
} else {
oldChild.unmount(with: reconciler)
let newElement = Mounted(model: newChild, parent: self)
newElement.mount(with: reconciler, to: target)
self.children?[i] = newElement
}
// reconciler.reconcile(
// children[i],
// with: newChildren[i],
// getElementType: {$0.type},
// updateChild: {
// $0.environmentValues = self.environmentValues
// $0.updateEnvironment()
// $0.model = newChildren[i]
// $0.update(with: reconciler)
// }, mountChild: {
// MountedElement(model: $0, parent: self)
// })
}
if children.count > newChildren.count {
for i in newChildren.count..<children.count {
children[i].unmount(with: reconciler)
}
self.children?.removeLast(children.count - newChildren.count)
} else if newChildren.count > children.count {
var newElements: [Mounted] = []
for i in children.count..<newChildren.count {
let new = Mounted(model: newChildren[i], parent: self)
new.mount(with: reconciler, to: target)
newElements.append(new)
}
self.children?.append(contentsOf: newElements)
}
}
children?.forEach({
$0.environmentValues = environmentValues
$0.updateEnvironment()
$0.update(with: reconciler)
})
if let modifier = model.model as? ApplyableModel {
modifier.applyModifier({
reconciler.renderer.apply($0, to: target)
})
}
return
}
let element = reconciler.render(mountedModel: self)
if let modifier = element as? ApplyableModel {
modifier.applyModifier({
reconciler.renderer.apply($0, to: target)
})
}
reconciler.reconcile(
self,
with: element,
getElementType: { $0.type },
updateChild: {
$0.environmentValues = self.environmentValues
$0.model = AnyModel(erasing: element)
$0.update(with: reconciler)
},
mountChild: {
let child = MountedElement(model: $0, parent: self)
// child.mount(with: reconciler, to: target)
return child
}
)
}
func unmount(with reconciler: StackReconciler<R>) {
children?.forEach( { $0.unmount(with: reconciler) } )
reconciler.unmountFromRenderer(self)
}
// MARK: Storage
/// A type erased storage for `@State` values
var store: [Any] = []
/// A store for all subscriptions
var subscriptions: [AnyCancellable] = []
var environmentValues: EnvironmentValues
func updateEnvironment() {
switch mounted {
case .experience(let e):
environmentValues.inject(into: &experience.experience, e.type)
case .model(let m):
environmentValues.inject(into: &model.model, m.type)
case .anchor(let a):
environmentValues.inject(into: &anchor.anchor, a.type)
}
}
}
extension EnvironmentValues {
mutating func inject(into element: inout Any, _ type: Any.Type) {
guard let info = TypeInfo.typeInfo(of: type) else { return }
// Extract the view from the AnyView for modification, apply Environment changes:
if let container = element as? ModifierContainer {
container.environmentModifier?.modifyEnvironment(&self)
}
// Inject @Environment values
// swiftlint:disable force_cast
// `DynamicProperty`s can have `@Environment` properties contained in them,
// so we have to inject into them as well.
for dynamicProp in info.properties.filter({ $0.type is DynamicProperty.Type }) {
guard let propInfo = TypeInfo.typeInfo(of: dynamicProp.type) else { return }
var propWrapper = dynamicProp.get(from: element) as! DynamicProperty
for prop in propInfo.properties.filter({ $0.type is EnvironmentReader.Type }) {
var wrapper = prop.get(from: propWrapper) as! EnvironmentReader
wrapper.setContent(from: self)
prop.set(value: wrapper, on: &propWrapper)
}
dynamicProp.set(value: propWrapper, on: &element)
}
for prop in info.properties.filter({ $0.type is EnvironmentReader.Type }) {
var wrapper = prop.get(from: element) as! EnvironmentReader
wrapper.setContent(from: self)
prop.set(value: wrapper, on: &element)
}
// swiftlint:enable force_cast
}
}
extension TypeInfo {
/// Extract all `DynamicProperty` from a type, recursively.
/// This is necessary as a `DynamicProperty` can be nested.
/// `EnvironmentValues` can also be injected at this point.
func dynamicProperties(
_ environment: inout EnvironmentValues,
source: inout Any
) -> [PropertyInfo] {
var dynamicProps = [PropertyInfo]()
for prop in properties where prop.type is DynamicProperty.Type {
dynamicProps.append(prop)
guard let propInfo = TypeInfo.typeInfo(of: prop.type) else { continue }
environment.inject(into: &source, prop.type)
var extracted = prop.get(from: source)
dynamicProps.append(
contentsOf: propInfo.dynamicProperties(
&environment,
source: &extracted
)
)
// swiftlint:disable:next force_cast
var extractedDynamicProp = extracted as! DynamicProperty
extractedDynamicProp.update()
prop.set(value: extractedDynamicProp, on: &source)
}
return dynamicProps
}
} |
import { Address } from "@/app/staff/utils/orders";
import AddressAutoComplete from "@/components/Form/AutoCompleteInput";
import {
District,
SpecificAddress,
Ward,
getDistrictsByProvince,
getProvinces,
getWardsByDistrictAndProvince,
} from "@/libs/address";
import { removeVietnameseTones } from "@/utils/helper";
import { faCircleXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Input } from "antd";
import { KeyboardEventHandler, useState } from "react";
const provinces = getProvinces();
export default function AddressInput({
value,
handleChange,
className,
includeSpecificAddress = true,
rowLayoutOnSmallView = false,
}: {
value: Address;
handleChange: (newAddress: Address) => void;
className?: string;
includeSpecificAddress?: boolean;
rowLayoutOnSmallView?: boolean;
}) {
const [districts, setDistricts] = useState<District[]>([]);
const [wards, setWards] = useState<Ward[]>([]);
const [specificAddresses, setSpecificAddresses] = useState<SpecificAddress[]>(
[]
);
const handleChangeProvince = (province: string) => {
setDistricts(getDistrictsByProvince(province));
setWards([]);
setSpecificAddresses([]);
handleChange({ province, district: "", ward: "", name: "", id: "" });
};
const handleChangeDistrict = (district: string) => {
setWards(getWardsByDistrictAndProvince(district, value.province!));
setSpecificAddresses([]);
handleChange({ district, ward: "", name: "", id: "" });
};
const handleChangeWard = (ward: string) => {
setSpecificAddresses([]);
handleChange({ ward, name: "", id: "" });
};
const handleEnterSpecificAddress: KeyboardEventHandler = async (e) => {
if (e.key === "Enter") {
e.preventDefault();
const res = await fetch(
"/api/address/search?" +
new URLSearchParams({
province: value.province ? value.province : "",
district: value.district ? value.district : "",
ward: value.ward ? value.ward : "",
specificAddress: value.name ? value.name : "",
})
);
const response = await res.json();
if (res.status === 200) {
setSpecificAddresses(response.data);
}
}
};
const filterOption = (
inputValue: string,
option: { value: string; label: string }
) => {
return (
removeVietnameseTones(option!.value)
.toUpperCase()
.indexOf(removeVietnameseTones(inputValue).toUpperCase()) !== -1
);
};
return (
<div className={className}>
<div className="flex flex-col gap-4">
<div
className={`flex ${
rowLayoutOnSmallView ? "flex-row" : "flex-col"
} sm:flex-col gap-4`}
>
<AddressAutoComplete
label="Tỉnh/Thành Phố"
placeholder="Tỉnh/Thành Phố"
required={true}
value={value.province}
options={provinces}
onChange={handleChangeProvince}
filterOption={filterOption}
/>
<AddressAutoComplete
label="Quận/Huyện"
placeholder="Quận/Huyện"
required={true}
value={value.district}
options={districts}
onChange={handleChangeDistrict}
filterOption={filterOption}
/>
<AddressAutoComplete
label="Xã/Phường"
placeholder="Xã/Phường"
required={true}
value={value.ward}
options={wards}
onChange={handleChangeWard}
filterOption={filterOption}
/>
</div>
{includeSpecificAddress && (
<AddressAutoComplete
label="Địa Chỉ Cụ Thể"
placeholder="Địa Chỉ Cụ Thể"
required={true}
value={value.name}
options={specificAddresses}
disabled={!value.province || !value.district || !value.ward}
filterOption={filterOption}
onSearch={(address) => handleChange({ name: address, id: "" })}
onSelect={(address, option) => {
handleChange({ name: address, id: option.placeId });
}}
onKeyDown={handleEnterSpecificAddress}
>
<Input
size="large"
allowClear={{
clearIcon: <FontAwesomeIcon icon={faCircleXmark} />,
}}
/>
</AddressAutoComplete>
)}
</div>
</div>
);
} |
# cython: profile=True
##
# S. Rychkov, S. El-Showk, May-June 2013
# File contains prec_float and prec_interval classes : cython wrappers for mpfr_t and mpfi_t
# with overloaded arithmetic operations
##
# Edit by Carlos Cardona 2022
from libc.stdlib cimport malloc, free
import utils.stats as stats
def isinteger(a):
return (isinstance(a,int) or isinstance(a,long))
def zeros(size,prec):
return [ prec_float(0,prec=prec) for i in range(size)]
cpdef prec_float sqrt(prec_float x):
cdef prec_float ret
ret = prec_float (0, prec = <int>mpfr_get_prec (x.data))
mpfr_sqrt(ret.data, x.data, MPFR_RNDD)
return ret
cpdef double to_double(prec_float x):
return mpfr_get_d(x.data,MPFR_RNDD)
# used to unpickle a prec float
def make_prec_float(val, prec):
return prec_float(val, prec=prec)
#################### BEGIN --- CLASS ------prec_float #############################
cdef class prec_float:
def __cinit__(self, value, int prec = 212):
"""initialize an mpfr float with precision prec, from integer, double or """
# not working for some reason
#if prec < 0:
# raise ValueError("precision must be specified")
self.prec=prec
mpfr_init2(self.data, self.prec)
if isinstance (value, int):
mpfr_set_si(self.data, value,MPFR_RNDD)
elif isinstance(value, str):
# mpfr_set_str(self.data, value, 10, MPFR_RNDD)
bytes_str=value.encode('ascii') # Carlos edit
mpfr_set_str(self.data, bytes_str, 10, MPFR_RNDD)
elif isinstance(value, float):
mpfr_set_d(self.data, value,MPFR_RNDD)
elif isinstance(value, prec_float):
typed_value = <prec_float>value
mpfr_set(self.data, typed_value.data, MPFR_RNDD)
else:
raise TypeError("Prec_float can be initialized from int, str, double, or prec_float")
stats.pf_init +=1
stats.pf_mem += sizeof(mpfr_t)
def __dealloc__(self):
mpfr_clear(self.data)
# for some reason we can't access this this way
stats.pf_del +=1
stats.pf_free += sizeof(mpfr_t)
## Overloaded functions
def __neg__(prec_float self):
"""Sign flip"""
ret=prec_float(0, prec = self.prec)
mpfr_neg(ret.data, self.data, MPFR_RNDD)
return ret
def __add__(prec_float self, prec_float other):
cdef prec_float ret
ret=prec_float(0, prec=self.prec)
mpfr_add(ret.data, self.data, other.data, MPFR_RNDD)
stats.pf_adds += 1
return ret
def __sub__(prec_float self, prec_float other):
cdef prec_float ret
ret=prec_float(0, prec=self.prec)
mpfr_sub(ret.data, self.data, other.data, MPFR_RNDD)
return ret
def __mul__(prec_float self, prec_float other):
cdef prec_float ret
ret=prec_float(0, prec=self.prec)
mpfr_mul(ret.data, self.data, other.data, MPFR_RNDD)
stats.pf_mults += 1
return ret
# def __div__(prec_float self, prec_float other):
def __truediv__(prec_float self, prec_float other): # Carlos edit
cdef prec_float ret
ret=prec_float(0, prec=self.prec)
mpfr_div(ret.data, self.data, other.data, MPFR_RNDD)
return ret
def __pow__(prec_float self, prec_float other, z):
cdef prec_float ret
ret=prec_float(0, prec=self.prec)
mpfr_pow(ret.data, self.data, other.data, MPFR_RNDD)
return ret
def log(prec_float self):
cdef prec_float ret
ret=prec_float(0, prec=self.prec)
mpfr_log(ret.data, self.data, MPFR_RNDD)
return ret
def exp(prec_float self):
cdef prec_float ret
ret=prec_float(0, prec=self.prec)
mpfr_exp(ret.data, self.data, MPFR_RNDD)
return ret
def sqrt(prec_float self):
cdef prec_float ret
ret = prec_float(0, prec = self.prec)
mpfr_sqrt(ret.data, self.data, MPFR_RNDD)
return ret
def abs(prec_float self):
"""abs value"""
ret=prec_float(0, prec = self.prec)
mpfr_abs(ret.data, self.data, MPFR_RNDD)
return ret
# DON'T USE THESE - BUGGY
# def __iadd__(prec_float self, prec_float other):
# mpfr_add(self.data, self.data, other.data, MPFR_RNDD)
# def __isub__(prec_float self, prec_float other):
# mpfr_sub(self.data, self.data, other.data, MPFR_RNDD)
# def __imul__(prec_float self, prec_float other):
# mpfr_mul(self.data, self.data, other.data, MPFR_RNDD)
# def __idiv__(prec_float self, prec_float other):
# mpfr_div(self.data, self.data, other.data, MPFR_RNDD)
def __richcmp__(prec_float self, prec_float value, int cmptype):
"""comparison
op cmptype
< 0
== 2
> 4
<= 1
!= 3
>= 5"""
cdef int cmp
cmp = mpfr_cmp(self.data, value.data)
if cmptype == 0:
if cmp < 0: return True
else: return False
if cmptype == 2:
if cmp == 0: return True
else: return False
if cmptype == 4:
if cmp > 0: return True
else: return False
if cmptype == 1:
if cmp <= 0: return True
else: return False
if cmptype == 3:
if cmp != 0: return True
else: return False
if cmptype == 5:
if cmp >= 0: return True
else: return False
## Printing functions
def __str__(self):
bs= 2*self.prec # grossly overkill
cdef char* buf = <char*> malloc(bs * sizeof(char))
mpfr_sprintf(buf, "%.Re", self.data)
#return str(buf) # Carlos edit
return buf.decode('ascii')
def __bytes__(self):
bs= 2*self.prec # grossly overkill
cdef char* buf = <char*> malloc(bs * sizeof(char))
mpfr_sprintf(buf, "%.Re", self.data)
return buf # Carlos edit
def __repr__(self):
return self.__str__()
def __reduce__(self):
pstr=self.__str__()
#ret=(prec_float.__init__, pstr, self.prec)
return (make_prec_float, (pstr, self.prec))
def bufrepr(self, buf):
mpfr_sprintf(<char*>buf, "%.Re", self.data)
return buf
def assign_prec_float(self, value):
"""assigns the already initialized precision float with data from another precision float;
only works if the two precision floats have the same precision"""
if not isinstance(value, prec_float):
raise TypeError("assign_prec_float: attempted to assign value which is not prec_float")
typed_value = <prec_float>value # cast static typed copy to be able to access private fields data and prec
if not self.prec == typed_value.prec:
raise TypeError("assign_prec_float: attempted to assign value which has different precision")
mpfr_set(self.data, typed_value.data, MPFR_RNDD)
#################### BEGIN --- CLASS ------prec_interval #############################
cdef class prec_interval:
def __cinit__(self, v1, v2, int prec):
"""initialize an mpfi float with precision prec, from integer, double,
string or prec_float. If v1 is a string it should be either a number or
in the form '[a,b]' and then v2 is ignored. Otherwise v1 and v2 assumed to be of the same type."""
self.prec=prec
mpfi_init2(self.data, self.prec)
if isinstance (v1, int):
mpfi_interv_si(self.data,v1,v2)
elif isinstance(v1, str):
mpfi_set_str(self.data, v1, 10)
elif isinstance(v1, float):
mpfi_interv_d(self.data, v1, v2)
elif isinstance(v1, prec_float):
typed_value = <prec_float>v1
typed_value2 = <prec_float>v2
mpfi_interv_fr(self.data, typed_value.data, typed_value2.data)
else:
raise TypeError("Prec_interval can be initialized from int, str, double, or prec_float")
def __dealloc__(self):
mpfi_clear(self.data)
## Overloaded functions
def __neg__(prec_interval self):
"""Sign flip"""
ret=prec_interval(0, 0, prec = self.prec)
mpfi_neg(ret.data, self.data)
return ret
def __add__(prec_interval self, prec_interval other):
cdef prec_interval ret
ret=prec_interval(0, 0, prec=self.prec)
mpfi_add(ret.data, self.data, other.data)
return ret
def __sub__(prec_interval self, prec_interval other):
cdef prec_interval ret
ret=prec_interval(0, 0, prec=self.prec)
mpfi_sub(ret.data, self.data, other.data)
return ret
def __mul__(prec_interval self, prec_interval other):
cdef prec_interval ret
ret=prec_interval(0, 0, prec=self.prec)
mpfi_mul(ret.data, self.data, other.data)
return ret
def __div__(prec_interval self, prec_interval other):
cdef prec_interval ret
ret=prec_interval(0, 0, prec=self.prec)
mpfi_div(ret.data, self.data, other.data)
return ret
def __pow__(prec_interval self, prec_interval other, z):
cdef prec_interval ret
ret=prec_interval(0, 0, prec=self.prec)
mpfi_log(ret.data, self.data)
mpfi_mul(ret.data, ret.data, other.data)
mpfi_exp(ret.data, ret.data)
return ret
## unpacks into a pair of prec_float
def unpack(self):
x0 = prec_float(0,prec=self.prec)
x1 = prec_float(0,prec=self.prec)
mpfi_get_left(x0.data, self.data)
mpfi_get_right(x1.data, self.data)
return (x0,x1)
def length(self):
x0 = prec_float(0,prec=self.prec)
x1 = prec_float(0,prec=self.prec)
mpfi_get_left(x0.data, self.data)
mpfi_get_right(x1.data, self.data)
return x1 - x0
## Printing functions
def __str__(self):
return self.unpack().__str__()
def __repr__(self):
return self.__str__() |
# global
import abc
from typing import Optional, Union
# local
import ivy
class _ArrayWithLossesExperimental(abc.ABC):
def l1_loss(
self: Union[ivy.Array, ivy.NativeArray],
target: Union[ivy.Array, ivy.NativeArray],
/,
*,
reduction: Optional[str] = "mean",
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
ivy.Array instance method variant of ivy.l1_loss. This method simply wraps the
function, and so the docstring for ivy.l1_loss also applies to this method with
minimal changes.
Parameters
----------
self
input array.
target
input array containing the targeted values.
reduction
``'mean'``: The output will be averaged.
``'sum'``: The output will be summed.
``'none'``: No reduction will be applied to the output. Default: ``'mean'``.
out
optional output array, for writing the result to. It must have a shape that
the inputs broadcast to.
Returns
-------
ret
The L1 loss between the input array and the targeticted values.
Examples
--------
>>> x = ivy.array([1.0, 2.0, 3.0])
>>> y = ivy.array([0.7, 1.8, 2.9])
>>> z = x.l1_loss(y)
>>> print(z)
ivy.array(0.20000000000000004)
"""
return ivy.l1_loss(self._data, target, reduction=reduction, out=out)
def smooth_l1_loss(
self: ivy.Array,
target: Union[ivy.Array, ivy.NativeArray],
/,
*,
beta: Optional[float] = 1.0,
reduction: Optional[str] = "mean",
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
ivy.Array instance method variant of ivy. smooth_l1_loss. This method simply
wraps the function, and so the docstring for ivy.smooth_l1_loss also applies to
this method with minimal changes.
Parameters
----------
self
input array containing true labels.
target
input array containing targeted labels.
beta
A float specifying the beta value for
the smooth L1 loss. Default: 1.0.
reduction
Reduction method for the loss.
Options are 'none', 'mean', or 'sum'.
Default: 'mean'.
out
Optional output array, for writing the result to.
It must have a shape
that the inputs broadcast to.
Returns
-------
ret
The smooth L1 loss between the given labels.
Examples
--------
>>> x = ivy.array([1, 2, 3, 4])
>>> y = ivy.array([2, 2, 2, 2])
>>> z = x.smooth_l1_loss(y, beta=0.5)
>>> print(z)
ivy.array(0.8125)
"""
return ivy.smooth_l1_loss(
self._data, target, beta=beta, reduction=reduction, out=out
) |
/*
* dedupv1 - iSCSI based Deduplication System for Linux
*
* (C) 2008 Dirk Meister
* (C) 2009 - 2011, Dirk Meister, Paderborn Center for Parallel Computing
* (C) 2012 Dirk Meister, Johannes Gutenberg University Mainz
*
* This file is part of dedupv1.
*
* dedupv1 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.
*
* dedupv1 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 dedupv1. If not, see http://www.gnu.org/licenses/.
*/
#ifndef LOG_REPLAYER_H__
#define LOG_REPLAYER_H__
#include <core/dedup.h>
#include <base/locks.h>
#include <base/thread.h>
#include <core/idle_detector.h>
#include <core/log.h>
namespace dedupv1d {
/**
* The LogReplayer has the responsibility to replay log entries in background if any of the following
* two conditions are true:
* - The log is nearly full: Nearly full is usually seen as something like 70% of the log capacity
* - The system is idle and the log replaying is activated
*
* If the system detects and idle period and if the replay during idle time is not deactivated using the configuration system,
* the log replayer will replay event. When the idle period ends and the system has not been stopped before, the old state is
* restored.
*
* TODO (dmeister) Adapt the replay speed to the amount of idle ticks.
*/
class LogReplayer: public dedupv1::IdleTickConsumer {
DISALLOW_COPY_AND_ASSIGN(LogReplayer);
public:
/**
* stats of the log replayer
*/
enum log_replayer_state {
LOG_REPLAYER_STATE_CREATED,//!< LOG_REPLAYER_STATE_CREATED
LOG_REPLAYER_STATE_STARTED,
LOG_REPLAYER_STATE_RUNNING,//!< LOG_REPLAYER_STATE_RUNNING
LOG_REPLAYER_STATE_PAUSED, //!< LOG_REPLAYER_STATE_PAUSED
LOG_REPLAYER_STATE_STOPPED,//!< LOG_REPLAYER_STATE_STOPPED
LOG_REPLAYER_STATE_FAILED
//!< LOG_REPLAYER_STATE_FAILED
};
private:
/**
* Default number of elements replayed at one if system is idle
*/
static const uint32_t kDefaultMaxAreaSizeReplaySystemIdle_ = 4096;
/**
* Default number of elements replayed at one if system going full
*/
static const uint32_t kDefaultMaxAreaSizeReplayLogFull_ = 4096;
/**
* Reference to the log.
* Set during the startup
*/
dedupv1::log::Log* log_;
/**
* Reference to the idle detector
* Set during the startup, but maybe null if no idle system is used
*/
dedupv1::IdleDetector* idle_detector_;
/**
* log replay background thread
*/
dedupv1::base::Thread<bool> thread_;
/**
* State of the log replayer.
*/
volatile enum log_replayer_state state_;
/**
* State of the log replayer thread.
*/
volatile bool thread_state_;
/**
* Lock to protected shared variables of the log replayer, e.g. the stats
*/
dedupv1::base::MutexLock lock_;
/**
* Condition that is fired if the log replayer thread stops.
*/
dedupv1::base::Condition cond_;
/**
* Sleep time between in microseconds.
* Default: 50ms
*/
uint32_t throttle_;
/**
* Sleep time in microseconds when the log is nearly full
* Default: 0ms
*/
uint32_t nearly_full_throttle_;
/**
* Sleep time between checks
* Default: 1s
*/
uint32_t check_interval_;
/**
* Stores the state of the system before the idle period.
* LOG_REPLAYER_STATE_CREATED denotes a non-set value
*/
enum log_replayer_state state_before_idle_;
/**
* iff true, the log is currently replaying items because of one of several reasons:
* idleness, unpauses log replay, log full.
*/
bool is_replaying_;
/**
* lock to protect is_replaying_
*/
dedupv1::base::MutexLock is_replaying_lock_;
/**
* Maxmimum Events to be replayed at once if system is idle
*/
uint32_t max_area_size_replay_system_idle_;
/**
* Maxmimum Events to be replayed at once if log is going full
*/
uint32_t max_area_size_replay_log_full_;
/**
* Loop method that is called in a background thread.
* @return
*/
bool Loop();
/**
* the actual loop contents
*/
bool DoLoop();
/**
* replays a single log event.
*
* @param num_elements Number of Elements to replay
*/
dedupv1::log::log_replay_result Replay(uint32_t num_elements = 1);
/**
* Tries to start the log replay.
* Does nothing if the log is already being replayed
*/
bool TryStartReplay();
/**
* Tries to stop the log replay.
* Does nothing if the log is already being replayed
*/
bool TryStopReplay();
public:
/**
* Constructor.
* @return
*/
LogReplayer();
/**
* Destructor
* @return
*/
virtual ~LogReplayer();
/**
*
* @param log
* @param idle_detector reference to the idle detector. May be null. If a idle detector is given, the client has to ensure
* that the detector lives longer than the log replayer.
* @return
*/
bool Start(dedupv1::log::Log* log, dedupv1::IdleDetector* idle_detector);
/**
* Runs the log replayer
* @return
*/
bool Run();
/**
* Stops the replayer
* @param stop_context
* @return
*/
bool Stop(const dedupv1::StopContext& stop_context);
/**
* Pauses the log replayer.
* @return
*/
bool Pause();
/**
* Resumes the log replayer
* @return
*/
bool Resume();
/**
* Configures the log replayer
*
* Available options:
* - throttle.default: uint32_t
* - throttle.nearly-full: uint32_t
* - area-size-system-idle: StorageUnit
* - area-size-log-full: StorageUnit
*
* @param option_name
* @param option
* @return
*/
bool SetOption(const std::string& option_name, const std::string& option);
/**
* Returns the name of the current state
* @return
*/
const char* state_name();
/**
* Returns the log of the replayer
* @return
*/
inline dedupv1::log::Log* log();
/**
* Returns the state of the log replayer
* @return
*/
inline enum log_replayer_state state() const;
/**
* Called then the system is detected to be idle
*/
void IdleStart();
/**
* Called when the system stopped to be idle
*/
void IdleEnd();
inline bool is_replaying() const;
inline bool is_failed() const;
#ifdef DEDUPV1D_TEST
void ClearData();
#endif
};
bool LogReplayer::is_failed() const {
return state_ == LOG_REPLAYER_STATE_FAILED ||
(state_ == LOG_REPLAYER_STATE_PAUSED && !thread_state_) ||
(state_ == LOG_REPLAYER_STATE_RUNNING && !thread_state_);
}
dedupv1::log::Log* LogReplayer::log() {
return this->log_;
}
LogReplayer::log_replayer_state LogReplayer::state() const {
return this->state_;
}
bool LogReplayer::is_replaying() const {
return is_replaying_;
}
}
#endif // LOG_REPLAYER_H__ |
import styled from "styled-components";
import SectionHeader from "./SectionHeader";
// import useFakeFixtures from "../../hooks/fake/useFakeFixtures";
import useColor from "../../hooks/useColor";
import { mix } from "polished";
import SubTitle from "../common/SubTitle";
import Loading from "../common/Loading";
import { LazyLoadImage } from "react-lazy-load-image-component";
import "react-lazy-load-image-component/src/effects/blur.css";
import useLeagueId from "../../hooks/useLeagueId";
import useFixtures from "../../hooks/useFixtures";
interface MatchProps {
$color: string;
}
const LatestMatchesWrapper = styled.div`
flex: 1;
padding: 0.5rem 1rem;
border-radius: ${(props) => props.theme.border.radius};
background-color: ${(props) => props.theme.colors.secondBackground};
min-width: 250px;
`;
const MatchWrapper = styled.div`
width: 100%;
display: flex;
gap: 1rem;
margin-top: 1rem;
@media (max-width: 950px) {
flex-direction: column;
}
`;
const Match = styled.div<MatchProps>`
flex: 1;
padding: 1rem 1rem;
border-radius: ${(props) => props.theme.border.radius};
background-color: ${(props) => mix(0.8, "#808080", props.$color)};
`;
const ScoreWrapper = styled.div`
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
`;
const LogoWrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 1rem;
gap: 0.5rem;
text-align: center;
`;
const Logo = styled(LazyLoadImage)`
width: 70%;
height: auto;
min-width: 50px;
max-width: 100px;
`;
const TeamName = styled.p`
font-size: 0.8rem;
`;
const Score = styled.div`
padding: 8px;
border-radius: ${(props) => props.theme.border.radius};
background-color: ${(props) => props.theme.colors.background};
min-width: 50px;
text-align: center;
`;
const LatestMatches = () => {
const color = useColor();
const leagueId = useLeagueId();
// const {
// fakeLatestMatchesQuery: { data: matches, isLoading, isError },
// } = useFakeFixtures();
const {
bannerLatestMatchesQuery: { data: matches, isLoading, isError },
} = useFixtures(leagueId);
return (
<LatestMatchesWrapper>
<SectionHeader title="최근 경기" src={`/league/${leagueId}/schedule`} />
{isError && <div>Error</div>}
{isLoading && <Loading />}
{isLoading ||
(matches && (
<>
<MatchWrapper>
<Match $color={color || "#777"}>
<SubTitle subtitle={matches[0].league.round || ""} />
<ScoreWrapper>
<LogoWrapper>
<Logo effect="blur" src={matches[0].teams.home.logo || "Not-Name"} alt="logo" />
<TeamName>{matches[0].teams.home.name || "Not-Name"}</TeamName>
</LogoWrapper>
<Score>{`${matches[0].goals.home} : ${matches[0].goals.away}`}</Score>
<LogoWrapper>
<Logo effect="blur" src={matches[0].teams.away.logo || "Not-Name"} alt="logo" />
<TeamName>{matches[0].teams.away.name || "Not-Name"}</TeamName>
</LogoWrapper>
</ScoreWrapper>
</Match>
<Match $color={color || "#777"}>
<SubTitle subtitle={matches[1]?.league.round || ""} />
<ScoreWrapper>
<LogoWrapper>
<Logo effect="blur" src={matches[1]?.teams.home.logo || "Not-Name"} alt="logo" />
<TeamName>{matches[1]?.teams.home.name || "Not-Name"}</TeamName>
</LogoWrapper>
<Score>{`${matches[1]?.goals.home || 0} : ${matches[1]?.goals.away || 0}`}</Score>
<LogoWrapper>
<Logo effect="blur" src={matches[1]?.teams.away.logo || "Not-Name"} alt="logo" />
<TeamName>{matches[1]?.teams.away.name || "Not-Name"}</TeamName>
</LogoWrapper>
</ScoreWrapper>
</Match>
</MatchWrapper>
</>
))}
</LatestMatchesWrapper>
);
};
export default LatestMatches; |
/* render.c: functions for rendering a peg solitaire game
* Copyright (C) 2018 Juhani Numminen
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "render.h"
#include <gtk/gtk.h>
#include <librsvg/rsvg.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "callbacks.h"
#include "data.h"
#include "game.h"
#include "i18n.h"
#include "share.h"
#define GAME_NOT_DRAGGING -1
static int game_dragging_at_x = GAME_NOT_DRAGGING;
static int game_dragging_at_y = GAME_NOT_DRAGGING;
static bool button_down = false;
static GdkPoint dragging_peg = {0, 0};
static GdkCursor *hand_closed_cursor = NULL;
static GdkCursor *hand_open_cursor = NULL;
static GdkCursor *default_cursor = NULL;
static cairo_pattern_t *hole_pattern = NULL;
static cairo_pattern_t *peg_pattern = NULL;
static double offset_x = 0, offset_y = 0;
static double tile_size = 0;
static GdkCursor *try_cursor_names(const char *names[]) {
GdkDisplay *display = gtk_widget_get_display(pegSolitaireWindow);
GdkCursor *cursor = NULL;
for (int i = 0; names[i] && !cursor; i++)
cursor = gdk_cursor_new_from_name(display, names[i]);
if (!cursor)
g_warning(_("The \"%s\" cursor is not available"), names[0]);
return cursor;
}
void init_cursors(void) {
default_cursor = try_cursor_names((const char *[]){"default", NULL});
hand_closed_cursor =
try_cursor_names((const char *[]){"closedhand", "grabbing", NULL});
hand_open_cursor =
try_cursor_names((const char *[]){"openhand", "grab", NULL});
}
static void set_cursor(GdkCursor *cursor) {
gdk_window_set_cursor(gtk_widget_get_window(GTK_WIDGET(boardDrawingArea)),
cursor);
}
static GdkPoint widget_coords_to_cell(int x, int y) {
return (GdkPoint){(x - offset_x) / tile_size, (y - offset_y) / tile_size};
}
static RsvgHandle *load_svg(const char *str) {
GError *err = NULL;
RsvgHandle *svg =
rsvg_handle_new_from_data((const guint8 *)str, strlen(str), &err);
if (err) {
GtkDialog *dialog = GTK_DIALOG(gtk_message_dialog_new(
NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
_("Something went wrong.\n"
"Could not load internal image data:\n"
"%s"),
err->message));
gtk_window_set_title(GTK_WINDOW(dialog), _("Peg Solitaire"));
gtk_dialog_run(dialog);
exit(1);
}
return svg;
}
static cairo_pattern_t *rsvg_to_pattern(RsvgHandle *svg) {
RsvgDimensionData svg_dimensions;
rsvg_handle_get_dimensions(svg, &svg_dimensions);
cairo_surface_t *surface = cairo_image_surface_create(
CAIRO_FORMAT_ARGB32, svg_dimensions.width, svg_dimensions.height);
cairo_t *cr = cairo_create(surface);
rsvg_handle_render_cairo(svg, cr);
cairo_pattern_t *pattern = cairo_pattern_create_for_surface(surface);
cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
cairo_matrix_t scale;
cairo_matrix_init_scale(&scale, svg_dimensions.width,
svg_dimensions.height);
cairo_pattern_set_matrix(pattern, &scale);
cairo_destroy(cr);
cairo_surface_destroy(surface);
g_object_unref(svg);
return pattern;
}
void game_load_resources(void) {
hole_pattern = rsvg_to_pattern(load_svg(hole_svg));
peg_pattern = rsvg_to_pattern(load_svg(peg_svg));
}
void game_unload_resources(void) {
cairo_pattern_destroy(peg_pattern);
cairo_pattern_destroy(hole_pattern);
}
// Following functions are gtk callbacks and all their parameters are required.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
gboolean drawarea_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data) {
int width = gtk_widget_get_allocated_width(widget);
int height = gtk_widget_get_allocated_height(widget);
double shorter_side = fmin(width, height);
offset_x = 0.5 * (width - shorter_side);
offset_y = 0.5 * (height - shorter_side);
tile_size = shorter_side / game_board_size;
cairo_translate(cr, offset_x, offset_y);
cairo_scale(cr, tile_size, tile_size);
cairo_set_source(cr, hole_pattern);
for (int y = 0; y < game_board_size; y++)
for (int x = 0; x < game_board_size; x++)
if (game_board_mask[y][x])
cairo_rectangle(cr, x, y, 1, 1);
cairo_fill(cr);
cairo_set_source(cr, peg_pattern);
for (int y = 0; y < game_board_size; y++)
for (int x = 0; x < game_board_size; x++)
if (game_board[y][x])
cairo_rectangle(cr, x, y, 1, 1);
cairo_fill(cr);
if (game_dragging_at_x != GAME_NOT_DRAGGING) {
cairo_translate(cr, (game_dragging_at_x - offset_x) / tile_size - 0.5,
(game_dragging_at_y - offset_y) / tile_size - 0.5);
cairo_set_source(cr, peg_pattern);
cairo_rectangle(cr, 0, 0, 1, 1);
cairo_fill(cr);
}
return FALSE;
}
gboolean drawarea_motion(GtkWidget *widget, GdkEventMotion *event,
gpointer user_data) {
GdkPoint cell = widget_coords_to_cell(event->x, event->y);
if (button_down) {
game_dragging_at_x = event->x;
game_dragging_at_y = event->y;
gtk_widget_queue_draw(widget);
} else if (game_is_peg_at(cell)) {
set_cursor(hand_open_cursor);
} else {
set_cursor(default_cursor);
}
return FALSE;
}
gboolean drawarea_button_press(GtkWidget *widget, GdkEventButton *event,
gpointer user_data) {
if (event->button == 1 && !button_down /* && !is_game_end()*/) {
GdkPoint cell = widget_coords_to_cell(event->x, event->y);
if (!game_is_peg_at(cell))
return FALSE;
game_dragging_at_x = event->x;
game_dragging_at_y = event->y;
set_cursor(hand_closed_cursor);
dragging_peg = cell;
button_down = true;
game_toggle_cell(cell);
gtk_widget_queue_draw(widget);
}
return FALSE;
}
gboolean drawarea_button_release(GtkWidget *widget, GdkEventButton *event,
gpointer user_data) {
if (event->button == 1 && button_down) {
button_down = false;
game_dragging_at_x = GAME_NOT_DRAGGING;
GdkPoint dest = widget_coords_to_cell(event->x, event->y);
// Either execute the move or put the peg back where we started.
if (game_move(dragging_peg, dest)) {
set_cursor(hand_open_cursor);
update_statusbar();
if (is_game_end()) {
gtk_label_set_text(statusMessageLabel, game_cheese());
}
} else {
game_toggle_cell(dragging_peg);
}
gtk_widget_queue_draw(widget);
}
return FALSE;
}
#pragma GCC diagnostic pop |
<!DOCTYPE html>
<html>
<head>
<title>Using a Function for Promises</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
const apple = new Image(),
orange = new Image(),
carrot = new Image(),
pumpkin = new Image(),
eggplant = new Image();
function loadImage(img, src) {
img.src = src;
return img.decode();
}
loadImage(apple, "apple.png")
.then(() => loadImage(orange, "orange.png"))
.then(() => loadImage(carrot, "carrot.png"))
.then(() => loadImage(pumpkin, "pumpkin.png"))
.then(() => loadImage(eggplant, "eggplant.png"))
.then(() => {
$("body").append($(apple), $(orange), $(carrot), $(pumpkin), $(eggplant));
})
.catch(() => {
$("body").append($("<p>The image cannot be loaded.</p>"));
})
});
</script>
</body>
</html> |
/*
* @Author: lyf
* @Date: 2021-02-25 16:37:45
* @LastEditors: lyf
* @LastEditTime: 2021-12-13 15:07:57
* @Description: In User Settings Edit
* @FilePath: /js-css-case/src/examples-react/case3/index.tsx
*
* context
* 1. context的value值改变, 其子孙组建中 使用useContext的组建都会重新渲染(即使该组建被memo函数包裹, 即使该组建的props未改变)
* 2. 如下: context的value值有函数, 则该函数必须用useCallback包裹, 否则每次渲染都会生成新函数
*/
import React, { useState, useCallback, useMemo } from 'react';
import ShowX from './showX';
import ShowY from './showY';
import Show from './show';
import { useMutationObserver } from '@hooks/utils';
import Context from './constants';
const Case3 = () => {
const [time, setTime] = useState(Date.now());
const [state, setState] = useState({ x: 1, y: 1, m: 1 });
const microtask = useMutationObserver(() => {
console.log('microtask...');
});
const addX = useCallback(() => {
// 这种方式, 他在deps中必须有state
// const { y } = state
// setState((state) => ({ ...state, y: y + 1 }))
// 推荐如下方式, 不需要任何deps
setState(({ x, y, m }) => ({ x: x + 1, y, m }));
}, []);
const addY = useCallback(() => {
setState(({ x, y, m }) => ({ x, y: y + 1, m }));
}, []);
const addZ = useCallback(() => {
setTime(Date.now());
}, []);
const handleM = () => {
setState((state) => ({ ...state, m: state.m + 1 }));
};
const handleMicrotask = () => {
microtask();
Promise.resolve().then(() => {
console.log('handleMicrotask...');
});
setTimeout(() => {
console.log('handleMicrotask setTimeout...');
}, 0);
};
const value = useMemo(() => ({ ...state, addX, addY, addZ }), [state]);
return (
<Context.Provider value={value}>
time: {time}
<ShowX />
<ShowY />
<Show />
<button onClick={handleM}>加m</button>
<button onClick={handleMicrotask}>触发microtask</button>
</Context.Provider>
);
};
export default Case3; |
const app = require("../server");
const request = require("supertest");
const authenticateToken = require("../middlewares/authenticateToken");
const { UserRepository } = require("../repositories/user.repository");
const { reportRepository } = require("../repositories/report.repository");
jest.mock("jsonwebtoken");
jest.mock("../repositories/user.repository");
jest.mock("../repositories/report.repository");
jest.mock("../middlewares/authenticateToken", () =>
jest.fn().mockImplementation((req, res, next) => {
next();
})
);
describe("GET /api/reports/home", () => {
beforeEach(() => {
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_provider" };
next();
});
});
it("should return 500 for server errors", async () => {
UserRepository.retrieve.mockImplementation(() => {
const error = new Error("Unexpected error");
error.name = "UnknownError";
throw error;
});
const response = await request(app).get(`/api/reports/home`);
expect(response.status).toBe(500);
expect(response.body).toEqual(
"server encountered an unexpected condition that prevented it from fulfilling the request."
);
});
it("should return 404 for not found user", async () => {
UserRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app).get(`/api/reports/home`);
expect(response.status).toBe(404);
expect(response.body).toEqual(
"No data found at getAllReportsOfUser with id 123 ."
);
});
it("should return 404 when no reports found", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_provider" };
});
reportRepository.findReportsOfUser.mockImplementation(() => {
return [];
});
const response = await request(app).get(`/api/reports/home`);
expect(response.status).toBe(404);
expect(response.body).toEqual("No data found at getAllReportsOfUser .");
});
it("should return 200 and reports", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_provider" };
});
reportRepository.findReportsOfUser.mockImplementation(() => {
return [{ reportId: "1" }];
});
const response = await request(app).get(`/api/reports/home`);
expect(response.status).toBe(200);
expect(response.body).toEqual([{ reportId: "1" }]);
});
});
describe("GET /api/reports/past", () => {
beforeEach(() => {
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_provider" };
next();
});
});
it("should return 500 for server errors", async () => {
UserRepository.retrieve.mockImplementation(() => {
const error = new Error("Unexpected error");
error.name = "UnknownError";
throw error;
});
const response = await request(app).get(`/api/reports/past`);
expect(response.status).toBe(500);
expect(response.body).toEqual(
"server encountered an unexpected condition that prevented it from fulfilling the request."
);
});
it("should return 404 for not found user", async () => {
UserRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app).get(`/api/reports/past`);
expect(response.status).toBe(404);
expect(response.body).toEqual(
"No data found at getOldReportsOfUser with id 123 ."
);
});
it("should return 404 when no reports found", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_provider" };
});
reportRepository.findReportsOfUser.mockImplementation(() => {
return [];
});
const response = await request(app).get(`/api/reports/past`);
expect(response.status).toBe(404);
expect(response.body).toEqual("No data found at getOldReportsOfUser .");
});
it("should return 200 and reports", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_provider" };
});
reportRepository.findReportsOfUser.mockImplementation(() => {
return [{ reportId: "1" }];
});
const response = await request(app).get(`/api/reports/past`);
expect(response.status).toBe(200);
expect(response.body).toEqual([{ reportId: "1" }]);
});
});
describe("GET /api/reports/:id", () => {
beforeEach(() => {
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_provider" };
next();
});
});
it("should return 500 for server errors", async () => {
reportRepository.retrieve.mockImplementation(() => {
const error = new Error("Unexpected error");
error.name = "UnknownError";
throw error;
});
const response = await request(app).get(`/api/reports/1`);
expect(response.status).toBe(500);
expect(response.body).toEqual(
"server encountered an unexpected condition that prevented it from fulfilling the request."
);
});
it("should return 404 when no report found", async () => {
reportRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app).get(`/api/reports/1`);
expect(response.status).toBe(404);
expect(response.body).toEqual("No data found at getReport with id 1 .");
});
it("should return 403 when report is not assigned to user", async () => {
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", assignedUser: "456" };
});
const response = await request(app).get(`/api/reports/1`);
expect(response.status).toBe(403);
expect(response.body).toEqual(
"Access Denied you forbidden for this content."
);
});
it("should return 200 and report", async () => {
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", assignedUser: "123" };
});
const response = await request(app).get(`/api/reports/1`);
expect(response.status).toBe(200);
expect(response.body).toEqual({ reportId: "1", assignedUser: "123" });
});
});
describe("POST /api/reports", () => {
beforeEach(() => {
jest.clearAllMocks();
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_provider" };
next();
});
});
it("should return 500 for server errors", async () => {
UserRepository.retrieve.mockImplementation(() => {
const error = new Error("Unexpected error");
error.name = "UnknownError";
throw error;
});
const response = await request(app).post(`/api/reports`);
expect(response.status).toBe(500);
expect(response.body).toEqual(
"server encountered an unexpected condition that prevented it from fulfilling the request."
);
});
it("should return 404 when no user found", async () => {
UserRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app).post(`/api/reports`);
expect(response.status).toBe(404);
expect(response.body).toEqual(
"No data found at createReport with id 123 ."
);
});
it("should return 400 if user of service_provider try to create a report", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_provider" };
});
const response = await request(app).post(`/api/reports`);
expect(response.status).toBe(400);
expect(response.body).toEqual(
"Only service request users can submit reports."
);
});
it("should return 400 for form errors", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_request" };
});
reportRepository.create.mockImplementation(() => {
throw new Error("Form error");
});
const response = await request(app).post(`/api/reports`);
expect(response.status).toBe(400);
expect(response.body).toEqual(
"Please provide all required fields at createReport"
);
});
it("should return 400 for no service provider available", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_request" };
});
UserRepository.findNearbyAndByProfession.mockImplementation(() => {
return [];
});
const response = await request(app).post(`/api/reports`).send({
location: "location",
profession: "profession",
description: "description",
urgency: "low",
dateOfResolve: "24/12/2021",
range: 10,
});
expect(response.status).toBe(400);
expect(response.body).toEqual(
"No service provider available for this report. Please try again later."
);
});
});
describe("PUT /api/reports/updateDate/:id", () => {
beforeEach(() => {
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_request" };
next();
});
});
it("should return 500 for server errors", async () => {
UserRepository.retrieve.mockImplementation(() => {
const error = new Error("Unexpected error");
error.name = "UnknownError";
throw error;
});
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: "24/12/2024" });
expect(response.status).toBe(500);
expect(response.body).toEqual(
"server encountered an unexpected condition that prevented it from fulfilling the request."
);
});
it("should return 400 when no new date provided", async () => {
const response = await request(app).put(`/api/reports/updateDate/1`);
expect(response.status).toBe(400);
expect(response.body).toEqual(
"Please provide a new date and the report id"
);
});
it("should return 400 when the new date is invalid", async () => {
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: new Date("2000-12-24") });
expect(response.status).toBe(400);
expect(response.body).toEqual("The date must be in the future");
});
it("should return 404 when no user found with this token", async () => {
UserRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: new Date("2030-12-24") });
expect(response.status).toBe(404);
expect(response.body).toEqual(
"No data found at updateDateOfResolve with id 123 ."
);
});
it("should return 403 when a service provider user try to change the date", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "456", role: "service_provider" };
});
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: new Date("2030-12-24") });
expect(response.status).toBe(403);
expect(response.body).toEqual(
"Access Denied you forbidden for this content."
);
});
it("should return 404 when no report found", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_request" };
});
reportRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: new Date("2030-12-24") });
expect(response.status).toBe(404);
expect(response.body).toEqual(
"No data found at updateDateOfResolve with id 1 ."
);
});
it("should return 400 when the new date is equal to the old date", async () => {
UserRepository.retrieve.mockImplementation(() => {
return { userId: "123", role: "service_request" };
});
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", dateOfResolve: new Date("2030-12-24") };
});
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: new Date("2030-12-24") });
expect(response.status).toBe(400);
expect(response.body).toEqual(
"The new date must be different from the old date"
);
});
it("should return 400 when failed crud", async () => {
UserRepository.retrieve
.mockImplementationOnce(() =>
Promise.resolve({ userId: "123", role: "service_request" })
)
.mockImplementationOnce(() =>
Promise.resolve({
userId: "456",
role: "service_request",
reports: ["1"],
})
);
reportRepository.retrieve.mockImplementation((id) =>
Promise.resolve({
reportId: id,
assignedUser: "456",
dateOfResolve: new Date("2032-12-24"),
})
);
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: new Date("2030-12-24").toISOString() });
expect(response.status).toBe(400);
expect(response.body).toEqual("Failed to update the report");
});
it("should return 200 when the date is updated", async () => {
UserRepository.retrieve.mockResolvedValue({
userId: "123",
role: "service_request",
});
reportRepository.retrieve.mockResolvedValue({
reportId: "1",
assignedUser: "456",
dateOfResolve: new Date("2025-12-24"),
});
UserRepository.retrieve.mockResolvedValue({
userId: "456",
role: "service_request",
reports: ["1"],
});
reportRepository.retrieve.mockResolvedValue({
reportId: "1",
assignedUser: "456",
dateOfResolve: new Date("2025-12-24"),
});
reportRepository.updateDateOfResolve.mockResolvedValue(true);
const response = await request(app)
.put(`/api/reports/updateDate/1`)
.send({ newDateOfResolve: new Date("2030-12-24").toISOString() });
expect(response.status).toBe(200);
expect(response.body).toEqual("Report updated");
});
});
describe("PUT /api/reports/updateStatus/:id", () => {
beforeEach(() => {
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_provider" };
next();
});
});
it("should return 500 for server errors", async () => {
reportRepository.retrieve.mockImplementation(() => {
const error = new Error("Unexpected error");
error.name = "UnknownError";
throw error;
});
const response = await request(app)
.put(`/api/reports/updateStatus/1`)
.send({ newStatus: "in_progress" });
// expect(response.status).toBe(500);
expect(response.body).toEqual(
"server encountered an unexpected condition that prevented it from fulfilling the request."
);
});
it("should return 400 when no new status provided", async () => {
const response = await request(app).put(`/api/reports/updateStatus/1`);
expect(response.status).toBe(400);
expect(response.body).toEqual(
"Please provide the status and the report id"
);
});
it("should return 403 when a service_request user try to change the status", async () => {
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_request" };
next();
});
const response = await request(app)
.put(`/api/reports/updateStatus/1`)
.send({ newStatus: "in_progress" });
expect(response.status).toBe(403);
expect(response.body).toEqual(
"Access Denied you forbidden for this content."
);
});
it("should return 404 when no report found", async () => {
reportRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app)
.put(`/api/reports/updateStatus/1`)
.send({ newStatus: "in_progress" });
expect(response.status).toBe(404);
expect(response.body).toEqual("No data found at updateStatus with id 1 .");
});
it("should return 400 when the new status is invalid", async () => {
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", status: "pending" };
});
const response = await request(app)
.put(`/api/reports/updateStatus/1`)
.send({ newStatus: "invalid" });
expect(response.status).toBe(400);
expect(response.body).toEqual("Invalid status");
});
it("should return 400 when the new status is equal to the old status", async () => {
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", status: "pending", assignedUser: "123" };
});
const response = await request(app)
.put(`/api/reports/updateStatus/1`)
.send({ newStatus: "pending" });
expect(response.status).toBe(400);
expect(response.body).toEqual(
"The new status must be different from the old status"
);
});
it("should return 400 when failed crud", async () => {
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", status: "pending", assignedUser: "123" };
});
reportRepository.updateStatus.mockImplementation(null);
const response = await request(app)
.put(`/api/reports/updateStatus/1`)
.send({ newStatus: "in_progress" });
expect(response.status).toBe(400);
expect(response.body).toEqual("Failed to update the report");
});
it("should return 200 when the status is updated", async () => {
reportRepository.retrieve.mockResolvedValue({
reportId: "1",
status: "pending",
assignedUser: "123",
});
reportRepository.updateStatus.mockResolvedValue(true);
const response = await request(app)
.put(`/api/reports/updateStatus/1`)
.send({ newStatus: "in_progress" });
expect(response.status).toBe(200);
expect(response.body).toEqual("Report status updated");
});
});
describe("DELETE /api/reports", () => {
beforeEach(() => {
authenticateToken.mockImplementation((req, res, next) => {
req.user = { userId: "123", role: "service_request" };
next();
});
});
it("should return 500 for server errors", async () => {
reportRepository.retrieve.mockImplementation(() => {
const error = new Error("Unexpected error");
error.name = "UnknownError";
throw error;
});
const response = await request(app).delete(`/api/reports`).send({ id: 1 });
expect(response.status).toBe(500);
expect(response.body).toEqual(
"server encountered an unexpected condition that prevented it from fulfilling the request."
);
});
it("should return 400 for no id provided", async () => {
const response = await request(app).delete(`/api/reports`);
expect(response.status).toBe(400);
expect(response.body).toEqual("Please provide the report id");
});
it("should return 404 when no report found with this id", async () => {
reportRepository.retrieve.mockImplementation(() => {
return null;
});
const response = await request(app).delete(`/api/reports`).send({ id: 1 });
expect(response.status).toBe(404);
expect(response.body).toEqual("No data found at deleteReport with id 1 .");
});
it("should return 403 when a service_request user try to delete report that he didnt submit", async () => {
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", reportByUser: "456" };
});
const response = await request(app).delete(`/api/reports`).send({ id: 1 });
expect(response.status).toBe(403);
expect(response.body).toEqual(
"Access Denied you forbidden for this content."
);
});
it("should return 400 when failed crud", async () => {
reportRepository.retrieve.mockImplementation(() => {
return { reportId: "1", reportByUser: "123" };
});
reportRepository.delete.mockImplementation(() => {
return null;
});
const response = await request(app).delete(`/api/reports`).send({ id: 1 });
expect(response.status).toBe(400);
expect(response.body).toEqual("failed to delete the report");
});
it("should return 200 when the report is deleted", async () => {
reportRepository.retrieve.mockResolvedValue({
reportId: "1",
reportByUser: "123",
});
reportRepository.delete.mockResolvedValue(true);
const response = await request(app).delete(`/api/reports`).send({ id: 1 });
expect(response.status).toBe(200);
expect(response.body).toEqual("Report has been deleted");
});
}); |
<?php
declare(strict_types=1);
/*
* This file is part of the latent/el-admin.
*
* (c) latent<pltrueover@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Latent\ElAdmin\Controller;
use Illuminate\Http\JsonResponse;
use Latent\ElAdmin\Enum\ModelEnum;
use Latent\ElAdmin\Exceptions\ValidateException;
use Latent\ElAdmin\Services\AuthServices;
use Latent\ElAdmin\Services\Permission;
use Latent\ElAdmin\Support\Helpers;
use Psr\SimpleCache\InvalidArgumentException;
class AuthController extends Controller
{
use Permission;
/**
* User guard.
*/
protected string $guard;
public function __construct()
{
$this->guard = (string) config('el_admin.guard');
}
/**
* User login.
*
* @throws ValidateException
*/
public function login(): JsonResponse
{
$params = $this->validator([
'email' => 'required|email',
'password' => 'required|min:6|max:20',
]);
if (! $token = auth($this->guard)->attempt([
'email' => $params['email'],
'password' => $params['password'],
'status' => ModelEnum::NORMAL]
)) {
return $this->fail(trans('el_admin.login_error'));
}
return (new AuthServices())->respondWithToken((string) $token);
}
/**
* Get the authenticated User.
*
* @throws InvalidArgumentException
* @throws ValidateException
*/
public function me(): JsonResponse
{
$params = $this->validator([
'is_menus' => 'int|in:0,1',
]);
$user = auth($this->guard)->user()?->toArray();
if (! empty($params['is_menus'])) {
[$menus, $nodes] = $this->getUserMenusAndNode();
$menus = Helpers::getTree($menus);
$nodes = Helpers::getTree($nodes);
$user = array_merge($user, ['menus' => $menus, 'nodes' => $nodes]);
}
return $this->success($user);
}
public function logout(): JsonResponse
{
auth($this->guard)->logout();
return $this->success();
}
/**
* Refresh token.
*/
public function refresh(): JsonResponse
{
return (new AuthServices())->respondWithToken((string) auth($this->guard)->refresh());
}
} |
# Inventory Management System (MERN Project)

## Introduction
Welcome to the Inventory Management System! This project is built using the MERN stack (MongoDB, Express.js, React.js, Node.js). It allows users to manage inventory by performing CRUD (Create, Read, Update, Delete) operations on products.
## Demo of CRUD operation in App
[Watch Demo on YouTube](https://youtu.be/p90kZwRzoWA)
## Server Setup
### Installation
1. Navigate to the `server` directory.
2. Run `npm install` to install dependencies.
- 
### Starting the Server
- Start the server by running `npm start`.
- Upon successful start, you'll see the message:
- 
### Endpoints
- **Create a Product:** `POST /products/create?name=<name>&price=<price>&desc=<description>&supplier=<supplier name>&mfg=<mfg date>&exp=<exp date>&quantity=<quantity>`
- **Get All Products:** `GET /products/get`
- **Update a Product:** `PUT /products/update/<_id>/?name=<name>&price=<price>&desc=<description>&supplier=<supplier name>&mfg=<mfg date>&exp=<exp date>&quantity=<quantity>`
- **Delete a Product:** `DELETE /products/delete/<_id>`
## Client Setup
### Installation
1. Navigate to the `client/inventory` directory.
2. Run `npm install` to install dependencies.
- 
### Starting the React App
- Start the React app by running `npm start`.
- The app will open in your default browser at http://localhost:3000.
## Usage
1. Use the navigation buttons to access different sections:
- **Home:** Click on the logo.
- 
- **Products:** Click on the "Product" button.
- 
2. On the Product page, you can perform CRUD operations on products.
3. [Click to watch the demo](https://youtu.be/p90kZwRzoWA)
## Notes
- Ensure that the server is running for successful frontend communication to backend server for CRUD operations .
- Make sure your MongoDB service is running properly on your operating system. |
# Stable Diffusion XL for JAX + TPUv5e
[TPU v5e](https://cloud.google.com/blog/products/compute/how-cloud-tpu-v5e-accelerates-large-scale-ai-inference) is a new generation of TPUs from Google Cloud. It is the most cost-effective, versatile, and scalable Cloud TPU to date. This makes them ideal for serving and scaling large diffusion models.
[JAX](https://github.com/google/jax) is a high-performance numerical computation library that is well-suited to develop and deploy diffusion models:
- **High performance**. All JAX operations are implemented in terms of operations in [XLA](https://www.tensorflow.org/xla/) - the Accelerated Linear Algebra compiler
- **Compilation**. JAX uses just-in-time (jit) compilation of JAX Python functions so it can be executed efficiently in XLA. In order to get the best performance, we must use static shapes for jitted functions, this is because JAX transforms work by tracing a function and to determine its effect on inputs of a specific shape and type. When a new shape is introduced to an already compiled function, it retriggers compilation on the new shape, which can greatly reduce performance. **Note**: JIT compilation is particularly well-suited for text-to-image generation because all inputs and outputs (image input / output sizes) are static.
- **Parallelization**. Workloads can be scaled across multiple devices using JAX's [pmap](https://jax.readthedocs.io/en/latest/_autosummary/jax.pmap.html), which expresses single-program multiple-data (SPMD) programs. Applying pmap to a function will compile a function with XLA, then execute in parallel on XLA devices. For text-to-image generation workloads this means that increasing the number of images rendered simultaneously is straightforward to implement and doesn't compromise performance.
👉 Try it out for yourself:
[](https://huggingface.co/spaces/google/sdxl)
## Stable Diffusion XL pipeline in JAX
Upon having access to a TPU VM (TPUs higher than version 3), you should first install
a TPU-compatible version of JAX:
```
pip install jax[tpu] -f https://storage.googleapis.com/jax-releases/libtpu_releases.html
```
Next, we can install [flax](https://github.com/google/flax) and the diffusers library:
```
pip install flax diffusers transformers
```
In [sdxl_single.py](./sdxl_single.py) we give a simple example of how to write a text-to-image generation pipeline in JAX using [StabilityAI's Stable Diffusion XL](stabilityai/stable-diffusion-xl-base-1.0).
Let's explain it step-by-step:
**Imports and Setup**
```python
import jax
import jax.numpy as jnp
import numpy as np
from flax.jax_utils import replicate
from MuseVdiffusers import FlaxStableDiffusionXLPipeline
from jax.experimental.compilation_cache import compilation_cache as cc
cc.initialize_cache("/tmp/sdxl_cache")
import time
NUM_DEVICES = jax.device_count()
```
First, we import the necessary libraries:
- `jax` is provides the primitives for TPU operations
- `flax.jax_utils` contains some useful utility functions for `Flax`, a neural network library built on top of JAX
- `diffusers` has all the code that is relevant for SDXL.
- We also initialize a cache to speed up the JAX model compilation.
- We automatically determine the number of available TPU devices.
**1. Downloading Model and Loading Pipeline**
```python
pipeline, params = FlaxStableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", revision="refs/pr/95", split_head_dim=True
)
```
Here, a pre-trained model `stable-diffusion-xl-base-1.0` from the namespace `stabilityai` is loaded. It returns a pipeline for inference and its parameters.
**2. Casting Parameter Types**
```python
scheduler_state = params.pop("scheduler")
params = jax.tree_util.tree_map(lambda x: x.astype(jnp.bfloat16), params)
params["scheduler"] = scheduler_state
```
This section adjusts the data types of the model parameters.
We convert all parameters to `bfloat16` to speed-up the computation with model weights.
**Note** that the scheduler parameters are **not** converted to `blfoat16` as the loss
in precision is degrading the pipeline's performance too significantly.
**3. Define Inputs to Pipeline**
```python
default_prompt = ...
default_neg_prompt = ...
default_seed = 33
default_guidance_scale = 5.0
default_num_steps = 25
```
Here, various default inputs for the pipeline are set, including the prompt, negative prompt, random seed, guidance scale, and the number of inference steps.
**4. Tokenizing Inputs**
```python
def tokenize_prompt(prompt, neg_prompt):
prompt_ids = pipeline.prepare_inputs(prompt)
neg_prompt_ids = pipeline.prepare_inputs(neg_prompt)
return prompt_ids, neg_prompt_ids
```
This function tokenizes the given prompts. It's essential because the text encoders of SDXL don't understand raw text; they work with numbers. Tokenization converts text to numbers.
**5. Parallelization and Replication**
```python
p_params = replicate(params)
def replicate_all(prompt_ids, neg_prompt_ids, seed):
...
```
To utilize JAX's parallel capabilities, the parameters and input tensors are duplicated across devices. The `replicate_all` function also ensures that every device produces a different image by creating a unique random seed for each device.
**6. Putting Everything Together**
```python
def generate(...):
...
```
This function integrates all the steps to produce the desired outputs from the model. It takes in prompts, tokenizes them, replicates them across devices, runs them through the pipeline, and converts the images to a format that's more interpretable (PIL format).
**7. Compilation Step**
```python
start = time.time()
print(f"Compiling ...")
generate(default_prompt, default_neg_prompt)
print(f"Compiled in {time.time() - start}")
```
The initial run of the `generate` function will be slow because JAX compiles the function during this call. By running it once here, subsequent calls will be much faster. This section measures and prints the compilation time.
**8. Fast Inference**
```python
start = time.time()
prompt = ...
neg_prompt = ...
images = generate(prompt, neg_prompt)
print(f"Inference in {time.time() - start}")
```
Now that the function is compiled, this section shows how to use it for fast inference. It measures and prints the inference time.
In summary, the code demonstrates how to load a pre-trained model using Flax and JAX, prepare it for inference, and run it efficiently using JAX's capabilities.
## Ahead of Time (AOT) Compilation
FlaxStableDiffusionXLPipeline takes care of parallelization across multiple devices using jit. Now let's build parallelization ourselves.
For this we will be using a JAX feature called [Ahead of Time](https://jax.readthedocs.io/en/latest/aot.html) (AOT) lowering and compilation. AOT allows to fully compile prior to execution time and have control over different parts of the compilation process.
In [sdxl_single_aot.py](./sdxl_single_aot.py) we give a simple example of how to write our own parallelization logic for text-to-image generation pipeline in JAX using [StabilityAI's Stable Diffusion XL](stabilityai/stable-diffusion-xl-base-1.0)
We add a `aot_compile` function that compiles the `pipeline._generate` function
telling JAX which input arguments are static, that is, arguments that
are known at compile time and won't change. In our case, it is num_inference_steps,
height, width and return_latents.
Once the function is compiled, these parameters are omitted from future calls and
cannot be changed without modifying the code and recompiling.
```python
def aot_compile(
prompt=default_prompt,
negative_prompt=default_neg_prompt,
seed=default_seed,
guidance_scale=default_guidance_scale,
num_inference_steps=default_num_steps
):
prompt_ids, neg_prompt_ids = tokenize_prompt(prompt, negative_prompt)
prompt_ids, neg_prompt_ids, rng = replicate_all(prompt_ids, neg_prompt_ids, seed)
g = jnp.array([guidance_scale] * prompt_ids.shape[0], dtype=jnp.float32)
g = g[:, None]
return pmap(
pipeline._generate,static_broadcasted_argnums=[3, 4, 5, 9]
).lower(
prompt_ids,
p_params,
rng,
num_inference_steps, # num_inference_steps
height, # height
width, # width
g,
None,
neg_prompt_ids,
False # return_latents
).compile()
````
Next we can compile the generate function by executing `aot_compile`.
```python
start = time.time()
print("Compiling ...")
p_generate = aot_compile()
print(f"Compiled in {time.time() - start}")
```
And again we put everything together in a `generate` function.
```python
def generate(
prompt,
negative_prompt,
seed=default_seed,
guidance_scale=default_guidance_scale
):
prompt_ids, neg_prompt_ids = tokenize_prompt(prompt, negative_prompt)
prompt_ids, neg_prompt_ids, rng = replicate_all(prompt_ids, neg_prompt_ids, seed)
g = jnp.array([guidance_scale] * prompt_ids.shape[0], dtype=jnp.float32)
g = g[:, None]
images = p_generate(
prompt_ids,
p_params,
rng,
g,
None,
neg_prompt_ids)
# convert the images to PIL
images = images.reshape((images.shape[0] * images.shape[1], ) + images.shape[-3:])
return pipeline.numpy_to_pil(np.array(images))
```
The first forward pass after AOT compilation still takes a while longer than
subsequent passes, this is because on the first pass, JAX uses Python dispatch, which
Fills the C++ dispatch cache.
When using jit, this extra step is done automatically, but when using AOT compilation,
it doesn't happen until the function call is made.
```python
start = time.time()
prompt = "photo of a rhino dressed suit and tie sitting at a table in a bar with a bar stools, award winning photography, Elke vogelsang"
neg_prompt = "cartoon, illustration, animation. face. male, female"
images = generate(prompt, neg_prompt)
print(f"First inference in {time.time() - start}")
```
From this point forward, any calls to generate should result in a faster inference
time and it won't change.
```python
start = time.time()
prompt = "photo of a rhino dressed suit and tie sitting at a table in a bar with a bar stools, award winning photography, Elke vogelsang"
neg_prompt = "cartoon, illustration, animation. face. male, female"
images = generate(prompt, neg_prompt)
print(f"Inference in {time.time() - start}")
``` |
#include <Seeed_Arduino_SSCMA.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include "certs.h"
SSCMA AI;
JsonDocument doc;
JsonDocument dataIn;
WiFiMulti WiFiMulti;
void setup() {
AI.begin();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while ((WiFiMulti.run() != WL_CONNECTED)) {
// Wait for WiFi Start
}
setClock();
}
void loop() {
// Fill This with your data
dataIn["detection"] = predict();
// Dont Modify Nothing After This
// API Call Preparation
doc["apikey"] = apikey;
doc["sensor"] = sensorName;
doc["private"] = privateFlag;
// Pre Process the JSON object
doc["dataIn"] = dataIn;
String data;
serializeJson(doc, data);
// Send API Call
sendData(data);
// Wait 10 min
delay(1000 * 60 * 10); // Testing
}
int predict() {
if (!AI.invoke()) {
return AI.classes()[0].target;
} else {
return -1;
}
}
void sendData(String httpRequestData) {
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
client->setCACert(CERT_CA);
{
// Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is
HTTPClient https;
if (https.begin(*client, "https://us-central1-bot-weave.cloudfunctions.net/addData")) { // HTTPS
// start connection and send HTTP header
https.addHeader("Content-Type", "application/json");
https.setTimeout(1000 * 30); // 30 Seconds
int httpCode = https.POST(httpRequestData);
if (httpCode > 0) {
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = https.getString();
}
}
https.end();
} else {
// No Connection
}
}
delete client;
}
}
void setClock() {
configTime(0, 0, "pool.ntp.org");
time_t nowSecs = time(nullptr);
while (nowSecs < 8 * 3600 * 2) {
delay(500);
yield();
nowSecs = time(nullptr);
}
struct tm timeinfo;
gmtime_r(&nowSecs, &timeinfo);
} |
# Задание на практику 
# Задания лекции
1. Для заданных значений параметров несущего колебания и НЧ сигнала определите значение частоты дискретизации (в менеджере переменных), значение индекса АМ. Получите временную и спектральную диаграммы несущего колебания и НЧ сигнала.
2. Получите сигнал АМ с параметрами fc = 4, fm = 0.2, Ac = 2 , Am = 0.5. Получите временную и спектральную диаграммы несущего колебания и НЧ сигнала. Определите нормированную частоту среза ФНЧ fn в менеджере переменных. Попробуйте изменить ее значение (задайте в программе fn) и сравните качество дететирования.
3. Получите сигнал АМ с параметрами fc = 2, fm = 0.2, Ac = 2 , Am = 1.5. Получите временную и спектральную диаграммы несущего колебания и НЧ сигнала. Определите нормированную частоту среза ФНЧ fn в менеджере переменных. Попробуйте изменить ее значение (задайте в программе fn) и сравните качество дететирования.
# Задания практики
**Задание №1**
1. При помощи документации настройте приемник и передатчик на одну несущую частоту - **2.4** [GHz] + **2** [MHz] * “**номер стола**”;
2. Установить `.sample_rate = 1e6`;
3. По умолчанию, количество сэмплов, получаемых с буфера, равно **1024**.
4. Сгенерируйте простую синусоиду:
1. Количество элементов вектора - на свое усмотрение;
2. Макс. амплитуда может быть равна **2**14;**
5. Отправьте сгенерированные сэмплы синусоиды на функцию передатчика;
6. Отобразите на графике принятый сигнал и его спектр;
7. p.s. за регулировку мощности передатчика и чувствительностью приемника отвечают методы `tx_hardwaregain_chan0` и `rx_hardwaregain_chan0` соответственно;
**Задание №2**
1. Установите размер **1 символа** - на свое усмотрение.
2. При помощи **ASCII** таблицы (кодировщика) закодируйте свои данные (ФИО) в виде битовой последовательности.
3. При помощи изменения максимальной амплитуды радиосигнала сформируйте синусоиду (из Задания №1) по правилам амплитудной модуляции. Уровни модуляции для `“0”` и `“1”` установите опытным путем.
4. Передайте ваши данные на `tx()` и “**примите + декодируйте**” на стороне `rx()`.
5. Опишите с какими проблемами вы столкнулись во время выполнения задания и как их решили.
**Задание №3 (бонус)**
1. Примите + декодируйте данные от соседей.
2. Запишите полученный список соседей в файл.
# Выполнение
## Задания лекции
<details>
## №1
Частота дискретизации `fs` = *204.7*
Значение индекса АМ `mu`=*0.5*
<img src="./photo/1.png" width="800" />
<img src="./photo/1_0.png" width="600" />
## №2
`fc = 4, fm = 0.2, Ac = 2 , Am = 0.5`
<img src="./photo/2_0.png" width="600" /><img src="./photo/2.png" width="800" />
<img src="./photo/2_3.png" width="600" />
Нормированная частота среза ФНЧ `fn` = *0.000977*
<img src="./photo/2_200.png" width="800" />
Нормированную частоту среза ФНЧ умножил на 200 `fn*200` = *0.1954*
ФНЧ не работает
## №3
`fc = 2, fm = 0.2, Ac = 2 , Am = 1.5`
<img src="./photo/3_0.png" width="600" /><img src="./photo/3.png" width="800" />
<img src="./photo/3_3.png" width="600" />
Нормированная частота среза ФНЧ `fn` = *0.000977*
<img src="./photo/3_20.png" width="600" />
Нормированную частоту среза ФНЧ умножил на 50 `fn*50` = *0.04885*
ФНЧ работает, но не идеально
</details>
## Задания практики
<details>
### Задание №1
**1**
```py
frequency = 2400e6+(2e6*2)
sdr.rx_lo = int(frequency)
sdr.tx_lo = int(frequency)
```
**2**
```py
sdr.sample_rate = 1e6
```
**4**
```py
fc = 10000
ts = 1/float(1e6)
t = np.arange(0, fc*ts, ts)
i = np.sin(2*np.pi*t*fc) * 2**14
q = np.cos(2*np.pi*t*fc) * 2**14
samples = i + 1j*q
```
**5**
```py
sdr.tx_cyclic_buffer = True # Enable cyclic buffers
sdr.tx(samples)
```
**6**
```py
for r in range(30):
rx = sdr.rx()
plt.clf()
plt.plot(rx.real)
plt.ylim(-1000, 1000)
plt.draw()
plt.pause(0.05)
time.sleep(0.0001)
```
<img src="./photo/p1.png" width="500" />
### Задание №2
**1**
```py
symbol=12
```
**2**
` 112, 117, 115, 104, 110, 105, 116, 115, 97 - pushnitsa `
в двоичном коде:
`0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1`
**3**
Сформировал сигнал
```py
for i in range(len(binary_list)):
if(binary_list[i]==0):
for p in range(symbol):
x.append(1)
else:
for p in range(symbol):
x.append(6)
x1=np.array(x)
```
Сформировал синусоиду
```py
t=np.linspace(0,len(x1),len(x1))
fc=80
q=np.sin(2*np.pi*t*fc)
```
Перемножил их
```py
sam = 2*(1.5*x1)*q
```
<img src="./photo/p2.png" width="600" />
##### (4,5 пункты времяни выполнить не хватило) (перенесено на следующую практику)
</details> |
/*
* Unless expressly otherwise stated, code from this project is licensed under the MIT license [https://opensource.org/licenses/MIT].
*
* Copyright (c) <2018> <Markus Gärtner, Volodymyr Kushnarenko, Florian Fritze, Sibylle Hermann and Uli Hahn>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package bwfdm.replaydh.ui.workflow;
import static java.util.Objects.requireNonNull;
import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jgoodies.forms.builder.FormBuilder;
import bwfdm.replaydh.core.RDHEnvironment;
import bwfdm.replaydh.core.RDHException;
import bwfdm.replaydh.io.FileTracker;
import bwfdm.replaydh.io.LocalFileObject;
import bwfdm.replaydh.io.TrackerException;
import bwfdm.replaydh.io.TrackerListener;
import bwfdm.replaydh.io.TrackingAction;
import bwfdm.replaydh.io.TrackingStatus;
import bwfdm.replaydh.resources.ResourceManager;
import bwfdm.replaydh.ui.GuiUtils;
import bwfdm.replaydh.ui.actions.ActionManager;
import bwfdm.replaydh.ui.actions.ActionManager.ActionMapper;
import bwfdm.replaydh.ui.helper.CloseableUI;
import bwfdm.replaydh.ui.helper.ScrollablePanel;
import bwfdm.replaydh.ui.helper.ScrollablePanel.ScrollableSizeHint;
import bwfdm.replaydh.ui.icons.IconRegistry;
import bwfdm.replaydh.utils.LazyCollection;
import bwfdm.replaydh.utils.annotation.Experimental;
/**
* @author Markus Gärtner
*
*/
public class WorkspaceTrackerPanel extends JPanel implements CloseableUI {
private static final long serialVersionUID = 5100311840353055034L;
private static final Logger log = LoggerFactory.getLogger(WorkspaceTrackerPanel.class);
private final RDHEnvironment environment;
private final ActionManager actionManager;
private final ActionMapper actionMapper;
/**
* Container for the fast changing content
*/
private final ScrollablePanel contentPanel;
private final JToolBar toolBar;
private final Map<TrackingStatus, FileOutlinePanel> panels = new EnumMap<>(TrackingStatus.class);
private final JLabel contentHeader;
/**
* Interface to the file tracker facility (usually GIT)
*/
private final FileTracker fileTracker;
private final Handler handler;
/**
* Flag to prevent redundant refresh operations when the file tracker
* posts both events via the {@link PropertyChangeListener} and
* {@link TrackerListener} interfaces. Switching this field to {@code true}
* will result in the next property change event to be ignored.
*/
private boolean ignoreNextStatusChange = false;
public WorkspaceTrackerPanel(RDHEnvironment environment) {
super(new BorderLayout());
this.environment = requireNonNull(environment);
handler = new Handler();
actionManager = environment.getClient().getGui().getActionManager().derive();
try {
actionManager.loadActions(WorkspaceTrackerPanel.class.getResource("workspace-tracker-panel-actions.xml"));
} catch (IOException e) {
throw new RDHException("Failed to load actions for"+WorkspaceTrackerPanel.class, e);
}
actionMapper = actionManager.mapper(this);
toolBar = actionManager.createToolBar("replaydh.ui.core.workspaceTrackerPanel.toolBarList", null);
fileTracker = environment.getClient().getFileTracker();
fileTracker.addTrackerListener(handler);
contentHeader = (JLabel) GuiUtils.createInfoComponent("", false, null);
for(TrackingStatus status : TrackingStatus.values()) {
panels.put(status, new FileOutlinePanel(environment, actionManager, status));
}
contentPanel = new ScrollablePanel();
contentPanel.setScrollableWidth(ScrollableSizeHint.FIT);
FormBuilder.create()
.columns("fill:pref:grow")
.rows("pref, 5dlu, pref, pref, pref, pref, pref")
.panel(contentPanel)
.add(contentHeader) .xy(1, 1)
.add(panel(TrackingStatus.CORRUPTED)) .xy(1, 3)
.add(panel(TrackingStatus.UNKNOWN)) .xy(1, 4)
.add(panel(TrackingStatus.MISSING)) .xy(1, 5)
.add(panel(TrackingStatus.MODIFIED)) .xy(1, 6)
.add(panel(TrackingStatus.TRACKED)) .xy(1, 7)
.build();
environment.addPropertyChangeListener(RDHEnvironment.NAME_WORKSPACE, handler);
JScrollPane scrollPane = new JScrollPane(contentPanel);
add(toolBar, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
environment.getClient().getGui().registerHelp(this, "replaydh.ui.core.workspaceTrackerPanel");
registerActions();
refreshActions();
update();
}
private FileOutlinePanel panel(TrackingStatus status) {
FileOutlinePanel panel = panels.get(status);
if(panel==null)
throw new IllegalStateException("No outline panel for tracking status: "+status);
return panel;
}
private void registerActions() {
actionMapper.mapTask("replaydh.ui.core.workspaceTrackerPanel.createDummyFile", handler::createDummyFile);
actionMapper.mapTask("replaydh.ui.core.workspaceTrackerPanel.editDummyFile", handler::editDummyFile);
actionMapper.mapTask("replaydh.ui.core.workspaceTrackerPanel.deleteDummyFile", handler::deleteDummyFile);
}
private void refreshActions() {
// no-op
}
/**
* @see bwfdm.replaydh.ui.helper.CloseableUI#close()
*/
@Override
public void close() {
environment.removePropertyChangeListener(RDHEnvironment.NAME_WORKSPACE, handler);
fileTracker.removeTrackerListener(handler);
actionMapper.dispose();
}
private void checkDevMode() {
if(!environment.getClient().isDevMode())
throw new IllegalStateException("Cannot execute method outside of dev mode!!!");
}
public void update() {
TrackerStateHint hint = fileTracker.hasStatusInfo() ?
TrackerStateHint.UPDATE_DONE : TrackerStateHint.UNKNOWN;
showFileTrackerState(hint);
}
private LocalFileObject wrapFile(Path file, TrackingStatus trackingStatus) {
return new LocalFileObject(file.toAbsolutePath(), trackingStatus);
}
private boolean hasFiles(TrackingStatus trackingStatus) {
try {
return fileTracker.hasFilesForStatus(trackingStatus);
} catch (TrackerException e) {
log.error("Failed to query file tracker for state on "+trackingStatus, e);
return false;
}
}
private Set<Path> getFiles(TrackingStatus trackingStatus) {
try {
return fileTracker.getFilesForStatus(trackingStatus);
} catch (TrackerException e) {
log.error("Failed to query file tracker for files on "+trackingStatus, e);
return Collections.emptySet();
}
}
private Set<LocalFileObject> wrapFilesFromTracker(TrackingStatus trackingStatus) {
Set<Path> files = getFiles(trackingStatus);
LazyCollection<LocalFileObject> result = LazyCollection.lazySet();
files.forEach(file -> result.add(wrapFile(file, trackingStatus)));
return result.getAsSet();
}
private Set<LocalFileObject> extractFilesForUpdate(
Set<LocalFileObject> filesToUpdate, Set<LocalFileObject> files) {
for(LocalFileObject fileObject : files) {
// Schedule all files for update if not inked to a known resource definition
if(fileObject.getResource()==null) {
filesToUpdate.add(fileObject);
}
}
return files;
}
private void showFileTrackerState(final TrackerStateHint hint) {
// Switch over to EDT if needed
if(!SwingUtilities.isEventDispatchThread()) {
GuiUtils.invokeEDT(() -> showFileTrackerState(hint));
return;
}
// System.out.println(hint);
String textKey = null;
Icon icon = null;
Set<LocalFileObject> filesToUpdate = new HashSet<>();
boolean showCorruptedPanel = false;
boolean showNewPanel = false;
boolean showMissingPanel = false;
boolean showModifiedPanel = false;
boolean showTrackedPanel = false;
switch (requireNonNull(hint)) {
case UPDATE_DONE: {
boolean hasNew = hasFiles(TrackingStatus.UNKNOWN);
boolean hasMissing = hasFiles(TrackingStatus.MISSING);
boolean hasModified = hasFiles(TrackingStatus.MODIFIED);
boolean hasCorrupted = hasFiles(TrackingStatus.CORRUPTED);
boolean hasTracked = hasFiles(TrackingStatus.TRACKED);
if(!hasNew && !hasMissing && !hasModified && !hasCorrupted) {
textKey = "replaydh.panels.workspaceTracker.unchangedState";
} else {
textKey = "replaydh.panels.workspaceTracker.validState";
if(hasCorrupted) {
Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.CORRUPTED);
panel(TrackingStatus.CORRUPTED).setFiles(extractFilesForUpdate(filesToUpdate, files));
}
if(hasNew) {
Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.UNKNOWN);
panel(TrackingStatus.UNKNOWN).setFiles(extractFilesForUpdate(filesToUpdate, files));
}
if(hasMissing) {
Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.MISSING);
panel(TrackingStatus.MISSING).setFiles(extractFilesForUpdate(filesToUpdate, files));
}
if(hasModified) {
Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.MODIFIED);
panel(TrackingStatus.MODIFIED).setFiles(extractFilesForUpdate(filesToUpdate, files));
}
if(hasTracked) {
Set<LocalFileObject> files = wrapFilesFromTracker(TrackingStatus.TRACKED);
panel(TrackingStatus.TRACKED).setFiles(extractFilesForUpdate(filesToUpdate, files));
}
showCorruptedPanel = hasCorrupted;
showNewPanel = hasNew;
showMissingPanel = hasMissing;
showModifiedPanel = hasModified;
showTrackedPanel = hasTracked;
}
} break;
case UPDATE_CANCELLED:
textKey = "replaydh.panels.workspaceTracker.updateCanceled";
break;
case UPDATE_FAILED:
textKey = "replaydh.panels.workspaceTracker.updateFailed";
break;
case UPDATING:
textKey = "replaydh.panels.workspaceTracker.updateRunning";
icon = IconRegistry.getGlobalRegistry().getIcon("loading-128.gif");
break;
// Default state, let's just show generic "welcome" screen
case UNKNOWN:
default:
textKey = "replaydh.panels.workspaceTracker.unknownStatus";
break;
}
panel(TrackingStatus.CORRUPTED).setVisible(showCorruptedPanel);
panel(TrackingStatus.UNKNOWN).setVisible(showNewPanel);
panel(TrackingStatus.MISSING).setVisible(showMissingPanel);
panel(TrackingStatus.MODIFIED).setVisible(showModifiedPanel);
panel(TrackingStatus.TRACKED).setVisible(showTrackedPanel);
String text = null;
if(textKey!=null) {
text = ResourceManager.getInstance().get(textKey);
}
contentHeader.setText(GuiUtils.toSwingTooltip(text));
contentHeader.setIcon(icon);
contentHeader.setVisible(text!=null || icon!=null);
//TODO schedule update
revalidate();
repaint();
refreshActions();
}
private FileOutlinePanel getFileOutlinePanel(TrackingStatus trackingStatus) {
switch (trackingStatus) {
case IGNORED: return null;
default:
return panel(trackingStatus);
}
}
private void updateFilePanel(LocalFileObject file) {
FileOutlinePanel fileOutlinePanel = getFileOutlinePanel(file.getTrackingStatus());
if(fileOutlinePanel!=null) {
fileOutlinePanel.updateFilePanel(file);
}
}
private enum TrackerStateHint {
UNKNOWN,
UPDATING,
UPDATE_FAILED,
UPDATE_CANCELLED,
UPDATE_DONE,
;
}
private class Handler implements PropertyChangeListener, TrackerListener {
@Experimental
private final Random random = new Random(System.currentTimeMillis());
/**
* @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
//TODO handle workspace change
}
/**
* @see bwfdm.replaydh.io.TrackerListener#statusInfoChanged(bwfdm.replaydh.io.FileTracker)
*/
@Override
public void statusInfoChanged(FileTracker tracker) {
if(!ignoreNextStatusChange) {
TrackerStateHint hint = fileTracker.hasStatusInfo() ?
TrackerStateHint.UPDATE_DONE : TrackerStateHint.UNKNOWN;
showFileTrackerState(hint);
}
ignoreNextStatusChange = false;
}
/**
* @see bwfdm.replaydh.io.TrackerListener#refreshStarted(bwfdm.replaydh.io.FileTracker)
*/
@Override
public void refreshStarted(FileTracker tracker) {
showFileTrackerState(TrackerStateHint.UPDATING);
}
/**
* @see bwfdm.replaydh.io.TrackerListener#refreshFailed(bwfdm.replaydh.io.FileTracker, java.lang.Exception)
*/
@Override
public void refreshFailed(FileTracker tracker, Exception e) {
showFileTrackerState(TrackerStateHint.UPDATE_FAILED);
}
/**
* @see bwfdm.replaydh.io.TrackerListener#refreshDone(bwfdm.replaydh.io.FileTracker, boolean)
*/
@Override
public void refreshDone(FileTracker tracker, boolean canceled) {
TrackerStateHint hint = canceled ?
TrackerStateHint.UPDATE_CANCELLED : TrackerStateHint.UPDATE_DONE;
showFileTrackerState(hint);
}
/**
* @see bwfdm.replaydh.io.TrackerListener#trackingStatusChanged(bwfdm.replaydh.io.FileTracker, java.util.Set, bwfdm.replaydh.io.TrackingAction)
*/
@Override
public void trackingStatusChanged(FileTracker tracker, Set<Path> files, TrackingAction action) {
update();
}
@Experimental
private Path getNewFile() {
Path workspace = fileTracker.getTrackedFolder();
Path file;
do {
String fileName = "test"+String.valueOf(1+random.nextInt(200))+".txt";
file = workspace.resolve(fileName);
} while(Files.exists(file, LinkOption.NOFOLLOW_LINKS));
return file;
}
@Experimental
private void createDummyFile() {
checkDevMode();
Path file = getNewFile();
try {
Files.createFile(file);
appendToDummyFile(file);
} catch (IOException e) {
log.error("Failed to create dummy file: "+file, e);
GuiUtils.beep();
}
}
@Experimental
private Path getRandomFile() {
try {
Path[] files = Files.list(fileTracker.getTrackedFolder())
.filter(path ->
path.getFileName().toString().startsWith("test"))
.sorted()
.toArray(size -> new Path[size]);
int num = files.length;
return num>0 ? files[random.nextInt(num)] : null;
} catch (IOException e) {
log.error("Failed to pick random file in folder", e);
GuiUtils.beep();
return null;
}
}
@Experimental
private void editDummyFile() {
checkDevMode();
Path file = getRandomFile();
if(file!=null) {
appendToDummyFile(file);
}
}
private void appendToDummyFile(Path file) {
try(Writer w = Files.newBufferedWriter(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
w.append(LocalDateTime.now().toString());
w.append(System.lineSeparator());
} catch (IOException e) {
log.error("Failed to edit random file {}", file, e);
}
}
@Experimental
private void deleteDummyFile() {
checkDevMode();
Path file = getRandomFile();
if(file!=null) {
try {
Files.delete(file);
} catch (IOException e) {
log.error("Failed to delete random file {}", file, e);
}
}
}
}
} |
# 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
#
#
#
# 示例:
#
# 输入:1->2->4, 1->3->4
# 输出:1->1->2->3->4->4
#
# Related Topics 链表
# 👍 1260 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# 迭代:判断表头哪一个值更小,添加到节点,原地调整指向
# 时间n+m,空间1
head = ListNode(0)
pre = head
while l1 and l2:
if l1.val <= l2.val:
pre.next = l1
l1 = l1.next
else:
pre.next = l2
l2 = l2.next
pre = pre.next
# 合并后,最多剩一个的,数值很大,直接插入后面
if l1 is not None:
pre.next = l1
else:
pre.next = l2
return head.next
def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode:
# 递归:时间O(n+m),空间O(n+m)
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2 |
import { TECH_STACKS } from '@/constants';
import { QueryType } from '@/type';
import { Button, Form, Input, InputNumber, message, Radio, Select } from 'antd';
import dayjs from 'dayjs';
import { Dispatch, SetStateAction } from 'react';
import styles from './Sider.module.scss';
const Option = Select.Option;
export default function Sider({
onSend,
loading,
setQrShow,
hasKey,
}: {
onSend: (values: QueryType) => Promise<void>;
loading: boolean;
setQrShow: Dispatch<SetStateAction<boolean>>;
hasKey: boolean;
}) {
const handleFinish = (values: QueryType) => {
if (hasKey) {
return onSend(values);
}
const limitFetch = JSON.parse(localStorage.getItem('limitFetch') || '{}');
const resumeCode = localStorage.getItem('resumeCode');
if (!resumeCode) setQrShow(true);
const dateA = dayjs();
const dateB = dayjs(limitFetch.day);
const daysDiff = dayjs(dateA).diff(dayjs(dateB), 'day');
// 天数大于1天或者次数小于10次都可以请求
if (daysDiff >= 1) {
localStorage.setItem(
'limitFetch',
JSON.stringify({
day: dateA,
count: 1,
})
);
} else if (!limitFetch?.count || limitFetch?.count <= 10) {
localStorage.setItem(
'limitFetch',
JSON.stringify({
day: dateA,
count: (limitFetch.count || 0) + 1,
})
);
} else {
// 天数小于10,次数大于10
return message.warning('次数限制,明天再尝试');
}
onSend(values);
};
return (
<div className={styles.sider}>
<div className={styles.title}>ChatResume</div>
<div className={styles.tips1}>
若一直无法返回结果,则表明key的额度用完了或者需要科学上网。
</div>
<div className={styles.tips2}>
为了延长key的使用时间,所以限制了使用频率。右上角设置自己的key则没有使用次数限制。
</div>
<Form
onFinish={handleFinish}
layout="vertical"
size="middle"
initialValues={{ isNeedTitle: '否' }}
>
<Form.Item
name="title"
label="项目名称"
rules={[{ required: true, message: '请输入标题' }]}
>
<Input placeholder="输入你的项目名称" />
</Form.Item>
<Form.Item name="isNeedTitle" label="是否需要别名">
<Radio.Group>
<Radio value="是">是</Radio>
<Radio value="否">否</Radio>
</Radio.Group>
</Form.Item>
<Form.Item name="year" label="工作经验">
<InputNumber placeholder="输入你希望的年限" />
</Form.Item>
<Form.Item
name="techStacks"
label="技术栈"
rules={[{ required: true, message: '请选择技术栈' }]}
>
<Select
mode="tags"
placeholder="选择你项目技术栈"
maxTagCount={5}
filterOption={(inputValue: string, option: { value: string }) => {
return (option?.value as string)
.toLowerCase()
.includes(inputValue.toLowerCase());
}}
>
{TECH_STACKS.map((stack) => (
<Option key={stack} value={stack}>
{stack}
</Option>
))}
</Select>
</Form.Item>
<Form.Item name="business" label="业务方向">
<Input placeholder="输入你的业务" />
</Form.Item>
<Button
loading={loading}
htmlType="submit"
size="middle"
className={styles.button}
>
生成
</Button>
</Form>
</div>
);
} |
<?php
/*
* This file is part of the 'octris/core' package.
*
* (c) Harald Lapp <harald@octris.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Octris\Core\Db\Type;
/**
* Iterator for recursive iterating data objects of query results
*
* @copyright copyright (c) 2012-2014 by Harald Lapp
* @author Harald Lapp <harald@octris.org>
*/
class DataIterator implements \Iterator
{
/**
* The dataobject to iterate.
*
* @type \Octris\Core\Db\Type\SubObject
*/
protected $data;
/**
* Keys stored in dataobject.
*
* @type array
*/
protected $keys;
/**
* Internal pointer position.
*
* @type int
*/
protected $position = 0;
/**
* Constructor.
*
* @parem \Octris\Core\Db\Type\SubObject $dataobject The dataobject to iterate.
*/
public function __construct(\Octris\Core\Db\Type\SubObject $dataobject)
{
$this->data = $dataobject;
$this->keys = $dataobject->getKeys();
}
/** Iterator **/
/**
* Get value of item.
*
* @return mixed Value stored at current position.
*/
public function current()
{
return $this->data[$this->keys[$this->position]];
}
/**
* Get key of current item.
*
* @return scalar Key of current position.
*/
public function key()
{
return $this->keys[$this->position];
}
/**
* Advance pointer.
*/
public function next()
{
++$this->position;
}
/**
* Reset pointer.
*/
public function rewind()
{
$this->position = 0;
}
/**
* Test if current pointer position is valid.
*
* @return bool True, if position is valid.
*/
public function valid()
{
return isset($this->keys[$this->position]);
}
} |
import React, {useContext, useEffect} from "react";
import {browseDisplayStrings} from "../../../resources/PublicDisplayStrings";
import {LocaleContext} from "../../../context/LocaleContext";
import {apiUrl} from "../../../helpers/Variables";
import Panel from "../../commons/elements/containers/Panel";
import ArticleCard from "../../commons/elements/containers/ArticleCard";
import {PanelLoader} from "../../commons/elements/loaders/Loader";
import {PanelEmp} from "../../commons/elements/loaders/AlertEmpty";
import {PanelErr} from "../../commons/elements/loaders/AlertError";
const BrowseBlogs = ({user, data, isLoading, isError, fetchData}) => {
// Localizations
browseDisplayStrings.setLanguage(useContext(LocaleContext));
// Executes fetch on page load
const api = `${apiUrl}/blogs/getall?page=1&limit=100${user ? `&userID=${user.id}` : ``}`;
useEffect(() => {
fetchData(api);
}, [user]);
return (
<section>
<div className="section-content">
<h1>{browseDisplayStrings.browseBlogsHeader}</h1>
<p>{browseDisplayStrings.browseBlogsSubheader}</p>
<Panel filler="card--full">
{!isLoading ? <>
{!isError ? <>
{data && data.length > 0 ? <>
{data.map(item => (
<ArticleCard className="card--full"
key={item.blog_id}
id={item.blog_id}
type="blog"
title={item.blog_title}
thumbnail={item.blog_thumbnail}
subtitle={item.blog_subtitle}
userId={item.user_id}
firstName={item.first_name}
lastName={item.last_name}
time={item.time_created}
isFavorite={item.is_like}
totalLikes={item.totalLike}/>))}
</> : <PanelEmp/>}
</> : <PanelErr reload={() => fetchData(api)}/>}
</> : <PanelLoader/>}
</Panel>
</div>
</section>
)
}
export default BrowseBlogs; |
import "./product-search-bar.css";
import React, { Dispatch, SetStateAction, useState } from "react";
import ICategory from "../../models/category.model";
import IBrand from "../../models/brand.model";
export interface ProductSearchBarProps {
className?: string;
categories: ICategory[];
brands: IBrand[];
searchFilter: Dispatch<SetStateAction<string | undefined>>;
categoryFilter: Dispatch<SetStateAction<number | undefined>>;
brandFilter: Dispatch<SetStateAction<number | undefined>>;
}
export const ProductSearchBar: React.FC<ProductSearchBarProps> = ({
className = "",
categories,
brands,
searchFilter,
categoryFilter,
brandFilter,
}) => {
const [brand, setBrandValue] = useState<number | undefined>(undefined);
const [category, setCategoryValue] = useState<number | undefined>(undefined);
const [searchValue, setSearchValue] = useState<string | undefined>(undefined);
const handleSearchInputChange = (
event: React.ChangeEvent<HTMLInputElement>
) => {
setSearchValue(event.target.value);
searchFilter(event.target.value);
};
const handleBrandSelectChange = (
event: React.ChangeEvent<HTMLSelectElement>
) => {
setBrandValue(parseInt(event.target.value));
brandFilter(parseInt(event.target.value));
};
const handleCategorySelectChange = (
event: React.ChangeEvent<HTMLSelectElement>
) => {
setCategoryValue(parseInt(event.target.value));
categoryFilter(parseInt(event.target.value));
};
return (
<div className={`${className} searchContainer`}>
<label>
<svg
viewBox="0 0 24 24"
width="20"
height="20"
stroke="currentColor"
stroke-width="1.5"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
className="css-i6dzq1"
>
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
</svg>
<input
placeholder="Buscar Producto"
type="search"
value={searchValue}
onChange={handleSearchInputChange}
/>
</label>
<select
defaultValue=""
className="searchSelect"
value={brand}
onChange={handleBrandSelectChange}
>
<option hidden value="">
Línea
</option>
{brands.map((brand: IBrand) => (
<option value={brand.id}>{brand.name}</option>
))}
</select>
<select
defaultValue=""
className="searchSelect"
value={category}
onChange={handleCategorySelectChange}
>
<option hidden value="">
Categoría
</option>
{categories
.filter((category) => category.is_active)
.map((category: ICategory) => (
<option value={category.id}>{category.name}</option>
))}
</select>
</div>
);
}; |
import {inject} from 'aurelia-framework';
import {Dependency} from './dependecy';
import {Redirect} from 'aurelia-router';
@inject(Dependency)
export class App {
constructor() {
this.header = 'Navigation';
this.content = 'Page info';
console.log(Dependency);
}
updateContent() {
this.header = 'New Cool Name'
this.content = 'New Content'
}
configureRouter(config, router) {
this.router = router;
config.title = 'Aurelia Recipe App';
config.map([
{ route: ['', 'home'], name: 'home', moduleId: 'home/index', title: 'Main Page', nav: true },
{ route: 'login', name: 'login', moduleId: 'login', title: 'Log In', nav: true },
{ route: 'registration', name: 'registration', moduleId: 'registration', title: 'Registration', nav: true },
{ route: 'fridge', name: 'fridge', moduleId: 'fridge', title: 'Fridge', nav: true, settings: { roles: ['admin']} },
{ route: 'recipe-add', name: 'recipe-add', moduleId: 'recipe-add', title: 'Add Recipe', nav: true },
]);
}
manage_sideBar() {
if (document.getElementById("navigation").style.display == "block") {
this.close_sideBar();
} else {
this.open_sideBar();
}
}
open_sideBar() {
document.getElementById("navigation").style.display = "block";
}
close_sideBar() {
document.getElementById("navigation").style.display = "none";
}
created(owningView, myView) {
// Invoked once the component is created...
}
bind(bindingContext, overrideContext) {
// Invoked once the databinding is activated...
}
attached(argument) {
// Invoked once the component is attached to the DOM...
}
detached(argument) {
// Invoked when component is detached from the dom
}
unbind(argument) {
// Invoked when component is unbound...
}
}
class AuthorizeStep {
run(navigationInstruction, next) {
if (navigationInstruction.getAllInstructions().some(i => i.config.settings.auth)) {
var isLoggedIn = false; // insert magic here;
if (!isLoggedIn) {
return next.cancel(new Redirect('login'));
}
}
return next();
}
} |
import React from "react";
import { Form } from "antd";
import { useMultiStepForm } from "../Hooks/useMultiStepForm";
import Styles from "../App.module.css";
import From1 from "./From1";
import From2 from "./From2";
import { useFroms } from "../Contest/FormContext";
const NewForm = ({ setOpen }) => {
const { steps, currentStepIndex, step, isFirstStep, back, next, isLastStep } =
useMultiStepForm([<From1 />, <From2 />]);
const { userDetails, setuserDetails, forms, setforms } = useFroms();
function onFinish(e) {
setforms((prev) => [...prev, userDetails]);
setuserDetails({});
back();
setOpen(false);
}
console.log(userDetails);
return (
<>
<Form name="sCorpForm" layout="vertical" onFinish={onFinish}>
<div style={{ position: "absolute", top: "1rem", right: "3rem" }}>
Page {currentStepIndex + 1}/{steps.length}
</div>
{step}
<div className={Styles.pageButtons}>
<div>
{isFirstStep && (
<button type="button" onClick={back}>
Back
</button>
)}
</div>
<div className={Styles.savebutton}>
<button type="button" onClick={back}>
Save
</button>
{!isLastStep && (
<button type="button" onClick={next}>
Next
</button>
)}
{isLastStep && <button type="submit">Submit</button>}
</div>
</div>
</Form>
</>
);
};
export default NewForm; |
#include "Bureaucrat.hpp"
Bureaucrat::Bureaucrat(std::string name, size_t grade) : _name(name), _grade(grade)
{
if (this->_grade < 1)
throw Bureaucrat::GradeTooHighException();
if (this->_grade > 150)
throw Bureaucrat::GradeTooLowException();
}
Bureaucrat::~Bureaucrat()
{
}
Bureaucrat::Bureaucrat(const Bureaucrat &rhs)
{
*this = rhs;
}
Bureaucrat& Bureaucrat::operator=(const Bureaucrat &rhs)
{
if (this != &rhs)
this->_grade = rhs._grade;
return (*this);
}
size_t Bureaucrat::getGrade() const
{
return (this->_grade);
}
const std::string Bureaucrat::getName() const
{
return (this->_name);
}
void Bureaucrat::incrementGrade()
{
if (this->_grade > 1)
this->_grade -= 1;
else
throw Bureaucrat::GradeTooHighException();
}
void Bureaucrat::decrementGrade()
{
if (this->_grade < 150)
this->_grade += 1;
else
throw Bureaucrat::GradeTooLowException();
}
std::ostream& operator<<(std::ostream &os, const Bureaucrat &rhs)
{
os << rhs.getName() << ", bureaucrat grade " << rhs.getGrade() << "." << std::endl;
return (os);
}
const char* Bureaucrat::GradeTooHighException::what() const throw()
{
return ("Grade too high");
}
const char* Bureaucrat::GradeTooLowException::what() const throw()
{
return ("Grade too low");
} |
if !exists('g:loaded_telescope') | finish | endif
nnoremap <silent> ff <cmd>Telescope find_files<cr>
nnoremap <silent> fr <cmd>Telescope live_grep<cr>
nnoremap <silent> \\ <cmd>Telescope buffers<cr>
nnoremap <silent> ;; <cmd>Telescope help_tags<cr>
lua << EOF
local actions = require('telescope.actions')
local fb_actions = require "telescope".extensions.file_browser.actions
local builtin = require("telescope.builtin")
-- Global remapping
------------------------------
require("telescope").setup {
defaults = {
mappings = {
n = {
["q"] = actions.close
},
},
},
extensions = {
file_browser = {
theme = "dropdown",
-- disables netrw and use telescope-file-browser in its place
hijack_netrw = true,
mappings = {
-- your custom insert mode mappings
["i"] = {
["<C-w>"] = function() vim.cmd('normal vbd') end,
},
["n"] = {
-- your custom normal mode mappings
["N"] = fb_actions.create,
["h"] = fb_actions.goto_parent_dir,
["/"] = function()
vim.cmd('startinsert')
end
},
},
},
},
}
require("telescope").load_extension "file_browser"
vim.keymap.set('n', 'ff',
function()
builtin.find_files({
no_ignore = false,
hidden = true
})
end)
vim.keymap.set('n', 'fr', function()
builtin.live_grep()
end)
vim.keymap.set('n', '\\\\', function()
builtin.buffers()
end)
vim.keymap.set('n', ';t', function()
builtin.help_tags()
end)
vim.keymap.set('n', ';;', function()
builtin.resume()
end)
vim.keymap.set('n', ';e', function()
builtin.diagnostics()
end)
vim.api.nvim_set_keymap(
"n",
"fb",
":Telescope file_browser",
{ noremap = true }
) |
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<meta charset="utf-8"></meta>
<title><ui:insert name="title">Default Title</ui:insert></title>
<meta content="width=device-width, initial-scale=1.0" name="viewport"></meta>
<meta content="" name="keywords"></meta>
<meta content="" name="description"></meta>
<meta charset="utf-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></link>
<link rel="stylesheet" href="resources/css/mycss.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</h:head>
<h:body>
<h:form>
<nav class="navbar bg-dark navbar-dark">
<h:link class="navbar-brand" outcome="dashboard"><img class="grow" src="#{resource['images/cricket.png']}" style="height: 50px;width:65px;" /></h:link>
<h:panelGroup rendered="#{sessionBean.isLogged}">
<p id="hm">Welcome,#{sessionBean.email}|<h:graphicImage value="#{rankBean.processFindRank()}"></h:graphicImage>:#{rankBean.returnTypeOfRank()}|Won Trophies:
<ui:repeat value="#{trophyBean.catch3Trophies()}" var="trophyTmp" varStatus="getObj">
<h:graphicImage value="#{trophyTmp}"></h:graphicImage>
</ui:repeat>
</p>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav float-right">
<!--
<li class="nav-item">
<h:commandLink action="#{sessionBean.editUser(sessionBean.email)}" style="color:white;">
#{bundle.User}
<img src="https://img.icons8.com/color/48/000000/gender-neutral-user.png"></img>
</h:commandLink>
</li>
-->
<li class="nav-item">
<h:link outcome="indexHistory" style="color:white;">
#{bundle.History}
<img src="https://img.icons8.com/office/40/000000/opened-folder.png"></img>
</h:link>
</li>
<li class="nav-item">
<h:link outcome="indexTrophy" style="color:white;">
#{bundle.Trophy}
<img src="https://img.icons8.com/color/48/000000/trophy.png"></img>
</h:link>
</li>
<li class="nav-item">
<h:link outcome="indexCategories" style="color:white;">
#{bundle.Categories}
<img src="https://img.icons8.com/office/40/000000/opened-folder.png"></img>
</h:link>
</li>
<li class="nav-item">
<li>
<h:commandLink action="#{sessionBean.processLogout}">
<img src="https://img.icons8.com/office/30/000000/shutdown.png"></img>
</h:commandLink>
</li>
</li>
</ul>
</div>
</h:panelGroup>
</nav>
<br></br>
</h:form>
<div class="container">
<div class="row">
<div class="col-2"></div>
<div class="col-8">
<div class="container">
<header class="section-header">
<div class="jumbotron">
<ui:insert name="containerTitle">Default Title</ui:insert>
</div>
</header>
</div>
</div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-2"></div>
<div class="col-8">
<div class="container">
<ui:insert name="containerContent">Default Body</ui:insert>
</div>
</div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-12">
<div class="container">
<div class="copyright">
© Copyright <strong>7(--2) Homens 1 Desafio</strong>| <img src="#{resource['images/isec.png']}" style="height:25px;width:25px;" />|<Strong>UC:</Strong> PS. <Strong> Professor:</Strong> João Cunha. <Strong>All Rights Reserved</Strong>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
<!-- DatePicker JavaScript & CSS -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> </link>
<script src="resources/js/formatDatePicker.js"></script>
<script src="resources/js/toggleButton.js"></script>
</h:body>
</html> |
import { Logger } from '@nestjs/common';
import { IoAdapter } from '@nestjs/platform-socket.io';
import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
OnGatewayInit,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
class StartChat {
chat: {
id: number;
me_id: number;
opp_id: number;
};
}
@WebSocketGateway(3201, {
transports: ['websocket'],
namespace: 'chat',
cors: true,
})
export class ChatGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer()
server: Server;
sockets = [];
private logger: Logger = new Logger('ChatGateWay');
@SubscribeMessage('startChat')
handleStartChat(
@ConnectedSocket() socket: Socket,
@MessageBody() startChat: StartChat,
) {
const {
chat: { id, opp_id, me_id },
} = startChat;
const chatId = String(id);
socket.join(chatId);
socket.to(chatId).emit('startChat', { room: chatId });
return;
}
@SubscribeMessage('events')
handleEvent(@MessageBody() data: string): string {
console.log(data);
this.server.emit(data);
return data;
}
@SubscribeMessage('clientToServer')
async handleMessage(@MessageBody() data: string) {
console.log(data);
return data;
}
@SubscribeMessage('whoAreThere')
handleWho(@MessageBody() data: string) {
}
@SubscribeMessage('create')
handleCreate(@MessageBody() data: string) {
console.log(data);
return;
}
afterInit(server: Server) {
this.logger.log('Init');
}
handleConnection(socket: Socket) {
this.logger.log(`Client Connected : ${socket.id}`);
}
handleDisconnect(socket: Socket) {
this.logger.log(`Client Disconnected : ${socket.id}`);
}
} |
<template>
<ValidationObserver v-slot="{ handleSubmit }">
<form @submit.prevent="handleSubmit(processForm)">
<div class="modal-card" style="width: 40em">
<header class="modal-card-head">
<p class="modal-card-title">
{{ currentData ? `Edit ${currentData.name}` : "Add a new Client" }}
</p>
</header>
<section class="modal-card-body">
<ValidatedInput
v-model="name"
placeholder="Enter a client name"
maxlength="32"
:validation="{
name: 'name',
rules: 'required|alpha_dash',
}"
:field="{ label: 'Name', expanded: true }"
/>
<ValidatedInput
v-model="description"
placeholder="Enter client description"
type="textarea"
maxlength="255"
:validation="{ name: 'Description', rules: '' }"
:field="{ label: 'Description', expanded: true }"
/>
<b-table :data="clients.filter((e) => e.name !== startName)">
<b-table-column v-slot="props" label="Name" width="80pt" centered>
<p>{{ props.row.name }}</p>
</b-table-column>
<b-table-column label="Cost" centered v-slot="props">
<ValidatedInput
inputType="b-numberinput"
v-model="cost[props.row.name]"
min="0"
step="0.01"
:validation="{
rules: 'required',
}"
:showStar="false"
:field="{}"
/>
</b-table-column>
<b-table-column label="Time" centered v-slot="props">
<ValidatedInput
inputType="b-numberinput"
v-model="time[props.row.name]"
min="0"
step="0.01"
:validation="{
rules: 'required',
}"
:showStar="false"
:field="{}"
/>
</b-table-column>
</b-table>
</section>
<footer class="modal-card-foot">
<button class="button" type="button" @click="$parent.close()">
Close
</button>
<button class="button is-primary">
<p v-if="!currentData">Add</p>
<p v-else>Update</p>
</button>
</footer>
</div>
</form>
</ValidationObserver>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
name: "ClientForm",
props: ["currentData"],
data() {
return {
name: this.currentData ? this.currentData.name : "",
description: this.currentData ? this.currentData.description : "",
cost: this.currentData ? this.currentData.cost : {},
time: this.currentData ? this.currentData.time : {},
startName: this.currentData ? this.currentData.name : "",
};
},
methods: {
...mapActions("clients", ["getClients", "addClient", "updateClient"]),
processForm() {
const processFormAction = this.currentData
? this.updateClient
: this.addClient;
let requestData = {
name: this.name,
description: this.description,
cost: this.cost,
time: this.time,
};
if (this.currentData) {
requestData = {
update: {
payload: {
name: this.name,
description: this.description,
cost: this.cost,
time: this.time,
},
clientId: this.currentData.id,
},
};
}
const toastMessage = this.currentData
? `Updated ${this.name} Client`
: "Added a new Client";
processFormAction(requestData)
.then(() => {
this.$parent.close();
this.$buefy.toast.open({
message: toastMessage,
position: "is-top",
type: "is-primary",
container: "div.toast-space",
});
})
.catch((err) => {
this.$errorHandler.handleResponseError(err);
});
},
},
computed: {
...mapGetters("clients", ["clients"]),
},
};
</script> |
<template>
<main>
<div class="container-elements">
<div class="mt-5">
<a v-show="searchedFilmList != 0" class="anchor" href="#film-list">FILM</a>
<a v-show="searchedSeriesList != 0" class="anchor" href="#series-list">SERIE TV</a>
</div>
<div class="pt-3" v-show="searchedFilmList == 0">
<h2 class="text-white text-start display-2 text-center fw-bold">I <span class="main-text-color">FILM</span> DEL MOMENTO</h2>
<ElementsList
:searchedElements="trends"
:searchedCast="searchedFilmActors"
:genreList="movieGenre"
/>
</div>
<div class="py-5" v-show="searchedFilmList != 0" id="film-list">
<h2 class="text-white text-start display-2 text-center fw-bold">FILM</h2>
<ElementsList
:searchedElements="searchedFilmList"
:searchedCast="searchedFilmActors"
:genreList="movieGenre"
/>
</div>
<div class="py-4" v-show="searchedSeriesList != 0" id="series-list">
<h2 class="text-white text-start display-2 text-center fw-bold">SERIE TV</h2>
<ElementsList
:searchedElements="searchedSeriesList"
:searchedCast ="searchedSeriesActors"
:genreList="seriesGenre"
/>
</div>
</div>
</main>
</template>
<script>
import axios from 'axios';
import ElementsList from "./ElementsList.vue"
export default {
props:{
searchedFilmList:Array,
searchedSeriesList:Array,
searchedFilmActors:Array,
searchedSeriesActors:Array,
keyApi:String,
},
components:{
ElementsList,
},
data:function(){
return{
trends:[],
seriesGenre:[],
movieGenre:[],
}
},
created(){
axios.get(`https://api.themoviedb.org/3/trending/movie/day?api_key=${this.keyApi}`) // Facciamo una ricerca nei film e popoliamo il suo array
.then( (result) => {
this.trends = result.data.results
axios.get(`https://api.themoviedb.org/3/genre/movie/list?api_key=${this.keyApi}`)
.then((result) => {
this.movieGenre = result.data.genres
})
.catch((error) => {
console.warn(error)
})
})
axios.get(`https://api.themoviedb.org/3/genre/tv/list?api_key=${this.keyApi}`)
.then((result) => {
this.seriesGenre = result.data.genres
})
.catch((error) => {
console.warn(error)
})
.catch((error) => {
console.warn(error)
})
}
}
</script>
<style lang="scss">
@import "../styles/variables.scss";
// Style for both menu horizontal scroll
main{
margin-top: 150px;
}
.container-elements{
margin: 0 100px;
.anchor{
text-decoration: none;
color: white;
padding: 10px 15px;
text-align: center;
background-color: grey;
border-radius: 10px;
margin: 0 10px;
letter-spacing: 2px;
}
}
</style> |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { UsersComponent } from './users/users.component';
import { PostsComponent } from './posts/posts.component';
import { DetailsComponent } from './details/details.component';
import { TodoComponent } from './todo/todo.component';
const routes: Routes = [
{
path: '',
component: UsersComponent
},
{
path: 'details/:id',
component: DetailsComponent
},
{
path: 'posts',
component: PostsComponent
},
{
path: 'todo',
component: TodoComponent
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes)],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule { } |
import numpy as np
import torch
import re
import os
import wfdb
U_INDICES = [16, 23, 24, 31]
NO_U_INDICES = [0,1,2,3,4,5,6,7,8,9,
10,11,12,13,14,15,17,
18,19,20,21,22,25,26,
27,28,29,30]
def extract_info_from_name(filename):
parsed = {}
basename = os.path.basename(filename).split(".")[0]
pattern = r"session(\d+)_participant(\d+)_gesture(\d+)_trial(\d+)"
match = re.match(pattern, basename)
parsed['session'] = match.group(1)
parsed['participant'] = match.group(2)
parsed['gesture'] = match.group(3)
parsed['trial'] = match.group(4)
parsed['filename'] = filename
return parsed
def extract_basename(filename):
"""
Function to extract just the unique headers of the dat and hea files (removing the file spec)
"""
return os.path.splitext(filename)[0]
def extract_unique_values_from_folder(folder:str):
"""
Function to extract just the unique headers of the dat and hea files (removing the file name)
"""
unique = set()
for f in os.listdir(folder):
unique.add(extract_basename(os.path.join(folder, f)))
return list(unique)
def get_label(file):
info = extract_info_from_name(file)
return int(info['gesture'])
def load_file(file:str):
"""Load in a wav file
Args:
file (str): This is a filename where the .dat / .hea
has been stripped off
Returns:
_type_: Nd.Array
"""
wave_file = wfdb.rdrecord(file)
wave_data = wave_file.p_signal
#filter out the U signal
wave_data = wave_data[:, NO_U_INDICES]
return wave_data |
<template>
<q-banner rounded class="bg-grey-3">
<q-img :src=coaBackground height="160px">
<div class="absolute-full text-subtitle2 flex flex-center">
name: {{ name }}
<br/>
wins: {{ nWins }}
<br/>
losses: {{ nLosses }}
<br/>
ratio: {{ ratio }}
</div>
</q-img>
</q-banner>
</template>
<script lang="ts" setup>
import {
computed,
ComputedRef,
defineComponent,
} from 'vue';
import { asyncComputed } from '@vueuse/core';
import { useAuthStore } from 'src/stores/auth.store';
import { CoalitionChoice } from 'src/types';
import { useMatchHistoryStore } from 'src/stores/history.store';
import { useSocialStore } from '../stores/social.store';
const $soc = useSocialStore(); const $auth = useAuthStore();
const $his = useMatchHistoryStore();
defineComponent({ name: 'StatsBanner' });
const props = defineProps({
userId: {
type: Number, default: -1,
},
name: {
type: String, default: '',
},
nWins: {
type: Number, defaut: 0,
},
nLosses: {
type: Number, default: 0,
},
height: {
type: String,
},
});
const ratio = computed(() => $his.getUserMatchesHistory($auth.user.id)?.stats.ratio);
const isSelf = computed(() => (props.userId === $auth.user.id));
const rel = asyncComputed(async () => {
if (isSelf.value) { return undefined; }
// const res = $soc.getRelByUserId(props.userId);
// if (res) { return res; }
// try {
// await $soc.addRelByUserId(props.userId);
// } catch (e) {
// // e
// }
return $soc.getRelByUserId(props.userId);
});
const coalition: ComputedRef<CoalitionChoice> = computed(() => {
if (isSelf.value) { return $auth.user.coalition; }
if (rel.value) { return rel.value.to.coalition; }
return CoalitionChoice.FEDERATION;
});
const coaBackground = computed(() => `/${coalition.value}_background.jpg`);
</script> |
#!/usr/bin/python3
"""Function that prints a square with # character"""
def print_square(size):
"""prints square with # character"""
if type(size) is not int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
elif type(size) is float and size < 0:
raise TypeError("size must be an integer")
else:
for i in range(size):
for j in range(size):
print("#", end="")
print() |
from django.db import models
import random
import datetime
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
import os
from django.conf import settings
from django.utils.safestring import mark_safe
class Publisher(models.Model):
name = models.CharField(max_length=200)
website = models.URLField()
city = models.CharField(max_length=20, blank=True)
country = models.CharField(max_length=20, default='USA')
def __str__(self):
return self.name
class Book(models.Model):
CATEGORY_CHOICES = [
('S', 'Scinece&Tech'),
('F', 'Fiction'),
('B', 'Biography'),
('T', 'Travel'),
('O', 'Other')
]
title = models.CharField(max_length=200)
category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, default='S')
num_pages = models.PositiveIntegerField(default=100)
price = models.DecimalField(max_digits=10, decimal_places=2,validators=[MaxValueValidator(1000), MinValueValidator(0)])
publisher = models.ForeignKey(Publisher, related_name='books', on_delete=models.CASCADE)
description = models.TextField(blank=True)
num_reviews = models.PositiveIntegerField(default=0)
def __str__(self):
return self.title
class Member(User):
STATUS_CHOICES = [
(1, 'Regular member'),
(2, 'Premium Member'),
(3, 'Guest Member'),
]
status = models.IntegerField(choices=STATUS_CHOICES, default=1)
address = models.CharField(max_length=300, blank=True)
city = models.CharField(max_length=20, default='Windsor')
province = models.CharField(max_length=2, default='ON')
last_renewal = models.DateField(default=timezone.now)
auto_renew = models.BooleanField(default=True)
borrowed_books = models.ManyToManyField(Book, blank=True)
image = models.ImageField(upload_to='media', blank=True)
externalURL = models.URLField(blank=True)
def url(self):
if self.externalURL:
return self.externalURL
else:
return os.path.join('/', settings.MEDIA_URL, os.path.basename(str(self.image)))
def image_tag(self):
return mark_safe('<img src="{}" width="150" height="150" />'.format(self.url()))
image_tag.short_description = 'Image'
def url(self):
# returns a URL for either internal stored or external image url
if self.externalURL:
return self.externalURL
else:
# is this the best way to do this??
return os.path.join('/', settings.MEDIA_URL, os.path.basename(str(self.image)))
def image_tag(self):
# used in the admin site model as a "thumbnail"
return mark_safe('<img src="{}" width="50" height="50" />'.format(self.url()))
image_tag.short_description = 'Image'
class Order(models.Model):
ORDER_CHOICES = [
(0, 'Purchase'),
(1, 'Borrow')
]
books = models.ManyToManyField(Book)
member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='books')
order_type = models.IntegerField(choices=ORDER_CHOICES, default=1)
order_date = models.DateField(default=timezone.now)
def __str__(self):
return str(self.id)
def total_items(self):
return self.books.count()
class Review(models.Model):
reviewer = models.EmailField()
book = models.ForeignKey(Book, on_delete=models.CASCADE)
rating = models.PositiveIntegerField()
comments = models.TextField(blank=True)
date = models.DateField(default=timezone.now)
def __str__(self):
return str(self.id) |
// Given a number N and a bit number K, check if Kth index bit of N is set or not. A bit is called set if it is 1. Position of set bit '1' should be indexed starting with 0 from LSB side in binary representation of the number.
// Note: Index is starting from 0. You just need to return true or false, driver code will take care of printing "Yes" and "No".
// Example 1:
// Input:
// N = 4
// K = 0
// Output:
// No
// Explanation:
// Binary representation of 4 is 100, in which 0th index bit from LSB is not set. So, return false.
// Example 2:
// Input:
// N = 4
// K = 2
// Output:
// Yes
// Explanation:
// Binary representation of 4 is 100, in which 2nd index bit from LSB is set. So, return true.
// Example 3:
// Input:
// N = 500
// K = 3
// Output:
// No
// Explanation:
// Binary representation of 500 is 111110100, in which 3rd index bit from LSB is not set. So, return false.
// Your task:
// You don't have to read input or print anything. Your task is to complete the function checkKthbit that takes n and k as parameters and returns either true(if kth bit is set) or false(if kth bit is not set).
// Expected Time Complexity: O(1).
// Expected Auxiliary Space: O(1).
// Constraints:
// 1 ≤ N ≤ 109
// 0 ≤ K ≤ 31
bool checkKthBit(int n, int k) {
return ((n >> k) & 1) == 1;
} |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
part 'qr_scan_event.dart';
part 'qr_scan_state.dart';
class QRScanBloc extends Bloc<QRScanEvent, QRScanState> {
QRScanBloc() : super(const QRScanState()) {
on<QRScanOnDetectEvent>(_onQRScanOnDetect);
on<QRScanTryAgainEvent>(_onQRScanTryAgain);
}
Future<void> _onQRScanOnDetect(
QRScanOnDetectEvent event,
Emitter<QRScanState> emit,
) async {
emit(state.copyWith(
status: QRScanStatus.inProcess,
displayValue: event.displayValue,
));
debugPrint(state.displayValue.toString());
try {
await Future.delayed(const Duration(milliseconds: 1200));
if (state.displayValue.contains(RegExp(r'^\d+$'))) {
emit(state.copyWith(
displayValue: int.parse(state.displayValue).toString(),
inProcessMsg: 'Validating the Relevent Bicycle',
));
// call bicycle api and check the state
} else {
emit(state.copyWith(
errorMsg: '_Bad State : Cannot Validate QR Code',
status: QRScanStatus.failure,
));
throw Exception();
}
} catch (e) {
debugPrint(e.toString());
}
}
Future<void> _onQRScanTryAgain(
QRScanTryAgainEvent event,
Emitter<QRScanState> emit,
) async {
emit(state.copyWith(
displayValue: '',
errorMsg: 'Null',
inProcessMsg: 'Validating the\nQR Code',
status: QRScanStatus.initial,
));
}
} |
import { Box, Tooltip } from "@chakra-ui/react"
import { FC, PropsWithChildren, useEffect, useRef, useState } from "react"
import CopyToClipboard from "react-copy-to-clipboard"
import { useOnClickOutside } from "../hooks"
interface CopyTooltipProps extends PropsWithChildren {
copyValue: string
prompt?: string
message?: string
autoDismiss?: boolean
onClick?: () => void
}
export const CopyTooltip: FC<CopyTooltipProps> = ({
copyValue,
prompt = "Click to copy",
message = "Copied",
autoDismiss = true,
children,
onClick,
}) => {
const [visible, setVisible] = useState(false)
const timeoutIdRef = useRef<ReturnType<typeof setTimeout>>()
const clickOutsideRef = useRef<HTMLDivElement>(null)
useOnClickOutside(clickOutsideRef, () => setVisible(false))
useEffect(() => {
if (autoDismiss && visible) {
timeoutIdRef.current = setTimeout(() => setVisible(false), 2500)
}
return () => {
clearTimeout(timeoutIdRef.current)
}
}, [autoDismiss, visible])
return (
<Tooltip label={visible ? message : prompt} isOpen={visible || undefined}>
<Box ref={clickOutsideRef}>
{!onClick && (
<CopyToClipboard text={copyValue} onCopy={() => setVisible(true)}>
{children}
</CopyToClipboard>
)}
{onClick && <Box onClick={onClick}>{children}</Box>}
</Box>
</Tooltip>
)
} |
import React, { useContext, useRef, useState } from "react";
import { AuthContext } from "@/context/AuthContext";
import classNames from "classnames";
import styles from '@/app/posts/postspage.module.scss';
import { db, storage } from "@/firebase/config";
import { v4 as uuid } from 'uuid';
import { Timestamp, doc, setDoc } from "firebase/firestore";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";
function NewPost() {
const [text, setText] = useState("");
const [file, setFile] = useState(null);
const { user } = useContext(AuthContext);
const refPreview = useRef();
const handleUpload = (e)=>{
console.log("file: ",e.target);
setFile(e.target.files[0]);
if(e.target.files[0].type.includes("image")){
var reader = new FileReader();
reader.onload = function (e) {
refPreview.current.children[1].src = e.target.result;
refPreview.current.style.display='flex';
};
reader.readAsDataURL(e.target.files[0]);
}
else{
refPreview.current.children[1].src = "/file.png";
refPreview.current.style.display='flex';
}
}
const handleCancel = (e)=>{
setFile(null);
refPreview.current.children[1].src="";
refPreview.current.style.display='none';
}
const handlePost = async() => {
try{
const postId = uuid();
if(file){
const storageRef = ref(storage, uuid());
uploadBytesResumable(storageRef, file).then(() => {
getDownloadURL(storageRef).then( async(downloadURL) => {
await setDoc(doc(db, "posts", user.uid),{
[postId]:{
text,
posterId: user.uid,
postDate: Timestamp.now(),
like: {},
comment: {},
date: Timestamp.now(),
img: downloadURL,
}
}, {merge: true});
});
});
}
else{
await setDoc(doc(db, "posts", user.uid),{
[postId]:{
text,
posterId: user.uid,
postDate: Timestamp.now(),
like: {},
comment: {},
date: Timestamp.now(),
}
}, {merge: true});
}
}
catch (err ){
}
setText("");
setFile(null);
refPreview.current.children[1].src="";
refPreview.current.style.display='none';
};
return (
<>
<div className={styles.newPostContainer}>
<div className={styles.newPost}>
<div className={styles.postTitle}>
<img src={user?user.photoURL :"/user.png"} style={{width:"50px", height:"50px", borderRadius:"50%", objectFit:"cover"}}/>
<div className={styles.postInfo}>
<div className={styles.name}>{user.displayName}</div>
</div>
</div>
<textarea onChange={e=>setText(e.target.value)} value={text} placeholder="在想甚麼?"></textarea>
<div className={styles.previewbox} style={{display: "none"}} ref={refPreview}>
<div className={styles.previewInfo}>
<span>{ file && file.name}</span>
<button className={styles.close_btn} onClick={handleCancel}>X</button>
</div>
<img style={{height:"250px", width:"100%", objectFit:"cover"}}></img>
</div>
<div className={styles.btnList}>
<input type="file" style={{display: "none"}} accept="image/*" id="file" onChange={handleUpload}/>
<label className={classNames(styles.btn,styles.pointer,styles.bc_gray)} htmlFor="file">
<img src="/img.png" alt="" />
加入圖片
</label>
{
(text || file)
? <button className={classNames(styles.btn,styles.pointer,styles.bc_blue)} onClick={handlePost}>發布</button>
: <button className={classNames(styles.btn,styles.bc_gray)} >發布</button>
}
</div>
</div>
</div>
</>
);
}
export default NewPost; |
import { type FC } from "react";
import Sidebar from "./Sidebar";
import Topbar from "./Topbar";
interface ILayoutProps {
children: React.ReactNode;
}
const Layout: FC<ILayoutProps> = ({ children }) => {
return (
<div className="min-w-screen flex relative w-full h-full bg-white">
<Sidebar />
<div className="w-5/6 h-full flex flex-col">
<Topbar />
<div className="w-full flex-1 overflow-y-auto">{children}</div>
</div>
</div>
);
};
export default Layout; |
// Different data types and attributes example
class DataTypeAttributes extends HTMLElement {
// Return list of attributes
static get observedAttributes() {
return ['text', 'integer', 'number', 'date', 'boolean'];
}
// Callback function that the browser calls to inform the custom element that one of its
// attributes has changed.
attributeChangedCallback(name, oldValue, newValue) {
// Update the information
this._updateInfo();
}
// Public method to set the text attribute to something random
setRandomText() {
// Set character list
const charList = 'abcdefghijklmnopqrstuvwxyz';
// Set text list
let textList = [];
// For each character
for (let count = 0; count < 10; count++) {
// Add random character to text list
textList.push(charList.charAt(Math.random() * charList.length));
}
// Set text attribute
this.setAttribute('text', textList.join(''));
}
// Public method to set the integer attribute to something random
setRandomInteger() {
// Make a random integer
const randomInteger = Math.floor(Math.random() * 1000000);
// Set integer attribute
this.setAttribute('integer', randomInteger.toString());
}
// Public method to set the number attribute to something random
setRandomNumber() {
// Make a random number
const randomNumber = (Math.random() * 1000000);
// Set number attribute
this.setAttribute('number', randomNumber.toFixed(4));
}
// Public method to set the date attribute to something random
setRandomDate() {
// Create random date
const randomDate = new Date((new Date()) - Math.floor(Math.random() * 10000000000));
// Set date attribute
this.setAttribute('date', randomDate.toISOString());
}
// Public method to switch the boolean attribute
switchBoolean() {
// If the attribute exists
if (this.hasAttribute('boolean') === true) {
// Remove the attribute
this.removeAttribute('boolean');
} else {
// Add the attribute (without a value)
this.setAttribute('boolean', '');
}
}
// Get text method
_getText() {
// Get text attribute value
const textValue = this.getAttribute('text');
// If nothing then return default
if (!textValue) return '';
// Return the text value
return textValue;
}
// Get integer method
_getInteger() {
// Get integer attribute value
const integerValue = this.getAttribute('integer');
// If nothing then return default
if (!integerValue) return 0;
// Convert into an integer
const integer = parseInt(integerValue);
// If not a valid number
if (isNaN(integer) === true) return 0;
// Return the integer
return integer;
}
// Get number method
_getNumber() {
// Get number attribute value
const numberValue = this.getAttribute('number');
// If nothing then return default
if (!numberValue) return 0;
// Convert into a number
const number = parseFloat(numberValue);
// If not a valid number
if (isNaN(number) === true) return 0;
// Return the number
return number;
}
// Get date method
_getDate() {
// Get date attribute value
const dateValue = this.getAttribute('date');
// If nothing then return default
if (!dateValue) return null;
// Parse the ISO date into milliseconds
const dateMilliseconds = Date.parse(dateValue);
// Convert into a date
const date = new Date(dateMilliseconds);
// Return the date
return date;
}
// Get boolean method
_getBoolean() {
// If has attribute then return true value
if (this.hasAttribute('boolean') === true) return true;
// Otherwise return false value
return false;
}
// Update the text information
_updateInfo() {
// Get current values
const text = this._getText();
const integer = this._getInteger();
const number = this._getNumber();
const date = this._getDate();
const boolean = this._getBoolean();
// Set HTML
this.innerHTML =
`
<b>text = ${text}</b><br>
<b>integer = ${integer}</b><br>
<b>number = ${number}</b><br>
<b>date = ${date}</b><br>
<b>boolean = ${boolean}</b><br>
`;
}
}
// Tell the browser about the new tag and the class it is linked to
customElements.define('data-type-attributes', DataTypeAttributes); |
package domain;
public class Employee extends Person implements Worker, Comparable {
protected int no;
protected int year;
public Employee(int no, String firstName, String lastName) {
super(firstName, lastName);
this.no = no;
}
public Employee(int no, String firstName, String lastName, int year) {
super(firstName, lastName);
this.no = no;
this.year = year;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getYear() {
return year;
}
@Override
public String toString() {
return "Employee: No - " + no + ", Year - " + year + ", First Name - " + firstName + ", Last Name - " + lastName;
}
@Override
public int hashCode() {
System.out.println("hashCode() on Employee with no: " + no);
return no;
}
@Override
public boolean equals(Object obj) {
System.out.println("equals() on Employee with no: " + no);
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Employee other = (Employee) obj;
System.out.println("equals() on Employee with no: " + this + " other Employee with no: " + obj);
return no == other.no;
}
@Override
public void work() {
System.out.println("Employee is working!");
}
@Override
public double calculateSalary() {
return year * BASE_SALARY;
}
@Override
public int compareTo(Object o) {
Employee other = (Employee) o;
return Integer.compare(no, other.no);
// We can use the code instead of it:
// int result = Integer.compare(no, other.no);
// if (no == other.no) {
// result = 0;
// } else if (no < other.no) {
// result = -1;
// } else {
// result = 1;
// }
// return result;
}
// @Override
// public int compareTo(Object o) {
// Employee other = (Employee) o;
// return lastName.compareTo(other.lastName);
// }
} |
package TOML;
# -------------------------------------------------------------------
# TOML - Parser for Tom's Obvious, Minimal Language.
#
# Copyright (C) 2013 Darren Chamberlain <darren@cpan.org>
# -------------------------------------------------------------------
use 5.008005;
use strict;
use warnings;
use Exporter 'import';
our ($VERSION, @EXPORT, @_NAMESPACE, $PARSER);
use B;
use Carp qw(croak);
use TOML::Parser 0.03;
$VERSION = "0.97";
@EXPORT = qw(from_toml to_toml);
$PARSER = TOML::Parser->new(inflate_boolean => sub { $_[0] });
sub to_toml {
my $stuff = shift;
local @_NAMESPACE = ();
_to_toml($stuff);
}
sub _to_toml {
my ($stuff) = @_;
if (ref $stuff eq 'HASH') {
my $res = '';
my @keys = sort keys %$stuff;
for my $key (grep { ref $stuff->{$_} ne 'HASH' } @keys) {
my $val = $stuff->{$key};
$res .= "$key = " . _serialize($val) . "\n";
}
for my $key (grep { ref $stuff->{$_} eq 'HASH' } @keys) {
my $val = $stuff->{$key};
local @_NAMESPACE = (@_NAMESPACE, $key);
$res .= sprintf("[%s]\n", join(".", @_NAMESPACE));
$res .= _to_toml($val);
}
return $res;
} else {
croak("You cannot convert non-HashRef values to TOML");
}
}
sub _serialize {
my $value = shift;
my $b_obj = B::svref_2object(\$value);
my $flags = $b_obj->FLAGS;
return $value
if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV?
my $type = ref($value);
if (!$type) {
return string_to_json($value);
} elsif ($type eq 'ARRAY') {
return sprintf('[%s]', join(", ", map { _serialize($_) } @$value));
} elsif ($type eq 'SCALAR') {
if (defined $$value) {
if ($$value eq '0') {
return 'false';
} elsif ($$value eq '1') {
return 'true';
} else {
croak("cannot encode reference to scalar");
}
}
croak("cannot encode reference to scalar");
}
croak("Bad type in to_toml: $type");
}
my %esc = (
"\n" => '\n',
"\r" => '\r',
"\t" => '\t',
"\f" => '\f',
"\b" => '\b',
"\"" => '\"',
"\\" => '\\\\',
"\'" => '\\\'',
);
sub string_to_json {
my ($arg) = @_;
$arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
$arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
return '"' . $arg . '"';
}
sub from_toml {
my $string = shift;
local $@;
my $toml = eval { $PARSER->parse($string) };
return wantarray ? ($toml, $@) : $toml;
}
1;
__END__
=encoding utf-8
=for stopwords versa
=head1 NAME
TOML - Parser for Tom's Obvious, Minimal Language.
=head1 SYNOPSIS
use TOML qw(from_toml to_toml);
# Parsing toml
my $toml = slurp("~/.foo.toml");
my $data = from_toml($toml);
# With error checking
my ($data, $err) = from_toml($toml);
unless ($data) {
die "Error parsing toml: $err";
}
# Creating toml
my $toml = to_toml($data);
=head1 DESCRIPTION
C<TOML> implements a parser for Tom's Obvious, Minimal Language, as
defined at L<https://github.com/mojombo/toml>. C<TOML> exports two
subroutines, C<from_toml> and C<to_toml>,
=head1 FAQ
=over 4
=item How change how to de-serialize?
You can change C<$TOML::PARSER> for change how to de-serialize.
example:
use TOML;
use TOML::Parser;
local $TOML::PARSER = TOML::Parser->new(
inflate_boolean => sub { $_[0] eq 'true' ? \1 : \0 },
);
my $data = TOML::from_toml('foo = true');
=back
=head1 FUNCTIONS
=over 4
=item from_toml
C<from_toml> transforms a string containing toml to a perl data
structure or vice versa. This data structure complies with the tests
provided at L<https://github.com/mojombo/toml/tree/master/tests>.
If called in list context, C<from_toml> produces a (C<hash>,
C<error_string>) tuple, where C<error_string> is C<undef> on
non-errors. If there is an error, then C<hash> will be undefined and
C<error_string> will contains (scant) details about said error.
=item to_toml
C<to_toml> transforms a perl data structure into toml-formatted
string.
=back
=head1 SEE ALSO
L<TOML::Parser>
=head1 LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02111-1301 USA
=head1 AUTHOR
Darren Chamberlain <darren@cpan.org>
=head1 CONTRIBUTORS
=over 4
=item Tokuhiro Matsuno <tokuhirom@cpan.org>
=item Matthias Bethke <matthias@towiski.de>
=item Sergey Romanov <complefor@rambler.ru>
=item karupanerura <karupa@cpan.org>
=back |
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MusicWebApp1.Models;
namespace MusicWebApp1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ArtistController : ControllerBase
{
private readonly MusicApiContext _context;
public ArtistController(MusicApiContext context)
{
_context = context;
}
// GET: api/Artist
[HttpGet]
public async Task<ActionResult<IEnumerable<Artist>>> GetArtists()
{
if (_context.Artists == null)
{
return NotFound();
}
return await _context.Artists.ToListAsync();
}
// GET: api/Artist/5
[HttpGet("{id}")]
public async Task<ActionResult<Artist>> GetArtist(int id)
{
if (_context.Artists == null)
{
return NotFound();
}
var artist = await _context.Artists.FindAsync(id);
if (artist == null)
{
return NotFound();
}
return artist;
}
// PUT: api/Artist/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutArtist(int id, Artist artist)
{
if (id != artist.Id)
{
return BadRequest();
}
_context.Entry(artist).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ArtistExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Artist
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Artist>> PostArtist(Artist artist)
{
if (_context.Artists == null)
{
return Problem("Entity set 'MusicApiContext.Artists' is null.");
}
_context.Artists.Add(artist);
await _context.SaveChangesAsync();
return CreatedAtAction("GetArtist", new { id = artist.Id }, artist);
}
// DELETE: api/Artist/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteArtist(int id)
{
if (_context.Artists == null)
{
return NotFound();
}
var artist = await _context.Artists.FindAsync(id);
if (artist == null)
{
return NotFound();
}
_context.Artists.Remove(artist);
await _context.SaveChangesAsync();
return NoContent();
}
private bool ArtistExists(int id)
{
return (_context.Artists?.Any(e => e.Id == id)).GetValueOrDefault();
}
}
} |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstclear_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ataboada <ataboada@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/05/08 18:54:14 by ataboada #+# #+# */
/* Updated: 2023/10/06 17:35:41 by ataboada ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/**
* @brief Deletes and frees the given element and every successor of that
* element, using the function ’del’ and free(3). Finally, the pointer to the
* list must be set to NULL.
* @param lst The address of a pointer to an element.
* @param del The address of the function used to delete the content of the
* element.
* @return Nothing.
*/
void ft_lstclear(t_list **lst, void (*del)(void *))
{
t_list *temp;
if (!lst || !del || !*(lst))
{
return ;
}
while (*lst)
{
temp = (*lst)->next;
ft_lstdelone(*lst, del);
*lst = temp;
}
lst = 0;
} |
// (C) 2024 FOTEC Forschungs- und Technologietransfer GmbH
// Das Forschungsunternehmen der Fachhochschule Wiener Neustadt
//
// Kontakt biss@fotec.at / www.fotec.at
//
// Erstversion vom 15.11.2023 10:55
// Entwickler Mandl Matthias (MMa)
// Projekt IXchange
using System;
using System.Linq;
using System.Threading.Tasks;
using Biss.Apps.Attributes;
using Biss.Apps.Enum;
using Biss.Apps.ViewModel;
using Biss.Dc.Server;
using ConnectivityHost.Helper;
using IXchange.Service.AppConnectivity.DataConnector;
using IXchange.Service.AppConnectivity.Helper;
namespace ConnectivityHost.BaseApp.ViewModel
{
/// <summary>
/// <para>Viewmodel fürs Nachricht versenden</para>
/// Klasse VmMessage. (C) 2021 FOTEC Forschungs- und Technologietransfer GmbH
/// </summary>
[ViewName("ViewMessage")]
public class VmMessage : VmProjectBase
{
/// <summary>
/// Design Instanz für XAML d:DataContext="{x:Static viewmodels:VmMessage.DesignInstance}"
/// </summary>
public static VmMessage DesignInstance = new VmMessage();
/// <summary>
/// VmMessage
/// </summary>
public VmMessage() : base("Nachricht")
{
View.ShowFooter = false;
View.ShowHeader = true;
View.ShowBack = true;
View.ShowMenu = false;
}
#region Properties
/// <summary>
/// Send via Push Command
/// </summary>
public VmCommand CmdSend { get; set; } = null!;
/// <summary>
/// Nachrichten Text
/// </summary>
public VmEntry TitleEntry { get; set; } = new(EnumVmEntryBehavior.Instantly, "Überschrift");
/// <summary>
/// Nachrichten Text
/// </summary>
public VmEntry MessageEntry { get; set; } = new(EnumVmEntryBehavior.Instantly, "Nachricht");
/// <summary>
/// Daten fürs Versenden der Nachricht.
/// </summary>
public SendMessageData Data { get; set; } = new();
/// <summary>
/// Dc Connection
/// </summary>
public IDcConnections DcConnections { get; set; } = null!;
/// <summary>
/// Server Remote Calls
/// </summary>
public IServerRemoteCalls ServerRemoteCalls { get; set; } = null!;
#endregion
/// <summary>
/// Wird aufgerufen sobald die View initialisiert wurde
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public override Task OnActivated(object? args = null)
{
if (args is SendMessageData data)
{
Data = data;
if (Data.SendVia == SendViaEnum.Email)
{
TitleEntry.Title = "Betreff";
}
}
TitleEntry.ValidateFunc = Validate;
MessageEntry.ValidateFunc = Validate;
View.BusyClear();
base.OnActivated(args);
return Task.CompletedTask;
}
/// <summary>
/// Commands Initialisieren (aufruf im Kostruktor von VmBase)
/// </summary>
#pragma warning disable CA1506
protected override void InitializeCommands()
#pragma warning restore CA1506
{
CmdSend = new VmCommand("Senden", async () =>
{
switch (Data.SendVia)
{
case SendViaEnum.Dc:
var successes = 0;
var fails = 0;
var currentConnectedDeviceIds = DcConnections.GetClients();
foreach (var tableDevice in Data.Devices)
{
if (currentConnectedDeviceIds.All(x => x.DeviceId != tableDevice.Id))
{
fails++;
continue;
}
try
{
await ((ServerRemoteCalls) ServerRemoteCalls).SendMessage(MessageEntry.Value, TitleEntry.Value, tableDevice.Id, null).ConfigureAwait(true);
successes++;
}
catch (Exception)
{
fails++;
}
}
_ = await MsgBox.Show($"Es kamen {successes} Benachrichtigungen an und {fails} nicht an!").ConfigureAwait(true);
break;
case SendViaEnum.Push:
var tokens = Data.Devices.Where(x => !string.IsNullOrWhiteSpace(x.DeviceToken)).Select(x => x.DeviceToken).ToList();
var success = 0;
var fail = 0;
if (tokens.Any())
{
if (tokens.Count > 500)
{
#pragma warning disable CS0618 // Type or member is obsolete
var chunks = tokens.Split(500);
#pragma warning restore CS0618 // Type or member is obsolete
foreach (var chunk in chunks)
{
var result = await Push.SendMessageToDevices(TitleEntry.Value, MessageEntry.Value, chunk).ConfigureAwait(true);
success += result.SuccessCount;
fail += result.FailureCount;
}
}
else
{
var result = await Push.SendMessageToDevices(TitleEntry.Value, MessageEntry.Value, tokens).ConfigureAwait(true);
success = result.SuccessCount;
fail = result.FailureCount;
}
_ = await MsgBox.Show($"Es kamen {success} Benachrichtigungen an und {fail} nicht an!").ConfigureAwait(true);
}
break;
}
await Nav.Back().ConfigureAwait(true);
},
() =>
!string.IsNullOrWhiteSpace(TitleEntry.Value) && !string.IsNullOrWhiteSpace(MessageEntry.Value));
}
private (string, bool) Validate(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return ("Darf nicht leer sein!", true);
}
CmdSend.CanExecute();
return ("", true);
}
}
} |
import Link from "next/link"
import { Button } from "./ui/button"
import { Card } from "./ui/card"
const FeatureSection = () => {
return (
<section
id="features"
className="container py-8 space-y-6 rounded-lg md:py-12 lg:py-24"
>
<div className="mx-auto flex max-w-[58rem] flex-col items-center space-y-4 text-center">
<h2 className="font-heading text-3xl leading-[1.1] sm:text-3xl md:text-6xl">
Features
</h2>
<p className="max-w-[85%] leading-normal text-muted-foreground sm:text-lg sm:leading-7">
We provide comprehensive computer repair, updating, and
troubleshooting services to individuals and businesses.
</p>
</div>
<div className="mx-auto grid justify-center gap-4 sm:grid-cols-2 md:max-w-[64rem] md:grid-cols-3">
<Card>
<div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-12 h-12 lucide lucide-shield-alert"
>
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
<path d="M12 8v4"></path>
<path d="M12 16h.01"></path>
</svg>
<div className="space-y-2">
<h3 className="font-bold">Virus Removal</h3>
<p className="text-sm text-muted-foreground">
Viruses, malware, and
spyware from your computer to ensure it's running smoothly
and securely.
</p>
</div>
</div>
</Card>
<Card>
<div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-12 h-12 lucide lucide-download"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" x2="12" y1="15" y2="3"></line>
</svg>
<div className="space-y-2">
<h3 className="font-bold">Software Installation</h3>
<p className="text-sm text-muted-foreground">
Install and configure software programs,
productivity tools, antivirus software, and multimedia apps.
</p>
</div>
</div>
</Card>
<Card>
<div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-12 h-12 lucide lucide-screen-share"
>
<path d="M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3"></path>
<path d="M8 21h8"></path>
<path d="M12 17v4"></path>
<path d="m17 8 5-5"></path>
<path d="M17 3h5v5"></path>
</svg>
<div className="space-y-2">
<h3 className="font-bold">Remote Support</h3>
<p className="text-sm text-muted-foreground">
We provide remote support to diagnose and fix
your computer issues without the need for an in-person visit.
</p>
</div>
</div>
</Card>
<Card>
<div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6">
<svg viewBox="0 0 24 24" className="w-12 h-12 fill-current">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="lucide lucideLaptop"
>
<path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"></path>
</svg>{" "}
</svg>
<div className="space-y-2">
<h3 className="font-bold">Operating System Updates</h3>
<p className="text-sm text-muted-foreground">
Upgrade your operating system to the latest
version, ensuring you have access to the latest features and
security updates.
</p>
</div>
</div>
</Card>
<Card>
<div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-12 h-12 lucide lucideWrench"
>
<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path>
</svg>
<div className="space-y-2">
<h3 className="font-bold">System Optimization</h3>
<p className="text-sm text-muted-foreground">
We can help you optimize your computer's performance by
cleaning up unnecessary files, tweaking settings to improve
speed and efficiency
</p>
</div>
</div>
</Card>
<Card>
<div className="flex h-[fit] gap-2 flex-col justify-between rounded-md p-6">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-12 h-12 lucide lucide-hard-drive"
>
<line x1="22" x2="2" y1="12" y2="12"></line>
<path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"></path>
<line x1="6" x2="6.01" y1="16" y2="16"></line>
<line x1="10" x2="10.01" y1="16" y2="16"></line>
</svg>
<div className="space-y-2">
<h3 className="font-bold">Hardware Upgrades</h3>
<p className="text-sm text-muted-foreground">
If your computer is running slowly or need more storage space,
we can upgrade your hardware, including RAM, hard drives, and
graphics cards
</p>
</div>
</div>
</Card>
</div>
<div className="mx-auto text-center md:max-w-[58rem]">
<p className="leading-normal text-muted-foreground sm:text-lg sm:leading-7">
Troubleshoot can help you with a wide range of computer problems,
including hardware issues, software installation, virus removal, and
system optimization.
</p>
</div>
<div className="mx-auto text-center md:max-w-[58rem]">
<Button><Link href={"/faq"}>
Check out FAQ</Link></Button>
</div>
</section>
)
}
export default FeatureSection |
import User from "../models/userModel.js";
import bcrypt from "bcryptjs";
import generateToken from "../utils/jwtToken.js";
import sendEmail from "../utils/sendEmail.js";
import { sendVerificationCode } from "../utils/sendEmailSignUp.js";
import generateVerificationCode from "../utils/VerificationCode.js";
import { sendOTPNo } from "../utils/SendOtpPhoneNo.js";
// import crypto from "crypto"
// ___________________________Sign Up________________________
// const generateVerificationCode = () => {
// return Math.random().toString(36).substr(2, 6).toUpperCase();
// };
const signUp = async (req, res) => {
try {
const { firstName, lastName, email, password, phoneNumber, dob, gender } = req.body;
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(409).json({ message: 'Email is already registered' });
}
if (!req.file) {
return res.status(400).json({ message: 'Please upload your image' });
}
const avatarPath = req.file.path;
const encPassword = await bcrypt.hash(password, 12);
// Generate a verification code for email
const verificationCode = generateVerificationCode();
const verificationCodeExpiresAt = new Date(Date.now() + 120000); // 120,000 milliseconds = 2 minute (adjust as needed)
// Generate a verification code for phone number
const isVerificationCode = generateVerificationCode();
const isVerificationCodeExpiresAt = new Date(Date.now() + 120000); // 900,000 milliseconds = 15 minute (adjust as needed)
// console.log('verificationCode', verificationCode);
const newUser = new User({
firstName,
lastName,
email,
password: encPassword,
phoneNumber,
dob,
gender,
avatar: avatarPath,
verified: false, //for email
verificationCode,
verificationCodeExpiresAt,
isVerified: false, //for Phone No
isVerificationCode,
isVerificationCodeExpiresAt,
});
// console.log('newUser', newUser);
await newUser.save();
// Send the verification code to the user's email
// console.log('email, verificationCode', email, verificationCode);
await sendVerificationCode(email, verificationCode);
await sendOTPNo(phoneNumber, isVerificationCode)
return res.status(201).json({
success: true,
message: "User created successfully. Please verify your Phone No.",
email,
});
}
catch (error) {
console.error('Error in signUp:', error);
return res.status(500).json({ message: 'Internal server error' });
}
};
export default signUp;
export const verifyCode = async (req, res) => {
try {
console.log('req.body', req.body)
const { email, verificationCode } = req.body;
// const user = await User.findOne({ email });
const user = await User.findOne({ verificationCode });
console.log('verificationCode', verificationCode);
console.log('user.verificationCode', user?.verificationCode);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
// Check if the verification code has expired
if (user.verificationCodeExpiresAt < new Date()) {
return res.status(400).json({ message: 'Verification code has expired' });
}
if (user.verificationCode === verificationCode) {
// Update the user's record to mark it as verified
await User.findByIdAndUpdate(user._id, { verified: true });
user.verificationCode = undefined;
user.verificationCodeExpiresAt = undefined;
await user.save();
return res.status(200).json({ message: 'Verification successful' });
} else {
return res.status(400).json({ message: 'Invalid verification code' });
}
} catch (error) {
console.error('Error in verifyCode:', error);
return res.status(500).json({ message: 'Internal server error' });
}
};
export const resendVerificationCode = async (req, res) => {
try {
const { email } = req.body;
const user = await User.findOne({ email });
console.log("🚀 ~ Resend user:", user)
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
if (user.verified) {
return res.status(400).json({ message: 'User is already verified' });
}
// Check if the verification code has expired
if (user.verificationCodeExpiresAt && user.verificationCodeExpiresAt < new Date()) {
// Generate a new verification code
const verificationCode = generateVerificationCode();
console.log('New verificationCode', verificationCode);
// Update the user's verification code and expiration time in the database
user.verificationCode = verificationCode;
user.verificationCodeExpiresAt = new Date(Date.now() + 60000); // 60,000 milliseconds = 1 minute (adjust as needed)
await user.save();
// Send the new verification code to the user's email
await sendVerificationCode(email, verificationCode);
return res.status(200).json({ message: 'Verification code resent successfully' });
}
else {
return res.status(400).json({ message: 'Verification code is still valid' });
}
} catch (error) {
console.error('Error in resendVerificationCode:', error);
return res.status(500).json({ message: 'Internal server error' });
}
};
// verify phone number
export const verifyCodePhoneNo = async (req, res) => {
try {
const { phoneNumber, isVerificationCode } = req.body;
console.log('isVerificationCode', isVerificationCode)
// const user = await User.findOne({ email });
const user = await User.findOne({ isVerificationCode });
console.log('isVerificationCode', isVerificationCode);
console.log('user.isVerificationCode', user?.isVerificationCode);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
// Check if the verification code has expired
if (user.isVerificationCodeExpiresAt < new Date()) {
return res.status(400).json({ message: 'Verification code has expired' });
}
if (user.isVerificationCode === isVerificationCode) {
// Update the user's record to mark it as verified
await User.findByIdAndUpdate(user._id, { isVerified: true });
user.isVerificationCode = undefined;
user.isVerificationCodeExpiresAt = undefined;
await user.save();
return res.status(200).json({ message: 'Verification successful' });
} else {
return res.status(400).json({ message: 'Invalid verification code' });
}
} catch (error) {
console.error('Error in verifyCode:', error);
return res.status(500).json({ message: 'Internal server error' });
}
};
export const resendOtpNo = async (req, res) => {
try {
const { email, phoneNumber } = req.body;
console.log('email', email);
console.log('phoneNumber', phoneNumber);
const user = await User.findOne({ email });
console.log('user', user);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
if (user.isVerified) {
return res.status(400).json({ message: 'User is already verified' });
}
// Check if the verification code has expired
if (user.isVerificationCodeExpiresAt && user.isVerificationCodeExpiresAt < new Date()) {
const isVerificationCode = generateVerificationCode();
console.log('New isVerificationCode', isVerificationCode);
// Update the user's verification code and expiration time in the database
user.isVerificationCode = isVerificationCode;
user.isVerificationCodeExpiresAt = new Date(Date.now() + 120000) // 900000 milliseconds = 15 minutes (adjust as needed)
await user.save();
// Send the new verification code to the user's phone number
await sendVerificationCode(phoneNumber, isVerificationCode);
return res.status(200).json({ message: 'Verification code resent successfully' });
}
else {
return res.status(400).json({ message: 'Verification code is still valid' });
}
} catch (error) {
console.error('Error in resendOtpNo:', error);
return res.status(500).json({ message: 'Internal server error' });
}
};
// const signUp = async (req, res) => {
// try {
// const { firstName, lastName, email, password, dob, gender } = req.body;
// const existingUser = await User.findOne({ email });
// if (existingUser) {
// return res.status(409).json({ message: 'Email is already registered' });
// }
// if (!req.file) {
// return res.status(400).json({ message: 'Please upload your image' });
// }
// const avatarPath = req.file.path;
// const encPassword = await bcrypt.hash(password, 12);
// const newUser = new User({
// firstName,
// lastName,
// email,
// password: encPassword,
// dob,
// gender,
// avatar: avatarPath,
// });
// await newUser.save();
// return res.status(201).json({ message: 'User created successfully' });
// } catch (error) {
// console.error('Error in signUp:', error);
// return res.status(500).json({ message: 'Internal server error' });
// }
// }
// export default signUp;
// ___________________________Login________________________
export const userLogin = async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ message: 'Invalid email or password' });
}
if (!user.verified) {
return res.status(401).json({ message: "Account not verified. Please verify your email first." });
}
// if (!user.phoneNumber || !user.isVerified) {
// return res.status(401).json({ message: "Account not verified. Please verify your PhoneNo first." });
// // await res.status(201).json({ message: "Account not verified. Please verify your PhoneNo first." });
// }
const token = generateToken(email);
res.status(200).json({ message: 'User signed in successfully . Please verify your PhoneNo first.', token, user });
} catch (error) {
console.error('Error in signIn User:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
// ___________________________Forget password email________________________
export const forgotPassword = async (req, res, next) => {
try {
const { email } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
const resetToken = generateToken(email);
user.resetPasswordToken = resetToken;
user.resetPasswordExpire = Date.now() + 3600000;
await user.save();
const verifyUrl = `${process.env.FRONTEND_URL}/password/reset/${resetToken}`;
const message = `Your password reset token is ttemp :- \n\n${verifyUrl}\n\nIf you have not requested this email, please ignore it.`;
await sendEmail({
email: user.email,
subject: 'My App Password Reset',
message,
});
res.status(200).json({
success: true,
message: `Email sent to ${user.email} successfully`,
});
} catch (error) {
console.error('Error in forgotPassword:', error);
res.status(500).json({ message: 'Failed to send email' });
}
};
// ___________________________Reset Password________________________
export const resetPassword = async (req, res, next) => {
try {
const { token } = req.params;
const { password, confirmPassword } = req.body;
const user = await User.findOne({
resetPasswordToken: token,
});
if (!user) {
return res.status(400).json({ message: 'Invalid or expired reset token' });
}
const encPassword = await bcrypt.hash(password, 12);
// Update the user's password and clear the reset token fields
user.password = encPassword;
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
await user.save();
// Respond with a success message
res.status(200).json({ success: true, message: 'Password reset successful' });
} catch (error) {
console.error('Error in resetPassword:', error);
res.status(500).json({ message: 'Failed to reset password' });
}
};
// ___________________________User Auth________________________
export const userAuth = (req, res) => {
res.status(200).json({ message: 'Authentication Successfully', user: req.user });
};
// ___________________________Update Password________________________
// export const updatePassword = async (req, res, next) => {
// try {
// const user = await User.findById(req.user._id);
// const isPasswordMatched = await bcrypt.compare(
// req.body.oldPassword.toString(),
// user.password.toString()
// );
// if (!isPasswordMatched) {
// return res.status(404).json({ message: 'Old password is incorrect' });
// }
// if (req.body.newPassword !== req.body.confirmPassword) {
// return res.status(400).json({ message: 'Passwords do not match' });
// }
// const encPassword = await bcrypt.hash(req.body.newPassword, 12);
// user.password = encPassword;
// await user.save();
// res.status(200).json({ success: true, message: 'Password updated successfully' });
// } catch (error) {
// console.error('Error in updatePassword:', error);
// res.status(500).json({ message: 'Failed to update password' });
// }
// };
export const updatePassword = async (req, res, next) => {
try {
const user = await User.findById(req.user._id);
console.log('user update', user);
console.log('req.body', req.body)
console.log("req.body.oldPassword", req.body.oldPassword)
console.log("user.password", user.password)
const isPasswordMatched = await bcrypt.compare(req.body.oldPassword, user.password,);
// const isPasswordMatched = await bcrypt.compare(
// req.body.oldPassword.toString(),
// user.password.toString()
// );
console.log('isPasswordMatched', isPasswordMatched)
if (!isPasswordMatched) {
return res.status(404).json({ message: 'Old password is incorrect' });
}
if (req.body.newPassword !== req.body.confirmPassword) {
return res.status(400).json({ message: 'Password do not match' });
}
// Password bcrypt
const encPassword = await bcrypt.hash(req.body.newPassword, 12);
// user.password = req.body.newPassword;
user.password = encPassword;
await user.save();
res.status(200).json({ success: true, message: 'Password updated successfully' });
} catch (error) {
console.error('Error in updatePassword:', error);
res.status(500).json({ message: 'Failed to update password' });
}
};
// ___________________________Update Profile________________________
export const updateProfile = async (req, res) => {
try {
// Find the user by ID
const userId = req.user.id;
console.log(" updateProfile ~ userId:", userId)
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
// Update the user's avatar if provided
if (req.file) {
user.avatar = req.file.path;
}
console.log(" updateProfile ~ req.file:", req.file)
// Save the updated user to the database
await user.save();
res.status(200).json({ message: 'Profile updated successfully' });
} catch (error) {
console.error('Error in updateProfile:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
// ___________________________Update User Info________________________
export const updateUserInfo = async (req, res) => {
try {
const { firstName, lastName, dob, gender, phoneNumber } = req.body;
// Find the user by ID
const userId = req.user.id;
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
// Update the user's firstName, lastName, dob, and gender
user.firstName = firstName;
user.lastName = lastName;
user.phoneNumber = phoneNumber;
user.email = email;
user.dob = dob;
user.gender = gender;
// Save the updated user to the database
await user.save();
res.status(200).json({ message: 'User Info updated successfully' });
} catch (error) {
console.error('Error in update user info:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
// ___________________________Logout________________________
export const logout = (req, res) => {
res.clearCookie('token'); // Clear the token cookie
res.status(200).json({ message: 'Logged out successfully' });
}; |
import { createContext, useContext } from 'react'
import {
NOTIFICATION_TYPES,
NO_NOTIFICATION_STATE,
handleAxiosError,
NOTIFICATION_TIMEOUT,
ERROR_NOTIFICATION_TIMEOUT,
} from '@/features/notification'
/**
* The context object for the notification state.
*
* @typedef {Object} NotificationContextObject
*/
const NotificationContext = createContext(NO_NOTIFICATION_STATE)
export default NotificationContext
/**
* The reducer function for the notification state.
*
* @function notificationReducer
* @param {Object} state - The current state of the notification.
* @param {Object} action - The action object to apply to the state.
* @param {string} action.type - The type of the action.
* @param {Object} action.payload - The payload of the action.
* @param {string} action.payload.type - The type of the notification (e.g. 'info', 'warning', 'error').
* @param {string} action.payload.message - The message to display in the notification.
* @param {string} action.payload.details - Optional details to display in the notification.
* @param {Error} action.payload.error - Optional error object to include in the notification.
* @param {number} action.payload.timeoutId - Optional ID of the timeout for the notification.
* @returns {Object} The new state of the notification.
*/
export const notificationReducer = (state, action) => {
switch (action.type) {
case 'notification/setNotification':
return {
type: action.payload.type,
message: action.payload.message,
details: action.payload.details,
error: action.payload.error,
timeoutId: action.payload.timeoutId,
}
case 'notification/setErrorNotification':
return {
type: action.payload.type,
message: action.payload.message,
details: action.payload.details,
error: action.payload.error,
timeoutId: action.payload.timeoutId,
}
case 'notification/removeNotification':
return NO_NOTIFICATION_STATE
default:
return state
}
}
/**
* A hook that returns the current notification state from the notification context.
*
* @function useNotificationValue
* @returns {Object} The current notification state from the notification context.
* @throws {Error} If used outside of an NotificationContextProvider.
*/
export const useNotificationValue = () => {
const context = useContext(NotificationContext)
return context.notification
}
/**
* A hook that returns the dispatch function from the notification context.
*
* @function useNotificationDispatch
* @returns {Function} The dispatch function from the notification context.
*/
export const useNotificationDispatch = () => {
const context = useContext(NotificationContext)
return context.dispatch
}
/**
* A hook that returns the dispatch function from the notification context.
*
* @function useNotificationDispatch
* @returns {Function} The dispatch function from the notification context.
* @throws {Error} If used outside of an NotificationContextProvider.
*/
export const useSetNotification = () => {
const dispatch = useNotificationDispatch()
const notificationValue = useNotificationValue()
const setNotification = ({
type,
message,
details,
timeoutInSeconds = NOTIFICATION_TIMEOUT,
}) => {
if (notificationValue.timeoutId) {
clearTimeout(notificationValue.timeoutId)
}
const timeoutId = setTimeout(() => {
dispatch({ type: 'notification/removeNotification' })
}, timeoutInSeconds * 1000)
return {
type: 'notification/setNotification',
payload: {
type,
message,
details,
error: null,
timeoutId,
},
}
}
return setNotification
}
/**
* A hook that returns the setErrorNotification function, which can be used to
* set an error notification.
*
* @function useSetErrorNotification
* @returns {Function} The setErrorNotification function.
*/
export const useSetErrorNotification = () => {
const dispatch = useNotificationDispatch()
const notificationValue = useNotificationValue()
const setErrorNotification = ({
error,
message,
details,
timeoutInSeconds = ERROR_NOTIFICATION_TIMEOUT,
}) => {
if (notificationValue.timeoutId) {
clearTimeout(notificationValue.timeoutId)
}
const timeoutId = setTimeout(() => {
dispatch({ type: 'notification/removeNotification' })
}, timeoutInSeconds * 1000)
const payload = handleAxiosError(error, message, details)
payload.type = NOTIFICATION_TYPES.ERROR
payload.timeoutId = timeoutId
return {
type: 'notification/setNotification',
payload: payload,
}
}
return setErrorNotification
}
/**
* Returns an action object to remove the current notification from the notification state.
*
* @function removeNotification
* @returns {Object} An action object to remove the current notification.
*/
export const removeNotification = () => {
return {
type: 'notification/removeNotification',
}
}
/**
* A hook that returns the `removeNotification` function, which can be used to remove the current notification from the notification state.
*
* @function useRemoveNotification
* @returns {Function} The `removeNotification` function.
*/
export const useRemoveNotification = () => {
return removeNotification
} |
"""
https://docs.python.org/3/library/sqlite3.html
Run this as a standalone Python module.
How-to guides for further reading:
How to use placeholders to bind values in SQL queries
How to adapt custom Python types to SQLite values
How to convert SQLite values to custom Python types
How to use the connection context manager
How to create and use row factories
Explanation for in-depth background on transaction control.
"""
import sqlite3
con = sqlite3.connect("tutorial.db") # IMPLICITLY CREATES DB IF DOESN'T ALREADY EXIST.
# In order to execute SQL statements and fetch results from SQL queries, we will need to use a database cursor. Call con.cursor() to create the Cursor:
cur = con.cursor()
# create a database table called "movie" with columns for title, release year, and review score. Thanks to the flexible typing feature of SQLite, specifying the data types is optional
try:
cur.execute("CREATE TABLE movie(title, year, score)")
except:
pass
# verify that the new table has been created by querying the "sqlite_master" table built-in to SQLite, which should now contain an entry for the movie table definition
res = cur.execute("SELECT name FROM sqlite_master")
print(res.fetchone()) # fetch the resulting row.
# look for a table that doesn't exist.
res = cur.execute("SELECT name FROM sqlite_master WHERE name='spam'")
print(res.fetchone())
# add 2 rows of data to the table
# INSERT statement implicitly opens a transaction, which needs to be committed before changes are saved in the database
cur.execute("""
INSERT INTO movie VALUES
('Monty Python and the Holy Grail', 1975, 8.2),
('And Now for Something Completely Different', 1971, 7.5)
""")
con.commit()
# verify that the data was inserted correctly by executing a SELECT query.
res = cur.execute("SELECT score FROM movie")
print(res.fetchall() ) # fetch all rows.
# insert three more rows by calling cur.executemany(...)
data = [
("Monty Python Live at the Hollywood Bowl", 1982, 7.9),
("Monty Python's The Meaning of Life", 1983, 7.5),
("Monty Python's Life of Brian", 1979, 8.0),
]
cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
con.commit() # Remember to commit the transaction after executing INSERT.
# Notice that ? placeholders are used to bind data to the query. Always use placeholders instead of string formatting to bind Python values to SQL statements, to avoid SQL injection attacks (see How to use placeholders to bind values in SQL queries for more details).
# We can verify that the new rows were inserted by executing a SELECT query, this time iterating over the results of the query:
for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):
print(row)
# Finally, verify that the database has been written to disk by calling con.close() to close the existing connection, opening a new one, creating a new cursor, then querying the database:
con.close()
new_con = sqlite3.connect("tutorial.db")
new_cur = new_con.cursor()
res = new_cur.execute("SELECT title, year FROM movie ORDER BY score DESC")
title, year = res.fetchone()
print(f'The highest scoring Monty Python movie is {title!r}, released in {year}')
new_con.close() |
import { YouTrackIssue, YouTrackUser, YouTrackWorkItem } from '../types/YouTrackApi.types'
export interface YouTrackApi {
/**
* Возвращает список ранее загруженных пользователей
*/
get users(): YouTrackUser[]
/**
* Обновить список пользователей
*/
fetchUsers(): Promise<void>
/**
* Получить список задач
*/
get issues(): YouTrackIssue[]
/**
* Обновить список задач
*/
fetchIssues(): Promise<void>
/**
* Найти задачи по названию проекта (нужно для автокомплита)
* @param partialProjectName
*/
findIssuesByProject(partialProjectName: string): YouTrackIssue[]
/**
* Обновить список временных записей
*/
fetchWorkItems(): Promise<void>
/**
* Получить временные записи по id задачи
* @param issueid
*/
getWorkitemsFromIssue(issueid: string): YouTrackWorkItem[]
} |
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>Signup Form</h1>
<form onsubmit="signup(); return false ">
<label for="firstName">First Name</label>
<input type="text" id="firstName" required>
<br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" required>
<br>
<label for="email">Email</label>
<input type="email" id="email" required>
<br>
<label for="password">Password</label>
<input type="password" id="password" required>
<br>
<label for="repeatPassword">Repeat Password</label>
<input type="password" id="repeatPassword" required>
<br>
<input type="submit" value="Signup">
</form>
<p id="message"></p>
<br>
<br>
<script>
function signup() {
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var repeatPassword = document.getElementById('repeatPassword').value;
if (password !== repeatPassword) {
document.querySelector("#message").innerHTML = 'Passwords do not match, please try again';
return;
}
axios.post('https://signup-app2.herokuapp.com/signup', {
firstName,
lastName,
email,
password,
})
.then(function (response) {
console.log(response.data);
document.querySelector("#message").innerHTML = response.data.message;
})
.catch(function (error) {
console.log(error.response.data);
document.querySelector("#message").innerHTML = error.response.data.message;
});
}
</script>
<!-- //1. UNIFORM RESOURSE:
// GET /user/:userID to get single user
// GET /users to get all users
// POST /user to create single user
// POST /users to create multiple user
// PUT /user:userID to modify single user
// PUT /users to modify multiple user
// DELETE /user:userID to delete single user
// DELETE /users to delete multipls user
// GET /post/:postID to get single post
// GET /posts to get all posts
// POST /post to create single post
// POST /posts to create multiple posts
// PUT /post/:postID to modify single post
// PUT /posts to modify multiple posts
// DELETE /post/:postID to delete single post
// DELETE /posts to delete multipls posts
// GET /group/:groupID to get single group
// GET /groups to get all groups
// POST /group to create single group
// POST /groups to create multiple groups
// PUT /group/:groupID to modify single group
// PUT /groups to modify multiple groups
// DELETE /group/:postID to delete single group
// DELETE /groups to delete multipls groups
// don't use these
// GET /get-user
// POST /create-user
// 2.CLIENT AND SERVER SHOULD BE SEPARATE
// 3.STATE LESS
// 4.CACHEABLE
// 5.LAYERED SYSTEM -->
</body>
</html> |
#pragma once
#include <memory>
#include <my_cpp_utils/json_formatter.h>
#include <spdlog/sinks/daily_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
namespace utils
{
class Logger
{
private:
inline static std::shared_ptr<spdlog::logger>& GetSingletoneInstance()
{
static std::shared_ptr<spdlog::logger> logger;
return logger;
}
public:
inline static void Init(
const std::filesystem::path& logFilePath, spdlog::level::level_enum level = spdlog::level::level_enum::info)
{
auto& logger = GetSingletoneInstance();
if (logger)
throw std::runtime_error("Logger is already initialized");
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stderr_color_sink_mt>());
sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_mt>(logFilePath.string(), 23, 59));
logger = std::make_shared<spdlog::logger>("global", begin(sinks), end(sinks));
logger->set_level(level);
// Set the pattern
// [%Y-%m-%d %H:%M:%S.%e] is the timestamp
// [%l] is the log level
// [%t] is the thread ID
// %v is the actual log message
logger->set_pattern("[%H:%M:%S.%e] [%l] [%t] %v");
}
inline static spdlog::logger& GetInstance()
{
auto& logger = GetSingletoneInstance();
if (!logger)
throw std::runtime_error("Logger is not initialized. Use Logger::init()");
return *logger;
}
};
} // namespace utils
#define MY_LOG(severity, fmt_string, ...) \
utils::Logger::GetInstance().severity(fmt::format(fmt_string __VA_OPT__(, ) __VA_ARGS__))
#define MY_FMT(fmt_string, ...) fmt::format(fmt_string, __VA_ARGS__) |
package john.LOGIN_SYSTEM.forgetpassword;
import jakarta.servlet.http.HttpSession;
import john.LOGIN_SYSTEM.common.components.PasswordStrength;
import john.LOGIN_SYSTEM.common.components.VerificationCode;
import john.LOGIN_SYSTEM.common.components.email.EmailService;
import john.LOGIN_SYSTEM.common.components.email.TransactionType;
import john.LOGIN_SYSTEM.common.response.ResponseLayer;
import john.LOGIN_SYSTEM.common.response.ResponseTerminal;
import john.LOGIN_SYSTEM.common.response.ResponseType;
import john.LOGIN_SYSTEM.forgetpassword.token.CodeToken;
import john.LOGIN_SYSTEM.forgetpassword.token.CodeTokenService;
import john.LOGIN_SYSTEM.repository.entity.user.UserEntity;
import john.LOGIN_SYSTEM.repository.entity.user.UserRepository;
import john.LOGIN_SYSTEM.session.SessionService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
class ForgetPasswordService {
private final UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder;
private final PasswordStrength passwordStrength;
private final VerificationCode verification;
private final EmailService emailService;
private final ResponseTerminal terminal;
private final SessionService redisSession;
private final CodeTokenService tokenService;
@Autowired
public ForgetPasswordService(UserRepository userRepository,
BCryptPasswordEncoder passwordEncoder,
PasswordStrength passwordStrength,
VerificationCode verification,
EmailService email,
ResponseTerminal terminal,
SessionService redisSession,
CodeTokenService tokenService) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.passwordStrength = passwordStrength;
this.verification = verification;
this.emailService = email;
this.terminal = terminal;
this.redisSession = redisSession;
this.tokenService = tokenService;
}
// VERIFY USER ACCOUNT IF EXIST
// Check input formats
// Check provided email if account exist
// Proceed to next method for password match
public ResponseLayer verifyAccountFirst(String email, HttpSession session) {
var userEmail = userRepository.findByEmail(email);
if (userEmail.isEmpty()) {
return new ResponseLayer(
false, "Invalid email", HttpStatus.NOT_FOUND);
}
if (!userEmail.get().isEnabled()) {
return new ResponseLayer(
false, "Account is locked", HttpStatus.BAD_REQUEST);
}
UserEntity user = userEmail.get();
CodeToken token = verificationCode(user);
// send verification code via email
emailService.sendEmail(user.getUsername(), user.getEmail(), token.getVerificationCode(), TransactionType.RESET_PASSWORD);
// generate entry session for reset password
int EXPIRATION_IN_MINUTES = 5;
redisSession.setSession(session, "verification-code", token.getVerificationCode(), EXPIRATION_IN_MINUTES);
redisSession.setSession(session, "user-id", user.getId().toString());
terminal.status(ResponseType.ACCOUNT_EXIST);
return new ResponseLayer(true, "Account exist", HttpStatus.OK);
}
// Generate verification code
private CodeToken verificationCode(UserEntity user) {
CodeToken token = new CodeToken(user.getId());
verification.generateVerificationCode(token);
return token;
}
// VERIFICATION PROCESS
public ResponseLayer matchVerification(String userInput, HttpSession session) {
String verificationCode = (String) redisSession.getSession(session, "verification-code");
CodeToken verification = tokenService.handleExpiration(verificationCode);
// Expired. remove session attributes
if (verification == null) {
redisSession.removeSession(session, "verification-code");
redisSession.removeSession(session, "user-id");
return new ResponseLayer(false, "Verification code expired", HttpStatus.BAD_REQUEST);
}
// Invalid input
if (!userInput.equals(verification.getVerificationCode())) {
return new ResponseLayer(false, "Invalid verification code", HttpStatus.BAD_REQUEST);
}
tokenService.deleteVerificationCode(verification);
return new ResponseLayer(true, "Verified. Proceed to change-password", HttpStatus.OK);
}
// VALIDATE USER INPUTS FIRST BEFORE RESET PASSWORD
// Check password strength
// Check password if same as previous
// Save new password; Return false if SYSTEM error persist
public ResponseLayer resetPassword(ObjectId userId, String newPassword) {
// Password strength
// Retrieve account from database
var checkNewPassword = passwordStrength.checkPassword(newPassword);
Optional <UserEntity> checkUser = userRepository.findById(userId);
if (!checkNewPassword.isSuccess()) {
return checkNewPassword;
} else if (checkUser.isEmpty()) {
return new ResponseLayer(false, "User not found", HttpStatus.NOT_FOUND);
}
// Instantiate user account into variable
UserEntity user = checkUser.get();
// Return false if new password is same as the previous one
if (passwordEncoder.matches(user.getSalt() + newPassword, user.getPassword())) {
return new ResponseLayer(
false, "Provided password is the same as previous", HttpStatus.BAD_REQUEST);
}
// Perform password hashing before saving
String hashedPassword = passwordEncoder.encode(user.getSalt() + newPassword);
// Update user password
if (userRepository.updatePassword(user, hashedPassword).isPresent()) {
return new ResponseLayer(
true, "Password reset successfully", HttpStatus.OK);
} else {
return new ResponseLayer(
false, "Password reset fail", HttpStatus.SERVICE_UNAVAILABLE);
}
}
} |
import { HelmetProvider } from 'react-helmet-async';
import { Routes, Route } from 'react-router-dom';
import HistoryRouter from '../history-route/history-route';
import browserHistory from '../../browser-history';
import ScrollToTop from '../scroll-to-top/scroll-to-top';
import Main from '../../pages/main/main';
import Login from '../../pages/login/login';
import Favorites from '../../pages/favorites/favorites';
import Offer from '../../pages/offer/offer';
import NotFound from '../../pages/not-found/not-found';
import PrivateRoute from '../private-route/private-route';
import { AppRoute } from '../../constants';
function App(): JSX.Element {
return (
<HelmetProvider>
<HistoryRouter history={browserHistory}>
<ScrollToTop />
<Routes>
<Route index element={<Main />} />
<Route path={AppRoute.Login} element={<Login />} />
<Route
path={AppRoute.Favorites}
element={
<PrivateRoute>
<Favorites />
</PrivateRoute>
}
/>
<Route path={AppRoute.Offer} element={<Offer />} />
<Route path="*" element={<NotFound />} />
</Routes>
</HistoryRouter>
</HelmetProvider>
);
}
export default App; |
<script>
import { writable } from 'svelte/store'
import H2 from 'components/H2/H2.svelte'
import Input from 'components/Input/Input.svelte'
import ButtonBurgerShape from 'components/ButtonBurgerShape/ButtonBurgerShape.svelte'
import RecipeCard from 'components/RecipeCard/RecipeCard.svelte'
import { getRandomInt, getRandomNItems } from 'services/random.service'
let recipes = []
let ingredient = ''
let noRecipeFound = false
const listOfTotalRecipes = writable([])
const inputIngredient = writable('')
export const getRandomRecipes = n => {
const randomPage = ingredient ? getRandomInt(10) : getRandomInt(50)
const url = ingredient ?
`api/puppy/?q=${ingredient}&p=${randomPage}` :
`api/puppy/?p=${randomPage}`
fetch(url)
.then(res => res.json())
.then(data => {
const listOfRecipes = data && data.results.length > 0 && getRandomNItems(data.results, n)
noRecipeFound = !listOfRecipes
listOfTotalRecipes.set(listOfRecipes)
})
.catch(err => {
throw Error(err)
})
}
listOfTotalRecipes.subscribe(value => {
recipes = value
})
const handleChange = event => {
inputIngredient.set(event.target.value)
}
inputIngredient.subscribe(value => {
ingredient = value
})
</script>
<style>
.container {
display: flex;
flex-direction: row;
width: 100%;
}
.group-container {
display: flex;
flex-direction: column;
align-items: center;
}
.button-container {
display: flex;
flex-direction: row;
}
.global-container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
align-items: center;
margin: 20px 0;
}
.not-found {
margin: 10px;
color: #EE6663;
}
</style>
<div class="container">
<Input label={'Une envie de...'} onChange={handleChange}/>
<div class="group-container">
<H2 title="...Combien voulez vous de propositions ?"/>
<div class="button-container">
<ButtonBurgerShape className="with-marge" onClick={() => getRandomRecipes(1)} text="1"/>
<ButtonBurgerShape className="with-marge" onClick={() => getRandomRecipes(5)} text="5"/>
<ButtonBurgerShape onClick={() => getRandomRecipes(10)} text="10"/>
</div>
</div>
</div>
{#if recipes.length > 0}
<div class="global-container">
{#each recipes as recipe}
<RecipeCard title={recipe.title} href={recipe.href} ingredients={recipe.ingredients} src={recipe.thumbnail}/>
{/each}
</div>
{/if}
{#if noRecipeFound}
<div class="not-found">
Désolé, nous n'avons trouvé aucune recette qui correspond :'(
</div>
{/if} |
package com.ntumart.dipapp.api.controllers;
import com.ntumart.dipapp.api.repository.InterestRepository;
import com.ntumart.dipapp.api.service.InterestService;
import com.ntumart.dipapp.exceptions.EmptyFileException;
import com.ntumart.dipapp.exceptions.ProductNotFoundException;
import com.ntumart.dipapp.models.Interest;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/user")
public class InterestController {
@Autowired InterestService interestService;
@Autowired InterestRepository interestRepository;
@RequestMapping(
value = "/addinterest",
method = RequestMethod.POST,
produces = {"application/json"})
@ResponseBody
public ResponseEntity<String> addInterest(@RequestBody Interest interest) {
try {
interestService.addInterest(interest);
System.out.println("Received Interest object: " + interest);
return ResponseEntity.ok("Interest Added Successfully");
} catch (EmptyFileException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File is empty");
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error uploading the file");
}
}
@GetMapping("/interest/{userID}")
public ResponseEntity<List<Object>> userID(@PathVariable int userID)
throws ProductNotFoundException {
List<Object> interest = interestRepository.userID(userID);
if (interest == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(interest);
}
@GetMapping("/{userID}/checkInterest")
public ResponseEntity<String> checkCategory(@PathVariable int userID) {
Interest interest = interestRepository.checkCategory(userID);
if (interest == null) {
return ResponseEntity.notFound().build();
}
if (interest.getCategory1() == null || interest.getCategory1().isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Categories is empty");
} else {
// } else if(interest.getCategory2() == null || interest.getCategory2().isEmpty()){
// return ResponseEntity.ok("4 Categories is not selected");
// } else if(interest.getCategory3() == null || interest.getCategory3().isEmpty()){
// return ResponseEntity.ok("3 Categories is not selected");
// } else if(interest.getCategory4() == null || interest.getCategory4().isEmpty()){
// return ResponseEntity.ok("2 Categories is not selected");
// } else if(interest.getCategory5() == null || interest.getCategory5().isEmpty()){
// return ResponseEntity.ok("1 Categories is not selected");
// } else {
return ResponseEntity.status(HttpStatus.FOUND).body("No issue");
}
}
@GetMapping("/checking/{userID}")
public ResponseEntity<Interest> getInterestByUserID(@PathVariable int userID)
throws ProductNotFoundException {
Interest interest = interestService.getInterestByUserID(userID);
return ResponseEntity.ok(interest);
}
@PostMapping("/updateInterest/{userID}")
public ResponseEntity<String> updateInterest(
@PathVariable int userID,
@RequestParam(value = "category1") String category1,
@RequestParam(value = "category2") String category2,
@RequestParam(value = "category3") String category3,
@RequestParam(value = "category4") String category4,
@RequestParam(value = "category5") String category5)
throws IOException, ProductNotFoundException {
interestService.updateInterest(userID, category1, category2, category3, category4, category5);
return ResponseEntity.ok("Interest Updated Successfully");
}
} |
/**
* The starting point of the application.
*
* @author Eric Sundqvist
* @author Mats Loock
* @version 1.0.0
*/
import express from 'express'
import helmet from 'helmet'
import logger from 'morgan'
import { router } from './routes/router.js'
import { connectDB } from './config/mongoose.js'
try {
await connectDB()
const app = express()
// Set various HTTP headers to make the application little more secure (https://www.npmjs.com/package/helmet).
app.use(helmet())
// Set up a morgan logger using the dev format for log entries.
app.use(logger('dev'))
// Parse requests of the content type application/json.
app.use(express.json())
// Register routes.
app.use('/', router)
// Error handler.
app.use(function (err, req, res, next) {
err.status = err.status || 500
if (req.app.get('env') !== 'development') {
console.log(err)
if (err.status === 409) {
return res.status(err.status).send()
} else {
if (err.status === 500) err.message = 'An unexpected condition was encountered.'
if (err.status === 400) {
err.message =
'The request cannot or will not be processed due to something that is perceived to be a client error (for example, validation error).'
}
return res.status(err.status).json({
status: err.status,
message: err.message
})
}
}
// Development only!
// Only providing detailed error in development.
return res.status(err.status).json({
status: err.status,
message: err.message,
cause: err.cause
? {
status: err.cause.status,
message: err.cause.message,
stack: err.cause.stack
}
: null,
stack: err.stack
})
})
// Starts the HTTP server listening for connections.
app.listen(process.env.PORT, () => {
console.log(`Server running at http://localhost:${process.env.PORT}`)
console.log('Press Ctrl-C to terminate...')
})
} catch (err) {
console.error(err)
process.exitCode = 1
} |
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import * as productActions from '../actions/productsActions';
const AddProductForm = () => {
const [visible, setVisible] = useState(false);
const [name, setName] = useState('');
const [price, setPrice] = useState(0);
const [quantity, setQuantity] = useState(0);
const dispatch = useDispatch();
const resetForm = () => {
setName('');
setPrice(0);
setQuantity(0);
setVisible(!visible);
};
const handleClick = (e) => {
e.preventDefault();
resetForm();
};
const onFormSubmit = async (product) => {
dispatch(productActions.productAdded(product, resetForm));
};
const handleFormSubmit = (e) => {
try {
e.preventDefault();
onFormSubmit({ title: name, price, quantity });
} catch (err) {
console.error(err);
}
};
const formVisible = visible ? 'add-form visible' : 'add-form';
return (
<div className={formVisible}>
<p>
<a
className="button add-product-button"
href="#/"
onClick={handleClick}
>
Add A Product
</a>
</p>
<>
<h3>Add Product</h3>
<form onSubmit={handleFormSubmit}>
<div className="input-group">
<label htmlFor="product-name">Product Name</label>
<input
type="text"
id="product-name"
value={name}
onChange={({ target }) => setName(target.value)}
/>
</div>
<div className="input-group">
<label htmlFor="product-price">Price</label>
<input
type="text"
id="product-price"
value={price}
onChange={({ target }) => setPrice(target.value)}
/>
</div>
<div className="input-group">
<label htmlFor="product-quantity">Quantity</label>
<input
type="text"
id="product-quantity"
value={quantity}
onChange={({ target }) => setQuantity(target.value)}
/>
</div>
<div className="actions form-actions">
<a
href="#/"
type="submit"
className="button"
onClick={handleFormSubmit}
>
Add
</a>
<a href="#/" className="button" onClick={handleClick}>
Cancel
</a>
</div>
</form>
</>
</div>
);
};
export default AddProductForm; |
# IOTA
- Em uma declaração de constantes, o identificador IOTA representa números sequenciais não tipados.
```GO
package main
import "fmt"
const (
x = iota
y = iota
z = iota
)
func main() {
fmt.Println(x, y, z)
}
OUTPUT: 0, 1, 2
```
- Podemos descartar valores
````GO
package main
import "fmt"
const (
a = iota
_ = iota
c = iota
x = iota
_ = iota
z = iota
)
func main() {
fmt.Println(a, c, x, z)
}
OUTPUT: 0, 2, 3, 5
package main
import "fmt"
const (
a = iota * 10
_
c
x
_
z
)
func main() {
fmt.Println(a, c, x, z)
}
OUTPUT: 0, 20, 30, 50
```` |
"use server";
import { RegisterSchema } from "@/schemas/registerSchema";
import * as z from "zod";
import bcrypt from "bcryptjs";
import { db } from "@/lib/db";
import { getUserbyEmail } from "@/data/auth/user";
export const register = async (values:z.infer<typeof RegisterSchema>) => {
const validatedFields = RegisterSchema.safeParse(values);
if(!validatedFields.success) {
return {error: "Invalid Fields!"};
}
const {email, password, name} = validatedFields.data;
const hashedPassword = await bcrypt.hash(password, 10);
const existingUser = await getUserbyEmail(email);
if(existingUser) {
return {error: "Email already in use!"};
}
await db.user.create({
data:{
name,
email,
password: hashedPassword,
}
});
return {success: "Account created!"};
} |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../34_ERC721_en/IERC165.sol";
/**
* @dev ERC1155 standard interface contract, realizes the function of EIP1155
* See: https://eips.ethereum.org/EIPS/eip-1155[EIP].
*/
interface IERC1155 is IERC165 {
/**
* @dev single-type token transfer event
* Released when `value` tokens of type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev multi-type token transfer event
* ids and values are arrays of token types and quantities transferred
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev volume authorization event
* Released when `account` authorizes all tokens to `operator`
*/
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
/**
* @dev Released when the URI of the token of type `id` changes, `value` is the new URI
*/
event URI(string value, uint256 indexed id);
/**
* @dev Balance inquiry, returns the position of the token of `id` type owned by `account`
*/
function balanceOf(
address account,
uint256 id
) external view returns (uint256);
/**
* @dev Batch balance inquiry, the length of `accounts` and `ids` arrays have to wait.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Batch authorization, authorize the caller's tokens to the `operator` address.
* Release the {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Batch authorization query function, if the authorization address `operator` is authorized by `account`, return `true`
* See {setApprovalForAll} function.
*/
function isApprovedForAll(
address account,
address operator
) external view returns (bool);
/**
* @dev Secure transfer, transfer `amount` unit `id` type token from `from` to `to`.
* Release {TransferSingle} event.
* Require:
* - If the caller is not a `from` address but an authorized address, it needs to be authorized by `from`
* - `from` address must have enough open positions
* - If the receiver is a contract, it needs to implement the `onERC1155Received` method of `IERC1155Receiver` and return the corresponding value
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Batch security transfer
* Release {TransferBatch} event
* Require:
* - `ids` and `amounts` are of equal length
* - If the receiver is a contract, it needs to implement the `onERC1155BatchReceived` method of `IERC1155Receiver` and return the corresponding value
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
} |
向通道中加入一个组织
-----------
> 原文链接:https://hyperledger-fabric.readthedocs.io/en/latest/channel_update_tutorial.html
> 提示:确保您已按照 Install Samples, Binaries and Docker Images 和 Prerequisites 文章所述下载了相应的 docker 镜像和二进制文件。特别是,您的 fabric-samples 文件夹版本必须包含 eyfn.sh 脚本(first-network 文件夹中)及其相关脚本。
本篇教程是构建第一个 fabric 网络教程的扩展,并演示向 BYFN 网络中自动生成的应用频道(mychannel)中添加新组织-- Org3。这里就假设您对 BYFN 网络,包括上述实用程序的用法和功能都已经十分了解。
> 译者注:BYFN 网络,即 构建第一个 fabric 网络 教程建立的 Fabric 网络。BYFN 为 build your first network 的缩写。
虽然这里我们只关注新组织的集成,但在执行其他通道配置更新时,例如更新修改策略(modification policies )或更改批量大小(altering batch size),也可以采用相同的方法。如果想要了解有关通道配置更新的过程和可能性的更多内容,请查看更新通道配置 这篇文章。还有一个要注意的点是,这里演示的频道配置更新通常是组织管理员(而不是链码或应用程序开发人员)的责任。
> 提示:在继续下面内容之前,请确保自动化 byfn.sh 脚本在您的计算机上运行时没有错误。如果你将二进制文件和相关工具(cryptogen,configtxgen 等)导出到 PATH 变量中,可以相应地修改命令而不用传递完全限定的路径。
# 启动环境
我们将在您的本地克隆的 Fabric-samples 中的子目录 first-network 下进行操作,快去切换到该目录吧。另外,再打开一些额外的终端以方便使用。
首先,使用 byfn.sh 脚本来清理下环境。这个命令将终止所有活动或过时的 docker 容器并删除以前生成的文件。其实执行通道配置更新任务,是无需关闭 Fabric 网络的,但是为了本教程执行的顺利,我们从初始状态进行操作。因此,让我们运行以下命令来清理以前的所有环境:
```bash
./byfn.sh down
```
接下来,生成 BYFN 网络默认需要的文件:
```bash
./byfn.sh generate
```
最后,使用在 CLI 容器中的执行的脚本启动网络:
```bash
./byfn.sh up
```
现在,你的机器上运行了一个干净的 BYFN。接下来,您有两条路可以走。首先,我们提供一个完全注释的脚本,它将执行配置交易更新以将 Org3 加入网络。此外,我们将展示一个相同过程的“手动”版本,展示每个步骤,并解释它完成的内容。(因为我们在手动执行之前,还会向您展示如何关闭网络,所以您也可以先运行自动脚本,然后再手动运行每个步骤)
# 使用脚本将 Org3 加入 Channel
在 first-network 目录下 执行以下命令:
```bash
./eyfn.sh up
```
看一看输出容。将看到添加了 Org3 加密资料,创建配置更新并对其签名,然后安装了链码以便允许 Org3 执行帐本查询。
如果一切顺利,最终你将看到以下信息:
```text
```
通过执行以下命令(而不是./byfn.sh up),eyfn.sh 可以与 byfn.sh 使用相同的 Node.js 链码和数据库选项:
```bash
./byfn.sh up -c testchannel -s couchdb -l node
```
```bash
./eyfn.sh up -c testchannel -s couchdb -l node
```
如果想要仔细研究这个过程,就看看接下来部分,将向展示进行通道更新的每个命令以及它的作用。
# 手动将 Org3 加入通道
> 提示:下面的步骤是把 cli 和 Org3cli 容器中的 CORE_LOGGING_LEVEL 设置为 DEBUG。
>
> cli 容器 在 first-network/docker-compose-cli.yaml 中,修改代码如下:
>
> ```yaml
> cli:
> container_name: cli
> image: hyperledger/fabric-tools:$IMAGE_TAG
> tty: true
> stdin_open: true
> environment:
> - GOPATH=/opt/gopath
> - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
> #- CORE_LOGGING_LEVEL=INFO
> - CORE_LOGGING_LEVEL=DEBUG
> ```
>
> Org3cli 容器 在 first-network/docker-compose-cli.yaml 中,修改代码如下:
>
> ```yaml
> Org3cli:
> container_name: Org3cli
> image: hyperledger/fabric-tools:$IMAGE_TAG
> tty: true
> stdin_open: true
> environment:
> - GOPATH=/opt/gopath
> - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
> #- CORE_LOGGING_LEVEL=INFO
> - CORE_LOGGING_LEVEL=DEBUG
> ```
如果您使用过 eyfn.sh 脚本,则需要关闭网络。执行下面命令:
```bash
./eyfn.sh down
```
这将关闭网络,删除所有容器并撤消我们为添加 Org3 所做的工作。
网络关闭后,接下来重启网络:
```bash
./byfn.sh generate
```
接着执行:
```bash
./byfn.sh up
```
这将使您的网络恢复到执行 eyfn.sh 脚本之前的状态。
现在我们准备手动添加 Org3 了。首先,第一步,我们需要生成 Org3 的加密资料。
## 生成 Org3 加密资料
在另一个终端中,从 first-network 切换到 org3-artifacts 目录中:
```bash
cd org3-artifacts
```
这里有两个 yaml 文件:org3-crypto.yaml 和 configtx.yaml。首先,为 Org3 生成加密材料:
```bash
../../bin/cryptogen generate --config=./org3-crypto.yaml
```
此命令会读读取 org3-crypto.yaml 文件, 并利用 cryptogen 为 Org3 CA 以及绑定到此组织的两个节点生成密钥和证书。与 BYFN 实现一样,这些加密资料将放入当前工作目录(在我们的示例中为 org3-artifacts)新生成的 crypto-config 文件夹中。
现在使用 configtxgen 工具,把 Org3 的配置信息输出到 JSON 文件中。当然,我们先要设置 configtxgen 命令需要提取配置文件 configtx.yaml 的工作目录。
```bash
export FABRIC_CFG_PATH=$PWD
../../bin/configtxgen -printOrg Org3MSP > ../channel-artifacts/org3.json
```
上面的命令创建一个 JSON 文件 - org3.json - 并将其输出到 first-network 目录下的 channel-artifacts 中。此文件包含 Org3 的策略定义,以及以 base 64 格式的三个重要证书:管理员用户证书(稍后将需要担任 Org3 的管理员),CA 根证书和 TLS 根证书。在接下来的步骤中,我们会将此 JSON 文件追加到通道配置中。
我们最后的工作是将 Orderer Org 的 MSP 材料移植到 Org3 crypto-config 目录中。特别是 Orderer 的 TLS 根证书,它将允许 Org3 实体与 orderer 网络节点之间的安全通信。
```bash
cd ../ && cp -r crypto-config/ordererOrganizations org3-artifacts/crypto-config/
```
现在我们准备好更新频道配置。
## 准备 CLI 环境
更新过程要使用配置转换器工具 - configtxlator。此工具提供了:独立于 SDK 的无状态 REST API;提供 CLI 命令,以简化 Fabric 网络中的配置任务;允许数据在不同的格式之间轻松转换(在本例中,如 protobufs 和 JSON 之间);可以根据两个通道配置之间的差异计算配置更新事务。
首先,执行进入 CLI 容器。之前,这个 CLI 容器已经使用 BYFN 的 crypto-config 配置文件启动了,我们可以访问两个原始节点组织和 Orderer 组织的 MSP 资料。由于引导程序的身份是 Org1 的管理员用户,所以我们想要以 Org2 的身份执行任何步骤都需要设置特定的 MSP 环境变量。
```bash
docker exec -it cli bash
```
设置 ORDERER_CA 和 CHANNEL_NAME 变量:
```bash
export ORDERER_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
export CHANNEL_NAME=mychannel
```
检查下变量是否设置正确
```bash
echo $ORDERER_CA && echo $CHANNEL_NAME
```
> 提示:如果因为某些原因,要重启 CLI 容器,那在重启后就需要重新设置这两个环境变量。
## 获取配置
这个 CLI 容器中已经设好了两个关键的环境变量:ORDERER_CA 和 CHANNEL_NAME。现在我们来获取 mychannel 通道最新的配置块。
为什么需要获取最新的通道配置?这是因为 通道配置元素是版本化的。版本非常重要,一方面,它可以防止配置的重复更改(例如,恢复到具有旧 CRLs 的通道配置,这就可能会带来安全风险)。另一方面,它可以保证并发(例如,在添加新组织后你要从通道中删除组织,版本控制就可以防止删除两个组织,只删除想要删除的组织)。
```bash
peer channel fetch config config_block.pb -o orderer.example.com:7050 -c $CHANNEL_NAME --tls --cafile $ORDERER_CA
```
上面命令将二进制 protobuf 通道配置块保存到 config_block.pb。注意,名称和文件扩展名可以是任意的。但是建议指定其所表示的对象类型及编码(protobuf 或 JSON)。
当发出 peer channel fetch 命令时,终端中有很多输出。来看下输出日志中的最后一行:
```text
2017-11-07 17:17:57.383 UTC [channelCmd] readBlock -> DEBU 011 Received block: 2
```
这告诉我们 mychannel 的最新配置块实际上是块 2,而不是创世块。默认情况下,peer channel fetch config 命令返回指定通道的最新配置块,在这个案例中是第三个块。这是因为 BYFN 脚本在两个单独的通道更新事务中为我们的两个组织(Org1 和 Org2)定义了锚节点。
因此,我们有以下配置顺序:
- 0 块:创始块 (第一个块)
- 1 块:Org1 锚点对等更新(第二个块)
- 2 块:Org2 锚点对等更新(第三个块)
## 将配置转换为 JSON 文件并修剪
现在我们将使用 configtxlator 工具将此通道配置块转码为 JSON 格式。我们还必须删除所有头信息(header)、元数据(metadata)、创建者签名(creator signatures)等一系列与我们想要修改的内容无关的数据。我们使用 jq 这个该工具来完成这些操作:
```bash
configtxlator proto_decode --input config_block.pb --type common.Block | jq .data.data[0].payload.data.config > config.json
```
上述命令会在 first-network 内的 fabric-samples 文件夹中,给我们生成一个精简的 JSON 文件 - config.json。
在你本地的编辑器或浏览器中打开这个文件。即使在完成本教程之后,此文件也值得研究,因为它揭示了底层配置结构和可以进行的其他类型的通道更新。想了解更多通道配置更新的内容,可以移步这里。
> 译者注:这里不会在 first-network/fabric-samples 文件夹中,而是在 CLI 容器中。想要查看,可以通过下面命令,拷贝到容器外的 first-network/fabric-sample/channel-artifacts 中:
> cp config.json ./channel-artifacts/
## 添加 Org3 加密资料
> 提示:不管你想要更新什么样的配置,其步骤都和我们目前执行的步骤相同。我们在本教程中采取这样添加组织的方式,因为这会是您会遇到的最复杂的通道配置更新方式之一。
我们将再次使用 jq 工具往通道的应用程序组字段中追加 Org3 的配置--org3.json ,并将输出文件命名为 modified_config.json。
```bash
jq -s '.[0] \* {"channel_group":{"groups":{"Application":{"groups": {"Org3MSP":.[1]}}}}}' config.json ./channel-artifacts/org3.json > modified_config.json
```
> 译者注:就是把 org3.json 中的内容,拷贝到 config.json 中的 channel_group.groups.Application.groups.Org3MSP 属性中,并把新的 config.json 保存为 modified_config.json
现在,在 CLI 容器中,我们有两个 JSON 文件 - config.json 和 modified_config.json。初始文件(config.json)仅包含 Org1 和 Org2 身份资料,而“modified”文件包含所有三个 Orgs。此时,只需重新编码这两个 JSON 文件并计算增量即可。
首先,将 config.json 转换为 protobuf 格式的 config.pb 文件:
```bash
configtxlator proto_encode --input config.json --type common.Config --output config.pb
```
接下来,将 modified_config.json 转为 modified_config.pb:
```bash
configtxlator proto_encode --input modified_config.json --type common.Config --output modified_config.pb
```
现在使用 configtxlator 来计算这两个配置 protobufs 之间的增量。此命令将输出名为 org3_update.pb 的新 protobuf 格式文件:
```bash
configtxlator compute_update --channel_id $CHANNEL_NAME --original config.pb --updated modified_config.pb --output org3_update.pb
```
这个新的 org3_update.pb 文件,包含 Org3 的定义和 Org1 及 Org2 资料的高级指针。我们放弃对 Org1 和 Org2 的 MSP 材料的扩展和策略信息的修改,因为这些数据已经存在于通道的创世块中。因此,我们只需要两种配置之间的增量。
在最终提交通道更新之前,我们还需要执行一些步骤。首先,让我们将此对象解码为可编辑的 JSON 格式并将其命名为 org3_update.json:
```bash
configtxlator proto_decode --input org3_update.pb --type common.ConfigUpdate | jq . > org3_update.json
```
现在,我们有一个解码的更新文件 - org3_update.json - 我们需要包装一个 envelope 消息。这一步将返回我们之前剥离的 header 字段。我们将此文件命名为 org3_update_in_envelope.json:
```bash
echo '{"payload":{"header":{"channel_header":{"channel_id":"mychannel", "type":2}},"data":{"config_update":'$(cat org3_update.json)'}}}' | jq . > org3_update_in_envelope.json
```
> 译者注:即把 org3_update.json 中的内容,放置在 payload.data.config_update 中,并把这个包含 header 字段的新 json 存到 org3_update_in_envelope.json 中。
最后,我们将再次使用 configtxlator 工具将新生成的 org3_update_in_envelope.json 转换为 Fabric 所需的 protobuf 格式。我们将这个最终更新对象命名为 org3_update_in_envelope.pb
```bash
configtxlator proto_encode --input org3_update_in_envelope.json --type common.Envelope --output org3_update_in_envelope.pb
```
## 签名并提交配置更新
终于快要结束了!
现在,我们的 cli 中期中有一个 org3_update_in_envelope.pb 文件。在把这个配置写入账本之前,我们需要管理员用户的签名。我们的通道应用程序组的修改策略(mod_policy)被默认设置了“MAJORITY(多数)”,也就是说,我们需要大多数现有的组织管理员来签名。因为我们只有两个组织--Org1 和 Org2--而两个中的多数是 2。所以,我们需要这两个签名。如果没有这两个签名,排序服务(orderering service)将因不满足这个策略而拒绝交易。
首先,我们将使用 Org1 管理员的身份去签名。因为这个 CLI 容器是使用 Org1 MSP 启动的,因此我们只需要执行 peer channel signconfigtx 命令:
```bash
peer channel signconfigtx -f org3_update_in_envelope.pb
```
最后,我们来切换 CLI 容器的身份为 Org2 的管理员身份。要修改这个身份,只需要 修改四个环境变量
> 提示:在组织之间切换身份来签署配置交易(或执行任何其他操作)并不能代表真实的 Fabric 操作。永远不要把整个网络的加密资料安装在单个容器上启动。相反,配置更新需要安全地从外传递给 Org2 管理员进行检查和批准。
设置 Org2 环境变量:
```bash
# 你可以一次性执行下面这些命令
export CORE_PEER_LOCALMSPID="Org2MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp
export CORE_PEER_ADDRESS=peer0.org2.example.com:7051
```
最后,我们将执行 peer channel update 命令。 Org2 管理员签名在此命令中会被附带调用,因此无需再次手动签名 protobuf 文件:
> 提示:接下来要进行的 orderer 服务更新调用将进行一系列系统签名和策略检查。因此, 您可能会发现检查 orderer 节点的日志流会很有用。在另一个 shell 端执行 docker logs -f orderer.example.com 命令来查看 orderer 节点日志。
执行更新调用:
```bash
peer channel update -f org3_update_in_envelope.pb -c $CHANNEL_NAME -o orderer.example.com:7050 --tls --cafile $ORDERER_CA
```
如果更新已成功提交,应该会看到类似于以下内容的消息提示:
```text
2018-02-24 18:56:33.499 UTC [msp/identity] Sign -> DEBU 00f Sign: digest: 3207B24E40DE2FAB87A2E42BC004FEAA1E6FDCA42977CB78C64F05A88E556ABA
```
还将看到我们的配置事务的提交:
```
2018-02-24 18:56:33.499 UTC [channelCmd] update -> INFO 010 Successfully submitted channel update
```
通道更新调用成功会向通道中所有的节点返回一个新块 - 块 5。如果你还记得的话,块 0-2 是初始通道配置,而块 3 和 4 是 mycc 链码的实例化和调用。因此,块 5 用作最新的通道配置,其中在通道上定义了 Org3。
检查 peer0.org1.example.com 的日志(在另一个终端):
```bash
docker logs -f peer0.org1.example.com
```
如果想要检查新配置块内容,请按照上面的演示过程来获取和解码新配置块。
## 配置领导节点选举
> 提示:在本教程中,此部分作为一般参考用于理解领导者选举设置。此示例默认为动态领导者选举,该选举是在 peer-base.yaml 中为网络中的所有节点设置的。
新加入的节点都是使用创始块启动的。但创始块中并不包含被新添加到通道配置更新中组织的信息。所以,这些新节点无法验证其他节点从他们自己的组织转发过来的块,直到他们获得将组织添加到频道的配置事务。因此,新加入的节点必须具有以下配置之一,以便它们从 orderer 服务接收块:
1、要使用静态领导模式,请将节点配置为组织领导者:
```bash
CORE_PEER_GOSSIP_USELEADERELECTION=false
CORE_PEER_GOSSIP_ORGLEADER=true
```
> 提示:对于添加到通道的所有新节点,此配置必须相同。
2、要使用动态领导者选举,请将节点配置为使用领导者选举:
```bash
CORE_PEER_GOSSIP_USELEADERELECTION=true
CORE_PEER_GOSSIP_ORGLEADER=false
```
> 提示:由于新添加的组织的节点将无法形成成员视图(membership view),此选项与静态配置类似,因为每个节点将开始宣称自己是领导者。但是,一旦他们更新了将组织添加到通道的配置事务,组织中将只有一个活跃的领导者。因此,如果您最终希望组织的节点使用领导者选举,建议使用此选项。
## 把 Org3 加入通道
此时,通道配置已更新为包含我们的新组织--Org3 - 意味着与其关联的节点现在可以加入 mychannel。
首先,让我们启动为 Org3 特定的 CLI 容器。
打开一个新的终端,在 first-network 目录下,启动 Org3 容器:
```bash
docker-compose -f docker-compose-org3.yaml up -d
```
这个 compose 文件已配置在我们的初始网络中,因此两个节点和 CLI 容器将能够使用现有节点和 oredrer 节点进行通信。现在已经运行了三个容器,我们来进入 Org3 的 CLI 容器:
```bash
docker exec -it Org3cli bash
```
就像我们对初始 CLI 容器所做的那样,设置两个关键环境变量:ORDERER_CA 和 CHANNEL_NAME:
```bash
export ORDERER_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
export CHANNEL_NAME=mychannel
```
检查以确保已正确设置变量:
```bash
echo $ORDERER_CA && echo $CHANNEL_NAME
```
现在我们向 orderer 服务发起请求来获取 mychannel 的创世块。由于我们成功地更新了通道,orderer 服务能够验证这个请求中的 Org3 签名。如果 Org3 没有成功更新入通道配置中,orderer 服务则会拒绝此请求。
使用 peer channel fetch 命令获取块:
```bash
peer channel fetch 0 mychannel.block -o orderer.example.com:7050 -c $CHANNEL_NAME --tls --cafile $ORDERER_CA
```
请注意,我们传递 0 这个参数,表名我们要获取账本中的第一个区块(即创始块)。如果我们只是 使用 peer channel fetch config 命令,我们会获取第 5 个区块--定义了 Org3 配置更新的区块。但是,我们不能从下游区块来开始我们的帐本 - 我们必须从块 0 开始。
执行 peer channel join 命令并传入 genesis 块 - mychannel.block:
```bash
peer channel join -b mychannel.block
```
如果要加入 Org3 的第二个节点,请重新设置 TLS 和 ADDRESS 变量并执行 peer channel join command :
```bash
export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org3.example.com/peers/peer1.org3.example.com/tls/ca.crt
export CORE_PEER_ADDRESS=peer1.org3.example.com:7051
peer channel join -b mychannel.block
```
## 升级和调用 Chaincode
本教程最后一块内容就是更新链码的版本,并更新背书策略(把 Org3 包含进去)。马上就要升级链码,因此我们可以放直接弃安装第 1 版链码的步骤。我们只关注 Org3 将成为背书策略一部分的新版本,因此我们将直接跳转到链码的第 2 版。
在 Org3 的 CLI 容器中执行:
```bash
peer chaincode install -n mycc -v 2.0 -p github.com/chaincode/chaincode_example02/go/
```
如果要在 Org3 的第二个节点上安装链码,就需要相应地修改环境变量,并重新执行该命令。需要注意的是,第二次安装不是强制要求的,因为您只需要在那些将作为背书节点或以其他方式与账本有接口关系的节点上安装链代码(例如,仅查询)。节点仍将运行验证逻辑,并在没有运行链码容器的情况下充当提交者。
现在,回到最开始的 CLI 容器,并在 Org1 和 Org2 的节点上安装新版本链码。之前,我们使用 Org2 管理员身份提交了频道更新调用,因此容器仍然代表着 peer0.org2,我们直接安装:
```bash
peer chaincode install -n mycc -v 2.0 -p github.com/chaincode/chaincode_example02/go/
```
然后,切换到 peer0.org1 的身份:
```bash
export CORE_PEER_LOCALMSPID="Org1MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=peer0.org1.example.com:7051
```
再次安装:
```bash
peer chaincode install -n mycc -v 2.0 -p github.com/chaincode/chaincode_example02/go/
```
现在我们准备升级链码了。对底层源代码没有做任何修改,我们只是在 mychannel 上的链码 mycc 里面,将 Org3 添加到 的背书政策中。
> 提示:满足链码实例化策略的任何身份都可以发出升级调用。默认情况下,这些身份是通道管理员。
执行升级命令:
```bash
peer chaincode upgrade -o orderer.example.com:7050 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C $CHANNEL_NAME -n mycc -v 2.0 -c '{"Args":["init","a","90","b","210"]}' -P "OR ('Org1MSP.peer','Org2MSP.peer','Org3MSP.peer')"
```
在上面的命令中,通过 v 标志指定我们的新版本。背书策略已被修改为
-P“OR('Org1MSP.peer','Org2MSP.peer','Org3MSP.peer')”,反映了策略中添加了 Org3。最后就是我们的函数请求构造(使用 c 标志指定)。
与实例化调用一样,链码升级需要使用 init 方法。如果您的链码需要将参数传递给 init 方法,那么您需要在此处执行此操作。
升级调用向账本中添加了一个新块 - 块 6 ,来允许 Org3 的节点在背书阶段执行交易。回到 Org3 CLI 容器,我们来查询下 a 的值,这需要花一些时间,因为需要为目标节点构建链代码镜像,并且链码容器需要启动:
```bash
peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}'
```
我们应该看到返回为 Query Result:90。
现在发出一个调用,将 10 从 a 转移到 b:
```bash
peer chaincode invoke -o orderer.example.com:7050 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C $CHANNEL_NAME -n mycc -c '{"Args":["invoke","a","b","10"]}'
```
最后查询一次:
```bash
peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}'
```
我们应该看到 Query Result:80 的响应,这就准确地反映了这个 chaincode 状态的更新。
# 总结
通道配置更新过程确实非常复杂,但是步骤中方法还是有些逻辑的。最后也就是生成 protobuf 二进制格式表示的 delta 事务对象,然后获取必需数量的管理员签名,以便通道配置更新事务满足通道的修改策略。
我们完成这样的功能,主要就用到了 configtxlator 和 jq 工具以及很多的 peer channel 命令。 |
package seq_cmd
import (
"fmt"
"strconv"
"time"
"github.com/lunfardo314/proxima/ledger"
"github.com/lunfardo314/proxima/ledger/transaction"
"github.com/lunfardo314/proxima/ledger/txbuilder"
"github.com/lunfardo314/proxima/proxi/glb"
"github.com/lunfardo314/proxima/sequencer/factory/commands"
"github.com/lunfardo314/proxima/util"
"github.com/spf13/cobra"
)
func initSeqWithdrawCmd() *cobra.Command {
seqSendCmd := &cobra.Command{
Use: "withdraw <amount>",
Aliases: util.List("send"),
Short: `withdraw tokens from sequencer to the target lock`,
Args: cobra.ExactArgs(1),
Run: runSeqWithdrawCmd,
}
seqSendCmd.InitDefaultHelpCmd()
return seqSendCmd
}
const ownSequencerCmdFee = 500
func runSeqWithdrawCmd(_ *cobra.Command, args []string) {
glb.InitLedgerFromNode()
walletData := glb.GetWalletData()
glb.Assertf(walletData.Sequencer != nil, "can't get own sequencer ID")
glb.Infof("sequencer ID (source): %s", walletData.Sequencer.String())
glb.Infof("wallet account is: %s", walletData.Account.String())
targetLock := glb.MustGetTarget()
amount, err := strconv.ParseUint(args[0], 10, 64)
glb.AssertNoError(err)
glb.Infof("amount: %s", util.GoTh(amount))
glb.Infof("querying wallet's outputs..")
walletOutputs, err := getClient().GetAccountOutputs(walletData.Account, func(_ *ledger.OutputID, o *ledger.Output) bool {
return o.NumConstraints() == 2
})
glb.AssertNoError(err)
glb.Infof("will be using %d tokens as tag-along fee. Outputs in the wallet:", ownSequencerCmdFee)
for i, o := range walletOutputs {
glb.Infof("%d : %s : %s", i, o.ID.StringShort(), util.GoTh(o.Output.Amount()))
}
prompt := fmt.Sprintf("withdraw %s from %s to the target %s?",
util.GoTh(amount), walletData.Sequencer.StringShort(), targetLock.String())
if !glb.YesNoPrompt(prompt, false) {
glb.Infof("exit")
return
}
cmdConstr, err := commands.MakeSequencerWithdrawCommand(amount, targetLock.AsLock())
glb.AssertNoError(err)
transferData := txbuilder.NewTransferData(walletData.PrivateKey, walletData.Account, ledger.TimeNow()).
WithAmount(ownSequencerCmdFee).
WithTargetLock(ledger.ChainLockFromChainID(*walletData.Sequencer)).
MustWithInputs(walletOutputs...).
WithSender().
WithConstraint(cmdConstr)
txBytes, err := txbuilder.MakeSimpleTransferTransaction(transferData)
glb.AssertNoError(err)
txStr := transaction.ParseBytesToString(txBytes, transaction.PickOutputFromListFunc(walletOutputs))
glb.Verbosef("---- request transaction ------\n%s\n------------------", txStr)
glb.Infof("submitting the transaction...")
err = getClient().SubmitTransaction(txBytes)
glb.AssertNoError(err)
if glb.NoWait() {
return
}
txid, err := transaction.IDFromTransactionBytes(txBytes)
glb.AssertNoError(err)
glb.ReportTxInclusion(txid, time.Second)
} |
import React, { useContext, useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
// mui
import { Stack, Typography, Grid, TextField, Button, Box, Toolbar, Paper, Autocomplete } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import { SyncAlt } from "@mui/icons-material";
// contexts
import AdminContext from "../../contexts/AdminContext";
// constants
import { AUTH_ADMIN_ROUTE, PROFILE_ROUTE } from "../../constants/routes";
import { ADMIN_NEW_DOCUMENT_ENDPOINT } from "../../constants/endpoints";
// components
import Footer from "../../components/Footer";
import Loader from "../../components/Loader";
const NewDocuments = () => {
const formRef = useRef(null);
const navigate = useNavigate();
const { user, isProfileComplete, documents, collections, collection, setCollection } = useContext(AdminContext);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (!user) navigate(AUTH_ADMIN_ROUTE);
}, [user, navigate]);
const handleNewDocument = (e) => {
e.preventDefault();
const form = e.target;
const data = {};
const formData = new FormData(form);
formData.forEach((value, key) => (data[key] = value));
try {
setIsLoading(true);
axios
.post(ADMIN_NEW_DOCUMENT_ENDPOINT, { name: collection, data })
.then((res) => {
alert(data.title + " uploaded successfully!");
setIsLoading(false);
})
.catch((err) => {
console.log(err);
setIsLoading(false);
});
} catch (err) {
console.log(err);
}
};
return (
<Box
component="main"
sx={{
backgroundColor: (theme) => (theme.palette.mode === "light" ? theme.palette.grey[100] : theme.palette.grey[900]),
flexGrow: 1,
height: "100vh",
overflow: "auto",
}}
>
{isLoading ? <Loader /> : null}
<Toolbar />
{isProfileComplete(user) ? (
<Grid container spacing={2} sx={{ p: 2 }}>
<Grid item xs={12}>
<Paper sx={{ p: 2, display: "flex", flexDirection: "column" }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" spacing={2} mb={2}>
<Typography component="h2" variant="h6" color="primary" gutterBottom>
New Document
</Typography>
<Autocomplete
disablePortal
sx={{ minWidth: 200 }}
options={collections}
value={collection}
onChange={(e, value) => setCollection(value)}
renderInput={(params) => <TextField {...params} label="Search Collections" />}
/>
</Stack>
<form onSubmit={handleNewDocument} ref={formRef}>
<Grid container spacing={2}>
{documents.length &&
Object.keys(documents[0]).map((key) => (
<Grid key={key} item xs={12} sm={6} md={4} lg={3}>
<TextField multiline maxRows={4} name={key} label={key} fullWidth variant="outlined" />
</Grid>
))}
</Grid>
<Stack spacing={2} direction="row" justifyContent={"space-between"} sx={{ display: "flex", mt: 2 }}>
<LoadingButton loading={isLoading} type="submit" variant="contained" startIcon={<SyncAlt />}>
Upload
</LoadingButton>
</Stack>
</form>
</Paper>
</Grid>
</Grid>
) : (
<Stack py={16} spacing={2} alignItems="center" justifyContent="center">
<Typography component="p" variant="h4" align="center" color="error">
Profile Incomplete!
</Typography>
<Typography component="p" variant="body1" align="center" color="text.secondary">
Update your profile with all the necessary details to become a document/service provider!
</Typography>
<Button onClick={() => navigate(PROFILE_ROUTE)} sx={{ width: "fit-content" }} variant="contained">
Update Profile
</Button>
</Stack>
)}
<Footer />
</Box>
);
};
export default NewDocuments; |
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import dynamic from "next/dynamic";
import { FC } from "react";
const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });
type TCurve =
| "smooth"
| "straight"
| "stepline"
| "smooth"
| "straight"
| "stepline";
type Props = {
id: string | "bar-chart";
series: any | undefined;
type?: "bar" | any;
colors?: Array<string>;
className?: string;
dropShadowColor?: string;
strokeColor?: Array<string>;
height?: number | string;
width?: number | string;
stacked?: boolean;
plotOptions?: boolean;
showGrid?: boolean;
categories?: Array<string>;
label?: Array<string>;
curve?: TCurve | TCurve[];
showDownloads?: boolean;
};
export const CustomChart: FC<Props> = ({
type,
colors,
id,
series,
className,
height,
showGrid,
label,
categories,
curve,
showDownloads,
stacked,
}) => {
const yaxisOptions = {
show: true,
labels: {
show: true,
style: {
colors: "grey",
fontSize: "13px",
fontWeight: 100,
fontFamily: "Outfit",
},
formatter: (value: any) => {
return type !== "line" && type !== "area" && value > 0 ? value : value;
},
},
axisBorder: {
show: false,
},
axisTicks: {
show: false,
},
};
const options = {
chart: {
id: id,
toolbar: {
show: true,
tools: {
download: showDownloads ? true : false,
selection: false,
zoom: false,
zoomin: false,
zoomout: false,
pan: false,
reset: false,
},
},
selection: {
enabled: true,
stroke: {},
},
background: "#FFF",
dropShadow: {
enabled: true,
blur: 5,
opacity: 0.2,
color: "grey",
},
stacked: stacked,
},
labels: label,
xaxis: {
categories: categories || [],
labels: {
show: true,
style: {
fontFamily: `Outfit`,
color: "grey",
fontWeight: 300,
},
},
axisBorder: {
show: false,
},
axisTicks: {
show: false,
},
},
yaxis: yaxisOptions,
fill: {
colors: colors,
},
states: {
hover: {
filter: { type: "none" },
},
active: {
filter: { type: "none" },
},
},
grid: {
show: showGrid ?? true,
borderColor: `${"#EAEAEA"}`,
yaxis: {
lines: {
show: true,
},
},
xaxis: {
lines: {
show: false,
},
tooltip: {
enabled: false,
},
labels: {
show: true,
style: {
fontSize: "13px",
fontWeight: "300",
fontFamily: "Outfit",
},
},
},
},
dataLabels: {
enabled: false,
},
tooltip: {
enabled: true,
shared: false,
show: false,
style: {
fontSize: "12px",
fontFamily: "Outfit",
background: "green",
},
x: {
show: false,
},
y: {
show: true,
formatter: function (value: number) {
return `${value}`;
},
},
marker: { show: false },
theme: "dark",
},
stroke: {
show: true,
colors: colors,
curve: curve,
},
colors: colors,
};
return (
<Chart
options={options}
series={series}
type={type}
height={height ?? 300}
width={"100%"}
className={className}
/>
);
}; |
/*
* Copyright (c) 2010 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ihtsdo.project.wizard;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.ihtsdo.wizard.I_fastWizard;
/**
* The Class SimpleTextCollector.
*
* @author Guillermo Reynoso
*/
public class SimpleTextCollector extends JPanel implements I_fastWizard {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 4533413277239846148L;
/**
* Instantiates a new simple text collector.
*/
public SimpleTextCollector() {
initComponents();
}
/**
* Inits the components.
*/
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
label1 = new JLabel();
textField1 = new JTextField();
//======== this ========
setLayout(new GridBagLayout());
((GridBagLayout)getLayout()).columnWidths = new int[] {0, 0, 0, 0, 0};
((GridBagLayout)getLayout()).rowHeights = new int[] {15, 0, 0, 0, 0};
((GridBagLayout)getLayout()).columnWeights = new double[] {0.0, 0.0, 1.0, 0.0, 1.0E-4};
((GridBagLayout)getLayout()).rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 1.0E-4};
//---- label1 ----
label1.setText("text");
add(label1, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
add(textField1, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
/** The label1. */
private JLabel label1;
/** The text field1. */
private JTextField textField1;
/** The key. */
private String key;
// JFormDesigner - End of variables declaration //GEN-END:variables
/* (non-Javadoc)
* @see org.ihtsdo.wizard.I_fastWizard#getData()
*/
@Override
public HashMap<String, Object> getData() throws Exception {
if (textField1.getText().trim().equals("")){
throw new Exception ("The name cannot be null.");
}
HashMap<String, Object> res=new HashMap<String, Object>();
res.put(key, textField1.getText());
return res;
}
/* (non-Javadoc)
* @see org.ihtsdo.wizard.I_fastWizard#setKey(java.lang.String)
*/
@Override
public void setKey(String key) {
this.key=key;
}
/**
* Sets the label.
*
* @param strLabel the new label
*/
public void setLabel(String strLabel){
label1.setText(strLabel);
}
} |
//
// LoginViewController.swift
// CBDS Calculator
//
// Created by Zhang Sheng on 7/23/20.
// Copyright © 2020 Sheng Zhang. All rights reserved.
//
import UIKit
import FirebaseAuth
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var welcomeLabel: UILabel!
@IBOutlet weak var dontHaveAnAccountLabel: UILabel!
@IBOutlet weak var signUpNowButton: UIButton!
@IBOutlet weak var emailImage: UIImageView!
@IBOutlet weak var passwordImage: UIImageView!
@IBOutlet weak var forgetYourPassword: UIButton!
@IBOutlet weak var guestLoginButton: UIButton!
@IBOutlet weak var statisticsLabel: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
emailTextField.delegate = self
passwordTextField.delegate = self
self.statisticsLabel.layer.borderWidth = 2.0
self.statisticsLabel.layer.cornerRadius = 8
self.spinner.isHidden = true
self.spinner.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
return true
}
@IBAction func signUpNowTapped(_ sender: UIButton) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SignUpViewController") as! SignUpViewController
vc.modalTransitionStyle = .flipHorizontal
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true)
}
@IBAction func loginTapped(_ sender: UIButton) {
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
let error = validateEmailandPassword(emailTextField: emailTextField, passwordTextField: passwordTextField)
if error != nil {
// show pop up alert message
showAlert(title: "Login Failed", message: error!, view: self)
}
else {
// Validate the user email and password using Firebase Auth
let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().signIn(withEmail: email, password: password) { (result, errorFromFirebase) in
if let errorFromFirebase = errorFromFirebase {
// show pop up alert message
showAlert(title: "Login Failed", message: errorFromFirebase.localizedDescription, view: self)
}
else {
// Transition to the NavigationController
UIView.animate(withDuration: 1.5, animations: {
self.backgroundImage.alpha = 0.2
self.loginButton.alpha = 0.2
self.welcomeLabel.alpha = 0.2
self.dontHaveAnAccountLabel.alpha = 0.2
self.signUpNowButton.alpha = 0.2
self.emailImage.alpha = 0.2
self.passwordImage.alpha = 0.2
self.emailTextField.alpha = 0.2
self.passwordTextField.alpha = 0.2
self.forgetYourPassword.alpha = 0.2
self.guestLoginButton.alpha = 0.2
self.statisticsLabel.alpha = 0.2
self.spinner.isHidden = false
self.spinner.startAnimating()
}, completion: { done in
if done {
self.transitionToNavigationController()
}
})
}
}
}
}
@IBAction func guestLoginTapped(_ sender: UIButton) {
// Transition to the NavigationController
UIView.animate(withDuration: 1.5, animations: {
self.backgroundImage.alpha = 0.2
self.loginButton.alpha = 0.2
self.welcomeLabel.alpha = 0.2
self.dontHaveAnAccountLabel.alpha = 0.2
self.signUpNowButton.alpha = 0.2
self.emailImage.alpha = 0.2
self.passwordImage.alpha = 0.2
self.emailTextField.alpha = 0.2
self.passwordTextField.alpha = 0.2
self.forgetYourPassword.alpha = 0.2
self.guestLoginButton.alpha = 0.2
self.statisticsLabel.alpha = 0.2
self.spinner.isHidden = false
self.spinner.startAnimating()
}, completion: { done in
if done {
self.transitionToNavigationController()
}
})
}
private func transitionToNavigationController() {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController
vc.modalTransitionStyle = .coverVertical
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true)
}
@IBAction func resetPassword(_ sender: UIButton) {
showForgetYourPasswordAlert()
}
private func showForgetYourPasswordAlert() {
let alert = UIAlertController(title: "Reset Your Password", message: "Please enter your email address below. We will send you an email to reset your password", preferredStyle: .alert)
alert.addTextField { textField in
textField.placeholder = "Email"
}
let send = UIAlertAction(title: "Send", style: .default) { _ in
if let emailTextField = alert.textFields?.first, let email = emailTextField.text {
Auth.auth().sendPasswordReset(withEmail: email, completion: nil)
}
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(send)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
} |
// 199 https://leetcode.com/problems/binary-tree-right-side-view/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
/**
* @param {TreeNode} root
* @return {number[]}
*/
// idea: collect the last value of each level
const rightSideView = function(root) {
const result = [];
if (root === null) {
return result;
}
const nodeQueue = [root];
while (nodeQueue.length > 0) {
const currentLevelSize = nodeQueue.length;
result.push(nodeQueue[0].val);
for (let i = 0; i < currentLevelSize; i++) {
const shiftedNode = nodeQueue.shift();
const { left, right } = shiftedNode;
if (right !== null) {
nodeQueue.push(right);
}
if (left !== null) {
nodeQueue.push(left);
}
}
}
return result;
};
const node15 = new TreeNode(15);
const node7 = new TreeNode(7);
const node20 = new TreeNode(20, node15, node7);
const node9 = new TreeNode(9);
const root = new TreeNode(3, node9, node20);
const result = rightSideView(root);
console.log(result); |
/// adult : false
/// gender : 0
/// id : 3234630
/// known_for_department : "Acting"
/// name : "Sangeeth Shobhan"
/// original_name : "Sangeeth Shobhan"
/// popularity : 214.068
/// profile_path : "/7Vox31bH7XmgPNJzMKGa4uGyjW8.jpg"
/// known_for : [{"adult":false,"backdrop_path":"/jBnnkkXRZ0pV3Tw31Z2ALO638wA.jpg","id":1187075,"title":"MAD","original_language":"te","original_title":"MAD","overview":"Set in an engineering college and revolves around the antics of the students there, primarily the boys, who get a kick out of torturing the hostel warden.","poster_path":"/nDpOmgBfQZwOpFBcgokQGqd74r1.jpg","media_type":"movie","genre_ids":[35,10749,18],"popularity":8.388,"release_date":"2023-10-06","video":false,"vote_average":7,"vote_count":4},{"adult":false,"backdrop_path":"/1jof3bGVg67HLmvRHfTzqb2IODO.jpg","id":138179,"name":"Oka Chinna Family Story","original_language":"te","original_name":"ఒక చిన్న Family Story","overview":"Mahesh and his mother embark on an adventurous journey filled with hilarious situations as they try to make quick money to repay a huge loan.","poster_path":"/u1Tq2Qqb1oUJ6WSzVJqWk03LzEl.jpg","media_type":"tv","genre_ids":[35,10751],"popularity":7.198,"first_air_date":"2021-11-19","vote_average":7.5,"vote_count":2,"origin_country":["IN"]}]
class MovieProfileModel {
MovieProfileModel({
bool? adult,
num? gender,
num? id,
String? knownForDepartment,
String? name,
String? originalName,
num? popularity,
String? profilePath,
List<KnownFor>? knownFor,}){
_adult = adult;
_gender = gender;
_id = id;
_knownForDepartment = knownForDepartment;
_name = name;
_originalName = originalName;
_popularity = popularity;
_profilePath = profilePath;
_knownFor = knownFor;
}
MovieProfileModel.fromJson(dynamic json) {
_adult = json['adult'];
_gender = json['gender'];
_id = json['id'];
_knownForDepartment = json['known_for_department'];
_name = json['name'];
_originalName = json['original_name'];
_popularity = json['popularity'];
_profilePath = json['profile_path'];
if (json['known_for'] != null) {
_knownFor = [];
json['known_for'].forEach((v) {
_knownFor?.add(KnownFor.fromJson(v));
});
}
}
bool? _adult;
num? _gender;
num? _id;
String? _knownForDepartment;
String? _name;
String? _originalName;
num? _popularity;
String? _profilePath;
List<KnownFor>? _knownFor;
MovieProfileModel copyWith({ bool? adult,
num? gender,
num? id,
String? knownForDepartment,
String? name,
String? originalName,
num? popularity,
String? profilePath,
List<KnownFor>? knownFor,
}) => MovieProfileModel( adult: adult ?? _adult,
gender: gender ?? _gender,
id: id ?? _id,
knownForDepartment: knownForDepartment ?? _knownForDepartment,
name: name ?? _name,
originalName: originalName ?? _originalName,
popularity: popularity ?? _popularity,
profilePath: profilePath ?? _profilePath,
knownFor: knownFor ?? _knownFor,
);
bool? get adult => _adult;
num? get gender => _gender;
num? get id => _id;
String? get knownForDepartment => _knownForDepartment;
String? get name => _name;
String? get originalName => _originalName;
num? get popularity => _popularity;
String? get profilePath => _profilePath;
List<KnownFor>? get knownFor => _knownFor;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['adult'] = _adult;
map['gender'] = _gender;
map['id'] = _id;
map['known_for_department'] = _knownForDepartment;
map['name'] = _name;
map['original_name'] = _originalName;
map['popularity'] = _popularity;
map['profile_path'] = _profilePath;
if (_knownFor != null) {
map['known_for'] = _knownFor?.map((v) => v.toJson()).toList();
}
return map;
}
}
/// adult : false
/// backdrop_path : "/jBnnkkXRZ0pV3Tw31Z2ALO638wA.jpg"
/// id : 1187075
/// title : "MAD"
/// original_language : "te"
/// original_title : "MAD"
/// overview : "Set in an engineering college and revolves around the antics of the students there, primarily the boys, who get a kick out of torturing the hostel warden."
/// poster_path : "/nDpOmgBfQZwOpFBcgokQGqd74r1.jpg"
/// media_type : "movie"
/// genre_ids : [35,10749,18]
/// popularity : 8.388
/// release_date : "2023-10-06"
/// video : false
/// vote_average : 7
/// vote_count : 4
class KnownFor {
KnownFor({
bool? adult,
String? backdropPath,
num? id,
String? title,
String? originalLanguage,
String? originalTitle,
String? overview,
String? posterPath,
String? mediaType,
List<num>? genreIds,
num? popularity,
String? releaseDate,
bool? video,
num? voteAverage,
num? voteCount,}){
_adult = adult;
_backdropPath = backdropPath;
_id = id;
_title = title;
_originalLanguage = originalLanguage;
_originalTitle = originalTitle;
_overview = overview;
_posterPath = posterPath;
_mediaType = mediaType;
_genreIds = genreIds;
_popularity = popularity;
_releaseDate = releaseDate;
_video = video;
_voteAverage = voteAverage;
_voteCount = voteCount;
}
KnownFor.fromJson(dynamic json) {
_adult = json['adult'];
_backdropPath = json['backdrop_path'];
_id = json['id'];
_title = json['title'];
_originalLanguage = json['original_language'];
_originalTitle = json['original_title'];
_overview = json['overview'];
_posterPath = json['poster_path'];
_mediaType = json['media_type'];
_genreIds = json['genre_ids'] != null ? json['genre_ids'].cast<num>() : [];
_popularity = json['popularity'];
_releaseDate = json['release_date'];
_video = json['video'];
_voteAverage = json['vote_average'];
_voteCount = json['vote_count'];
}
bool? _adult;
String? _backdropPath;
num? _id;
String? _title;
String? _originalLanguage;
String? _originalTitle;
String? _overview;
String? _posterPath;
String? _mediaType;
List<num>? _genreIds;
num? _popularity;
String? _releaseDate;
bool? _video;
num? _voteAverage;
num? _voteCount;
KnownFor copyWith({ bool? adult,
String? backdropPath,
num? id,
String? title,
String? originalLanguage,
String? originalTitle,
String? overview,
String? posterPath,
String? mediaType,
List<num>? genreIds,
num? popularity,
String? releaseDate,
bool? video,
num? voteAverage,
num? voteCount,
}) => KnownFor( adult: adult ?? _adult,
backdropPath: backdropPath ?? _backdropPath,
id: id ?? _id,
title: title ?? _title,
originalLanguage: originalLanguage ?? _originalLanguage,
originalTitle: originalTitle ?? _originalTitle,
overview: overview ?? _overview,
posterPath: posterPath ?? _posterPath,
mediaType: mediaType ?? _mediaType,
genreIds: genreIds ?? _genreIds,
popularity: popularity ?? _popularity,
releaseDate: releaseDate ?? _releaseDate,
video: video ?? _video,
voteAverage: voteAverage ?? _voteAverage,
voteCount: voteCount ?? _voteCount,
);
bool? get adult => _adult;
String? get backdropPath => _backdropPath;
num? get id => _id;
String? get title => _title;
String? get originalLanguage => _originalLanguage;
String? get originalTitle => _originalTitle;
String? get overview => _overview;
String? get posterPath => _posterPath;
String? get mediaType => _mediaType;
List<num>? get genreIds => _genreIds;
num? get popularity => _popularity;
String? get releaseDate => _releaseDate;
bool? get video => _video;
num? get voteAverage => _voteAverage;
num? get voteCount => _voteCount;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['adult'] = _adult;
map['backdrop_path'] = _backdropPath;
map['id'] = _id;
map['title'] = _title;
map['original_language'] = _originalLanguage;
map['original_title'] = _originalTitle;
map['overview'] = _overview;
map['poster_path'] = _posterPath;
map['media_type'] = _mediaType;
map['genre_ids'] = _genreIds;
map['popularity'] = _popularity;
map['release_date'] = _releaseDate;
map['video'] = _video;
map['vote_average'] = _voteAverage;
map['vote_count'] = _voteCount;
return map;
}
} |
package me.shu.exercise.zookeeper;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 《ZooKeeper 事件类型详解》
*
* @author nileader/nileader@gmail.com
*
*/
public class AllZooKeeperWatcher implements Watcher {
private static final Logger LOG = LoggerFactory
.getLogger(AllZooKeeperWatcher.class);
AtomicInteger seq = new AtomicInteger();
private static final int SESSION_TIMEOUT = 10000;
private static final String CONNECTION_STRING = "hk-ubuntu.cloudapp.net:2181";
private static final String ZK_PATH = "/shu/test";
private static final String CHILDREN_PATH = "/shu/test/data";
private ZooKeeper zk = null;
private CountDownLatch connectedSemaphore = new CountDownLatch(1);
/**
* 创建ZK连接
*
* @param connectString
* ZK服务器地址列表
* @param sessionTimeout
* Session超时时间
*/
public void createConnection(String connectString, int sessionTimeout) {
this.releaseConnection();
try {
zk = new ZooKeeper(connectString, sessionTimeout, this);
LOG.info("开始连接ZK服务器");
connectedSemaphore.await();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭ZK连接
*/
public void releaseConnection() {
if (this.zk != null) {
try {
this.zk.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 创建节点
*
* @param path
* 节点path
* @param data
* 初始数据内容
* @return
*/
public boolean createPath(String path, String data) {
try {
this.zk.exists(path, true);
LOG.info("节点创建成功, Path: " + this.zk.create(path, //
data.getBytes(), //
Ids.OPEN_ACL_UNSAFE, //
CreateMode.PERSISTENT) + ", content: " + data);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 读取指定节点数据内容
*
* @param path
* 节点path
* @return
*/
public String readData(String path, boolean needWatch) {
try {
return new String(this.zk.getData(path, needWatch, null));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 更新指定节点数据内容
*
* @param path
* 节点path
* @param data
* 数据内容
* @return
*/
public boolean writeData(String path, String data) {
try {
LOG.info("更新数据成功,path:" + path + ", stat: "
+ this.zk.setData(path, data.getBytes(), -1));
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 删除指定节点
*
* @param path
* 节点path
*/
public void deleteNode(String path) {
try {
if (this.zk.exists(path, true) != null) {
this.zk.delete(path, -1);
LOG.info("删除节点成功,path:" + path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除指定节点
*
* @param path
* 节点path
*/
public Stat exists(String path, boolean needWatch) {
try {
return this.zk.exists(path, needWatch);
} catch (Exception e) {
return null;
}
}
/**
* 获取子节点
*
* @param path
* 节点path
*/
private List<String> getChildren(String path, boolean needWatch) {
try {
return this.zk.getChildren(path, needWatch);
} catch (Exception e) {
return null;
}
}
public void deleteAllTestPath() {
this.deleteNode(CHILDREN_PATH);
this.deleteNode(ZK_PATH);
}
@Test
public void all() throws InterruptedException {
AllZooKeeperWatcher sample = new AllZooKeeperWatcher();
sample.createConnection(CONNECTION_STRING, SESSION_TIMEOUT);
// 清理节点
sample.deleteAllTestPath();
if (sample.createPath(ZK_PATH, System.currentTimeMillis() + "")) {
// 读取数据
sample.readData(ZK_PATH, true);
// 读取子节点
sample.getChildren(ZK_PATH, true);
// 更新数据
sample.writeData(ZK_PATH, System.currentTimeMillis() + "");
// 创建子节点
sample.createPath(CHILDREN_PATH, System.currentTimeMillis() + "");
}
// 清理节点
sample.deleteAllTestPath();
sample.releaseConnection();
}
/**
* 收到来自Server的Watcher通知后的处理。
*/
@Override
public void process(WatchedEvent event) {
if (event == null) {
return;
}
// 连接状态
KeeperState keeperState = event.getState();
// 事件类型
EventType eventType = event.getType();
// 受影响的path
String path = event.getPath();
String logPrefix = "【Watcher-" + this.seq.incrementAndGet() + "】";
LOG.info(logPrefix + "收到Watcher通知");
LOG.info(logPrefix + "连接状态:\t" + keeperState.toString());
LOG.info(logPrefix + "事件类型:\t" + eventType.toString());
if (KeeperState.SyncConnected == keeperState) {
// 成功连接上ZK服务器
if (EventType.None == eventType) {
LOG.info(logPrefix + "成功连接上ZK服务器");
connectedSemaphore.countDown();
} else if (EventType.NodeCreated == eventType) {
LOG.info(logPrefix + "节点创建");
this.exists(path, true);
} else if (EventType.NodeDataChanged == eventType) {
LOG.info(logPrefix + "节点数据更新");
LOG.info(logPrefix + "数据内容: " + this.readData(ZK_PATH, true));
} else if (EventType.NodeChildrenChanged == eventType) {
LOG.info(logPrefix + "子节点变更");
LOG.info(logPrefix + "子节点列表:" + this.getChildren(ZK_PATH, true));
} else if (EventType.NodeDeleted == eventType) {
LOG.info(logPrefix + "节点 " + path + " 被删除");
}
} else if (KeeperState.Disconnected == keeperState) {
LOG.info(logPrefix + "与ZK服务器断开连接");
} else if (KeeperState.AuthFailed == keeperState) {
LOG.info(logPrefix + "权限检查失败");
} else if (KeeperState.Expired == keeperState) {
LOG.info(logPrefix + "会话失效");
}
LOG.info("--------------------------------------------");
}
} |
import { useTheme } from "next-themes";
import React, { useEffect, useRef, useState } from "react";
import { IoMdAdd } from "react-icons/io";
import { GrPowerReset } from "react-icons/gr";
import { MdOutlineCancel } from "react-icons/md";
import { AiOutlineCopy } from "react-icons/ai";
import toast, { Toaster } from "react-hot-toast";
import { palette } from "./tailwindColorPalette";
import { useOutsideClick } from "hooks/useOutsideClick";
import styles from "./styles.module.css";
import { FaRandom } from "react-icons/fa";
export const GenerateBoxShadow = React.forwardRef((props, ref) => {
let defaultBoxShadow = {
id: new Date().getTime(),
horizontalOffset: 0,
verticalOffset: 20,
blur: 20,
spread: 10,
color: "#00000024",
};
const [boxShadow, setBoxShadow] = useState([defaultBoxShadow]);
const [activeShadow, setActiveShadow] = useState(null);
const [modal, setModal] = useState(false);
const boxRef = useRef();
useOutsideClick(boxRef, () => setModal(false));
const generateShadow = () => {
let final = [];
boxShadow.forEach((el) => {
let temp =
`${el.horizontalOffset}px ` +
`${el.verticalOffset}px ` +
`${el.blur}px ` +
`${el.spread}px ` +
`${el.color}`;
temp = el.inset ? `inset ${temp}` : temp;
final.push(temp);
});
return final.join(",");
};
const onChangeHandler = (action, data) => {
switch (action) {
case "horizontalOffset":
findAndUpdateValue("horizontalOffset", data);
break;
case "verticalOffset":
findAndUpdateValue("verticalOffset", data);
break;
case "blur":
findAndUpdateValue("blur", data);
break;
case "spread":
findAndUpdateValue("spread", data);
break;
case "inset":
findAndUpdateValue("inset", data);
break;
case "color":
findAndUpdateValue("color", data);
break;
case "delete":
handleShadowDelete(data);
break;
case "color-button":
// open modal
setActiveShadow(data);
setModal(true);
break;
case "color-select":
handleColorSelect(data);
break;
default:
break;
}
};
const handleColorSelect = (selectedColor) => {
//
let data = {
...activeShadow,
updatedValue: selectedColor,
};
findAndUpdateValue("color", data);
setActiveShadow(null);
setModal(false);
};
const handleShadowDelete = (shadowElement) => {
let temp = boxShadow.filter((el) => el.id !== shadowElement.id);
setBoxShadow(temp);
};
const addShadowLayer = () => {
// box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
let temp = [...boxShadow];
temp.push({
...defaultBoxShadow,
id: new Date().getTime(),
horizontalOffset: 0,
verticalOffset: 3,
blur: 8,
spread: 0,
color: "#00000024",
});
setBoxShadow([...temp]);
};
const findAndUpdateValue = (key, data) => {
let target = boxShadow.map((el) => {
if (el.id === data.id) {
el[key] = data.updatedValue;
}
return el;
});
setBoxShadow(target);
};
const copyToClipboard = (text) => {
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand("copy");
var msg = successful ? "successful" : "unsuccessful";
} catch (err) {
console.error("Fallback: Oops, unable to copy", err);
}
document.body.removeChild(textArea);
notify("Copied Successfully!");
};
const copyVanillaCSS = () => {
let generatedShadow = `box-shadow: ${generateShadow()}`;
copyToClipboard(generatedShadow);
};
const generateTailwindCSSJIT = () => {
let probableOutput = `box-shadow: ${generateShadow()}`;
if (probableOutput.includes("box-shadow:")) {
probableOutput = probableOutput.split("box-shadow:")[1];
}
if (probableOutput.includes(";")) {
probableOutput = probableOutput.split(";")[0];
}
let finalOutput = probableOutput.trim().split(" ").join("_");
finalOutput = `shadow-[${finalOutput}]`;
copyToClipboard(finalOutput);
};
const handleReset = () => {
setBoxShadow([defaultBoxShadow]);
};
const notify = (message) => {
toast(message || "Copied successfully!", {
duration: 4000,
position: "top-center",
// Styling
style: {},
className: "",
// Custom Icon
icon: "👏",
// Change colors of success/error/loading icon
iconTheme: {
primary: "#000",
secondary: "#fff",
},
// Aria
ariaProps: {
role: "status",
"aria-live": "polite",
},
});
};
const handleRandomize = () => {
let temp = [...boxShadow];
temp.forEach((el) => {
el.horizontalOffset = Math.floor(Math.random() * 41) - 20;
el.verticalOffset = Math.floor(Math.random() * 41) - 20;
el.blur = Math.floor(Math.random() * 50);
el.spread = Math.floor(Math.random() * 50);
el.color = randomColor();
});
setBoxShadow(temp);
};
const randomColor = () => {
let color = "#";
let letters = "0123456789ABCDEF";
for (let i = 0; i < 8; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
return (
<div
ref={ref}
className="bg-gray-50 w-full px-4 lg:px-20 min-h-screen relative mb-20"
>
<Toaster />
{modal && (
<PaletteModal
onChangeHandler={onChangeHandler}
palette={palette}
ref={boxRef}
/>
)}
<div className="pt-10 pb-20">
<h2 className="font-bold text-xl md:text-3xl tracking-normal mb-4 text-black dark:text-black mx-auto mt-4 text-center ">
Box Shadow Generator for{" "}
<span className="bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500">
TailwindCSS
</span>
</h2>
<h4 className="prose text-gray-700 font-light dark:text-gray-400 text-center mx-auto">
A free tool that helps you generate box shadows for TailwindCSS (JIT)
and Vanilla CSS with ease.
</h4>
</div>
<div className="w-fullitems-center flex flex-col lg:flex-row">
<div className="w-full lg:w-[60%]">
<div class="relative flex flex-col justify-center py-6 sm:py-12">
<div class="absolute inset-0 bg-center [mask-image:linear-gradient(180deg,white,rgba(255,255,255,0))]"></div>
<div
style={{
boxShadow: generateShadow(),
}}
class="relative bg-white px-6 pt-10 pb-8 ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10"
>
<div class="mx-auto max-w-md">
<img
src="/avatar-new.png"
alt="Manu Arora"
className="h-8 rounded-full"
/>
<div class="divide-y divide-gray-300/50">
<div class="space-y-6 py-8 text-base leading-7 text-gray-600">
<p>
Add shadow to this box with the controls on the side
panel. This box mimics a card box that you might have on
your website.
</p>
<p>
Add shadow layers, change colors and play with the
controls.
</p>
</div>
<div class="pt-8 text-base font-semibold leading-7">
<p class="text-gray-900">Want beautiful shadows already?</p>
<p>
<button
onClick={() => window && window.scrollTo(0, 0)}
href="https://tailwindcss.com/docs"
class="text-sky-500 hover:text-sky-600"
>
Explore the presets
</button>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="h-full w-full lg:w-[40%] flex flex-col">
<div className="flex flex-row justify-between flex-wrap mb-2 text-xs space-x-2 pb-4 px-2">
<button
onClick={addShadowLayer}
className="text-white flex flex-row space-x-1 items-center font-light bg-zinc-500 px-2 py-1 rounded-md hover:bg-zinc-600"
>
<IoMdAdd className="stroke-[10px]" /> Add Shadow Layer
</button>
<div className="flex flex-row space-x-2">
<button
onClick={handleRandomize}
className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200"
>
<FaRandom className="stroke-[1px] mr-2" /> Randomize
</button>
<button
onClick={handleReset}
className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200"
>
<GrPowerReset className="stroke-[10px] mr-2" /> Reset
</button>
<button
onClick={copyVanillaCSS}
className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200"
>
<AiOutlineCopy className="stroke-[10px] mr-2" /> Vanilla CSS
</button>
<button
onClick={generateTailwindCSSJIT}
className="text-black flex flex-row space-x-2 items-center font-light bg-slate-100 px-2 py-1 rounded-md hover:bg-slate-200"
>
<AiOutlineCopy className="stroke-[10px] mr-2" /> Tailwind JIT
</button>
</div>
</div>
<div className="text-black palette rounded-md px-2 h-[30rem] overflow-y-auto space-y-4">
{boxShadow.map((el, idx) => (
<FormElement
shadowElement={el}
onChangeHandler={onChangeHandler}
key={el.id}
/>
))}
</div>
</div>
</div>
</div>
);
});
const FormElement = ({ onChangeHandler, shadowElement }) => {
return (
<div className="relative bg-white rounded-lg shadow-lg shadow-black/10 py-4 px-6">
<button
className="absolute right-2 top-2"
onClick={() => onChangeHandler("delete", shadowElement)}
>
<MdOutlineCancel className="text-slate-500 hover:text-red-500" />
</button>
<div className="flex flex-row space-x-2 mb-2">
<label
className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white"
htmlFor={`horizontalOffset-${shadowElement.id}`}
>
X
</label>
<input
value={shadowElement.horizontalOffset}
className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700"
id={`horizontalOffset-${shadowElement.id}`}
type="number"
onChange={(e) =>
onChangeHandler("horizontalOffset", {
updatedValue: e.target.value,
...shadowElement,
})
}
/>
<p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white">
{shadowElement.horizontalOffset}px Horizontal Offset
</p>
</div>
<div className="flex flex-row space-x-2 mb-2">
<label
className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white"
htmlFor={`verticalOffset-${shadowElement.id}`}
>
Y
</label>
<input
value={shadowElement.verticalOffset}
className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700"
id={`verticalOffset-${shadowElement.id}`}
type="number"
onChange={(e) =>
onChangeHandler("verticalOffset", {
updatedValue: e.target.value,
...shadowElement,
})
}
/>
<p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white">
{shadowElement.verticalOffset}px Vertical Offset
</p>
</div>
<div className="flex flex-row space-x-2 mb-2">
<label
className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white"
htmlFor={`blur-${shadowElement.id}`}
>
B
</label>
<input
min="0"
value={shadowElement.blur}
className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700"
id={`blur-${shadowElement.id}`}
type="number"
onChange={(e) =>
onChangeHandler("blur", {
updatedValue: e.target.value,
...shadowElement,
})
}
/>
<p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white">
{shadowElement.blur}px blur
</p>
</div>
<div className="flex flex-row space-x-2 mb-2">
<label
className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white"
htmlFor={`spread-${shadowElement.id}`}
>
S
</label>
<input
min="0"
value={shadowElement.spread}
className="inline-block w-28 shadow rounded-md px-2 text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700"
id={`spread-${shadowElement.id}`}
type="number"
onChange={(e) =>
onChangeHandler("spread", {
updatedValue: e.target.value,
...shadowElement,
})
}
/>
<p className="border border-slate-700 px-2 py-px rounded-md bg-slate-600 text-xs text-white">
{shadowElement.spread}px spread
</p>
</div>
<div className="flex flex-row space-x-2 mb-2">
<label
className="border border-slate-700 px-2 py-0.5 text-xs rounded-md bg-slate-600 text-white"
htmlFor={`color-${shadowElement.id}`}
>
C
</label>
<input
value={shadowElement.color}
className="inline-block w-28 shadow rounded-md px-2 uppercase text-sm text-zinc-600 border border-transparent focus:outline-none focus:border-blue-700"
id={`color-${shadowElement.id}`}
type="text"
onChange={(e) =>
onChangeHandler("color", {
updatedValue: e.target.value,
...shadowElement,
})
}
/>
<button
onClick={() => onChangeHandler("color-button", shadowElement)}
className="p-3 w-10 rounded-md"
style={{ backgroundColor: shadowElement.color }}
></button>
</div>
<div className="flex flex-row space-x-2 mb-2">
<div class={styles["checkbox-wrapper-1"]}>
<input
id={`inset-${shadowElement.id}`}
class={styles.substituted}
type="checkbox"
aria-hidden="true"
onChange={(e) =>
onChangeHandler("inset", {
updatedValue: e.target.checked,
...shadowElement,
})
}
/>
<label className="text-base" htmlFor={`inset-${shadowElement.id}`}>
Inset
</label>
</div>
{/*
<input
min="0"
value={shadowElement.inset}
className="accent-sky-500 px-4 py-4 inline-block"
id={`inset-${shadowElement.id}`}
type="checkbox"
onChange={(e) =>
onChangeHandler("inset", {
updatedValue: e.target.checked,
...shadowElement,
})
}
/> */}
</div>
</div>
);
};
const PaletteModal = React.forwardRef((props, ref) => {
const { onChangeHandler, palette } = props;
return (
<div className="h-full w-full absolute z-20 inset-0 flex items-center justify-center bg-black/10">
<div
ref={ref}
className="h-3/4 w-2/4 rounded-md bg-white overflow-y-auto p-4 shadow"
>
<h1 className="font-bold text-base text-center text-zinc-700 mb-4">
Tailwind CSS Color Palette
</h1>
{palette.map((pal, idx) => (
<div className=" mb-2" key={pal.paletteName}>
<h4 className="font-bold text-zinc-700 mx-4">{pal.paletteName}</h4>
<div className="flex flex-row flex-wrap">
{pal.swatches.map((sw, idx) => (
<div>
<button
onClick={() => onChangeHandler("color-select", sw.color)}
className="h-10 w-20 rounded-md mx-2 my-1"
style={{ backgroundColor: sw.color }}
></button>
<p className="text-zinc-400 text-[0.60rem] mx-2 font-light">
<span className="font-normal text-zinc-600">{sw.name}</span>{" "}
- {sw.color}
</p>
</div>
))}
</div>
</div>
))}
</div>
</div>
);
}); |
3 # The Location Class
class Location:
# Constructor
def __init__(self, name):
self.name = name
self.power = 0
self.units = []
# ACTIONS : Sometimes even our territory values must be changed when Actions occur, we do this in these functions
# -----------------------------------------------------------------------
# For when a unit is bought and placed here
def purchaseUnit(self, un):
self.power += un.getPower()
self.units.append(un)
self.owner = un.getOwner()
def move_from(self, un):
self.power -= un.getPower()
self.units.remove(un)
if len(self.units) == 0:
self.owner = None
return True
return False
def move_to(self, un):
self.power += un.getPower()
self.units.append(un)
un.move(self)
if len(self.units) == 1:
self.owner = un.getOwner()
return True
return False
# Function to defend from player pl's attacking unit un
def defend(self, att_pow):
# So long as the attacking power is not brought to 0, then the defenders will keep fighting
while att_pow > 0 and self.power > 0:
# Trade the first unit
defender = self.units[0]
def_pow = defender.getPower()
# If the defender is stronger, then it just takes the damage
if def_pow > att_pow:
defender.takeDamage(att_pow)
# If not then it will die
else:
self.owner.loseUnit(self, defender)
att_pow -= def_pow
def loseUnit(self, un):
self.power -= un.getPower()
self.units.remove(un)
if len(self.units) == 0:
self.owner = None
return True
return False
class Coast(Location):
def __init__(self, name, data, ter):
super().__init__(name, data["sea_neighbors"], data["sea_button"])
self.territory = ter
def getTerritory(self):
return self.territory
def navPower(self):
return sum([un.getPower() for un in self.units])
class Territory(Location):
def __init__(self, name, data):
super().__init__(name, data["neighbors"], data["button"].center)
self.coast = Coast(name, data, self)
self.button = data["button"]
self.border = data["border"]
self.resources = data["resources"]
self.turn_claimed = None
def getCoast(self):
return self.coast
def getButton(self):
return self.button
def getBorder(self):
return self.border
def getResources(self):
return self.resources
def isClaimed(self, turn):
if self.turn_claimed is not None:
return self.turn_claimed == 0 or self.turn_claimed <= turn - 3
return False
def attPower(self):
return sum([un.getPower() for un in self.units if not un.isDefensive() and not un.isArial()])
def defPower(self):
return sum([un.getPower() for un in self.units if un.isDefensive()])
def ariPower(self):
return sum([un.getPower() for un in self.units if un.isArial()])
# ACTIONS : Sometimes even our territory values must be changed when Actions occur, we do this in these functions
# -----------------------------------------------------------------------
# Function to begin the game calle by this territories new owner
def startGame(self, owner, un):
self.owner = owner
self.turn_claimed = 0
self.power += un.getPower()
self.units.append(un)
def move_from(self, un):
if super(Territory, self).move_from(un):
self.turn_claimed = None
return True
return False
def loseUnit(self, un):
if super(Territory, self).loseUnit(un):
self.turn_claimed = None
return True
return False
# Turn a integer into a Roman Numeral
def roman(number):
ret_val = ""
num = [1, 4, 5, 9, 10, 40, 50, 90,
100, 400, 500, 900, 1000]
sym = ["I", "IV", "V", "IX", "X", "XL",
"L", "XC", "C", "CD", "D", "CM", "M"]
i = 12
while number:
div = number // num[i]
number %= num[i]
while div:
ret_val += sym[i]
div -= 1
i -= 1
return ret_val |
var CG = (function(CG) {
let g_width, g_x, g_y, g_z, g_x0, g_y0;
class Tetraedro{
/**
* @param {WebGLRenderingContext} gl
* @param {Number[]} color
* @param {Number} width
* @param {Matrix4} initial_transform
* Constructor de tetraedro
*/
constructor(gl, color, width, initial_transform) {
g_width = (width || 1);
let anguloT = 2 * Math.PI/3;
g_x = width*2*Math.sqrt(2)/3;
g_y = 0;
g_z = -width/3;
g_x0 = g_x * Math.cos(anguloT) + g_y * Math.sin(anguloT);
g_y0 = -g_x * Math.sin(anguloT) + g_y * Math.cos(anguloT);
this.initial_transform = initial_transform || new CG.Matrix4();
this.positionbuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionbuffer);
let vertices = this.getVertices();
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
this.color = color;
// buffer de normales
this.normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer);
let normals = this.getNormals(vertices);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);
this.num_elements = vertices.length/3;
}
/**
* @param {WebGLRenderingContext} gl
* @param {GLint} positionAttributeLocation
* @param {WebGLUniformLocation} colorUniformLocation
* @param {WebGLUniformLocation} PVM_matrixLocation
* @param {Matrix4} projectionViewMatrix
* Función que dibuja el objeto geométrico usando el color asignado
*/
draw(gl, positionAttributeLocation, normalAttributeLocation, colorUniformLocation, PVM_matrixLocation, VM_matrixLocation, projectionMatrix, viewMatrix) {
// buffer de posiciones
gl.enableVertexAttribArray(positionAttributeLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionbuffer);
gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0);
// Buffer de normales
gl.enableVertexAttribArray(normalAttributeLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer);
gl.vertexAttribPointer(normalAttributeLocation, 3, gl.FLOAT, false, 0, 0);
// Color de la figura
gl.uniform4fv(colorUniformLocation, this.color);
// VM_MatrixLocation
let viewModelMatrix = CG.Matrix4.multiply(viewMatrix, this.initial_transform);
gl.uniformMatrix4fv(VM_matrixLocation, false, viewModelMatrix.toArray());
// PVM
let projectionViewModelMatrix = CG.Matrix4.multiply(projectionMatrix, viewModelMatrix);
gl.uniformMatrix4fv(PVM_matrixLocation, false, projectionViewModelMatrix.toArray());
// Dibujado
gl.drawArrays(gl.TRIANGLES, 0, this.num_elements);
}
/**
* @param {WebGLRenderingContext} gl
* @param {GLint} positionAttributeLocation
* @param {WebGLUniformLocation} colorUniformLocation
* @param {WebGLUniformLocation} PVM_matrixLocation
* @param {Matrix4} projectionViewMatrix
* Función que dibuja el objeto geométrico en modo wireframe
*/
drawWireframe(gl, positionAttributeLocation, colorUniformLocation, PVM_matrixLocation, projectionViewMatrix) {
let positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
let vertices = this.getVerticesW();
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
let indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
let faces = this.getFaces();
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(faces), gl.STATIC_DRAW);
let num_elementsL = faces.length;
gl.enableVertexAttribArray(positionAttributeLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0);
gl.uniform4fv(colorUniformLocation, [0,0,0,1]);
let projectionViewModelMatrix = CG.Matrix4.multiply(projectionViewMatrix, this.initial_transform);
gl.uniformMatrix4fv(PVM_matrixLocation, false, projectionViewModelMatrix.toArray());
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.drawElements(gl.LINE_STRIP, num_elementsL, gl.UNSIGNED_SHORT, 0);
}
/**
* Función que devuelve un arreglo con los vértices del tetraedro.
*/
getVerticesW() {
return [
0, 0, g_width, /*0*/
g_x0, g_y0, g_z, /*1*/
g_x0, -g_y0, g_z, /*2*/
g_x, g_y, g_z /*3*/
];
}
/**
* Función que devuelve el arreglo de vértices para ser usado por drawArrays
*/
getVertices() {
return [
0, 0, g_width, /*0*/ g_x0, g_y0, g_z, /*1*/ g_x, g_y, g_z /*3*/,
0, 0, g_width, /*0*/ g_x0, -g_y0, g_z, /*2*/ g_x0, g_y0, g_z, /*1*/
0, 0, g_width, /*0*/ g_x, g_y, g_z, /*3*/ g_x0, -g_y0, g_z, /*2*/
g_x0, g_y0, g_z, /*1*/ g_x0, -g_y0, g_z, /*2*/ g_x, g_y, g_z /*3*/
];
}
/**
* Función que devuelve las normales para el tetraedro
*/
getNormals(vertices) {
let normals = [];
let v1 = new CG.Vector3();
let v2 = new CG.Vector3();
let v3 = new CG.Vector3();
let n;
//Reconstrucción de vértices
for (let i = 0; i < vertices.length; i+=9) {
v1.set(vertices[i ], vertices[i+1], vertices[i+2]);
v2.set(vertices[i+3], vertices[i+4], vertices[i+5]);
v3.set(vertices[i+6], vertices[i+7], vertices[i+8]);
// Cálculo de la normal
n = CG.Vector3.cross(CG.Vector3.substract(v1, v2), CG.Vector3.substract(v2, v3)).normalize();
normals.push(
n.x, n.y, n.z,
n.x, n.y, n.z,
n.x, n.y, n.z
);
}
return normals;
}
/**
* Función que devuelve las caras de la figura
*/
getFaces() {
return [
3, 1, 0,
0, 1, 2,
2, 0, 3,
3, 2, 1
];
}
}
CG.Tetraedro = Tetraedro;
return CG;
})(CG || {}); |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { of, Subject, from } from 'rxjs';
import { IVol } from 'app/entities/vol/vol.model';
import { VolService } from 'app/entities/vol/service/vol.service';
import { IHotel } from 'app/entities/hotel/hotel.model';
import { HotelService } from 'app/entities/hotel/service/hotel.service';
import { IActivite } from 'app/entities/activite/activite.model';
import { ActiviteService } from 'app/entities/activite/service/activite.service';
import { IVoyageur } from 'app/entities/voyageur/voyageur.model';
import { VoyageurService } from 'app/entities/voyageur/service/voyageur.service';
import { IReservation } from '../reservation.model';
import { ReservationService } from '../service/reservation.service';
import { ReservationFormService } from './reservation-form.service';
import { ReservationUpdateComponent } from './reservation-update.component';
describe('Reservation Management Update Component', () => {
let comp: ReservationUpdateComponent;
let fixture: ComponentFixture<ReservationUpdateComponent>;
let activatedRoute: ActivatedRoute;
let reservationFormService: ReservationFormService;
let reservationService: ReservationService;
let volService: VolService;
let hotelService: HotelService;
let activiteService: ActiviteService;
let voyageurService: VoyageurService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([]), ReservationUpdateComponent],
providers: [
FormBuilder,
{
provide: ActivatedRoute,
useValue: {
params: from([{}]),
},
},
],
})
.overrideTemplate(ReservationUpdateComponent, '')
.compileComponents();
fixture = TestBed.createComponent(ReservationUpdateComponent);
activatedRoute = TestBed.inject(ActivatedRoute);
reservationFormService = TestBed.inject(ReservationFormService);
reservationService = TestBed.inject(ReservationService);
volService = TestBed.inject(VolService);
hotelService = TestBed.inject(HotelService);
activiteService = TestBed.inject(ActiviteService);
voyageurService = TestBed.inject(VoyageurService);
comp = fixture.componentInstance;
});
describe('ngOnInit', () => {
it('Should call Vol query and add missing value', () => {
const reservation: IReservation = { id: 456 };
const vols: IVol[] = [{ id: 22849 }];
reservation.vols = vols;
const volCollection: IVol[] = [{ id: 17106 }];
jest.spyOn(volService, 'query').mockReturnValue(of(new HttpResponse({ body: volCollection })));
const additionalVols = [...vols];
const expectedCollection: IVol[] = [...additionalVols, ...volCollection];
jest.spyOn(volService, 'addVolToCollectionIfMissing').mockReturnValue(expectedCollection);
activatedRoute.data = of({ reservation });
comp.ngOnInit();
expect(volService.query).toHaveBeenCalled();
expect(volService.addVolToCollectionIfMissing).toHaveBeenCalledWith(volCollection, ...additionalVols.map(expect.objectContaining));
expect(comp.volsSharedCollection).toEqual(expectedCollection);
});
it('Should call Hotel query and add missing value', () => {
const reservation: IReservation = { id: 456 };
const hotels: IHotel[] = [{ id: 4692 }];
reservation.hotels = hotels;
const hotelCollection: IHotel[] = [{ id: 17597 }];
jest.spyOn(hotelService, 'query').mockReturnValue(of(new HttpResponse({ body: hotelCollection })));
const additionalHotels = [...hotels];
const expectedCollection: IHotel[] = [...additionalHotels, ...hotelCollection];
jest.spyOn(hotelService, 'addHotelToCollectionIfMissing').mockReturnValue(expectedCollection);
activatedRoute.data = of({ reservation });
comp.ngOnInit();
expect(hotelService.query).toHaveBeenCalled();
expect(hotelService.addHotelToCollectionIfMissing).toHaveBeenCalledWith(
hotelCollection,
...additionalHotels.map(expect.objectContaining),
);
expect(comp.hotelsSharedCollection).toEqual(expectedCollection);
});
it('Should call Activite query and add missing value', () => {
const reservation: IReservation = { id: 456 };
const activites: IActivite[] = [{ id: 18204 }];
reservation.activites = activites;
const activiteCollection: IActivite[] = [{ id: 3143 }];
jest.spyOn(activiteService, 'query').mockReturnValue(of(new HttpResponse({ body: activiteCollection })));
const additionalActivites = [...activites];
const expectedCollection: IActivite[] = [...additionalActivites, ...activiteCollection];
jest.spyOn(activiteService, 'addActiviteToCollectionIfMissing').mockReturnValue(expectedCollection);
activatedRoute.data = of({ reservation });
comp.ngOnInit();
expect(activiteService.query).toHaveBeenCalled();
expect(activiteService.addActiviteToCollectionIfMissing).toHaveBeenCalledWith(
activiteCollection,
...additionalActivites.map(expect.objectContaining),
);
expect(comp.activitesSharedCollection).toEqual(expectedCollection);
});
it('Should call Voyageur query and add missing value', () => {
const reservation: IReservation = { id: 456 };
const voyageur: IVoyageur = { id: 25612 };
reservation.voyageur = voyageur;
const voyageurCollection: IVoyageur[] = [{ id: 4244 }];
jest.spyOn(voyageurService, 'query').mockReturnValue(of(new HttpResponse({ body: voyageurCollection })));
const additionalVoyageurs = [voyageur];
const expectedCollection: IVoyageur[] = [...additionalVoyageurs, ...voyageurCollection];
jest.spyOn(voyageurService, 'addVoyageurToCollectionIfMissing').mockReturnValue(expectedCollection);
activatedRoute.data = of({ reservation });
comp.ngOnInit();
expect(voyageurService.query).toHaveBeenCalled();
expect(voyageurService.addVoyageurToCollectionIfMissing).toHaveBeenCalledWith(
voyageurCollection,
...additionalVoyageurs.map(expect.objectContaining),
);
expect(comp.voyageursSharedCollection).toEqual(expectedCollection);
});
it('Should update editForm', () => {
const reservation: IReservation = { id: 456 };
const vols: IVol = { id: 10947 };
reservation.vols = [vols];
const hotels: IHotel = { id: 5679 };
reservation.hotels = [hotels];
const activites: IActivite = { id: 13150 };
reservation.activites = [activites];
const voyageur: IVoyageur = { id: 9098 };
reservation.voyageur = voyageur;
activatedRoute.data = of({ reservation });
comp.ngOnInit();
expect(comp.volsSharedCollection).toContain(vols);
expect(comp.hotelsSharedCollection).toContain(hotels);
expect(comp.activitesSharedCollection).toContain(activites);
expect(comp.voyageursSharedCollection).toContain(voyageur);
expect(comp.reservation).toEqual(reservation);
});
});
describe('save', () => {
it('Should call update service on save for existing entity', () => {
// GIVEN
const saveSubject = new Subject<HttpResponse<IReservation>>();
const reservation = { id: 123 };
jest.spyOn(reservationFormService, 'getReservation').mockReturnValue(reservation);
jest.spyOn(reservationService, 'update').mockReturnValue(saveSubject);
jest.spyOn(comp, 'previousState');
activatedRoute.data = of({ reservation });
comp.ngOnInit();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.next(new HttpResponse({ body: reservation }));
saveSubject.complete();
// THEN
expect(reservationFormService.getReservation).toHaveBeenCalled();
expect(comp.previousState).toHaveBeenCalled();
expect(reservationService.update).toHaveBeenCalledWith(expect.objectContaining(reservation));
expect(comp.isSaving).toEqual(false);
});
it('Should call create service on save for new entity', () => {
// GIVEN
const saveSubject = new Subject<HttpResponse<IReservation>>();
const reservation = { id: 123 };
jest.spyOn(reservationFormService, 'getReservation').mockReturnValue({ id: null });
jest.spyOn(reservationService, 'create').mockReturnValue(saveSubject);
jest.spyOn(comp, 'previousState');
activatedRoute.data = of({ reservation: null });
comp.ngOnInit();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.next(new HttpResponse({ body: reservation }));
saveSubject.complete();
// THEN
expect(reservationFormService.getReservation).toHaveBeenCalled();
expect(reservationService.create).toHaveBeenCalled();
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).toHaveBeenCalled();
});
it('Should set isSaving to false on error', () => {
// GIVEN
const saveSubject = new Subject<HttpResponse<IReservation>>();
const reservation = { id: 123 };
jest.spyOn(reservationService, 'update').mockReturnValue(saveSubject);
jest.spyOn(comp, 'previousState');
activatedRoute.data = of({ reservation });
comp.ngOnInit();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.error('This is an error!');
// THEN
expect(reservationService.update).toHaveBeenCalled();
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).not.toHaveBeenCalled();
});
});
describe('Compare relationships', () => {
describe('compareVol', () => {
it('Should forward to volService', () => {
const entity = { id: 123 };
const entity2 = { id: 456 };
jest.spyOn(volService, 'compareVol');
comp.compareVol(entity, entity2);
expect(volService.compareVol).toHaveBeenCalledWith(entity, entity2);
});
});
describe('compareHotel', () => {
it('Should forward to hotelService', () => {
const entity = { id: 123 };
const entity2 = { id: 456 };
jest.spyOn(hotelService, 'compareHotel');
comp.compareHotel(entity, entity2);
expect(hotelService.compareHotel).toHaveBeenCalledWith(entity, entity2);
});
});
describe('compareActivite', () => {
it('Should forward to activiteService', () => {
const entity = { id: 123 };
const entity2 = { id: 456 };
jest.spyOn(activiteService, 'compareActivite');
comp.compareActivite(entity, entity2);
expect(activiteService.compareActivite).toHaveBeenCalledWith(entity, entity2);
});
});
describe('compareVoyageur', () => {
it('Should forward to voyageurService', () => {
const entity = { id: 123 };
const entity2 = { id: 456 };
jest.spyOn(voyageurService, 'compareVoyageur');
comp.compareVoyageur(entity, entity2);
expect(voyageurService.compareVoyageur).toHaveBeenCalledWith(entity, entity2);
});
});
});
}); |
<!DOCTYPE html>
<html>
<head>
<title>PSY9219M - Research Methods and Skills</title>
<meta charset="utf-8">
<meta name="author" content="Dr Matt Craddock" />
<link href="libs/remark-css/default.css" rel="stylesheet" />
<link href="libs/remark-css/default-fonts.css" rel="stylesheet" />
<link rel="stylesheet" href="css\my-theme.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# PSY9219M - Research Methods and Skills
### Dr Matt Craddock
### 25/09/2018
---
# Who am I?
.pull-left[

]
.pull-right[
### Dr Matt Craddock
- Research background in cognitive neuroscience
- EEG, fMRI, non-invasive brain stimulation
- Programming in R, Matlab, Python
- Past experience with SPSS, SigmaPlot, Excel
|Sarah Swift Building Room 2226|
|------------------------------|
|mcraddock@lincoln.ac.uk |
]
---
# PSY9219M - Research Methods and Skills
--
.pull-left[

]
--
.pull-right[

]
---
# Course outline
.pull-left[
### Weeks 1-5
- Introduction to R
- Basic R programming
- Plotting with ggplot2
- Data import, selection and manipulation
- Describing and summarising your data
]
.pull-right[
### Weeks 5-6, 8-10
- Hypothesis testing and estimation
- *t*-tests and comparing two groups
- Correlation and linear regression
- One-way ANOVA
- Factorial ANOVA
]
### Weeks 11-13
- Qualitative methods
---
# Course outline
.pull-left[
### Weeks 1-5

]
.pull-right[
### Weeks 5-6, 8-10

]
---
# Course outline
.pull-left[
### Weeks 1-5

]
.pull-right[
### Weeks 5-10

]
---
class: inverse, center, middle
# Introduction to R and RStudio
---
background-image: url(https://www.r-project.org/Rlogo.png)
background-position: 80% 10%
# What is R?
.large[
R is a statistical, mathematical programming language
* Created in 1993
* Designed from the ground up to support many statistical tasks
* Covers all aspects of data analysis from import through to production of reports
* Free, open source
* Can be downloaded from the [R-project](https://r-project.org) website
* Continually evolving
* R has over 12,000 *packages* that add additional functions
]
---
class: inverse, center, middle
# But WHY?
---
# What can you do?
.pull-left[

]
.pull-right[
]
---
background-image: url(../images/01/Rcompanies.png)
background-size: contain
---
background-image: url(../images/01/spss_usage.png)
#Still not convinced?
---
# Scenario A
.large[
You've just started work in a psychology lab. You're asked to help analyse some old data. There is reaction time data from 50 participants. Each participant's data is stored in a separate text file.
- How do you combine the data from each participant together to be able to analyse the data?
- It turns out some of the participants only completed part of the experiment - which ones, and what should you do with their data?
- What steps should you take to select and perform appropriate statistical analysis?
]
---
# Scenario B
.large[
You've been asked to design, implement, and evaluate a new treatment regime across several psychiatric institutes. Several colleagues are skeptical that it can deliver the kind of improvements in outcomes indicated in a publication describing the method.
- How do you interpret the strength of the previously published evidence?
- How do you design a rigorous test of the treatment efficacy?
- How do you evaluate and report on the outcomes of your trial?
]
---
class: inverse, center, middle
# Getting started
---
background-image: url(../images/01/RStudio-logo.png)
background-size: 30%
background-position: 80% 5%
# What is RStudio?
.large[
- An **Integrated Development Environment (IDE)**
- An interface for R that makes your life much, much easier
- Makes many things explicit that you would otherwise have to guess
]

---
background-image: url(../images/01/rstudiocloud_page.png)
background-size: 60%
background-position: 50% 90%
# Getting started
.large[
1. Open up a web browser
2. Go to https://rstudio.cloud
3. Sign up! Use your REAL NAME, and your University of Lincoln email address.
]
---
background-image: url(../images/01/RStudioCloud.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/RStudioCloud_proj_circ.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/default_project.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/cloud-tools.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/cloud-appear.png)
background-size: contain
class: inverse
---
class: inverse, center, middle
# How it works!
---
background-image: url(../images/01/proj_console.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/proj_console_repl.png)
background-size: contain
class: inverse
---
# How to use R
* The R Console
* REPL: Read/Evaluate/Print/Loop
* Type stuff in, it tries to do it
When you see the **>** symbol -
```r
*>
```
... R is waiting for your input.
```r
> 5
[1] 5
```
---
# Warming up
Try using R like a calculator!
### Basic arithmetic operators
|Symbol |Operation |
|:------|:--------------|
|+ |addition |
|- |subtraction |
|* |multiplication |
|/ |division |
|^ |exponentiation |
|%% |modulo |
---
# Warming up
You can break up long maths expressions over multiple lines:
```r
2 + 4 + 5 +
5 + 6 + 7 + 8 +
10
```
```
## [1] 47
```
Note that when you do that, the ">" symbol changes to a "+"
```r
> 5 +
*+ 5
[1] 10
```
---
# Remember!
.large[**>** means R is waiting for input.]
```r
>
```
.large[**+** means R is waiting for you to finish your command.]
```r
+
```
Either finish your command, or press the **Esc** key to cancel it.
---
# Text input
R can also accept text strings as input.
```r
"hello world!"
[1] "hello world!"
```
You need to use quotation marks ("") to tell R that this is text:
```r
hello world!
```
```
## Error: <text>:1:7: unexpected symbol
## 1: hello world
## ^
```
Otherwise, you'll receive an error like the one above.
---
# Why is there an error?
In R, you can assign values to an **object** for subsequent use. **Objects** have names that are written as text.
The assignment operator is the two-character symbol:
```r
*<-
```
You assign values to objects by putting the **<-** sign between the name of the object and the value you want to give it:
```r
example <- 5
example
```
```
## [1] 5
```
Note that R does not immediately provide output when you assign the output to an object.
---
# The assignment operator
.large[Think of **<-** as meaning "is now". i.e.
```r
example <- 5
```
can be read as
```r
The object "example" is now 5
```
]
---
# Working with objects
Once an object is assigned, the name that you gave it *stands in* for the *value* that you assigned to it, and can be used as if it were that value:
```r
example
```
```
## [1] 5
```
```r
example + 10
```
```
## [1] 15
```
```r
example + 13 - 1 * 2 %% 4
```
```
## [1] 16
```
---
background-image: url(../images/01/cloud_environ.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/cloud_environ2.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/cloud-history.png)
background-size: contain
class: inverse
---
class: inverse, center, middle
# Try it out!
---
# Try a few things out!
1. Assign some values to objects using the assignment operator (**<-**)
2. Try using arithmetic operations (e.g. *, /, %%) on those objects
3. Try using arithmetic operations to combine multiple numerical objects
4. Try using arithmetic operations on text
---
# Combining multiple things
Sometimes you want to allocate more than one value to an object.
You can use the **c()** function to do this.
```r
c(8, 5, 10)
```
```
## [1] 8 5 10
```
```r
example <- c(8, 5, 10)
example
```
```
## [1] 8 5 10
```
```r
c("hello", "how", "are", "you")
```
```
## [1] "hello" "how" "are" "you"
```
## IMPORTANT: BRACKETS () AFTER A WORD MEAN THAT THIS IS A **FUNCTION**
---
# Vectors
The function **c()** is creating **vectors**.
Vectors are simply a one-dimensional collection of things that all have the same *type* (we will cover data types next week!).
Note that mixing, for example, text and numbers, will yield a *character* vector.
```r
c(5, "five", 2)
```
```
## [1] "5" "five" "2"
```
---
# Functions
Functions are commands that operate on **objects**.
For example, to calculate the *mean* of several numbers, you can use the function **mean()**. The output of functions can also be assigned to **objects** using **<-**.
```r
mean(c(8, 5, 10))
```
```
## [1] 7.666667
```
```r
example <- c(8, 5, 10)
mean(example)
```
```
## [1] 7.666667
```
```r
example_mean <- mean(example)
example_mean
```
```
## [1] 7.666667
```
---
# Try it out!
1. Use **c()** to create a vector of numbers.
2. Use **c()** to create a vector of strings.
3. Calculate the **mean()** of a vector of numbers.
4. Try guessing some other simple statistics (e.g. other types of *average*) that you can use.
---
background-image: url(../images/01/cloud-help.png)
background-size: 40%
background-position: 50% 75%
# Getting help
If you don't know how to use a function, R has built-in help!
There are several ways you can access it:
```r
help("mean")
?mean
??mean
```
---
# Packages
Packages are the key to R's versatility. Over 12000 are currently available from the **Comprehensive R Archive Network** - [CRAN](https::https://cran.r-project.org/). The **install.packages()** function can be used to install packages.
Let's install the "cowsay" package. **cowsay** is an extraordinarily useful package, as you'll see.
One way to install the package is using the console:
```r
install.packages("cowsay")
```
Once it's installed, use the **library()** function to load the package!
```r
library(cowsay)
```
But **another** way to install is using the GUI!
---
background-image: url(../images/01/cloud-packages.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/cloud-cowsay.png)
background-size: contain
class: inverse
---
background-image: url(../images/01/cloud-help.png)
background-position: 90% 85%
background-size: 40%
# Try out the **cowsay** package
**cowsay** adds a function called **say()**. Load the function in as follows, and look at the help for **say()**.
```r
library(cowsay)
?say()
```
.left-pull[
Remember that help appears in the bottom right window!
Look at **Usage** and **Arguments**
**Usage** is how to use the function.
**Arguments** are what the functions expect and understand.
]
---
```r
say(what = "Feed me, human.", by = "cat")
```
```
## Colors cannot be applied in this environment :( Try using a terminal or RStudio.
```
```
##
## --------------
## Feed me, human.
## --------------
## \
## \
## \
## |\___/|
## ==) ^Y^ (==
## \ ^ /
## )=*=(
## / \
## | |
## /| | | |\
## \| | |_|/\
## jgs //_// ___/
## \_)
##
```
---
# Try out the say() function
1. Try a few different animals by changing the **by** argument
2. Change what the animals say by changing the **what** argument.
3. Assign the output to an object using the **<-** operator.
4. Print out the value that you assigned to the object.
---
# Additional resources
.pull-left[

]
.pull-right[

]
There are copies of both these books in the library.
R for Data Science is available freely online at http://r4ds.had.co.nz/
---
background-image: url(../images/01/Datacamp_.png)
background-size: contain
class: inverse
---
# DataCamp
DataCamp provides a huge number of practical exercises across many different languages, not least of which is R.
# Get signed up for DataCamp!
.large[
# [https://tinyurl.com/DatacampSignup](https://tinyurl.com/DatacampSignup)
]
---
# Homework!
1. If you didn't get properly signed up with RStudio.cloud today, do it!
2. Get signed up with DataCamp using the link provided
3. Read through Chapter 1 of R for Data Science
4. Try out some of the introductory exercises
---
class: title-slide-final, middle, inverse
background-image: url('images/University of Lincoln_logo_General White Landscape.png')
background-size: 500px
background-position: 50% 10%
---
# Scenario C
.large[
You've collected data from 100 participants using an online questionnaire with 20 questions. Some responses are free text (i.e. they can write whatever they like). Some responses use a Likert scale. For those responses, you also have a set of standard values that represent population averages.
- What kind of statistical analyses are appropriate for these data?
- How do you get the data into a format you can analyse it?
- How do you combine it with and compare it against the data from the broader population?
]
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script src="js/macros.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false,
"ratio": "16:9"
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();</script>
<script>
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html> |
<script setup>
import { ref, onMounted } from 'vue'
const DataValue = ref([]);
const isLoad = ref(true);
const LoadImg = (imgUrl) => {
const imgArr = [...imgUrl];
let i = 0;
imgArr.forEach(src => {
const img = new Image();
img.src = src;
img.onload = () => {
i += 1;
if (i === imgArr.length) {
isLoad.value = false;
}
}
})
}
onMounted(() => {
fetch('https://610cd85966dd8f0017b76eb5.mockapi.io/api/card')
.then(res => res.json()).then(res => {
DataValue.value = res;
const imgArr = res.map(item => [item.avatar, item.content]);
LoadImg([].concat(...imgArr));
});
})
</script>
<template>
<div :class="['card', {load: isLoad}]" v-for="item in DataValue" :key="item.id">
<header>
<div class="photo">
<img :src="item.avatar">
</div>
<p>{{ isLoad ? "" : item.username }}</p>
</header>
<p>{{ isLoad ? "" : item.text }}</p>
<main>
<img :src="item.content">
</main>
</div>
</template>
<style lang="scss" scoped>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
img {
display: block;
}
html,
body {
width: 100%;
height: 100%;
background-color: #e1e1e1;
display: flex;
justify-content: center;
align-items: center;
}
#app {
width: 100%;
height: 100%;
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
padding: 35px;
}
.card {
width: 300px;
height: auto;
border-radius: 10px;
overflow: hidden;
background-color: #fff;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2);
margin-bottom: 50px;
>p {
font-size: 14px;
padding: 0 10px;
margin-bottom: 10px;
}
header {
width: 100%;
display: flex;
justify-content: flex-start;
align-items: center;
padding: 10px;
>div {
margin-right: 10px;
>img {
border-radius: 50%;
}
}
>p {
font-size: 13px;
}
}
img {
opacity: 1;
transition: opacity .3s;
}
}
.load {
width: 300px;
height: 380px;
border-radius: 10px;
overflow: hidden;
background-color: #fff;
>header {
width: 100%;
display: flex;
justify-content: flex-start;
align-items: center;
padding: 10px;
>div {
width: 30px;
height: 30px;
border-radius: 50px;
margin-right: 10px;
background-color: #ededed;
>img {
border-radius: 50%;
}
}
>p {
font-size: 13px;
display: block;
width: 40%;
height: 18px;
background-color: #ededed;
}
}
>p {
font-size: 14px;
margin: 0 10px 10px 10px;
display: block;
width: 70%;
height: 18px;
background-color: #ededed;
}
>main {
width: 100%;
height: 300px;
background-color: #ededed;
}
img {
opacity: 0;
}
}
@keyframes loading {
to {
background-position-x: -20%;
}
}
.load {
.photo,
p,
main {
background: linear-gradient(100deg,
rgba(256, 256, 256, 0) 30%,
rgba(256, 256, 256, 0.5) 50%,
rgba(256, 256, 256, 0) 30%) #ededed;
background-size: 200% 100%;
background-position-x: 180%;
animation: 2s loading ease-in-out infinite;
}
}
</style> |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\SharedCatalog\Test\Unit\Model;
use Magento\CatalogPermissions\App\ConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
/**
* Unit test for Magento\SharedCatalog\Model\CategoryPermissions class.
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CategoryPermissionsTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\CatalogPermissions\App\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $configResource;
/**
* @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $storeManager;
/**
* @var \Magento\SharedCatalog\Model\CategoryPermissions
*/
private $model;
/**
* @var \Magento\SharedCatalog\Model\CategoryPermissionsInvalidator|\PHPUnit_Framework_MockObject_MockObject
*/
private $invalidatorMock;
/**
* @inheritdoc
*/
protected function setUp()
{
$this->configResource = $this->getMockBuilder(
\Magento\Framework\App\Config\ConfigResource\ConfigInterface::class
)
->disableOriginalConstructor()
->getMock();
$this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class)
->disableOriginalConstructor()
->getMockForAbstractClass();
$this->invalidatorMock = $this->createMock(
\Magento\SharedCatalog\Model\CategoryPermissionsInvalidator::class
);
$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$this->model = $objectManager->getObject(
\Magento\SharedCatalog\Model\CategoryPermissions::class,
[
'configResource' => $this->configResource,
'storeManager' => $this->storeManager,
'invalidator' => $this->invalidatorMock
]
);
}
/**
* Test enable method.
*
* @return void
*/
public function testEnable()
{
$this->configResource->expects($this->exactly(4))
->method('saveConfig')
->withConsecutive(
[
ConfigInterface::XML_PATH_ENABLED,
1,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
],
[
ConfigInterface::XML_PATH_GRANT_CATALOG_CATEGORY_VIEW,
ConfigInterface::GRANT_ALL,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
],
[
ConfigInterface::XML_PATH_GRANT_CATALOG_PRODUCT_PRICE,
ConfigInterface::GRANT_ALL,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
],
[
ConfigInterface::XML_PATH_GRANT_CHECKOUT_ITEMS,
ConfigInterface::GRANT_ALL,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
]
)
->willReturnSelf();
$website = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class)
->disableOriginalConstructor()
->getMockForAbstractClass();
$website->expects($this->atLeastOnce())
->method('getId')
->willReturn(1);
$this->storeManager->expects($this->atLeastOnce())
->method('getWebsites')
->willReturn([$website]);
$this->invalidatorMock->expects($this->once())->method('invalidate');
$this->model->enable();
}
} |
#include <iostream>
using namespace std;
class Base
{
protected:
int baseData;
public:
Base(int baseData) : baseData(baseData) { }
Base& operator= (const Base& rhs)
{
cout << "Base& operator= ()" << endl;
baseData = rhs.baseData;
return *this;
}
void Show() { cout << "Base: " << baseData << endl; }
};
class Derived : public Base
{
protected:
int derivedData;
public:
Derived(int baseData, int derivedData) : Base(baseData), derivedData(derivedData) { }
// 자식에서 대입 연산자를 정의하면,
// 기본 대입 연산자와 달리
//
// 부모의 대입 연산자를 자동으로 호출하지 않는다.
Derived& operator= (const Derived& rhs)
{
cout << "Derived& operator= ()" << endl;
derivedData = rhs.derivedData;
return *this;
}
void Show() { cout << "Base: " << baseData << ", Derived: " << derivedData << endl; }
};
int main(int argc, char* argv[])
{
Derived dest(0, 0), src(1, 2);
dest = src;
dest.Show();
return 0;
} |
use crate::cartridge;
use crate::cartridge::mbc1::MBC1;
use crate::cartridge::Interface;
#[test]
fn new() {
struct TestCase {
init_fn: fn() -> Vec<u8>,
}
let test_cases: Vec<TestCase> = vec![
TestCase {
init_fn: || -> Vec<u8> {
let mut cart_data: Vec<u8> = vec![0x00; 0x8000];
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1;
return cart_data;
},
},
TestCase {
init_fn: || -> Vec<u8> {
let mut cart_data: Vec<u8> = vec![0x00; 0x8000];
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
return cart_data;
},
},
TestCase {
init_fn: || -> Vec<u8> {
let mut cart_data: Vec<u8> = vec![0x00; 0x8000];
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM_BATTERY;
return cart_data;
},
},
];
for tc in test_cases {
let mbc1 = MBC1::new(vec![]);
let implementation = cartridge::new((tc.init_fn)());
match implementation.as_any().downcast_ref::<MBC1>() {
Some(mbc1) => {}
None => panic!("returned cartridge implementation was not a MBC1!"),
};
}
}
#[test]
fn read() {
struct TestCase {
description: String,
run_fn: fn(),
}
let test_cases: Vec<TestCase> = vec![
TestCase {
description: String::from("read from bank 0 w/ no bank switching"),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x4000];
cart_data[0x0] = 0x7F;
let mbc1 = MBC1::new(cart_data);
let read_result = mbc1.read(0x0);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read from bank 0 w/ bank switching but ram bank register is 0",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x4000];
cart_data[0x0] = 0x7F;
cart_data[cartridge::header::ROM_SIZE_ADDR] =
cartridge::rom_size_id::ONE_MEGABYTE;
let mut mbc1 = MBC1::new(cart_data);
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
let read_result = mbc1.read(0x0);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read from bank 0x20 w/ bank switching when ram bank register is 1",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x21 * 0x4000];
cart_data[0x20 * 0x4000] = 0x7F;
cart_data[cartridge::header::ROM_SIZE_ADDR] =
cartridge::rom_size_id::ONE_MEGABYTE;
let mut mbc1 = MBC1::new(cart_data);
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
mbc1.ram_bank_select_register = 0x1;
let read_result = mbc1.read(0x0);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read from bank 0x40 w/ bank switching when ram bank register is 2",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x41 * 0x4000];
cart_data[0x40 * 0x4000] = 0x7F;
cart_data[cartridge::header::ROM_SIZE_ADDR] =
cartridge::rom_size_id::ONE_MEGABYTE;
let mut mbc1 = MBC1::new(cart_data);
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
mbc1.ram_bank_select_register = 0x2;
let read_result = mbc1.read(0x0);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read from bank 0x60 w/ bank switching when ram bank register is 3",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x61 * 0x4000];
cart_data[0x60 * 0x4000] = 0x7F;
cart_data[cartridge::header::ROM_SIZE_ADDR] =
cartridge::rom_size_id::ONE_MEGABYTE;
let mut mbc1 = MBC1::new(cart_data);
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
mbc1.ram_bank_select_register = 0x3;
let read_result = mbc1.read(0x0);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read from bank 0x00 w/ bank switching when ram bank register is greater than 4 (bit masking)",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[0x0000] = 0x7F;
cart_data[cartridge::header::ROM_SIZE_ADDR] =
cartridge::rom_size_id::ONE_MEGABYTE;
let mut mbc1 = MBC1::new(cart_data);
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
mbc1.ram_bank_select_register = 0x4;
let read_result = mbc1.read(0x0);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read rom region 0x4000 - 0x8000 w/ rom select register 0 -> should still access bank 1, not bank 0",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x2 * 0x4000];
cart_data[0x4000] = 0x7F;
let mut mbc1 = MBC1::new(cart_data);
mbc1.rom_bank_select_register = 0x0;
let read_result = mbc1.read(0x4000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read rom region 0x4000 - 0x8000 w/ rom select register 1 -> should select data in bank 1",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x2 * 0x4000];
cart_data[0x4000] = 0x7F;
let mut mbc1 = MBC1::new(cart_data);
mbc1.rom_bank_select_register = 0x1;
let read_result = mbc1.read(0x4000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read rom region 0x4000 - 0x8000 w/ rom select register 3 -> should select data in bank 3",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x4 * 0x4000];
cart_data[0x4000 * 0x3] = 0x7F;
let mut mbc1 = MBC1::new(cart_data);
mbc1.rom_bank_select_register = 0x3;
let read_result = mbc1.read(0x4000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read rom region 0x4000 - 0x8000 w/ rom select register 3 + ram banking mode -> should still only select bank 3",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x4 * 0x4000];
cart_data[0x4000 * 0x3] = 0x7F;
let mut mbc1 = MBC1::new(cart_data);
mbc1.rom_bank_select_register = 0x3;
mbc1.ram_bank_select_register = 0x1;
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
let read_result = mbc1.read(0x4000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read rom region 0x4000 - 0x8000 w/ rom select register 3 + ram banking mode + 1MB cart -> should select bank 0x23",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x24 * 0x4000];
cart_data[cartridge::header::ROM_SIZE_ADDR] =
cartridge::rom_size_id::ONE_MEGABYTE;
cart_data[0x4000 * 0x23] = 0x7F;
let mut mbc1 = MBC1::new(cart_data);
mbc1.rom_bank_select_register = 0x3;
mbc1.ram_bank_select_register = 0x1;
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
let read_result = mbc1.read(0x4000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read rom region 0x4000 - 0x8000 w/ rom select register 0 + ram banking mode + ram select register 3 + 1MB cart -> should select bank 0x61",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x62 * 0x4000];
cart_data[cartridge::header::ROM_SIZE_ADDR] =
cartridge::rom_size_id::ONE_MEGABYTE;
cart_data[0x4000 * 0x61] = 0x7F;
let mut mbc1 = MBC1::new(cart_data);
mbc1.rom_bank_select_register = 0x0;
mbc1.ram_bank_select_register = 0x3;
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
let read_result = mbc1.read(0x4000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read ram region 0xA000-0xBFFF -> cart has no ram -> should return 0xFF",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] =
cartridge::ram_size_id::NO_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_bank_select_register = 0x0;
mbc1.ram_banks[0][0] = 0x7F;
let read_result = mbc1.read(0xA000);
assert_eq!(
read_result.unwrap(),
0xFF,
)
},
},
TestCase {
description: String::from(
"read ram region 0xA000-0xBFFF + cart type has ram + but type is not MBC1 w/ RAM -> should return 0xFF",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] =
cartridge::ram_size_id::ONE_BANK;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_bank_select_register = 0x0;
mbc1.ram_banks[0][0] = 0x7F;
let read_result = mbc1.read(0xA000);
assert_eq!(
read_result.unwrap(),
0xFF,
)
},
},
TestCase {
description: String::from(
"read ram region 0xA000-0xBFFF + ram select register is 0 + cart type has ram + cart is MBC1_RAM + ram is disabled -> should return 0xFF",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] =
cartridge::ram_size_id::ONE_BANK;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_bank_select_register = 0x0;
mbc1.ram_banks[0][0] = 0x7F;
let read_result = mbc1.read(0xA000);
assert_eq!(
read_result.unwrap(),
0xFF,
)
},
},
TestCase {
description: String::from(
"read ram region 0xA000-0xBFFF + ram select register is 0 + cart type has ram + cart is MBC1_RAM + ram is enabled -> should return value in ram bank 0",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] =
cartridge::ram_size_id::ONE_BANK;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_bank_select_register = 0x0;
mbc1.ram_banks[0][0] = 0x7F;
mbc1.ram_enabled = true;
let read_result = mbc1.read(0xA000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read ram region 0xA000-0xBFFF + ram select register is 1 + cart type has ram + cart is MBC1_RAM + ram is enabled + cart has more than 4 banks -> should return value in ram bank 1",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] =
cartridge::ram_size_id::FOUR_BANKS;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_bank_select_register = 0x1;
mbc1.ram_banks[1][0] = 0x7F;
mbc1.ram_enabled = true;
let read_result = mbc1.read(0xA000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read ram region 0xA000-0xBFFF + ram select register is 4 + cart type has ram + cart is MBC1_RAM + ram is enabled + cart has more than 4 banks -> should return value in ram bank 0 (because of mask)",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] =
cartridge::ram_size_id::FOUR_BANKS;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_bank_select_register = 0x4;
mbc1.ram_banks[0][0] = 0x7F;
mbc1.ram_enabled = true;
let read_result = mbc1.read(0xA000);
assert_eq!(
read_result.unwrap(),
0x7F,
)
},
},
TestCase {
description: String::from(
"read from undefined region",
),
run_fn: || {
let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
let mbc1 = MBC1::new(cart_data);
let read_result = mbc1.read(0x8000);
assert!(read_result.is_none())
},
},
];
for tc in test_cases {
println!("{}", tc.description);
(tc.run_fn)();
}
}
#[test]
fn write() {
struct TestCase {
description: String,
run_fn: fn(),
}
let test_cases: Vec<TestCase> = vec![
TestCase {
description: String::from(
"writing to 0x0000 - 0x2000 -> non 0x-A value in the lower nibble -> disables ram",
),
run_fn: || {
let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_enabled = true;
mbc1.write(0x0000, 0x13);
assert!(!mbc1.ram_enabled);
},
},
TestCase {
description: String::from(
"writing to 0x0000 - 0x2000 -> 0x5A value (lower nibble == 0xA) -> enables ram",
),
run_fn: || {
let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x0000, 0x5A);
assert!(mbc1.ram_enabled);
},
},
TestCase {
description: String::from(
"writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 1 bank -> should set register to 1",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x00;
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x2000, 0xFF);
assert_eq!(mbc1.rom_bank_select_register, 0x01);
},
},
TestCase {
description: String::from(
"writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 4 banks -> should set register to 3",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x01;
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x2000, 0xFF);
assert_eq!(mbc1.rom_bank_select_register, 0x03);
},
},
TestCase {
description: String::from(
"writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 8 banks -> should set register to 7",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x02;
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x2000, 0xFF);
assert_eq!(mbc1.rom_bank_select_register, 0x07);
},
},
TestCase {
description: String::from(
"writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 16 banks -> should set register to 15",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x03;
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x2000, 0xFF);
assert_eq!(mbc1.rom_bank_select_register, 0x0F);
},
},
TestCase {
description: String::from(
"writing to 0x2000 - 0x4000 -> value is 0xFF -> cart only has 32 banks -> should set register to 31",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
cart_data[cartridge::header::ROM_SIZE_ADDR] = 0x04;
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x2000, 0xFF);
assert_eq!(mbc1.rom_bank_select_register, 0x1F);
},
},
TestCase {
description: String::from(
"writing to 0x4000 - 0x6000 -> value is 0x1 -> should set ram select register to 1",
),
run_fn: || {
let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x4000, 0x1);
assert_eq!(mbc1.ram_bank_select_register, 0x1);
},
},
TestCase {
description: String::from(
"writing to 0x4000 - 0x6000 -> value is 0xFF -> should set ram select register to 3",
),
run_fn: || {
let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x4000, 0xFF);
assert_eq!(mbc1.ram_bank_select_register, 0x3);
},
},
TestCase {
description: String::from(
"writing to 0x6000 - 0x8000 -> value is 0x1 -> should set banking mode to ram banking mode",
),
run_fn: || {
let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0x6000, 0x1);
assert_eq!(mbc1.banking_mode, MBC1::RAM_BANKING_MODE);
},
},
TestCase {
description: String::from(
"writing to 0x6000 - 0x8000 -> value is 0x10 -> should set banking mode to simple banking mode",
),
run_fn: || {
let cart_data: Vec<u8> = vec![0x0; 0x1 * 0x4000];
let mut mbc1 = MBC1::new(cart_data);
mbc1.banking_mode = MBC1::RAM_BANKING_MODE;
mbc1.write(0x6000, 0x10);
assert_eq!(mbc1.banking_mode, MBC1::SIMPLE_BANKING_MODE);
},
},
TestCase {
description: String::from(
"writing to 0xA000 - 0xC000 (ram) + ram enabled + cart does not support ram -> should do nothing",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x00; 0x4000];
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1;
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0xB000, 0x10);
assert_eq!(mbc1.ram_banks[0][0x1000], 0x00);
},
},
TestCase {
description: String::from(
"writing to 0xA000 - 0xC000 (ram) + ram disabled + cart has ram -> should do nothing",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x00; 0x4000];
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.write(0xB000, 0x10);
assert_eq!(mbc1.ram_banks[0][0x1000], 0x00);
},
},
TestCase {
description: String::from(
"writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 0",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x00; 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::ONE_BANK;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_enabled = true;
mbc1.write(0xB000, 0x10);
assert_eq!(mbc1.ram_banks[0][0x1000], 0x10);
},
},
TestCase {
description: String::from(
"writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 1",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x00; 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_enabled = true;
mbc1.ram_bank_select_register = 0x01;
mbc1.write(0xB000, 0x10);
assert_eq!(mbc1.ram_banks[1][0x1000], 0x10);
},
},
TestCase {
description: String::from(
"writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 2",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x00; 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_enabled = true;
mbc1.ram_bank_select_register = 0x02;
mbc1.write(0xB000, 0x10);
assert_eq!(mbc1.ram_banks[2][0x1000], 0x10);
},
},
TestCase {
description: String::from(
"writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 3",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x00; 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_enabled = true;
mbc1.ram_bank_select_register = 0x03;
mbc1.write(0xB000, 0x10);
assert_eq!(mbc1.ram_banks[3][0x1000], 0x10);
},
},
TestCase {
description: String::from(
"writing to 0xA000 - 0xC000 (ram) + ram enabled + cart has ram -> should write to ram bank 0",
),
run_fn: || {
let mut cart_data: Vec<u8> = vec![0x00; 0x4000];
cart_data[cartridge::header::RAM_SIZE_ADDR] = cartridge::ram_size_id::FOUR_BANKS;
cart_data[cartridge::header::TYPE_ADDR] = cartridge::mbc_id::MBC1_RAM;
let mut mbc1 = MBC1::new(cart_data);
mbc1.ram_enabled = true;
mbc1.ram_bank_select_register = 0x04;
mbc1.write(0xB000, 0x10);
assert_eq!(mbc1.ram_banks[0][0x1000], 0x10);
},
},
];
for tc in test_cases {
println!("{}", tc.description);
(tc.run_fn)();
}
} |
/*
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Installation : #
# NodeMCU ESP8266/ESP12E RFID MFRC522 / RC522 #
# D2 <----------> SDA/SS #
# D5 <----------> SCK #
# D7 <----------> MOSI #
# D6 <----------> MISO #
# GND <----------> GND #
# D1 <----------> RST #
# 3V/3V3 <----------> 3.3V #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 4 //--> SDA / SS is connected to pinout D2
#define RST_PIN 5 //--> RST is connected to pinout D1
#define ON_Board_LED 2 //--> Defining an On Board LED, used for indicators when the process of connecting to a wifi router
#define Buzzer 16 // D0 pin for the buzzer
MFRC522 mfrc522(SS_PIN, RST_PIN); //--> Create MFRC522 instance.
int readsuccess;
byte readcard[4];
char str[32] = "";
String StrUID;
void setup() {
Serial.begin(115200); //--> Initialize serial communications with the PC
SPI.begin(); //--> Init SPI bus
mfrc522.PCD_Init(); //--> Init MFRC522 card
delay(500);
pinMode(ON_Board_LED, OUTPUT);
pinMode(Buzzer, OUTPUT);
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board
digitalWrite(Buzzer, LOW);
Serial.println("");
Serial.println("Please tag a card or keychain to see the UID !");
Serial.println("");
}
void loop() {
readsuccess = getid();
if (readsuccess) {
digitalWrite(ON_Board_LED, LOW);
digitalWrite(Buzzer, HIGH);
String UIDresultSend = StrUID;
Serial.println(UIDresultSend);
delay(1000);
digitalWrite(ON_Board_LED, HIGH);
digitalWrite(Buzzer, LOW);
}
}
//----------------Procedure for reading and obtaining a UID from a card or keychain--------------//
int getid() {
if (!mfrc522.PICC_IsNewCardPresent()) {
return 0;
}
if (!mfrc522.PICC_ReadCardSerial()) {
return 0;
}
Serial.print("THE UID OF THE SCANNED CARD IS : ");
for (int i = 0; i < 4; i++) {
readcard[i] = mfrc522.uid.uidByte[i]; //storing the UID of the tag in readcard
array_to_string(readcard, 4, str);
StrUID = str;
}
mfrc522.PICC_HaltA();
return 1;
}
//----------------------------Procedure to change the result of reading an array UID into a string-----------------------------//
void array_to_string(byte array[], unsigned int len, char buffer[]) {
for (unsigned int i = 0; i < len; i++)
{
byte nib1 = (array[i] >> 4) & 0x0F;
byte nib2 = (array[i] >> 0) & 0x0F;
buffer[i * 2 + 0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA;
buffer[i * 2 + 1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA;
}
buffer[len * 2] = '\0';
} |
import {Action} from '@ngrx/store';
import {Visitor} from '../models/visitor.model';
import {VisitorForm} from '../models/visitor-form.model';
export const FETCH_VISITORS_SUCCESS = '[Visitor] Fetch Visitors Success';
export const FETCH_VISITORS_START = '[Visitor] Fetch Visitors Start';
export const FETCH_VISITOR_START = '[Visitor] Fetch Visitor Start';
export const CLEAR_SELECTED_VISITOR = '[Visitor] Clear Selected Visitor';
export const FETCH_VISITOR_SUCCESS = '[Visitor] Fetch Visitor Success';
export const UPDATE_VISITOR_START = '[Visitor] Update Visitor Start';
export const UPDATE_VISITOR_SUCCESS = '[Visitor] Update Visitor Success';
export const DELETE_VISITOR_SUCCESS = '[Visitor] Delete Visitor Success';
export const DELETE_VISITOR_START = '[Visitor] Delete Visitor Start';
export const CREATE_VISITOR_SUCCESS = '[Visitor] Create Visitor Success';
export const CREATE_VISITOR_START = '[Visitor] Create Visitor Start';
export class FetchVisitorsSuccess implements Action {
readonly type = FETCH_VISITORS_SUCCESS;
constructor(public payload: Visitor[]) {}
}
export class FetchVisitorsStart implements Action {
readonly type = FETCH_VISITORS_START;
}
export class ClearSelectedVisitor implements Action {
readonly type = CLEAR_SELECTED_VISITOR;
}
export class DeleteVisitorSuccess implements Action {
readonly type = DELETE_VISITOR_SUCCESS;
constructor(public payload: Visitor['visitorId']) {}
}
export class DeleteVisitorStart implements Action {
readonly type = DELETE_VISITOR_START;
constructor(public payload: Visitor) {}
}
export class CreateVisitorSuccess implements Action {
readonly type = CREATE_VISITOR_SUCCESS;
constructor(public payload: Visitor) {}
}
export class CreateVisitorStart implements Action {
readonly type = CREATE_VISITOR_START;
constructor(public payload: VisitorForm) {}
}
export class FetchVisitorSuccess implements Action {
readonly type = FETCH_VISITOR_SUCCESS;
constructor(public payload: Visitor) {}
}
export class FetchVisitorStart implements Action {
readonly type = FETCH_VISITOR_START;
constructor(public payload: Visitor['visitorId']) {}
}
export class UpdateVisitorStart implements Action {
readonly type = UPDATE_VISITOR_START;
constructor(public payload: VisitorForm) {}
}
export class UpdateVisitorSuccess implements Action {
readonly type = UPDATE_VISITOR_SUCCESS;
constructor(public payload: Visitor) {}
}
export type VisitorActions =
| ClearSelectedVisitor
| CreateVisitorSuccess
| DeleteVisitorSuccess
| FetchVisitorsSuccess
| FetchVisitorSuccess
| UpdateVisitorSuccess; |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('group_user', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('group_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
$table->unique(['user_id', 'group_id']); // Ensures a user cannot join the same group multiple times
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('group_user');
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.