text
stringlengths 184
4.48M
|
---|
package dev.shog.chad.framework.handle.xp
import dev.shog.chad.framework.obj.Player
import java.util.concurrent.ConcurrentHashMap
/**
* Handles ranks
*
* @author sho
*/
object RankHandler {
/**
* The different ranks in Chad, with XP being the amount of XP to receive that rank
*/
enum class Rank(val xp: Long, val id: Int) {
NONE(0, 0), ONE(50, 1), TWO(400, 2), THREE(1000, 3), FOUR(2000, 4), FIVE(3000, 5), SIX(4500, 6), SEVEN(6000, 7), EIGHT(8000, 8), NINE(10000, 9), TEN(15000, 10), ELEVEN(20000, 11), TWELVE(30000, 12), THIRTEEN(45000, 13), FOURTEEN(70000, 14), FIFTEEN(100000, 15)
}
/**
* The different ranks with their IDS
*/
private val ranks = object : ConcurrentHashMap<Int, Rank>() {
init {
for (rank in Rank.values()) {
put(rank.id, rank)
}
}
}
/**
* Gets a rank from the hashmap through an ID
*/
private fun getRankByID(id: Int): Rank? = ranks[id]
/**
* If the user can rank up
*/
fun rankUp(player: Player): Boolean {
val rank = getUserRank(player)
val updated = getUserRank(player, refresh = true)
return if (updated != rank) {
player.setObject(Player.DataType.RANK, updated.id)
true
} else false
}
/**
* Calculates a user's rank through their XP levels
*/
private fun calculateUserRank(xp: Long): Rank {
var userRank: Rank = RankHandler.Rank.NONE
for (rank in Rank.values()) if (xp >= rank.xp) userRank = rank
return userRank
}
/**
* The amount of XP til the user can rank up
*/
fun toNextRank(player: Player): Long {
val xp = XPHandler.getUserXP(player)
val aboveRank = getUpperRank(getUserRank(player, refresh = true)) ?: return 0
return aboveRank.xp - xp
}
/**
* The amount of XP the user is above their previous rank
*/
fun aboveRank(player: Player): Long {
val xp = XPHandler.getUserXP(player)
val lowerRank = getLowerRank(getUserRank(player, refresh = true)) ?: return 0
return xp - lowerRank.xp
}
/**
* Gets the rank above the inputted rank
*/
private fun getUpperRank(rank: Rank): Rank? = getRankByID(rank.id + 1)
/**
* Gets the rank below the inputted rank
*/
fun getLowerRank(rank: Rank): Rank? = getRankByID(rank.id - 1)
/**
* Gets a user's rank
*/
fun getUserRank(player: Player, refresh: Boolean = false): Rank {
return when (refresh) {
true -> calculateUserRank(XPHandler.getUserXP(player))
false -> getRankByID(player.getObject(Player.DataType.RANK).toString().toInt())!!
}
}
}
|
/*
* Copyright(C) (2023) Sapper Inc. (open.source at zyient dot io)
*
* 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 io.zyient.base.core.io.impl;
import io.zyient.base.core.io.Reader;
import io.zyient.base.core.io.model.FileInode;
import io.zyient.base.core.utils.Timer;
import lombok.Getter;
import lombok.NonNull;
import lombok.experimental.Accessors;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
@Getter
@Accessors(fluent = true)
public abstract class RemoteReader extends Reader {
private final RemoteFsCache cache;
private File cacheFile;
private RandomAccessFile inputStream;
protected RemoteReader(@NonNull FileInode inode,
@NonNull RemoteFileSystem fs) {
super(inode, fs);
cache = fs.cache();
}
@Override
public void doOpen() throws IOException {
try {
cacheFile = cache.get(inode());
if (cacheFile == null || !cacheFile.exists()) {
throw new IOException(
String.format("Error downloading file to local. [path=%s]", inode.getAbsolutePath()));
}
inputStream = new RandomAccessFile(cacheFile, "r");
} catch (Exception ex) {
throw new IOException(ex);
}
}
@Override
public int read() throws IOException {
return inputStream.read();
}
/**
* @param buffer
* @param offset
* @param length
* @return
* @throws IOException
*/
@Override
public int doRead(byte @NonNull [] buffer, int offset, int length) throws IOException {
return inputStream.read(buffer, offset, length);
}
@Override
public byte[] readAllBytes() throws IOException {
checkOpen();
try (Timer t = new Timer(metrics().timerFileRead())) {
if (inputStream.getChannel().size() > Integer.MAX_VALUE) {
throw new IOException(String.format("File size too large. [size=%d]", inputStream.getChannel().size()));
}
byte[] buffer = new byte[(int) inputStream.getChannel().size()];
int s = read(buffer);
if (s != inputStream.getChannel().size()) {
throw new IOException(
String.format("Failed to read all bytes: [expected=%d][read=%d][file=%s]",
inputStream.getChannel().size(), s, cacheFile.getAbsolutePath()));
}
return buffer;
}
}
@Override
public byte[] readNBytes(int len) throws IOException {
checkOpen();
try (Timer t = new Timer(metrics().timerFileRead())) {
byte[] buffer = new byte[len];
int s = read(buffer, 0, len);
if (s != len) {
throw new IOException(
String.format("Failed to read all bytes: [expected=%d][read=%d][file=%s]",
inputStream.getChannel().size(), s, cacheFile.getAbsolutePath()));
}
return buffer;
}
}
@Override
public int readNBytes(byte[] buffer, int off, int len) throws IOException {
checkOpen();
return read(buffer, off, len);
}
@Override
public long skip(long n) throws IOException {
checkOpen();
return inputStream.skipBytes((int) n);
}
@Override
public void skipNBytes(long n) throws IOException {
skip(n);
}
@Override
public int available() throws IOException {
checkOpen();
long pos = inputStream.getChannel().position();
long size = inputStream.getChannel().size();
return (int) (size - pos);
}
@Override
public synchronized void mark(int readlimit) {
}
@Override
public synchronized void reset() throws IOException {
seek(0);
}
@Override
public boolean markSupported() {
return false;
}
@Override
public long transferTo(OutputStream out) throws IOException {
throw new IOException("Not supported...");
}
/**
* @return
*/
@Override
public boolean isOpen() {
return (inputStream != null);
}
@Override
public long seek(long offset) throws IOException {
checkOpen();
if (offset >= inputStream.getChannel().size()) {
offset = inputStream.getChannel().size();
}
inputStream.seek(offset);
return offset;
}
@Override
public File copy() throws IOException {
checkOpen();
return cacheFile;
}
@Override
public void close() throws IOException {
if (inputStream != null) {
inputStream.close();
}
cacheFile = null;
inputStream = null;
}
}
|
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tabelas</title>
<style>
body{
font-family: Arial, Helvetica, sans-serif;
}
table{
width: 400px;
height: 400px;
border-collapse: collapse;
}
td{
border: 1px solid black;
padding: 8px;
text-align: center; /*alinhamento horizontal*/
vertical-align: top; /*alinhamento vertical*/
}
</style>
</head>
<body>
<h1>Minha primeira Tabela</h1>
<!--
HIERAQUIAS DE TABELAS
TABLE = Tabela simples <table>
TABLE ROWS = linhas de tabela <tr>
TABLE HEADER = Cabeçalho de tabela
TABLE DATA = Dados de tabela <td>
-->
<table>
<tr> <!--primeira linha-->
<td>A1</td>
<td>B1</td>
<td>C1</td>
</tr>
<tr> <!--segunda linha-->
<td>A2</td>
<td>B2</td>
<td>C2</td>
</tr>
<tr> <!--terceira linha-->
<td>A3</td>
<td>B3</td>
<td>C3</td>
</tr>
<tr> <!--quarta linha-->
<td>A4</td>
<td>B4</td>
<td>C4</td>
</tr>
</table>
</body>
</html>
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CarManufacturer
{
public class StartUp
{
static void Main(string[] args)
{
List<List<double>> listTiresYears = new List<List<double>>();
List<List<double>> listTiresPressures = new List<List<double>>();
List<int> listHorsePowers = new List<int>();
List<double> listCubicCapacity = new List<double>();
List<Car> listCars = new List<Car>();
Tires tires = new Tires();
Engine engine = new Engine();
string cmdTires;
while ((cmdTires = Console.ReadLine()) != "No more tires")
{
string[] splitted = cmdTires.Split();
List<double> listYears = tires.GetYearInfo(splitted);
List<double> listPressures = tires.GetPressureInfo(splitted);
listTiresYears.Add(listYears);
listTiresPressures.Add(listPressures);
}
string cmdEngines;
while ((cmdEngines = Console.ReadLine()) != "Engines done")
{
string[] splitted = cmdEngines.Split();
listHorsePowers.Add(int.Parse(splitted[0]));
listCubicCapacity.Add(double.Parse(splitted[1]));
}
string cmdCars;
while ((cmdCars = Console.ReadLine()) != "Show special")
{
string[] splitted = cmdCars.Split();
string make = splitted[0];
string model = splitted[1];
int year = int.Parse(splitted[2]);
double fuelQuantity = double.Parse(splitted[3]);
double fuelConsumption = double.Parse(splitted[4]);
int engineIndex = int.Parse(splitted[5]);
int tiresIndex = int.Parse(splitted[6]);
int horsePower = listHorsePowers[engineIndex];
double pressure = listTiresPressures[tiresIndex].Sum();
Car car = new Car(make, model, year, horsePower, fuelQuantity, fuelConsumption,
engineIndex, tiresIndex, pressure);
listCars.Add(car);
}
foreach (var car in listCars)
{
if (car.Year >= 2017 && car.HorsePower > 330
&& car.TotalPressure > 9 && car.TotalPressure < 10)
{
car.FuelQuantity -= (car.FuelConsumption / 100) * 20;
Console.WriteLine($"Make: {car.Make}");
Console.WriteLine($"Model: {car.Model}");
Console.WriteLine($"Year: {car.Year}");
Console.WriteLine($"HorsePowers: {car.HorsePower}");
Console.WriteLine($"FuelQuantity: {car.FuelQuantity}");
}
}
}
}
}
|
import 'package:flutter/material.dart';
import '../../../../constants/device_size.dart';
class CustomRoundRectButton extends StatelessWidget {
final String text;
double? radius;
double? height;
double? width;
Color? color;
double? fontSize;
VoidCallback? callBack;
double? elevation;
LinearGradient? linearGradient;
CustomRoundRectButton({Key? key,
required this.text,required this.height,this.width,this.fontSize,this.callBack,this.radius=10,this.linearGradient,this.elevation});
VoidCallback nothing = (){};
@override
Widget build(BuildContext context) {
return SizedBox(
width: width??displayWidth(context),
child: Card(
color: Colors.transparent,
elevation: elevation??0,
shape: RoundedRectangleBorder(
side: linearGradient==null?BorderSide(color: Colors.white):BorderSide.none,
borderRadius: BorderRadius.circular(radius!),
),
child: Container(
height: height!,
margin: EdgeInsets.zero,
padding: EdgeInsets.zero,
decoration: BoxDecoration(
color: color==null&&linearGradient==null?Colors.transparent:color,
borderRadius: BorderRadius.circular(radius!),
gradient: linearGradient,
),
child: MaterialButton(
elevation: 0,
onPressed: callBack??nothing,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(radius!),
),
height: height!,
color: Colors.transparent,
//padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 20),
child: Text(
text,
style: TextStyle(color: Colors.white,fontSize: fontSize),
)),
),
),
);
}
}
|
import { Device } from './state';
import { Epic, combineEpics, ActionsObservable } from 'redux-observable';
import { RootEpic } from '../epics';
import { Observable } from 'rxjs';
import { Action } from '../types';
import { actions } from '../action';
import { DeviceFromServer, fromServer } from './filters';
import { Query } from './action';
import * as Actions from './action';
import { of, from } from 'rxjs';
import {
map,
switchMap,
repeat,
delay,
startWith,
takeUntil,
catchError,
filter
} from 'rxjs/operators';
export const fetch$: RootEpic = (action$, state$, { io }): Observable<Action> =>
action$.pipe(
filter((e): e is Actions.Fetch => e.type === Actions.FETCH),
switchMap(action => {
let url = 'api/v1/devices';
let query = state$.value.devices;
let keys = Object.keys(query.search) as (keyof Device)[];
url += `?start=${query.start}`;
url += `&limit=${query.limit}`;
if (keys.length) url += `&search=${keys[0]}:${query.search[keys[0]]}`;
if (query.sort) url += `&sort=${query.sort}`;
if (query.order) url += `&order=${query.order}`;
return from(io.get<DeviceFromServer[]>(url)).pipe(
map(response =>
actions.device.fetchOk({ devices: fromServer(response.json) })
)
);
}),
catchError(error => of(actions.device.fetchErr()))
);
const query: Query<Device> = {
sort: 'last_seen' as keyof Device,
order: 'DESC'
};
export const poll$: RootEpic = (action$, state$): Observable<Action> =>
action$.pipe(
filter((e): e is Actions.PollStart => e.type === Actions.POLL_START),
switchMap(poll =>
action$.pipe(
filter((e): e is Actions.FetchOk => e.type === Actions.FETCH_OK),
delay(poll.ms || 5000),
map(() => actions.device.fetch({ query })),
repeat(),
takeUntil(action$.pipe(filter(e => e.type === Actions.POLL_STOP))),
startWith(actions.device.fetch({ query }))
)
),
catchError(error => of(actions.device.fetchErr()))
);
export const count$: RootEpic = (action$, state$, { io }): Observable<Action> =>
action$.pipe(
filter((e): e is Actions.Count => e.type === Actions.COUNT),
switchMap(response =>
from(io.get<{ count: number }>('/api/v1/devices/count')).pipe(
map(response => {
const { count } = response.json;
return actions.device.countOk({ count });
})
)
),
catchError(error => of(actions.device.countErr()))
);
export default combineEpics(fetch$, poll$, count$);
|
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
// We shouldn't coerce capturing closure to a function
let cap = 0;
let _ = match "+" {
"+" => add,
"-" => |a, b| (a - b + cap) as i32,
_ => unimplemented!(),
};
//~^^^ ERROR `match` arms have incompatible types
// We shouldn't coerce capturing closure to a non-capturing closure
let _ = match "+" {
"+" => |a, b| (a + b) as i32,
"-" => |a, b| (a - b + cap) as i32,
_ => unimplemented!(),
};
//~^^^ ERROR `match` arms have incompatible types
// We shouldn't coerce non-capturing closure to a capturing closure
let _ = match "+" {
"+" => |a, b| (a + b + cap) as i32,
"-" => |a, b| (a - b) as i32,
_ => unimplemented!(),
};
//~^^^ ERROR `match` arms have incompatible types
// We shouldn't coerce capturing closure to a capturing closure
let _ = match "+" {
"+" => |a, b| (a + b + cap) as i32,
"-" => |a, b| (a - b + cap) as i32,
_ => unimplemented!(),
};
//~^^^ ERROR `match` arms have incompatible types
}
// ferrocene-annotations: fls_dw33yt5g6m0k
// Type Coercion
//
// ferrocene-annotations: fls_exe4zodlwfez
// Type Unification
//
// ferrocene-annotations: fls_e5td0fa92fay
// Match Expressions
|
package com.example.and_sec_7.ui.Screens.StepInfo
import android.app.Application
import androidx.health.connect.client.HealthConnectClient
import androidx.lifecycle.AndroidViewModel
import com.example.and_sec_7.g_mainActivity
import java.time.Instant
import java.time.LocalDate
data class Date(
var year: Int,
var month: Int,
var day: Int
)
class StepsInfoViewModel(app: Application): AndroidViewModel(app) {
private val today: LocalDate = LocalDate.now()
private var startDate: Date = Date(year = today.year, month = today.monthValue, day = today.dayOfMonth)
private var endDate: Date = Date(year = today.year, month = today.monthValue, day = today.dayOfMonth)
fun setStartDate(year: Int, month: Int, day: Int)
{
startDate.year = year
startDate.month = month
startDate.day = day
}
fun setEndDate(year: Int, month: Int, day: Int)
{
endDate.year = year
endDate.month = month
endDate.day = day
}
fun getStartDate() : Date
{
return startDate
}
fun getEndDate() : Date
{
return endDate
}
fun readStepsByTimeRange(
healthConnectClient: HealthConnectClient,
startTime: Instant,
endTime: Instant,
onStepCountUpdated: (Int, String) -> Unit
)
{
g_mainActivity.readStepsByTimeRange(healthConnectClient, startTime, endTime, onStepCountUpdated)
}
}
|
/**
*
*/
package com.bpgracey.resilient;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.bpgracey.resilient.exceptions.ProductLineException;
import com.bpgracey.resilient.exceptions.ProductNameException;
import com.bpgracey.resilient.exceptions.ValueException;
import com.bpgracey.resilient.taxes.TaxCalc;
/**
* @author Ban
*
*/
public class ProductLine extends ReceiptLine {
private static final Pattern PRODUCT_LINE_PATTERN = Pattern.compile("(\\d+)\\s+(.+?)\\s+at\\s+(\\d+\\.\\d\\d)");
protected Product product;
protected Integer quantity;
protected Value price;
protected Value importTax;
protected Value salesTax;
protected Value total;
public ProductLine(String line) throws ProductNameException, ValueException, ProductLineException {
if (line == null || line.isEmpty()) throw new ProductLineException("Empty line");
Matcher m = PRODUCT_LINE_PATTERN.matcher(line);
if (m.find()) {
this.quantity = Integer.valueOf(m.group(1));
this.product = new Product(m.group(2));
this.price = new Value(m.group(3));
} else throw new ProductLineException();
}
public ProductLine(int quantity, String product, String price) throws ProductNameException, ValueException {
this.product = new Product(product);
this.quantity = quantity;
this.price = new Value(price);
}
public Product getProduct() {
return product;
}
public Integer getQuantity() {
return quantity;
}
public Value getPrice() {
return price;
}
public Value getTotal() {
if (total == null)
total = price.add(getSalesTax()).add(getImportTax()).multiply(quantity);
return total;
}
public Value getImportTax() {
if (importTax == null)
importTax = TaxCalc.getInstance().calcImportTax(product, price);
return importTax;
}
public Value getSalesTax() {
if (salesTax == null)
salesTax = TaxCalc.getInstance().calcSalesTax(product, price);
return salesTax;
}
@Override
public String toString() {
return "" + getQuantity() + "\t" + getProduct() + ":\t" + getTotal();
}
}
|
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
// use Illuminate\Console\View\Components\Alert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use RealRashid\SweetAlert\Facades\Alert;
class ChildrenController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// Debugging
// dd('ChildrenController@index', auth()->user());
// Get All Childrens
$childrens = \App\Models\Children::where('user_id', auth()->user()->id)->paginate(10);
// Debugging
// dd($childrens);
// Return View
return view('pages.user.children.index', compact('childrens'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
// Debugging
// dd('User Create');
// Return View
return view('pages.user.children.create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
// Debugging
// dd('Store', $request->all());
// Validate Request with Validator
$validator = \Validator::make($request->all(), [
// _token
'_token' => 'required|string',
// _method
'_method' => 'required|string',
// name
'name' => 'required|string',
// gander
'gander' => 'required',
// birhdate
'birhdate' => 'required|date',
// place
'place' => 'required|string',
// blood
'blood' => 'required',
// height
'height' => 'required|integer',
// weight
'weight' => 'required|integer',
// notes
'notes' => 'required|string',
// avatar
'avatar' => 'required|image',
], [
// _token
'_token.required' => 'Token Dibutuhkan',
'_token.string' => 'Token Harus String',
// _method
'_method.required' => 'Method Dibutuhkan',
'_method.string' => 'Method Harus String',
// name
'name.required' => 'Nama Dibutuhkan',
'name.string' => 'Nama Harus String',
// gander
'gander.required' => 'Jenis Kelamin Dibutuhkan',
// birhdate
'birhdate.required' => 'Tanggal Lahir Dibutuhkan',
'birhdate.date' => 'Tanggal Lahir Harus Tanggal',
// place
'place.required' => 'Tempat Lahir Dibutuhkan',
'place.string' => 'Tempat Lahir Harus String',
// blood
'blood.required' => 'Golongan Darah Dibutuhkan',
// height
'height.required' => 'Tinggi Badan Dibutuhkan',
'height.integer' => 'Tinggi Badan Harus Angka',
// weight
'weight.required' => 'Berat Badan Dibutuhkan',
'weight.integer' => 'Berat Badan Harus Angka',
// notes
'notes.required' => 'Catatan Dibutuhkan',
'notes.string' => 'Catatan Harus String',
// avatar
'avatar.required' => 'Avatar Dibutuhkan',
'avatar.image' => 'Avatar Harus Gambar',
]);
// Check Validator Fails
if ($validator->fails()) {
// Set Alert Error
Alert::error('Gagal', $validator->errors()->first());
// Return a view
return redirect()->back()->withInput();
}
// Upload Image
try {
//code...
// Rename Image File
$image_name = \Str::random(10) . '.' . $request->file('avatar')->getClientOriginalExtension();
// Store Thumbnail
Storage::putFileAs('public/avatar/', $request->file('avatar'), $image_name);
} catch (\Throwable $th) {
throw $th;
Alert::error('Error', 'Gagal Mengolah Gambar!');
return redirect()->route('user.children.create')->withErrors($validator)->withInput();
}
// Debugging
// dd($request->all());
// Insert Children from Request data to Database
$children = new \App\Models\Children();
try {
//code...
// user_id
$children->user_id = auth()->user()->id;
// name
$children->name = $request->name;
// slug
$children->slug = \Str::slug($request->name);
// avatar
$children->avatar = $image_name ?? $children->avatar;
// gander
$children->gander = $request->gander;
// birthdate
$children->birthdate = $request->birhdate;
// place
$children->place = $request->place;
// blood_type
$children->blood_type = $request->blood;
// height
$children->height = $request->height;
// weight
$children->weight = $request->weight;
// notes
$children->notes = $request->notes;
// allergies
// chronic_diseases
// Save
$children->save();
// Set Alert Success
Alert::success('Berhasil', 'Data Berhasil Ditambahkan');
// Return a view
return redirect()->route('user.children.index');
} catch (\Throwable $th) {
throw $th;
// Set Alert Error
Alert::error('Gagal', 'Data Gagal Ditambahkan');
// Return a view\
return redirect()->route('user.children.index');
}
// Set Alert Warning
Alert::warning('Peringatan', 'Data Tidak Ditambahkan');
// Return a view
return redirect()->route('user.children.index');
}
/**
* Display the specified resource.
*/
public function show(string $slug)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $slug)
{
// Debugging
// dd('Edit', $slug);
// Select Children from Request data to Database
$children = \App\Models\Children::where('slug', $slug)->firstOrFail();
// Return a view
return view('pages.user.children.edit', compact('children'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $slug)
{
// Debugging
// dd('Store', $request->all(), $slug);
// Validate Request with Validator
$validator = \Validator::make($request->all(), [
// _token
'_token' => 'required|string',
// _method
'_method' => 'required|string',
// name
'name' => 'required|string',
// gander
'gander' => 'required',
// birhdate
'birhdate' => 'required|date',
// place
'place' => 'required|string',
// blood
'blood' => 'required',
// height
'height' => 'required|integer',
// weight
'weight' => 'required|integer',
// notes
'notes' => 'required|string',
// avatar
'avatar' => 'required|image',
], [
// _token
'_token.required' => 'Token Dibutuhkan',
'_token.string' => 'Token Harus String',
// _method
'_method.required' => 'Method Dibutuhkan',
'_method.string' => 'Method Harus String',
// name
'name.required' => 'Nama Dibutuhkan',
'name.string' => 'Nama Harus String',
// gander
'gander.required' => 'Jenis Kelamin Dibutuhkan',
// birhdate
'birhdate.required' => 'Tanggal Lahir Dibutuhkan',
'birhdate.date' => 'Tanggal Lahir Harus Tanggal',
// place
'place.required' => 'Tempat Lahir Dibutuhkan',
'place.string' => 'Tempat Lahir Harus String',
// blood
'blood.required' => 'Golongan Darah Dibutuhkan',
// height
'height.required' => 'Tinggi Badan Dibutuhkan',
'height.integer' => 'Tinggi Badan Harus Angka',
// weight
'weight.required' => 'Berat Badan Dibutuhkan',
'weight.integer' => 'Berat Badan Harus Angka',
// notes
'notes.required' => 'Catatan Dibutuhkan',
'notes.string' => 'Catatan Harus String',
// avatar
'avatar.required' => 'Avatar Dibutuhkan',
'avatar.image' => 'Avatar Harus Gambar',
]);
// Check Validator Fails
if ($validator->fails()) {
// Set Alert Error
Alert::error('Gagal', $validator->errors()->first());
// Return a view
return redirect()->back()->withInput();
}
// Check Image
if ($request->hasFile('avatar')) {
// Upload Image
try {
//code...
// Rename Image File
$image_name = \Str::random(10) . '.' . $request->file('avatar')->getClientOriginalExtension();
// Store Thumbnail
Storage::putFileAs('public/avatar/', $request->file('avatar'), $image_name);
} catch (\Throwable $th) {
//throw $th;
Alert::error('Error', 'Gagal Mengolah Gambar!');
return redirect()->route('admin.food.create')->withErrors($validator)->withInput();
}
}
// Select Children from Request data to Database
$children = \App\Models\Children::where('slug', $slug)->firstOrFail();
try {
//code...
// user_id
$children->user_id = auth()->user()->id;
// name
$children->name = $request->name;
// slug
$children->slug = \Str::slug($request->name);
// avatar
$children->avatar = $image_name ?? $children->avatar;
// gander
$children->gander = $request->gander;
// birthdate
$children->birthdate = $request->birhdate;
// place
$children->place = $request->place;
// blood_type
$children->blood_type = $request->blood;
// height
$children->height = $request->height;
// weight
$children->weight = $request->weight;
// notes
$children->notes = $request->notes;
// allergies
// chronic_diseases
// Save
$children->save();
// Set Alert Success
Alert::success('Berhasil', 'Data Berhasil Diubah');
// Return a view
return redirect()->route('user.children.index');
} catch (\Throwable $th) {
throw $th;
// Set Alert Error
Alert::error('Gagal', 'Data Gagal Diubah');
// Return a view
return redirect()->route('user.children.index');
}
// Set Alert Warning
Alert::warning('Peringatan', 'Data Tidak Diubah');
// Return a view
return redirect()->route('user.children.index');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $slug)
{
// Debugging
// Select Children from Request data to Database
$children = \App\Models\Children::where('slug', $slug)->firstOrFail();
// Delete
try {
//code...
$children->delete();
// Set Alert Success
Alert::success('Berhasil', 'Data Berhasil Dihapus');
// Return a view
return redirect()->route('user.children.index');
} catch (\Throwable $th) {
//throw $th;
// Set Alert Error
Alert::error('Gagal', 'Data Gagal Dihapus');
// Return a view
return redirect()->route('user.children.index');
}
// Return a View
return redirect()->route('user.children.index');
}
}
|
import { createContext, useContext, useState } from "react"
const CartContext = createContext()
export const useCartContext = () => useContext(CartContext)
const CartContextProvider = ({ children }) => {
const [cart, setCart] = useState([])
const [c, setC] = useState(0)
const [mT, setMT] = useState(0)
const actualizarCantidad = cart.reduce((acc, cart) => acc + cart.quantity, 0)
const actualizarTotal = cart.reduce((acc, cart) => acc + (cart.quantity * cart.precio), 0)
const isInCart = (id) => cart.find(prod => prod.id == id)
const addToCart = (producto, cantidad) => {
const newCart = [...cart]
const productoEnCart = isInCart(producto.id)
if (productoEnCart) {
newCart[newCart.findIndex(prod => prod.id == productoEnCart.id)].quantity += cantidad
setCart(newCart)
setC(c + cantidad)
setMT(mT + (cantidad * productoEnCart.precio))
return
}
producto.quantity = cantidad
setCart([...newCart, producto])
setC(c + cantidad)
setMT(mT + (cantidad * producto.precio))
}
const deleteFromCart = (producto) => {
const newCart = [...cart]
const productoEnCart = isInCart(producto.id)
if (!productoEnCart) {
return
}
const deleteProduct = newCart.filter((prod) => prod.id !== producto.id)
setCart(deleteProduct)
setC(c - producto.quantity)
setMT(mT - (producto.quantity * producto.precio))
}
const deleteCart = () => {
setCart([])
setC(0)
setMT(0)
}
return (
<CartContext.Provider value={{ cart, addToCart, deleteFromCart, deleteCart, c, mT }}>{children}</CartContext.Provider>
)
}
export default CartContextProvider
|
# Deploying the Neighborly App with Azure Functions
## Project Overview
For the final project, we are going to build an app called "Neighborly". Neighborly is a Python Flask-powered web application that allows neighbors to post advertisements for services and products they can offer.
The Neighborly project is comprised of a front-end application that is built with the Python Flask micro framework. The application allows the user to view, create, edit, and delete the community advertisements.
The application makes direct requests to the back-end API endpoints. These are endpoints that we will also build for the server-side of the application.
You can see an example of the deployed app below.

## Dependencies
You will need to install the following locally:
- [Pipenv](https://pypi.org/project/pipenv/)
- [Visual Studio Code](https://code.visualstudio.com/download)
- [Azure Function tools V3](https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash#install-the-azure-functions-core-tools)
- [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)
- [Azure Tools for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack)
On Mac, you can do this with:
```bash
# install pipenv
brew install pipenv
# install azure-cli
brew update && brew install azure-cli
# install azure function core tools
brew tap azure/functions
brew install azure-functions-core-tools@3
```
## Project Instructions
In case you need to return to the project later on, it is suggested to store any commands you use so you can re-create your work. You should also take a look at the project rubric to be aware of any places you may need to take screenshots as proof of your work (or else keep your resource up and running until you have passed, which may incur costs).
### I. Creating Azure Function App
We need to set up the Azure resource group, region, storage account, and an app name before we can publish.
1. Create a resource group.
2. Create a storage account (within the previously created resource group and region).
3. Create an Azure Function App within the resource group, region and storage account.
- Note that app names need to be unique across all of Azure.
- Make sure it is a Linux app, with a Python runtime.
Example of successful output, if creating the app `myneighborlyapiv1`:
```bash
Your Linux function app 'myneighborlyapiv1', that uses a consumption plan has been successfully created but is not active until content is published using Azure Portal or the Functions Core Tools.
```
4. Set up a Cosmos DB Account. You will need to use the same resource group, region and storage account, but can name the Cosmos DB account as you prefer. **Note:** This step may take a little while to complete (15-20 minutes in some cases).
5. Create a MongoDB Database in CosmosDB Azure and two collections, one for `advertisements` and one for `posts`.
6. Print out your connection string or get it from the Azure Portal. Copy/paste the **primary connection** string. You will use it later in your application.
Example connection string output:
```bash
bash-3.2$ Listing connection strings from COSMOS_ACCOUNT:
+ az cosmosdb keys list -n neighborlycosmos -g neighborlyapp --type connection-strings
{
"connectionStrings": [
{
"connectionString": "AccountEndpoint=https://neighborlycosmos.documents.azure.com:443/;AccountKey=xxxxxxxxxxxx;",
"description": "Primary SQL Connection String"
},
{
"connectionString": "AccountEndpoint=https://neighborlycosmos.documents.azure.com:443/;AccountKey=xxxxxxxxxxxxx;",
"description": "Secondary SQL Connection String"
}
... [other code omitted]
]
}
```
7. Import Sample Data Into MongoDB.
- Download dependencies:
```bash
# get the mongodb library
brew install [email protected]
# check if mongoimport lib exists
mongoimport --version
```
- Import the data from the `sample_data` directory for Ads and Posts to initially fill your app.
Example successful import:
```
Importing ads data ------------------->
2020-05-18T23:30:39.018-0400 connected to: mongodb://neighborlyapp.mongo.cosmos.azure.com:10255/
2020-05-18T23:30:40.344-0400 5 document(s) imported successfully. 0 document(s) failed to import.
...
Importing posts data ------------------->
2020-05-18T23:30:40.933-0400 connected to: mongodb://neighborlyapp.mongo.cosmos.azure.com:10255/
2020-05-18T23:30:42.260-0400 4 document(s) imported successfully. 0 document(s) failed to import.
```
8. Hook up your connection string into the NeighborlyAPI server folder. You will need to replace the *url* variable with your own connection string you copy-and-pasted in the last step, along with some additional information.
- Tip: Check out [this post](https://docs.microsoft.com/en-us/azure/cosmos-db/connect-mongodb-account) if you need help with what information is needed.
- Go to each of the `__init__.py` files in getPosts, getPost, getAdvertisements, getAdvertisement, deleteAdvertisement, updateAdvertisement, createAdvertisements and replace your connection string. You will also need to set the related `database` and `collection` appropriately.
```bash
# inside getAdvertisements/__init__.py
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python getAdvertisements trigger function processed a request.')
try:
# copy/paste your primary connection url here
#-------------------------------------------
url = ""
#--------------------------------------------
client=pymongo.MongoClient(url)
database = None # Feed the correct key for the database name to the client
collection = None # Feed the correct key for the collection name to the database
... [other code omitted]
```
Make sure to do the same step for the other 6 HTTP Trigger functions.
9. Deploy your Azure Functions.
1. Test it out locally first.
```bash
# cd into NeighborlyAPI
cd NeighborlyAPI
# install dependencies
pipenv install
# go into the shell
pipenv shell
# test func locally
func start
```
You may need to change `"IsEncrypted"` to `false` in `local.settings.json` if this fails.
At this point, Azure functions are hosted in localhost:7071. You can use the browser or Postman to see if the GET request works. For example, go to the browser and type in:
```bash
# example endpoint for all advertisements
http://localhost:7071/api/getadvertisements
#example endpoint for all posts
http://localhost:7071/api/getposts
```
2. Now you can deploy functions to Azure by publishing your function app.
The result may give you a live url in this format, or you can check in Azure portal for these as well:
Expected output if deployed successfully:
```bash
Functions in <APP_NAME>:
createAdvertisement - [httpTrigger]
Invoke url: https://<APP_NAME>.azurewebsites.net/api/createadvertisement
deleteAdvertisement - [httpTrigger]
Invoke url: https://<APP_NAME>.azurewebsites.net/api/deleteadvertisement
getAdvertisement - [httpTrigger]
Invoke url: https://<APP_NAME>.azurewebsites.net/api/getadvertisement
getAdvertisements - [httpTrigger]
Invoke url: https://<APP_NAME>.azurewebsites.net/api/getadvertisements
getPost - [httpTrigger]
Invoke url: https://<APP_NAME>.azurewebsites.net/api/getpost
getPosts - [httpTrigger]
Invoke url: https://<APP_NAME>.azurewebsites.net/api/getposts
updateAdvertisement - [httpTrigger]
Invoke url: https://<APP_NAME>.azurewebsites.net/api/updateadvertisement
```
**Note:** It may take a minute or two for the endpoints to get up and running if you visit the URLs.
Save the function app url **https://<APP_NAME>.azurewebsites.net/api/** since you will need to update that in the client-side of the application.
### II. Deploying the client-side Flask web application
We are going to update the Client-side `settings.py` with published API endpoints. First navigate to the `settings.py` file in the NeighborlyFrontEnd/ directory.
Use a text editor to update the API_URL to your published url from the last step.
```bash
# Inside file settings.py
# ------- For Local Testing -------
#API_URL = "http://localhost:7071/api"
# ------- For production -------
# where APP_NAME is your Azure Function App name
API_URL="https://<APP_NAME>.azurewebsites.net/api"
```
### III. CI/CD Deployment
1. Deploy your client app. **Note:** Use a **different** app name here to deploy the front-end, or else you will erase your API. From within the `NeighborlyFrontEnd` directory:
- Install dependencies with `pipenv install`
- Go into the pip env shell with `pipenv shell`
- Deploy your application to the app service. **Note:** It may take a minute or two for the front-end to get up and running if you visit the related URL.
Make sure to also provide any necessary information in `settings.py` to move from localhost to your deployment.
2. Create an Azure Registry and dockerize your Azure Functions. Then, push the container to the Azure Container Registry.
3. Create a Kubernetes cluster, and verify your connection to it with `kubectl get nodes`.
4. Deploy app to Kubernetes, and check your deployment with `kubectl config get-contexts`.
### IV. Event Hubs and Logic App
1. Create a Logic App that watches for an HTTP trigger. When the HTTP request is triggered, send yourself an email notification.
2. Create a namespace for event hub in the portal. You should be able to obtain the namespace URL.
3. Add the connection string of the event hub to the Azure Function.
### V. Cleaning Up Your Services
Before completing this step, make sure to have taken all necessary screenshots for the project! Check the rubric in the classroom to confirm.
Clean up and remove all services, or else you will incur charges.
```bash
# replace with your resource group
RESOURCE_GROUP="<YOUR-RESOURCE-GROUP>"
# run this command
az group delete --name $RESOURCE_GROUP
```
## AZURE WEB DEVELOPER NEIGHBORLYAPP PROJECT DEPLOYEMNTS STEPS
- Steps: Azure Portal and CLI:
- Create a resource group
- Create a storage account
- Create an Azure Function App, using Linux and python
- Set up a Cosmos DB Account
- Create a MongoDB Database in CosmosDB Azure and two collections, one for `advertisments` and one for `posts`
- Obtain your connection string
- Import the sample data into MongoDB
- Hook up all seven HTTP Triggers to the database connection
- Deploy your Azure Functions. You should be able to reach the API endpoints from your browser.
# Create an Azure Function App with Azure CLI
```
on MAc
cd my_project/
source ml_env/bin/activate
cd Microsost\ Azure/Microservices\ /NeighborlyAPP_Project/
cd NeighborlyAPI/
```
- This will automatically activate the venv environment... with python version 3.9.8
`python --version `
# Note that your functionapp python version matches the local computer dev env python version. Here Python 3.7.11
`pip install -r requirements.txt`
## First login to the accaount using:
`az login`
- sign in into Azure Tools VS Code
## Function app and storage account names must be unique
```
storageName=microadstorage
functionAppName=adlondonapp
region=uksouth
myResourceGroup=cloud-demo
```
# Create Resource Group: this has already been created in the lab
`az group create --name $myResourceGroup --location $region`
# Create an Azure storage account in the resource group.
```
az storage account create \
--name $storageName \
--location $region \
--resource-group $myResourceGroup \
--sku Standard_LRS
```
# Create a function app in the resource group.
```
az functionapp create \
--name $functionAppName \
--storage-account $storageName \
--consumption-plan-location $region \
--resource-group $myResourceGroup \
--functions-version \
--os-type Linux \
--runtime python
```
# Alternatively on Mac
```
az functionapp create \
--name $functionAppName\
--storage-account $storageName \
--resource-group $myResourceGroup \
--os-type Linux \
--consumption-plan-location $region \
--runtime python
```
# Deploying with Azure CLI
- cd Microservices/NeighborlyApp_Project/NeighborlyAPI
# NEXT: Create a Python function in Azure Using Azure CLI
- run the command: `func init LocalAzureFuncProject --python`
- cd LocalAzureFuncProject
- run the command: ` func new --name PythonHttpNeighborApp --template "HTTP trigger" --authlevel "anonymous" `
# Run the function locally
- on terminal, run the command: `func start`
- open the url on browser: `http://localhost:7071/api/PythonHttpNeighborApp`
- Query with by apending this to the end: `?name=Azure%20Functions`
- `http://localhost:7071/api/PythonHttpNeighborApp/?name=Azure%20Functions`
- Quit the app browser: ctrl + c
# Deploy the function project to Azure
- run the command: `func azure functionapp publish adlondonapp`
# Invoke the function
- open the Invoke url on browser: `https://adlondonapp.azurewebsites.net/api/pythonhttpneighborapp`
- append `?name=Azure%20Functions`
- `https://adlondonapp.azurewebsites.net/api/pythonhttpneighborapp/?name=Azure%20Functions`
# SET UP A COSMOS DB ACCOUNT
## Create Azure Cosmos DB Resources Using CLI: Define variables for MongoDB API resources
# Cloud Lab users should use the existing Resource group in their account
```
resourceGroupName="cloud-demo"
location='uksouth'
accountName="azurecosmosdbln" #needs to be lower case
serverVersion='4.0'
```
# Create Resource Group: This is already created for lab
- az group create -n $resourceGroupName -l $location
# Create a Cosmos account for MongoDB
```
az cosmosdb create \
-n $accountName \
-g $resourceGroupName \
--locations regionName=$region \
--kind MongoDB \
--default-consistency-level Eventual \
--enable-automatic-failover false
```
# Create a new MongoDB database with a sample collection
```
DB_NAME = neighborapp-db
CREATE_LEASE_COLLECTION=0 #yes,no=(1,0)
```
# Get CosmosDB key and save it as a variable
```
COSMOSDB_KEY=$(az cosmosdb keys list --name $accountName --resource-group $resourceGroupName --output tsv |awk '{print $1}')
az cosmosdb database create --db-name neighborapp-db \
--resource-group cloud-demo \
--key $COSMOSDB_KEY \
--name azurecosmosdbln \
--resource-group-name cloud-demo \
--throughput 400 \
SAMPLE_COLLECTION_ADS=advertisements
SAMPLE_COLLECTION_POSTS=posts
```
# Create a MongoDB API Collection for Advertisements with a partition key and provision 400 RU/s throughput
```
az cosmosdb mongodb collection create \
--resource-group cloud-demo \
--name $SAMPLE_COLLECTION_ADS \
--account-name azurecosmosdbln \
--database-name neighborapp-db \
--throughput 400
```
# Create a MongoDB API Collection for Posts
```
az cosmosdb mongodb collection create \
--resource-group cloud-demo \
--name $SAMPLE_COLLECTION_POSTS \
--account-name azurecosmosdbln \
--database-name neighborapp-db \
--throughput 400
```
# listing connection strings from Cosmos Account
- az cosmosdb keys list -n azurecosmosdbln -g cloud-demo --type connection-strings
- copied connection strings
```
{
"connectionStrings": [
{
"connectionString": "mongodb://azurecosmosdbln:HEbTAVWb6jit5uNbhFRY9hunPfqWpt2Pu35K2PWFyuhfLYgXmsz1Nd7Dv7pALt7cvytXCjkCvIxiW32Cb5iJ3A==@azurecosmosdbln.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@azurecosmosdbln@",
"description": "Primary MongoDB Connection String"
},
{
"connectionString": "mongodb://azurecosmosdbln:EOyVHfCQloPDHYZmgrHrHZV09Ve9FTD2OBhxVOVvG5aoShuJdUbQ5fBn8BM1tlFgMCVvfQ0b8dxlx3iiDMGJgw==@azurecosmosdbln.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@azurecosmosdbln@",
"description": "Secondary MongoDB Connection String"
},
{
"connectionString": "mongodb://azurecosmosdbln:dgtYfkIalcA2l3asDo13o3s1MCx9PfPk4q8gigkIiOzfaKvw7BeTPoKtoAjcxh17KrCNioNIn76UacIrEZO4kw==@azurecosmosdbln.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@azurecosmosdbln@",
"description": "Primary Read-Only MongoDB Connection String"
},
{
"connectionString": "mongodb://azurecosmosdbln:Rr2fq62WSxa5BpnpZzSFLP9Gk3Sdu3vIMLTZbnj5XVGrBrqvEw0ezo0EiegYubq7gT3u6TvzeCgJUQ3qqBWbQQ==@azurecosmosdbln.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@azurecosmosdbln@",
"description": "Secondary Read-Only MongoDB Connection String"
}
]
}
```
# Import the data from the sample_data directory for Ads and posts to fill the app
# get the mongodb library
- brew install [email protected]
# check if mongoimport lib exists
- mongoimport --version
# This information is viewable in your portal >> Azure Cosmos DB >> Select the DB name >> Settings >> Connection String >>
# replace the host, port, username, and primary password with your own
```
MONGODB_HOST=azurecosmosdbln.mongo.cosmos.azure.com
MONGODB_PORT=10255
USER=azurecosmosdbln
```
# Copy/past the primary password here
```
PRIMARY_PW=HEbTAVWb6jit5uNbhFRY9hunPfqWpt2Pu35K2PWFyuhfLYgXmsz1Nd7Dv7pALt7cvytXCjkCvIxiW32Cb5iJ3A==
FILE_DIR_ADS=../sample_data/sampleAds.json
FILE_DIR_POSTS=../sample_data/samplePosts.json
```
#Import command for Linux and Mac OS
```
mongoimport -h $MONGODB_HOST:$MONGODB_PORT \
--db neighborapp-db --collection $SAMPLE_COLLECTION_ADS -u $USER -p $PRIMARY_PW \
--ssl --jsonArray --file $FILE_DIR_ADS --writeConcern "{w:0}"
mongoimport -h $MONGODB_HOST:$MONGODB_PORT \
--db neighborapp-db --collection $SAMPLE_COLLECTION_POSTS -u $USER -p $PRIMARY_PW \
--ssl --jsonArray --file $FILE_DIR_ADS --writeConcern "{w:0}"
```
## Create Event Hub and Logic App | Create EventHub on Azure portal
```
storageName=microadstorage
functionAppName=adlondonapp
region=uksouth
myResourceGroup=cloud-demo
Type=Consumption
LogicAppName=AdLogicApp
Namespace name=neighborlyappeventhub
Throughput Units=40
Pricing tier=Basic
```
- select `neighborlyappeventhub` >> Shared access Policy
```
Connection-string-primary-key=Endpoint=sb://neighborlyappeventhub.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=lss2c/lwDZQQ5Pj7wzfKm6WEk4enjUGPn+F782qx2mA=
```
# Synching local.setting.json in VS and Azure
```
softwareupdate --all --install --force
brew tap azure/functions
brew install azure-functions-core-tools@4
storageName=microadstorage
functionAppName=adlondonapp
region=uksouth
myResourceGroup=cloud-demo
func azure functionapp publish $functionAppName --python
func azure functionapp fetch-app-settings $functionAppName # to copy from Azure to local
func azure functionapp publish $functionAppName --publish-settings-only # to copy from local to Azure
```
# Create Logic App And Send Email
```
RESOURCE_GROUP=cloud-demo
Logic_App_name=adlogicApp
region=uksouth
Type=Consumption
```
# Part2 - Deploy your client app from the NeighborlyFrontEnd
- cd NeighborlyFrontEnd
- pip install -r requiremnets.txt
# Inside file settings.py
# ------- For Local Testing -------
#API_URL = "http://localhost:7071/api"
# ------- For production -------
# where APP_NAME is your Azure Function App name
- API_URL="https://adlondonapp.azurewebsites.net/api"
- Make sure Werkzeug<1.0 because werkzeug.contrib.atom is deprecated in recent versions of Werkzeug
- Also the code does not use dominate, visitor, azure-functions, flask-restplus and flask_swagger_ui for anything. You can remove them.
- You can deploy the client-side Flask app with:
```
APP_NAME=neighborlyad-webapp
myResourceGroup=cloud-demo
region=uksouth
az webapp up \
--resource-group cloud-demo \
--name $APP_NAME \
--sku F1 \
--location $region \
--verbose
```
- After running this command once, a configuration file will be created that will store any arguments you gave the previous time, so you can run just az webapp up and it will re-use arguments. Note that certain updates, such as changes to requirements.txt files, won't be appropriately pushed just by using az webapp up, so you may need to use az webapp update or just delete the app and re-deploy.
```
az webapp up \
--name $APP_NAME \
--verbose
```
- Once deployed, the flask app will be available at the URL http://<APP_NAME>.azurewebsites.net/ - meaning the app name you use must be unique.
# Part 3: CI/CD Deployment
1. Create an Azure Registry
2. Dockerize your Azure Functions
# create docker file
- func init --docker-only --python
# Create Registry on Azure portal but here using CLI to create Azure registry container
```
RESOURCE_GROUP="cloud-demo"
APP_REGISTRY="neighborlyAppRegistry"
az acr create --resource-group $RESOURCE_GROUP --name $APP_REGISTRY --sku Basic
```
- In the Azure portal, search Container Registries. Here, you should be able to see the registry that you created in Step 2. Navigate to the registry amd click on Access Keys. By default, the Admin user option would be disabled. Enable it.
```
REGISTRY_SERVER=neighborlyappregistry.azurecr.io
REGISTRY=neighborlyAppRegistry
docker login neighborlyappregistry.azurecr.io --username neighborlyAppRegistry --password YK1pWFYa=zvS3gLp=/s=3di7b6kqDybk
image_name=neighborly-api
TAG=neighborlyappregistry.azurecr.io/neighborlyapp-api:v1
docker build -t $TAG .
# List your images with:
docker images
```
- push the container to the Azure Container Registry
```
REGISTRY_SERVER=neighborlyappregistry.azurecr.io
az acr login --name $REGISTRY_SERVER
docker push neighborlyappregistry.azurecr.io/neighborlyapp-api:v1
```
# Part 3: Create a Kubernetes Cluster
- Create a Kubernetes cluster, and verify your connection to it with `kubectl get nodes`
- Run the installation command: `brew install kubectl` or `brew install kubernetes-cli`
- Test to ensure the version you installed is up-to-date: `kubectl version --client`
```
RESOURCE_GROUP=cloud-demo
AKS_CLUSTER=neighborlyapp-aks-cluster
az aks create --resource-group $RESOURCE_GROUP --name $AKS_CLUSTER --node-count 2 --enable-addons monitoring --generate-ssh-keys
# Merge "neighborly-aks-cluster" as current context in /Users/<username>/.kube/config
az aks get-credentials --name $AKS_CLUSTER --resource-group $RESOURCE_GROUP
#verify your connection to it with:
kubectl get nodes
```
# Deploy app to Kubernetes, and check your deployment with kubectl config get-contexts:
-To run Functions on your Kubernetes cluster, you must install the KEDA component. You can install this component using Azure Functions Core Tools.
```
func kubernetes install --namespace keda
RESOURCE_GROUP=cloud-demo
AKS_CLUSTER=neighborlyapp-aks-cluster
IMAGE_NAME=neighborlyappregistry.azurecr.io/neighborlyapp-api:v1
REGISTRY=neighborlyAppRegistry
```
# Update a managed Kubernetes cluster. Where --attach-acr grants the 'acrpull' role assignment to the ACR specified by name or resource ID. It might take up to 10 minutes or more for it to work. be patient.
```
az aks update -n $AKS_CLUSTER -g $RESOURCE_GROUP --attach-acr $REGISTRY
func kubernetes deploy --name $AKS_CLUSTER \
--image-name $IMAGE_NAME \
-—polling-interval 3 —cooldown-period 5
# Check your deployment:
kubectl config get-contexts
```
# Deployment Images for step guide

- Deployed Resources

- Event Trigger Endpoint Configuration

- Event Triggers

- MongoDB Database and Collections

- Function App HTTP Triggers

- Syncing Triggers

- Connection string endpoint

- Logic App Design Triger

- Logic App Design Triger2

- Logic App Email Triger

- Web Deployment

- Web Deployment App

- Web Deployment App2

# Resources
- You will need to install the following locally:
- [Azure core functions cmd](https://github.com/Azure/azure-functions-core-tools)
- [Pipenv](https://pypi.org/project/pipenv/)
- [VS Code](https://code.visualstudio.com/download)
- [Azure Function tools V3](https://docs.microsoft.com/en-gb/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cportal%2Cbash%2Ckeda#install-the-azure-functions-core-tools&WT.mc_id=udacity_learn-wwl)
- [Install Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli)
- [Microservices project](https://github.com/udacity/nd081-c2-Building-and-deploying-cloud-native-applications-from-scratch-project-starter)
- [Azure Tools for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack)
- [Connecting a MongoDB appliaction to Azure Cosmos](https://docs.microsoft.com/en-gb/azure/cosmos-db/mongodb/connect-mongodb-account?WT.mc_id=udacity_learn-wwl)
- [Udacity Microsoft Azure Web Developer Resource](https://github.com/DhruvKinger/Link-of-all-blogs)
- [Udacity Microsoft Web Developer Projects Resources](https://github.com/DhruvKinger/Udacity-KnowledgeQuestions/)
- [Download MongoDB Compass](https://www.mongodb.com/try/download/compass)
- [Find all Azure command arguements here](https://docs.microsoft.com/en-gb/cli/azure/webapp?view=azure-cli-latest#az-webapp-up&?WT.mc_id=udacity_learn-wwl)
- [ Docker installations for all OS](https://docs.docker.com/get-docker/)
- [Dockerfile](https://docs.docker.com/engine/reference/builder/)
- [Private Docker container registeries](https://docs.microsoft.com/en-gb/azure/container-registry/container-registry-intro?WT.mc_id=udacity_learn-wwl)
- [Azure container Registry documentation](https://docs.microsoft.com/en-gb/azure/container-registry/container-registry-concepts?WT.mc_id=udacity_learn-wwl)
|
import React, { useState, lazy, Suspense } from "react";
import styles from "./styles/Home.module.css";
import Sidebar from "../components/Sidebar";
import HomeSidebar from "../components/Sidebar/SidebarHomeContent";
const Readme = lazy(() => import("../components/Readme"));
const Model = lazy(() => import("../components/Model"));
const Slider = lazy(() => import("../components/Slider"));
export default function Main() {
const [swiperEl, setSwiperEl] = useState(1);
const [isReadme, setIsReadme] = useState(false);
const slideTo = (index) => swiperEl.slideTo(index, 500);
return (
<main className={styles.main}>
<Sidebar>
<HomeSidebar slideTo={slideTo} setIsReadme={setIsReadme} isReadme={isReadme} />
</Sidebar>
<div className={styles.wrapper}>
<Suspense fallback={<div>Loading...</div>}>
<Model slideTo={slideTo} />
{isReadme && <Readme setIsReadme={setIsReadme} />}
<Slider setSwiperEl={setSwiperEl} />
</Suspense>
</div>
</main>
);
}
|
//
// EmojiMemoryGame.swift
// Memorize
//
// Created by Carlos Arriaga on 13/12/23.
//
import Foundation
//Makes the created objects observable by the views
class EmojiMemoryGame: ObservableObject {
typealias Card = MemoryGame<String>.Card
//static - so as not to depend on an instance to access it
private static var emojis = ["🚀","🚁","🏎","🚒","🚗","🚕","🚌","🚓","🚑","🚐","🚜","🛵","🚙","🚎","🛻","🚚","🚛","🛸","⛵️","✈️"]
//model - will be the connection with our model
//@Published - Ensures that observers are notified of any changes to this property.
@Published private var model = createMemoryGame()
//Just the connection with the model Cards
var cards: Array<Card> {
model.cards
}
//The deck to be played is created
private static func createMemoryGame() -> MemoryGame<String> {
//The closing of MemoryGame.init appears here
MemoryGame<String>(numberOfPairsOfCards: 5) { pairIndex in //pairIndex comes from MemoryGame.init
emojis[pairIndex] //return the emoji for the card in turn
}
}
// MARK: Intent
//Connects to the function of the model
func choose(_ card: Card) {
model.choose(card)
}
func shuffle() {
model.shuffle()
}
func restart() {
model = EmojiMemoryGame.createMemoryGame()
}
}
|
using System.Collections.Generic;
using System.Runtime.InteropServices;
using HarmonyLib;
using Il2CppSystem;
using Il2CppSystem.Runtime.CompilerServices;
using UnityEngine;
namespace Luna;
public static class UiManager
{
public enum UIState
{
Title,
Mission,
Options,
OptionsSubGameplay,
OptionsSubGraphics,
OptionsSubAudio,
OptionsSubCamera,
Profile,
Results,
CharacterSelect,
LevelSelect,
}
public static UIController Controller { get; private set; }
private static Dictionary<UIState, object> _uiMenus;
private static UIState _currentUIState;
public static UIState CurrentUIState
{
get => _currentUIState;
set => _currentUIState = value;
}
public static bool EnableUIInput { get; set; } = true;
public static void LockCursor() => Controller.onLockCursor();
/// <summary>
/// Refreshes all the Menus.
/// This needs to be called when the UIState gets changed externally
/// </summary>
public static void RefreshMenus()
{
foreach (var menu in _uiMenus)
{
if (menu.Key == CurrentUIState)
ChangeMenuState(menu.Value, true);
else
ChangeMenuState(menu.Value, false);
}
}
/// <summary>
/// Refreshes all the Menus.
/// Sets the Current UI State and then Refreshes the UI
/// </summary>
/// <param name="state">The UI State that should be set</param>
public static void RefreshMenus(UIState state)
{
CurrentUIState = state;
foreach (var menu in _uiMenus)
{
if (menu.Key == state)
ChangeMenuState(menu.Value, true);
else
ChangeMenuState(menu.Value, false);
}
}
public static void DisableAllMenus()
{
foreach (var menu in _uiMenus)
ChangeMenuState(menu.Value, false);
}
private static void ChangeMenuState(object menu, bool state)
{
switch (menu)
{
case IngameMenu ingameMenu:
ingameMenu.gameObject.SetActive(state);
break;
case CharacterSelectMenu characterSelectMenu:
characterSelectMenu.gameObject.SetActive(state);
break;
case LevelSelectMenu levelSelectMenu:
levelSelectMenu.gameObject.SetActive(state);
break;
case MissionUI missionUI:
missionUI.gameObject.SetActive(state);
break;
case OptionsMenu optionsMenu:
optionsMenu.gameObject.SetActive(state);
break;
case PauseMenu pauseMenu:
pauseMenu.gameObject.SetActive(state);
break;
case TitleScreenMenu titleScreenMenu:
titleScreenMenu.gameObject.SetActive(state);
titleScreenMenu.Deactivate();
break;
}
}
[HarmonyPatch(typeof(UIController), "Start")]
[HarmonyPostfix]
private static void UIController_Start()
{
Controller = UIController.Instance;
_uiMenus = new Dictionary<UIState, object>()
{
{UIState.Title, Controller.titleScreenMenu}, //TITLE SCREEN MENU
{UIState.Mission, Controller.missionUI}, //MISSION UI
{UIState.Options, Controller.optionsMenu}, //OPTIONS MENU
{UIState.OptionsSubGameplay, Controller.gameplayMainMenu}, //INGAME MENU
{UIState.OptionsSubGraphics, Controller.graphicsMenu}, //INGAME MENU
{UIState.OptionsSubAudio, Controller.audioMenu}, //INGAME MENU
{UIState.OptionsSubCamera, Controller.gameplayMenu}, //INGAME MENU
{UIState.Profile, Controller.profileMenu}, //PROFILE MENU
{UIState.Results, Controller.resultsMenu}, //RESULTS MENU
{UIState.CharacterSelect, Controller.characterSelectMenu}, //CHARACTER SELECT MENU
{UIState.LevelSelect, Controller.levelSelectMenu}, //LEVEL SELECT MENU
};
var image = new Texture2D(512, 512);
image.LoadImage(Resource.GameLogo);
var sprite = Sprite.Create(image, new Rect(0, 0, image.width, image.height), new Vector2(0.5f, 0.5f));
UIController.Instance.gameLogo.overrideSprite = sprite;
}
#region Change UI State
[HarmonyPatch(typeof(IngameMenu), "OnEnable")]
[HarmonyPostfix]
private static void IngameMenu_OnEnable(IngameMenu __instance)
{
if (__instance == Controller.gameplayMainMenu)
CurrentUIState = UIState.OptionsSubGameplay;
else if (__instance == Controller.graphicsMenu)
CurrentUIState = UIState.OptionsSubGraphics;
else if (__instance == Controller.audioMenu)
CurrentUIState = UIState.OptionsSubAudio;
else if (__instance == Controller.gameplayMenu)
CurrentUIState = UIState.OptionsSubCamera;
}
[HarmonyPatch(typeof(CharacterSelectMenu), "OnEnable")]
[HarmonyPostfix]
private static void CharacterSelectMenu_OnEnable() => CurrentUIState = UIState.CharacterSelect;
[HarmonyPatch(typeof(TitleScreenMenu), "OnEnable")]
[HarmonyPostfix]
private static void TitleScreenMenu_OnEnable() => CurrentUIState = UIState.Title;
[HarmonyPatch(typeof(MissionUI), "OnEnable")]
[HarmonyPostfix]
private static void MissionUI_OnEnable() => CurrentUIState = UIState.Mission;
[HarmonyPatch(typeof(OptionsMenu), "OnEnable")]
[HarmonyPostfix]
private static void OptionsMenu_OnEnable() => CurrentUIState = UIState.Options;
//The real Pause Menu
//Gets triggered when the Player Resumes the actual mission
[HarmonyPatch(typeof(PauseMenu), "OnUIPause")]
[HarmonyPostfix]
private static void PauseMenu_OnUIPause()
{
if (Game.GameState == GameState.Mission)
CurrentUIState = UIState.Mission;
}
[HarmonyPatch(typeof(ProfileMenu), "OnEnable")]
[HarmonyPostfix]
private static void ProfileMenu_OnEnable() => CurrentUIState = UIState.Profile;
[HarmonyPatch(typeof(ResultsMenu), "OnEnable")]
[HarmonyPostfix]
private static void ResultsMenu_OnEnable() => CurrentUIState = UIState.Results;
[HarmonyPatch(typeof(LevelSelectMenu), "OnEnable")]
[HarmonyPostfix]
private static void LevelSelectMenu_OnEnable() => CurrentUIState = UIState.LevelSelect;
#endregion
#region Updating UI
[HarmonyPatch(typeof(IngameMenu), "GetInput")]
[HarmonyPrefix]
private static bool IngameMenu_GetInput() => EnableUIInput;
[HarmonyPatch(typeof(CharacterSelectMenu), "GetInput")]
[HarmonyPrefix]
private static bool CharacterSelectMenu_GetInput() => EnableUIInput;
[HarmonyPatch(typeof(TitleScreenMenu), "GetInput")]
[HarmonyPrefix]
private static bool TitleScreenMenu_GetInput() => EnableUIInput;
[HarmonyPatch(typeof(OptionsMenu), "GetInput")]
[HarmonyPrefix]
private static bool OptionsMenu_GetInput() => EnableUIInput;
[HarmonyPatch(typeof(ProfileMenu), "GetInput")]
[HarmonyPrefix]
private static bool ProfileMenu_GetInput() => EnableUIInput;
[HarmonyPatch(typeof(ResultsMenu), "GetInput")]
[HarmonyPrefix]
private static bool ResultsMenu_GetInput() => EnableUIInput;
[HarmonyPatch(typeof(LevelSelectMenu), "GetInput")]
[HarmonyPrefix]
private static bool LevelSelectMenu_GetInput() => EnableUIInput;
[HarmonyPatch(typeof(PauseMenu), "GetInput")]
[HarmonyPrefix]
private static bool PauseMenu_GetInput() => EnableUIInput;
#endregion
}
|
### Comparing functional presence and volume across each quadrat
### Created by Danielle Barnas
### Created on December 14, 2022
### Modified March 5, 2023
##### LOAD LIBRARIES #####
library(tidyverse)
library(here)
library(FD)
library(tripack) # Triangulation of Irregularly Spaced Data
library(geometry) # Mesh Generation and Surface Tessellation
library(matrixStats) # Functions that Apply to Rows and Columns of Matrices (and to Vectors)
library(patchwork)
library(PNWColors)
library(ggrepel)
library(pairwiseAdonis)
##### READ IN DATA #####
# rename CowTags with alphabetical lettering
alphatag <- read_csv(here("Data","CowTag_to_AlphaTag.csv"))
traits <- read_csv(here("Data", "Surveys","Distinct_Taxa.csv"))
comp <- read_csv(here("Data", "Surveys", "Species_Composition_2022.csv"))
meta <- read_csv(here("Data", "Full_Metadata.csv"))
shore <- read_csv(here("Data", "Shore_distance.csv")) %>% select(-Location)
chem <- read_csv(here("Data","Biogeochem", "Nutrients_Processed_All.csv")) %>%
filter(Season == "Dry") %>%
filter(Location == "Varari",
#CowTagID != "VSEEP" &
CowTagID != "V13") %>%
select(CowTagID, Parameters, CVSeasonal) %>%
pivot_wider(names_from = Parameters, values_from = CVSeasonal)
redchem <- chem %>% select(CowTagID, Phosphate_umolL, NN_umolL)
# have one df with the CV, mean, mediam, august, march, both data, look back at min and max values for pH and Silicate
# richness, % richness of community pool, and % volume of community pool
Fric <- read_csv(here("Data", "Sp_FE_Vol.csv"))
# PCoA axes of traits
fd.coord.sgd <- read.csv(here("Data","FE_4D_coord_dmb.csv"), row.names = 1) # class data.frame
# FE with trait groups
fes_traits.sgd <- read_csv(here("Data", "Distinct_FE.csv"))
# species abundances (%) wide format
myspecies <- read_csv(here("Data", "Species_Abundances_wide.csv"))
# species and functional entities
species_entities <- read_csv(here("Data", "Species_FE.csv"))
##### CLEAN AND ANALYSIS #####
comp <- comp %>%
filter(Location == "Varari") %>% # only analyze varari for now
filter(CowTagID != "V13")
# only cowtag ID's
quad.label <- chem %>%
#filter(Location == "Varari",
#CowTagID != "VSEEP",
#CowTagID != "V13") %>%
distinct(CowTagID)
mylongspecies <- myspecies %>%
pivot_longer(cols = 2:52, names_to = "Taxa", values_to = "pCover") %>%
left_join(meta) %>%
select(Location, CowTagID, Taxa, pCover)
# df with unique functional entities for each row
entity <- fes_traits.sgd
# CowTagIDs as factors, to be used as relative SGD identifiers along gradient
relative.sgd <- quad.label$CowTagID
## Percent Cover
# CowTagIDs as rownames
sgd.sp <- column_to_rownames(.data = myspecies, var = "CowTagID")
sgd.sp <- as.data.frame(sgd.sp)
## Plot convex hull (modified Teixido script)
### Bar plot
# order CowTagID's by distance from the seepage point
tagOrder <- meta %>%
filter(Location == "Varari",
#CowTagID != "VSEEP",
CowTagID != "V13") %>%
arrange(dist_to_seep_m) %>% # set arrange factor
select(CowTagID) %>%
left_join(alphatag)
# set cowtag order as arrange factor order
tagOrder <- tagOrder$AlphaTag[1:20] # exclude maya's sites
############################################# plot convex hull
# color palette assignment
cols <- pnw_palette("Bay",20,type="continuous")
cols <- rev(cols) # reverse color pattern so high sgd gets red
names(cols) <- tagOrder
# add raw richness values to Fric to put value above plot bars
Fric_rich <- Fric %>%
select(CowTagID, NbSp, NbFEs) %>%
rename(Sp = NbSp, FE = NbFEs) %>%
pivot_longer(cols = Sp:FE, names_to = 'Parameters', values_to = 'richness')
# change legend to show distances from seep values rather than survey location (or just remove?)
# Figure 1. Species and functional diversity changes along SGD gradient
# All volumes in distinct plots
p <- Fric %>%
left_join(alphatag) %>%
left_join(meta) %>%
select(Sp = NbSpP, FE = NbFEsP, Vol4D = Vol8D, AlphaTag) %>%
pivot_longer(cols = 1:3, names_to = "Parameters", values_to = "Values") %>%
mutate(AlphaTag = factor(AlphaTag)) %>%
mutate(Parameters = factor(Parameters, levels = c("Sp", "FE", "Vol4D"))) %>%
# plot facet_wrapped
ggplot(aes(x = Parameters, y = Values, fill = AlphaTag)) +
geom_col(color = "black") +
facet_wrap(~AlphaTag) +
theme_bw() +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 90),
legend.position = "none") +
ylim(0,100) +
scale_fill_manual(values = cols) +
labs(fill = "Survey Location", x = "", y = "Relative % of Community") +
geom_text(aes(x = Parameters, label = round(Values,0)),
size = 3, vjust = -0.4)
p
ggsave(here("Output", "PaperFigures", "Figure1barplot_distance.png"), p, width = 6, height = 5)
### Raw data figure for species and functional richness at each plot - before relative plot above (1a, 1b)
Richness <- Fric_rich %>%
pivot_wider(names_from = 'Parameters', values_from = 'richness')
# plot same format as above but raw richness values
richness_plot <- Richness %>%
left_join(alphatag) %>%
mutate(CowTagID = factor(AlphaTag)) %>%
pivot_longer(cols = 2:3, names_to = "Parameters", values_to = "Values") %>%
ggplot(aes(x = Parameters, y = Values, fill = AlphaTag)) +
geom_col(color = "black") +
facet_wrap(~AlphaTag) +
theme_bw() +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 90),
legend.position = "none") +
geom_text(aes(x = Parameters, label = Values),
size = 3, vjust = -0.4) +
scale_fill_manual(values = cols) +
labs(fill = "Survey Location", x = "", y = "Richness")
richness_plot
#ggsave(here("Output", "PaperFigures", "Raw_richness_CowTags.png"), richness_plot, width = 6, height = 5)
### Functional space using PCoA (modified Teixido script)
q <- list()
All.ch.tib <- tibble(x = as.numeric(),
y = as.numeric(),
CowTagID = as.character())
All.m.sgd <- tibble(PC1 = as.numeric(),
PC2 = as.numeric(),
PC3 = as.numeric(),
PC4 = as.numeric(),
CowTagID = as.character(),
FE = as.character())
# needs to be df before running for loop
species_entities <- as.data.frame(column_to_rownames(species_entities, var = 'Taxa'))
cowtagOrder <- alphatag %>%
arrange(AlphaTag) %>%
select(CowTagID)
cowtagOrder <- cowtagOrder$CowTagID[2:20] # removes seep
# residuals (~ meanRugositY)
# r.meta <- meta %>%
# filter(Location == "Varari", CowTagID != "VSEEP" & CowTagID != "V13") %>%
# select(CowTagID, meanRugosity)
# r.sgd.sp <- rownames_to_column(sgd.sp, var = "CowTagID") %>%
# left_join(r.meta) %>%
# pivot_longer(cols = 2:52, names_to = "species", values_to = "pcover") %>%
# mutate(rcover = pcover / meanRugosity)
for(i in cowtagOrder) {
tag = i # use for rbinding data below
species.sgd <- colnames(sgd.sp)[which(sgd.sp[i,] > 0)]
# only species present in each treatment
fes_cond.sgd <- species_entities[rownames(species_entities) %in% species.sgd, ]
m.sgd <- fd.coord.sgd[rownames(fd.coord.sgd) %in% fes_cond.sgd, ]
m.sgd <- data.matrix(m.sgd) # parse from data frame to matrix array
mid.m.sgd <- as_tibble(m.sgd) %>%
mutate(CowTagID = tag, FE = rownames(m.sgd))
All.m.sgd <- All.m.sgd %>% rbind(mid.m.sgd)
tr.sgd <- tri.mesh(m.sgd[,1],m.sgd[,2], duplicate = "remove") # duplicate: default = "error", "strip" = removes all duplicate points, "remove" = leaves one point of duplicate points
ch.sgd <- convex.hull(tr.sgd)
ch.tib <- cbind(ch.sgd$x, ch.sgd$y, ch.sgd$i) # parse as tibble df
colnames(ch.tib) <- c("x", "y", "i")
ch.tib <- as_tibble(ch.tib) %>%
select(x,y) %>%
mutate(CowTagID = tag)
All.ch.tib <- All.ch.tib %>% rbind(ch.tib)
}
# add VSEEP coordinates
seep.species.sgd <- colnames(sgd.sp)[which(sgd.sp['VSEEP',] > 0)] # select present species from seep
seep.fes_cond.sgd <- species_entities[rownames(species_entities) %in% seep.species.sgd, ]
seep.m.sgd <- fd.coord.sgd[rownames(fd.coord.sgd) %in% seep.fes_cond.sgd, ]
seep.mid.m.sgd <- as_tibble(seep.m.sgd) %>%
mutate(CowTagID = "VSEEP", FE = rownames(seep.m.sgd))
sub.ch.tib <- seep.mid.m.sgd %>%
select(CowTagID, x = PC1, y = PC2)
All.ch.tib <- All.ch.tib %>%
rbind(sub.ch.tib) %>%
left_join(alphatag) %>%
select(-CowTagID) %>%
mutate(AlphaTag = factor(AlphaTag))
All.m.sgd <- All.m.sgd %>%
rbind(seep.mid.m.sgd) %>%
left_join(alphatag) %>%
select(-CowTagID) %>%
mutate(AlphaTag = factor(AlphaTag))
# graph faceted polygons showing functional volume
qAll <- ggplot(data = All.ch.tib, aes(x = x, y = y)) +
geom_polygon(aes(fill = AlphaTag, color = AlphaTag), alpha = 0.5) + # create polygon using product of convex.hull(tri.mesh)
labs(x = "PCoA 1", y = "PCoA 2") +
geom_point(data = as_tibble(All.m.sgd), aes(x = PC1, y = PC2, color = AlphaTag)) +
theme_bw() +
theme(#legend.position = "none",
panel.grid = element_blank(),
panel.spacing = unit(1, "lines")) + # increase facet wrap panel spacing
scale_fill_manual(values = cols) +
scale_color_manual(values = cols) +
facet_wrap(~AlphaTag) +
xlim(min(fd.coord.sgd[,1]), max(fd.coord.sgd[,1])) + ylim(min(fd.coord.sgd[,2]), max(fd.coord.sgd[,2]))
qAll
# I want to view this on a map. Can I put polygons as map points?
#ggsave(here("Output", "PaperFigures", "Teixido_Figure1volume_dmb_CowTags.png"), qAll, width = 8, height = 5)
### COMBINE VOLUME FIGURE FROM Presence SCRIPT WITH ABOVE TO INCLUDE POLYGON
mypalette <- rev(pnw_palette(name = "Bay", n = 20))
alphapalette <- c(paste0(mypalette[1],"70"), paste0(mypalette[2],"70"), paste0(mypalette[3],"70"),
paste0(mypalette[4],"70"), paste0(mypalette[4],"70"), paste0(mypalette[6],"70"),
paste0(mypalette[7],"70"), paste0(mypalette[8],"70"), paste0(mypalette[9],"70"),
paste0(mypalette[10],"70"), paste0(mypalette[11],"70"), paste0(mypalette[12],"70"),
paste0(mypalette[13],"70"), paste0(mypalette[14],"70"), paste0(mypalette[15],"70"),
paste0(mypalette[16],"70"), paste0(mypalette[17],"70"), paste0(mypalette[18],"70"),
paste0(mypalette[19],"70"), paste0(mypalette[20], "70"))
#load data
ab.sgd <- read_csv(here("Data", "Species_Abundances_wide.csv"))
ab.sgd <- as.data.frame(column_to_rownames(ab.sgd, var = 'CowTagID')) # move tag names to rownames and make data.frame class
spe_fes.sgd <- as.data.frame(read_csv(here("Data", "Species_FE.csv")))
alphatag <- read_csv(here("Data","CowTag_to_AlphaTag.csv"))
################################## Data manipulation and arrangements
ab.conditions.sgd <- ab.sgd
################################# compute abundance of FEs for the three conditions
fes.sgd <- levels(as_factor(spe_fes.sgd$FE))
ab.conditions.sgd <- rownames_to_column(ab.conditions.sgd, var = "CowTagID")
ab.conditions.sgd2 <- ab.conditions.sgd %>%
pivot_longer(names_to = "Taxa", values_to = "pCover", cols = 2:ncol(ab.conditions.sgd)) %>%
left_join(spe_fes.sgd) %>%
group_by(CowTagID, FE) %>%
summarise(pCover = sum(pCover)) %>%
ungroup()
ab.conditions.sgd <- ab.conditions.sgd2 %>%
pivot_wider(names_from = FE, values_from = pCover)
######################
# Figure 2. Overall distribution of FE abundance across the functional space
names(alphapalette) <- alphatag$AlphaTag[1:20]
## relative abundance in ggplot
fig2.fd.sgd <- rownames_to_column(as.data.frame(fd.coord.sgd), var = "FE") %>%
full_join(ab.conditions.sgd2) %>%
left_join(alphatag) %>%
arrange(AlphaTag)
fig2b <- fig2.fd.sgd %>%
filter(pCover > 0) %>%
ggplot(aes(x = PC1, y = PC2)) +
geom_point(aes(size = pCover,
color = AlphaTag,
fill = AlphaTag),
shape = 21) + # shape of a fillable circle. lets us fill with alpha values
geom_polygon(data = All.ch.tib,
aes(x = x, y = y,
color = AlphaTag),
alpha = 0.5,
fill = NA) + # no fill on the polygon
labs(x = "PCoA1", y = "PCoA2") +
facet_wrap(~AlphaTag) +
theme_bw() +
theme(panel.grid = element_blank(),
legend.position = "none",
strip.background = element_rect(fill = "white")) +
scale_fill_manual(values = alphapalette) +
scale_color_manual(values = mypalette)
fig2b
ggsave(here("Output", "PaperFigures", "Plot_Vol_Abund_PCoA_distance.png"), fig2b, height = 5, width = 7)
## checking things with nyssa
# bring taxonomic group up to Phyla and rename group to Phyla
# normalize to rugosity and use residuals and check patterns above again
# model everything with and witout normalizing to rugosity and send nyssa a Rmd of paired relationships with response variables
# - normalized and not
# create a mega plot iwth all the variables for means and CV and min and max, etc. for reference
#
#
#
# ### View location of each functional entity:
# fd.coord.sgd.tibble <- as_tibble(rownames_to_column(as.data.frame(fd.coord.sgd))) %>%
# rename(FE = "rowname")
#
# FE_pca_plot <- fd.coord.sgd.tibble %>%
# ggplot(aes(x = PC1, y = PC2)) +
# geom_point() +
# geom_text_repel(aes(label = FE),
# size = 3) +
# theme_bw() +
# theme(panel.grid = element_blank())
# FE_pca_plot
# #ggsave(here("Output", "PaperFigures", "FE_pca_labeled.png"), FE_pca_plot, width = 10, height = 10)
#
#
# ## View functional trait faceted figures
# plot_fe_group_pcoa <- fd.coord.sgd.tibble %>%
# separate(FE, into = c('Taxonomic Group','Morphology','Calcification','Energetic Resource'),
# sep = ",", remove = F) %>%
# pivot_longer(cols = 'Taxonomic Group':'Energetic Resource', names_to = "Group", values_to = "Trait") %>%
# ggplot(aes(x = PC1, y = PC2)) +
# geom_point() +
# geom_text_repel(aes(label = Trait),
# size = 2,
# max.overlaps = 18) +
# theme_bw() +
# theme(panel.grid = element_blank()) +
# facet_wrap(~Group)
# plot_fe_group_pcoa
# #ggsave(here("Output", "PaperFigures", "FE_group_pcoa.png"), plot_fe_group_pcoa, width = 6, height = 6)
#
# ## pc1 is driven by energetic resource (autotrophs on the left, mixotrophs on the right, heterotrophs in the middle)
# ## let's also view some combinations to see what's driving pc2
# plot_fe_group_pcoa2 <- fd.coord.sgd.tibble %>%
# separate(FE, into = c('Taxon_Group', 'Morph', 'Calc', 'ER'),
# sep = ",", remove = F) %>%
# unite(Taxon_Group, Morph, col = "Taxon_Morph", remove = F) %>%
# unite(Taxon_Group, Calc, col = "Taxon_Calc", remove = F) %>%
# unite(Morph, Calc, col = "Morph_Calc", remove = F) %>%
# pivot_longer(cols = c('Taxon_Morph', 'Taxon_Calc', 'Morph_Calc'), names_to = "Group", values_to = "Trait") %>%
# rename('Taxonomic Group' = Taxon_Group,
# 'Morphology' = Morph,
# 'Calcification' = Calc,
# 'Energetic Resource' = ER) %>%
# ggplot(aes(x = PC1, y = PC2)) +
# geom_point() +
# geom_text_repel(aes(label = Trait),
# size = 3,
# max.overlaps = 18) +
# theme_bw() +
# theme(panel.grid = element_blank()) +
# facet_wrap(~Group)
# #plot_fe_group_pcoa2
#
#
# ### View representative species for each functional entity
# FE_representatives <- as_tibble(rownames_to_column(species_entities)) %>%
# rename(Species = "rowname") %>%
# left_join(fd.coord.sgd.tibble) %>%
# group_by(FE) %>%
# filter(row_number()==1)
#
# FE_reps_pca_plot <- FE_representatives %>%
# ggplot(aes(x = PC1, y = PC2)) +
# geom_point() +
# geom_text_repel(aes(label = Species),
# size = 3) +
# theme_bw() +
# theme(panel.grid = element_blank())
# FE_reps_pca_plot
# #ggsave(here("Output", "PaperFigures", "FE_pca_labeled_representatives.png"), FE_reps_pca_plot, width = 10, height = 10)
#
#
# ### Show all trait points possible as a blank diagram for visualization of full volume
#
# FE_pca_plot_allPoints <- fig2.fd.sgd %>%
# filter(pCover > 0) %>%
# filter(CowTagID == "V2") %>% # to show outline diagram of polygon and V2 hits every outer point
# ggplot(aes(x = PC1, y = PC2)) +
# geom_point() + # shape of a fillable circle. lets us fill with alpha values
# geom_polygon(data = All.ch.tib %>% filter(AlphaTag == "S"),
# aes(x = x, y = y),
# alpha = 0.5,
# fill = NA,
# color = "black") + # no fill on the polygon
# labs(x = "PCoA1", y = "PCoA2") +
# theme_bw() +
# theme(panel.grid = element_blank(),
# legend.position = "none",
# strip.background = element_rect(fill = "white"))
#
# FE_pca_plot_allPoints
# #ggsave(here("Output", "PaperFigures","Example_Polygon.png"), FE_pca_plot_allPoints, width = 6, height = 6)
#
# mylm <- fd.coord.sgd.tibble %>%
# separate(FE, into = c('Taxon_Group', 'Morph', 'Calc', 'ER'),
# sep = ",", remove = F)
# # unite(Taxon_Group, Morph, col = "Taxon_Morph", remove = F) %>%
# # unite(Taxon_Group, Calc, col = "Taxon_Calc", remove = F) %>%
# # unite(Morph, Calc, col = "Morph_Calc", remove = F) %>%
# #pivot_longer(cols = c('Taxon_Morph', 'Taxon_Calc', 'Morph_Calc'), names_to = "Group", values_to = "Trait")
# summary(lm(data = mylm,PC2 ~ Taxon_Group))
# summary(lm(data = mylm,PC2 ~ Morph))
#
#
# ## Can use the three values above (SpR, FER, Vol4D), and also community composition: either relative abundance or presence-absence
# ## then can do a permanova / nMDS of community comp with the volume / FErichness
#
#
#
# ### relative abundance
# FE_nmds_data <- myspecies %>%
# filter(CowTagID != "VSEEP") %>% # remove seep for nMDS for now
# pivot_longer(cols = Turf:'Caulerpa racemosa', names_to = "Taxa", values_to = "pCover") %>%
# filter(pCover > 0) %>%
# left_join(as_tibble(rownames_to_column(species_entities, var = "Taxa"))) %>%
# group_by(CowTagID, FE) %>% # get relative abundance of FE (pCvoer is already percent, so just add percentages of FE)
# mutate(pCoverFE = sum(pCover)) %>%
# distinct(CowTagID, FE, pCoverFE) %>%
# drop_na(FE) %>%
# pivot_wider(names_from = FE, values_from = pCoverFE) %>% # longform for the nmds and will establish absence through NAs
# mutate_at(vars(2:ncol(.)), .funs = ~if_else(is.na(.), 0, .)) # zero for NA's 1's for presence
# # will cbind cowtags later
# # set levels as numerical order of plates
# CTlevels <- c('V1','V2','V3','V4','V5','V6','V7','V8','V9','V10','V11','V12','V14','V15','V16','V17','V18','V19','V20')
# FE_nmds_data$CowTagID <- factor(FE_nmds_data$CowTagID, levels = CTlevels)
# # arrange by cowtag and then remove for nmds
# FE_nmds_data <- FE_nmds_data %>%
# arrange(CowTagID) %>%
# ungroup() %>%
# select(-CowTagID)
#
#
# ord1 <- metaMDS(FE_nmds_data, k=2, distance='bray')
#
# # stress with k=2 dimensions. Is it < 0.3?
# ord1$stress
#
# # stress plot - want to minimize scatter
# stressplot(ord1)
#
# #param_mds <- nMDS_species(ord1) # MDS1 and MDS2 for FEs
# # get points for species
# Group <- rownames(ord1$species) # get characteristic names
# MDS1 <- c(ord1$species[,1]) # MDS1 for characteristics
# MDS2 <- c(ord1$species[,2]) # MDS2 for characteristics
# Data <- as_tibble(cbind(Group, MDS1, MDS2)) %>% # bind all cols into tibble
# mutate(MDS1 = as.numeric(MDS1), # as numeric
# MDS2 = as.numeric(MDS2)) %>%
# #mutate(Taxon_Group = if_else(Taxa == "Hard Substrate", "Abiotic", Taxon_Group)) %>%
# select(MDS1, MDS2, Group)
#
#
# #param_mds_cat <- nMDS_points(ord1, meta, c('CowTagID', 'dist_to_seep_m')) # MDS1 and MDS2 for CowTagID
# Groupb <- as.character(CTlevels) # assign CowTagID
# MDS1b <- ord1$points[,1] # MDS1 for CowTagID
# MDS2b <- ord1$points[,2] # MDS2 for CowTagID
# Datab <- as_tibble(cbind(Groupb, MDS1b, MDS2b)) %>% # bind all cols into tibble
# mutate(MDS1b = as.numeric(MDS1b), # as numeric
# MDS2b = as.numeric(MDS2b)) %>%
# rename(CowTagID = Groupb)
#
# joinDF <- meta %>%
# select(CowTagID, dist_to_seep_m)
#
# Datab <- Datab %>%
# left_join(joinDF)
#
#
# ## plot
# nMDSplot <- ggplot(data = Data,
# aes(x = MDS1,
# y = MDS2)) +
# geom_point(color = "black") +
# geom_point(data = Datab,
# aes(x = MDS1b,
# y = MDS2b,
# color = (dist_to_seep_m)),
# size = 3) +
# geom_text_repel(data = Data, # site characteristics
# aes(x = MDS1,
# y = MDS2,
# label = Group),
# size = 2) +
# theme_bw() +
# theme(panel.grid = element_blank(),
# legend.position = "right") +
# geom_label_repel(data = Datab, # site characteristics
# aes(x = MDS1b,
# y = MDS2b,
# label = CowTagID),
# size = 5,
# max.overlaps = 16) + # increase from 10 because too many FEs overlapping
# scale_color_gradient(low = "red", high = "yellow")
# nMDSplot
#
# ggsave(here("Output", "PaperFigures", "FE_nmds_plot.png"), nMDSplot, width = 10, height = 10)
#
# ### PERMANOVA
# richPermFull <- cbind(Groupb, FE_nmds_data) %>% # bind cowTagIDs
# rename(CowTagID = Groupb) %>%
# left_join(joinDF) %>%
# mutate(relDist = if_else(dist_to_seep_m <= 26, "Near", if_else(dist_to_seep_m > 100, "Far", "Mid")))
#
# # dist < 26 > 100 ***0.001 V20, V17, V14 near vs mid 0.012, near vs far 0.045
# # dist < 47 > 100 **0.003 V20, V17, V14, V9 near vs mid 0.006
# # dist < 50 > 100 insignif. V20, V17, V14, V9, V10
#
# # dist < 26 > 120 **0.002 near vs mid 0.009
# # dist < 47 > 120 **0.001 near vs mid 0.021
#
# permanovamodel<-adonis2(richPermFull[,2:25]~relDist, richPermFull, permutations = 999,
# method="bray") # should change out cowtagid with some grouping name
# permanovamodel
#
# #If we are to trust the results of the permanova, then we have to assume that the dispersion among
# #data is the same in each group. We can test with assumption with a PermDisp test:
# disper<-vegdist(richPermFull[,2:25])
# betadisper(disper, richPermFull$relDist)
# #Look at the Average distance to median...these numbers should be reasonably similar
# #A rule of thumb is that one number should not be twice as high as any other
#
# pairwise.adonis(richPermFull[2:25], richPermFull$relDist, perm=999)
#
# #Get coefficients to see which species are most important in explaining site differences:
# #permanovamodel$coefficients
#
#
#
#
# #################################################################################
# #################################################################################
# #################################################################################
#
#
#
# ### Intersecting functional space using PCoA (modified Teixido script)
#
#
# # Supplementary Figure 1. Intersection of the three functional volumes among pH zones.
# # all volumes in 1 figure,
#
#
# r <- All.ch.tib %>%
# mutate(CowTagID = factor(CowTagID, levels = tagOrder)) %>% # if not already run above
# ggplot(aes(x = x, y = y)) +
# geom_polygon(aes(color = CowTagID, fill = CowTagID), alpha = 0.3) + # create polygon using product of convex.hull(tri.mesh)
# labs(x = "PCoA 1", y = "PCoA 2", fill = "Survey Location", color = "Survey Location") +
# geom_point(data = All.m.sgd, aes(x = PC1, y = PC2, color = CowTagID)) +
# theme_bw() +
# theme(panel.grid = element_blank()) +
# xlim(min(fd.coord.sgd[,1]), max(fd.coord.sgd[,1])) + ylim(min(fd.coord.sgd[,2]), max(fd.coord.sgd[,2])) +
# scale_color_manual(values = cols) +
# scale_fill_manual(values = cols)
# r
#
# ggsave(here("Output", "Teixido", "Teixido_S1_dmb_CowTags.png"), r, width = 6, height = 5)
#
#
#
# ## Null Model of Functional Richness among SGD zones
#
#
# ############### null model of Functional richness among pH zones
#
# sgd.sp <- data.matrix(sgd.sp) # replace ab.conditions - must be matrix class
#
# n_perm = 100
# min.relative.sgd <- relative.sgd[c(1:3,5,8:19)]
# Fric_perm <- lapply(min.relative.sgd, function (x) { # condition
#
# species.sgd <- colnames(sgd.sp)[which(sgd.sp[x,] > 0)] # ab.conditions
#
# perm <- sapply((1:n_perm), function (z) {
#
# species_entities$FE <- sample(species_entities$FE) # spe_fes
#
# fes_cond.sgd <- species_entities[rownames(species_entities) %in% species.sgd, ]
#
# m.sgd <- fd.coord.sgd[rownames(fd.coord.sgd) %in% fes_cond.sgd, ]
#
# ch.sgd <- convhulln(m.sgd, options = "FA")
#
# chg.sgd <- convhulln(fd.coord.sgd, options = "FA")
#
# c(length(species.sgd), length(species.sgd)/ncol(sgd.sp)*100, dim(m.sgd)[1], dim(m.sgd)[1]/dim(fd.coord.sgd)[1]*100, ch.sgd$vol/chg.sgd$vol*100)
#
# })#eo sapply
#
# rownames(perm) <- c("NbSp", "NbSpP", "NbFE", "NbFEP", "Vol")
#
#
# perm
#
# })#eo lapply
#
# names(Fric_perm) = min.relative.sgd # condition
#
#
#
# Fric_perm_Q <- lapply(Fric_perm, function (x) {
#
# rowQuantiles(x, probs=c(0.05, 0.95))
#
# })#eo lapply
#
#
#
# Fric = as.data.frame(Fric)
#
# Fric$lowerFE <- sapply(relative.sgd, function (x) { Fric_perm_Q[[x]][3,1] })#eo sapply # condition
# Fric$upperFE <- sapply(relative.sgd, function (x) { Fric_perm_Q[[x]][3,2] })#eo sapply
# Fric$lowerVol <- sapply(relative.sgd, function (x) { Fric_perm_Q[[x]][5,1] })#eo sapply
# Fric$upperVol <- sapply(relative.sgd, function (x) { Fric_perm_Q[[x]][5,2] })#eo sapply
# Fric$cond <- relative.sgd
# relative.sgd <- factor(relative.sgd, levels = tagOrder)
#
# Fric$cond <- as.factor(relative.sgd)
# levels(Fric$cond)
# colnames(Fric) <- c("NbSp", "NbSpP", "NbFE","NbFEP", "Vol8D", "lowerFE", "upperFE", "lowerVol", "upperVol", "cond")
#
#
# #Plot the null model
# #Supplementary Figure 2. Null model of functional richness (functional volume) among pH zones.
#
# tiff(filename="Output/Teixido/Figure_S2_dmb_CowTags.tif", height=10, width=10, units="cm", compression = c("lzw"), res=300, pointsize=8)
#
#
# s <- Fric %>%
# ggplot(aes(x = cond, y = Vol8D)) +
# geom_point(aes(color = cond), size = 3) +
# theme_bw() +
# theme(panel.grid = element_blank()) +
# scale_color_manual(values = cols) +
# labs(x = "Survey Locations", y = "Relative Richness (%)") +
# ylim(0,100) # set y axis scale
# s
#
# ggsave("Output/Teixido/Figure_S2_dmb_CowTags.png", s, width = 6, height = 5)
#
#
#
#
#
#
#
#
#
#
#
#
# ################################################ Convex Hull Intersect
#
# #load intersect function to compute convex hull (vertices + volume) of two set of points and their intersection
#
#
#
# # source(here("Scripts","Teixido","intersect.R"))
# #
# #
# # mat_int <- Fric <- lapply(relative.sgd, function (x) { # condition
# #
# # species <- colnames(sgd.sp)[which(sgd.sp[x,] > 0)] # ab.conditions
# #
# # fes_cond <- species_entities[rownames(species_entities) %in% species, ] # spe_fes
# #
# # m <- fd.coord.sgd[rownames(fd.coord.sgd) %in% fes_cond,]
# #
# # return(m)
# #
# # })#eo lapply
# #
# # names(mat_int) = relative.sgd # condition
# #
# # ###############intersect Low with Moderate
# #
# # Low_int_Mod <- CHVintersect(mat_int[["Low"]],mat_int[["Moderate"]])
# #
# # # percentage of the Moderate volume within Low
# # Low_int_Mod$vol[3]/Low_int_Mod$vol[2]
# #
# #
# #
# #
# # ###############intersect Low with High
# #
# # Low_int_High <- CHVintersect(mat_int[["Low"]],mat_int[["High"]])
# #
# # #pergcentage of the Extreme Low volume within Ambient
# # Low_int_High$vol[3]/Low_int_High$vol[2]
# #
# #
# #
# # ###############intersect Moderate with High
# #
# # Mod_int_High <- CHVintersect(mat_int[["Moderate"]],mat_int[["High"]])
# #
# # #percentage of the High volume within Low
# # Mod_int_High$vol[3]/Mod_int_High$vol[2]
# #
#
#
#
#
#
#
#
#
#
#
#
#
# ########################################### BETA DIVERSITY
#
# library('betapart')
#
#
# ###### taxonomic (Jaccard)
# sgd.sp[which(sgd.sp>0)] = 1 # ab.conditions
# bata.taxo <- beta.pair(sgd.sp, index.family="jaccard")
#
#
# ###### functional (Jaccard like)
#
# # Compute abundances of FEs for the three conditions
#
# # Load again the spe_fes matrix, 2 column variables
#
# #spe_fes <- read.csv2("Data_Species_FEs.csv", sep=";", dec=",")
# species_entities <- rownames_to_column(species_entities)
# colnames(species_entities) <- c("species", "FE")
# species_entities$FE <- as_factor(species_entities$FE)
#
#
#
# # tidy version of computing abundances of FE's for three conditions
# ab.fe.conditions <- sgd.sp %>%
# as_tibble(sgd.sp) %>%
# mutate(CowTagID = relative.sgd) %>% # effectively makes rownames a column
# relocate(CowTagID, .before = Turf) %>%
# pivot_longer(cols = 2:ncol(.), names_to = "species", values_to = "presence") %>%
# left_join(species_entities) %>%
# drop_na() %>% # for now removes cyanobacteria
# group_by(CowTagID, FE) %>%
# summarise(presence = sum(presence)) %>%
# mutate(presence = if_else(presence > 0, 1, 0), # binary for presence-absence
# FE = as.character(FE)) %>%
# ungroup() %>%
# pivot_wider(names_from = FE, values_from = presence)
#
# ab.fe.conditions <- column_to_rownames(ab.fe.conditions, var = "CowTagID")
#
#
# # true functional beta; essential: colnames(ab.fe.conditions) == rownames(fd.coord.sgd)
# beta.fun <- functional.beta.pair(data.matrix(ab.fe.conditions), fd.coord.sgd, index.family="jaccard")
#
# #######Plot categories of the 15 functional traits across the functional space
#
# #get data to plot the traits
# #]fes <- read.csv2("Data/Teixido/Data_FEs.csv", sep=",", dec=".", row.names=1)
# fes <- column_to_rownames(entity, var = "FE")
#
# #spe_fes <- read.csv2("Data/Teixido/Data_Species_FEs.csv", sep=";", dec=",", row.names=1)
# spe_fes <- column_to_rownames(species_entities, var = "species")
#
# ###### Supplementary Figure 6. Distribution of functional trait categories across the functional space
#
# tiff(filename="Output/Teixido/Figure_S6_dmb_CowTags.tif", height=20, width=30, units="cm", compression = c("lzw"), res=300, pointsize=10)
#
# ftr <- colnames(fes)
#
# par(mfrow=c(3,5))
#
# for (i in ftr) {
#
# lab <- as.factor(sort(unique(fes[,i])))
#
# plot(fd.coord.sgd[,1], fd.coord.sgd[,2], pch=16, cex=1.2, col = as.numeric(fes[,i]), xlim = c(-0.3, 0.7),
# main=gsub("."," ", i, fixed = T), xlab="PCoA 1", ylab="PCoA 2")
# legend(x=-0.25, y=0.2, legend=lab, pch=rep(16, length(lab)), col=as.numeric(as.factor(lab)), bty = "n")
#
# }
#
# dev.off()
#
#
#
#
#
#
#
# ########################################### VOLUME MAPPED ALONG REEF
#
# library(ggmap)
# library(maptools)
#
# # mean lat and long for the maps
# LocationGPS <- meta %>%
# filter(Location == "Varari",
# CowTagID != "V13") %>%
# group_by(Location) %>% # varari vs cabral
# summarise(lon = median(lon, na.rm = TRUE),
# lat = median(lat, na.rm = TRUE))
#
#
# VarariBaseMap <- get_map(LocationGPS %>% filter(Location == "Varari") %>% select(lon,lat), maptype = 'satellite', zoom = 19)
#
# VmapSites <- ggmap(VarariBaseMap) +
# geom_point(data = Full_data %>% filter(CowTagID != "V13"),
# aes(x = lon, y = lat),
# color = "white",
# size = 2) +
# labs(x = "Longitude", y = "Latitude", #label x and y axes
# title = "Varari Sample Locations") +
# geom_label(data = Full_data %>% filter(CowTagID != "V13"),
# aes(x = lon, y = lat,
# label = CowTagID),
# size = 1.5)
#
# VmapSites
#
#
# volSites <- VmapSites + ggplot(data = All.ch.tib, aes(x = x, y = y)) +
# geom_polygon(aes(fill = CowTagID, color = CowTagID), alpha = 0.5) + # create polygon using product of convex.hull(tri.mesh)
# labs(x = "PCoA 1", y = "PCoA 2") +
# geom_point(data = as_tibble(All.m.sgd), aes(x = PC1, y = PC2, color = CowTagID)) +
# theme_bw() +
# theme(panel.grid = element_blank()) +
# scale_fill_manual(values = cols) +
# scale_color_manual(values = cols) +
# facet_wrap(~CowTagID) +
# xlim(min(fd.coord.sgd[,1]), max(fd.coord.sgd[,1])) + ylim(min(fd.coord.sgd[,2]), max(fd.coord.sgd[,2]))
#
# #ggsave(here("Output","Teixido", "SiteMap_Volume.png"), volSites, width = 10, height = 9)
#
#
#
#
#
#
#
#
#
#
#
|
package taskmanager.tasks;
import java.time.LocalDateTime;
import java.util.Objects;
public class Task {
protected TaskType type;
protected int id = 0;
protected String name;
protected String description;
protected Status status;
protected long duration = 0;
protected LocalDateTime startTime;
public Task(String name, String description) {
this.name = name;
this.description = description;
this.status = Status.NEW;
this.type = TaskType.TASK;
}
public Task(String name, String description, long duration, LocalDateTime startTime) {
this.name = name;
this.description = description;
this.duration = duration;
this.startTime = startTime;
setStatus(Status.NEW);
setType(TaskType.TASK);
}
public Task(String name, String description, Status status, long duration, LocalDateTime startTime) {
this.name = name;
this.description = description;
this.status = status;
this.duration = duration;
this.startTime = startTime;
setType(TaskType.TASK);
}
public Task(int id, String name, String description, Status status, long duration, LocalDateTime startTime) {
this.id = id;
this.name = name;
this.description = description;
this.status = status;
this.duration = duration;
this.startTime = startTime;
type = getType();
}
public Task() {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Task task = (Task) o;
return id == task.id && duration == task.duration && type == task.type && Objects.equals(name, task.name) && Objects.equals(description, task.description) && status == task.status && Objects.equals(startTime, task.startTime);
}
@Override
public int hashCode() {
return Objects.hash(type, id, name, description, status, duration, startTime);
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public LocalDateTime getEndTime() {
if (startTime != null) {
return startTime.plusMinutes(duration);
}
return null;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public void setType(TaskType type) {
this.type = type;
}
public TaskType getType() {
return type;
}
public void createTime(long duration, LocalDateTime startTime) {
this.duration = duration;
this.startTime = startTime;
}
@Override
public String toString() {
String toString = Integer.toString(getId()) +
',' + getType() +
"," + name +
"," + status +
"," + description;
if (duration == 0) {
return toString + "," + duration + "," + null;
} else {
return toString + "," + duration + "," + startTime;
}
}
}
|
// Alon Filler 216872374
import java.util.Random;
import java.awt.Color;
/**
* Forced to create this JDOC due to checkstyles.
*/
public class ContainedBall extends Ball {
private Container container;
/**
* Random Ball constructor.
* @param r the radius of the Ball
* @param color the color of the Ball
* @param container the Container in which the Ball should reside
*/
public ContainedBall(int r, Color color, Container container) {
Random random = new Random();
this.setRadius(r);
this.setColor(color);
this.setVelocity(new Velocity());
this.container = new Container(container);
this.setCenter(
new Point(
random.nextInt(this.container.getWidth() + 1) + this.container.getTopLeft().getX(),
random.nextInt(this.container.getHeight() + 1) + this.container.getTopLeft().getY()
)
);
}
/**
* Constructor of the ContainedBall class.
* @param center the center of the ContainedBall
* @param radius the radius of the ContainedBall
* @param color the color of the ContainedBall
* @param container the Container inside which the ContainedBall is trapped
*/
public ContainedBall(Point center, int radius, Color color, Container container) {
super(center, radius, color);
this.container = new Container(container);
}
/**
* Determines whether the ContainedBall touches the Container vertically.
* @return true if they touch and false otherwise
*/
public boolean isTouchingContainerVertically() {
return (
ThresholdCompare.isThresholdBasedGreaterEqual(
this.getSize(),
this.getY() - this.container.getTopLeft().getY()
)
|| ThresholdCompare.isThresholdBasedGreaterEqual(
this.getSize(),
this.container.getBottomRight().getY() - this.getY()
)
);
}
/**
* Determines whether the ContainedBall touches the Container horizontally.
* @return true if they touch and false otherwise
*/
public boolean isTouchingContainerHorizontally() {
return (
ThresholdCompare.isThresholdBasedGreaterEqual(
this.getSize(),
this.getX() - this.container.getTopLeft().getX()
)
|| ThresholdCompare.isThresholdBasedGreaterEqual(
this.getSize(),
this.container.getBottomRight().getX() - this.getX()
)
);
}
/**
* moves the center Point one step.
*/
public void moveOneStep() {
if (this.isTouchingContainerVertically()) {
this.setVelocity(new Velocity(
this.getVelocity().getDx(),
-this.getVelocity().getDy()
));
}
if (this.isTouchingContainerHorizontally()) {
this.setVelocity(new Velocity(
-this.getVelocity().getDx(),
this.getVelocity().getDy()
));
}
this.setCenter(this.getVelocity().applyToPoint(this.getCenter()));
}
}
|
package com.myspeechy.myspeechy.modules
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.ktx.database
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.ktx.storage
import com.myspeechy.myspeechy.data.DataStoreManager
import com.myspeechy.myspeechy.data.authDataStore
import com.myspeechy.myspeechy.data.lesson.LessonDb
import com.myspeechy.myspeechy.data.lesson.LessonRepository
import com.myspeechy.myspeechy.data.loadData
import com.myspeechy.myspeechy.data.navBarDataStore
import com.myspeechy.myspeechy.data.notificationsDataStore
import com.myspeechy.myspeechy.data.themeDataStore
import com.myspeechy.myspeechy.domain.MeditationNotificationServiceImpl
import com.myspeechy.myspeechy.domain.auth.AuthService
import com.myspeechy.myspeechy.domain.chat.ChatsServiceImpl
import com.myspeechy.myspeechy.domain.chat.PrivateChatServiceImpl
import com.myspeechy.myspeechy.domain.chat.PublicChatServiceImpl
import com.myspeechy.myspeechy.domain.chat.UserProfileService
import com.myspeechy.myspeechy.domain.lesson.MainLessonServiceImpl
import com.myspeechy.myspeechy.domain.lesson.MeditationLessonServiceImpl
import com.myspeechy.myspeechy.domain.lesson.ReadingLessonServiceImpl
import com.myspeechy.myspeechy.domain.lesson.RegularLessonServiceImpl
import com.myspeechy.myspeechy.domain.meditation.MeditationStatsServiceImpl
import com.myspeechy.myspeechy.domain.useCases.CheckIfIsAdminUseCase
import com.myspeechy.myspeechy.domain.useCases.DecrementMemberCountUseCase
import com.myspeechy.myspeechy.domain.useCases.DeletePublicChatUseCase
import com.myspeechy.myspeechy.domain.useCases.JoinPublicChatUseCase
import com.myspeechy.myspeechy.domain.useCases.LeavePrivateChatUseCase
import com.myspeechy.myspeechy.domain.useCases.LeavePublicChatUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityRetainedComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Named
@Module
@InstallIn(ActivityRetainedComponent::class)
object ViewModelModule {
@Provides
fun provideLessonDb(@ApplicationContext context: Context): LessonDb {
return LessonDb.getDb(context)
}
@Provides
fun provideLessonRepository(db: LessonDb): LessonRepository {
return LessonRepository(db.lessonDao())
}
@Provides
@Named("AuthDataStore")
fun provideAuthDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.authDataStore
@Provides
fun provideDataStoreManager(@ApplicationContext context: Context): DataStoreManager {
return DataStoreManager(context.authDataStore, context.navBarDataStore, context.loadData,
context.themeDataStore,
context.notificationsDataStore,)
}
@Provides
fun provideMainLessonServiceImpl(): MainLessonServiceImpl {
return MainLessonServiceImpl(Firebase.firestore.collection("users"),
Firebase.auth)
}
@Provides
fun provideReadingLessonServiceImpl(): ReadingLessonServiceImpl {
return ReadingLessonServiceImpl(Firebase.firestore.collection("users"),
Firebase.auth)
}
@Provides
fun provideRegularLessonServiceImpl(): RegularLessonServiceImpl {
return RegularLessonServiceImpl(Firebase.firestore.collection("users"),
Firebase.auth)
}
@Provides
fun provideMeditationLessonServiceImpl(): MeditationLessonServiceImpl {
return MeditationLessonServiceImpl(Firebase.firestore.collection("users"),
Firebase.auth)
}
@Provides
fun provideMeditationStatsServiceImpl(): MeditationStatsServiceImpl {
return MeditationStatsServiceImpl(
Firebase.firestore,
Firebase.auth)
}
@Provides
fun provideChatsServiceImpl(): ChatsServiceImpl {
return ChatsServiceImpl(
Firebase.database.reference,
Firebase.auth,
provideLeavePrivateChatUseCase(),
provideLeavePublicChatUseCase(),
provideJoinPublicChatUseCase(),
provideCheckIfIsAdminUseCase(),
provideDeletePublicChatUseCase()
)
}
@Provides
fun providePublicChatServiceImpl(): PublicChatServiceImpl {
return PublicChatServiceImpl(
Firebase.auth,
Firebase.storage.reference,
Firebase.database.reference,
provideLeavePublicChatUseCase(),
provideDeletePublicChatUseCase(),
provideJoinPublicChatUseCase()
)
}
@Provides
fun providePrivateChatServiceImpl(): PrivateChatServiceImpl = PrivateChatServiceImpl(
Firebase.auth,
Firebase.storage.reference,
Firebase.database.reference,
provideLeavePrivateChatUseCase(),)
@Provides
fun provideCheckIfIsAdminUseCase(): CheckIfIsAdminUseCase = CheckIfIsAdminUseCase(Firebase.auth.currentUser?.uid, Firebase.database.reference)
@Provides
fun provideDeletePublicChatUseCase(): DeletePublicChatUseCase =
DeletePublicChatUseCase(Firebase.database.reference, DecrementMemberCountUseCase(Firebase.database.reference))
@Provides
fun provideJoinPublicChatUseCase(): JoinPublicChatUseCase = JoinPublicChatUseCase(Firebase.auth.currentUser?.uid, Firebase.database.reference)
@Provides
fun provideLeavePublicChatUseCase(): LeavePublicChatUseCase =
LeavePublicChatUseCase(Firebase.auth.currentUser?.uid, Firebase.database.reference, DecrementMemberCountUseCase(Firebase.database.reference))
@Provides
fun provideLeavePrivateChatUseCase(): LeavePrivateChatUseCase = LeavePrivateChatUseCase(Firebase.auth.currentUser?.uid, Firebase.database.reference)
@Provides
fun provideUserProfileServiceImpl(): UserProfileService =
UserProfileService(AuthService(Firebase.auth,
Firebase.database.reference,
Firebase.firestore, Firebase.storage.reference,
provideLeavePublicChatUseCase(),
provideLeavePrivateChatUseCase(),
provideCheckIfIsAdminUseCase(),
provideDeletePublicChatUseCase(),
))
@Provides
fun provideFilesDirPath(@ApplicationContext context: Context): String = context.cacheDir.path
@Provides
fun provideMeditationNotificationServiceImpl(@ApplicationContext context: Context):
MeditationNotificationServiceImpl = MeditationNotificationServiceImpl(context)
}
|
import { Link } from "react-router-dom"
import PropTypes from 'prop-types';
import './card.css'
const CategoryCard = (props) => {
const { avatar, lastName, firstName, phoneNumber, email, delet, edit, id } = props;
return (
<div className="card mb-4">
<img src={avatar} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title line-clamp">{lastName}</h5>
<p className="card-title line-clamp">{firstName}</p>
<p className="card-title line-clamp">{phoneNumber}</p>
<p className="card-title line-clamp">{email}</p>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "center"}}>
<Link to={`/categories/${id}`} className="btn btn-primary">
Go products {id}
</Link>
<Link className="btn btn-danger" onClick={delet}>
Delete
</Link>
</div><br />
<Link className="btn btn-primary" onClick={edit}>
Edit
</Link>
</div>
</div>
);
};
CategoryCard.propTypes = {
avatar: PropTypes.string,
lastName: PropTypes.string,
firstName: PropTypes.string,
phoneNumber: PropTypes.string,
email: PropTypes.string,
id: PropTypes.string,
delet: PropTypes.func.isRequired,
edit: PropTypes.func.isRequired,
};
export default CategoryCard
|
@model AirportАutomationWeb.Dtos.Flight.FlightCreateDto;
@{
ViewData["Title"] = "View";
}
@{
ViewBag.Title = "Create Flight";
}
@Html.AntiForgeryToken()
<h4>Create Flight</h4>
<hr />
<form asp-action="CreateFlight">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group pb-3">
<label asp-for="DepartureDate" class="control-label">Departure Date</label>
<input asp-for="DepartureDate" class="form-control" type="date" />
<span asp-validation-for="DepartureDate" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="AirlineId" class="control-label">Airline</label>
<select asp-for="AirlineId" class="form-control" id="airlineSelect"
onmousedown="if(this.options.length>6){this.size=10;}" onchange='this.size=0;' onblur="this.size=0;"></select>
<span asp-validation-for="AirlineId" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
<div class="form-group">
<input type="button" value="Load More" class="btn btn-primary" id="loadMoreButton" onclick="populateSelectFlight();" />
</div>
</div>
<div class="col-md-4">
<div class="form-group pb-3">
<label asp-for="DepartureTime" class="control-label">Departure Time</label>
<input asp-for="DepartureTime" class="form-control" type="time" />
<span asp-validation-for="DepartureTime" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DestinationId" class="control-label">Destination</label>
<select asp-for="DestinationId" class="form-control" id="destinationSelect"
onmousedown="if(this.options.length>6){this.size=10;}" onchange='this.size=0;' onblur="this.size=0;"></select>
<span asp-validation-for="DestinationId" class="text-danger"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<div class="mb-3 form-column-align">
</div>
<label asp-for="PilotId" class="control-label">Pilot</label>
<select asp-for="PilotId" class="form-control" id="pilotSelect"
onmousedown="if(this.options.length>6){this.size=10;}" onchange='this.size=0;' onblur="this.size=0;"></select>
<span asp-validation-for="PilotId" class="text-danger"></span>
</div>
</div>
</div>
</form>
@if (TempData["AlertMessage"] != null)
{
@await Html.PartialAsync("_AlertPartial", TempData)
}
@await Html.PartialAsync("_BackToListPartial")
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script src="~/js/FetchDataForFlight.js"></script>
}
|
import 'dart:io';
import 'package:databasesqflitcode/databasehelper.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
ElevatedButton(onPressed: () async{
int? i = await databaseHelper.instance.insert(
{'NAME':'kishore'}
);
print(i);
}, child: Text("insert")),
ElevatedButton(onPressed: () async{
List<Map<String, dynamic>>? row = await databaseHelper.instance.queryAll();
print(row);
}, child: Text("query")),
ElevatedButton(onPressed: ()async{
int? updateid = await databaseHelper.instance.update({'_id':3,'NAME':'hero'});
print(updateid);
}, child: Text("update")),
ElevatedButton(onPressed: ()async{
int? deleteid = await databaseHelper.instance.delete(3);
print(deleteid);
}, child: Text("delete")),
],
),
),
),
);
}
}
|
import {
CREATE_ELEMENT_VNODE,
TO_DISPLAY_STRING,
helperMapName,
} from "./runtimeHelpers";
import { NodeTypes } from "./ast";
import { isString } from "../../shared";
export function generate(ast) {
const context = createCodegenContext();
const { push } = context;
genFunctionPreamble(ast, context);
let functionName = "render";
const args = ["_ctx", "_cache"];
const signature = args.join(", ");
push(`function ${functionName}(${signature}){`);
push("return ");
genNode(ast.codegenNode, context);
push("}");
return {
code: context.code,
};
}
// 生成前导码
function genFunctionPreamble(ast: any, context) {
const { push } = context;
const VueBinging = "Vue";
const aliasHelper = (s) => `${helperMapName[s]}: _${helperMapName[s]}`;
if (ast.helpers.length > 0) {
push(
`const { ${ast.helpers.map(aliasHelper).join(", ")} } = ${VueBinging}`
);
}
push("\n");
push("return ");
}
function genNode(node: any, context) {
// 处理不同类型节点
switch (node.type) {
case NodeTypes.TEXT:
genText(node, context);
break;
case NodeTypes.INTERPOLATION:
genInterpolation(node, context);
break;
case NodeTypes.SIMPLE_EXPRESSION:
genExpression(node, context);
break;
case NodeTypes.ELEMENT:
genElement(node, context);
break;
case NodeTypes.COMPOUND_EXPRESSION:
genCompoundExpression(node, context);
default:
break;
}
}
function genCompoundExpression(node, context) {
console.log("compound", node, context);
const { push } = context;
const children = node.children;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (isString(child)) {
push(child);
} else {
genNode(child, context);
}
}
}
function genElement(node, context) {
const { push, helper } = context;
const { tag, children, props } = node;
push(`${helper(CREATE_ELEMENT_VNODE)}(`);
genNodeList(genNullable([tag, props, children]), context);
// genNode(children, context);
push(")");
}
function genNodeList(nodes, context) {
const { push } = context;
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (isString(node)) {
push(node);
} else {
genNode(node, context);
}
if (i < nodes.length - 1) {
push(", ");
}
}
}
function genNullable(args: any) {
return args.map((arg) => arg || "null");
}
function genText(node: any, context: any) {
const { push } = context;
push(`'${node.content}'`);
}
function createCodegenContext() {
const context = {
code: "",
push(source) {
context.code += source;
},
// 辅助函数,获取key对应的字符串,并在前面加下划线_
helper(key) {
return `_${helperMapName[key]}`;
},
};
return context;
}
// 生成插值字符串
function genInterpolation(node: any, context: any) {
const { push, helper } = context;
push(`${helper(TO_DISPLAY_STRING)}(`);
// 处理插值内部的表达式节点
genNode(node.content, context);
push(")");
}
// 生成表达式字符串
function genExpression(node: any, context: any) {
const { push } = context;
push(`${node.content}`);
}
|
import os
import random
import torch
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
# Set Seed
def seed_torch(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
# log string
def log_string(log, string):
log.write(string + '\n')
log.flush()
print(string)
# metric
def metric(pred, label, masked: bool):
with np.errstate(divide = 'ignore', invalid = 'ignore'):
mask = np.not_equal(label, 0)
mask = mask.astype(np.float32)
mask /= np.mean(mask)
mae = np.abs(np.subtract(pred, label)).astype(np.float32)
rmse = np.square(mae)
mape = np.divide(mae, label)
if masked:
mae = np.nan_to_num(mae * mask)
mae = np.mean(mae)
if masked:
rmse = np.nan_to_num(rmse * mask)
rmse = np.sqrt(np.mean(rmse))
mape = np.nan_to_num(mape * mask)
mape = np.mean(mape)
return mae, rmse, mape
def seq2instance_TE(data, P, Q):
num_step, dims = data.shape
num_sample = num_step - P - Q + 1
x = np.zeros(shape = (num_sample, P, dims))
y = np.zeros(shape = (num_sample, Q, dims))
for i in range(num_sample):
x[i] = data[i : i + P]
y[i] = data[i + P : i + P + Q]
return x, y
def seq2instance(data, P, Q):
# print(data.shape)
num_step, nodes, dims = data.shape
num_sample = num_step - P - Q + 1
x = np.zeros(shape = (num_sample, P, nodes, dims))
y = np.zeros(shape = (num_sample, Q, nodes, 1))
for i in range(num_sample):
x[i] = data[i : i + P]
tmp = data[i + P : i + P + Q,:,0]
tmp = tmp.reshape(tmp.shape + (1,))
y[i] = tmp
return x, y
def loadData(args):
# Traffic
if args.dataset in {'PeMS04', 'PeMS08', 'Loop'}:
df = np.load(args.traffic_file, allow_pickle=True)
Traffic = df['data']
else:
df = pd.read_hdf(args.traffic_file)
Traffic = df.values
# train/val/test
num_step = Traffic.shape[0]
train_steps = round(args.train_ratio * num_step)
test_steps = round(args.test_ratio * num_step)
val_steps = num_step - train_steps - test_steps
train = Traffic[: train_steps]
val = Traffic[train_steps : train_steps + val_steps]
test = Traffic[-test_steps :]
# X, Y
trainX, trainY = seq2instance(train, args.P, args.Q)
valX, valY = seq2instance(val, args.P, args.Q)
testX, testY = seq2instance(test, args.P, args.Q)
# normalization
mean, std = np.mean(trainX,axis=(0,1,2),keepdims=True), np.std(trainX, axis=(0,1,2), keepdims=True)
trainX = (trainX - mean) / std
valX = (valX - mean) / std
testX = (testX - mean) / std
mean, std = mean[0,0,0,0], std[0,0,0,0]
# spatial embedding
f = open(args.SE_file, mode = 'r')
lines = f.readlines()
temp = lines[0].split(' ')
N, dims = int(temp[0]), int(temp[1])
SE = np.zeros(shape = (N, dims), dtype = np.float32)
for line in lines[1 :]:
temp = line.split(' ')
index = int(temp[0])
SE[index] = temp[1 :]
# temporal embedding
if args.dataset in {'PeMS04', 'PeMS08'}:
start_time = datetime(
2016, 7, 1, 0, 0, 0) if args.dataset == 'PeMS08' else datetime(2018, 1, 1, 0, 0, 0)
Time = [start_time + i * timedelta(minutes=5) for i in range(num_step)]
Time = pd.to_datetime(Time)
elif args.dataset == 'Loop':
Time = df['time']
Time = pd.to_datetime(Time)
else:
Time = df.index
dayofweek = np.reshape(Time.weekday, newshape = (-1, 1))
timeofday = (Time.hour * 3600 + Time.minute * 60 + Time.second) \
// (300.0) # (<5 * Minutes>.total_seconds()) # Time.freq.delta.total_seconds()
timeofday = np.reshape(timeofday, newshape = (-1, 1))
# Time Series 6&8
Peri_72 = timeofday//72
Peri_96 = timeofday//96
Peri_144 = timeofday//144
Time = np.concatenate((dayofweek, timeofday, Peri_72, Peri_96, Peri_144), axis = -1)
# train/val/test
train = Time[: train_steps]
val = Time[train_steps : train_steps + val_steps]
test = Time[-test_steps :]
# shape = (num_sample, P + Q, 2)
trainTE = seq2instance_TE(train, args.P, args.Q)
trainTE = np.concatenate(trainTE, axis = 1).astype(np.int32)
valTE = seq2instance_TE(val, args.P, args.Q)
valTE = np.concatenate(valTE, axis = 1).astype(np.int32)
testTE = seq2instance_TE(test, args.P, args.Q)
testTE = np.concatenate(testTE, axis = 1).astype(np.int32)
return (trainX, trainTE, trainY, valX, valTE, valY, testX, testTE, testY,
SE, mean, std)
|
/// <reference types="cypress" />
// ***********************************************
// This example commands.ts shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
Cypress.Commands.add('login', () => {
const url = Cypress.env('FRONT_URL')
cy.visit(`${url}admin`)
cy.get('#email').should('exist')
cy.get('#email').type('[email protected]')
cy.get('#email').should('have.value', '[email protected]')
cy.get('#password').should('exist')
cy.get('#password').type('c2BhhMk?48+BDt9q')
cy.get('#password').should('have.value', 'c2BhhMk?48+BDt9q')
cy.get('button[type=submit]').should('be.enabled')
cy.get('button[type=submit]').click()
})
Cypress.Commands.add('dataCy', (value: string) => {
return cy.get(`[data-cy=${value}]`)
})
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import streamlit as st
# pip install konlpy WordCloud
from konlpy.tag import Okt
from collections import Counter
from wordcloud import WordCloud
# 멀티 페이지용 제목
st.set_page_config(page_title='Hello, textmining',
page_icon='📑')
st.sidebar.header('Hello, textmining!📑')
st.title('텍스트마이닝 시각화 📑')
# 폰트 및 형태소 분석기 초기화
fontpath = 'c:/Windows/Fonts/malgun.ttf'
twitter = Okt()
with open('./data/trump_ko.txt', encoding='utf-8') as f:
tdocs = f.read()
with open('./data/stevejobs_ko.txt', encoding='utf-8') as f:
sdocs = f.read()
option1 = st.selectbox('워드 클라우드할 텍스르를 선택하세요',
['도람프 연설문', '스티브 잡스 연설문'])
docs = tdocs if option1 == '도람프 연설문' else sdocs
st.write(docs[:300])
# 워드 클라우드 시각화1
tokens = twitter.nouns(docs)
words = [t for t in tokens if len(t) > 1]
with st.spinner('워드클라우드 생성중...'):
wc = Counter(words)
wc = dict(wc.most_common()) # 가장 많은 순으로 정렬
wcimg = WordCloud(font_path=fontpath, background_color='white',
width=640, height=480).generate_from_frequencies(wc)
fig = plt.figure()
ax = plt.imshow(wcimg, interpolation='bilinear')
plt.axis('off')
st.pyplot(fig)
# 워드 클라우드 시각화2
|
import React from "react";
import {
ChakraProvider,
Center,
VStack,
useToast,
Alert,
AlertIcon,
AlertTitle,
AlertDescription,
Text,
Link,
Heading,
Fade,
SlideFade,
} from "@chakra-ui/react";
import Ipfs from "ipfs";
import FileUploader from "./components/fileUpload";
import GlobalContext, { initialState, reducer } from "./context/globalContext";
import { ethers } from "ethers";
import Onboard from "bnc-onboard";
import WalletDisplay from "./components/walletDisplay";
import GithubCorner from "react-github-corner";
import { GLOBALS } from "./helpers/globals";
let web3: ethers.providers.Web3Provider;
function App() {
const [state, dispatch] = React.useReducer(reducer, initialState);
const toast = useToast();
const startUp = async () => {
try {
//@ts-ignore
let ipfs = await Ipfs.create({
relay: { enabled: true, hop: { enabled: true, active: true } },
});
dispatch({ type: "START_IPFS", payload: { ipfs: ipfs } });
} catch (error) {
console.error("IPFS init error:", error);
}
};
React.useEffect(() => {
startUp();
}, []);
const wallets = [
{ walletName: "metamask", preferred: true },
{ walletName: "trust", preferred: true },
{ walletName: "torus" },
{ walletName: "opera" },
{ walletName: "operaTouch" },
];
const onboard = Onboard({
networkId: state?.chain ? state.chain : 42,
subscriptions: {
wallet: (wallet) => {
try {
//@ts-ignore
if (window.ethereum) {
//@ts-ignore
window.ethereum.enable();
}
web3 = new ethers.providers.Web3Provider(wallet.provider);
dispatch({ type: "SET_WEB3", payload: { web3: web3 } });
} catch (err) {
console.log(err);
toast({
position: "top",
status: "error",
title: "Something went wrong",
description: err?.toString(),
duration: 5000,
});
}
},
address: (address) => {
dispatch({ type: "SET_ADDRESS", payload: { address: address } });
},
balance: (balance) => {
dispatch({ type: "SET_BALANCE", payload: { balance: balance } });
},
network: (network) => {
dispatch({ type: "SET_CHAIN", payload: { chain: network } });
},
},
walletSelect: {
wallets: wallets,
},
});
const handleConnect = async () => {
dispatch({ type: "SET_ONBOARD", payload: { onboard: onboard } });
try {
const walletSelected = await onboard.walletSelect();
} catch (err) {
console.log(err);
toast({
position: "top",
status: "error",
title: "Something went wrong",
description: err?.toString(),
duration: 5000,
});
}
};
return (
<ChakraProvider>
<GlobalContext.Provider value={{ dispatch, state }}>
<GithubCorner
href="https://github.com/acolytec3/signpost"
bannerColor="#000"
octoColor="#fff"
size={80}
direction="left"
/>
<Center h="90vh">
<VStack>
<Heading>SignPost</Heading>
<Text size="xs" mb="2em">Sign your NFT</Text>
<WalletDisplay handleConnect={handleConnect} />
<SlideFade in={state.web3 !== undefined}>
<FileUploader />
</SlideFade>
</VStack>
</Center>
{!state.web3 && <Alert status="info">
<AlertIcon />
<AlertDescription>
<Text>
Click{" "}
<Link
href="https://github.com/acolytec3/signpost/blob/master/README.md#usage"
color="teal.500"
>
here
</Link>{" "}
for usage instructions
</Text>
</AlertDescription>
</Alert>}
{state.chain && Object.keys(GLOBALS.CHAINS).filter(
(chainId) => chainId === state.chain.toString()
).length < 1 && (
<Alert status="error">
<AlertIcon />
<AlertTitle mr={2}>Unsupported network</AlertTitle>
<AlertDescription>
Please switch to a supported network before continuing.
</AlertDescription>
</Alert>
)}
</GlobalContext.Provider>
</ChakraProvider>
);
}
export default App;
|
import { Typography } from "@mui/material";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { Status } from "../../lib/status";
const theme = createTheme();
theme.typography.body1 = {
fontSize: "1rem",
"@media (min-width:350px)": {
fontSize: "2rem",
},
};
export default function GridSquare({
value,
status = "DEFAULT",
}: Status): JSX.Element {
const styles = {
display: "inline-flex",
flex: 1,
justifyContent: "center",
alignItems: "center",
fontWeight: "bold",
border: "",
backgroundColor: "",
color: "white",
minWidth: "20px",
};
if (status === "CORRECT") {
styles.backgroundColor = "#6aaa64";
styles.border = "";
} else if (status === "PRESENT") {
styles.backgroundColor = "#c9b458";
} else if (status === "INCORRECT") {
styles.backgroundColor = "#939598";
} else if (status === "FAKE") {
styles.backgroundColor = "#de1c18";
} else {
styles.border = "solid 2px #d3d6da";
styles.color = "black";
}
return (
<div style={styles}>
<ThemeProvider theme={theme}>
<Typography variant="body1">{value}</Typography>
</ThemeProvider>
</div>
);
}
|
***This QUERY extracts a completed Rental Summary, including Statistical analyses
regarding revenues, durations, and using timestamps instead from the Data set to gain reliability in our results.***
SELECT COUNT(A.rental_id) AS num_of_transactions,
COUNT(DISTINCT B.film_id) AS num_films,
-- Calculating rental duration
MIN(A.return_date - A.rental_date) AS min_rental_duration,
MAX(A.return_date - A.rental_date) AS max_rental_duration,
-- Rental duration Days, format: Numeric with decimals. 1 day = 86400 seconds
AVG(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400) AS avg_rental_duration_days_numeric,
MIN(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400) AS min_rental_duration_days_numeric,
MAX(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400) AS max_rental_duration_days_numeric,
SUM(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400) AS sum_rental_duration_days_numeric,
-- Using extract to calc and retrieve the revenue
AVG(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400 * D.rental_rate) AS avg_film_revenue,
MIN(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400 * D.rental_rate) AS min_film_revenue,
MAX(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400 * D.rental_rate) AS max_film_revenue,
SUM(EXTRACT(EPOCH FROM (A.return_date - A.rental_date)) / 86400 * D.rental_rate) AS total_revenue,
COUNT(DISTINCT D.rental_rate) AS num_of_rates,
AVG(D.rental_rate) AS avg_rate,
MIN(D.rental_rate) AS min_rate,
MAX(D.rental_rate) AS max_rate
FROM rental A
INNER JOIN inventory B ON A.inventory_id = B.inventory_id
INNER JOIN store C ON B.store_id = C.store_id
INNER JOIN film D ON B.film_id = D.film_id
|
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Profile } from "../components/Profile/Profile/Profile";
import { openEditModal, userUnfollow } from "../store/actions";
import { EditProfile } from "../components/EditProfile/EditProfile";
export function ProfilePage() {
const userData = useSelector(state => state.userData.userData);
const isEditModalOpen = useSelector(state => state.modal.isEditModal);
const isFollow = useSelector(state => state.userData.followData.userFollow);
const dispatch = useDispatch();
useEffect(() => {
dispatch(userUnfollow());
}, [isFollow]);
return (
<>
<Profile buttonText="Edit profile"
image={userData.image}
background={userData.background}
name={userData.name}
userName={userData.userName}
date={userData.date}
address={userData.address}
followings={userData.followings}
followers={userData.followers}
userId={userData.userId}
btnClick={() => dispatch(openEditModal())}
/>
{isEditModalOpen &&
(<EditProfile name={userData.name} userId={userData.userId} address={userData.address}
image={userData.image} background={userData.background} birthday={userData.birthday}/>)
}
</>
);
}
|
import React, { Component } from "react";
import CardList from "../components/CardList";
import SearchBox from '../components/SearchBox.js'
import './App.css'
import Scroll from '../components/Scroll.js'
class App extends Component {
constructor() {
super()
this.state = {
robots: [],
searchField: ''
};
};
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => { return response.json() })
.then(users => this.setState({ robots: users }))
}
onSearch = (event) => {
this.setState({ searchField: event.target.value })
}
render() {
const {robots,searchField} = this.state;
const filteredRobots = robots.filter(robot => {
return robot.name.toLowerCase().includes(searchField.toLowerCase())
});
return !robots.length ? (<h1>LOADING</h1>) :
<div className="tc">
<h1 className="f-headline ">RoboFriends</h1>
<SearchBox onSearchChange={this.onSearch} />
<Scroll>
<CardList robots={filteredRobots} />
</Scroll>
</div>
}
}
export default App;
|
<template>
<div
class="p-4"
:class="[colorValue,widthValue,radiusStyle,{'border-2' : border},'relative']">
<!--Card Title-->
<div :class="['font-bold text-xl',$slots.hasOwnProperty('subTitle') ? '' : 'pb-2']">
<slot name="title"></slot>
</div>
<!--Card Subtitle-->
<div class="text-sm pb-2">
<slot name="subTitle"></slot>
</div>
<!--Separator-->
<hr v-if="line" :class="'my-1 border border-'+color+'-300'"/>
<div
v-if="$slots.secondContent"
class="content-card-show-button"
@click="showSecondContent = ! showSecondContent" >
<font-awesome-icon icon="code" />
</div>
<div class="flex flex-wrap">
<!--Card Main Content-->
<slot v-if="!showSecondContent" name="content"></slot>
<!--Card Second Content-->
<slot v-if="showSecondContent" name="secondContent"></slot>
</div>
</div>
</template>
<script>
import {radiusSize} from "@/mixins/radiusSizeMixin";
export default {
name: "ContentCard",
props: ['color', 'width', 'line', 'radius', 'border'],
mixins : [radiusSize],
data() {
return {
showSecondContent : false,
}
},
computed: {
colorValue() {
if (this.color === 'red') {
return 'bg-red-200 border-red-500';
} else if (this.color === 'blue') {
return 'bg-blue-200 border-blue-500';
} else if (this.color === 'indigo') {
return 'bg-indigo-200 border-indigo-500';
} else if (this.color === 'yellow') {
return 'bg-yellow-200 border-yellow-500';
} else if (this.color === 'green') {
return 'bg-green-200 border-green-500';
} else if (this.color === 'gray') {
return 'bg-gray-200 border-gray-500';
} else if (this.color === 'black') {
return 'bg-gray-700 border-black text-gray-200';
} else {
return 'bg-white'
}
},
widthValue() {
if (this.width != null) {
return 'col-span-12 lg:col-span-' + this.width;
} else {
return 'col-span-12'
}
}
}
}
</script>
|
import React, { Component } from 'react';
// import { Container } from './App.styled';
import { Section } from '../components/Section/Section';
import { FeedbackOptions } from '../components/FeedbackOptions/FeedbackOptions';
import { Statistics } from '../components/Statistics/Statistics';
import { Notification } from '../components/Notification/Notification';
export class App extends Component {
state = {
good: 0,
neutral: 0,
bad: 0,
};
onLeaveFeedback = option => {
this.setState(prevState => {
return {
[option]: prevState[option] + 1,
};
});
};
countTotalFeedback = () => {
const { good, neutral, bad } = this.state;
return good + neutral + bad;
};
countPositiveFeedbackPercentage = () => {
const { good, neutral, bad } = this.state;
return Math.round((good / (good + neutral + bad)) * 100);
};
render() {
const { good, neutral, bad } = this.state;
return (
<div>
<Section title={'Please leave your feedback'}>
<FeedbackOptions
options={Object.keys(this.state)}
onLeaveFeedback={this.onLeaveFeedback}
/>
</Section>
<Section title={'Statistics'}>
{good + neutral + bad > 0 ? (
<Statistics
good={good}
neutral={neutral}
bad={bad}
total={this.countTotalFeedback}
positivePercentage={this.countPositiveFeedbackPercentage}
></Statistics>
) : (
<Notification message="There is no feedback"></Notification>
)}
</Section>
</div>
);
}
}
|
<script>
import {ref} from 'vue'
import router from "@/router"
import { ElMessage } from 'element-plus'
export default {
created(){
this.getInfo()
},
methods: {
formatId(row) {
return row.id.toString().padStart(9, '0');
},
getInfo() {
fetch(`http://127.0.0.1:8000/borrowRecord/${localStorage.getItem('account')}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok")
}
return response.json()
})
.then(borrowRecords => {
console.log(borrowRecords) // 输出获取到的信息
this.borrowRecord=borrowRecords
})
.catch(error => {
console.error(`Error fetching book: ${error.message}`)
// 在这里处理请求出错的情况
})
},
returnBook(id){
fetch('http://127.0.0.1:8000/returnBook', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
book_id: id,
account: localStorage.getItem('account')
}),
})
.then(response => response.json())
.then(data => {
// 处理借书成功或失败的情况
if (data.message === '归还成功') {
console.log('还书成功');
ElMessage.success("还书成功");
// 在这里执行相关操作,例如更新页面状态等
this.getInfo()
} else {
ElMessage.error("归还失败");
console.log('还书失败');
// 在这里执行相关操作,例如显示错误信息等
}
})
.catch(error => {
console.error('还书请求出错', error);
ElMessage.error("还书失败");
// 在这里处理请求出错的情况
});
}
},
data(){
return{
borrowRecord:ref[
{
id:'0',
title:'0'
}
],
}
}
};
</script>
<template>
<el-table :data="borrowRecord" height="500" border style="width: 100%" :default-sort="{ prop: 'id', order: 'ascending' }">
<el-table-column
sortable
prop="id"
label="图书编号"
label-align="center"
align="center"
:formatter="formatId"
/>
<el-table-column
prop="title"
label="书名"
label-align="center"
align="center"
/>
<el-table-column fixed="right" label="操作" width="120" label-align="center" align="center">
<template #default="scope">
<el-button
link
type="primary"
size="small"
@click.prevent="returnBook(scope.row.id)"
>
还书
</el-button>
</template>
</el-table-column>
</el-table>
</template>
<style scoped>
</style>
|
<?php
namespace App\Form;
use App\Entity\Utilisateur;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UtilisateurType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('nom')
->add('prenom')
->add('dateNaissance')
->add('telephone')
->add('email')
->add('mdp')
->add('sexe',ChoiceType::class,[
'choices'=>[
'Homme'=>'homme',
'Femme'=>'femme'
]
])
->add('domaine')
->add('niveau')
->add('specialite')
->add('role',ChoiceType::class,[
'choices'=>[
'Étudiant'=>'Etudiant',
'Enseigant'=>'enseignant'
]
])
->add('Inscrire',SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Utilisateur::class,
]);
}
}
|
import React from 'react';
import Alert from '@mui/material/Alert';
import AppleIcon from '@mui/icons-material/Apple';
function FourApp(props) {
//배열변수 선언
const names=['영환','성경','호석','민규','성신','형준'];
//반복문을 변수에 저장후 출력해도 된다
const nameList = names.map((name)=>(<li>{name}</li>))
//색상을 5개 배열로 주시고 결과물을 div로 출력하세요(box로 className 주고할것)
const color = ['red', 'green', 'blue', 'yellow', 'violet'];
return (
<div>
<h3 className={'alert alert-info'}>FourApp입니다</h3>
<Alert severity="error">배열연습<AppleIcon/></Alert>
<div>
<h3>map연습</h3>
<ol>
{
names.map((name,index) =>(<b style={{marginLeft:'10px'}}>{index}:{name}</b>))
}
</ol>
<ol>
{nameList}
</ol>
</div>
<hr/>
<Alert severity="success">과제_배열색상 가로로 출력하기</Alert>
{
color.map((color)=>(<div className="box" style={{backgroundColor:color, width:'100px'
,height:'100px',float:'left'}}></div>))
}
</div>
);
}
export default FourApp;
|
#include <graaflib/graph.h>
#include <gtest/gtest.h>
#include <utils/fixtures/fixtures.h>
#include <type_traits>
#include <utility>
namespace graaf {
template <typename T>
struct WeightedGraphTest : public testing::Test {
using graph_t = typename T::first_type;
using edge_t = typename T::second_type;
};
TYPED_TEST_SUITE(WeightedGraphTest, utils::fixtures::weighted_graph_types);
TYPED_TEST(WeightedGraphTest, AddWeightedEdge) {
// GIVEN
using graph_t = typename TestFixture::graph_t;
using edge_t = typename TestFixture::edge_t;
using weight_t = decltype(get_weight(std::declval<edge_t>()));
graph_t graph{};
const auto vertex_id_1{graph.add_vertex(10)};
const auto vertex_id_2{graph.add_vertex(20)};
// WHEN
graph.add_edge(vertex_id_1, vertex_id_2, edge_t{static_cast<weight_t>(3)});
// THEN
ASSERT_TRUE(graph.has_edge(vertex_id_1, vertex_id_2));
ASSERT_EQ(get_weight(graph.get_edge(vertex_id_1, vertex_id_2)),
static_cast<weight_t>(3));
}
template <typename T>
struct UnitWeightedGraphTest : public testing::Test {
using graph_t = typename T::first_type;
using edge_t = typename T::second_type;
};
TYPED_TEST_SUITE(UnitWeightedGraphTest,
utils::fixtures::unit_weighted_graph_types);
TYPED_TEST(UnitWeightedGraphTest, AddUnitWeightedEdge) {
// GIVEN
using graph_t = typename TestFixture::graph_t;
using edge_t = typename TestFixture::edge_t;
using weight_t = decltype(get_weight(std::declval<edge_t>()));
graph_t graph{};
const auto vertex_id_1{graph.add_vertex(10)};
const auto vertex_id_2{graph.add_vertex(20)};
// WHEN
graph.add_edge(vertex_id_1, vertex_id_2, edge_t{});
// THEN
ASSERT_TRUE(graph.has_edge(vertex_id_1, vertex_id_2));
// By default each edge has a unit weight
ASSERT_EQ(get_weight(graph.get_edge(vertex_id_1, vertex_id_2)),
static_cast<weight_t>(1));
}
template <typename T>
struct UnweightedGraphTest : public testing::Test {
using graph_t = typename T::first_type;
using edge_t = typename T::second_type;
};
TYPED_TEST_SUITE(UnweightedGraphTest, utils::fixtures::unweighted_graph_types);
TYPED_TEST(UnweightedGraphTest, AddUnweightedEdge) {
// GIVEN
using graph_t = typename TestFixture::graph_t;
using edge_t = typename TestFixture::edge_t;
using weight_t = decltype(get_weight(std::declval<edge_t>()));
graph_t graph{};
const auto vertex_id_1{graph.add_vertex(10)};
const auto vertex_id_2{graph.add_vertex(20)};
// WHEN
graph.add_edge(vertex_id_1, vertex_id_2, edge_t{static_cast<weight_t>(42)});
// THEN
ASSERT_TRUE(graph.has_edge(vertex_id_1, vertex_id_2));
// By default each edge has a unit weight
ASSERT_EQ(graph.get_edge(vertex_id_1, vertex_id_2).val,
static_cast<weight_t>(42));
}
} // namespace graaf
|
# !/usr/bin/env python3
# ------------------ Python Standard Libraries-------------------------------
import math
# ------------------ ROS2 Depedencies ----------------------------------------
import rclpy
from rclpy.node import Node
# -------------------- Turtlesim msg and srvs --------------------------------
from turtlesim.msg import Pose
from turtlesim.srv import Spawn, SetPen, Kill
from turtlesim.srv import TeleportAbsolute, TeleportRelative
from std_srvs.srv import Empty
# -------------- Class implementation for using turtlesim --------------------
class PlaygroundTurtle(Node):
"""
Class oriented for turtlesim usage, oriented to generating the subscriptions
and clients needed for using the functionalities of the turtles.
Attributes
---
cli : rclpy client
Client implementation
req : request
Generic request for interaction between service and client
res : response
Generic request for interaction between service and client
pub : rcply publisher
Publisher implementation
sub : rcply subscriber
Subscriber implementation
Methods
---
clear_board():
Clear screen of turtlesim
spawn_turtle(x, y, theta, name):
Create new turtle
kill_turtle(name):
Delete given turtle
teleport_abs_turtle(x, y, theta, name):
Move turtle according world origin
teleport_rel_turtle(v_x, v_theta, name):
Move turtle relative to its tf with velocity
set_pen_turtle(r, g, b, width, name):
Set color and width trace of the turtle
get_pose_turtle(name):
Getter of pose of the given turtle
save_pose_turtle(msg):
Callback to store pose
"""
def __init__(self):
"""
Constructor that initialize the node with name 'playground_turtle' and
defines the generic client, request, response, publisher and subscriber
objects for connecting with turtlesim.
"""
super().__init__('playground_turtle_py')
self.cli = None
self.req = None
self.res = None
self.pub = None
self.sub = None
self.pose = Pose()
def clear_board(self):
"""
Call service that clear the background of the turtlesim.
Returns
---
True if the response is received without errors.
"""
self.cli = self.create_client(Empty, '/clear')
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger("Waiting turtlesim for action: Clear...")
self.req = Empty.Request()
self.res = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.res)
return True
def spawn_turtle(self, x, y, theta, name):
"""
Call service that appears new turtles.
Params
---
x : float
X position in the turtlesim map to spawn.
y : float
Y position in the turtlesim map to spawn.
theta : float
Orientation of the turtlesim to spawn (radians)
name : String
Name of the new turtle.
Returns
---
True if the response is received without errors.
"""
self.cli = self.create_client(Spawn, '/spawn')
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger("Waiting turtlesim for action: Spawn...")
self.req = Spawn.Request()
self.req.x = float(x)
self.req.y = float(y)
self.req.theta = float(theta)
self.req.name = str(name)
self.res = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.res)
return True
def kill_turtle(self, name):
"""
Call service that elimiates a certain turtle.
Params
---
name : String
Name of the turtle to delete
Returns
---
True if the response is received without errors.
"""
self.cli = self.create_client(Kill, '/kill')
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger("Waiting turtlesim for action: Kill...")
self.req = Kill.Request()
self.req.name = str(name)
self.res = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.res)
return True
def teleport_abs_turtle(self, x, y, theta, name):
"""
Call service that teleport a certain turtle (absolute position to
turtlesim origin)
Params
---
x : float
X position in the turtlesim map.
y : float
Y position in the turtlesim map.
theta : float
Orientation of the turtle in space (radians).
name : string
Name of the turtle to mov
Returns
---
True if the response is received without errors.
"""
self.cli = self.create_client(TeleportAbsolute, "/" + str(name) +
"/teleport_absolute")
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger("Waiting turtlesim for action: Teleport (Abs) " +
str(name) + "...")
self.req = TeleportAbsolute.Request()
self.req.x = float(x)
self.req.y = float(y)
self.req.theta = float(theta)
self.res = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.res)
return True
def teleport_rel_turtle(self, v_x, v_theta, name):
"""
Call service that teleport a certain turtle (relative to the
tranform of the same turtle)
Params
---
v_x : float
Linear velocity to move oriented to x direction.
v_theta : float
Angular velocity to move oriented around z axis.
name : string
Name of the turtle to mov.
Returns
---
True if the response is received without errors.
"""
self.cli = self.create_client(TeleportRelative, "/" + str(name) +
"/teleport_relative")
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger("Waiting turtlesim for action: Teleport (Rel) " +
str(name) + "...")
self.req = TeleportRelative.Request()
self.req.linear = float(v_x)
self.req.angulary = float(v_theta)
self.res = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.res)
return True
def set_pen_turtle(self, r, g, b, width, name):
"""
Set color and width of the trace of the given turtle.
Params
---
r : int
Must be a value between 0 - 255 of red intensity
g : int
Must be a value between 0 - 255 of green intensity
b : int
Must be a value between 0 - 255 of blue intensity
width : int
Specify width of the line trace
name : string
Name of the turtle to change trace color
Returns
---
True if the response is received without errors.
"""
self.cli = self.create_client(SetPen, "/" + name + "/set_pen")
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger("Waiting turtlesim for action: Set Pen " +
str(name) + "...")
self.req = SetPen.Request()
self.req.r = int(r)
self.req.g = int(g)
self.req.b = int(b)
self.req.width = int(width)
self.res = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.res)
return True
def get_pose_turtle(self, name):
"""
Getter of the pose of the turtle by using pose subscription via
callback
Params
---
name : string
Name of the turtle to obtain the pose
"""
self.sub = self.create_subscription(Pose, "/" + str(name) + "/pose",
save_pos_turtle, 10)
def save_pos_turtle(self, msg):
"""
Callback for getting the pose of the given turtle.
Params
---
msg : Turtle Pose
Pose obtained via message of the turtle
"""
self.pose = msg
def main():
"""
Main oriented to test the playground functions that interacts with
turtlesim.
"""
# Initialize ROS Client Library for Python
rclpy.init()
# Define name and instance class
name1 = "dan_turtle"
my_turtle = PlaygroundTurtle()
# Start playing with turtlesim
my_turtle.clear_board()
my_turtle.spawn_turtle(3, 3, 0, name1)
my_turtle.teleport_abs_turtle(7, 3, 3*math.pi/2, name1)
my_turtle.set_pen_turtle(255, 0, 0, 2, name1)
my_turtle.teleport_abs_turtle(7, 7, -math.pi, name1)
my_turtle.set_pen_turtle(0, 255, 0, 1, name1)
my_turtle.teleport_abs_turtle(3, 7, math.pi/2, name1)
my_turtle.set_pen_turtle(0, 0, 255, 2, name1)
my_turtle.teleport_abs_turtle(3, 3, math.pi/2, name1)
my_turtle.kill_turtle(name1)
# Destroy node and close program
my_turtle.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
"""
Module: user
unittests for derived class User
"""
import unittest
from models.base_model import BaseModel
from models.user import User
import os
class TestUser(unittest.TestCase):
"""
User testcases class
"""
def setUp(self):
self.user = User()
self.user.email = "[email protected]"
self.user.password = "ALX_SE AirBnB Clone"
self.user.first_name = "Amowie"
self.user.last_name = "Ugberaese"
def tearDown(self):
del self.user
try:
os.remove("file.json")
except FileNotFoundError:
pass
def test_instance_creation(self):
self.assertIsInstance(self.user, BaseModel)
def test_docstring(self):
self.assertIsNotNone(User.__doc__)
def test_timedelta(self):
self.user.save()
self.assertNotEqual(self.user.created_at, self.user.updated_at)
def test_attributes(self):
self.assertTrue(hasattr(self.user, 'id'))
self.assertTrue(hasattr(self.user, 'email'))
self.assertTrue(hasattr(self.user, 'password'))
self.assertTrue(hasattr(self.user, 'first_name'))
self.assertTrue(hasattr(self.user, 'last_name'))
self.assertTrue(hasattr(self.user, 'created_at'))
self.assertTrue(hasattr(self.user, 'updated_at'))
def test_string_representation(self):
expected = "[User] ({}) {}".format(self.user.id, self.user.__dict__)
self.assertEqual(str(self.user), expected)
def test_to_dictionary(self):
a_dict = self.user.to_dict()
self.assertIsInstance(a_dict['email'], str)
self.assertIsInstance(a_dict['password'], str)
self.assertIsInstance(a_dict['first_name'], str)
self.assertIsInstance(a_dict['last_name'], str)
self.assertIsInstance(a_dict['created_at'], str)
self.assertIsInstance(a_dict['updated_at'], str)
self.assertEqual(self.user.__class__.__name__, 'User')
if __name__ == '__main__':
unittest.main()
|
import styles from "./Weather.module.css";
import { useAppDispatch, useAppSelector } from "../../store/Hooks";
import {
select5DaysWeather,
selectCurrentCity,
selectCurrentWeather,
selectIsCurrentCityInFavorites,
selectIsLoading,
} from "../../store/weather/WeatherSlice";
import {
addToFavorites,
removeFromFavorites,
} from "../../store/favorites/FavoritesSlice";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import FavoriteIcon from "@mui/icons-material/Favorite";
import { format } from "date-fns";
import AutocompleteComponent from "./AutocompleteComponent";
import Degrees from "../../shared/components/Degrees";
import Loader from "../../shared/loader/Loader";
import { IFavoriteListItem } from "../../store/favorites/FavoritesTypes";
import WeatherDay from "./WeatherDay";
import { IUpcoming5DaysWeather } from "../../store/weather/WeatherTypes";
const Weather = () => {
const dispatch = useAppDispatch();
const currentWeatherData = useAppSelector(selectCurrentWeather);
const _5DaysWeather = useAppSelector(select5DaysWeather);
const currentCity = useAppSelector(selectCurrentCity);
const isLoading = useAppSelector(selectIsLoading);
const isInFavorites = useAppSelector(selectIsCurrentCityInFavorites);
const addWeatherToFavorites = () => {
if (currentWeatherData) {
const data: IFavoriteListItem = {
city: currentCity.city,
degrees: currentWeatherData.temperature.metric.value,
temperature: {
value: currentWeatherData.temperature.imperial.value,
unit: currentWeatherData.temperature.imperial.unit,
},
weatherCondition: currentWeatherData.weatherText,
weatherIcon: currentWeatherData.weatherIcon,
keyArea: currentCity.keyArea,
};
if (!isInFavorites) {
dispatch(addToFavorites(data));
}
}
};
const removeWeatherFromFavorites = () => {
dispatch(removeFromFavorites(currentCity));
};
return (
<div className={styles.weatherContainer}>
<div className={styles.saveToFavoritesIcon}>
{isInFavorites ? (
<FavoriteIcon
onClick={removeWeatherFromFavorites}
fontSize={"inherit"}
color={"inherit"}
/>
) : (
<FavoriteBorderIcon
onClick={addWeatherToFavorites}
fontSize={"inherit"}
color={"inherit"}
/>
)}
</div>
<div className={styles.autoCompleteContainer}>
<AutocompleteComponent />
</div>
{isLoading ? (
<Loader />
) : (
<>
<div className={styles.WeatherStatus}>
{currentWeatherData ? (
<>
<div className={styles.dayDetails}>
{currentWeatherData.day} | {currentWeatherData.monthAndDate}
</div>
<div className={styles.mainWeatherDetails}>
{currentCity.city}
</div>
<div> {currentCity.country}</div>
<div className={styles.mainWeatherDetails}>
<Degrees
temperature={currentWeatherData.temperature.imperial.value}
unit={currentWeatherData.temperature.imperial.unit}
/>
</div>
<img
src={require(`.././../../public/icons/${currentWeatherData.weatherIcon}.png`)}
alt="weather icon"
height={100}
width={"auto"}
/>
<div className={styles.mainWeatherDetails}>
{currentWeatherData.weatherText}
</div>
</>
) : (
<></>
)}
</div>
<div className={styles.upcomingDaysContainer}>
<div className={styles.upcomingDaysWeather}>
{_5DaysWeather ? (
<>
{_5DaysWeather.map(
(city: IUpcoming5DaysWeather, index: number) => {
const date = new Date(city.date);
const day = format(date, "iiii");
return <WeatherDay day={day} city={city} key={index} />;
}
)}
</>
) : (
<></>
)}
</div>
</div>
</>
)}
</div>
);
};
export default Weather;
|
import React from "react";
import { injectIntl } from "react-intl";
import { currentUser } from "constants/defaultValues";
import { setCurrentUser } from "helpers/Utils";
import { UserApi } from "features/repositories";
import { Api } from "@mui/icons-material";
const Index = ({ intl }) => {
const { messages } = intl;
const [message, setMessage] = React.useState(null);
const [user, setUser] = React.useState("");
const [password, setPassword] = React.useState("");
const clickLogin = () => {
var api = UserApi.Login({ user: user, password: password }).apply();
api.then((res) => {
console.log(res.data);
if (res.data.message) alert(res.data.message);
else {
const currentUser = { ...res.data.user, token: res.data.token };
setCurrentUser({ ...currentUser, roleTitle: "کاربر سیستم" }).then(
() => {
setCurrentUser({
...res.data.user,
token: res.data.token,
app: res.data.app,
roleTitle: "کاربر سیستم",
}).then(() => {
window.location.href = `/app/${res.data.app}`;
});
}
);
}
});
//setCurrentUser(currentUser).then(() => {
// window.location.href="/app"
//});
};
return (
<div className="d-flex col-12 col-lg-5 col-xl-4 align-items-center authentication-bg p-sm-5 p-4">
<div className="w-px-400 mx-auto">
<div className="app-brand mb-4">
<div className="app-brand-link gap-2 mb-2">
<span className="app-brand-logo demo"></span>
<span className="app-brand-text demo h3 mb-0 fw-bold">
{messages["app.name"]}
</span>
</div>
</div>
{
//<p className="mb-4">{messages["user.login.title"]}</p>
}
<div className="mb-3">
<label htmlFor="email" className="form-label">
{messages["user.login.name_or_mobile"]}
</label>
<input
type="text"
value={user}
onChange={(e) => {
setUser(e.target.value);
}}
className="form-control text-start"
dir="ltr"
id="email"
name="email-username"
placeholder={messages["user.login.placeholder"]}
autoFocus
/>
</div>
<div className="mb-3 form-password-toggle">
<div className="d-flex justify-content-between">
<label className="form-label" htmlFor="password">
{messages["user.login.password"]}
</label>
<a href="#">
<small>{messages["user.login.forgot-password"]}</small>
</a>
</div>
<div className="input-group input-group-merge">
<input
type="password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
id="password"
className="form-control text-start"
dir="ltr"
name="password"
placeholder="············"
aria-describedby="password"
/>
<span className="input-group-text cursor-pointer">
<i className="bx bx-hide"></i>
</span>
</div>
</div>
<div className="mb-3">
<div className="form-check">
<input
className="form-check-input"
type="checkbox"
id="remember-me"
/>
<label className="form-check-label" htmlFor="remember-me">
{" "}
{messages["user.login.remember-password"]}{" "}
</label>
</div>
</div>
<button onClick={clickLogin} className="btn btn-primary d-grid w-100">
{messages["user.login.button"]}
</button>
</div>
</div>
);
};
export default injectIntl(Index);
|
# status_updates
## Overview
A status update is an update on the progress of a particular object,
and is sent out to all followers when created. These updates
include both text describing the update and a `status_type` intended to
represent the overall state of the project. These include: `on_track` for projects that
are on track, `at_risk` for projects at risk, `off_track` for projects that
are behind, and `on_hold` for projects on hold.
Status updates can be created and deleted, but not modified.
### Available Operations
* [create_status_for_object](#create_status_for_object) - Create a status update
* [delete_status](#delete_status) - Delete a status update
* [get_status](#get_status) - Get a status update
* [get_statuses_for_object](#get_statuses_for_object) - Get status updates from an object
## create_status_for_object
Creates a new status update on an object.
Returns the full record of the newly created status update.
### Example Usage
```python
import testing_2
from testing_2.models import operations, shared
s = testing_2.Testing2(
security=shared.Security(
oauth2="",
),
)
req = operations.CreateStatusForObjectRequest(
request_body=operations.CreateStatusForObjectRequestBodyInput(
data=shared.StatusUpdateRequestInput(
html_text='<body>The project <strong>is</strong> moving forward according to plan...</body>',
parent='odio',
status_type=shared.StatusUpdateRequestStatusType.ACHIEVED,
text='The project is moving forward according to plan...',
title='Status Update - Jun 15',
),
),
limit=708548,
offset='vero',
opt_fields=[
'dolore',
'quibusdam',
],
opt_pretty=False,
)
res = s.status_updates.create_status_for_object(req)
if res.create_status_for_object_201_application_json_object is not None:
# handle response
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `request` | [operations.CreateStatusForObjectRequest](../../models/operations/createstatusforobjectrequest.md) | :heavy_check_mark: | The request object to use for the request. |
### Response
**[operations.CreateStatusForObjectResponse](../../models/operations/createstatusforobjectresponse.md)**
## delete_status
Deletes a specific, existing status update.
Returns an empty data record.
### Example Usage
```python
import testing_2
from testing_2.models import operations, shared
s = testing_2.Testing2(
security=shared.Security(
oauth2="",
),
)
req = operations.DeleteStatusRequest(
opt_fields=[
'sequi',
'natus',
'impedit',
'aut',
],
opt_pretty=False,
status_gid='voluptatibus',
)
res = s.status_updates.delete_status(req)
if res.delete_status_200_application_json_object is not None:
# handle response
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `request` | [operations.DeleteStatusRequest](../../models/operations/deletestatusrequest.md) | :heavy_check_mark: | The request object to use for the request. |
### Response
**[operations.DeleteStatusResponse](../../models/operations/deletestatusresponse.md)**
## get_status
Returns the complete record for a single status update.
### Example Usage
```python
import testing_2
from testing_2.models import operations, shared
s = testing_2.Testing2(
security=shared.Security(
oauth2="",
),
)
req = operations.GetStatusRequest(
opt_fields=[
'nulla',
'fugit',
],
opt_pretty=False,
status_gid='porro',
)
res = s.status_updates.get_status(req)
if res.get_status_200_application_json_object is not None:
# handle response
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `request` | [operations.GetStatusRequest](../../models/operations/getstatusrequest.md) | :heavy_check_mark: | The request object to use for the request. |
### Response
**[operations.GetStatusResponse](../../models/operations/getstatusresponse.md)**
## get_statuses_for_object
Returns the compact status update records for all updates on the object.
### Example Usage
```python
import testing_2
import dateutil.parser
from testing_2.models import operations, shared
s = testing_2.Testing2(
security=shared.Security(
oauth2="",
),
)
req = operations.GetStatusesForObjectRequest(
created_since=dateutil.parser.isoparse('2020-01-18T09:21:05.997Z'),
limit=478370,
offset='eligendi',
opt_fields=[
'alias',
'officia',
],
opt_pretty=False,
parent='tempora',
)
res = s.status_updates.get_statuses_for_object(req)
if res.get_statuses_for_object_200_application_json_object is not None:
# handle response
```
### Parameters
| Parameter | Type | Required | Description |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `request` | [operations.GetStatusesForObjectRequest](../../models/operations/getstatusesforobjectrequest.md) | :heavy_check_mark: | The request object to use for the request. |
### Response
**[operations.GetStatusesForObjectResponse](../../models/operations/getstatusesforobjectresponse.md)**
|
package oopsInJava;
// class -> class , interface-> interface = extends
// class -> interface = implements
interface E
{
// Inside interfaces we can define variable but by default they are "final and static"
// so we need to initialise teh variable since its final
int age = 12;
String name = "Payal";
// Both of these methods are public abstract automatically
void show();
void show2();
}
class F implements E
{
@Override
public void show() {
System.out.println("Show");
}
@Override
public void show2() {
System.out.println("In show 2");
}
}
class InterfaceConcept {
public static void main(String[] args) {
// you cant create an object of interfaces
F f = new F();
f.show();
// A class can implement multiple interfaces
}
}
// In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. They provide a way to achieve abstraction and multiple inheritance in Java. An interface is a contract that a class can implement, which means that the class agrees to perform the specific behaviors declared by the interface.
//
//Real-Life Scenario
//Let's consider a real-life scenario involving a payment system in an online store. There are multiple ways to process payments, such as credit cards, PayPal, and bank transfers. Each payment method has its own way of processing payments but they all share the common behavior of processing a payment.
//
//Step-by-Step Explanation:
//Define the Interface:
//
//We define an interface PaymentMethod that declares the processPayment method. This method will be implemented by different classes representing different payment methods.
//
//java
//Copy code
//public interface PaymentMethod {
// void processPayment(double amount);
//}
//Implement the Interface:
//
//We create classes for different payment methods like CreditCard, PayPal, and BankTransfer, each implementing the PaymentMethod interface.
//
//java
//Copy code
//public class CreditCard implements PaymentMethod {
// @Override
// public void processPayment(double amount) {
// System.out.println("Processing credit card payment of $" + amount);
// }
//}
//
//public class PayPal implements PaymentMethod {
// @Override
// public void processPayment(double amount) {
// System.out.println("Processing PayPal payment of $" + amount);
// }
//}
//
//public class BankTransfer implements PaymentMethod {
// @Override
// public void processPayment(double amount) {
// System.out.println("Processing bank transfer payment of $" + amount);
// }
//}
//Use the Interface:
//
//In our payment processing system, we can use the PaymentMethod interface to process payments without worrying about the specific implementation. This provides flexibility and allows for easy addition of new payment methods in the future.
//
//java
//Copy code
//public class PaymentProcessor {
// private PaymentMethod paymentMethod;
//
// public PaymentProcessor(PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public void process(double amount) {
// paymentMethod.processPayment(amount);
// }
//}
//Test the Implementation:
//
//We can create instances of different payment methods and use the PaymentProcessor to process payments.
//
//java
//Copy code
//public class Main {
// public static void main(String[] args) {
// PaymentMethod creditCard = new CreditCard();
// PaymentMethod payPal = new PayPal();
// PaymentMethod bankTransfer = new BankTransfer();
//
// PaymentProcessor processor = new PaymentProcessor(creditCard);
// processor.process(100.0); // Output: Processing credit card payment of $100.0
//
// processor = new PaymentProcessor(payPal);
// processor.process(200.0); // Output: Processing PayPal payment of $200.0
//
// processor = new PaymentProcessor(bankTransfer);
// processor.process(300.0); // Output: Processing bank transfer payment of $300.0
// }
//}
//Benefits:
//Abstraction: The interface provides a way to define methods without implementing them. The actual implementation is left to the classes that implement the interface.
//
//Flexibility: You can easily switch between different implementations of the interface without changing the client code.
//
//Maintainability: Adding a new payment method only requires creating a new class that implements the PaymentMethod interface. The existing code does not need to be modified.
//
//Multiple Inheritance: Java does not support multiple inheritance of classes, but a class can implement multiple interfaces, allowing it to inherit behavior from multiple sources.
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' hide RefreshIndicator, RefreshIndicatorState;
import '../../../shared_ui.dart';
class AuntyRefreshHeader extends RefreshIndicator {
final String? semanticsLabel;
final String? semanticsValue;
final Color? textColor;
final double distance;
final Color? backgroundColor;
const AuntyRefreshHeader({
Key? key,
double height = 80.0,
this.semanticsLabel,
this.semanticsValue,
this.textColor,
double offset = 0,
this.distance = 250.0,
this.backgroundColor,
Duration completeDuration = const Duration(milliseconds: 600),
}) : super(
key: key,
refreshStyle: RefreshStyle.Behind,
offset: offset,
height: height,
completeDuration: completeDuration,
);
@override
State<StatefulWidget> createState() {
return _AuntyRefreshHeaderState();
}
}
class _AuntyRefreshHeaderState extends RefreshIndicatorState<AuntyRefreshHeader> with TickerProviderStateMixin {
late ScrollPosition _position;
late Animation<Offset> _positionFactor;
late AnimationController _scaleFactor;
late AnimationController _positionController;
late AnimationController _valueAni;
@override
void initState() {
_valueAni = AnimationController(vsync: this, value: 0.0, lowerBound: 0.0, upperBound: 1.0, duration: const Duration(milliseconds: 300));
_valueAni.addListener(() {
if (mounted && _position.pixels <= 0) setState(() {});
});
_positionController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
_scaleFactor = AnimationController(vsync: this, value: 1.0, lowerBound: 0.0, upperBound: 1.0, duration: const Duration(milliseconds: 300));
_positionFactor = _positionController.drive(
Tween<Offset>(
begin: const Offset(0.0, 0.0),
end: const Offset(0.0, 0.0),
),
);
super.initState();
}
@override
void didUpdateWidget(covariant AuntyRefreshHeader oldWidget) {
_position = Scrollable.of(context).position;
super.didUpdateWidget(oldWidget);
}
@override
void onOffsetChange(double offset) {
if (!floating) {
_valueAni.value = offset / configuration!.headerTriggerDistance;
_positionController.value = offset / configuration!.headerTriggerDistance;
}
}
@override
void onModeChange(RefreshStatus? mode) {
if (mode == RefreshStatus.refreshing) {
_positionController.value = widget.distance / widget.height;
_scaleFactor.value = 1;
}
super.onModeChange(mode);
}
@override
void resetValue() {
_scaleFactor.value = 1.0;
_positionController.value = 0.0;
_valueAni.value = 0.0;
super.resetValue();
}
@override
void didChangeDependencies() {
_position = Scrollable.of(context).position;
super.didChangeDependencies();
}
@override
Future<void> readyToRefresh() {
return _positionController.animateTo(widget.distance / widget.height);
}
@override
Future<void> endRefresh() {
return _scaleFactor.animateTo(0.0);
}
@override
void dispose() {
_valueAni.dispose();
_scaleFactor.dispose();
_positionController.dispose();
super.dispose();
}
@override
Widget buildContent(BuildContext context, RefreshStatus? mode) {
return SafeArea(
child: SlideTransition(
position: _positionFactor,
transformHitTests: false,
child: pullToRefreshHeader(context, mode),
),
);
}
Widget pullToRefreshHeader(BuildContext context, RefreshStatus? mode) {
switch (mode) {
case RefreshStatus.idle:
return refreshHeader(
'Pull down to refresh',
childFirst: Icon(
Icons.arrow_downward,
color: widget.textColor,
size: 24,
),
);
case RefreshStatus.canRefresh:
return refreshHeader(
'Release to refresh',
childFirst: Icon(
Icons.refresh,
color: widget.textColor,
size: 24,
),
);
case RefreshStatus.refreshing:
return refreshHeader(
'Refreshing...',
childFirst: const CupertinoActivityIndicator(),
);
case RefreshStatus.completed:
return refreshHeader(
'Completed',
childFirst: Icon(
Icons.check,
color: widget.textColor,
size: 24,
),
);
default:
return const SizedBox.shrink();
}
}
Widget refreshHeader(String content, {Widget? childFirst}) {
return Center(
child: Wrap(
direction: Axis.horizontal,
spacing: 15,
children: [
if (childFirst != null) ...[
childFirst,
],
Text(
content,
style: TextStyles.caption12Regular.copyWith(color: widget.textColor),
),
],
),
);
}
}
|
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
pub struct HashnodeResponse {
pub data: Option<Data>,
pub errors: Option<Vec<serde_json::Value>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Data {
pub publication: Publication,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Publication {
pub posts: Posts,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Posts {
pub edges: Vec<Edge>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Edge {
pub node: HashNodeArticle,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HashNodeArticle {
pub slug: String,
pub title: String,
pub tags: Vec<Tag>,
pub published_at: String,
pub content: Content,
pub brief: String,
pub publication: Publication2,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tag {
pub name: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Content {
pub markdown: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Publication2 {
pub links: Links,
pub author: Author,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Links {
pub hashnode: String,
pub website: String,
pub github: String,
pub twitter: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Author {
pub username: String,
}
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct User {
// pub publication: Publication,
// }
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct Publication {
// pub posts: Vec<Post>,
// }
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct Post {
// pub slug: String,
// }
// #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct ArticleFetched {
// pub data: Option<ArticleFetchedData>,
// pub errors: Option<Vec<serde_json::Value>>,
// }
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct ArticleFetchedData {
// pub post: ArticleFetchedPost,
// }
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct ArticleFetchedPost {
// pub slug: String,
// pub title: String,
// pub tags: Vec<Tag>,
// pub date_added: String,
// pub content_markdown: String,
// pub brief: String,
// pub publication: ArticleFetchedPublication,
// }
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct Tag {
// pub name: String,
// }
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct ArticleFetchedPublication {
// pub links: Links,
// pub username: String,
// }
// #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// #[serde(rename_all = "camelCase")]
// pub struct Links {
// pub hashnode: String,
// pub website: String,
// pub github: String,
// pub twitter: String,
// }
|
#nullable disable
using IdSubjects;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;
namespace AuthCenterWebApp.Areas.Settings.Pages.Authentication;
public class SetPasswordModel : PageModel
{
private readonly NaturalPersonManager userManager;
private readonly SignInManager<NaturalPerson> signInManager;
public SetPasswordModel(
NaturalPersonManager userManager,
SignInManager<NaturalPerson> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required(ErrorMessage = "Validate_Required")]
[StringLength(100, ErrorMessage = "Validate_StringLength", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("NewPassword", ErrorMessage = "Validate_PasswordConfirm")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await this.userManager.GetUserAsync(this.User);
if (user == null)
{
return this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId(this.User)}'.");
}
var hasPassword = await this.userManager.HasPasswordAsync(user);
return hasPassword ? this.RedirectToPage("./ChangePassword") : this.Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!this.ModelState.IsValid)
{
return this.Page();
}
var user = await this.userManager.GetUserAsync(this.User);
if (user == null)
{
return this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId(this.User)}'.");
}
var addPasswordResult = await this.userManager.AddPasswordAsync(user, this.Input.NewPassword);
if (!addPasswordResult.Succeeded)
{
foreach (var error in addPasswordResult.Errors)
{
this.ModelState.AddModelError(string.Empty, error.Description);
}
return this.Page();
}
await this.signInManager.RefreshSignInAsync(user);
this.StatusMessage = "您的密码已设置。";
return this.RedirectToPage();
}
}
|
package com.nhnacademy.exam040304;
import java.awt.Rectangle;
public class BoundedWorld extends MovableWorld {
public boolean outOfBounds(Ball ball) {
return (ball.getX() - ball.getRadius() < getBounds().getMinX())
|| (ball.getX() + ball.getRadius() > getBounds().getMaxX())
|| (ball.getY() - ball.getRadius() < getBounds().getMinY())
|| (ball.getY() + ball.getRadius() > getBounds().getMaxY());
}
public void bounceBall(MovableBall ball) {
if (ball.getX() - ball.getRadius() < getBounds().getMinX()) {
ball.moveTo((int) getBounds().getMinX() + ball.getRadius(), ball.getY());
ball.setDX(-ball.getDX());
} else if (ball.getX() + ball.getRadius() > getBounds().getMaxX()) {
ball.moveTo((int) getBounds().getMaxX() - ball.getRadius(), ball.getY());
ball.setDX(-ball.getDX());
}
if (ball.getY() - ball.getRadius() < getBounds().getMinY()) {
ball.moveTo(ball.getX(), (int) getBounds().getMinY() + ball.getRadius());
ball.setDY(-ball.getDY());
} else if (ball.getY() + ball.getRadius() > getBounds().getMaxY()) {
ball.moveTo(ball.getX(), (int) getBounds().getMaxY() - ball.getRadius());
ball.setDY(-ball.getDY());
}
}
@Override
public void move() {
for (int i = 0; i < getCount(); i++) {
Ball ball1 = get(i);
if (ball1 instanceof MovableBall) {
((MovableBall) ball1).move();
if (outOfBounds(ball1)) {
bounceBall((MovableBall) ball1);
}
for (int j = i + 1; j < getCount(); j++) {
Ball ball2 = get(j);
if (ball1.isCollision(ball2)) {
Rectangle intersection = ball1.getRegion().intersection(ball2.getRegion());
if ((intersection.getWidth() != ball1.getRegion().getWidth()) &&
(intersection.getWidth() != ball2.getRegion().getWidth())) {
if (ball1.getX() - ball1.getRadius() < ball2.getX() - ball2.getRadius()) {
int newX = 2 * (ball2.getX() - ball2.getRadius() + ball1.getRadius()) - ball1.getX();
((MovableBall) ball1).moveTo(newX, ball1.getY());
((MovableBall) ball1).setDX(-((MovableBall) ball1).getDX());
} else if (ball1.getX() + ball1.getRadius() > ball2.getX() + ball2.getRadius()) {
int newX = 2 * (ball2.getX() + ball2.getRadius() - ball1.getRadius()) - ball1.getX();
((MovableBall) ball1).moveTo(newX, ball1.getY());
((MovableBall) ball1).setDX(-((MovableBall) ball1).getDX());
}
}
if ((intersection.getHeight() != ball1.getRegion().getHeight()) &&
(intersection.getHeight() != ball2.getRegion().getHeight())) {
if (ball1.getY() - ball1.getRadius() < ball2.getY() - ball2.getRadius()) {
int newY = 2 * (ball2.getY() - ball2.getRadius() + ball1.getRadius()) - ball1.getY();
((MovableBall) ball1).moveTo(ball1.getX(), newY);
((MovableBall) ball1).setDY(-((MovableBall) ball1).getDY());
} else if (ball1.getY() + ball1.getRadius() > ball2.getY() + ball2.getRadius()) {
int newY = 2 * (ball2.getY() + ball2.getRadius() - ball1.getRadius()) - ball1.getY();
((MovableBall) ball1).moveTo(ball1.getX(), newY);
((MovableBall) ball1).setDY(-((MovableBall) ball1).getDY());
}
}
}
}
}
}
repaint();
}
}
|
import React, { useState, useEffect, ReactElement } from 'react';
import AccordionModule from '../parts/Accordion';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import FormControl from '@mui/material/FormControl';
import Typography from '@mui/material/Typography';
// Define an interface for field errors
interface FieldError {
error: boolean;
helperText: string;
}
// Define the props type for HazardModule
interface HazardModuleProps {
expanded: boolean;
onSubmit: (data: any, module: string) => void;
}
// HazardModule component
const HazardModule: React.FC<HazardModuleProps> = ({ expanded, onSubmit }): ReactElement => {
const [hazardName, setHazardName] = useState('');
const [hazardType, setHazardType] = useState('');
const [preLikelihood, setPreLikelihood] = useState('');
const [preExposure, setPreExposure] = useState('');
const [preConsequence, setPreConsequence] = useState('');
// Define an interface for field errors
interface FieldErrors {
[key: string]: FieldError;
}
// Initialize field errors state
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({
hazardName: { error: false, helperText: '' },
hazardType: { error: false, helperText: '' },
preLikelihood: { error: false, helperText: '' },
preExposure: { error: false, helperText: '' },
preConsequence: { error: false, helperText: '' },
});
// Function to validate a field's value
const validateField = (fieldName: string, value: string | null, callback?: (isValid: boolean) => void): void => {
console.log(`Validating field: ${fieldName} with value: ${value}`);
let isValid = true;
let helperText = '';
switch (fieldName) {
case 'hazardName':
case 'hazardType':
case 'preLikelihood':
case 'preExposure':
case 'preConsequence':
isValid = typeof value === 'string' && value.trim() !== '';
helperText = isValid ? '' : '*Required';
break;
}
console.log(`Validation result for ${fieldName}:`, { error: !isValid, helperText });
setFieldErrors(prevErrors => ({
...prevErrors,
[fieldName]: { error: !isValid, helperText: helperText },
}));
if (callback) {
callback(isValid);
}
};
// Handle change for the 'hazardName' field
const handleHazardNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = event.target.value;
setHazardName(newValue);
validateField('hazardName', newValue);
};
// Handle change for the 'hazardType' field
const handleHazardTypeChange = (event: React.ChangeEvent<{ value: unknown }>) => {
const newValue = event.target.value as string;
setHazardType(newValue);
validateField('hazardType', newValue);
};
// Handle change for the 'preLikelihood' field
const handlePreLikelihoodChange = (event: React.MouseEvent<HTMLElement, MouseEvent>, newPreLikelihood: string) => {
setPreLikelihood(newPreLikelihood);
validateField('preLikelihood', newPreLikelihood);
};
// Handle change for the 'preExposure' field
const handlePreExposureChange = (event: React.MouseEvent<HTMLElement, MouseEvent>, newPreExposure: string) => {
setPreExposure(newPreExposure);
validateField('preExposure', newPreExposure);
};
// Handle change for the 'preConsequence' field
const handlePreConsequenceChange = (event: React.MouseEvent<HTMLElement, MouseEvent>, newPreConsequence: string) => {
setPreConsequence(newPreConsequence);
validateField('preConsequence', newPreConsequence);
};
const resetForm = () => {
setHazardName('');
setHazardType('');
setPreLikelihood('');
setPreExposure('');
setPreConsequence('');
setFieldErrors({
hazardName: { error: false, helperText: '' },
hazardType: { error: false, helperText: '' },
preLikelihood: { error: false, helperText: '' },
preExposure: { error: false, helperText: '' },
preConsequence: { error: false, helperText: '' },
});
};
useEffect(() => {
console.log("Field errors updated:", fieldErrors);
}, [fieldErrors]);
useEffect(() => {
if (!expanded) {
resetForm();
}
}, [expanded]);
return (
<AccordionModule
title="Hazard Information"
onSubmit={(event) => {
event.preventDefault(); // Prevent default form submission
const state = { hazardName, hazardType, preLikelihood, preExposure, preConsequence };
onSubmit(state, 'hazardModule'); // Use the onSubmit prop for submission
}}
buttonLabel="Submit Hazard"
expanded={expanded}
>
<TextField
id="inputHazardName"
label="Hazard Name"
variant="outlined"
fullWidth
margin="normal"
value={hazardName}
onChange={handleHazardNameChange}
error={fieldErrors.hazardName.error}
helperText={fieldErrors.hazardName.helperText}
required
/>
<TextField
select
fullWidth
margin="normal"
label="Select Hazard Type"
value={hazardType}
onChange={handleHazardTypeChange}
error={fieldErrors.hazardType.error}
helperText={fieldErrors.hazardType.helperText}
>
<MenuItem value="Health">Health</MenuItem>
<MenuItem value="Safety">Safety</MenuItem>
</TextField>
<FormControl fullWidth margin="normal" error={fieldErrors.preLikelihood.error}>
<Typography>Likelihood of Occurrence</Typography>
<ToggleButtonGroup
value={preLikelihood}
exclusive
onChange={handlePreLikelihoodChange}
>
{[1, 2, 3, 4, 5].map((num) => (
<ToggleButton key={num} value={String(num)}>{num}</ToggleButton>
))}
</ToggleButtonGroup>
<Typography variant="caption" color="error">{fieldErrors.preLikelihood.helperText}</Typography>
</FormControl>
<FormControl fullWidth margin="normal" error={fieldErrors.preExposure.error}>
<Typography>Exposure to Hazard</Typography>
<ToggleButtonGroup
value={preExposure}
exclusive
onChange={handlePreExposureChange}
>
{[1, 2, 3, 4, 5].map((num) => (
<ToggleButton key={num} value={String(num)}>{num}</ToggleButton>
))}
</ToggleButtonGroup>
<Typography variant="caption" color="error">{fieldErrors.preExposure.helperText}</Typography>
</FormControl>
<FormControl fullWidth margin="normal" error={fieldErrors.preConsequence.error}>
<Typography>Consequence of Exposure</Typography>
<ToggleButtonGroup
value={preConsequence}
exclusive
onChange={handlePreConsequenceChange}
>
{[1, 2, 3, 4, 5].map((num) => (
<ToggleButton key={num} value={String(num)}>{num}</ToggleButton>
))}
</ToggleButtonGroup>
<Typography variant="caption" color="error">{fieldErrors.preConsequence.helperText}</Typography>
</FormControl>
</AccordionModule>
);
};
export default HazardModule;
|
#Title: Derivation in Calculus
#Slide: 1
#Header: Table of Contents
#Content:
1. Introduction to Derivation
2. Understanding the Derivative
3. Rules of Differentiation
4. Derivative of Basic Functions
5. Derivative of Trigonometric Functions
6. Derivative of Exponential and Logarithmic Functions
7. Derivative of Composite Functions
8. Applications of Derivation
9. Summary
10. References
#Slide: 2
#Header: Learning Aims
#Content: Students will learn the concept of derivation in calculus and how to find the derivative of different functions.
#Slide: 3
#Header: Success Criteria
#Content: By the end of this presentation, students will be able to:
- Explain the concept of derivation and the importance of finding the derivative in calculus.
- Apply the rules of differentiation to find the derivative of basic, trigonometric, exponential, logarithmic, and composite functions.
- Solve real-life problems using the derivative.
#Slide: 4
#Header: Introduction to Derivation
#Content: Derivation is a fundamental concept in calculus that allows us to find the rate of change of a function at any point. It helps us understand how functions behave and enables us to solve various mathematical and real-world problems.
#Slide: 5
#Header: Understanding the Derivative
#Content: The derivative of a function represents its rate of change. It is denoted by f'(x) or dy/dx. The derivative measures the slope of the tangent line to a function at a specific point.
#Slide: 6
#Header: Rules of Differentiation
#Content: There are several rules to find the derivative of a function, including the power rule, constant rule, product rule, quotient rule, and chain rule. These rules provide a systematic approach to differentiation.
#Slide: 7
#Header: Derivative of Basic Functions
#Content: The derivative of basic functions such as constant functions, linear functions, quadratic functions, square root functions, and reciprocal functions can be found using the rules of differentiation.
#Slide: 8
#Header: Derivative of Trigonometric Functions
#Content: Trigonometric functions like sine, cosine, tangent, cotangent, secant, and cosecant have specific derivatives. Learning these derivatives helps in finding the rate of change of trigonometric functions.
#Slide: 9
#Header: Derivative of Exponential and Logarithmic Functions
#Content: Exponential and logarithmic functions have their own derivatives, which are crucial in understanding exponential growth and decay, as well as solving problems involving logarithmic functions.
#Slide: 10
#Header: Derivative of Composite Functions
#Content: Composite functions involve chaining multiple functions together. The chain rule provides a method to find the derivative of composite functions.
#Slide: 11
#Header: Applications of Derivation
#Content: Derivation has numerous applications in various fields such as physics, economics, biology, and engineering. It helps in solving optimization problems, determining maximum and minimum values, and analyzing rates of change.
#Slide: 12
#Headers: Summary
#Content: In this presentation, we learned about derivation in calculus. We understood the concept of the derivative, learned various rules of differentiation, and explored the derivatives of basic, trigonometric, exponential, logarithmic, and composite functions. We also discussed the applications of derivation in real-life scenarios.
#Slide: 13
#Headers: References
#Content: Include a list of references used for this presentation.
|
import { useState, useEffect } from 'react';
import {
Text,
View,
Alert,
ScrollView
} from 'react-native';
import { AntDesign } from '@expo/vector-icons';
import styles from './styles.js';
import api from '../../../service/api';
import NavTab from '../NavTab';
export default function ListagemUsuarios({ route, navigation }) {
const { usuarioParam } = route.params;
const [usuarios, setUsuarios] = useState([]);
useEffect(
() => {
getUsuarios();
}, []);
async function getUsuarios() {
await api.get(`/usuarios/${usuarioParam.usuarioLogado.cargo}/all`, { headers: { 'Authorization': `Bearer ${usuarioParam.token}` } })
.then(async (response) => {
setUsuarios(response.data)
})
.catch(error => Alert.alert(error));
}
async function deletaUsuario(id) {
await api.delete(`/usuarios/${id}`)
.then(async (response) => {
Alert.alert('Usuario deletado com sucesso!');
getUsuarios();
})
.catch(error => console.log(error));
}
return (
<View style={styles.containerMain}>
<View style={styles.header}>
<View style={styles.line} />
<Text style={styles.overlayText}>Usuarios</Text>
</View>
<ScrollView contentContainerStyle={[styles.scroll, { marginBottom: 20 }]}>
{
usuarios.map((usuario, index) => (
<View style={styles.border} key={index.toString()}>
<View style={[styles.border, styles.borderItem]}>
<Text style={styles.info}>{usuario.nome}</Text>
</View>
<View style={[styles.border, styles.borderItem]}>
<Text style={styles.info}>{usuario.email}</Text>
</View>
<AntDesign onPress={() => deletaUsuario(usuario.id)}
style={styles.icon} name="delete" size={48} color="white" />
</View>
))
}
</ScrollView>
<View style={styles.navBar}>
<NavTab navigation={navigation} usuario={usuarioParam} />
</View>
</View>
);
}
|
# 如何用 FastAPI 部署 NLP 模型
> 原文:<https://www.freecodecamp.org/news/how-to-deploy-an-nlp-model-with-fastapi/>
如果你从事自然语言处理,知道如何部署模型是你需要掌握的最重要的技能之一。
模型部署是将模型集成到现有生产环境中的过程。该模型将接收输入,并为特定用例的决策预测输出。
> “只有当一个模型与业务系统完全集成时,我们才能从它的预测中提取真正的价值”。——克里斯托弗·萨米乌拉
你可以通过不同的方式将你的 [NLP](https://hackernoon.com/your-guide-to-natural-language-processing-nlp-dw8g360f?ref=hackernoon.com) 模型部署到产品中,比如使用 Flask、Django、Bottle 或其他框架。但是在今天的文章中,您将学习如何使用 ****FastAPI 构建和部署您的 NLP 模型。****
在本文中,您将了解到:
* 如何建立一个将 IMDB 电影评论分类成不同情绪的 NLP 模型?
* 什么是 FastAPI,如何安装?
* 如何用 FastAPI 部署您的模型?
* 如何在任何 Python 应用程序中使用您部署的 NLP 模型。
所以让我们开始吧。🚀
## 如何建立自然语言处理模型
首先,我们需要建立我们的 NLP 模型。我们将使用 [IMDB 电影数据集](https://www.kaggle.com/c/word2vec-nlp-tutorial/data?ref=hackernoon.com)来构建一个简单的模型,该模型可以分类电影评论是正面还是负面。下面是你应该遵循的步骤。
### 导入重要的包
首先,我们需要导入一些 Python 包来加载数据,清理数据,创建机器学习模型(分类器),并保存模型以进行部署。
```
# import important modules
import numpy as np
import pandas as pd
# sklearn modules
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB # classifier
from sklearn.metrics import (
accuracy_score,
classification_report,
plot_confusion_matrix,
)
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
# text preprocessing modules
from string import punctuation
# text preprocessing modules
from nltk.tokenize import word_tokenize
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re #regular expression
# Download dependency
for dependency in (
"brown",
"names",
"wordnet",
"averaged_perceptron_tagger",
"universal_tagset",
):
nltk.download(dependency)
import warnings
warnings.filterwarnings("ignore")
# seeding
np.random.seed(123
```
从数据文件夹加载数据集:
```
# load data
data = pd.read_csv("../data/labeledTrainData.tsv", sep='\t')
```
然后展示数据集的一个样本:
```
# show top five rows of data
data.head()
```

我们的数据集有 3 列:
* ****Id**** —这是评论的 Id
* ****情绪**** —要么积极(1),要么消极(0)
* ****回顾**** —评论电影
接下来,让我们检查数据集的形状:
```
# check the shape of the data
data.shape
```
(25000, 3)
该数据集有 25,000 条评论。
现在我们需要检查数据集是否有任何缺失值:
```
# check missing values in data
data.isnull().sum()
```
id 0
感悟 0
回顾 0
dtype: int64
输出显示我们的数据集没有任何缺失值。
### 如何评价班级分布
我们可以使用 Pandas 包中的 ****`value_counts()`**** 方法来评估数据集的类分布。
```
# evalute news sentiment distribution
data.sentiment.value_counts()
```
1 12500
0 12500
名称:情操,数据类型:int64
在这个数据集中,我们有相同数量的正面和负面评论。
### 如何处理数据
在分析数据集之后,下一步是在创建我们的机器学习模型之前,将数据集预处理成正确的格式。
这个数据集中的评论包含了很多我们在创建机器学习模型时不需要的不必要的单词和字符。
我们将通过删除停用字词、数字和标点来清理邮件。然后我们将使用 NLTK 包中的词汇化过程将每个单词转换成它的基本形式。
****`text_cleaning()`**** 函数将处理所有必要的步骤来清理我们的数据集。
```
stop_words = stopwords.words('english')
def text_cleaning(text, remove_stop_words=True, lemmatize_words=True):
# Clean the text, with the option to remove stop_words and to lemmatize word
# Clean the text
text = re.sub(r"[^A-Za-z0-9]", " ", text)
text = re.sub(r"\'s", " ", text)
text = re.sub(r'http\S+',' link ', text)
text = re.sub(r'\b\d+(?:\.\d+)?\s+', '', text) # remove numbers
# Remove punctuation from text
text = ''.join([c for c in text if c not in punctuation])
# Optionally, remove stop words
if remove_stop_words:
text = text.split()
text = [w for w in text if not w in stop_words]
text = " ".join(text)
# Optionally, shorten words to their stems
if lemmatize_words:
text = text.split()
lemmatizer = WordNetLemmatizer()
lemmatized_words = [lemmatizer.lemmatize(word) for word in text]
text = " ".join(lemmatized_words)
# Return a list of words
return(text)
```
现在我们可以通过使用 ****text_cleaning()**** 函数来清理我们的数据集:
```
#clean the review
data["cleaned_review"] = data["review"].apply(text_cleaning)
```
然后将数据分成特征变量和目标变量,如下所示:
```
#split features and target from data
X = data["cleaned_review"]
y = data.sentiment.values
```
我们用于训练的特征是 ****`cleaned_review`**** 变量,目标是 ****`sentiment`**** 变量。
然后,我们将数据集分成训练和测试数据。测试规模是整个数据集的 15%。
```
# split data into train and validate
X_train, X_valid, y_train, y_valid = train_test_split(
X,
y,
test_size=0.15,
random_state=42,
shuffle=True,
stratify=y,
)
```
### 如何创建 NLP 模型
我们将训练多项式[朴素贝叶斯](https://www.freecodecamp.org/news/how-naive-bayes-classifiers-work/)算法来分类评论是正面还是负面。这是文本分类最常用的算法之一。
但是在训练模型之前,我们需要将我们清理过的评论转换成数值,以便模型能够理解这些数据。
在这种情况下,我们将从 scikit-learn 中使用 [****`TfidfVectorizer`**** 的方法。TfidfVectorizer 将帮助我们将一组文本文档转换为 TF-IDF 特征矩阵。](https://www.freecodecamp.org/news/how-to-extract-keywords-from-text-with-tf-idf-and-pythons-scikit-learn-b2a0f3d7e667/)
为了应用这一系列步骤(预处理和训练),我们将使用来自 scikit-learn 的一个[管道类](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html?ref=hackernoon.com),它顺序应用一系列转换和一个最终估计器。
```
# Create a classifier in pipeline
sentiment_classifier = Pipeline(steps=[
('pre_processing',TfidfVectorizer(lowercase=False)),
('naive_bayes',MultinomialNB())
])
```
然后我们像这样训练我们的分类器:
```
# train the sentiment classifier
sentiment_classifier.fit(X_train,y_train)
```
然后,我们根据验证集创建一个预测:
```
# test model performance on valid data
y_preds = sentiment_classifier.predict(X_valid)
```
将使用 ****`accuracy_score`**** 评估指标来评估模型的性能。我们使用 accuracy_score 是因为我们在情感变量中有相同数量的类。
```
accuracy_score(y_valid,y_preds)
```
0.8629333333333333
我们的模型的准确度在 ****86.29%**** 左右,这是很好的性能。
### 如何保存模型管线
我们可以使用 ****`joblib`**** Python 包将模型管道保存在模型的目录下。
```
#save model
import joblib
joblib.dump(sentiment_classifier, '../models/sentiment_model_pipeline.pkl')
```
现在我们已经构建了 NLP 模型,让我们学习如何使用 FastAPI。
## 什么是 FastAPI?
FastAPI 是一个快速的现代 Python web 框架,用于构建不同的[API](https://hackernoon.com/how-to-use-the-requests-python-library-to-make-an-api-call-and-save-it-as-a-pandas-dataframe-z43k33rm?ref=hackernoon.com)。它提供了更高的性能,更容易编码,并且提供了自动和交互式的文档。

FastAPI 建立在两个主要的 Python 库 ****— Starlette**** (用于 web 处理)和 ****Pydantic**** (用于数据处理和验证)。与 Flask 相比,FastAPI 非常快,因为它将异步函数处理程序带到了表中。
如果你想了解 FastAPI 的更多信息,我推荐你阅读 Sebastián Ramírez 的这篇文章。
在本文中,我们将尝试使用 FastAPI 的一些特性来服务于我们的 NLP 模型。
### 如何安装 FastAPI
首先,确保你安装了最新版本的 FastAPI(带 pip):
```
pip install fastapi
```
你还需要一个 ASGI 服务器用于生产,比如[uvicon](http://www.uvicorn.org/?ref=hackernoon.com)。
```
pip install uvicorn
```
## 如何用 FastAPI 部署 NLP 模型
在本节中,我们将使用 FastAPI 将我们训练过的 [NLP](https://www.freecodecamp.org/news/learn-natural-language-processing-no-experience-required/) 模型部署为 REST API。我们将把 API 的代码保存在一个名为 ****main.py**** 的 Python 文件中。这个文件将负责运行我们的 FastAPI 应用程序。
### 导入包
第一步是导入将帮助我们构建 FastAPI 应用程序和运行 NLP 模型的包。
```
# text preprocessing modules
from string import punctuation
# text preprocessing modules
from nltk.tokenize import word_tokenize
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re # regular expression
import os
from os.path import dirname, join, realpath
import joblib
import uvicorn
from fastapi import FastAPI
```
### 如何初始化 FastAPI 应用程序实例
我们可以使用以下代码来初始化 FastAPI 应用程序:
```
app = FastAPI(
title="Sentiment Model API",
description="A simple API that use NLP model to predict the sentiment of the movie's reviews",
version="0.1",
)
```
如您所见,我们已经定制了 FastAPI 应用程序的配置,包括:
* API 的标题
* API 的描述。
* API 的版本。
### 如何加载 NLP 模型
为了加载 NLP 模型,我们将使用 ****`joblib.load()`**** 方法并将路径添加到模型目录中。NLP 模型的名称是 ****`sentiment_model_pipeline.pkl`**** :
```
# load the sentiment model
with open(
join(dirname(realpath(__file__)), "models/sentiment_model_pipeline.pkl"), "rb"
) as f:
model = joblib.load(f)
```
### 如何定义一个函数来清理数据
我们将使用第 1 部分中的同一个函数 ****`text_cleaning()`**** ,它通过删除停用词、数字和标点来清除评论数据。最后,我们将通过使用 [NLTK 包](https://www.freecodecamp.org/news/natural-language-processing-tutorial-with-python-nltk/)中的词汇化过程将每个单词转换成它的基本形式。
```
def text_cleaning(text, remove_stop_words=True, lemmatize_words=True):
# Clean the text, with the option to remove stop_words and to lemmatize word
# Clean the text
text = re.sub(r"[^A-Za-z0-9]", " ", text)
text = re.sub(r"\'s", " ", text)
text = re.sub(r"http\S+", " link ", text)
text = re.sub(r"\b\d+(?:\.\d+)?\s+", "", text) # remove numbers
# Remove punctuation from text
text = "".join([c for c in text if c not in punctuation])
# Optionally, remove stop words
if remove_stop_words:
# load stopwords
stop_words = stopwords.words("english")
text = text.split()
text = [w for w in text if not w in stop_words]
text = " ".join(text)
# Optionally, shorten words to their stems
if lemmatize_words:
text = text.split()
lemmatizer = WordNetLemmatizer()
lemmatized_words = [lemmatizer.lemmatize(word) for word in text]
text = " ".join(lemmatized_words)
# Return a list of words
return text
```
### 如何创建预测端点
下一步是用 GET 请求方法添加我们的预测端点“ ****/predict-review**** ”。
```
@app.get("/predict-review")
```
> API 端点是两个系统交互时通信通道的入口点。它指的是 API 和服务器之间的通信接触点。
然后我们为这个端点定义一个预测函数。该功能的名称是 ****`predict_sentiment()`**** 带评审参数。
predict _ perspective()函数将执行以下任务:
* 收到影评。
* 使用 ****text_cleaning()**** 功能清理电影评论。
* 使用我们的 NLP 模型进行预测。
* 将预测结果保存在 ****输出**** 变量中(0 或 1)。
* 将预测的概率保存在 ****probas**** 变量中,并格式化为两位小数。
* 最后,返回预测和概率结果。
```
@app.get("/predict-review")
def predict_sentiment(review: str):
"""
A simple function that receive a review content and predict the sentiment of the content.
:param review:
:return: prediction, probabilities
"""
# clean the review
cleaned_review = text_cleaning(review)
# perform prediction
prediction = model.predict([cleaned_review])
output = int(prediction[0])
probas = model.predict_proba([cleaned_review])
output_probability = "{:.2f}".format(float(probas[:, output]))
# output dictionary
sentiments = {0: "Negative", 1: "Positive"}
# show results
result = {"prediction": sentiments[output], "Probability": output_probability}
return result
```
以下是 ****main.py**** 文件中的所有代码块:
```
# text preprocessing modules
from string import punctuation
# text preprocessing modules
from nltk.tokenize import word_tokenize
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re # regular expression
import os
from os.path import dirname, join, realpath
import joblib
import uvicorn
from fastapi import FastAPI
app = FastAPI(
title="Sentiment Model API",
description="A simple API that use NLP model to predict the sentiment of the movie's reviews",
version="0.1",
)
# load the sentiment model
with open(
join(dirname(realpath(__file__)), "models/sentiment_model_pipeline.pkl"), "rb"
) as f:
model = joblib.load(f)
# cleaning the data
def text_cleaning(text, remove_stop_words=True, lemmatize_words=True):
# Clean the text, with the option to remove stop_words and to lemmatize word
# Clean the text
text = re.sub(r"[^A-Za-z0-9]", " ", text)
text = re.sub(r"\'s", " ", text)
text = re.sub(r"http\S+", " link ", text)
text = re.sub(r"\b\d+(?:\.\d+)?\s+", "", text) # remove numbers
# Remove punctuation from text
text = "".join([c for c in text if c not in punctuation])
# Optionally, remove stop words
if remove_stop_words:
# load stopwords
stop_words = stopwords.words("english")
text = text.split()
text = [w for w in text if not w in stop_words]
text = " ".join(text)
# Optionally, shorten words to their stems
if lemmatize_words:
text = text.split()
lemmatizer = WordNetLemmatizer()
lemmatized_words = [lemmatizer.lemmatize(word) for word in text]
text = " ".join(lemmatized_words)
# Return a list of words
return text
@app.get("/predict-review")
def predict_sentiment(review: str):
"""
A simple function that receive a review content and predict the sentiment of the content.
:param review:
:return: prediction, probabilities
"""
# clean the review
cleaned_review = text_cleaning(review)
# perform prediction
prediction = model.predict([cleaned_review])
output = int(prediction[0])
probas = model.predict_proba([cleaned_review])
output_probability = "{:.2f}".format(float(probas[:, output]))
# output dictionary
sentiments = {0: "Negative", 1: "Positive"}
# show results
result = {"prediction": sentiments[output], "Probability": output_probability}
return result
```
### 如何运行 API
以下命令将帮助我们运行我们创建的 FastAPI 应用程序。
```
uvicorn main:app --reload
```
下面是我们为 uvicorn 定义的运行 FastAPI 应用程序的设置。
* ****main:**** 拥有 FastAPI app 的文件 main.py。
* ****app:**** 在 main.py 内部用 app = FastAPI()行创建的对象。
* ****—重新加载**** :每当我们修改代码时,使服务器自动重启。

FastAPI 提供了一个自动交互式 API 文档页面。要访问它,请在浏览器中导航至[****http://127 . 0 . 0 . 1:8000/docs****](http://127.0.0.1:8000/docs),然后您将看到由 FastAPI 自动创建的文档页面。

文档页面显示了我们的 API 的名称、描述及其版本。它还显示了 API 中您可以与之交互的可用路线列表。
要进行预测,首先点击 ****预测-回顾**** 路线然后点击 ****按钮试走**** 。这允许您填充 review 参数并直接与 API 交互。

通过添加您选择的电影评论来填写评论栏。我补充了以下关于 2021 年上映的 ****【扎克·施奈德版正义联盟】**** 电影的影评。
> “我从头到尾都很喜欢这部电影。就像雷·费希尔说的,我希望这部电影不会结束。乞讨的场景令人兴奋,我非常喜欢那个场景。不像《正义联盟》这部电影展示了每个英雄最擅长自己的事情,让我们热爱每一个角色。谢谢扎克和整个团队。”
然后点击执行按钮进行预测,得到结果。

最后,来自 API 的结果显示,我们的 NLP 模型预测所提供的评论具有**正面情感,概率为 ****0.70**** :**
****
## **如何在任何 Python 应用程序中使用 NLP 模型**
**要在任何 Python 应用程序中使用我们的 NLP API,我们需要安装 requests Python 包。这个包将帮助我们向我们开发的 FastAPI 应用程序发送 HTTP 请求。**
**要安装请求包,请运行以下命令:**
```
`pip install requests`
```
**然后创建一个简单的 Python 文件叫做 ****`python_app.py`**** 。这个文件将负责发送我们的 HTTP 请求。**
**我们首先导入请求包:**
```
`import requests as r`
```
**补充一个关于 ****哥斯拉大战孔【2021】****电影的影评:**
```
`# add review
review = "This movie was exactly what I wanted in a Godzilla vs Kong movie. It's big loud, brash and dumb, in the best ways possible. It also has a heart in a the form of Jia (Kaylee Hottle) and a superbly expressionful Kong. The scenes of him in the hollow world are especially impactful and beautifully shot/animated. Kong really is the emotional core of the film (with Godzilla more of an indifferent force of nature), and is done so well he may even convert a few members of Team Godzilla."`
```
**然后在要传递给 HTTP 请求的关键参数中添加审查:**
```
`keys = {"review": review}`
```
**最后,我们向我们的 API 发送一个请求,对评论进行预测:**
```
`prediction = r.get("http://127.0.0.1:8000/predict-review/", params=keys)`
```
**然后我们可以看到预测结果:**
```
`results = prediction.json()
print(results["prediction"])
print(results["Probability"])`
```
**这将显示预测及其概率。结果如下:**
**正
0.54**
## **包扎**
**恭喜👏👏,你已经熬到这篇文章的结尾了。我希望您已经学到了一些新东西,现在知道如何用 FastAPI 部署您的 NLP 模型。**
**如果你想了解更多关于 FastAPI 的知识,我推荐你参加由[bitfuses](https://twitter.com/bitfumes?ref=hackernoon.com)创建的[完整 FastAPI 课程](https://www.youtube.com/watch?v=7t2alSnE2-I&ref=hackernoon.com)。**
**你可以在这里下载本文使用的[项目源代码。](https://github.com/Davisy/Deploy-NLP-Model-with-FastAPI)**
**如果你学到了新的东西或者喜欢阅读这篇文章,请分享给其他人看。在那之前,下一篇文章再见!。**
**你也可以在推特上找到我 [@Davis_McDavid](https://twitter.com/Davis_McDavid?ref=hackernoon.com)**
|
import { useCallback } from "react";
import PlayPauseButton from "./PlayPauseButton.jsx";
import Video from "./Video.jsx";
import { useContext } from "react";
import VideosToRenderContext from "../context/videosToRenderContext.jsx";
function VideoList({ updateVideo }) {
const videosToRender = useContext(VideosToRenderContext);
return (
<>
{videosToRender.map((val) => {
return (
<Video key={val.id} {...val} updateVideo={updateVideo}>
<PlayPauseButton
onPause={() => {
alert(`paused + ${val.title}`);
}}
onPlay={() => {
alert(`playing + ${val.title}`);
}}
></PlayPauseButton>
</Video>
);
})}
</>
);
}
export default VideoList;
|
import React, { useEffect, useState } from 'react';
import './SecondaryNavStyles.css';
import { Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import { useSearchProductsQuery } from '../../features/search';
import { selectCurrentToken } from '../../features/authSlice';
import { useSelector } from 'react-redux';
function SecondaryNav() {
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState([]);
const url = `products?search=${searchQuery}`
const { data, error, isLoading } = useSearchProductsQuery(url)
const token = useSelector(selectCurrentToken)
const handleSearch = async () => {
try {
setSearchResults(
(data?.braceletDetails || []).concat(
data?.chainDetails || [],
data?.limitedDropDetails || [],
data?.ringDetails || [],
data?.shirtDetails || [],
data?.newReleaseDetails || []
)
)
} catch (error) {
console.error('Error searching for products:', error);
}
};
useEffect(() => {
const offCanvas = document.getElementById('offcanvasRight');
if (offCanvas) {
const offCanvasCloseButton = offCanvas.querySelector('.btn-close');
if (offCanvasCloseButton) {
offCanvasCloseButton.click();
}
}
}, [window.location.pathname]);
return (
<div className="secondary-nav-wrapper ">
<div className="row p-1">
<div className="container p-0 px-4">
<div className="col-md-2 col-sm-none"></div>
<div className="col-md-8 col-lg-8 mid col-sm-10">
<ul className='p-0 my-2 parent'>
<Link to="/new-releases" className='text-decor noeffect'><li className='list-none text-uppercase me-4 d-none d-md-block p-1' ><span>New Releases</span></li></Link>
<li className='list-none '>
<div className="dropdown3">
<div className='dropdown3-btn btn text-dark text-uppercase'>
<span> Clothing</span> <i className="bi bi-chevron-down down-arrow mx-1"></i>
</div>
<div className="dropmenu3">
<ul className='p-3'>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/Shirts">Shirts</Link></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/tankTops">Tank Tops</Link></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/coming-soon">Pants</Link> <span style={{ fontSize: '10px', textDecoration: 'underline' }} className='text-dark p-1 rounded-1 ms-4 '>Coming Soon</span></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/coming-soon">TrackSuits</Link> <span style={{ fontSize: '10px', textDecoration: 'underline' }} className='text-dark p-1 rounded-1 ms-4 '>Coming Soon</span></li>
</ul>
</div>
</div>
</li>
<li className='list-none '>
<div className="dropdown3">
<div className='dropdown3-btn btn text-dark text-uppercase'>
<span> Assessories</span> <i className="bi bi-chevron-down down-arrow mx-1"></i>
</div>
<div className="dropmenu3">
<ul className='p-3'>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/Pendants">Pendants</Link></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/chains">Chains </Link></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/Rings">Rings </Link></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/Bracelets">Bracelets</Link></li>
</ul>
</div>
</div>
</li>
<li className='list-none '>
<div className="dropdown3">
<div className='dropdown3-btn btn text-dark text-uppercase'>
<span> about us</span> <i className="bi bi-chevron-down down-arrow mx-1"></i>
</div>
<div className="dropmenu3">
<ul className='p-1'>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/contact">Contact Us</Link></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/faq">FAQs</Link></li>
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/return-refund">Returns & Refunds</Link></li>
{
token ?
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark text-uppercase' to=""></Link></li>
:
<li className='list-none m-2'><Link className='text-decor fs-6 text-dark ' to="/account/login">Account</Link></li>
}
</ul>
</div>
</div>
</li>
</ul>
</div>
<div className="col-md-2 end m-1">
<button class="btn w-25 p-0" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight"><i className="bi bi-search fs-5 mx-1 text-dark"></i></button>
<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
<button type="button" class="btn-close d-none" data-bs-dismiss="offcanvas" aria-label="Close"></button>
<div class="offcanvas-header">
</div>
<div class="offcanvas-body">
<div className="search-input">
<input className='w-100 p-2' placeholder='Search' type="text" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
<button type='submit' onClick={handleSearch} className='btn p-2 w-25'><i class="icon bi bi-search"></i></button>
</div>
{searchResults.length >= 1 && (
<div className='py-3 row m-0' >
{searchResults.map((item, idx) => (
<Link to={`/${item.productId}/${item._id}`} className='p-0'><div key={idx} className='d-flex mb-3 border border-dark p-0'>
<div className='col-3'>
<img src={item.img[0]} alt="" width='80' height='80' />
</div>
<div className="col-9">
<h6 className='text-center pt-2'>{item.name}</h6>
<p className='text-center'>{item.price}</p>
</div>
</div>
</Link>
))}
</div>
)}
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default SecondaryNav
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:document_mobile/app/widget/folder_list.dart';
import 'package:document_mobile/src/bussiness/folder/bloc/folder_bloc.dart';
class FolderSearch extends SearchDelegate<List> {
String? searchText;
final String? hintText;
FolderSearch(this.hintText) : super(searchFieldLabel: "My own hint");
@override
String? get searchFieldLabel => hintText;
@override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
onPressed: () {
query = '';
close(context, []);
},
icon: const Icon(Icons.clear_outlined))
];
}
@override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, []);
},
icon: const Icon(Icons.arrow_back_ios_outlined));
}
@override
Widget buildResults(BuildContext context) {
searchText = query;
return BlocProvider(
create: ((context) => FolderBloc(RepositoryProvider.of(context))
..add(FolderPrivateSearchEvent(searchText: query))),
child: BlocConsumer<FolderBloc, FolderState>(
listener: (context, state) {
if (state is PrivateSearchError) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(state.error)));
}
},
builder: (context, state) {
if (state is PrivateSearchLoading) {
return const Center(
child: CircularProgressIndicator(
color: Colors.redAccent,
),
);
}
if (state is PrivateSearchLoaded) {
if (state.privateFolderSearch.result!.isEmpty) {
return const Center(
child: Text('No Folder Search'),
);
} else {
return FolderList(folderList: state.privateFolderSearch);
}
}
return Container();
},
),
);
}
@override
Widget buildSuggestions(BuildContext context) {
return Container();
}
}
|
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import PlanModalUtil from "../../../utils/Modals/PlanModalUtil/PlanModalUtil";
import css from "./CourseCardWithOptions.module.css";
import playIcon from "/icons/play-button.png";
import dotsIcon from "/icons/dots.png";
import Rating from "react-rating";
import { AiFillStar, AiOutlineStar } from "react-icons/ai";
import Button1 from "../../../utils/Buttons/Button1/Button1";
import instance from "../../../config/instance";
import Swal from "sweetalert2";
const CourseCardWithOptions = (props) => {
const { isOptions = false, options, data } = props;
const [modal, setModal] = useState(false);
const [rate, setRate] = useState(0);
const [reviewText, setReviewText] = useState("");
const {
path = "",
img = {},
_id = 0,
ttl = "",
author = "",
rating = 0,
courseCoveredPercent = 0,
} = data;
const [menuBox, setMenuBox] = useState(false);
useEffect(() => {
window.addEventListener("click", (e) => {
if (e.target.id !== `cwo-${_id}`) {
return setMenuBox(false);
}
});
return () => {
window.removeEventListener("click", (e) => {
if (e.target.id !== `cwo-${_id}`) {
return setMenuBox(false);
}
});
};
}, []);
const handleChangeComment = (e) => {
setReviewText(e.target.value);
};
const onSubmitRating = async () => {
try {
const response = await instance.post(`course/${_id}/reviews`, {
reviewText,
rating: rate,
});
console.log(response);
Swal.fire("Berhasil memberikan rating", "", "success");
} catch (error) {
console.log(error);
Swal.fire(error?.response?.data?.message, "", "error");
}
setModal(false);
};
const content = (
<>
<h3 className={css.mHeader}>Beri Rating Pada Kursus Ini</h3>
<p className={css.mtxt}>Pilih Rating</p>
<div className={css.stars}>
<Rating
onClick={setRate}
initialRating={rate}
emptySymbol={<AiOutlineStar size={40} color="black" />}
fullSymbol={<AiFillStar size={40} color="orange" />}
/>
</div>
<label>Tambahkan Komentar Anda :</label>
<textarea
onChange={handleChangeComment}
className={css.textarea}
name="comment"
cols="50"
rows="10"
></textarea>
<Button1
onClick={onSubmitRating}
txt="Kirim"
bck="var(--primary)"
hovBck="var(--primary-dark)"
extraCss={{
width: "100%",
margin: "1rem 0",
padding: "1rem",
border: "none",
color: "var(--white)",
}}
/>
</>
);
const modalHandler = (e) => {
e.preventDefault();
setModal((prev) => !prev);
};
return (
<>
{modal ? (
<PlanModalUtil setModal={setModal} content={content} />
) : null}
<Link to={`/course/view/${_id}`} className={css.outerDiv}>
{isOptions ? (
<div
className={css.optionsBox}
onClickCapture={(e) => e.preventDefault()}
>
<button
id={`cwo-${_id}`}
type="button"
className={css.menuBtn}
onClick={() => setMenuBox((prev) => !prev)}
>
<img
src={dotsIcon}
className={css.menuIcon}
id={`cwo-${_id}`}
/>
{menuBox ? (
<div className={css.menuBox}>
{options?.map((Option, index) => {
return (
<div
key={index}
className={css.optionComp}
>
{Option}
</div>
);
})}
</div>
) : null}
</button>
</div>
) : null}
<div className={css.imgBox}>
<img src={img.url} alt="course image" className={css.img} />
<div className={css.hovImgBox}>
<img
src={playIcon}
alt="play icon"
className={css.hovImg}
/>
</div>
</div>
<div className={css.bdy}>
<div className={css.ttl}>{ttl}</div>
<div className={css.author}>{author}</div>
{/* <progress
value={76}
max="100"
className={css.progressBar}
/> */}
<div className={css.footerBox}>
{/* <span className={css.txt}>
{courseCoveredPercent}% complete
</span> */}
<span className={css.txt}>Lanjut belajar</span>
<span className={css.starsRatings}>
<span></span>
<span onClick={modalHandler}>Leave a rating</span>
</span>
</div>
</div>
</Link>
</>
);
};
export default CourseCardWithOptions;
|
package com.datcute.chatapplication;
import android.Manifest;
import android.app.Dialog;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import com.datcute.chatapplication.databinding.ActivityUpdateProfileBinding;
import com.datcute.chatapplication.fragment.FragmentMessage;
import com.datcute.chatapplication.fragment.FragmentSetting;
import com.datcute.chatapplication.service.ImgUploadService;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class UpdateProfileActivity extends AppCompatActivity {
private ActivityUpdateProfileBinding binding;
public static final int MY_REQUEST_CODE = 10;
private Uri uriImage;
public UpdateProfileActivity() {
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
binding = ActivityUpdateProfileBinding.inflate(getLayoutInflater());
binding.btnupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(uriImage != null){
scheduleJob(String.valueOf(uriImage));
Toast.makeText(UpdateProfileActivity.this,"đang tiến hành cập nhật" ,Toast.LENGTH_LONG).show();
finish();
}
}
});
binding.img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openGallery();
}
});
setContentView(binding.getRoot());
}
private void scheduleJob(String imageUri) {
Intent jobIntent = new Intent(this, ImgUploadService.class);
// Tạo một PersistableBundle và thêm dữ liệu cần truyền
PersistableBundle persistableBundle = new PersistableBundle();
persistableBundle.putString(ImgUploadService.EXTRA_IMAGE_URI,imageUri);
jobIntent.putExtra(ImgUploadService.EXTRA_PERSISTABLE_BUNDLE, persistableBundle);
// Đặt các thông tin khác vào Intent
jobIntent.setAction(ImgUploadService.ACTION_UPLOAD_IMAGE);
// Tạo một JobInfo và thêm công việc vào JobScheduler
JobInfo jobInfo = new JobInfo.Builder(1, new ComponentName(this, ImgUploadService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setExtras(persistableBundle)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobInfo);
}
public void openGallery() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
activityResultLauncher.launch(Intent.createChooser(intent, "Select image"));
}
private ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
Intent intent = result.getData();
if (intent == null) {
return;
}
uriImage = intent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriImage);
setImg(bitmap);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
public void setImg(Bitmap bitmap){
binding.img.setImageBitmap(bitmap);
}
}
|
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
UseInterceptors,
UseGuards,
UploadedFiles,
Req,
BadRequestException,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { WorkerService } from './worker.service';
import { CreateWorkerDto } from './dto/create-worker.dto';
import { UpdateWorkerDto } from './dto/update-worker.dto';
import { CurrentUserInterceptor } from 'src/users/interceptors/current-user.interceptor';
import { AuthGuard } from 'src/guards/auth.guard';
import {
FileFieldsInterceptor,
FilesInterceptor,
} from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { FileFilter } from 'src/utils/file-validator';
import { extname } from 'path';
import { WorkerDto } from './dto/worker.dto';
import { Serialize } from 'src/interceptors/serialize.interceptor';
import { UsersService } from 'src/users/users.service';
import { CurrentUser } from 'src/decorators/current-user.decorator';
@Controller('worker')
@UseInterceptors(CurrentUserInterceptor)
@UseGuards(AuthGuard)
// @Serialize(WorkerDto)
export class WorkerController {
constructor(
private readonly workerService: WorkerService,
private readonly usersService: UsersService,
) {}
@Post('create')
@UseInterceptors(
FileFieldsInterceptor([{ name: 'Application', maxCount: 1 }], {
fileFilter: FileFilter,
storage: diskStorage({
destination: './uploads',
filename: (req, file, callback) => {
const uniqueSuffix =
Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = extname(file.originalname);
const filename = `${uniqueSuffix}${ext}`;
callback(null, filename);
},
}),
}),
)
async uploadFile(
@Body() body: CreateWorkerDto,
@UploadedFiles()
files: {
Application?: Express.Multer.File[];
},
@Req() req: any,
@CurrentUser() user: any,
) {
const isEmpty = Object.keys(files).length === 0;
if (isEmpty || !files || req.fileValidationError) {
throw new BadRequestException(req.fileValidationError);
}
const User = await this.usersService.findOneByEmail(body.user_email);
const product = await this.workerService.create(
{
...body,
Application: files?.Application?.[0]?.filename,
},
User,
);
throw new HttpException('CREATED', HttpStatus.CREATED);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.workerService.findOne(+id);
}
// @Patch(':id')
// update(@Param('id') id: string, @Body() updateWorkerDto: UpdateWorkerDto) {
// return this.workerService.update(+id, updateWorkerDto);
// }
// @Delete(':id')
// remove(@Param('id') id: string) {
// return this.workerService.remove(+id);
// }
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* WrongAnimal.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rtissera <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/02/22 10:50:40 by rtissera #+# #+# */
/* Updated: 2024/02/23 19:10:31 by rtissera ### ########.fr */
/* */
/* ************************************************************************** */
#pragma once
/******************************************************************************/
/* INCLUDES */
/******************************************************************************/
#include <iostream>
/******************************************************************************/
/* CLASSES */
/******************************************************************************/
class WrongAnimal {
protected:
std::string _type;
public:
WrongAnimal( void );
WrongAnimal( std::string type );
WrongAnimal( WrongAnimal const & src );
~WrongAnimal( void );
WrongAnimal& operator=( WrongAnimal const & rhs );
std::string getType( void ) const;
void makeSound( void ) const;
};
/******************************************************************************/
/* REDIRECTION OPERATOR */
/******************************************************************************/
std::ostream& operator<<( std::ostream& o, WrongAnimal const & rhs );
|
import { ComponentProps } from "react";
import NextLink from "next/link";
import { button } from "./Button.css";
import cx from "classnames";
import { semanticColorKeymap } from "@/themes/sprinkles/colors.css";
type ButtonProps = ComponentProps<"button">;
type NextLinkProps = ComponentProps<typeof NextLink>;
export type Props = (ButtonProps | NextLinkProps) & {
color?: keyof typeof semanticColorKeymap;
hasPadding?: boolean;
};
export function Button({
color,
hasPadding = true,
className = "",
tabIndex = 0,
...props
}: Props) {
const newClassNames = cx(className, button({ color, hasPadding }));
const sharedProps = { ...props, tabIndex, className: newClassNames };
if ("href" in sharedProps) {
return <NextLink {...sharedProps} />;
} else {
return <button {...sharedProps} />;
}
}
|
package br.com.projectstages_mvc.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import br.com.projectstages_mvc.dao.AmigosDao;
import br.com.projectstages_mvc.dao.CadastroDao;
import br.com.projectstages_mvc.dao.ChatDao;
import br.com.projectstages_mvc.dao.ConfiguracoesDao;
import br.com.projectstages_mvc.dao.NotificacaoAmizadeDao;
import br.com.projectstages_mvc.dao.ParticipantesDao;
import br.com.projectstages_mvc.dao.ProjetoDao;
import br.com.projectstages_mvc.model.Chat;
import br.com.projectstages_mvc.model.Configuracoes;
import br.com.projectstages_mvc.model.NotificacaoAmizade;
import br.com.projectstages_mvc.model.Participantes;
import br.com.projectstages_mvc.model.Projeto;
import br.com.projectstages_mvc.model.Usuario;
@Controller
@Transactional
public class AmigosController {
@Autowired
private CadastroDao cadastroDao;
@Autowired
private NotificacaoAmizadeDao notificacaoDao;
@Autowired
private ChatDao chatDao;
@Autowired
private ProjetoDao projetodao;
@Autowired
private AmigosDao amigosDao;
@Autowired
private ConfiguracoesDao configuracoesDao;
@Autowired
private ParticipantesDao participantesDao;
private Usuario user = new Usuario();
private Configuracoes config = new Configuracoes();
@RequestMapping("/amigos")
@Cacheable(value = "amigo")
public ModelAndView amigos(@AuthenticationPrincipal Usuario usuario) {
ModelAndView model = new ModelAndView("amigos");
List<Usuario> listUsers = new ArrayList<Usuario>();
listUsers = cadastroDao.getAllUsers();
int totalMensagens = 0;
int quantidade = 0;
List<NotificacaoAmizade> msgNotificacoes = new ArrayList<NotificacaoAmizade>();
List<Usuario> listAmigos = new ArrayList<Usuario>();
List<String> listEmailsAmigos = new ArrayList<String>();
List<Chat> listMensagens = new ArrayList<Chat>();
List<Projeto> listaProjetosParticipantes = new ArrayList<Projeto>();
List<Projeto> listaProjetosFavoritos = new ArrayList<Projeto>();
List<Participantes> projetosParticipantes = new ArrayList<Participantes>();
user = cadastroDao.findUsuario(usuario.getUsername());
projetosParticipantes = participantesDao.listarProjetosParticipantes(usuario.getUsername());
msgNotificacoes = notificacaoDao.listarTodasNotificacoesDoDestinatario(usuario.getUsername());
for (int i = 0; i < msgNotificacoes.size(); i++) {
if (msgNotificacoes.get(i).isVisualizacao() == false) {
quantidade++;
}
}
if (quantidade > 0) {
model.addObject("qtnNotificacao", quantidade);
}
// Lista meus amigos
listEmailsAmigos = amigosDao.listarTodosOsAmigos(usuario.getUsername());
for (int i = 0; i < listEmailsAmigos.size(); i++) {
listAmigos.add(cadastroDao.findUsuario(listEmailsAmigos.get(i)));
}
// Mostra o total de mensagens nao lidas.
listMensagens = chatDao.getAllMensagens(usuario.getEmail());
for (int j = 0; j < listMensagens.size(); j++) {
if (listMensagens.get(j).isVisualizacao() == false
&& listMensagens.get(j).getEmailDestinatario().equals(usuario.getEmail())) {
totalMensagens++;
}
}
if (totalMensagens > 0) {
model.addObject("totalMensagens", totalMensagens);
}
for (int i = 0; i < projetosParticipantes.size(); i++) {
listaProjetosParticipantes
.add(projetodao.listarProjetosParticipantePorID(projetosParticipantes.get(i).getIdProjeto()));
}
for (int i = 0; i < projetosParticipantes.size(); i++) {
if(projetosParticipantes.get(i).isProjetoFavorito()) {
listaProjetosFavoritos
.add(projetodao.listarProjetosParticipantePorID(projetosParticipantes.get(i).getIdProjeto()));
}
}
config = configuracoesDao.configuracoesDoUsuario(usuario.getUsername());
model.addObject("usuarios", listUsers);
model.addObject("listaProjeto", projetodao.listarTodosProjetos(usuario.getUsername()));
model.addObject("usuarioFoto", user.getFoto());
model.addObject("usuarioAtual", user);
model.addObject("listaAmigos", listAmigos);
model.addObject("projetosParticipantes", listaProjetosParticipantes);
model.addObject("projetosFavoritos",listaProjetosFavoritos);
return model;
// return "amigos";
}
@RequestMapping("/retorna/pesquisa")
@CacheEvict(value = "amigo", allEntries = true)
@ResponseBody
public List<Integer> getPesquisaUsuario(HttpServletRequest request) {
List<Integer> ids = new ArrayList<Integer>();
String userName = request.getParameter("nome");
List<Usuario> usuario = cadastroDao.pesquisarUsuarioNome(userName);
for (int i = 0; i < usuario.size(); i++) {
ids.add(usuario.get(i).getId());
}
return ids;
}
@RequestMapping("/clear/pesquisa")
@CacheEvict(value = "amigo", allEntries = true)
@ResponseBody
public List<Integer> clearPesquisaUsuario() {
List<Integer> ids = new ArrayList<Integer>();
List<Usuario> listUsers = new ArrayList<Usuario>();
listUsers = cadastroDao.getAllUsers();
for (int i = 0; i < listUsers.size(); i++) {
ids.add(listUsers.get(i).getId());
}
return ids;
}
// Retorna o status do Usuario
@RequestMapping("/retorna/status-usuario/amigos")
@CacheEvict(value = "amigo", allEntries = true)
@ResponseBody
public String getStatusUsuario(@AuthenticationPrincipal Usuario usuario) {
user = cadastroDao.findUsuario(usuario.getUsername());
return user.getStatusUsuario();
}
@RequestMapping("/retorna/modo-noturno/amigos")
@CacheEvict(value = "amigo", allEntries = true)
@ResponseBody
public boolean getModoNotuno() {
return config.isModoNoturno();
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.bootcss.com/vue/2.5.17/vue.min.js"></script>
</head>
<body>
<div id="demo"></div>
<script type="text/javascript">
const components = {
test1: {
id: 'test1',
template: `<div>test1</div>`,
},
test2: {
id: 'test2',
template: `<div>test2</div>`,
},
test3: {
id: 'test3',
template: `<div>test3</div>`,
},
};
const vm = new Vue({
el: '#demo',
data() {
return {
list: [1, 2, 3],
};
},
components,
render(h) {
return h('div', null, [
...this.list.map(() => {
return h('test1', {
ref: 'test'
});
}),
// h('test1', {
// ref: 'test',
// }),
// h('test1', {
// ref: 'test',
// }),
// h('test1', {
// ref: 'test',
// }),
]);
},
// template: `
// <div>
// <test1 v-for="item in list" :key="item" ref="test"></test1>
// </div>
// `
// template: `
// <div>
// <div v-for="item of list">
// <test1 ref="test"></test1>
// </div>
// </div>
// `
});
vm.$mount('#demo');
console.log(vm.$refs.test);
// 无论是v-for组件, 还是v-for下面的组件,相同的ref是数组,render下的全部是对象
</script>
</body>
</html>
|
//155. Min Stack
class MinStack {
stack: number[];
minStack: number[];
constructor() {
this.stack = [];
this.minStack = [];
}
push(val: number): void {
this.stack.push(val);
this.minStack.push(Math.min(val, this.minStack.length === 0 ? val : this.minStack[this.minStack.length - 1]))
}
pop(): void {
this.stack.pop();
this.minStack.pop();
}
top(): number {
return this.stack[this.stack.length - 1];
}
getMin(): number {
return this.minStack[this.minStack.length - 1];
}
}
|
import {
ActivityIndicator,
Pressable,
StyleSheet,
Text,
View,
} from 'react-native';
import React, {FC, useEffect, useState} from 'react';
import {useUserContext} from './context/UserContext';
import {
ChannelList,
Chat as ChatComponent,
DefaultStreamChatGenerics,
OverlayProvider,
} from 'stream-chat-react-native';
import {Channel} from 'stream-chat';
import {ChatScreenProp} from './navigation/types';
import {RFValue} from 'react-native-responsive-fontsize';
const Chat: FC<ChatScreenProp> = ({navigation}) => {
const {user, client, setCurrentChannel} = useUserContext();
const [userSet, setUserSet] = useState(false);
useEffect(() => {
if (!client) return;
if (!user) return;
const connectUser = async () => {
try {
await client.connectUser(
{id: user.name, name: user.name, image: user.image},
client.devToken(user.name),
);
setUserSet(true);
} catch (error) {
console.log({error});
}
};
connectUser();
const disconnectUser = async () => {
await client.disconnectUser();
};
return () => {
disconnectUser();
};
}, []);
useEffect(() => {
if (!userSet) return;
const createChannel = async () => {
const globalChannel = client?.channel('livestream', 'global', {
name: "Segun's Group",
image: 'https://i.pravatar.cc/300',
});
await globalChannel?.watch();
};
createChannel();
}, [userSet]);
const onSelect = (channel: Channel<DefaultStreamChatGenerics>) => {
setCurrentChannel(channel);
navigation.push('Chatroom');
};
const onPlus = () => {
navigation.push('UsersList');
};
return (
<OverlayProvider>
{!client ? (
<View style={styles.loaderContainer}>
<ActivityIndicator size={'large'} />
</View>
) : (
<ChatComponent client={client}>
<View style={styles.container}>
<ChannelList onSelect={onSelect} />
<Pressable style={styles.float} onPress={onPlus}>
<Text style={styles.plus}>+</Text>
</Pressable>
</View>
</ChatComponent>
)}
</OverlayProvider>
);
};
export default Chat;
const styles = StyleSheet.create({
container: {
flex: 1,
},
loaderContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
float: {
width: RFValue(40),
aspectRatio: 1,
borderRadius: RFValue(40) / 2,
backgroundColor: 'white',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
right: RFValue(15),
bottom: RFValue(30),
},
plus: {
fontSize: RFValue(30),
color: 'black',
},
});
|
package com.khalekuzzamanjustcse.common_ui.visual_array
import androidx.compose.animation.core.animateOffsetAsState
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
@Composable
fun CellPointerComposable(
cellSize: Dp,
label: String,
icon: ImageVector = Icons.Default.KeyboardArrowUp,
currentPosition: Offset = Offset.Zero,
) {
val offsetAnimation by animateOffsetAsState(currentPosition, label = "")
Column(
modifier = Modifier
.size(cellSize)
.offset {
IntOffset(offsetAnimation.x.toInt(), offsetAnimation.y.toInt())
},
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(
imageVector = icon,
contentDescription = null
)
Text(
text = label,
modifier = Modifier
)
}
}
|
import { FC, useState, useEffect } from 'react';
import { message, Modal } from 'antd';
import { connect } from 'dva';
import { Link } from 'umi';
import moment from 'moment';
import { unstable_batchedUpdates } from 'react-dom';
import { FetchQueryMidRangeAffluenceAnalyse } from '$services/customeranalysis';
import BasicDataTable from '$common/BasicDataTable';
import SearchContent from '../../Common/SearchContent';
import TableBtn from '../../Common/TableBtn/index.js';
type Props = Readonly<{
userBasicInfo: any,
}>
interface selectProps {
selectAll: boolean,
selectedRowKeys: string[] | number[],
selectedRows: any[],
}
interface pageProps {
pageSize: number,
current: number,
total: number,
}
const DefaultCustomer: FC<Props> = (props) => {
const [loading, setLoading] = useState<boolean>(false);
const [tableVisible, setTableVisible] = useState<boolean>(false);
const [dataSource, setDataSource] = useState<any>([]);
const [pagination, setPagination] = useState<pageProps>({ pageSize: 10, current: 1, total: 0, });
const [selection, setSelection] = useState<selectProps>({ selectAll: false, selectedRowKeys: [], selectedRows: [] });
const [md5, setMd5] = useState<string>('');
const [allParams, setAllParams] = useState<any[]>([]); // 所有子组件参数
const [fetchParams, setFetchParams] = useState<any>({}); // 所有查询字段参数
const [queryMark, setQueryMark] = useState<number>(0); // 作为点击查询的标识
useEffect(() => {
fetchData();
}, [JSON.stringify(pagination), queryMark])
// 根据标识名获取组件值
const getTypeValue = (typeName: string) => {
return allParams.find(item => item.name === typeName)?.value;
}
// 查询table数据
const fetchData = () => {
if(allParams.length > 0) {
setLoading(true);
const params: { [key: string]: any } = {
// queryLevel: 1, // 查询层级,默认为1
// queryValue: props.userBasicInfo.ryid, // 人员id
queryType: 3, // 查询类型 查询类型 0|查询 1|潜在 2|日增 3| 日减 4| 年增 5| 年减
custBelong: getTypeValue('customerAttribution'), // 客户归属
queryCause: getTypeValue('reduceReason').join(), // 减少原因
queryDate: Number(getTypeValue('datePicker')?.format('YYYYMMDD')) || Number(moment().subtract(1, 'days').format('YYYYMMDD')), // 查询日期
depart: getTypeValue('accountOpeningDepartment').join(), // 开户营业部
custsource: getTypeValue('custSource'), // 客户来源
custInfo: getTypeValue('inputBox'), // 客户信息
paging: 1,
current: pagination.current,
pageSize: pagination.pageSize,
};
if(getTypeValue('custSource') === 1) { // 客户来源选择渠道
params['chnl'] = getTypeValue('channel').join();
}
setFetchParams(params);
// console.log('params==========', params);
FetchQueryMidRangeAffluenceAnalyse(params).then((response: any) => {
const { records = [] } = response || {};
unstable_batchedUpdates(() => {
setLoading(false);
setMd5(response.note);
setDataSource(records);
setPagination({...pagination, total: response.total});
})
}).catch((error: any) => {
message.error(!error.success ? error.message : error.note);
});
}
}
const queryData = () => {
setTableVisible(true);
setPagination({ ...pagination, current: 1 });
setSelection({ selectAll: false, selectedRowKeys: [], selectedRows: [] });
setQueryMark(queryMark + 1);
}
// 获取所有组件值
const getAllParams = (paramsList: any[]) => {
setAllParams(paramsList);
}
const getColumns = () => {
return [
{
title: '日期',
dataIndex: 'data',
key: '日期',
},
{
title: '客户号',
dataIndex: 'custCode',
key: '客户号',
},
{
title: '客户姓名',
dataIndex: 'custName',
key: '客户姓名',
render: (text: string, record: any) => <Link to={`/customerPanorama/customerInfo?customerCode=${record.custCode}`} target='_blank'>{text}</Link>,
},
{
title: '开户营业部',
dataIndex: 'accountDepart',
key: '开户营业部',
},
{
title: '减少原因',
dataIndex: 'lessCause',
key: '减少原因',
},
];
}
const controlList = [
{ name: 'customerAttribution' },
{ name: 'reduceReason' },
{ name: 'datePicker' },
{ name: 'inputBox', inputItem: { label: '快速查询', tipContent: '客户号/客户名称' } },
{ name: 'accountOpeningDepartment' },
{ name: 'custSource' }
];
const btnProps = { type: 11, isId: { name: 'ID' }, total: pagination.total, getColumns: getColumns, param: fetchParams, selectAll: selection.selectAll, selectedRows: selection.selectedRows, md5: md5 };
const tableProps = {
bordered: true,
scroll: { x: true },
rowKey: 'key',
dataSource: dataSource.map((item: any, index: number) => {
return { ...item,key: ((pagination.current - 1) * pagination.pageSize) + index + 1 };
}),
columns: getColumns(),
className: 'm-Card-Table',
pagination: {
className: 'm-bss-paging',
showTotal: (totals: number) => {
return `总共${totals}条`;
},
showLessItems: true,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['10', '20', '50', '100'],
total: pagination.total,
paging: 1,
current: pagination.current,
pageSize: pagination.pageSize,
onChange: (current: number, pageSize: number) => {
setPagination({ ...pagination, current, pageSize });
},
onShowSizeChange: (current: number, pageSize: number) => {
setPagination({ ...pagination, current, pageSize });
},
},
rowSelection: {
type: 'checkbox',
crossPageSelect: true, // checkbox默认开启跨页全选
selectAll: selection.selectAll,
selectedRowKeys: selection.selectedRowKeys,
onChange: (currentSelectedRowKeys: string[] | number[], selectedRows: any[], currentSelectAll: boolean) => {
setSelection({ selectAll: currentSelectAll, selectedRowKeys: currentSelectedRowKeys, selectedRows });
},
getCheckboxProps: (record: any) => ({
disabled: record.status === 0, // Column configuration not to be checked
name: record.status,
}),
fixed: true,
},
};
return (
<>
<div style={{ padding: '8px 24px 24px' }}>
<SearchContent getAllParams={getAllParams} queryData={queryData} controlList={controlList} hasDateDefault={true} />
{
tableVisible && (
<>
<TableBtn {...btnProps}/>
<BasicDataTable {...tableProps} style={{ marginBottom: 20 }} loading={loading}/>
</>
)
}
</div>
</>
);
}
export default connect(({ global }: any)=>({
userBasicInfo: global.userBasicInfo,
}))(DefaultCustomer);
|
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Election;
class UpcomingElection extends Component
{
public $currentDateTime;
public function mount(): void
{
$this->currentDateTime = now()->format('Y-m-d H:i:s');
}
public function getUpcomingElections()
{
return Election::where('start', '>', $this->currentDateTime)->get();
}
public function render()
{
return view('livewire.upcoming-election', [
'upcoming_elections' => $this->getUpcomingElections()
]);
}
}
|
// This stateful child component renders all data needed for the puzzle so that
// the user can play. Each number in the puzzle is give its own button. Currently,
// the buttons do not do anything but we plan to add operations buttons so that the
// user can add, subtract, multiply, or divide the numbers they select from the data
// buttons.
import React, { useState } from 'react';
import { checkUser, addScore } from "../Auth/AuthService";
import Parse from "parse";
export default function PuzzleList({ parsed, parsedReset, puzzleId, puzzleName, puzzleDayName }) {
// Keep track of what the user inputted and what button needs to be clicked next
const [gameLog, setGameLog] = useState([]);
// Keep track of the first num, second num, and operator
const [firstNum, setFirstNum] = useState('');
const [firstNumKey, setFirstNumKey] = useState('');
const [secondNum, setSecondNum] = useState('');
const [operation, setOperation] = useState('');
// Keep track of which buttons have been clicked
const [clickedNumbers, setClickedNumbers] = useState({
num1: false,
num2: false,
num3: false,
num4: false,
num5: false,
num6: false,
});
// Keep track of which buttons should disappear
const [showNumbers, setShowNumbers] = useState({
num1: true,
num2: true,
num3: true,
num4: true,
num5: true,
num6: true,
});
// Handle number button clicks
const handleNumberClick = (numberKey, numberValue) => {
// Set button as clicked
setClickedNumbers((prevState) => ({
...prevState,
[numberKey]: true,
}));
// If a number has been selected (second num)
if (firstNum !== '' && firstNumKey !== numberKey && operation !== '') {
setSecondNum(numberValue)
}
// If a number has not been selected yet (first num)
else {
setFirstNumKey(numberKey);
setFirstNum(numberValue);
}
};
// Handle operator button clicks
const handleOperatorClick = (operator) => {
if (firstNum !== '') {
setOperation(operator)
}
};
// Handle reset button clicks
const handleResetClick = () => {
// Reset game log
setGameLog([])
// Reset all button statuses
resetClickedNumbers();
resetShowNumbers();
// Reset all button values
resetButtons();
// Reset both numbers and operation
resetExpression();
};
const validResult = (newResult) => {
// Check for division by 0
if (secondNum === 0 && operation === '/') {
alert('Error! You cannot divide by 0')
resetExpression();
return false
}
// Check for negative numbers
if (firstNum < secondNum && operation === '-') {
alert('Error! You cannot have negative numbers')
resetExpression();
return false
}
// Check for non-integer division
if (operation === '/' && !Number.isInteger(newResult)) {
alert('Error! You must divide evenly')
resetExpression();
return false
}
return true
}
const evalExpression = (the_first_num, the_sec_num) => {
if (operation === '+') {
return the_first_num + the_sec_num
}
else if (operation === '-') {
return the_first_num - the_sec_num
}
else if (operation === '*') {
return the_first_num * the_sec_num
}
else if (operation === '/') {
return the_first_num / the_sec_num
}
}
// Used to insert new score entry into scores database
const insertNewScore = () => {
// Add a score if user is logged in
if (checkUser()) {
const scoreEntry = {
user: Parse.User.current().id,
puzzle: puzzleId,
puzzleName: puzzleName,
puzzleDay: puzzleDayName,
score: 3
}
addScore(scoreEntry);
}
}
// Handle Enter button click and calculate result
const handleEnterClick = () => {
// Find out which two buttons have been clicked
const clickedNums = checkClickedNumbers();
// Evaluate the expression
const expression = firstNum.toString() + operation + secondNum.toString()
const newResult = evalExpression(parseInt(firstNum), parseInt(secondNum));
// Ensure the result is valid
if (!validResult(newResult)) {
return
}
// Hide one button then update another
hideAndUpdate(clickedNums, newResult);
// Update Gamelog
const newExpression = expression + " = " + newResult
setGameLog([...gameLog, newExpression]);
// Reset all buttons to be unclicked
resetClickedNumbers();
// Reset the values of the two numbers and operator
resetExpression();
// Check if the user won the puzzle
if (newResult === parsed["target"]) {
alert("Congratulations! You won! :)")
insertNewScore();
}
};
// Used for gameplay to keep one button and hide the other
const hideAndUpdate = (clickedNums, newResult) => {
// Hide first button
setShowNumbers((prevState) => ({
...prevState,
[clickedNums[0]]: false,
}));
// Update value of second button
parsed[clickedNums[1]] = newResult
}
// Set all buttons to be not clicked
const resetClickedNumbers = () => {
setClickedNumbers({
num1: false,
num2: false,
num3: false,
num4: false,
num5: false,
num6: false,
});
}
// Set all buttons to be shown
const resetShowNumbers = () => {
setShowNumbers({
num1: true,
num2: true,
num3: true,
num4: true,
num5: true,
num6: true,
});
}
// Reset both numbers and operation
const resetExpression = () => {
setFirstNum('')
setSecondNum('')
setOperation('')
}
// Reset the values of all the buttons
const resetButtons = () => {
parsed["num1"] = parsedReset["num1"];
parsed["num2"] = parsedReset["num2"];
parsed["num3"] = parsedReset["num3"];
parsed["num4"] = parsedReset["num4"];
parsed["num5"] = parsedReset["num5"];
parsed["num6"] = parsedReset["num6"];
}
// Find which buttons have been clicked
const checkClickedNumbers = () => {
const clickedNums = []
if (clickedNumbers.num1) {
clickedNums.push("num1")
}
if (clickedNumbers.num2) {
clickedNums.push("num2")
}
if (clickedNumbers.num3) {
clickedNums.push("num3")
}
if (clickedNumbers.num4) {
clickedNums.push("num4")
}
if (clickedNumbers.num5) {
clickedNums.push("num5")
}
if (clickedNumbers.num6) {
clickedNums.push("num6")
}
return clickedNums;
}
const openPopup = () => {
var popup = document.getElementById("popup");
popup.style.display = "block";
}
const closePopup = () => {
var popup = document.getElementById("popup");
popup.style.display = "none";
}
// Check if parsed exists and is an object
if (!parsed || typeof parsed !== 'object') {
return <div>No parsed data available</div>;
}
// Render the buttons
return (
<div className="puzzle-page">
<h1>Puzzle!</h1>
<button className="day-btn" onClick={openPopup}> How to Play </button>
<div id="popup" class="popup">
<h2>How to Play Digits Reborn</h2>
<p><b>Combine Numbers to Reach the Target</b></p>
<ul>
<li>Add, subtract, multiply, and divide any of the six numbers to get the target.</li>
<li>You do not have to use all of the numbers.</li>
<li>As you select buttons, your expression will appear on screen. Hit enter to carry out the expression.</li>
<li>Operations that produce fractions or negative numbers will not be accepted.</li>
</ul>
<button className="day-btn" onClick={closePopup}>Close</button>
</div>
<p><b>Target: {parsed["target"]}</b></p>
<div>
{showNumbers.num1 && (
<button className="home-button" key="num1" onClick={() => handleNumberClick('num1', parsed["num1"])}>
{parsed["num1"]}
</button>
)}
{showNumbers.num2 && (
<button className="home-button" key="num2" onClick={() => handleNumberClick('num2', parsed["num2"])}>
{parsed["num2"]}
</button>
)}
{showNumbers.num3 && (
<button className="home-button" key="num3" onClick={() => handleNumberClick('num3', parsed["num3"])}>
{parsed["num3"]}
</button>
)}
<br/>
{showNumbers.num4 && (
<button className="home-button" key="num4" onClick={() => handleNumberClick('num4', parsed["num4"])}>
{parsed["num4"]}
</button>
)}
{showNumbers.num5 && (
<button className="home-button" key="num5" onClick={() => handleNumberClick('num5', parsed["num5"])}>
{parsed["num5"]}
</button>
)}
{showNumbers.num6 && (
<button className="home-button" key="num6" onClick={() => handleNumberClick('num6', parsed["num6"])}>
{parsed["num6"]}
</button>
)}
<br />
<button className="day-btn" key="add" onClick={() => handleOperatorClick('+')}>
+
</button>
<button className="day-btn" key="sub" onClick={() => handleOperatorClick('-')}>
-
</button>
<button className="day-btn" key="mult" onClick={() => handleOperatorClick('*')}>
x
</button>
<button className="day-btn" key="div" onClick={() => handleOperatorClick('/')}>
/
</button>
<button className="day-btn" key="enter" onClick={handleEnterClick}>
Enter
</button>
<br/>
<button className="day-btn" key="reset" onClick={handleResetClick}>
Reset
</button>
</div>
<br/>
<div>
<p>My selection: {firstNum} {operation} {secondNum}</p>
<p>Game Log:</p>
<ul>
{gameLog.map((logEntry, index) => (
<li key={index}>{logEntry}</li>
))}
</ul>
</div>
</div>
);
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Portfolio</title>
<!-- css link -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/card_carousel.css">
<link rel="stylesheet" type="text/css" href="css/image_hover.css">
<!-- Bootstrap link -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Font Awsome -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- google font link -->
<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=Open+Sans&family=Roboto:wght@400;700&display=swap"
rel="stylesheet">
<!-- Owl Carousel link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css">
<!-- Css Bounce Animation -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
</head>
<body>
<!-- navbar -->
<div class="container-fluid py-lg-3 py-3">
<nav class="navbar sticky navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand fw-bolder ">LOGO</a>
<div class="collapse navbar-collapse" id="navbarTogglerDemo03">
<ul class="navbar-nav mx-auto mb-2 mb-lg-0"><a class="navbar-brand fw-bolder "
href="mailto:[email protected]">[email protected]</a></ul>
<ul class="navbar-nav mb-2 mb-lg-0">
<li class="nav-item ml-10px ">
<a class="nav-link nav-link-ltr " aria-current="page" href="#">Works</a>
</li>
<li class="nav-item ml-10px">
<a class="nav-link nav-link-ltr" href="#">Resume</a>
</li>
<li class="nav-item ml-10px">
<a class="nav-link nav-link-ltr" href="#">Services</a>
</li>
<li class="nav-item ml-10px">
<a class="nav-link nav-link-ltr ml-lg-4" href="#">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
<!-- Main Body -->
<section class="my-lg-4 my-5">
<div class="container">
<div class="row">
<div class="col-lg-6 col-12 ">
<!-- <img style='height: 170px;width: 150px;' src="imagess/photo.jpg"
class="p-1 shadow-lg img-circle mx-auto d-block mb-lg-5 mb-5"> -->
<h4 class="mb-lg-3 mb-5 animate__animated animate__slideInDown ">Hi, I'm
Ratheesh<span>🤘</span>
</h4>
<div class="mb-lg-5 ">
<p class="fs-4-5 h-2em fw-bolder lh-1 mb-lg-0 mb-5">Building digital
<span><strong class="text-slider fs-4-5"></strong></span>
</p>
</div>
<p class="mb-lg-1 fs-5 mb-2">a <b>Product Designer</b> and <b>Visual Developer</b> in SF.</p>
<p class="mb-lg-1 fs-5 mb-2">I specialize in UI/UX Design, Responsive Web Design,</p>
<p class="fs-5 mb-lg-5 mb-5">and Visual Development</p>
<button type="button" class="btn btn-dark btn-lg fs-12 px-5 py-4">CONNECT WITH ME
</button>
</div>
<div class="col-lg-6 col-12 d-lg-block d-none">
<img src="./images/dummy.png" class="d-block w-100" alt="dummy image">
</div>
</div>
</div>
</section>
<!-- Card Section Start-->
<section>
<ul class="cards">
<li>
<a href="" class="card">
<img src="./images/2071.jpg" class="card__image" alt="" />
<div class="card__overlay">
<div class="card__header">
<svg class="card__arc" xmlns="http://www.w3.org/2000/svg">
<path />
</svg>
<img class="card__thumb" src="https://i.imgur.com/7D7I6dI.png" alt="" />
<div class="card__header-text">
<h3 class="card__title">Jessica Parker</h3>
<span class="card__status">1 hour ago</span>
</div>
</div>
<p class="card__description">Lorem ipsum dolor sit amet consectetur adipisicing elit.
Asperiores, blanditiis?</p>
</div>
</a>
</li>
<li>
<a href="" class="card">
<img src="./images/3700_6_10.jpg" class="card__image" alt="" />
<div class="card__overlay">
<div class="card__header">
<svg class="card__arc" xmlns="http://www.w3.org/2000/svg">
<path />
</svg>
<img class="card__thumb" src="https://i.imgur.com/sjLMNDM.png" alt="" />
<div class="card__header-text">
<h3 class="card__title">kim Cattrall</h3>
<span class="card__status">3 hours ago</span>
</div>
</div>
<p class="card__description">Lorem ipsum dolor sit amet consectetur adipisicing elit.
Asperiores, blanditiis?</p>
</div>
</a>
</li>
<li>
<a href="" class="card">
<img src="images/5100_9_02.jpg" class="card__image" alt="" />
<div class="card__overlay">
<div class="card__header">
<svg class="card__arc" xmlns="http://www.w3.org/2000/svg">
<path />
</svg>
<img class="card__thumb" src="https://i.imgur.com/7D7I6dI.png" alt="" />
<div class="card__header-text">
<h3 class="card__title">Jessica Parker</h3>
<span class="card__tagline">Lorem ipsum dolor sit amet consectetur</span>
<span class="card__status">1 hour ago</span>
</div>
</div>
<p class="card__description">Lorem ipsum dolor sit amet consectetur adipisicing elit.
Asperiores, blanditiis?</p>
</div>
</a>
</li>
<li>
<a href="" class="card">
<img src="https://i.imgur.com/2DhmtJ4.jpg" class="card__image" alt="" />
<div class="card__overlay">
<div class="card__header">
<svg class="card__arc" xmlns="http://www.w3.org/2000/svg">
<path />
</svg>
<img class="card__thumb" src="https://i.imgur.com/sjLMNDM.png" alt="" />
<div class="card__header-text">
<h3 class="card__title">kim Cattrall</h3>
<span class="card__status">3 hours ago</span>
</div>
</div>
<p class="card__description">Lorem ipsum dolor sit amet consectetur adipisicing elit.
Asperiores, blanditiis?</p>
</div>
</a>
</li>
</ul>
</section>
<button class="custom-btn btn-13">Read d</button>
<!-- Card Section End -->
<!-- Image Hover -->
<!-- Carousel Section -->
<!-- <div id="carouselExampleFade" class="carousel slide carousel-fade" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="./images/dummy.png" class="d-block w-100" alt="Slider 1">
</div>
<div class="carousel-item">
<img src="./images/dummy.png" class="d-block w-100" alt="Slider 2">
</div>
<div class="carousel-item">
<img src="./images/dummy.png" class="d-block w-100" alt="Slider 3">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div> -->
<!-- Carousel Section End -->
<!-- <section class="my-lg-5 py-lg-4 my-5">
<div class="container">
<div class="row">
<div class="col-lg-4 col-12">
<div class="row">
<div class="col-lg-12">
<div class="hovereffect">
<img class="img-fluid" src="images/6.png" alt="lap">
<div class="overlay">
<h2></h2>
<p class="set1">
<a href="#">
<i class="fa fa-twitter text-light"></i>
</a>
<a href="#">
<i class="fa fa-facebook"></i>
</a>
</p>
<hr>
<hr>
<p class="set2">
<a href="#">
<i class="fa fa-instagram"></i>
</a>
<a href="#">
<i class="fa fa-dribbble"></i>
</a>
</p>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="hovereffect">
<img class="img-responsive" src="images/7.png" alt="lap">
<div class="overlay">
<h2></h2>
<p class="set1">
<a href="#">
<i class="fa fa-twitter"></i>
</a>
<a href="#">
<i class="fa fa-facebook"></i>
</a>
</p>
<hr>
<hr>
<p class="set2">
<a href="#">
<i class="fa fa-instagram"></i>
</a>
<a href="#">
<i class="fa fa-dribbble"></i>
</a>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-12">
<div class="hovereffect">
<img class="img-responsive" src="images/girl_center.png" alt="main">
<div class="overlay">
<a class="info" href="#">@ratheeshneymar</a>
</div>
</div>
</div>
<div class="col-lg-4 col-12">
<div class="row">
<div class="col-lg-12">
<div class="hovereffect">
<img class="img-responsive" src="images/3.png" alt="lap">
<div class="overlay">
<h2></h2>
<p class="set1">
<a href="#">
<i class="fa fa-twitter text-light"></i>
</a>
<a href="#">
<i class="fa fa-facebook"></i>
</a>
</p>
<hr>
<hr>
<p class="set2">
<a href="#">
<i class="fa fa-instagram"></i>
</a>
<a href="#">
<i class="fa fa-dribbble"></i>
</a>
</p>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="hovereffect">
<img class="img-responsive" src="images/4.png" alt="lap">
<div class="overlay">
<h2></h2>
<p class="set1">
<a href="#">
<i class="fa fa-twitter"></i>
</a>
<a href="#">
<i class="fa fa-facebook"></i>
</a>
</p>
<hr>
<hr>
<p class="set2">
<a href="#">
<i class="fa fa-instagram"></i>
</a>
<a href="#">
<i class="fa fa-dribbble"></i>
</a>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section> -->
<!-- Clients Section -->
<!-- <section class="my-lg-5">
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-8 text-center">
<p class="fs-1 fw-normal mb-lg-5 mb-5">Clients</p>
<div class="row text-center">
<div class="col-lg-2 col-12 mb-5 client-img-hover">
<a href="#"><img src="images/google.png" class="img-fluid" alt="google"></a>
</div>
<div class="col-lg-1 col-12"></div>
<div class="col-lg-2 col-12 mb-5 client-img-hover">
<a href="#"><img src="images/amazon.png" class="img-fluid" alt="amazon"></a>
</div>
<div class="col-lg-1 col-12"></div>
<div class="col-lg-2 col-12 mb-5 client-img-hover">
<a href="#"><img src="images/slack.png" class="img-fluid" alt="slack"></a>
</div>
<div class="col-lg-1 col-12"></div>
<div class="col-lg-2 col-12 mb-5 client-img-hover">
<a href="#"><img src="images/uber.png" class="img-fluid" alt="uber"></a>
</div>
</div>
</div>
<div class="col-lg-2"></div>
</div>
</div>
</section> -->
<!-- Services Section -->
<!-- <section class="my-lg-5 py-lg-4 my-5 py-5">
<div class="container">
<div class="row mb-lg-5 mb-5">
<div class="col-lg-12">
<div class="bg-left-half">
<p class="fs-1 py-5 text-center mb-lg-0">Services</p>
<div class="slider owl-carousel">
<div class="card border-0 py-lg-4 py-5 card-mobile">
<div class="content">
<div class="title">
<p class="fs-1 mb-lg-4 mb-5"> 🎯</p>
</div>
<div class="fw-bold fs-4 mb-lg-3">
<p>Strategy & Directions</p>
</div>
<p class="text-secondary">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit modi dolorem quis
quae animi nihil minus sed unde voluptas cumque.
</p>
</div>
</div>
<div class="card border-0 py-lg-4 py-5 card-mobile">
<div class="content">
<div class="title">
<p class="fs-1 mb-lg-4 mb-5"> ✍</p>
</div>
<div class="fw-bold fs-4 mb-lg-3">
<p>Design UI/UX</p>
</div>
<p class="text-secondary">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit modi dolorem quis
quae animi nihil minus sed unde voluptas cumque.
</p>
</div>
</div>
<div class="card border-0 py-lg-4 py-5 card-mobile">
<div class="content">
<div class="title">
<p class="fs-1 mb-lg-4 mb-5"> 📱</p>
</div>
<div class="fw-bold fs-4 mb-lg-3">
<p>Mobile App</p>
</div>
<p class="text-secondary">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit modi dolorem quis
quae animi nihil minus sed unde voluptas cumque.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section> -->
<!-- Resume Section -->
<!-- <section class="my-lg-5 py-lg-5 my-5 py-5">
<div class="container">
<div class="row container-fluid">
<div class="col-lg-12 mb-lg-4">
<p class="display-6 fw-bolder">Resume</p>
</div>
</div>
<div class="row container-fluid">
<div class="col-lg-6 col-12">
<p class="fs-3 fw-bold mb-lg-5">Work Experience</p>
<p class="fs-4 fw-bold mb-lg-1">Uber <i class='fa fa-location-arrow ml-10px'></i></p>
<p class="fs-6 fw-bold mb-lg-1">Product Designer</p>
<p class="fs-6 text-secondary">August 2018 - December 2019</p>
</div>
<div class="col-lg-6 col-12">
<p class="fs-3 fw-bold mb-lg-5">Education</p>
<p class="fs-4 fw-bold mb-lg-1">SUNY Polytechnic Institute <i class='fa fa-location-arrow ml-10px'></i></p>
<p class="fs-6 fw-bold mb-lg-1">Product Designer</p>
<p class="fs-6 text-secondary">August 2018 - December 2019</p>
</div>
</div>
</div>
</section> -->
<!-- Script links -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<!-- jquery link-->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<!-- Owl carousel script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<script>
$(".slider").owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 2000, //2000ms = 2s;
autoplayHoverPause: true,
});
</script>
<!-- text animation js -->
<script src="./js/type-animation.js"> </script>
<script>
if ($(".text-slider").length == 1) {
var typed_strings = $(".text-slider-items").text();
var typed = new Typed(".text-slider", {
strings: ['products ', 'brands', 'and experience'],
typeSpeed: 50,
loop: true,
cursorChar: '',
backDelay: 900,
backSpeed: 30,
});
}
</script>
</body>
</html>
|
package com.cy.algorithm.Oct3;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Yang on 2020/10/3.
*/
public class TwoSum {
/**
* 1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
*/
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0 ; i < nums.length; i++) {
int num = nums[i];
if (map.get(num) != null) {
return new int[] {i, map.get(num)};
}
map.put(target - num, i);
}
return null;
}
}
|
Modules in Python are files containing Python definitions and statements, allowing you to organize your code better and reuse functionalities across different programs.
It covers:
Creating modules with functions and definitions.
Importing modules into scripts or the interactive Python interpreter.
Managing namespaces to avoid conflicts between variables.
Different methods of importing from modules, including importing specific functions or importing all names except those starting with an underscore.
Executing modules as scripts.
The module search path and importing modules from different directories.
How Python caches compiled versions of modules for faster loading.
The concept of packages, which organize modules into a hierarchical structure using dotted module names.
Various ways to import from packages and the use of the __all__ attribute in packages.
It's a comprehensive explanation of how modules and packages work in Python, providing insights into structuring code and organizing functionalities in larger projects.
|
"""Seaborn is a Python data visualization library based on matplotlib that provides a high-level interface for
drawing attractive and informative statistical graphics. It is particularly suited for visualizing complex datasets
and is built to work well with pandas DataFrames, making it an ideal choice for many data science tasks. Seaborn
simplifies the process of creating certain types of plots, including those that show the relationships between
multiple variables.
The sns.pairplot function is used to create a grid of plots for pairwise relationships in a dataset. The function
creates a scatter plot for each pair of variables in your DataFrame, making it an excellent tool for exploratory data
analysis as it allows you to quickly see correlations, trends, and outliers. Additionally, it can plot a histogram or
a kernel density estimate (KDE) on the diagonal to show the distribution of single variables."""
import seaborn as sns # Import the seaborn library
import matplotlib.pyplot as plt # Import matplotlib's pyplot to customize plots further (e.g., display)
from IRIS_DATABASE_SETUP import df
# Use seaborn to visualize the relationships between variables
# Create a pair plot of the DataFrame `df`
# The `hue="target"` parameter colors the points in each plot by the "target" column, which in this case is the species
# of iris.
# This helps to distinguish between different species in each scatter plot.
sns.pairplot(df, hue="target")
# Display the plots
plt.show()
|
//---------------------------------------------------------------------------
// Sketch configuration
//---------------------------------------------------------------------------
// Socket for ATtiny85 on the board is wired as follows:
//
// +--v--+
// nIRQ --PB5--|1 8|--VCC
// Relay A --PB3--|2 7|--PB2-- 3-Wire Clock
// Relay B --PB4--|3 6|--PB1-- 3-Wire Chip Enable
// GND--|4 5|--PB0-- 3-Wire Data
// +-----+
//
// The above pins can be wired to an Arduino UNO for more a convenient
// development flow, see mappings below.
//
// In addition to the pin mapping:
//
// - CFG_ENABLE_RELAYS - Should the relays be toggled on interrupt.
// - CFG_ENABLE_POWERSAVE - Use power saving features.
// - CFG_LOGGING - Send debug logging to Arduino `Serial` out.
// - CFG_ENABLE_BUILT_IN_LED - Use built-in LED for status.
//---------------------------------------------------------------------------
#ifdef ARDUINO_AVR_UNO
// Useful for develpment, replace the ATtiny85 with a UNO board with the
// following wiring.
#define CB_CLOCK_IRQ_PIN 2
#define CB_CLOCK_CE_PIN 4
#define CB_CLOCK_CLK_PIN 5
#define CB_CLOCK_DATA_PIN 6
#define CB_RELAY_A_PIN 8
#define CB_RELAY_B_PIN 9
#define LED_PIN LED_BUILTIN
#define CFG_ENABLE_RELAYS true
#define CFG_ENABLE_POWERSAVE false
#define CFG_ENABLE_LOGGING true
#define CFG_ENABLE_LED false
void irq_start() {
attachInterrupt(digitalPinToInterrupt(CB_CLOCK_IRQ_PIN),
irq_handler,
FALLING);
}
#endif
#ifdef ARDUINO_attiny
#define CB_CLOCK_IRQ_PIN 5
#define CB_CLOCK_CE_PIN 1
#define CB_CLOCK_CLK_PIN 2
#define CB_CLOCK_DATA_PIN 0
#define CB_RELAY_A_PIN 3
#define CB_RELAY_B_PIN 4
#define LED_PIN 4
#define CFG_ENABLE_RELAYS true
#define CFG_ENABLE_POWERSAVE true
#define CFG_ENABLE_LOGGING false
#define CFG_ENABLE_LED false
// Note attachInterrupt() doesn't support PCINT
// interrupts.
void irq_start() {
// Unmask pin-change IRQ on clock IRQ pin.
PCMSK = 1u<<CB_CLOCK_IRQ_PIN;
// Enable pin change IRQ on 0-5.
GIMSK = 0b00100000;
// Enable iterrupts
interrupts();
}
ISR(PCINT0_vect) {
irq_handler();
}
#endif
#ifndef CB_CLOCK_IRQ_PIN
#error "Sketch doesn't support this board."
#endif
// Timing
#define CB_RELAY_SEC_ON 10
#define CB_RELAY_SEC_GAP 10
|
import { compare } from 'bcryptjs'
import { beforeEach, describe, expect, it } from 'vitest'
import { UserAlredyExistsError } from '../../errors/user-alredy-exists-error'
import { InMemoryUsersRepository } from '../../repositories/mock/users-repository'
import { UserRegisterUseCase } from '../userRegister-useCase'
describe('User Register Use Case', () => {
const name = 'Jhon Doe'
const email = '[email protected]'
const password = '123456'
let usersRepository: InMemoryUsersRepository
let sut: UserRegisterUseCase
beforeEach(() => {
usersRepository = new InMemoryUsersRepository()
sut = new UserRegisterUseCase(usersRepository)
})
it('should be able to register', async () => {
const { user } = await sut.execute({
name,
email,
password
})
expect(user.id).toEqual(expect.any(String))
})
it('should hash user password upon registration', async () => {
const { user } = await sut.execute({
name,
email,
password
})
const isPasswordCorrectlyHashed = await compare(password, user.password_hash)
expect(isPasswordCorrectlyHashed).toBe(true)
})
it('should not be able to register with same email twice', async () => {
await sut.execute({
name,
email,
password
})
await expect(async () => await sut.execute({
name,
email,
password
})).rejects.toBeInstanceOf(UserAlredyExistsError)
})
})
|
package com.example.capstoneproject.service.impl;
import com.example.capstoneproject.Dto.*;
import com.example.capstoneproject.Dto.request.HRBankRequest;
import com.example.capstoneproject.Dto.responses.*;
import com.example.capstoneproject.entity.*;
import com.example.capstoneproject.enums.BasicStatus;
import com.example.capstoneproject.enums.RoleType;
import com.example.capstoneproject.enums.StatusReview;
import com.example.capstoneproject.exception.BadRequestException;
import com.example.capstoneproject.mapper.ExperienceMapper;
import com.example.capstoneproject.repository.*;
import com.example.capstoneproject.service.ExpertService;
import com.example.capstoneproject.service.HistoryService;
import com.example.capstoneproject.service.PriceOptionService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import static com.example.capstoneproject.enums.RoleType.EXPERT;
@Service
public class ExpertServiceImpl implements ExpertService {
@Autowired
ExpertRepository expertRepository;
@Autowired
HistoryRepository historyRepository;
@Autowired
HistoryService historyService;
@Autowired
CvRepository cvRepository;
@Autowired
ReviewRequestRepository reviewRequestRepository;
@Autowired
ReviewResponseRepository reviewResponseRepository;
@Autowired
ExperienceMapper experienceMapper;
@Autowired
PriceOptionRepository priceOptionRepository;
@Autowired
ModelMapper modelMapper;
@Autowired
UsersRepository usersRepository;
@Autowired
PriceOptionService priceOptionService;
@Override
public boolean updateExpert(Integer expertId, ExpertUpdateDto dto) {
Users expertOptional = expertRepository.findExpertByIdAndRole_RoleName(expertId, EXPERT);
if (Objects.nonNull(expertOptional)) {
if (expertOptional instanceof Expert) {
Expert expert = (Expert) expertOptional;
if (dto != null) {
if (dto.getAvatar() != null && !dto.getAvatar().equals(expert.getAvatar())) {
expert.setAvatar(dto.getAvatar());
}
if (dto.getName() != null && !dto.getName().equals(expert.getName())) {
expert.setName(dto.getName());
}
if (dto.getJobTitle() != null && !dto.getJobTitle().equals(expert.getJobTitle())) {
expert.setJobTitle(dto.getJobTitle());
}
if (dto.getCompany() != null && !dto.getCompany().equals(expert.getCompany())) {
expert.setCompany(dto.getCompany());
}
if (dto.getAbout() != null && !dto.getAbout().equals(expert.getAbout())) {
expert.setAbout(dto.getAbout());
}
if (dto.getExperiences() != null && !dto.getExperiences().equals(expert.getExperience())) {
expert.setExperience(dto.getExperiences());
}
if (dto.getBankAccountName() != null && !dto.getBankAccountName().equals(expert.getBankAccountName())) {
expert.setBankAccountName(dto.getBankAccountName());
}
if (dto.getBankAccountNumber() != null && !dto.getBankAccountNumber().equals(expert.getBankAccountNumber())) {
expert.setBankAccountNumber(dto.getBankAccountNumber());
}
if (dto.getBankName() != null && !dto.getBankName().equals(expert.getBankName())) {
expert.setBankName(dto.getBankName());
}
if (dto.getPrice() != null) {
priceOptionService.editPriceOption(expert.getId(),dto.getPrice());
}
if(dto.getCvId()!=null){
Optional<Cv> cvOptional = cvRepository.findById(dto.getCvId());
if(cvOptional.isPresent()){
Cv cv = cvOptional.get();
expert.setCvId(cv.getId());
}else{
throw new BadRequestException("Cv ID not found.");
}
}
}
// Lưu lại cả Users và Expert
expertRepository.save(expert);
return true;
}
}
return false;
}
@Override
public ExpertConfigViewDto getExpertConfig(Integer expertId) {
Users expertOptional = expertRepository.findExpertByIdAndRole_RoleName(expertId, EXPERT);
if (Objects.nonNull(expertOptional)){
if (expertOptional instanceof Expert){
Expert expert = (Expert) expertOptional;
ExpertConfigViewDto expertConfigViewDto = new ExpertConfigViewDto();
expertConfigViewDto.setAvatar(expert.getAvatar());
expertConfigViewDto.setName(expert.getName());
expertConfigViewDto.setJobTitle(expert.getJobTitle());
expertConfigViewDto.setCompany(expert.getCompany());
expertConfigViewDto.setAbout(expert.getAbout());
expertConfigViewDto.setExperiences(expert.getExperience());
expertConfigViewDto.setBankAccountName(expert.getBankAccountName());
expertConfigViewDto.setBankName(expert.getBankName());
expertConfigViewDto.setBankAccountNumber(expert.getBankAccountNumber());
List<PriceOption> priceOptions = priceOptionRepository.findAllByExpertId(expert.getId());
if(!priceOptions.isEmpty()){
List<PriceOptionDto> priceOptionDtos = new ArrayList<>();
for(PriceOption priceOption: priceOptions){
PriceOptionDto priceOptionDto = new PriceOptionDto();
priceOptionDto.setDay(priceOption.getDay());
priceOptionDto.setPrice(priceOption.getPrice());
priceOptionDtos.add(priceOptionDto);
}
expertConfigViewDto.setPrice(priceOptionDtos);
}
if(expert.getCvId()!=null){
Optional<Cv> cvOptional = cvRepository.findById(expert.getCvId());
if(cvOptional.isPresent()){
Cv cv = cvOptional.get();
expertConfigViewDto.setCvId(cv.getId());
expertConfigViewDto.setCv(cv.getResumeName());
}
}
return expertConfigViewDto;
}else{
throw new BadRequestException("Cast from User to Expert fail.");
}
}else {
throw new BadRequestException("Expert Id not found.");
}
}
@Override
public List<ExpertViewChooseDto> getExpertList(String search) {
List<Expert> experts;
if (search == null) {
experts = expertRepository.findAllByRole_RoleNameAndPunishFalse(EXPERT);
} else {
experts = expertRepository.findAllByRole_RoleNameAndPunishFalse(EXPERT)
.stream()
.filter(expert -> isMatched(expert, search))
.collect(Collectors.toList());
}
List<ExpertViewChooseDto> result = experts.stream()
.map(this::convertToExpertViewChooseDto)
.filter(Objects::nonNull) // Filter out null values
.filter(dto -> dto.getPrice() != null) // Filter out DTOs with null price
.collect(Collectors.toList());
return result;
}
@Override
public ExpertReviewViewDto getDetailExpert(Integer expertId) {
Optional<Expert> expertOptional = expertRepository.findById(expertId);
ExpertReviewViewDto expertReviewViewDto = new ExpertReviewViewDto();
if(expertOptional.isPresent()){
Expert expert = expertOptional.get();
expertReviewViewDto.setId(expert.getId());
expertReviewViewDto.setName(expert.getName());
expertReviewViewDto.setAvatar(expert.getAvatar());
expertReviewViewDto.setTitle(expert.getJobTitle());
expertReviewViewDto.setStar(calculatorStar(expert.getId()));
expertReviewViewDto.setDescription(expert.getAbout());
expertReviewViewDto.setCompany(expert.getCompany());
expertReviewViewDto.setNumberComment(reviewResponseRepository.countNullCommentsByStatusAndExpertId(StatusReview.Done, expertId));
expertReviewViewDto.setCvId(expert.getCvId());
List<PriceOption> priceOptions = priceOptionRepository.findAllByExpertId(expert.getId());
// Collect prices excluding null values
List<Long> validPrices = priceOptions.stream()
.map(PriceOption::getPrice)
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (!validPrices.isEmpty()) {
long minPrice = Collections.min(validPrices);
long maxPrice = Collections.max(validPrices);
if (minPrice != maxPrice) {
expertReviewViewDto.setPriceMinMax(formatPrice(minPrice) + "-" + formatPrice(maxPrice));
} else {
expertReviewViewDto.setPriceMinMax(formatPrice(minPrice));
}
}
if(!priceOptions.isEmpty()){
List<PriceOptionViewDto> priceOpionDtos = new ArrayList<>();
for(PriceOption priceOption: priceOptions){
PriceOptionViewDto priceOptionViewDto = new PriceOptionViewDto();
priceOptionViewDto.setId(priceOption.getId());
priceOptionViewDto.setDay(priceOption.getDay());
priceOptionViewDto.setPrice(formatPrice(priceOption.getPrice()));
priceOpionDtos.add(priceOptionViewDto);
}
expertReviewViewDto.setPrice(priceOpionDtos);
}
expertReviewViewDto.setExperience(expert.getExperience());
expertReviewViewDto.setNumberReview(calculatorReview(expert.getId()));
List<ReviewResponse> reviewResponses = reviewResponseRepository.findAllByReviewRequest_ExpertId(expertId);
if(reviewResponses==null){
throw new BadRequestException("The system currently cannot find any reviews. Please come back later.");
}else{
List<ExpertReviewRatingViewDto> comments = new ArrayList<>();
for (ReviewResponse reviewResponse : reviewResponses){
if (reviewResponse.getComment() != null){
ExpertReviewRatingViewDto commentDto = new ExpertReviewRatingViewDto();
commentDto.setId(reviewResponse.getReviewRequest().getCv().getUser().getId());
commentDto.setName(reviewResponse.getReviewRequest().getCv().getUser().getName());
commentDto.setAvatar(reviewResponse.getReviewRequest().getCv().getUser().getAvatar());
commentDto.setComment(reviewResponse.getComment());
commentDto.setScore(reviewResponse.getScore());
commentDto.setDateComment(reviewResponse.getDateComment());
comments.add(commentDto);
}
}
expertReviewViewDto.setComments(comments);
}
return expertReviewViewDto;
}else {
throw new BadRequestException("Expert ID not found");
}
}
@Override
public void punishExpert(Integer expertId) {
Optional<Expert> expertOptional = expertRepository.findByIdAndRole_RoleName(expertId, EXPERT);
if(expertOptional.isPresent()){
LocalDate current = LocalDate.now();
Expert expert = expertOptional.get();
expert.setPunish(true);
expert.setPunishDate(current);
expertRepository.save(expert);
}else{
throw new BadRequestException("Expert ID not found");
}
}
@Override
public void unPunishExpert() {
List<Expert> punishedExperts = expertRepository.findByPunishIsTrue();
LocalDate current = LocalDate.now();
for (Expert expert : punishedExperts) {
LocalDate newPunishDate = expert.getPunishDate().plusWeeks(2);
if (newPunishDate.isAfter(current) || newPunishDate.isEqual(current)) {
expert.setPunish(false);
expert.setPunishDate(null);
expertRepository.save(expert);
}
}
// Optional<Expert> expertOptional = expertRepository.findByIdAndUsers_Role_RoleName(expertId, RoleType.EXPERT);
// if(expertOptional.isPresent()){
// LocalDate current = LocalDate.now();
// Expert expert = expertOptional.get();
// LocalDate newPunishDate = expert.getPunishDate().plusWeeks(2);
// if (newPunishDate.isAfter(current) || newPunishDate.isEqual(current)) {
// expert.setPunish(false);
// expert.setPunishDate(newPunishDate);
// expertRepository.save(expert);
// return true;
// } else {
// return false;
// }
// }else{
// throw new BadRequestException("Expert ID not found");
// }
}
@Override
public String update(HRBankRequest dto){
Users users = usersRepository.findUsersById(dto.getId()).get();
if (Objects.nonNull(users)){
if (users instanceof Expert){
Expert expert = (Expert) users;
modelMapper.map(dto, expert);
expertRepository.save(expert);
return "Update succesfully";
} else return "Update fail";
}
throw new BadRequestException("user not found");
}
@Override
public Expert create(Expert dto) {
Expert expert = new Expert();
expert.setName(dto.getName());
expert.setEmail(dto.getEmail());
expert.setPrice(0.0);
expert.setAvatar(dto.getAvatar());
expert.setRole(dto.getRole());
expert.setCreateDate(dto.getCreateDate());
return expertRepository.save(expert);
}
private boolean isMatched(Expert expert, String search) {
return (expert.getName().toLowerCase().contains(search.toLowerCase()) ||
expert.getCompany().toLowerCase().contains(search.toLowerCase()));
}
private ExpertViewChooseDto convertToExpertViewChooseDto(Expert expert) {
List<PriceOption> priceOptions = priceOptionRepository.findAllByExpertId(expert.getId());
if (priceOptions != null && !priceOptions.isEmpty()) {
ExpertViewChooseDto viewChooseDto = new ExpertViewChooseDto();
viewChooseDto.setId(expert.getId());
viewChooseDto.setName(expert.getName());
viewChooseDto.setJobTitle(expert.getJobTitle());
viewChooseDto.setCompany(expert.getCompany());
viewChooseDto.setStar(calculatorStar(expert.getId()));
viewChooseDto.setAvatar(expert.getAvatar());
viewChooseDto.setCompany(expert.getCompany());
// Collect prices excluding null values
List<Long> validPrices = priceOptions.stream()
.map(PriceOption::getPrice)
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (!validPrices.isEmpty()) {
long minPrice = Collections.min(validPrices);
long maxPrice = Collections.max(validPrices);
if (minPrice != maxPrice) {
viewChooseDto.setPrice(formatPrice(minPrice) + "-" + formatPrice(maxPrice));
} else {
viewChooseDto.setPrice(formatPrice(minPrice));
}
viewChooseDto.setExperience(expert.getExperience());
viewChooseDto.setNumberReview(calculatorReview(expert.getId()));
return viewChooseDto;
}
}
return null;
}
private Double calculatorStar(Integer expertId) {
List<ReviewResponse> reviewResponses = reviewResponseRepository.findAllByReviewRequest_ExpertId(expertId);
if (reviewResponses == null || reviewResponses.isEmpty()) {
return 0.0;
} else {
double totalScore = 0.0;
int validScoreCount = 0;
for (ReviewResponse response : reviewResponses) {
Double score = response.getScore();
if (score != null) {
totalScore += score;
validScoreCount++;
}
}
if (validScoreCount == 0) {
return 0.0;
} else {
double averageScore = totalScore / validScoreCount;
return Math.round(averageScore * 100.0) / 100.0;
}
}
}
private Integer calculatorReview(Integer expertId){
List<ReviewResponse> reviewResponses = reviewResponseRepository.findAllByReviewRequest_ExpertId(expertId);
if (reviewResponses == null || reviewResponses.isEmpty()) {
return 0;
} else{
int doneReviewCount = 0;
for (ReviewResponse response : reviewResponses) {
StatusReview status = response.getStatus();
if (status != null && status == StatusReview.Done) {
doneReviewCount++;
}
}
return doneReviewCount;
}
}
public static String formatPrice(long price) {
String priceStr = String.valueOf(price);
int length = priceStr.length();
StringBuilder formattedPrice = new StringBuilder();
for (int i = length - 1; i >= 0; i--) {
formattedPrice.insert(0, priceStr.charAt(i));
// Insert a dot after every 3 digits, but not at the beginning
if ((length - i) % 3 == 0 && i != 0) {
formattedPrice.insert(0, ".");
}
}
return formattedPrice.toString();
}
}
|
public class LeadProcessor implements Database.Batchable<sObject> {
public Database.QueryLocator start(Database.BatchableContext context) {
String query = 'SELECT Id, LeadSource FROM Lead';
return Database.getQueryLocator(query);
}
public void execute(Database.BatchableContext context, List<sObject> scope) {
List<Lead> leadsToUpdate = new List<Lead>();
for (sObject record : scope) {
Lead lead = (Lead)record;
lead.LeadSource = 'Dreamforce';
leadsToUpdate.add(lead);
}
Database.update(leadsToUpdate, false); // Use Database.update to update the leads
// If you want to handle any potential exceptions, you can use try-catch block as well
/*
try {
Database.update(leadsToUpdate, false);
} catch (Exception e) {
// Handle the exception
}
*/
}
public void finish(Database.BatchableContext context) {
// No action needed
}
}
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { of } from 'rxjs';
import { DogResponse, DogsService } from '../dogs.service';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
const mockDogResponse: DogResponse = {
message: 'test',
status: 'success'
}
let mockDogService: jasmine.SpyObj<DogsService>;
mockDogService = jasmine.createSpyObj('DogService', ['get']);
mockDogService.get.and.returnValue(of(mockDogResponse));
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let formElement: HTMLElement;
let usernameInput;
let passwordInput;
let submitButton;
let loginForm;
let usernameControl;
let passwordControl;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [LoginComponent],
imports: [FormsModule, ReactiveFormsModule],
providers: [
{ provide: DogsService, useValue: mockDogService }
]
}).compileComponents();
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.ngOnInit();
fixture.detectChanges();
formElement =
fixture.debugElement.nativeElement.querySelector('#loginForm');
usernameInput = formElement.querySelector('#username');
passwordInput = formElement.querySelector('#password');
submitButton = formElement.querySelector('#submit');
loginForm = component.loginForm;
usernameControl = loginForm.get('username');
passwordControl = loginForm.get('password');
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have the correct inputs', () => {
const inputs = formElement.querySelectorAll('input');
expect(inputs.length).toEqual(2);
});
it('should have the correct initial values and state', () => {
usernameControl = loginForm.get('username');
passwordControl = loginForm.get('password');
const loginFormValues = {
username: '',
password: '',
};
expect(loginForm.value).toEqual(loginFormValues);
expect(loginForm.valid).toBeFalsy();
expect(usernameControl.errors['required']).toBeTruthy();
expect(passwordControl.errors['required']).toBeTruthy();
expect(submitButton.disabled).toBeTruthy;
});
it('should accept valid input', () => {
const loginFormValues = {
username: '[email protected]',
password: 'testing',
};
usernameControl = loginForm.get('username') as FormControl;
passwordControl = loginForm.get('password') as FormControl;
usernameInput.value = '[email protected]';
usernameInput.dispatchEvent(new Event('input'));
passwordInput.value = 'testing';
passwordInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(loginForm.value).toEqual(loginFormValues);
expect(loginForm.valid).toBeTruthy();
expect(usernameControl.errors).toBeNull();
expect(passwordControl.errors).toBeNull();
expect(submitButton.disabled).toBeFalsy;
});
it('should submit the form data when the submit button is clicked', () => {
usernameInput.value = '[email protected]';
usernameInput.dispatchEvent(new Event('input'));
passwordInput.value = 'testing';
passwordInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(submitButton.disabled).toBeFalsy;
submitButton.click();
expect(mockDogService.get).toHaveBeenCalled();
expect(component.dogImgUrl).toBe('test');
});
});
|
# Assignment 1
You can answer the questions below using Python in any IDE, including Jupyter Notebooks. Submissions are only accepted via Github Classroom. If you would like to know how to submit assignments via Github Classroom, please see: https://www.youtube.com/watch?v=ObaFRGp_Eko
## Task 1: Super Mario

In this task you will have to use loops, `if` conditions and the `print` function to build an obstacle similar to the ones you would find in Super Mario. To do this, build a pyramid using hashes (`#`) as building blocks for your pyramid with 5 levels. The output should look like this:
` #`
` ##`
` ###`
` ####`
`#####`
Disclaimer: This problem is inspired by Harvard's cs50 course.
## Task 2: (Super) Super Mario
Write a function that takes as input an argument `levels` and returns a pyramid like in Task 1 with the number of levels equal to `levels` (i.e. the user of you function can decide the number of levels of the pyramid the function will produce). Note that for this function, you do not necessarily need a `return` statement.
## Task 3: Pandas practice
Follow the homework instructions here: https://github.com/ulrichwohak/da-coding-python/tree/main/lecture04-pandas-basics
Write a program that completes the task specified in the link above.
|
import React from 'react'
import { Link } from 'react-router-dom'
function ButtonCard({Button_text = 'Button_text', Title_text = 'Title_text', Detail_text = 'Detail_text', Route, variant = 1}) {
const BUTTON_VARIANT = {
1: "bg-white text-green hover:border hover:border-white hover:text-black hover:bg-lime-100",
2: "bg-white text-red hover:border hover:border-white hover:text-black hover:bg-rose-200"
}
const VARIANT = {
1: "bg-green",
2: "bg-red"
}
return (
<>
{/*Container*/}
<div className={`${VARIANT[variant]} rounded-md md:h-36 md:w-2/3 flex flex-col items-center md:flex-row md:justify-between justify-center`}>
{/*Container IMG & Text*/}
<div className='flex justify-start'>
{/*Container IMG*/}
<div className='p-4 w-fit hidden md:block'>
<img className='h-28 w-28' src='https://openmoji.org/data/color/svg/270D-1F3FB.svg' />
</div>
{/*Container Text*/}
<div className='p-2 mx-2 w-fit md:block'>
<h3 className='text-white my-4 text-2xl md:text-2xl'>{Title_text}</h3>
<p className='text-white text-lg'>{Detail_text}</p>
</div>
</div>
{/*Container Button*/}
<div className='flex justify-end items-end p-4 md:w-3/5'>
<Link to={`${Route}`}>
<button className={`${BUTTON_VARIANT[variant]} md:text-xl md:mt-12 w-fit h-fit p-4 rounded-lg`}>{Button_text}</button>
</Link>
</div>
</div>
</>
)
}
export default ButtonCard
|
const std = @import("std");
const arbor = @import("arbor.zig");
const clap = @import("clap_plugin.zig");
const vst2 = @import("vst2_plugin.zig");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const equalStrings = testing.expectEqualStrings;
const span = std.mem.span;
const allocator = testing.allocator;
const test_params = &[_]arbor.Parameter{
arbor.param.Float("gain", 0, 10, 0, .{ .flags = .{} }),
};
export fn init() *arbor.Plugin {
return arbor.init(allocator, test_params, .{
.deinit = deinit,
.prepare = prepare,
.process = process,
});
}
fn deinit(_: *arbor.Plugin) void {}
fn prepare(_: *arbor.Plugin, _: f32, _: u32) void {}
fn process(_: *arbor.Plugin, _: arbor.AudioBuffer(f32)) void {}
export fn gui_init(_: *arbor.Plugin) void {}
test "CLAP features" {
const features: arbor.PluginFeatures = arbor.features.STEREO | arbor.features.SYNTH |
arbor.features.EQ | arbor.features.EFFECT;
try expect(features & arbor.features.EFFECT > 0);
try expect(features & arbor.features.INSTRUMENT == 0);
var parsed = try arbor.parseClapFeatures(features);
var i: u32 = 0;
while (i < parsed.constSlice().len) : (i += 1) {
const feat = parsed.slice()[i];
if (feat == null) break;
if (i == 0)
try equalStrings(span(feat.?), "stereo");
if (i == 1)
try equalStrings(span(feat.?), "audio-effect");
if (i == 2)
try equalStrings(span(feat.?), "equalizer");
if (i == 3)
try equalStrings(span(feat.?), "synthesizer");
}
}
test "VST2" {
const vint = try arbor.Vst2VersionInt("0.1.0");
try expectEqual(100, vint);
const update = try arbor.Vst2VersionInt("2.3.5");
try expectEqual(2350, update);
const config = arbor.config;
if (config.format != .VST2) return;
const api = arbor.vst2;
const Host = struct {
pub fn cb(
_: ?*api.AEffect,
op: i32,
_: i32,
_: isize,
_: ?*anyopaque,
_: f32,
) callconv(.C) isize {
switch (@as(api.HostOpcodes, @enumFromInt(op))) {
.GetSampleRate => return 44100,
.GetNumFrames => return 256,
else => return 0,
}
}
};
const aeffect = try vst2.init(allocator, Host.cb);
const plug = vst2.plugCast(aeffect);
defer plug.deinit(allocator);
const Op = api.Opcode;
const dispatch = aeffect.dispatcher orelse {
try expect(false);
return;
};
// pass invalid opcode
try expectEqual(-1, dispatch(aeffect, -311, 42, 0, null, 0.423423423));
// vendor name
{
var buf: [api.StringConstants.MaxVendorStrLen]u8 = undefined;
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.GetVendorString), 0, 0, &buf, 0));
const exp_len = config.plugin_desc.company.len;
try equalStrings(config.plugin_desc.company, buf[0..exp_len]);
}
// plugin name
{
var buf: [api.StringConstants.MaxProductStrLen]u8 = undefined;
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.GetProductString), 0, 0, &buf, 0));
const exp_len = config.plugin_desc.name.len;
try equalStrings(config.plugin_desc.name, buf[0..exp_len]);
}
// param name
{
var buf: [api.StringConstants.MaxParamStrLen]u8 = undefined;
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.GetParamName), 0, 0, &buf, 0));
}
// param value to text
{
var buf: [api.StringConstants.MaxParamStrLen]u8 = undefined;
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.ParamValueToText), 0, 0, &buf, 0));
}
// SR & block size
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.SetSampleRate), 0, 0, null, 44100));
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.SetBlockSize), 0, 512, null, 0));
// Load/save state
{
const n_param = aeffect.num_params;
const params = try allocator.alloc(f32, @intCast(n_param));
defer allocator.free(params);
const ref_params = try allocator.alloc(f32, @intCast(n_param));
defer allocator.free(ref_params);
const size_bytes = params.len * @sizeOf(f32);
for (params, 0..) |*p, i| {
if (aeffect.getParameter) |get| {
p.* = get(aeffect, @intCast(i));
std.debug.print("p{d}: {d}\n", .{ i, p.* });
}
}
@memcpy(ref_params, params);
try expectEqual(
@as(isize, @intCast(size_bytes)),
dispatch(aeffect, @intFromEnum(Op.GetChunk), 0, 0, params.ptr, 0),
);
for (params, ref_params) |p, *r| {
try expectEqual(r.*, p);
r.* = 0.666;
}
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.SetChunk), 0, 0, ref_params.ptr, 0));
for (plug.plugin.params) |pp| {
try expectEqual(0.666, pp);
}
}
try expectEqual(0, dispatch(aeffect, @intFromEnum(Op.Open), 0, 0, null, 0));
}
|
package mende273.foody.ui.screen.meals.image
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import mende273.foody.ui.component.NetworkImage
import mende273.foody.ui.component.RoundedBackButton
@Composable
fun FullScreenImage(
modifier: Modifier = Modifier,
imageUrl: String,
onNavigateBackClicked: () -> Unit
) {
var scale by remember { mutableFloatStateOf(1f) }
var rotation by remember { mutableFloatStateOf(0f) }
var offset by remember { mutableStateOf(Offset.Zero) }
val state = rememberTransformableState { zoomChange, offsetChange, rotationChange ->
scale *= zoomChange
rotation += rotationChange
offset += offsetChange
}
Box {
NetworkImage(
modifier = modifier
.blur(
radiusX = 50.dp,
radiusY = 50.dp
),
url = imageUrl,
contentDescription = "background blurred image",
contentScale = ContentScale.Crop
)
NetworkImage(
modifier = Modifier
.graphicsLayer(
scaleX = scale,
scaleY = scale,
rotationZ = rotation,
translationX = offset.x,
translationY = offset.y
)
.transformable(state = state)
.fillMaxSize(),
url = imageUrl,
contentDescription = "full screen meal image",
contentScale = ContentScale.Fit
)
RoundedBackButton(onNavigateBackClicked = { onNavigateBackClicked() })
}
}
|
import React from "react";
import { connect } from 'react-redux';
import { AdminCMSService } from '../../../services/admin-cms.service';
import { adminActionTypes } from "../../../actions/adminActionTypes";
import * as Action from "../../../../shared/actions/action";
import { Constants } from "../../../../../common/app-settings/constants";
import { Utility } from "../../../../../common/utility";
import { GAService } from "../../../../shared/services/ga-service";
class TeamMember extends React.Component {
constructor(props) {
super(props);
this.onUserRemove = this.onUserRemove.bind(this);
this.setLeader = this.setLeader.bind(this);
}
onUserRemove(user) {
let confirmMessage = Utility.stringFormat(Constants.messages.editTeamModal.memberRemoveConfirm, (user.name ? user.name : (user.email ? user.email : null)), this.props.model.teamToEdit.label);
Utility.showConfirm(confirmMessage,
// on confirm click
() => {
this.props.dispatch(Action.getAction(adminActionTypes.SET_POPUPLOADER_TOGGLE, true));
AdminCMSService.destroyRelationFrom(this.props.model.teamToEdit.id, user.id).then((response) => {
if (response.data.destroyAssignmentRelation) {
this.props.dispatch(Action.getAction(adminActionTypes.REMOVE_TEAM_MEMBER, { teamId: this.props.model.teamToEdit.id, userId: user.id }));
this.props.dispatch(Action.getAction(adminActionTypes.SET_POPUPLOADER_TOGGLE, false));
let allLeaderIds = [];
allLeaderIds.push({ id: user.id, isLeader:false });
AdminCMSService.setLeader(allLeaderIds)
.then(response => {
AdminCMSService.getUsers(this.props.model.filterModel.selectedSite.siteId, this.props.sharedModel.selectedQCInstances)
.then(mappedData => {
this.props.dispatch(Action.getAction(adminActionTypes.SET_CANVASSERS_SEARCHED_RESULTS, mappedData.user));
this.props.dispatch(Action.getAction(adminActionTypes.SET_KEYWORD_SEARCH, { value: this.props.model.rightSideModel.keywordSearchCanvModel.selectedOption, convassersTabSelected: true }));
});
}).catch((err) => {
this.props.dispatch(Action.getAction(adminActionTypes.SHOW_VALIDATION_MESSAGE,
{ validationMessage: err.message, isPopup: false, type: Constants.validation.types.error.key }));
this.props.dispatch(Action.getAction(adminActionTypes.SET_POPUPLOADER_TOGGLE, false));
});
let canvasserName = Utility.replaceAtTheRateSymbol(user.name);
// log event on GA
GAService.logEvent(
Utility.stringFormat(Constants.google_analytics.eventLogging.actions.Admin.removeCanvasser, canvasserName, this.props.model.teamToEdit.label),
Utility.stringFormat(Constants.messages.google_analytics.unAssignedAt, Utility.convertToFormat(new Date(), Constants.dateTimeFormates.mmddyyyy)),
Constants.google_analytics.eventLogging.eventLabels.removeAssignment,
false);
} else {
this.props.dispatch(Action.getAction(adminActionTypes.SHOW_VALIDATION_MESSAGE, { validationMessage: Constants.messages.commonMessages.someErrorOccured, isPopup: false, type: Constants.validation.types.error.key }));
}
})
.catch((err) => {
this.props.dispatch(Action.getAction(adminActionTypes.SHOW_VALIDATION_MESSAGE, { validationMessage: err.message, isPopup: false, type: Constants.validation.types.error.key }));
this.props.dispatch(Action.getAction(adminActionTypes.SET_POPUPLOADER_TOGGLE, false));
this.props.dispatch(Action.getAction(adminActionTypes.SET_KEYWORD_SEARCH, { value: this.props.model.rightSideModel.keywordSearchCanvModel.selectedOption, convassersTabSelected: true }));
});
},
// on cancel click
() => {
this.props.dispatch(Action.getAction(adminActionTypes.SHOW_VALIDATION_MESSAGE, { validationMessage: Constants.emptyString }));
},
this.props.dispatch
);
}
setLeader(Leader) {
let allLeaderIds = [];
this.props.model.teamToEdit.user.forEach(function (user) {
allLeaderIds.push({ id: user.id, isLeader: (user.id != Leader.id ? false : (Leader.properties.isTeamLeader == "true" ? false : true)) });
})
this.props.dispatch(Action.getAction(adminActionTypes.SET_POPUPLOADER_TOGGLE, true));
AdminCMSService.setLeader(allLeaderIds)
.then(response => {
this.props.dispatch(Action.getAction(adminActionTypes.SET_TEAM_LEADER, { users: allLeaderIds }));
AdminCMSService.getUsers(this.props.model.filterModel.selectedSite.siteId, this.props.sharedModel.selectedQCInstances)
.then(mappedData => {
this.props.dispatch(Action.getAction(adminActionTypes.SET_CANVASSERS_SEARCHED_RESULTS, mappedData.user));
this.props.dispatch(Action.getAction(adminActionTypes.SET_KEYWORD_SEARCH, { value: this.props.model.rightSideModel.keywordSearchCanvModel.selectedOption, convassersTabSelected: true }));
this.props.dispatch(Action.getAction(adminActionTypes.SET_POPUPLOADER_TOGGLE, false));
});
this.props.dispatch(Action.getAction(adminActionTypes.SET_KEYWORD_SEARCH, { value: this.props.model.rightSideModel.keywordSearchCanvModel.selectedOption, convassersTabSelected: true }));
}).catch((err) => {
this.props.dispatch(Action.getAction(adminActionTypes.SHOW_VALIDATION_MESSAGE,
{ validationMessage: err.message, isPopup: false, type: Constants.validation.types.error.key }));
this.props.dispatch(Action.getAction(adminActionTypes.SET_POPUPLOADER_TOGGLE, false));
});
}
render() {
return (
<div className="team-members custom-scroll">
<table className="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th className="text-center">Assign as Team Leader</th>
<th className="text-center">Status</th>
<th className="text-right" style={{ "width": "10px" }}></th>
</tr>
</thead>
<tbody>
{
this.props.model.teamToEdit.user.length ?
this.props.model.teamToEdit.user.map((user, index) => {
return (
<tr key={"team-user-" + index}>
<td>({(index + 1)})</td>
<td className={"text-left member-name1"} >{Utility.getCanvasserDetails(user).name}</td>
<td className="text-left member-email1 email_absolute1">{Utility.getCanvasserDetails(user).email}</td>
<td className={"text-center"} >
<label className={"leader label label-default " + ((user.properties.isTeamLeader == "true") ? " active " : "")} onClick={() => { this.setLeader(user) }} title={(user.properties.isTeamLeader == "false") ? "Set Team Leader" : ''} >Team Leader</label>
</td>
<td className={"text-center "}>
{
(user.countInstanceStatus && user.countInstanceStatus.length && user.countInstanceStatus[0].label == Constants.routesStatus.in_progress) ?
<label className={"label checkedin_user"}>
{Constants.canvasserCheckedIn.checkedIn}
</label>
:
<label className={"label not_checkedin_user"}>
{Constants.canvasserCheckedIn.notCheckedIn}
</label>
}
</td>
<td className="text-center" style={{ paddingBottom: "4px" }}><i className="fa fa-times-circle-o remove-row-icon" onClick={() => { this.onUserRemove(user) }} title="Remove canvasser from team."></i></td>
</tr>
);
})
: <tr className="displaynone"><td colSpan="6"></td></tr>
}
</tbody>
</table>
{!this.props.model.teamToEdit.user.length ? <div className="team-row no-routes">{Constants.messages.noTeamMember}</div> : ''}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
model: state.adminModel,
sharedModel: state.sharedModel
}
}
export default connect(mapStateToProps)(TeamMember);
|
// require the express =>
const {v4:uuid4} = require('uuid')
const express = require('express')
const userExpress = express();
const userModel = require('../models/userModel')
const bodyParser = require('body-parser')
userExpress.use(bodyParser.json())
// create the user
const createUser = async (req, res) =>{
try {
const createUsers = userModel({
id: uuid4() ,
name: req.body.name,
position: req.body.position,
age: Number(req.body.age)
})
if(createUsers){
await createUsers.save()
res.status(200).json(createUsers)
}
else{
res.status(500).send('Problem in your request')
}
} catch (error) {
res.status(500).send({
message:error.message
})
}
// res.status(200).send('This is the post')
}
// get the user
const getUser =async (req, res) =>{
try {
// const id = req.params.id;
const findUser = await userModel.find();
if(findUser){
res.status(200).json(findUser)
}
else{
res.status(404).send('Can not find the user')
}
} catch (error) {
res.status(500).send({
message:error.message
})
}
// res.status(200).send('Get page')
}
// get user by id
const getSingleUser = async (req, res) =>{
try {
// const id = req.params.id;
const getSingleUser = await userModel.findOne({ _id: req.params.id })
if(getSingleUser){
res.status(200).send(getSingleUser)
}
else{
res.status(404).send('Can not get the user')
}
} catch (error) {
res.status(500).send({
message:error.message
})
}
}
// update the user
const updateUser = async (req, res) =>{
try {
const updateUser = await userModel.findOne({_id: req.params.id})
updateUser.name = req.body.name,
updateUser.age = Number(req.body.age)
updateUser.position = req.body.position
await updateUser.save();
res.status(200).json(updateUser)
// res.status(200).send(updateUser)
} catch (error) {
res.status(500).send({
message:error.message
})
}
// res.status(200).send('Update page')
}
// delete the user
const deleteUser = async(req, res) =>{
try {
// const deleteUser
const deleteUser = await userModel.deleteOne({_id:req.params.id})
if(deleteUser){
res.status(200).send(deleteUser)
}
else{
res.status(500).send({
message:'Not deleted',
})
}
} catch (error) {
res.status(500).send({
message:error.message
})
}
res.status(200).send('Delete page')
}
// export the module
module.exports = {
createUser,
getUser,
getSingleUser,
updateUser,
deleteUser
}
|
<div class="content-container container-fluid p-3">
<div class="px-5 onboarding-container">
<h1 class="text-center my-4">Onboarding</h1>
<div class="">
<form [formGroup]="subjectForm">
<label for="subject">Hírlevél tárgya</label>
<input type="text" class="form-control" formControlName="subject" >
</form>
</div>
<hr>
<div class="mt-4" *ngFor="let user of users; let i = index">
<hr *ngIf="i > 0" style="margin-top: 2rem; margin-bottom: 2rem;">
<form [formGroup]="getUserForm(user)">
<div class="form-group">
<div class="d-flex">
<label for="'name' + i">Név</label>
<button
*ngIf="users.length > 1"
class="icon-button icon-button-danger ml-auto"
matTooltip="Törlés"
(click)="deleteUser(user)">
<i class="fas fa-lg fa-fw fa-trash"></i>
</button>
</div>
<input
formControlName="name"
id="'name' + i"
type="text"
class="form-control"
placeholder="Belépő neve"/>
</div>
<div class="form-group">
<label for="'role' + i">Technológia</label>
<input
formControlName="role"
id="'role' + i"
type="text"
class="form-control"
placeholder="Belépő technológiai irányultsága"/>
</div>
<div class="form-group">
<label for="'description' + i">Bemutatkozás</label>
<textarea
formControlName="description"
id="'description' + i"
type="text"
class="form-control"
maxlength="300"
rows="5"
placeholder="Bemutatkozás szövege..."></textarea>
</div>
<div class="d-flex flex-row">
<label class="mr-2">Profilkép:</label>
<label class="mr-2" style="margin-bottom: 0;">{{ user.fileName }}</label>
<label class="ml-2" [for]="user.localId" class="btn btn-primary btn-sm" style="margin-bottom: 0;">Kép választása</label>
<input type="file" [id]="user.localId" style="display:none;" accept="image/jpeg, image/png" (change)="onFileSelect(user, $event)"/>
<div *ngIf="user.image && user.isPreviewGenerating" class="ml-4 sk-chase">
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
</div>
<button class="ml-2 btn btn-primary btn-sm" *ngIf="user.image && !user.isPreviewGenerating" (click)="getPreview(user)">Előnézet</button>
<button class="ml-2 btn btn-secondary btn-sm" *ngIf="user.image && !user.isPreviewGenerating" (click)="cropProfilePicture(user)">Kép szerkesztése</button>
</div>
</form>
</div>
<div class="d-flex">
<div class="ml-auto">
<button class="btn btn-primary" matTooltip="Belépő hozzáadása" (click)="addUser()"><i class="fas fa-fw fa-user-plus"></i></button>
<button class="btn btn-primary ml-1" [disabled]="sendButtonInactive()" (click)="sendOnBoardingNewsletter()">Kiküldés</button>
</div>
</div>
</div>
</div>
|
import datetime
from datetime import date
from kivymd.app import MDApp
from kivymd.uix.behaviors import FakeRectangularElevationBehavior
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivymd.uix.datatables import MDDataTable
from kivymd.uix.floatlayout import MDFloatLayout
from kivy.metrics import dp
from kivymd.uix.pickers import MDDatePicker
from kivymd.uix.button import MDFlatButton, MDRectangleFlatButton
from kivymd.uix.dialog import MDDialog
from kivy.properties import StringProperty, NumericProperty
from kivy.core.window import Window
from kivymd.toast import toast
from kivymd.uix.list import TwoLineListItem
from kivymd.uix.card import MDCard
# Window.size = (350, 600)
class MyCard(MDCard):
sect = StringProperty()
val = StringProperty()
class ActivityCard(MDCard):
date = StringProperty()
dep = NumericProperty()
gains = NumericProperty()
class DetailScreen(MDFloatLayout):
nom = StringProperty()
date_creation = StringProperty()
capital = NumericProperty()
class ToCard(FakeRectangularElevationBehavior, MDFloatLayout):
name = StringProperty()
date = StringProperty()
rt_previous = NumericProperty()
depenses = NumericProperty()
production = NumericProperty()
diff = NumericProperty()
class Table(MDApp):
dialog = None
project_count = NumericProperty()
somme_dep = StringProperty()
somme_gain = StringProperty()
act_len = NumericProperty()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.data_tables = None
global contacts
global contacts_name
contacts = []
contacts_name = []
self.detail_data = None
def on_start(self):
self.add_datatable()
self.initialise_all_act()
self.projet_dep_gains_count()
today = date.today()
wd = date.weekday(today)
days =["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"]
year = str(datetime.datetime.now().year)
month = str(datetime.datetime.now().strftime("%b"))
day = str(datetime.datetime.now().strftime("%d"))
sc.get_screen("accueil").ids.current_date.text = f"{days[wd]}, {day} {month} {year} "
# sc.get_screen("accueil").ids.current_date.text = f"{days[wd]}, {day} {month} {year}"
def build(self):
global sc
sc = ScreenManager()
sc.add_widget(Builder.load_file("accueil.kv"))
sc.add_widget(Builder.load_file("main.kv"))
sc.add_widget(Builder.load_file("update.kv"))
sc.add_widget(Builder.load_file("add_act.kv"))
sc.add_widget(Builder.load_file("add.kv"))
sc.add_widget(Builder.load_file("detail.kv"))
return sc
# première fonction...
def add_datatable(self):
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute("SELECT * from projets")
data = im.fetchall()
self.data_tables = MDDataTable(
size_hint=(.96, .7),
use_pagination=True,
check=True,
column_data=[
("id", dp(20)),
("Nom", dp(50)),
("Date de création", dp(50)),
("Capital (F GNF)", dp(50)),
],
row_data=[
(
i[:][0],
i[:][1],
i[:][2],
i[:][3],
)
for i in data
],
)
self.data_tables.bind(on_check_press=self.on_check_press)
sc.get_screen("page").ids.datatable.add_widget(self.data_tables)
def on_check_press(self, instance_table, current_row):
if current_row[0] not in contacts and current_row[1] not in contacts:
contacts.append(current_row[0])
contacts.append(current_row[1])
else:
contacts.remove(current_row[0])
contacts.remove(current_row[1])
# second fonction
def delete(self):
# alert message
if contacts:
self.dialog=MDDialog(
text="Êtes-vous de vouloir continuer",
buttons=[
MDFlatButton(text="[color=3338FF]Non[/color]", on_release=self.close),
MDRectangleFlatButton(text="[color=096C7F]Oui[/color]", on_release=self.open)
],
)
self.dialog.open()
def close(self, obj):
self.dialog.dismiss()
def open(self, obj):
for i in contacts:
if i:
import sqlite3
vt = sqlite3.connect("database.db")
im = vt.cursor()
im.execute(f"delete from projets where projet_id=?", (i[0]))
im.execute(f"delete from activite where projet_id=?", (i[0]))
vt.commit()
sc.get_screen("page").ids.datatable.clear_widgets()
self.add_datatable()
self.dialog.dismiss()
contacts.clear()
def detail_screen(self):
for i in contacts:
if i:
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute(f"SELECT * from projets where projet_id=?",(i[0]))
data = im.fetchall()
for j in data:
sc.get_screen("detail").ids.detail_page.nom = j[1]
sc.get_screen("detail").ids.detail_page.date_creation = j[2]
sc.get_screen("detail").ids.detail_page.capital = j[3]
# import sqlite3
vt = sqlite3.connect('database.db')
act = vt.cursor()
act.execute("SELECT * from activite where projet_id=?", (i[0]))
data_act = act.fetchall()
for e in data_act:
# benef = e[5] - e[4]
self.detail_data = ToCard(date=e[3], rt_previous=e[4], depenses=e[5], production=e[6], diff=e[7])
sc.get_screen("detail").ids.todo_list.add_widget(self.detail_data)
sc.transition.direction = "left"
sc.current = "detail"
else:
sc.current = "page"
sc.get_screen("detail").ids.todo_list.remove_widget(self.detail_data)
# open update.kv 1
# def updatenewpage(self):
# sc.current = "upd"
# open update.kv remanier
def updatenewpage(self):
for i in contacts:
if i:
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute(f"SELECT * from projets where projet_id=?",(i[0]))
data = im.fetchall()
for j in data:
sc.get_screen("update").ids.nom.text = j[1]
sc.get_screen("update").ids.date_creation.text = j[2]
sc.get_screen("update").ids.capital.text = str(j[3])
sc.transition.direction = "left"
sc.current = "update"
# open add.kv
def addnewpage(self):
sc.transition.direction = "left"
sc.current = "add_projet"
def add_act_newpage(self):
sc.transition.direction = "left"
sc.current = "add_activity"
# open main.kv
def back(self):
sc.get_screen("detail").ids.todo_list.clear_widgets()
sc.transition.direction = "right"
sc.current = "page"
def back2(self):
sc.transition.direction = "right"
sc.current = "detail"
def update(self, nom, date_creation, capital):
for i in contacts:
if i:
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute("update projets set nom=?, date_creation=?, capital=? where projet_id=?", (nom, date_creation, capital, i[0]))
vt.commit()
sc.get_screen("page").ids.datatable.remove_widget(self.data_tables)
self.add_datatable()
contacts.clear()
sc.transition.direction = "right"
sc.current="page"
def add(self, name, date_creation, capital):
if name != "" and date_creation != "" and capital != "":
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute("insert into projets(nom, date_creation, capital) VALUES(?, ?, ?)", (name, date_creation, capital))
vt.commit()
sc.get_screen("page").ids.datatable.remove_widget(self.data_tables)
self.add_datatable()
contacts.clear()
sc.transition.direction = "right"
sc.current="page"
def add_act(self, date, rt_previous, depenses, production):
if date != "" and rt_previous != "" and depenses != "" and production != "":
projet_id = contacts[0]
diff = int(production) - int(depenses)
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute("insert into activite(projet_id, date, rt_previous, depenses, production, diff) VALUES(?, ?, ?, ?, ?, ?)", (projet_id, date, rt_previous, depenses, production, diff))
vt.commit()
toast(f"activitée du {date} enrégistré...")
sc.get_screen("detail").ids.todo_list.clear_widgets()
self.detail_screen()
sc.transition.direction = "right"
sc.current="detail"
def date_dialog(self):
date_dialog = MDDatePicker(min_date=datetime.date.today())
date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel)
date_dialog.open()
def on_save(self, instance, value, date_range):
sc.get_screen("add_projet").ids.date_creation.text = str(value)
def on_cancel(self, instance, value):
pass
def date_dialog2(self):
date_dialog = MDDatePicker(min_date=datetime.date.today())
date_dialog.bind(on_save=self.on_save2, on_cancel=self.on_cancel2)
date_dialog.open()
def on_save2(self, instance, value, date_range):
sc.get_screen("add_activity").ids.date.text = str(value)
def on_cancel2(self, instance, value):
pass
############################################################################
####### ALL ACTIVITYS
##############################################################################
def initialise_all_act(self):
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute("SELECT * from activite")
data = im.fetchall()
self.act_len = len(data)
for i in data:
all_act = ActivityCard()
all_act.date = i[3]
all_act.dep = i[5]
all_act.gains = i[7]
sc.get_screen("accueil").ids.act_list.add_widget(all_act)
############################################################################
####### Count and new page
############################################################################
def projet_dep_gains_count(self):
import sqlite3
vt = sqlite3.connect('database.db')
im = vt.cursor()
im.execute("SELECT * from projets")
data = im.fetchall()
self.project_count = len(data)
g = vt.cursor()
g.execute("SELECT diff from activite")
gain = g.fetchall()
liste_gain = ()
for ga in gain:
liste_gain += ga
self.somme_gain = str(sum(liste_gain))
d = vt.cursor()
d.execute("SELECT depenses from activite")
dep = d.fetchall()
liste_dep = ()
for de in dep:
liste_dep += de
self.somme_dep = str(sum(liste_dep))
def all_projectnew_page(self):
sc.transition.direction = "left"
sc.current = "page"
def back_accueil(self):
sc.get_screen("accueil").ids.act_list.clear_widgets()
self.initialise_all_act()
self.projet_dep_gains_count()
sc.transition.direction = "right"
sc.current = "accueil"
if __name__ == '__main__':
Table().run()
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:grocery_app/constants.dart';
import 'package:grocery_app/cubits/cart_cubit/cart_cubit.dart';
import 'package:grocery_app/cubits/favourite_cubit/favourite_cubit.dart';
import 'package:persistent_bottom_nav_bar/persistent_tab_view.dart';
import '../cubits/category_cubit/category_cubit.dart';
import 'cart_view.dart';
import 'category_view.dart';
import 'favourite_view.dart';
import 'shop_view.dart';
final PersistentTabController _controller =
PersistentTabController(initialIndex: 0);
class NavBarView extends StatelessWidget {
const NavBarView({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => CartCubit()..getProducts(),
),
BlocProvider(
create: (context) => FavouriteCubit(),
),
],
child: Scaffold(
body: PersistentTabView(
context,
bottomScreenMargin: 0,
controller: _controller,
screens: _buildScreens(),
items: _navBarsItems(),
backgroundColor: Colors.white, // Default is Colors.white.
navBarStyle: NavBarStyle
.style6, // Choose the nav bar style with this property.
),
),
);
}
}
List<Widget> _buildScreens() {
return [
const ShopView(),
BlocProvider(
create: (context) => CategoryCubit()..getCategories(),
child: const CategoryView(),
),
const CartView(),
const FavouriteView(),
];
}
List<PersistentBottomNavBarItem> _navBarsItems() {
return [
navBarIcon(Icons.storefront_sharp, "Store"),
navBarIcon(Icons.manage_search_outlined, "Explore"),
navBarIcon(Icons.shopping_cart_outlined, "Cart"),
navBarIcon(Icons.favorite_border, "Favourite"),
// navBarIcon(Icons.person_outline, "Account"),
];
}
PersistentBottomNavBarItem navBarIcon(IconData icon, String title) {
return PersistentBottomNavBarItem(
title: title,
inactiveIcon: Icon(
icon,
color: Colors.black,
),
icon: Icon(
icon,
size: 22,
color: kSecondaryColor,
),
activeColorPrimary: kSecondaryColor,
);
}
|
/*
Copyright (C) 2023 e:fs TechHub GmbH ([email protected])
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { act, fireEvent, render, screen } from '@testing-library/react';
import TestWrapper from '@utils/TestWrapper/TestWrapper.spec';
import OrganizationAddTagPopover from './OrganizationAddTagPopover';
describe('OrganizationAddTagPopover', () => {
it('should render successfully', () => {
const handleAddOrgaTag = jest.fn();
const { baseElement } = render(
<TestWrapper>
<OrganizationAddTagPopover handleAddOrgaTag={handleAddOrgaTag} />
</TestWrapper>
);
expect(baseElement).toBeTruthy();
console.log(baseElement.innerHTML);
});
it('should click the + button to open the modal, enter a tag and add it', () => {
const handleAddOrgaTag = jest.fn();
render(
<TestWrapper>
<OrganizationAddTagPopover handleAddOrgaTag={handleAddOrgaTag} />
</TestWrapper>
);
const openPopoverButton = screen.getByRole('button', {
name: 'openAddEditSpaceTagPopover',
});
expect(openPopoverButton).toBeTruthy();
act(() => {
fireEvent.click(openPopoverButton);
});
const tagInputField = screen.getByRole('textbox', { name: 'tagInput' });
expect(tagInputField).toBeTruthy();
act(() => {
fireEvent.change(tagInputField, { target: { value: 'test tag' } });
});
const addTagButton = screen.getByRole('button', { name: 'addTagButton' });
expect(addTagButton).toBeTruthy();
act(() => {
fireEvent.click(addTagButton);
});
});
it('should click the + button to open the modal and then x button to close the modal', () => {
const handleAddOrgaTag = jest.fn();
render(
<TestWrapper>
<OrganizationAddTagPopover handleAddOrgaTag={handleAddOrgaTag} />
</TestWrapper>
);
const openPopoverButton = screen.getByRole('button', {
name: 'openAddEditSpaceTagPopover',
});
expect(openPopoverButton).toBeTruthy();
act(() => {
fireEvent.click(openPopoverButton);
});
const closePopoverButton = screen.getByRole('button', {
name: 'closePopoverButton',
});
expect(closePopoverButton).toBeTruthy();
act(() => {
fireEvent.click(closePopoverButton);
});
});
});
|
import { Injectable } from '@angular/core';
import { AlertService } from './alert.service';
import { ReservasService } from './reservas.service';
@Injectable({
providedIn: 'root'
})
export class DataService {
public ubicacionActual: string = 'Dashboard'; // Statebar - Direccion actual
public showMenu: Boolean = true; // Header - Controla la visualizacion de la barra de navegacion
public showAlertaReserva: Boolean = false;
public showAlertaReservaBarra: Boolean = false;
public cantidadReservasPorVencer: number = 0;
public audioReserva = new Audio();
constructor(
private reservasService: ReservasService,
private alertService: AlertService
) {}
// Redonde de numeros
redondear(numero:number, decimales:number):number {
if (typeof numero != 'number' || typeof decimales != 'number') return null;
let signo = numero >= 0 ? 1 : -1;
return Number((Math.round((numero * Math.pow(10, decimales)) + (signo * 0.0001)) / Math.pow(10, decimales)).toFixed(decimales));
}
// Consultar reservas por vencer
alertaReservas(): void {
this.reservasService.reservasPorVencer().subscribe({
next: ({ reservas }) => {
if(reservas.length > 0){
this.cantidadReservasPorVencer = reservas.length;
this.showAlertaReserva = true;
this.showAlertaReservaBarra = true;
this.sonidoReserva();
}else{
this.showAlertaReserva = false;
this.showAlertaReservaBarra = false;
}
}, error: ({ error }) => this.alertService.errorApi(error.message)
})
}
// Sonido - Alerta -> Reserva por vencer
sonidoReserva(): void {
this.audioReserva.src = "assets/sounds/Alert-Reserva.wav";
this.audioReserva.load();
this.audioReserva.play();
}
cerrarAlertaReservas(): void {
this.showAlertaReserva = false;
}
}
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { TopBarComponent } from './top-bar/top-bar.component';
import { ServerListComponent } from './server-list/server-list.component';
import { ServerDetailComponent } from './server-detail/server-detail.component';
import { AppListComponent } from './app-list/app-list.component';
import { AppDetailComponent } from './app-detail/app-detail.component';
import { SearchComponent } from './search/search.component';
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
HttpClientModule,
RouterModule.forRoot([
{ path: '', component: ServerListComponent },
{ path: 'details/:id', component: ServerDetailComponent },
{ path: 'apps', component: AppListComponent },
{ path: 'apps/:id', component: AppDetailComponent },
])
],
declarations: [
AppComponent,
TopBarComponent,
ServerListComponent,
ServerDetailComponent,
AppListComponent,
AppDetailComponent,
SearchComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
/*
Copyright Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
|
<template>
<div class="title">
<p>Add Income</p>
</div>
<form @submit.prevent="formHandler">
<input type="text" id="desc" placeholder="Income" v-model="formData.desc">
<input type="number" id="num" placeholder="Amount" v-model="formData.value">
<input type="date" id="date" lang="fr-CA" v-model="formData.date">
<input class="btn btn-outline-success" type="submit" value="Submit">
</form>
</template>
<script>
import { reactive } from 'vue'
export default {
emits: ["handle-data"],
setup(props , {emit}) {
const formData = reactive({
desc: null,
value:null,
date: null
})
function formHandler(){
emit("handle-data",{
desc: formData.desc,
value: formData.value,
date: formData.date
})
formData.desc = null
formData.value = null
formData.date = null
}
return {
formData,
formHandler
}
}
}
</script>
|
// import hooks from r3f
import { useFrame } from "@react-three/fiber";
// import custom hook
import useCurrentCameraDist from "../hooks/useCurrentCameraDist.jsx";
// import componenets
import WeirdSphere from "./WeirdSphere.jsx";
import Lights from "./Lights.jsx";
import OuterSphere from "./OuterSphere.jsx";
import { Vector2 } from "three";
// scene component
function Scene(props) {
const viewport = props.viewport;
const mouse = props.mouse;
const dist = useCurrentCameraDist(viewport);
const mouseClamped = {
x: (mouse.x / viewport.width) * 2 - 1,
y: (mouse.y / viewport.height) * 2 - 1,
};
// frame hook to update camera using mouse x and y positions
useFrame(({ camera }) => {
camera.position.x += (mouseClamped.x / 1.75 - camera.position.x) * 0.05;
camera.position.y += (mouseClamped.y / 0.75 - camera.position.y) * 0.05;
let XY = new Vector2(camera.position.x, camera.position.y);
camera.position.z = dist * Math.sin(Math.acos(XY.length() / dist)); // update z position
camera.lookAt(0, 0, 0); // update to look at center
});
// JSX for all the scene components
return (
<>
<Lights />
<WeirdSphere args={[1, 40]} mouseClamped={mouseClamped} />
<OuterSphere scale={1.75} />
</>
);
}
export default Scene;
|
import $content from '@atoms/workroom/content'
import { css, useTheme } from '@emotion/react'
import transition from '@styles/transition'
import React, { useEffect, useRef } from 'react'
import { useRecoilState } from 'recoil'
import Spacing from './layout/Spacing'
import Toolbar from './Toolbar'
type Command = '' | 'Tab'
function Editor() {
const textarea = useRef<HTMLTextAreaElement>(null)
const command = useRef<Command>('')
const tabAfterRange = useRef<number>(0)
const { color } = useTheme()
const [content, setContent] = useRecoilState($content)
const style = css`
width: 100%;
height: calc(calc(100% - 1rem) - 32px);
resize: none;
border: none;
letter-spacing: 0.075rem;
color: ${color.text_900};
background-color: transparent;
transition: ${transition.fast};
line-height: 2rem;
&::placeholder {
color: ${color.text_300};
}
`
function handleChangeContent(e: React.ChangeEvent<HTMLTextAreaElement>) {
setContent(e.target.value)
}
function onTab(e: React.KeyboardEvent<HTMLTextAreaElement>) {
e.preventDefault()
const { value, selectionStart } = e.currentTarget
const start = value.substring(0, selectionStart)
const end = value.substring(selectionStart)
command.current = 'Tab'
tabAfterRange.current = selectionStart + 2
setContent(`${start} ${end}`)
}
onTab.after = function () {
const range = tabAfterRange.current
textarea.current?.setSelectionRange(range, range)
command.current = ''
tabAfterRange.current = 0
}
function onKeydown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
if (e.key === 'Tab') onTab(e)
}
useEffect(() => {
if (command.current === 'Tab') onTab.after()
}, [content])
return (
<>
<Toolbar textarea={textarea} />
<Spacing size='1rem' />
<textarea
ref={textarea}
css={style}
value={content}
onChange={handleChangeContent}
onKeyDown={onKeydown}
placeholder='오늘 공유하고 싶은 내용을 입력해주세요.'
/>
</>
)
}
export default Editor
|
WITH
-- Collate patients receiving any recent acute respiratory illness (ARI) diagnosis
recentARI AS
( -- Look for any patient with an ARI, based on diagnosis code list suggested by CDC,
-- that was recorded recently (since 12/2019).
SELECT
person_id, visit_occurrence_id, condition_start_DATE, condition_start_DATETIME,
condition_source_value, condition_source_concept_id
FROM
`som-rit-phi-starr-prod.starr_omop_cdm5_deid_latest.condition_occurrence` AS condOccur
WHERE
condition_start_DATE >= '2019-12-01' AND
( condition_source_value LIKE 'J00.%' OR
condition_source_value LIKE 'J01.%' OR
condition_source_value LIKE 'J02.%' OR
condition_source_value LIKE 'J03.%' OR
condition_source_value LIKE 'J04.%' OR
condition_source_value LIKE 'J05.%' OR
condition_source_value LIKE 'J06.%' OR
condition_source_value LIKE 'J09.%' OR
condition_source_value LIKE 'J10.%' OR
condition_source_value LIKE 'J11.%' OR
condition_source_value LIKE 'J12.%' OR
condition_source_value LIKE 'J13.%' OR
condition_source_value LIKE 'J14.%' OR
condition_source_value LIKE 'J15.%' OR
condition_source_value LIKE 'J16.%' OR
condition_source_value LIKE 'J17.%' OR
condition_source_value LIKE 'J18.%' OR
condition_source_value LIKE 'J20.%' OR
condition_source_value LIKE 'J21.%' OR
condition_source_value LIKE 'J22' OR
condition_source_value LIKE 'J80' OR
condition_source_value LIKE 'A37.91' OR
condition_source_value LIKE 'A37.01' OR
condition_source_value LIKE 'A37.11' OR
condition_source_value LIKE 'A37.81' OR
condition_source_value LIKE 'A48.1' OR
condition_source_value LIKE 'B25.0' OR
condition_source_value LIKE 'B44.0' OR
condition_source_value LIKE 'B97.4' OR
condition_source_value LIKE 'U07.1'
)
),
recentARIDateTimeRange AS
( -- Look for only the last / most recent ARI occurrence date for each patient, in case one has multiple
SELECT
recentARI.person_id,
MIN(condition_start_DATETIME) AS firstARIDateTime, MAX(condition_start_DATETIME) AS lastARIDateTime
FROM recentARI
GROUP BY recentARI.person_id
),
-- Collate results on anyone receiving the SARS-CoV2 NAA Test Results
resultsSARSCoV2Tests AS
(
SELECT person_id, visit_occurrence_id, measurement_DATE, measurement_DATETIME, value_source_value, value_source_value IN ('Detected','Pos','Positive') AS detectedSARSCoV2
FROM `som-rit-phi-starr-prod.starr_omop_cdm5_deid_latest.measurement` as meas
WHERE measurement_concept_id = 706170 -- SARS-CoV2 NAA Test Result
AND meas.value_source_value is NOT NULL -- Only capture usable results and not extra descriptors
) ,
/* Note how often get null values
select count(*) nRecords, count(distinct person_id) as nPerson, count(distinct visit_occurrence_id) as nVisits, countif(value_source_value is not null) as nonNullValues
from resultsSARSCoV2Tests
nRecords 42268
nPerson 14934
nVisits 21043
nonNullValues 21197
*/
resultsSARSCoV2DateTimeRange AS
( -- Accounting for multiple possible tests per patient, group by patient ID and collate date time ranges
SELECT
person_id,
firstSARSCoV2TestedDateTime, lastSARSCoV2TestedDateTime,
firstSARSCoV2DetectedDateTime, lastSARSCoV2DetectedDateTime
FROM
(
SELECT person_id, MIN(measurement_DATETIME) AS firstSARSCoV2TestedDateTime, MAX(measurement_DATETIME) AS lastSARSCoV2TestedDateTime
FROM resultsSARSCoV2Tests
GROUP BY person_id
) AS firstLastSARSCoV2Tests
LEFT JOIN -- Left outer join, because not everyone who had a test will have a positive test result to join to
(
SELECT person_id, MIN(measurement_DATETIME) AS firstSARSCoV2DetectedDateTime, MAX(measurement_DATETIME) AS lastSARSCoV2DetectedDateTime
FROM resultsSARSCoV2Tests
WHERE resultsSARSCoV2Tests.detectedSARSCoV2
GROUP BY person_id
) AS firstLastDetectedSARSCoV2Tests
USING (person_id)
),
-- At this point:
-- recentARIDateTimeRange has one row per patient (41,341 rows as of 2020-04-20 cdm_release_DATE)
-- resultsSARSCoV2DateTimeRange has one row per patient (14,838)
-- Each with first and last dates of occurrences of ARI (after initial "recent" cutoff date) orSARS-CoV2 test results (including timing of positive/detected result, null if no positive/detected results)
recentARIandSARSCoV2DateTimeRange AS
( -- Full outer join in both directions because some people with ARI diagnosis don't get SARS-CoV2 testing and vice versa
SELECT *,
DATETIME_DIFF( firstSARSCoV2TestedDateTime, firstARIDateTime, DAY ) daysFirstARItoFirstSARSCoV2Tested,
DATETIME_DIFF( firstSARSCoV2TestedDateTime, lastARIDateTime, DAY ) daysLastARItoFirstSARSCoV2Tested,
DATETIME_DIFF( lastSARSCoV2TestedDateTime, firstARIDateTime, DAY ) daysFirstARItoLastSARSCoV2Tested,
DATETIME_DIFF( lastSARSCoV2TestedDateTime, lastARIDateTime, DAY ) daysLastARItoLastSARSCoV2Tested,
DATETIME_DIFF( firstSARSCoV2DetectedDateTime, firstARIDateTime, DAY ) daysFirstARItoFirstSARSCoV2Detected,
DATETIME_DIFF( firstSARSCoV2DetectedDateTime, lastARIDateTime, DAY ) daysLastARItoFirstSARSCoV2Detected,
DATETIME_DIFF( lastSARSCoV2DetectedDateTime, firstARIDateTime, DAY ) daysFirstARItoLastSARSCoV2Detected,
DATETIME_DIFF( lastSARSCoV2DetectedDateTime, lastARIDateTime, DAY ) daysLastARItoLastSARSCoV2Detected,
FROM
recentARIDateTimeRange FULL JOIN
resultsSARSCoV2DateTimeRange USING (person_id)
-- 4,091 inner join results (recent ARI diagnosis code AND SARS-CoV2 test results exist, but not necessarily in the correct datetime order)
-- 52,088 full outer join results (recent ARI diagnosi code OR SARS-CoV2 test results)
),
recentARIandSARSCoV2DateTimeRangeWithPatientDemo AS
( -- Join patient demographic information
SELECT
recentARIandSARSCoV2DateTimeRange.*,
year_of_birth, DATE_DIFF('2020-02-01', DATE(birth_DATETIME), YEAR) ageAsOfFeb2020,
person.gender_concept_id , genderConc.concept_name AS genderConcept,
person.race_source_value, person.race_concept_id, raceConc.concept_name as raceConcept,
person.ethnicity_source_value, person.ethnicity_concept_id, ethnicityConc.concept_name as ethnicityConcept
FROM
recentARIandSARSCoV2DateTimeRange
JOIN `som-rit-phi-starr-prod.starr_omop_cdm5_deid_latest.person` AS person USING (person_id)
LEFT JOIN `som-rit-phi-starr-prod.starr_omop_cdm5_deid_latest.concept` AS genderConc ON (person.gender_concept_id = genderConc.concept_id)
LEFT JOIN `som-rit-phi-starr-prod.starr_omop_cdm5_deid_latest.concept` AS raceConc ON (person.race_concept_id = raceConc.concept_id)
LEFT JOIN `som-rit-phi-starr-prod.starr_omop_cdm5_deid_latest.concept` AS ethnicityConc ON (person.ethnicity_concept_id = ethnicityConc.concept_id)
)
-- Example query for primary ARI and SARS CoV2 testing counts, grouped by different categories
SELECT
CAST(FLOOR(ageAsOfFeb2020 / 10)*10 AS INT64) AS ageMin, CAST(FLOOR(ageAsOfFeb2020 / 10)*10+10 AS INT64) as ageMax,
COUNTIF(lastARIDateTime IS NOT NULL) as nARIPatients,
COUNTIF(lastSARSCoV2TestedDateTime IS NOT NULL) as nSARSCoV2TestedPatients,
COUNTIF(lastSARSCoV2DetectedDateTime IS NOT NULL) as nSARSCoV2DetectedPatients,
-- Looking for relative date relationship between ARI diagnosis and SARS-CoV2 Test.
-- This logic is imperfect as is based on date spans. Consider redoing, but using patient-days as unit of observation (rows) instead of patients
COUNTIF( daysFirstARItoFirstSARSCoV2Tested BETWEEN 0 AND 60 OR daysLastARItoFirstSARSCoV2Tested BETWEEN 0 AND 60 ) AS nARIPatientsSARSCoV2TestedWithin60Days,
COUNTIF( daysFirstARItoFirstSARSCoV2Detected BETWEEN 0 AND 60 OR daysLastARItoFirstSARSCoV2Detected BETWEEN 0 AND 60 ) AS nARIPatientsSARSCoV2DetectedWithin60Days
FROM recentARIandSARSCoV2DateTimeRangeWithPatientDemo
GROUP BY ageMin, ageMax
ORDER BY ageMin
LIMIT 100
|
import { CreateLikeRepository } from '@server/data/protocols/db';
import { CreateLike } from '@server/domain/use-cases';
import { faker } from '@faker-js/faker';
import { DbCreateLike } from './db-create-like';
const createLikeRepositoryMock = (): CreateLikeRepository => {
return {
create: jest.fn(),
} as CreateLikeRepository;
};
describe('DbCreateLike', () => {
let createLikeRepository: CreateLikeRepository;
let dbCreateLike: DbCreateLike;
beforeEach(() => {
createLikeRepository = createLikeRepositoryMock();
dbCreateLike = new DbCreateLike(createLikeRepository);
});
it('should create a new like', async () => {
const createParams: CreateLike.Params = {
id: faker.string.uuid(),
post: { id: faker.string.uuid() },
user: { id: faker.string.uuid() },
};
const createdLike: CreateLike.Model = {
...createParams,
createdAt: new Date(),
};
jest
.spyOn(createLikeRepository, 'create')
.mockImplementationOnce(async () => createdLike);
const result = await dbCreateLike.create(createParams);
expect(createLikeRepository.create).toHaveBeenCalledWith(createParams);
expect(result).toEqual(createdLike);
});
});
|
import React from "react";
import { useState } from "react";
import { Container, Typography, Button } from "@mui/material";
import Header from "./HeaderAndFooter/Header";
import Footer from "./HeaderAndFooter/Footer";
import LessonQuestion from "./LessonQuestion";
import LessonText from "./LessonText";
import LessonFillInTheBlank from "./LessonFillInTheBlank";
import LessonCompleted from "./LessonCompleted";
import StreakCompleted from "./StreakCompleted";
import InfoIcon from "@mui/icons-material/Info";
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
import ErrorIcon from "@mui/icons-material/Error";
import DeleteIcon from "@mui/icons-material/Delete";
const styles = {
LessonPageContainer: {
display: "flex",
flexDirection: "column",
minHeight: "90vh",
},
content: {
flexGrow: 1,
},
};
const LessonPageContainer = () => {
const [completed, setCompleted] = useState(false);
const [ question, setQuestion ] = useState("What's your favourite color?");
const [ choices, setChoices ] = useState(["Red", "Blue", "Green", "Yellow"]);
const [ textLessonContent, setTextLessonContent ] = useState([
{
id: 0,
text: "<bold>You can edit this text!</Bold>",
isTextField: false,
severity: "info",
icon: <InfoIcon fontSize="inherit" />
},
{
id: 1,
text: "This is some text that you can edit.",
isTextField: true
},
{
id: 2,
text: "Here is a warning message.",
isTextField: false,
severity: "warning",
icon: <WarningAmberIcon fontSize="inherit" />
},
{
id: 3,
text: "Another editable text field.",
isTextField: true
}
]);
const [lessonMap, setLessonMap] = useState([
{ index: 0, type: "text", content: [] },
{ index: 1, type: "question", question: question, choices: choices },
{ index: 2, type: "filintheblanks", content: [] },
{ index: 3, type: "completed", completed: completed },
]);
const [currentLessonIndex, setCurrentLessonIndex] = useState(0);
const renderLessonComponent = (lessonType) => {
switch (lessonType) {
case "question":
return <LessonQuestion />;
case "text":
return <LessonText textLessonContent={textLessonContent} />;
case "filintheblanks":
return <LessonFillInTheBlank />;
case "completed":
return <LessonCompleted setCompleted={setCompleted} />;
case "streak":
return <StreakCompleted />;
default:
return null;
}
};
const onNextLesson = () => {
setCurrentLessonIndex((prevIndex) =>
prevIndex < lessonMap.length - 1 ? prevIndex + 1 : prevIndex
);
};
const onPreviousLesson = () => {
setCurrentLessonIndex((prevIndex) =>
prevIndex > 0 ? prevIndex - 1 : prevIndex
);
};
return (
<div style={styles.LessonPageContainer}>
<div style={styles.content}>
<Header
lessonTitle={`Lesson ${lessonMap[currentLessonIndex].index + 1}: ${
lessonMap[currentLessonIndex].type
}`}
/>
{renderLessonComponent(lessonMap[currentLessonIndex].type)}
</div>
<Footer onNextLesson={onNextLesson} onPreviousLesson={onPreviousLesson} displayContinue={(currentLessonIndex === lessonMap.length - 1)} />
</div>
);
};
export default LessonPageContainer;
|
#!/usr/bin/python3
import unittest
from models.base_model import BaseModel
import datetime
class TestBaseModelClass(unittest.TestCase):
""" Tests the BaseModel class"""
def test_init_(self):
""" Tests the constructer constructs form kwargs"""
b = BaseModel()
saved_as = b.to_dict()
c = BaseModel(**saved_as)
self.assertEqual(b.id, c.id)
def test_id_type(self):
""" Tests the type of id attribute"""
b1 = BaseModel()
self.assertIsInstance(b1.id, str)
def test_id_uniqeness(self):
""" Tests if id is unique for every object"""
id_list = []
for i in range(2000):
b2 = BaseModel()
self.assertNotIn(b2.id, id_list)
id_list.append(b2.id)
def test_created_at_type(self):
""" Tests the type of created_at is datetime"""
b3 = BaseModel()
self.assertIsInstance(b3.created_at, datetime.datetime)
def test_updated_at_type(self):
""" Test the type of updated_at is datetime"""
b4 = BaseModel()
self.assertIsInstance(b4.updated_at, datetime.datetime)
def test_created_and_updated_at_difference(self):
""" Tests the time two instances are created is different"""
b5 = BaseModel()
b6 = BaseModel()
self.assertNotEqual(b5.created_at, b6.created_at)
def test_str_(self):
""" Tests the representation of an object"""
b7 = BaseModel()
to_be_printed = "[{}] ({}) {}".format(b7.__class__.__name__,
b7.id, b7.__dict__)
self.assertEqual(str(b7), to_be_printed)
def test_to_dict_type(self):
"""Tests to_dict returns a dictinary"""
b9 = BaseModel()
saved_as = b9.to_dict()
self.assertIsInstance(saved_as, dict)
def test_to_dict_content(self):
""" Tests the content of dictinary from to_dict"""
b10 = BaseModel()
saved_as = b10.to_dict()
self.assertIn("__class__", saved_as)
self.assertIn("id", saved_as)
self.assertIn("created_at", saved_as)
self.assertIn("updated_at", saved_as)
def test_to_dict_type(self):
""" Tests the type of created_at and updated_at is str"""
b11 = BaseModel()
saved_as = b11.to_dict()
for key, value in saved_as.items():
if key == "created_at" or key == "updated at":
self.assertIsInstance(value, str)
def test_to_dict_new_attr(self):
""" Tests if new attributes are added to the dictionary returned"""
b12 = BaseModel()
b12.purpose = "test"
saved_as = b12.to_dict()
self.assertIn("purpose", saved_as)
if __name__ == '__main__':
unittest.main()
|
// 通过远程接口进行登录
import React, { Component } from "react";
import axios from "axios";
import "./css/public"
export default class Axios4 extends Component {
state = {
msg: "",
style: { display: "block" },
hide: { display: "none" }
}
// 点击登录事件
login = () => {
let userName = this.refs.userName.value;
let pwd = this.refs.pwd.value;
let obj = { userName: userName, pwd: pwd };
console.log(userName, pwd);
axios.post("/check", obj)
.then(res => {
if(res.data.status ==="10001"){
this.setState({
msg:res.data.msg,
style:{display:"none"},
hide:{display:"block"}
});
}else{
this.setState({
msg:res.data.msg,
})
setTimeout(()=>{
this.setState({msg:""})
},2000);
}
})
}
render() {
let { msg, style, hide } = this.state;
let { login } = this;
return (
<div>
<h3>Axios4组件:远程接口进行登录</h3>
<form style={style}>
用户:<input type="text" ref="userName" /><br />
密码:<input type="password" ref="pwd" /><br />
<input type="button" value="登录" onClick={login} />
<span>{msg}</span>
</form>
<p style={hide}>登陆成功</p>
</div>
);
}
}
|
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { FleteService } from 'src/flete/flete.service';
import { StoreService } from 'src/store/store.service';
@Injectable()
export class FexService {
constructor(
private readonly httpService: HttpService,
private readonly storeService: StoreService,
private readonly fleteService: FleteService,
) {}
async getStores() {
try {
const stores = await this.storeService.getStores();
//StoresMap debería ser un arreglo de Stores con el nombre adress y total
const storesMap = stores.map(async (store) => {
const servicios = await this.fleteService.getFletesByAccKey(
store.access_key,
);
let total = 0;
if (servicios.length > 0) {
total = servicios
.map((servicio) => servicio.total)
.reduce((a, b) => {
const valorNumerico = parseFloat(b);
return a + valorNumerico;
}, 0);
}
return {
id: store._id,
store_name: store.store_name,
address: store.address,
post_code: store.post_code,
city: store.city,
total,
};
});
const promisedStores = await Promise.all(storesMap);
return promisedStores;
} catch (error) {
console.log(error);
}
}
async getStore(id: string) {
try {
const store = await this.storeService.getStoreById(id);
const services = await this.fleteService.getFletesByAccKey(
store.access_key,
);
const servicesMap = services.map((serv) => {
return {
id: serv._id,
servicio: serv.servicio,
dir_origen: serv.dir_origen,
dir_destino: serv.dir_destino,
des_carga: serv.des_carga,
rec_nom: serv.rec_nom,
rec_tel: serv.rec_tel,
vehiculo: serv.vehiculo,
tipo: serv.tipo,
distancia: serv.distancia,
total: serv.total,
estado: serv.estado,
};
});
return servicesMap;
} catch (error) {
console.log(error);
}
}
}
|
import React, { FC, useState } from "react";
import { useNavigate } from "react-router-dom"
import Header from "./Header";
import Sidebar from "./Sidebar";
import Http from "../../helpers/Fetch";
import LoadingScreen from "./LoadingScreen";
import AuthUser from "../../helpers/AuthUser";
interface AuthLayoutProps {
children: React.ReactNode
}
const AuthLayout: FC<AuthLayoutProps> = ({ children }) => {
const navigate = useNavigate();
const user = AuthUser.GetAuth();
const [open, setOpen] = useState<boolean>(false);
const [openModal, setOpenModal] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const [userData, setUserData] = useState<any | null>(null);
const logout = async () => {
setLoading(true)
try {
await Http.get("/user/logout", { withCredentials: true, headers: { 'Authorization': `Bearer ${user?.token}` } });
AuthUser.RemoveAuth();
navigate("/auth/login");
setLoading(false);
} catch (error: any) {
console.log(error?.response);
setLoading(false);
}
}
const GetCurrentUser = async () => {
try {
const res = await Http.get("/user/currentUser", { headers: { 'Authorization': `Bearer ${user?.token}` } });
setUserData(res.data.data);
setOpenModal(true);
} catch (error: any) {
console.log(error);
}
};
const closeModal = () => {
setOpenModal(false);
setUserData(null);
};
return loading ? (
<LoadingScreen />
) : (
<div className="flex relative bg-gray-100 overflow-x-hidden min-h-screen antialiased">
<Sidebar open={open} closeMenu={() => setOpen(!open)} />
<div className="w-full relative ml-0 lg:ml-64">
<Header logout={logout} changeOpen={() => setOpen(!open)} getCurrentUser={GetCurrentUser} />
<main className="w-full mt-16">
{children}
</main>
</div>
{userData && openModal && (
<div className="fixed inset-0 bg-gray-800 bg-opacity-50 flex items-center justify-center">
<div className="bg-white p-8 max-w-md w-full rounded-md shadow-lg">
<h2 className="text-2xl font-bold mb-4">User Data</h2>
<div className="text-gray-900">
<p className="mb-2">
<span className="font-semibold">Name:</span> {userData.name}
</p>
<p className="mb-2">
<span className="font-semibold">Email:</span> {userData.email}
</p>
<p className="mb-2 ">
<span className="font-semibold">Role:</span> {userData.Role.roleName}
</p>
<p className="mb-2 font-semibold">
Active: {userData.active ? <span className="text-green-400">Active</span> : <span className="text-red-400">Non Active</span>}
</p>
<p className="mb-2 font-semibold">
Verified: {userData.verified ? <span className="text-green-400">Verified</span> : <span className="text-red-400">Non Verified</span>}
</p>
</div>
<button onClick={closeModal} className="mt-4 btn btn-secondary">Close</button>
</div>
</div>
)}
</div>
);
}
export default AuthLayout;
|
---
title: "\"[Updated] Million-Viewer Milestones YouTube's Pay Structure\""
date: 2024-06-05T11:08:43.392Z
updated: 2024-06-06T11:08:43.392Z
tags:
- ai video
- ai youtube
categories:
- ai
- youtube
description: "\"This Article Describes [Updated] Million-Viewer Milestones: YouTube's Pay Structure\""
excerpt: "\"This Article Describes [Updated] Million-Viewer Milestones: YouTube's Pay Structure\""
keywords: "\"YouTube's Revenue Model,Million Viewers Impact,YouTube Monetization,Video Platform Profit,Ad-Based Content Stream,Viewer Milestone Payments,Large Audience Earnings\""
thumbnail: https://www.lifewire.com/thmb/uGQ_9SJRmdHuoha7AbY8cdYwrjc=/540x405/filters:no_upscale():max_bytes(150000):strip_icc()/how-to-watch-the-alien-movies-in-order-612898751c874dffb6c6f3990444f8fe.jpg
---
## Million-Viewer Milestones: YouTube's Pay Structure
How much does YouTube pay for 1 million views? As a YouTuber, you become a business, and it helps to know the YouTube views to money earned.
If you are trying to earn a living on YouTube, one of the most excellent marks of a successful creator is often earning 1 million views on the platform ([click here for tips on how to do that](https://www.filmora.io/community-blog/24-smart-ways-that-actually-work---how-to-grow-309.html)). It usually serves as a benchmark for a time at which a channel is relatively sustainable. However, rather than meaning a YouTuber has made it big financially, reaching 1 million views is more likely to say they can expect to _start_ making real money.
When you hit 1 million views on any video on YouTube, you'll have a nice paycheck. You'll likely have to hit 1 million views on at least a few other videos before you could consider quitting your full-time job and doing YouTube as your primary source of income. This article will explore what 1 million views mean for your YouTube channel. We will look more into how revenue is calculated on YouTube and what you can expect to earn-out of a video with 1 million views.
#### In this article
01 [$2000 for 1 million views](#part1)
02 [How is the revenue calculated?](#part2)
03 [CPMs and CPCs](#part3)
04 [How monetization is changing](#part4)
## $2000 for 1 Million Views
In [a case study performed by Standupbits](https://www.fastcompany.com/3018123/a-million-youtube-views-wont-pay-your-rent-but-tubestart-could) and Josef Holm, a YouTube channel is created with over 3500 comedy clips that a comedian and stand up actor had put together over the years. The YouTube clips took extensive time to upload, and the library was prevalent. The YouTube ad revenue only equated to around $2000.
Although StandUpBits had uploaded thousands of clips and received over 1 million views on their channel, their library was only able to earn around $2000 from the ad revenue sharing. It's estimated the group had spent approximately $25,000 to finish off the clips, edit them, and upload them, which means they invested far more in the channel than they earned.
If you are thinking about a career on YouTube, reaching 1 million views might seem like an excellent target for making a successful page, and it is, but reaching 1 million views doesn’t magically guarantee financial success.
## How Revenue is Calculated
In order to understand how revenue is calculated over the YouTube marketplace, a YouTube user needs to first understand what the partnership program entails. Basically, a YouTube partner has the ability to monetize their videos and serve ads on their content.
In order to join this program you need to be able to commit to uploading ad-friendly (nothing controversial) content that is completely original and high quality and which also adheres to all of the community guidelines and YouTube’s Terms of Service (YouTube actually just introduced a couple of stricter rules - click here for [YouTube Monetization 2018](https://www.filmora.io/community-blog/youtube-monetization-2018---the-new-rules-everyone-hates-331.html)).
As of February 2018, to qualify for ad revenue, the YouTube channel must have:
1\. You will need to have 1,000 subscribers.
2\. You will need to have accumulated 4,000 hours of watch time over the last 12 months.
The AdSense revenue that you earn through YouTube will vary depending on a large number of factors related to the specific ads running and what type of content you produce.
## Understanding CPM and CPCs
### What is CPM?
CPM stands as the ‘cost per mille’ or ‘cost per thousand.’
Your CPM is the amount you earn for 1000 ad impressions (1000 viewers clicking on an ad or watching a skippable ad). Your CPM is usually related to the demographics of your users, the content you regularly post, the length of time on the videos that you post, and the gender of your viewers. YouTube CPMs can vary depending on the advertising bid the company has submitted with Google. The lowest bids can be around .33 cents per thousand views, and other advertisers can spend as much as $10 for 1000 views.
For example, gaming is the most prominent genre on YouTube, and there are many gaming-related ads to go around, but most of them are very low-paying (i.e., ads for free online games). Only YouTube gamers with extensive subscriber bases get higher-paying ads.
### What is CPC?
CPC means ‘cost per click.’ A CPC ad interprets an ‘ad impression’ as a click on an ad rather than a viewer merely seeing it. Most YouTube ads are CPC ads, but skippable video ads are CPV (cost per view), and impressions are based on viewers watching the ad instead of skipping it.
## Changes on YouTube and How You Can Earn More
Changes that have affected the way that revenue is calculated are the ability to skip ads and the lower click rates on advertising through YouTube. A huge portion of viewers uses ad blockers, which eliminates them as potential sources of revenue.
Ultimately earning ad revenue is a big game of reaching targeted demographics and [achieving ongoing viewership](https://www.filmora.io/community-blog/how-to-convert-viewers-into-subscribers-%28the-easy-way%29-287.html) for your videos. It does matter where your viewers are going to be viewing from, and the audience that your viewers are in (viewers from areas with more disposable income to spend on the products advertised to them are worth more to advertisers, as are viewers who are interested in higher-cost items).
[Forming relationships with brands](https://www.filmora.io/community-blog/tips-for-youtube-brand-deals-from-marketing-pro-amanda-haines-171.html) and doing product placements or sponsored videos can be a great way to earn more revenue than you will through AdSense. Just make sure the brands you build relationships with are relevant to your audience and that you incorporate the advertising in ways that don’t annoy your viewers.
Use the right keywords in your titles, descriptions, and tags. Without this keyword information, YouTube may pair your video with advertisers that aren’t right for your audience. First, using the wrong keywords won’t put your content in front of the viewers who want to see it, and, second, the ads that run won’t be a good fit and thus are less likely to be clicked on. It's also imperative that you focus on the metadata of every video. It can take some extra time to add in all of this information for each video, but it is well worth it if you are trying to get paid from YouTube.
[Click here for 4 ways to start growing your channel faster.](https://www.filmora.io/community-blog/youtube-subscriber-boost%21-the-4-simplest-tricks-to-grow-your-317.html)
So, how much does YouTube pay for 1 million views? Not as much as you might think. But don't give up, because ad revenue is not the only way to make money through YouTube. Here are[4 alternative ways to make money as a YouTuber](https://tools.techidaily.com/wondershare/filmora/download/).
#### [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Get started easily with Filmora's powerful performance, intuitive interface, and countless effects!
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)

02 [How is the revenue calculated?](#part2)
03 [CPMs and CPCs](#part3)
04 [How monetization is changing](#part4)
## $2000 for 1 Million Views
In [a case study performed by Standupbits](https://www.fastcompany.com/3018123/a-million-youtube-views-wont-pay-your-rent-but-tubestart-could) and Josef Holm, a YouTube channel is created with over 3500 comedy clips that a comedian and stand up actor had put together over the years. The YouTube clips took extensive time to upload, and the library was prevalent. The YouTube ad revenue only equated to around $2000.
Although StandUpBits had uploaded thousands of clips and received over 1 million views on their channel, their library was only able to earn around $2000 from the ad revenue sharing. It's estimated the group had spent approximately $25,000 to finish off the clips, edit them, and upload them, which means they invested far more in the channel than they earned.
If you are thinking about a career on YouTube, reaching 1 million views might seem like an excellent target for making a successful page, and it is, but reaching 1 million views doesn’t magically guarantee financial success.
## How Revenue is Calculated
In order to understand how revenue is calculated over the YouTube marketplace, a YouTube user needs to first understand what the partnership program entails. Basically, a YouTube partner has the ability to monetize their videos and serve ads on their content.
In order to join this program you need to be able to commit to uploading ad-friendly (nothing controversial) content that is completely original and high quality and which also adheres to all of the community guidelines and YouTube’s Terms of Service (YouTube actually just introduced a couple of stricter rules - click here for [YouTube Monetization 2018](https://www.filmora.io/community-blog/youtube-monetization-2018---the-new-rules-everyone-hates-331.html)).
As of February 2018, to qualify for ad revenue, the YouTube channel must have:
1\. You will need to have 1,000 subscribers.
2\. You will need to have accumulated 4,000 hours of watch time over the last 12 months.
The AdSense revenue that you earn through YouTube will vary depending on a large number of factors related to the specific ads running and what type of content you produce.
## Understanding CPM and CPCs
### What is CPM?
CPM stands as the ‘cost per mille’ or ‘cost per thousand.’
Your CPM is the amount you earn for 1000 ad impressions (1000 viewers clicking on an ad or watching a skippable ad). Your CPM is usually related to the demographics of your users, the content you regularly post, the length of time on the videos that you post, and the gender of your viewers. YouTube CPMs can vary depending on the advertising bid the company has submitted with Google. The lowest bids can be around .33 cents per thousand views, and other advertisers can spend as much as $10 for 1000 views.
For example, gaming is the most prominent genre on YouTube, and there are many gaming-related ads to go around, but most of them are very low-paying (i.e., ads for free online games). Only YouTube gamers with extensive subscriber bases get higher-paying ads.
### What is CPC?
CPC means ‘cost per click.’ A CPC ad interprets an ‘ad impression’ as a click on an ad rather than a viewer merely seeing it. Most YouTube ads are CPC ads, but skippable video ads are CPV (cost per view), and impressions are based on viewers watching the ad instead of skipping it.
## Changes on YouTube and How You Can Earn More
Changes that have affected the way that revenue is calculated are the ability to skip ads and the lower click rates on advertising through YouTube. A huge portion of viewers uses ad blockers, which eliminates them as potential sources of revenue.
Ultimately earning ad revenue is a big game of reaching targeted demographics and [achieving ongoing viewership](https://www.filmora.io/community-blog/how-to-convert-viewers-into-subscribers-%28the-easy-way%29-287.html) for your videos. It does matter where your viewers are going to be viewing from, and the audience that your viewers are in (viewers from areas with more disposable income to spend on the products advertised to them are worth more to advertisers, as are viewers who are interested in higher-cost items).
[Forming relationships with brands](https://www.filmora.io/community-blog/tips-for-youtube-brand-deals-from-marketing-pro-amanda-haines-171.html) and doing product placements or sponsored videos can be a great way to earn more revenue than you will through AdSense. Just make sure the brands you build relationships with are relevant to your audience and that you incorporate the advertising in ways that don’t annoy your viewers.
Use the right keywords in your titles, descriptions, and tags. Without this keyword information, YouTube may pair your video with advertisers that aren’t right for your audience. First, using the wrong keywords won’t put your content in front of the viewers who want to see it, and, second, the ads that run won’t be a good fit and thus are less likely to be clicked on. It's also imperative that you focus on the metadata of every video. It can take some extra time to add in all of this information for each video, but it is well worth it if you are trying to get paid from YouTube.
[Click here for 4 ways to start growing your channel faster.](https://www.filmora.io/community-blog/youtube-subscriber-boost%21-the-4-simplest-tricks-to-grow-your-317.html)
So, how much does YouTube pay for 1 million views? Not as much as you might think. But don't give up, because ad revenue is not the only way to make money through YouTube. Here are[4 alternative ways to make money as a YouTuber](https://tools.techidaily.com/wondershare/filmora/download/).
#### [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Get started easily with Filmora's powerful performance, intuitive interface, and countless effects!
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)

02 [How is the revenue calculated?](#part2)
03 [CPMs and CPCs](#part3)
04 [How monetization is changing](#part4)
## $2000 for 1 Million Views
In [a case study performed by Standupbits](https://www.fastcompany.com/3018123/a-million-youtube-views-wont-pay-your-rent-but-tubestart-could) and Josef Holm, a YouTube channel is created with over 3500 comedy clips that a comedian and stand up actor had put together over the years. The YouTube clips took extensive time to upload, and the library was prevalent. The YouTube ad revenue only equated to around $2000.
Although StandUpBits had uploaded thousands of clips and received over 1 million views on their channel, their library was only able to earn around $2000 from the ad revenue sharing. It's estimated the group had spent approximately $25,000 to finish off the clips, edit them, and upload them, which means they invested far more in the channel than they earned.
If you are thinking about a career on YouTube, reaching 1 million views might seem like an excellent target for making a successful page, and it is, but reaching 1 million views doesn’t magically guarantee financial success.
## How Revenue is Calculated
In order to understand how revenue is calculated over the YouTube marketplace, a YouTube user needs to first understand what the partnership program entails. Basically, a YouTube partner has the ability to monetize their videos and serve ads on their content.
In order to join this program you need to be able to commit to uploading ad-friendly (nothing controversial) content that is completely original and high quality and which also adheres to all of the community guidelines and YouTube’s Terms of Service (YouTube actually just introduced a couple of stricter rules - click here for [YouTube Monetization 2018](https://www.filmora.io/community-blog/youtube-monetization-2018---the-new-rules-everyone-hates-331.html)).
As of February 2018, to qualify for ad revenue, the YouTube channel must have:
1\. You will need to have 1,000 subscribers.
2\. You will need to have accumulated 4,000 hours of watch time over the last 12 months.
The AdSense revenue that you earn through YouTube will vary depending on a large number of factors related to the specific ads running and what type of content you produce.
## Understanding CPM and CPCs
### What is CPM?
CPM stands as the ‘cost per mille’ or ‘cost per thousand.’
Your CPM is the amount you earn for 1000 ad impressions (1000 viewers clicking on an ad or watching a skippable ad). Your CPM is usually related to the demographics of your users, the content you regularly post, the length of time on the videos that you post, and the gender of your viewers. YouTube CPMs can vary depending on the advertising bid the company has submitted with Google. The lowest bids can be around .33 cents per thousand views, and other advertisers can spend as much as $10 for 1000 views.
For example, gaming is the most prominent genre on YouTube, and there are many gaming-related ads to go around, but most of them are very low-paying (i.e., ads for free online games). Only YouTube gamers with extensive subscriber bases get higher-paying ads.
### What is CPC?
CPC means ‘cost per click.’ A CPC ad interprets an ‘ad impression’ as a click on an ad rather than a viewer merely seeing it. Most YouTube ads are CPC ads, but skippable video ads are CPV (cost per view), and impressions are based on viewers watching the ad instead of skipping it.
## Changes on YouTube and How You Can Earn More
Changes that have affected the way that revenue is calculated are the ability to skip ads and the lower click rates on advertising through YouTube. A huge portion of viewers uses ad blockers, which eliminates them as potential sources of revenue.
Ultimately earning ad revenue is a big game of reaching targeted demographics and [achieving ongoing viewership](https://www.filmora.io/community-blog/how-to-convert-viewers-into-subscribers-%28the-easy-way%29-287.html) for your videos. It does matter where your viewers are going to be viewing from, and the audience that your viewers are in (viewers from areas with more disposable income to spend on the products advertised to them are worth more to advertisers, as are viewers who are interested in higher-cost items).
[Forming relationships with brands](https://www.filmora.io/community-blog/tips-for-youtube-brand-deals-from-marketing-pro-amanda-haines-171.html) and doing product placements or sponsored videos can be a great way to earn more revenue than you will through AdSense. Just make sure the brands you build relationships with are relevant to your audience and that you incorporate the advertising in ways that don’t annoy your viewers.
Use the right keywords in your titles, descriptions, and tags. Without this keyword information, YouTube may pair your video with advertisers that aren’t right for your audience. First, using the wrong keywords won’t put your content in front of the viewers who want to see it, and, second, the ads that run won’t be a good fit and thus are less likely to be clicked on. It's also imperative that you focus on the metadata of every video. It can take some extra time to add in all of this information for each video, but it is well worth it if you are trying to get paid from YouTube.
[Click here for 4 ways to start growing your channel faster.](https://www.filmora.io/community-blog/youtube-subscriber-boost%21-the-4-simplest-tricks-to-grow-your-317.html)
So, how much does YouTube pay for 1 million views? Not as much as you might think. But don't give up, because ad revenue is not the only way to make money through YouTube. Here are[4 alternative ways to make money as a YouTuber](https://tools.techidaily.com/wondershare/filmora/download/).
#### [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Get started easily with Filmora's powerful performance, intuitive interface, and countless effects!
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)

02 [How is the revenue calculated?](#part2)
03 [CPMs and CPCs](#part3)
04 [How monetization is changing](#part4)
## $2000 for 1 Million Views
In [a case study performed by Standupbits](https://www.fastcompany.com/3018123/a-million-youtube-views-wont-pay-your-rent-but-tubestart-could) and Josef Holm, a YouTube channel is created with over 3500 comedy clips that a comedian and stand up actor had put together over the years. The YouTube clips took extensive time to upload, and the library was prevalent. The YouTube ad revenue only equated to around $2000.
Although StandUpBits had uploaded thousands of clips and received over 1 million views on their channel, their library was only able to earn around $2000 from the ad revenue sharing. It's estimated the group had spent approximately $25,000 to finish off the clips, edit them, and upload them, which means they invested far more in the channel than they earned.
If you are thinking about a career on YouTube, reaching 1 million views might seem like an excellent target for making a successful page, and it is, but reaching 1 million views doesn’t magically guarantee financial success.
## How Revenue is Calculated
In order to understand how revenue is calculated over the YouTube marketplace, a YouTube user needs to first understand what the partnership program entails. Basically, a YouTube partner has the ability to monetize their videos and serve ads on their content.
In order to join this program you need to be able to commit to uploading ad-friendly (nothing controversial) content that is completely original and high quality and which also adheres to all of the community guidelines and YouTube’s Terms of Service (YouTube actually just introduced a couple of stricter rules - click here for [YouTube Monetization 2018](https://www.filmora.io/community-blog/youtube-monetization-2018---the-new-rules-everyone-hates-331.html)).
As of February 2018, to qualify for ad revenue, the YouTube channel must have:
1\. You will need to have 1,000 subscribers.
2\. You will need to have accumulated 4,000 hours of watch time over the last 12 months.
The AdSense revenue that you earn through YouTube will vary depending on a large number of factors related to the specific ads running and what type of content you produce.
## Understanding CPM and CPCs
### What is CPM?
CPM stands as the ‘cost per mille’ or ‘cost per thousand.’
Your CPM is the amount you earn for 1000 ad impressions (1000 viewers clicking on an ad or watching a skippable ad). Your CPM is usually related to the demographics of your users, the content you regularly post, the length of time on the videos that you post, and the gender of your viewers. YouTube CPMs can vary depending on the advertising bid the company has submitted with Google. The lowest bids can be around .33 cents per thousand views, and other advertisers can spend as much as $10 for 1000 views.
For example, gaming is the most prominent genre on YouTube, and there are many gaming-related ads to go around, but most of them are very low-paying (i.e., ads for free online games). Only YouTube gamers with extensive subscriber bases get higher-paying ads.
### What is CPC?
CPC means ‘cost per click.’ A CPC ad interprets an ‘ad impression’ as a click on an ad rather than a viewer merely seeing it. Most YouTube ads are CPC ads, but skippable video ads are CPV (cost per view), and impressions are based on viewers watching the ad instead of skipping it.
## Changes on YouTube and How You Can Earn More
Changes that have affected the way that revenue is calculated are the ability to skip ads and the lower click rates on advertising through YouTube. A huge portion of viewers uses ad blockers, which eliminates them as potential sources of revenue.
Ultimately earning ad revenue is a big game of reaching targeted demographics and [achieving ongoing viewership](https://www.filmora.io/community-blog/how-to-convert-viewers-into-subscribers-%28the-easy-way%29-287.html) for your videos. It does matter where your viewers are going to be viewing from, and the audience that your viewers are in (viewers from areas with more disposable income to spend on the products advertised to them are worth more to advertisers, as are viewers who are interested in higher-cost items).
[Forming relationships with brands](https://www.filmora.io/community-blog/tips-for-youtube-brand-deals-from-marketing-pro-amanda-haines-171.html) and doing product placements or sponsored videos can be a great way to earn more revenue than you will through AdSense. Just make sure the brands you build relationships with are relevant to your audience and that you incorporate the advertising in ways that don’t annoy your viewers.
Use the right keywords in your titles, descriptions, and tags. Without this keyword information, YouTube may pair your video with advertisers that aren’t right for your audience. First, using the wrong keywords won’t put your content in front of the viewers who want to see it, and, second, the ads that run won’t be a good fit and thus are less likely to be clicked on. It's also imperative that you focus on the metadata of every video. It can take some extra time to add in all of this information for each video, but it is well worth it if you are trying to get paid from YouTube.
[Click here for 4 ways to start growing your channel faster.](https://www.filmora.io/community-blog/youtube-subscriber-boost%21-the-4-simplest-tricks-to-grow-your-317.html)
So, how much does YouTube pay for 1 million views? Not as much as you might think. But don't give up, because ad revenue is not the only way to make money through YouTube. Here are[4 alternative ways to make money as a YouTuber](https://tools.techidaily.com/wondershare/filmora/download/).
#### [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Get started easily with Filmora's powerful performance, intuitive interface, and countless effects!
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)

<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## Financial Flourishing with Glamour Vlogs
# How to Make Money with a Beauty Channel?

##### Richard Bennett
Nov 01, 2022• Proven solutions
[0](#commentsBoxSeoTemplate)
There are a lot of ways you can make money by posting makeup, beauty, or fashion videos on YouTube. These are all industries that understand the value of quality social media content.
In the video above, [beauty YouTuber](https://tools.techidaily.com/wondershare/filmora/download/) Gena M explains all the ways there are to make money posting makeup and fashion videos on YouTube. Gena’s most important piece of advice for other beauty vloggers is, to be honest. There is nothing wrong with making money from affiliates or sponsors, so long as you only associate with and recommend products you would actually buy.
Here’s more advice on how you can make money from your makeup videos:
## Sponsorships
If you are truly passionate about makeup or fashion then you probably have a few favorite brands. Even if you have never really thought about a brand as your favorite, chances are you purchase one or two types of lip gloss – or any other product – over others on a regular basis.
Wouldn’t it be nice if a company whose product you already love and use in your videos would start paying you just to mention them?
There are sites called influencer marketing platforms – the most popular one is FameBit – where you can find brands that are looking for creators just like you to work with them on marketing campaigns. Brands post what they are looking for, and you send them proposals for what kinds of videos you want to make for them.
Sometimes, creating branded content can be as easy as drawing attention to the brand of the eyeliner you use in a few of your tutorials.
Other times, brands may want you to say specific things or include logos in your videos.
Make sure to incorporate any brand messages or product placement you agree to do in ways that will feel natural to your viewers. You should let them know that you have a sponsor, and then incorporate the branded content in ways that do not take away from their enjoyment of your videos.
## Ad Revenue
Monetizing your videos and earning ad revenue is one of the primary ways beauty vloggers, and all other YouTubers, make money. It takes a long time to earn more than the pocket change from ads, but so long as you keep growing your audience your revenue will keep going up.
Pay attention to the estimated revenue reports to see which of your videos are earning the most money from ads (they won’t always be your most popular videos). By making more videos on similar topics you will be able to make more money.
## Affiliate Links
By becoming an Amazon affiliate, or joining the affiliate program of another online store, you can make money by including links to products in the descriptions of your video or in your related blog posts.
For example, if you talk about your new curling iron in a hair tutorial then you can include a special link to it on Amazon. If any of your viewers follow that link and buy it, you earn a percentage of the purchase.
Even better – if that person keeps shopping, or even skips the curling iron and buys something else, you earn a percentage of any purchase they make on Amazon for a certain period of time.
Affiliate links are mostly used by bloggers, not YouTubers, but you can still include them in the descriptions of your videos (not YouTube Cards or annotations though). It is not a bad idea for you to create blog posts to accompany your videos and post your affiliate links. Blogs are a great way to generate traffic to your videos.
## Gifts
Sometimes companies might just give you stuff.
As your following gets bigger, brands might start sending you samples of their products in the hopes that you will fall in love with them and mention, review, or use them in your videos. This is not the same as a sponsorship because the brand is not paying you for a specific kind of message.
Receiving these kinds of gifts is not the same as getting paid, but it can certainly save you money on makeup.

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Nov 01, 2022• Proven solutions
[0](#commentsBoxSeoTemplate)
There are a lot of ways you can make money by posting makeup, beauty, or fashion videos on YouTube. These are all industries that understand the value of quality social media content.
In the video above, [beauty YouTuber](https://tools.techidaily.com/wondershare/filmora/download/) Gena M explains all the ways there are to make money posting makeup and fashion videos on YouTube. Gena’s most important piece of advice for other beauty vloggers is, to be honest. There is nothing wrong with making money from affiliates or sponsors, so long as you only associate with and recommend products you would actually buy.
Here’s more advice on how you can make money from your makeup videos:
## Sponsorships
If you are truly passionate about makeup or fashion then you probably have a few favorite brands. Even if you have never really thought about a brand as your favorite, chances are you purchase one or two types of lip gloss – or any other product – over others on a regular basis.
Wouldn’t it be nice if a company whose product you already love and use in your videos would start paying you just to mention them?
There are sites called influencer marketing platforms – the most popular one is FameBit – where you can find brands that are looking for creators just like you to work with them on marketing campaigns. Brands post what they are looking for, and you send them proposals for what kinds of videos you want to make for them.
Sometimes, creating branded content can be as easy as drawing attention to the brand of the eyeliner you use in a few of your tutorials.
Other times, brands may want you to say specific things or include logos in your videos.
Make sure to incorporate any brand messages or product placement you agree to do in ways that will feel natural to your viewers. You should let them know that you have a sponsor, and then incorporate the branded content in ways that do not take away from their enjoyment of your videos.
## Ad Revenue
Monetizing your videos and earning ad revenue is one of the primary ways beauty vloggers, and all other YouTubers, make money. It takes a long time to earn more than the pocket change from ads, but so long as you keep growing your audience your revenue will keep going up.
Pay attention to the estimated revenue reports to see which of your videos are earning the most money from ads (they won’t always be your most popular videos). By making more videos on similar topics you will be able to make more money.
## Affiliate Links
By becoming an Amazon affiliate, or joining the affiliate program of another online store, you can make money by including links to products in the descriptions of your video or in your related blog posts.
For example, if you talk about your new curling iron in a hair tutorial then you can include a special link to it on Amazon. If any of your viewers follow that link and buy it, you earn a percentage of the purchase.
Even better – if that person keeps shopping, or even skips the curling iron and buys something else, you earn a percentage of any purchase they make on Amazon for a certain period of time.
Affiliate links are mostly used by bloggers, not YouTubers, but you can still include them in the descriptions of your videos (not YouTube Cards or annotations though). It is not a bad idea for you to create blog posts to accompany your videos and post your affiliate links. Blogs are a great way to generate traffic to your videos.
## Gifts
Sometimes companies might just give you stuff.
As your following gets bigger, brands might start sending you samples of their products in the hopes that you will fall in love with them and mention, review, or use them in your videos. This is not the same as a sponsorship because the brand is not paying you for a specific kind of message.
Receiving these kinds of gifts is not the same as getting paid, but it can certainly save you money on makeup.

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Nov 01, 2022• Proven solutions
[0](#commentsBoxSeoTemplate)
There are a lot of ways you can make money by posting makeup, beauty, or fashion videos on YouTube. These are all industries that understand the value of quality social media content.
In the video above, [beauty YouTuber](https://tools.techidaily.com/wondershare/filmora/download/) Gena M explains all the ways there are to make money posting makeup and fashion videos on YouTube. Gena’s most important piece of advice for other beauty vloggers is, to be honest. There is nothing wrong with making money from affiliates or sponsors, so long as you only associate with and recommend products you would actually buy.
Here’s more advice on how you can make money from your makeup videos:
## Sponsorships
If you are truly passionate about makeup or fashion then you probably have a few favorite brands. Even if you have never really thought about a brand as your favorite, chances are you purchase one or two types of lip gloss – or any other product – over others on a regular basis.
Wouldn’t it be nice if a company whose product you already love and use in your videos would start paying you just to mention them?
There are sites called influencer marketing platforms – the most popular one is FameBit – where you can find brands that are looking for creators just like you to work with them on marketing campaigns. Brands post what they are looking for, and you send them proposals for what kinds of videos you want to make for them.
Sometimes, creating branded content can be as easy as drawing attention to the brand of the eyeliner you use in a few of your tutorials.
Other times, brands may want you to say specific things or include logos in your videos.
Make sure to incorporate any brand messages or product placement you agree to do in ways that will feel natural to your viewers. You should let them know that you have a sponsor, and then incorporate the branded content in ways that do not take away from their enjoyment of your videos.
## Ad Revenue
Monetizing your videos and earning ad revenue is one of the primary ways beauty vloggers, and all other YouTubers, make money. It takes a long time to earn more than the pocket change from ads, but so long as you keep growing your audience your revenue will keep going up.
Pay attention to the estimated revenue reports to see which of your videos are earning the most money from ads (they won’t always be your most popular videos). By making more videos on similar topics you will be able to make more money.
## Affiliate Links
By becoming an Amazon affiliate, or joining the affiliate program of another online store, you can make money by including links to products in the descriptions of your video or in your related blog posts.
For example, if you talk about your new curling iron in a hair tutorial then you can include a special link to it on Amazon. If any of your viewers follow that link and buy it, you earn a percentage of the purchase.
Even better – if that person keeps shopping, or even skips the curling iron and buys something else, you earn a percentage of any purchase they make on Amazon for a certain period of time.
Affiliate links are mostly used by bloggers, not YouTubers, but you can still include them in the descriptions of your videos (not YouTube Cards or annotations though). It is not a bad idea for you to create blog posts to accompany your videos and post your affiliate links. Blogs are a great way to generate traffic to your videos.
## Gifts
Sometimes companies might just give you stuff.
As your following gets bigger, brands might start sending you samples of their products in the hopes that you will fall in love with them and mention, review, or use them in your videos. This is not the same as a sponsorship because the brand is not paying you for a specific kind of message.
Receiving these kinds of gifts is not the same as getting paid, but it can certainly save you money on makeup.

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Nov 01, 2022• Proven solutions
[0](#commentsBoxSeoTemplate)
There are a lot of ways you can make money by posting makeup, beauty, or fashion videos on YouTube. These are all industries that understand the value of quality social media content.
In the video above, [beauty YouTuber](https://tools.techidaily.com/wondershare/filmora/download/) Gena M explains all the ways there are to make money posting makeup and fashion videos on YouTube. Gena’s most important piece of advice for other beauty vloggers is, to be honest. There is nothing wrong with making money from affiliates or sponsors, so long as you only associate with and recommend products you would actually buy.
Here’s more advice on how you can make money from your makeup videos:
## Sponsorships
If you are truly passionate about makeup or fashion then you probably have a few favorite brands. Even if you have never really thought about a brand as your favorite, chances are you purchase one or two types of lip gloss – or any other product – over others on a regular basis.
Wouldn’t it be nice if a company whose product you already love and use in your videos would start paying you just to mention them?
There are sites called influencer marketing platforms – the most popular one is FameBit – where you can find brands that are looking for creators just like you to work with them on marketing campaigns. Brands post what they are looking for, and you send them proposals for what kinds of videos you want to make for them.
Sometimes, creating branded content can be as easy as drawing attention to the brand of the eyeliner you use in a few of your tutorials.
Other times, brands may want you to say specific things or include logos in your videos.
Make sure to incorporate any brand messages or product placement you agree to do in ways that will feel natural to your viewers. You should let them know that you have a sponsor, and then incorporate the branded content in ways that do not take away from their enjoyment of your videos.
## Ad Revenue
Monetizing your videos and earning ad revenue is one of the primary ways beauty vloggers, and all other YouTubers, make money. It takes a long time to earn more than the pocket change from ads, but so long as you keep growing your audience your revenue will keep going up.
Pay attention to the estimated revenue reports to see which of your videos are earning the most money from ads (they won’t always be your most popular videos). By making more videos on similar topics you will be able to make more money.
## Affiliate Links
By becoming an Amazon affiliate, or joining the affiliate program of another online store, you can make money by including links to products in the descriptions of your video or in your related blog posts.
For example, if you talk about your new curling iron in a hair tutorial then you can include a special link to it on Amazon. If any of your viewers follow that link and buy it, you earn a percentage of the purchase.
Even better – if that person keeps shopping, or even skips the curling iron and buys something else, you earn a percentage of any purchase they make on Amazon for a certain period of time.
Affiliate links are mostly used by bloggers, not YouTubers, but you can still include them in the descriptions of your videos (not YouTube Cards or annotations though). It is not a bad idea for you to create blog posts to accompany your videos and post your affiliate links. Blogs are a great way to generate traffic to your videos.
## Gifts
Sometimes companies might just give you stuff.
As your following gets bigger, brands might start sending you samples of their products in the hopes that you will fall in love with them and mention, review, or use them in your videos. This is not the same as a sponsorship because the brand is not paying you for a specific kind of message.
Receiving these kinds of gifts is not the same as getting paid, but it can certainly save you money on makeup.

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
<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://facebook-video-footage.techidaily.com/updated-in-2024-checking-credentials-on-youtube/"><u>[Updated] In 2024, Checking Credentials on YouTube</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-enhancing-video-soundtracks-on-digital-platforms-for-2024/"><u>[Updated] Enhancing Video Soundtracks on Digital Platforms for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-enlightenment-echoes-best-ed-tutorials-yt/"><u>[Updated] In 2024, Enlightenment Echoes Best Ed Tutorials YT</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-boosting-revenue-with-the-perfect-youtube-trailer-strategy-for-2024/"><u>[New] Boosting Revenue with the Perfect YouTube Trailer Strategy for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-5-pro-tips-to-perfectly-tag-videos-and-maximize-views/"><u>[Updated] In 2024, 5 Pro Tips to Perfectly Tag Videos and Maximize Views</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/the-ultimate-youtube-seo-toolkit-boosting-your-content-rankings-for-2024/"><u>The Ultimate YouTube SEO Toolkit Boosting Your Content Rankings for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-legality-of-recording-on-youtube-platform/"><u>[Updated] Legality of Recording on YouTube Platform?</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/in-2024-youtubes-transformation-blueprint-for-igtv-adaptation/"><u>In 2024, YouTube's Transformation Blueprint for IGTV Adaptation</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/unbeatable-choices-top-free-online-intros-for-2024/"><u>Unbeatable Choices Top Free Online Intros for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-overcoming-video-shadows-youtube-fix-tips/"><u>[Updated] Overcoming Video Shadows YouTube Fix Tips</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-youtubes-earnings-explained-making-money-from-ads/"><u>[New] YouTube’s Earnings Explained Making Money From Ads</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-visionaries-shaping-marvel-online-experience/"><u>[New] Visionaries Shaping Marvel Online Experience</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/paving-the-way-for-youtube-wealth-reaching-a-threshold-of-500-subs-for-2024/"><u>Paving the Way for YouTube Wealth Reaching a Threshold of 500 Subs for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-download-youtube-playlists-without-hassle-our-guide-for-2024/"><u>[Updated] Download YouTube Playlists Without Hassle - Our Guide for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-essential-microphones-tailored-to-channel-genres/"><u>[Updated] In 2024, Essential Microphones Tailored to Channel Genres</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/scouting-for-starred-youtube-conversations-for-2024/"><u>Scouting for Starred YouTube Conversations for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-the-art-of-attention-secrets-to-making-your-youtube-ads-stand-out/"><u>[Updated] The Art of Attention Secrets to Making Your YouTube Ads Stand Out</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-engage-in-enlightening-youtube-exchanges-for-2024/"><u>[Updated] Engage in Enlightening YouTube Exchanges for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-educator-elite-selective-learning-yt-channels-for-2024/"><u>[Updated] Educator Elite Selective Learning YT Channels for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/the-key-to-attracting-views-youtube-image-marketing-for-2024/"><u>The Key to Attracting Views YouTube Image Marketing for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-youtube-to-igtv-migration-step-by-step-guide/"><u>[Updated] YouTube-to-IGTV Migration Step-by-Step Guide</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-a-guide-to-profit-sharing-for-creators-of-video-clips-for-2024/"><u>[New] A Guide to Profit Sharing for Creators of Video Clips for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-cutting-edge-taggification-top-7-affordable-online-extractors-for-youtube-for-2024/"><u>[Updated] Cutting-Edge Taggification Top 7 Affordable Online Extractors for YouTube for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/unlock-youtube-ad-revenue-recent-policy-insights-for-2024/"><u>Unlock YouTube Ad Revenue Recent Policy Insights for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-essential-tips-sharing-your-apple-devices-screen-with-youtube-for-2024/"><u>[Updated] Essential Tips Sharing Your Apple Devices Screen with YouTube for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-in-2024-choreographing-climactic-crescendos/"><u>[New] In 2024, Choreographing Climactic Crescendos</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-puns-and-plots-developing-7-funny-video-storylines/"><u>[Updated] Puns & Plots Developing 7 Funny Video Storylines</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-essentials-to-skyrocketing-video-views-on-youtube-for-2024/"><u>[New] Essentials to Skyrocketing Video Views on YouTube for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-creating-content-earning-currency-launching-your-vlog/"><u>[Updated] In 2024, Creating Content, Earning Currency Launching Your Vlog</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-the-definitive-guide-to-youtubes-algorithmic-secrets-for-rankings/"><u>[Updated] The Definitive Guide to YouTube's Algorithmic Secrets for Rankings</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/the-roadmap-to-youtube-fame-accruing-more-subscribers-for-2024/"><u>The Roadmap to YouTube Fame Accruing More Subscribers for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-chuckle-factory-designing-7-video-ideas-for-humorists-for-2024/"><u>[Updated] Chuckle Factory Designing 7 Video Ideas for Humorists for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-elevate-your-videography-7-free-sound-effects-collection-for-2024/"><u>[New] Elevate Your Videography - 7 Free Sound Effects Collection for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-augment-your-vfx-arsenal-explore-these-top-8-sites-for-free-eco-backgrounds/"><u>[New] 2024 Approved Augment Your VFX Arsenal - Explore These Top 8 Sites for Free Eco-Backgrounds</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-mp3-export-made-easy-select-free-apps-for-iphone-and-youtube/"><u>[Updated] MP3 Export Made Easy Select Free Apps for iPhone & YouTube</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/new-transforming-youtubers-into-titans-with-key-insights-from-the-hub/"><u>[New] Transforming YouTubers Into Titans with Key Insights From the Hub</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/the-content-creators-dilemma-choosing-between-igtv-and-youtube-for-2024/"><u>The Content Creator’s Dilemma Choosing Between IGTV and YouTube for 2024</u></a></li>
<li><a href="https://youtube-video-recordings.techidaily.com/updated-can-you-legally-capture-video-from-youtube/"><u>[Updated] Can You Legally Capture Video From YouTube?</u></a></li>
<li><a href="https://snapchat-videos.techidaily.com/new-2024-approved-innovative-snapchat-techniques-for-lens-makers/"><u>[New] 2024 Approved Innovative Snapchat Techniques for Lens Makers</u></a></li>
<li><a href="https://unlock-android.techidaily.com/in-2024-how-to-track-imei-number-of-xiaomi-redmi-note-12-pro-4g-through-google-earth-by-drfone-android/"><u>In 2024, How To Track IMEI Number Of Xiaomi Redmi Note 12 Pro 4G Through Google Earth?</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/updated-the-best-ways-to-send-video-invitations-from-your-iphone-or-android-for-2024/"><u>Updated The Best Ways to Send Video Invitations From Your iPhone or Android for 2024</u></a></li>
<li><a href="https://tiktok-clips.techidaily.com/updated-gourmet-goals-on-tiktok-culinary-challenges-worth-pursuing-for-2024/"><u>[Updated] Gourmet Goals on TikTok Culinary Challenges Worth Pursuing for 2024</u></a></li>
<li><a href="https://extra-lessons.techidaily.com/10-best-screenshot-enhancers-iphoneandroid-sticker-magic-for-2024/"><u>10 Best Screenshot Enhancers IPhone/Android Sticker Magic for 2024</u></a></li>
<li><a href="https://tiktok-video-recordings.techidaily.com/updated-in-2024-crafting-a-viral-identity-the-best-30-innovative-tiktok-handles/"><u>[Updated] In 2024, Crafting a Viral Identity The Best 30 Innovative TikTok Handles</u></a></li>
<li><a href="https://twitter-clips.techidaily.com/new-mastering-media-your-step-by-step-video-tweet-for-2024/"><u>[New] Mastering Media Your Step-by-Step Video Tweet for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/unlock-full-potential-mac-plus-obs-plus-streamlabs-for-2024/"><u>Unlock Full Potential Mac + OBS + Streamlabs for 2024</u></a></li>
<li><a href="https://snapchat-videos.techidaily.com/updated-2024-approved-mastering-mobile-screen-recording-in-snapchat/"><u>[Updated] 2024 Approved Mastering Mobile Screen Recording in Snapchat</u></a></li>
<li><a href="https://video-content-creator.techidaily.com/2024-approved-top-converters-turn-videos-into-live-photos-with-ease/"><u>2024 Approved Top Converters Turn Videos Into Live Photos with Ease</u></a></li>
<li><a href="https://change-location.techidaily.com/pokemon-go-error-12-failed-to-detect-location-on-samsung-galaxy-s24-drfone-by-drfone-virtual-android/"><u>Pokemon Go Error 12 Failed to Detect Location On Samsung Galaxy S24? | Dr.fone</u></a></li>
<li><a href="https://some-guidance.techidaily.com/new-the-ultimate-guide-to-starting-zoom-chats-on-android/"><u>[New] The Ultimate Guide to Starting Zoom Chats on Android</u></a></li>
<li><a href="https://youtube-help.techidaily.com/new-eye-openers-yearly-infographics-on-yts-surprising-stats-17/"><u>[New] Eye-Openers! Yearly Infographics on YT's Surprising Stats ('17)</u></a></li>
<li><a href="https://ai-editing-video.techidaily.com/new-2024-approved-what-is-ai-composite-video-app-and-ai-composite-video-tutorial/"><u>New 2024 Approved What Is AI Composite Video App and AI Composite Video Tutorial</u></a></li>
<li><a href="https://video-content-creator.techidaily.com/updated-no-cost-video-watermarking-solutions-expert-recommendations/"><u>Updated No-Cost Video Watermarking Solutions Expert Recommendations</u></a></li>
<li><a href="https://audio-editing.techidaily.com/updated-2024-approved-the-pinnacle-of-sound-filtration-leading-apps-for-eliminating-background-ruckus/"><u>Updated 2024 Approved The Pinnacle of Sound Filtration Leading Apps for Eliminating Background Ruckus</u></a></li>
<li><a href="https://unlock-android.techidaily.com/tips-and-tricks-for-setting-up-your-vivo-s18e-phone-pattern-lock-by-drfone-android/"><u>Tips and Tricks for Setting Up your Vivo S18e Phone Pattern Lock</u></a></li>
<li><a href="https://facebook-video-recording.techidaily.com/updated-2024-approved-the-cryptic-collection-of-2023-auction-for-anonymity-artifacts/"><u>[Updated] 2024 Approved The Cryptic Collection of 2023 Auction for Anonymity Artifacts</u></a></li>
<li><a href="https://facebook-video-content.techidaily.com/updated-unlocking-the-power-of-cross-social-media-file-transfers-youtube-and-facebook/"><u>[Updated] Unlocking the Power of Cross-Social Media File Transfers (YouTube & Facebook)</u></a></li>
<li><a href="https://video-ai-editor.techidaily.com/new-the-best-free-video-editing-software-for-mp4-files-updated-for-2024/"><u>New The Best Free Video Editing Software for MP4 Files (Updated ) for 2024</u></a></li>
</ul></div>
|
"use client";
import { useState, useEffect, KeyboardEvent } from "react";
import { RatingProps } from "./Rating.props";
import styles from "./Rating.module.css";
import cn from "classnames";
import StarIcon from "./star.svg";
export const Rating = ({
isEditable = false,
rating,
setRating,
...props
}: RatingProps): JSX.Element => {
const [ratingArray, setRatingArray] = useState<JSX.Element[]>(
new Array(5).fill(<></>)
);
useEffect(() => {
constructRating(rating);
}, [rating]);
const constructRating = (currentRating: number) => {
const updatedArray = ratingArray.map(
(ratingElem: JSX.Element, i: number) => {
return (
<span
key={i}
className={cn(styles.star, {
[styles.filled]: i < currentRating,
[styles.editable]: isEditable,
})}
onMouseEnter={() => changeDisplay(i + 1)}
onMouseLeave={() => changeDisplay(rating)}
onClick={() => onClick(i + 1)}
>
<StarIcon
tabIndex={isEditable ? 0 : -1}
onKeyDown={(e: KeyboardEvent<SVGElement>) =>
isEditable && handleSpace(i + 1, e)
}
/>
</span>
);
}
);
setRatingArray(updatedArray);
};
const changeDisplay = (item: number) => {
if (!isEditable) {
return;
}
constructRating(item);
};
const onClick = (item: number) => {
if (!isEditable || !setRating) {
return;
}
setRating(item);
};
const handleSpace = (item: number, e: KeyboardEvent<SVGElement>) => {
if (e.code !== "Space" || !setRating) {
return;
}
setRating(item);
};
return (
<div {...props}>
{ratingArray.map((ratingElem: JSX.Element, i: number) => (
<span key={i}>{ratingElem}</span>
))}
</div>
);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.