text
stringlengths
184
4.48M
 using Application.DAL.Helper; using Core.Interfaces; using Core.Services; using Data.Contexts; using Data.Repos; using Data.Repos.DiscountRepo; using Data.Repos.OrderRepo; using Data.Repos.ProductRepo; using Data.SeedData; using Data.UnitOfWork; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Models.ResponseModels; using Models.Settings; using Newtonsoft.Json; using Services.AccountServices; using Services.Concrete; using Services.Interfaces; using System.Text; using WebApi.Helpers; using WebApi.Udapters; using static Org.BouncyCastle.Math.EC.ECCurve; namespace Application.Api.Extentions { public static class ApplicationExtentions { public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration configuration) { services.Configure<CloudinarySettings>(configuration.GetSection("CloudinarySettings")); services.Configure<MailSettings>(configuration.GetSection("MailSettings")); services.AddTransient<IEmailCoreService, EmailCoreService>(); services.AddScoped<IUnitOfWork, UnitOfWork>(); services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>)); services.AddTransient<IDbContext, ApplicationDbContext>(); services.AddScoped<IAccountServices, AccountServices>(); services.AddScoped<ICategoryService, CategoryService>(); services.AddScoped<ISupplierService, SupplierService>(); services.AddScoped<IProductService, ProductService>(); services.AddAutoMapper(typeof(MappingProfile)); services.AddScoped<IUploadPhotoService, UploadFileService>(); services.AddScoped<IUploadPhotoCoreService, UploadPhotoCoreService>(); services.AddScoped<IOrderService, OrderService>(); services.AddScoped<ITransactionService, TransactionService>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<ICartService, CartService>(); services.AddScoped<IReviewService, ReviewService>(); services.AddScoped<RoleManager<IdentityRole>>(); var jwt = new JWTSettings(); configuration.GetSection(nameof(JWTSettings)).Bind(jwt); services.AddScoped<IDiscountService, DiscountService>(); services.AddScoped<DiscountStatusUpdater>(); services.AddSingleton<IVnPayService, VnpayService>(); services.AddScoped<IReportService, ReportService>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)), ValidIssuer = jwt.Issuer, ValidAudience = jwt.Audience }; options.Events = new JwtBearerEvents() { OnChallenge = context => { context.HandleResponse(); context.Response.StatusCode = 401; context.Response.ContentType = "application/json"; var result = JsonConvert.SerializeObject(new BaseResponse<string>("You are not Authorized")); return context.Response.WriteAsync(result); }, OnForbidden = context => { context.Response.StatusCode = 403; context.Response.ContentType = "application/json"; var result = JsonConvert.SerializeObject(new BaseResponse<string>("You are not authorized to access this resource")); return context.Response.WriteAsync(result); }, }; }); services.AddSwaggerGen(options => { options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Scheme = "Bearer", BearerFormat = "JWT", In = ParameterLocation.Header, Name = "Authorization", Description = "Bearer Authentication with JWT Token", Type = SecuritySchemeType.Http }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, new List<string>() } }); }); return services; } } }
package HeimaLesson6.Oop.FilmSample; import java.util.Scanner; /* 设计一个电影系统: 1.创建一个电影对象实体类; 2.创建一个电影操作对象类; 3.准备全部电影信息 * */ public class FilmSample { public static void main(String[] args) { Film[] films = new Film[4]; Film m1 = new Film(1,"水门桥",38.9,9.8,"徐克","吴京","12万人想看"); Film m2 = new Film(2,"出拳吧",39,7.8,"唐晓白","田雨","3.5万人想看"); Film m3 = new Film(3,"月球陨落",42,7.9,"罗兰","贝瑞","17.9万人想看"); Film m4 = new Film(4,"一点就到家",35,8.7,"许宏宇","刘昊然","18.8万人想看"); films[0] = m1; films[1] = m2; films[2] = m3; films[3] = m4; FilmOperator filmoperator = new FilmOperator(films); Scanner sc = new Scanner(System.in); while (true) { System.out.println("===电影信息系统==="); System.out.println("输入数字1:查询全部电影信息"); System.out.println("输入数字2:根据编号查询电影信息"); int order = sc.nextInt(); switch (order){ case 1: filmoperator.PrintAllFilms(); break; case 2: System.out.println("请输入电影编号:"); filmoperator.SearchFilm(sc.nextInt()); break; default: System.out.println("您输入的指令有误!"); } } } }
import React, { useEffect, useState } from 'react'; import CustomerTable from './CustomerTable'; import AppsContainer from '../../../@crema/core/AppsContainer'; import { useIntl } from 'react-intl'; import { useDispatch, useSelector } from 'react-redux'; import { getCustomers } from '../../../redux/actions'; import AppsHeader from '../../../@crema/core/AppsContainer/AppsHeader'; import AppsContent from '../../../@crema/core/AppsContainer/AppsContent'; import AppsPagination from '../../../@crema/core/AppsPagination'; import AppInfoView from '../../../@crema/core/AppInfoView'; import { Input, Button, Modal } from 'antd'; import './index.style.less'; import AppPageMetadata from '../../../@crema/core/AppPageMetadata'; import EditCustomer from './EditCustomer'; const Customers = () => { const { messages } = useIntl(); const dispatch = useDispatch(); const { customers, customerCount } = useSelector(({ ecommerce }) => ecommerce); const { loading } = useSelector(({ common }) => common); const [page, setPage] = useState(0); const [search, setSearchQuery] = useState(''); const [isModalVisible, setIsModalVisible] = useState(false); const onChange = (page) => { setPage(page); }; useEffect(() => { dispatch(getCustomers(search, page)); }, [dispatch, search, page]); const onSearchOrder = (e) => { setSearchQuery(e.target.value); setPage(0); }; const showModal = () => { setIsModalVisible(true); }; const handleOk = () => { setIsModalVisible(false); }; const handleCancel = () => { setIsModalVisible(false); }; return ( <> <AppPageMetadata title="Customers" /> <AppsContainer title={messages['sidebar.ecommerce.customers']} fullView type="bottom"> <AppsHeader key={'wrap'}> <div className="customer-header"> <div className="customer-header-input-view"> <Input id="user-name" placeholder="Search" type="search" onChange={onSearchOrder} /> </div> <div className="customer-header-right"> <Button type="primary" onClick={showModal}> Add Customer </Button> <AppsPagination className="customer-header-pagination" pageSize={10} count={customerCount} page={page} onChange={onChange} /> </div> </div> </AppsHeader> <AppsContent key={'wrap1'} style={{ paddingTop: 10, paddingBottom: 10, }} > <CustomerTable loading={loading} customers={customers} /> </AppsContent> <AppsPagination key={'wrap2'} className="customer-footer-pagination" pageSize={10} count={customerCount} page={page} onChange={onChange} /> </AppsContainer> <Modal title={messages['ecommerce.addCustomer']} visible={isModalVisible} onOk={handleOk} footer={false} onCancel={handleCancel}> <EditCustomer /> </Modal> <AppInfoView /> </> ); }; export default Customers;
import * as Yup from 'yup'; export interface IProduct { id: string, name: string, price: number, original_price: number, description: string, images:{ base_url: string }[], brand: { id: number, name: string, slug: string }, specifications: ISpecification[] } export interface IUser { id: string, name: string, email: string, role: string, password: string, } export interface ISpecification { name: string, attributes: { code: string, name: string, value: string } } export const SignupSchema = Yup.object({ firstName: Yup.string().required("First name is required"), role: Yup.string().required("role is required"), email: Yup.string().email("Invalid email").required("Email is required"), password: Yup.string().min(6).required("Password is required"), confirmPassword: Yup.string().oneOf([Yup.ref("password")], "Passwords must match"), }) export type SignupForm = Yup.InferType<typeof SignupSchema> export const SigninSchema = Yup.object({ email: Yup.string().email("Invalid email").required("Email is required"), password: Yup.string().min(6).required("Password is required"), }) export type SigninForm = Yup.InferType<typeof SigninSchema> export const updateSchema = Yup.object({ name: Yup.string().required("First name is required"), price: Yup.number().required("Email is required"), original_price: Yup.number().required("Email is required"), description: Yup.string().min(6,"Tối thiểu 10 ký tự").required("Password is required"), }) export type updateForm = Yup.InferType<typeof updateSchema>
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; using System; using System.Threading.Tasks; using TrojWebApp.Models; using TrojWebApp.Services; namespace TrojWebApp.Controllers { [Authorize] public class ClientFundingsController : IdenityController { private readonly CasesConnection _caseConnection; public ClientFundingsController(TrojContext context, IConfiguration configuration, UserManager<IdentityUser> userManager) : base(userManager) { _caseConnection = new CasesConnection(context, configuration["CryKey"]); } // GET: ClientFundingsController public async Task<ActionResult> Index(int? id) { if (id == null) return NoContent(); CasesViewModel currentCase = await _caseConnection.GetCase(id.Value); if (currentCase == null) return NoContent(); ViewBag.CaseId = currentCase.CaseId.ToString(); ViewBag.CaseLinkText = currentCase.CaseType + "/" + currentCase.CaseId.ToString(); ViewBag.Client = currentCase.FirstName + " " + currentCase.LastName; ViewBag.PersonId = currentCase.PersonId.ToString(); string currentDate = DateTime.Now.ToShortDateString(); ViewBag.CurrentDate = currentDate; TotalSumModel totalSumModel = await _caseConnection.GetTotalSum(id.Value); ViewBag.TotalSum = totalSumModel.TotalSum; var clientFundings = await _caseConnection.GetClientFunding(id.Value); return View(clientFundings); } // POST: ClientFundingsController/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create(IFormCollection collection) { if (!collection.TryGetValue("CaseId", out StringValues caseId)) return NoContent(); if (!collection.TryGetValue("ClientSum", out StringValues clientSum)) return NoContent(); if (!collection.TryGetValue("Comment", out StringValues comment)) return NoContent(); if (!collection.TryGetValue("ClientFundDate", out StringValues clientFundDate)) return NoContent(); DateTime inputClientFundDate = DateTime.Now; if (clientFundDate != "") inputClientFundDate = DateTime.Parse(clientFundDate); ClientFundingsModel clientFunding = await _caseConnection.CreateClientFund(Int32.Parse(caseId.ToString()), double.Parse(clientSum.ToString()), inputClientFundDate, comment.ToString(), UserName); if (clientFunding == null) return NoContent(); return RedirectToAction("Index", new { id = clientFunding.CaseId }); } // GET: ClientFundingsController/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: ClientFundingsController/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: ClientFundingsController/Delete/5 public async Task<ActionResult> Delete(int id, int caseId) { var response = await _caseConnection.DeleteClientFunding(id); if (response == 0) return NoContent(); return RedirectToAction("Index", new { id = caseId }); } } }
package ch.kleis.lcaac.core.lang.value import ch.kleis.lcaac.core.lang.expression.EQuantityScale import ch.kleis.lcaac.core.lang.expression.EStringLiteral sealed interface DataValue<Q> : Value<Q> data class StringValue<Q>(val s: String) : DataValue<Q> { override fun toString(): String { return s } fun toEStringLiteral(): EStringLiteral<Q> = EStringLiteral(s) } data class QuantityValue<Q>(val amount: Q, val unit: UnitValue<Q>) : DataValue<Q> { override fun toString(): String { return "$amount ${unit.symbol}" } fun toEQuantityScale(): EQuantityScale<Q> = EQuantityScale(amount, unit.toEUnitLiteral()) } data class RecordValue<Q>(val entries: Map<String, DataValue<Q>>) : DataValue<Q> { override fun toString(): String { return entries.toString() } }
import React, { useState, useEffect } from 'react'; import GraphiQL from 'graphiql'; import 'graphiql/graphiql.css'; import CustomToolbar from './CustomToolbar'; import GraphiQLExplorer from 'graphiql-explorer'; import { graphQLFetcher } from '../utils/fetcher'; import { getIntrospectionQuery, buildClientSchema } from 'graphql'; function GraphiQLWrapper() { const [schema, setSchema] = useState(null); const [query, setQuery] = useState(''); const [variables, setVariables] = useState('{}'); // State for variables const [explorerIsOpen, setExplorerIsOpen] = useState(true); useEffect(() => { async function fetchSchema() { const response = await graphQLFetcher({ query: getIntrospectionQuery() }); const schema = buildClientSchema(response.data); setSchema(schema); } fetchSchema(); }, []); const handleEditQuery = (query) => { setQuery(query); }; const handleEditVariables = (event) => { setVariables(event.target.value); }; const handleExplorerEdit = (queryString) => { setQuery(queryString); }; return ( <div className="graphiql-container" style={{ display: 'flex', height: '100vh' }}> {schema && ( <GraphiQLExplorer schema={schema} query={query} onEdit={handleExplorerEdit} explorerIsOpen={explorerIsOpen} onToggleExplorer={() => setExplorerIsOpen(!explorerIsOpen)} /> )} <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}> <GraphiQL fetcher={graphQLFetcher} schema={schema} query={query} onEditQuery={handleEditQuery} variables={variables} toolbar={<CustomToolbar/> } /> <textarea style={{ flex: '0 0 200px', marginTop: '10px', padding: '10px' }} placeholder="Enter query variables as JSON" value={variables} onChange={handleEditVariables} /> </div> </div> ); } export default GraphiQLWrapper;
import React, { useEffect } from "react"; import { useSelector } from "react-redux"; import { Link, useNavigate } from "react-router-dom"; import MetaData from "../Layout/MetaData"; import Loader from "../Layout/Loader/Loader"; import "./css/Profile.css"; const Profile = () => { const navigate = useNavigate(); const { user, loading, isAuthenticated } = useSelector( (state) => state.userReducer, ); useEffect(() => { if (!isAuthenticated) { navigate("/login"); } }, [isAuthenticated, navigate]); return ( <> {loading ? ( <Loader /> ) : ( <> <MetaData title={`${ user?.name?.charAt(0).toUpperCase() + user?.name?.slice(1) }'s Profile`} /> <div className="profileContainer"> <div> <h1>My Profile</h1> <img src={user?.avatar?.url} alt={user.name} /> <Link to="/me/update">Edit Profile</Link> </div> <div> <div> <h4>Full Name</h4> <p>{user.name}</p> </div> <div> <h4>Email</h4> <p>{user.email}</p> </div> <div> <h4>Joined On</h4> <p>{String(user.createdAt).substr(0, 10)}</p> </div> <div> <Link to="/orders">My Orders</Link> <Link to="/password/update">Change Password</Link> </div> </div> </div> </> )} </> ); }; export default Profile;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flex</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="menu-container"> <div class="menu"> <div class="date">May 22, 2023</div> <!-- <div class="links"> --> <div class="signup">Sign Up</div> <div class="login">Login</div> <!-- </div> --> </div> </div> <div class="header-container"> <div class="header"> <div class="subscribe">Subscribe &#9662;</div> <div class="logo"><img src="./flexbox-images-449705/images/awesome-logo.svg"></div> <div class="social"><img src="./flexbox-images-449705/images/social-icons.svg"></div> </div> </div> <div class="photo-grid-container"> <div class="photo-grid"> <div class="photo-grid-item first-item"> <img src="./flexbox-images-449705/images/one.svg"> </div> <div class="photo-grid-item"> <img src="./flexbox-images-449705/images/two.svg"> </div> <div class="photo-grid-item"> <img src="./flexbox-images-449705/images/three.svg"> </div> <div class="photo-grid-item"> <img src="./flexbox-images-449705/images/four.svg" alt=""> </div> <div class="photo-grid-item last-item"> <img src="./flexbox-images-449705/images/five.svg" alt=""> </div> </div> </div> <div class="footer"> <div class="footer-item footer-one"></div> <div class="footer-item footer-two"></div> <div class="footer-item footer-three"></div> </div> </body> </html>
package com.example.to_docompose.ui.screens.list import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Search import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MediumTopAppBar import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue 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.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.to_docompose.R import com.example.to_docompose.components.PriorityItem import com.example.to_docompose.data.models.Priority import com.example.to_docompose.ui.theme.SEARCH_TOP_BAR_HIGH import com.example.to_docompose.ui.viewmodels.SharedVieModel import com.example.to_docompose.utils.SearchAppBarState import com.example.to_docompose.utils.TrailingIconState @OptIn(ExperimentalMaterial3Api::class) @Composable fun ListAppTopBar( sharedVieModel: SharedVieModel, searchAppBarState: SearchAppBarState, searchTextState: String, scrollBehavior: TopAppBarScrollBehavior ) { when(searchAppBarState){ SearchAppBarState.CLOSED ->{ DefaultListAppTopBar( onSearchClicked = { sharedVieModel.searchAppBarState.value = SearchAppBarState.OPENED }, onSortClicked = {}, onDeleteClicked = {}, scrollBehavior = scrollBehavior ) } else -> { SearchAppBar( text = searchTextState , onTextChange = {newSearchQuery -> sharedVieModel.searchTextState.value = newSearchQuery }, onSearchClicked = {}, onCloseClicked = { sharedVieModel.searchAppBarState.value = SearchAppBarState.CLOSED sharedVieModel.searchTextState.value = "" } ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DefaultListAppTopBar( onSearchClicked: () -> Unit, onSortClicked: (Priority) -> Unit, onDeleteClicked: () -> Unit, scrollBehavior: TopAppBarScrollBehavior ) { MediumTopAppBar( title = { Text( text = stringResource(R.string.list_screen_title), color = MaterialTheme.colorScheme.onBackground ) }, actions = { ListAppBarAction( onSearchClicked = onSearchClicked, onSortClicked = onSortClicked, onDeleteClicked = onDeleteClicked ) }, scrollBehavior = scrollBehavior ) } @Composable fun ListAppBarAction( onSearchClicked: () -> Unit, onSortClicked: (Priority) -> Unit, onDeleteClicked: () -> Unit ) { SearchAction(onSearchClicked = onSearchClicked) SortAction(onSortClicked = onSortClicked) DeleteAllItems(onDeleteClicked = onDeleteClicked) } @Composable fun SearchAction( onSearchClicked: () -> Unit ) { IconButton( onClick = { onSearchClicked() } ) { Icon( imageVector = Icons.Filled.Search, contentDescription = stringResource(R.string.search_action), tint = MaterialTheme.colorScheme.onBackground ) } } @Composable fun SortAction( onSortClicked: (Priority) -> Unit ) { var expended by remember { mutableStateOf(false) } IconButton(onClick = { expended = true }) { Icon( painter = painterResource(id = R.drawable.ic_filter), contentDescription = stringResource(R.string.sort_tasks), tint = MaterialTheme.colorScheme.onBackground ) DropdownMenu( modifier = Modifier .background(MaterialTheme.colorScheme.inverseOnSurface), expanded = expended, onDismissRequest = { expended = false } ) { DropdownMenuItem( text = { PriorityItem(priority = Priority.LOW) }, onClick = { onSortClicked(Priority.LOW) expended = false } ) DropdownMenuItem( text = { PriorityItem(priority = Priority.MEDIUM) }, onClick = { onSortClicked(Priority.MEDIUM) expended = false } ) DropdownMenuItem( text = { PriorityItem(priority = Priority.HIGH) }, onClick = { onSortClicked(Priority.HIGH) expended = false } ) DropdownMenuItem( text = { PriorityItem(priority = Priority.NONE) }, onClick = { onSortClicked(Priority.NONE) expended = false } ) } } } @Composable fun DeleteAllItems( onDeleteClicked: () -> Unit ) { var expended by remember { mutableStateOf(false) } IconButton(onClick = { expended = true }) { Icon( imageVector = Icons.Filled.MoreVert, contentDescription = stringResource(R.string.sort_tasks), tint = MaterialTheme.colorScheme.onBackground ) DropdownMenu( modifier = Modifier .background(MaterialTheme.colorScheme.inverseOnSurface), expanded = expended, onDismissRequest = { expended = false } ) { DropdownMenuItem( text = { Text( text = stringResource(R.string.delete_tasks), color = MaterialTheme.colorScheme.onSecondaryContainer ) }, onClick = { expended = false onDeleteClicked() }) } } } @Composable fun SearchAppBar( text: String, onTextChange: (text: String) -> Unit, onSearchClicked: (searchQuery: String) -> Unit, onCloseClicked: () -> Unit ){ var trailingIconState by remember { mutableStateOf(TrailingIconState.READY_TO_DELETE) } Surface( modifier = Modifier .fillMaxWidth() .height(SEARCH_TOP_BAR_HIGH), color = MaterialTheme.colorScheme.surface ) { TextField( modifier = Modifier .fillMaxWidth(), value = text, onValueChange = {newText -> onTextChange(newText) }, placeholder = { Text( modifier = Modifier .alpha(0.5f), text = stringResource(R.string.search_placeholder), color = MaterialTheme.colorScheme.onBackground ) }, textStyle = MaterialTheme.typography.bodyLarge, singleLine = true, leadingIcon = { IconButton(onClick = { /*TODO*/ }) { Icon( modifier = Modifier .alpha(0.38f), imageVector = Icons.Filled.Search, contentDescription = stringResource(R.string.search_icon), tint = MaterialTheme.colorScheme.onBackground ) } }, trailingIcon = { IconButton(onClick = { when(trailingIconState){ TrailingIconState.READY_TO_DELETE ->{ if (text.isEmpty()){ onCloseClicked() }else{ onTextChange("") trailingIconState = TrailingIconState.READY_TO_CLOSE } } TrailingIconState.READY_TO_CLOSE ->{ if (text.isNotEmpty()){ onTextChange("") }else{ onCloseClicked() trailingIconState = TrailingIconState.READY_TO_DELETE } } } }) { Icon( modifier = Modifier .alpha(0.78f), imageVector = Icons.Filled.Close, contentDescription = stringResource(R.string.close_icon), tint = MaterialTheme.colorScheme.onBackground ) } }, colors = TextFieldDefaults.colors( focusedContainerColor = Color.Transparent, unfocusedContainerColor = Color.Transparent, cursorColor = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.8f), focusedIndicatorColor = Color.Transparent, disabledIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, focusedTextColor = MaterialTheme.colorScheme.onBackground, unfocusedTextColor = MaterialTheme.colorScheme.onBackground ), keyboardOptions = KeyboardOptions( imeAction = ImeAction.Search ), keyboardActions = KeyboardActions( onSearch = { onSearchClicked(text) } ) ) } } /* @Preview @Composable fun DefaultListAppTopBarPreview() { DefaultListAppTopBar( onSearchClicked = {}, onSortClicked = {}, onDeleteClicked = {}, scrollBehavior = {} ) } */ @Preview @Composable fun SearchAppBArPreview(){ SearchAppBar( text = "" , onTextChange = {}, onSearchClicked = { }, onCloseClicked = {} ) }
<div class="list-group-item list-group-item-action mt-2 mb-2 rounded-3"> <div class="row d-flex w-100 justify-content-between mt-2 mb-2"> <div class="col-md"> <%= recipe_tile_image(current_user, recipe) %> </div> <div class="col text-left"> <h5><%= recipe.title %></h5> <%= recipe_badges(recipe) %> <br/> <%= recipe_tags(recipe) %> <div class="mt-4"><%= recipe.brief_info %></div> </div> <div class="col-auto"> <div class="row text-right"> <small> <%= time_ago_in_words recipe.created_at %> ago | <%= link_to recipe.user.email, user_path(recipe.user), target: "_top" %> <%= recipe_likes_count_badge(recipe) %> <%= recipe_cooked_badge(current_user, recipe) %> </small> </div> <div class="row mt-md-5 text-right"> <%= link_to recipe, class: "col-auto btn btn-primary me-1 mt-0" do %> <i class="fa-solid fa-info mx-2"></i> <% end %> <% if user_signed_in? and recipe.user == current_user %> <%= link_to edit_recipe_path(recipe), class: "col-auto btn btn-warning me-1" do %> <i class="fa-solid fa-pen"></i> <% end %> <%= link_to recipe, data: { turbo_method: :delete, turbo_confirm: "Are you sure?" }, class: "col-auto btn btn-danger" do %> <i class="fa-solid fa-trash-can"></i> <% end %> <% end %> </div> </div> </div> </div>
package com.kotlinenjoyers.trackiteasy.ui.common import android.content.res.Configuration import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.WifiOff import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp import com.kotlinenjoyers.trackiteasy.util.ConnectivityObserver @OptIn(ExperimentalMaterial3Api::class) @Composable fun MenuTopBar( modifier: Modifier = Modifier, title: String, navBack: () -> Unit, networkStatus: ConnectivityObserver.Status? = null, scrollBehavior: TopAppBarScrollBehavior? = if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE) TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) else null, ) { CenterAlignedTopAppBar( modifier = modifier, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text(title) }, scrollBehavior = scrollBehavior, navigationIcon = { IconButton(onClick = navBack) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null ) } }, actions = { if (networkStatus != null && networkStatus != ConnectivityObserver.Status.Available) Icon( modifier = modifier .padding(end = 8.dp) .size(36.dp), imageVector = Icons.Filled.WifiOff, contentDescription = null, tint = MaterialTheme.colorScheme.error, ) } ) }
#include "person.h" #ifndef Zombie_H #define Zombie_H using std:: string; class Zombie : public Person{ protected: int x;// Ava - testing int y;// Ava - testing public: //Base Constructor Zombie() : Person() {} //Augmented Constructor Zombie(int spd, int xpos, int infecRate, string _name) : Person(spd, xpos,infecRate, _name){} //takes in a populated map then uses it to check to see if there are the //non-Zombie Persons in the spaces on or around the Zombie to perform it's action //then returns a Pointer to the Person subclass object that will get effected Person* checkProximity(map<int,vector<Person*>> _intcity); //checks against a % chance //if succeeds the corresponding subclass conversions will take place //if fails will end the action void action(map<int,vector<Person*>>& _intcity,map<string,vector<Person*>>&_city);//bite //void move();//changed for speed void location(); /* ava testing; I want this to be used for understanding where a person is in what part of the city ┏ ┓ | B | ┏ ┗ ┛ ┓ ┏ ┓ ┏ ┓ ┏ ┓ | D | | A | | E | ┗ ┛ ┗ ┛ ┗ ┛ ┗ ┏ ┓ ┛ | C | ┗ ┛ CHEAT CODE: UP DOWN LEFT RIGHT so each box to start will be 10 by 10 if in the middle you can go to any spot if on the sides you can only go to three the map will be in the positive quadtrant to prevent negative numbers A: 1-100 == (rand()% 100)+1 B: 101-200 C: 201-300 D: 301-400 E: 401-500 ex: if (x < 100){ ABCDE available } if (x >= 201 && >= 300){ ADE available } things to note: A is always available 1. spawn x rand()%500 if (x < 100){ 2. x = (rand()% 100)+1 1-100 3. num = (rand()%5)+1 (1-5) 4. if in section n, then in section n } 1. spawn x rand()%500 2. x = 350 3. x = rand()%100; Note: if x = A = num = 1,2,3,4,5 missing: if x = B = num = 1,2,4,5 3 if x = C = num = 1,3,4,5 2 if x = D = num = 1,2,3,4 5 if x = E = num = 1,2,3,5 4 */ }; #endif
namespace HuffmanCoding.UnitTests; public class HuffmanFrequencyTableBuilderTests { [Fact] public void WithMaxNGramLength_ShouldSetMaxNGramLength() { // Arrange var builder = new HuffmanFrequencyTableBuilder(); // Act var result = builder.WithMaxNGramLength(3); // Assert result.Should().BeOfType<HuffmanFrequencyTableBuilder>(); } [Fact] public void WithSequences_ShouldSetSequences() { // Arrange var builder = new HuffmanFrequencyTableBuilder(); var sequences = new List<string> { "abc", "def" }; // Act var result = builder.WithSequences(sequences); // Assert result.Should().BeOfType<HuffmanFrequencyTableBuilder>(); } [Fact] public void WithLengthWeight_ShouldSetLengthWeight() { // Arrange var builder = new HuffmanFrequencyTableBuilder(); // Act var result = builder.WithLengthWeight(0.5); // Assert result.Should().BeOfType<HuffmanFrequencyTableBuilder>(); } [Fact] public void WithEndOfSequenceCharacter_ShouldSetEndOfSequenceCharacter() { // Arrange var builder = new HuffmanFrequencyTableBuilder(); // Act var result = builder.WithEndOfSequenceCharacter("e"); // Assert result.Should().BeOfType<HuffmanFrequencyTableBuilder>(); } [Fact] public void Build_ShouldReturnHuffmanFrequencyTable() { // Arrange var builder = new HuffmanFrequencyTableBuilder() .WithMaxNGramLength(3) .WithSequences(new List<string> { "abc", "def" }); // Act var result = builder.Build(); // Assert result.Should().BeOfType<HuffmanFrequencyTable>(); } [Fact] public void Build_ShouldCalculateCorrectFrequencies() { // Arrange var builder = new HuffmanFrequencyTableBuilder() .WithMaxNGramLength(3) .WithSequences(new List<string> { "abc", "abc", "def" }); // Act var result = builder.Build(); // Assert result["abc"].Should().Be(2); result["def"].Should().Be(1); } }
const SEVEN = 7; const MAX = "9876543201"; function featured(featuredNum) { if(featuredNum >= MAX) { return console.log("There is no possible number that fulfills those requirements."); } while(true) { featuredNum = getDivisibleSeven(featuredNum); if(!containsDuplicates(featuredNum)) { break; } } console.log(featuredNum); } function getDivisibleSeven(num) { if(num % SEVEN === 0 && num % 2 > 0) { return num + (SEVEN * 2); } else if (num % SEVEN === 0) { return num + SEVEN; } else { return num + (SEVEN - (num % SEVEN)); } // return num % SEVEN !== 0 ? num + (SEVEN - (num % SEVEN)) : num + SEVEN; } function containsDuplicates(num) { let arr = String(num).split("").sort((a, b) => a - b); for (let idx = 0; idx < arr.length - 1; idx += 1) { if(arr[idx] === arr[idx + 1]) { return true; } } return false; } featured(12); // 21 featured(20); // 21 featured(21); // 35 featured(997); // 1029 featured(1029); // 1043 featured(999999); // 1023547 featured(999999987); // 1023456987 featured(9876543186); // 9876543201 featured(9876543200); // 9876543201 featured(9876543201); // "There is no possible number that fulfills those requirements." /* input: integer output: next featured number greater than the integer. A featured number is: - an odd number - divisible evenly by 7 - with each digit occuring exactly once If it meetss the first two requirements, we can check if each digit is occuring exactly once with: copy and sort the arr, start the index one lower to avoid throwing an exception/undefined check if index 1 = index 2, if true, return contains duplicates. otherwise, increment the number by 7, repeat, until we find a new featured number and return that. make an array starring every digit. Might be able to use a filter to check. */
<?php /** * @file * Install, update and uninstall functions for the hello module. */ use Drupal\Core\Database\Database; /** * Implements hook_schema(). */ function hello_schema() { $schema['hello_node_history'] = array( 'description' => 'Stores node update history.', 'fields' => array( 'hid' => array( 'description' => 'Primary Key: Unique history ID.', 'type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE, ), 'nid' => array( 'description' => 'Node ID.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, ), 'uid' => array( 'description' => 'User ID.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, ), 'update_time' => array( 'description' => 'Timestamp of node update.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, ), ), 'primary key' => array('hid'), 'indexes' => array('nid' => array('nid')), ); return $schema; } /** * Implements hook_update_N(). */ /** * Add a 'uid' field to the hello_node_history table. */ function hello_update_8100() { $field_spec = array( 'type' => 'int', 'description' => "Store user ID.", 'unsigned' => TRUE, 'not null' => TRUE, ); $schema = Database::getConnection()->schema(); $schema->addField('hello_node_history', 'uid', $field_spec); }
# Feature: Manage posts # In order to [goal] # [stakeholder] # wants [behaviour] # # Scenario: Register new post # Given I am on the new post page # When I fill in "Title" with "title 1" # And I press "Create" # Then I should see "title 1" # # # Rails generates Delete links that use Javascript to pop up a confirmation # # dialog and then do a HTTP POST request (emulated DELETE request). # # # # Capybara must use Culerity/Celerity or Selenium2 (webdriver) when pages rely # # on Javascript events. Only Culerity/Celerity supports clicking on confirmation # # dialogs. # # # # Since Culerity/Celerity and Selenium2 has some overhead, Cucumber-Rails will # # detect the presence of Javascript behind Delete links and issue a DELETE request # # instead of a GET request. # # # # You can turn this emulation off by tagging your scenario with @no-js-emulation. # # Turning on browser testing with @selenium, @culerity, @celerity or @javascript # # will also turn off the emulation. (See the Capybara documentation for # # details about those tags). If any of the browser tags are present, Cucumber-Rails # # will also turn off transactions and clean the database with DatabaseCleaner # # after the scenario has finished. This is to prevent data from leaking into # # the next scenario. # # # # Another way to avoid Cucumber-Rails' javascript emulation without using any # # of the tags above is to modify your views to use <button> instead. You can # # see how in http://github.com/jnicklas/capybara/issues#issue/12 # # # Scenario: Delete post # Given the following posts: # |title| # |title 1| # |title 2| # |title 3| # |title 4| # When I delete the 3rd post # Then I should see the following posts: # |Title| # |title 1| # |title 2| # |title 4|
\input{base.tex} \begin{document} \title{Visual illusions and interactions in biologically inspired neural networks. Analyzing perception of tilt} \author{Martin Andreev Asenov} % to choose your course % please un-comment just one of the following \course{Artificial Intelligence and Computer Science} %\course{Artificial Intelligence and Software Engineering} %\course{Artificial Intelligence and Mathematics} %\course{Artificial Intelligence and Psychology } %\course{Artificial Intelligence with Psychology } %\course{Linguistics and Artificial Intelligence} %\course{Computer Science} %\course{Software Engineering} %\course{Computer Science and Electronics} %\course{Electronics and Software Engineering} %\course{Computer Science and Mathematics} %\course{Computer Science and Physics} %\course{Computer Science and Statistics} % to choose your report type % please un-comment just one of the following %\project{Undergraduate Dissertation} % CS&E, E&SE, AI&L %\project{Undergraduate Thesis} % AI%Psy \project{4th Year Project Report} \date{\today} \abstract{ We experience different tilt illusions and pop out effects. This is often explained by the line's representation in the visual cortex. A group of neurons is responsible for detecting different orientations in different parts of our visual field. A neuron tuned for a specific orientation spikes more, when its preferred orientation is presented, and less the more different the orientations is, forming a bell shaped curve of activity. We have multiple neurons for every part of our visual field, tuned for different orientations. Combining their responses we get an accurate response of the actual orientation, despite their noisy spiking. However neurons responsible for different part of our visual field are also connected to each other. This modulation explains some of the effect we are experiencing, as orientations in our visual fields are influenced by nearby ones. However those interaction have only been explored statically, calculating the modulation only once. In a full dynamic a change in an orientation, can lead to a change in another orientation, and so on. It's unclear if existing models change in a dynamic setting, does the system settles down to a stable state, or it keeps fluctuating. In this report, we explore an already existing static model of the above mentioned neurons and build a dynamic model. We explore the differences between the two to check if in a dynamic setting, we still experience the same effects. } \maketitle \section*{Acknowledgements} Acknowledgements go here. \tableofcontents \listoffigures %\listoftables %\pagenumbering{arabic} \chapter{Introduction} In processing visual information, our brain seems to favor continuity and prioritize the greater whole, rather than individual details. Sometimes this ability serves us well, ex. when trying to find a pattern among random noise, or a discontinuity in a certain pattern (fig.\ref{popout}). However in other cases this leads to various illusions (fig.\ref{illusion1}, fig.\ref{illusion2}). The project aims to explore the relevance of V1 and its orientation selectivity neurons in the context of those effects. Fig.\ref{illusion1} and Fig.\ref{popout} are particularly relevant to this project. This paper develops a model, based and built upon the one described in the recent elastica paper \cite{keemink2015unified}. The elastica principle defines the strength of the connections between different orientation selective neurons. It favours continuity, the smoother too bars are connected to each other, the stronger the modulation connection between them. Although there are other models explaining similar phenomena, illusions and effects separately, the neural model described claims to have all of those properties, unifying them in one model. However all the results in the paper were obtained by neurons getting a passive input based on the orientations in an image. We extend the model so neurons are directly connected to each other. As mentioned in \cite{keemink2015unified} in further development, adding dynamics to some of the already presented illusions could lead to some interesting behavior. The details of the illusions might depend on the static nature of the original model, and it is crucial that we understand how they come to be in a dynamical mode. We build a recurrent neural network of the orientation selective neurons in the V1 cortex. We set the strength of the connections between them (weights in the network), based on the elastica principle. We perform baseline experiments with the static model and compare the results in full dynamic setting. The different parts of the project are discussed below in the report. \begin{itemize} \item Background - gives some necessary neuroscience terminology and information about the problem and concepts we are going to use. We also briefly discuss recurrent neural networks, as they are the model used for simulating experiments. \item Design - discuss the design of the experiments and the evolution of the model, before the final version used for running experiments. \item Implementation - choice of programming languages and libraries, why they are important to the project and how they influence both the speed and ease of running experiments, but also the workflow of conducting research. \item Experiments - in depth description of experiments ran \item Evaluation - comparing the results gathered from experiments \item Timeline - timeline of the work done through the project. \item Conclusions - final conclusions \end{itemize} \plotfigure{illusion1}{The orientations of the small circles inside seem tilted \cite{baggott2010investigating}}{Tilt illusion} \plotfigureS{illusion2}{The lines do not seem parallel, when it reality they are \cite{vision-computation}}{Parallel illusion}{.5} \plotfigureS{popout}{The central bar is easily detected by our vision system, due to the difference from the nearby orientations}{Pop out effect}{.3} \chapter{Background} In explaining the model setup and performed experiments, it is important to first introduce some neuroscience terminology. As one can imagine the visual cortex is utterly complex. We are focusing on the V1 cortex, analyzing a specific type of orientation selective neurons. Even though we are focusing on a specific neurons in only a part of our visual processing pipeline, we make even more simplifications in order to be able to analyze specific features of those neurons. We also briefly introduce recurrent neural networks and how they are used in the project. \section{Neuroscience background} \subsection{Visual field and visual stimuli} Visual field is the area we can see with our eyes. The information undergo a variety of transformations in the different parts of our visual cortex. The first few processing steps are illustrated in fig.\ref{visual_fields}. The initial information we receive is changes in light from our retina. This then gets processed by the lateral geniculate nucleus (LGN). The LGN cells and passed down to the Primary visual cortex (V1). V1 extract information about edges and orientations in the different parts of our visual field. \plotfigureS{visual_fields}{Perceiving a line from the retina to LGN cells and then by V1 orientation selective cells.\cite{receptive-fields}}{Visual Field}{.5} Precisely how this information is processed is the main interest of this project. While at a retinal and LGN level, most of the transformations are low-level, V1 starts to extract some patterns. We don't only detect single orientations for different parts of our visual field. Nearby orientations can influence each other. (to rewrite) Nearby orientations of the orientations useful for the high level visual processing happening in V2, V3, V4, V5 and V6. mention visual stimuli Finally it is also worth mentioning that we see in different details in different parts of our visual fields. Most of the information we perceive is close to the central or foveal vision, which could lead to interesting behavior \cite{knight2008drastically}. A small part of our retina, known as 'blind spot', does not have any photoreceptors. Our brain compensates the lack of information by fulfilling details from nearby observations. Both of those details could lead to change in behavior in our model, however we will ignore this details in our experiments. \plotfigure{RetinotopicMapping}{\bt{Central and peripheral vision}\cite{retinotopic-mapping} Substantial number of the cells in the retina are devoted to only a small part of our visual field, or central vision. Although relevant to the project, we will ignore this detail, for the benefit of simpler model}{Central and peripheral vision} \subsection{Receptive fields} In general, a receptive field is defined as a region of the sensory space, which can stimulate a given sensory neuron. In our context we can define the receptive field of a neuron, as the part of visual field, which affects it \cite{Hartline700}. The above two definition are known as classical receptive fields. It was later discovered that time plays a role as well, making the definition more complicated \cite{deangelis1995receptive}. In our model, described later, we focus on the spatial and ignore the temporal separation of receptive fields. Moreover because neurons are connected to each other, the notion of receptive field can get a bit vague. Because of those connection a neuron, can get excited or inhibited from parts of the visual field, that the neuron is not directly connected to (fig.\ref{F4large}). To avoid confusion we will stick to the definition of classical receptive fields, and distinguish between the input a neuron receives because of its tuned orientation and modulation from nearby neurons. \plotfigureS{F4large}{\bt{Effect of the context on receptive field on a neuron}\cite{cavanaugh2002nature} The firing of neurons is indirectly modulated and their response shifted, based on the stimuli just outside of their receptive field. This leads to some of the complications of explaining receptive field. Even though a certain neuron is tuned for only a certain part of our vision field, for certain orientation, it can be affected by nearby neurons. If we take this to the extreme, then a receptive field is based on all the sensory input we receive, since one neuron excites a nearby one, which excites its nearby neurons, etc.}{Effect of the context on receptive field on a neuron}{.5} \subsection{Tuning curves} Different orientation selective neurons are tuned for different orientation at a specific part of the visual field, defined by their receptive field. In other words neurons like specific orientation place at a specific place. However they spike not only when the preferred orientation is presented, but also on similar to its preferred orientation. The intensity of spiking, when different orientations are presented, forms a bell shaped curve with a peak the preferred orientation of the neuron. \plotfigure{HubelWiesel}{\bt{Tuning curves}\cite{hubel1968receptive} Different orientation bars are presented in a certain part of the visual field(on the left), and the response of the neuron tuned for this specific part of the visual field and $0\degree$. Even though the neuron is tuned for $0\degree$, its spikes when similar orientations are presented. The closer the orientation is to its preferred one, the stronger the response.}{Tuning curves} \subsection{Population coding} We have multiple orientation selective neurons per part of our receptive field. They all spike with different intensity defined by their tuning curves. Our final perception of the orientation in that part of the visual field is based on the all the spiking of the neurons. Their preferred orientation and magnitude can form a vector, with direction based on the preferred orientation and length based on the magnitude. When the vectors are added together, we get the final perceived orientation, with magnitude, as before, the length of the vector and perceived orientation - the direction of the vector. \plotfigure{populationCoding}{\bt{Population coding in the motor cortex}\cite{amirikian2000directional} Although the above picture illustrates population coding in a different part of the brain, it still good illustration of population coding. Different orientation selective neurons respond with certain intensity (black bars) and their response are combined to show the final perceived perception(red bars).}{Population Coding} \section{Elastica principle} The elastica principle defines the strength of modulation between two neurons. We find the smoothest curve connecting the two bars. The elastica energy is then defined by the total curvature. The smoother curve they form, the more strongly they should be connected. The principle is illustrated in fig.\ref{elastica1}. \plotfiguresix{elastica1}{elastica5}{elastica3}{elastica4}{elastica2}{elastica6}{\bt{Elastica principle} (to include energies for all curves) a) 0 b) ...}{.3}{Elastica principle} \section{Recurrent Neural Networks} A recurrent neural network (RNN) is a type of neural network with two way connections between its neurons. The benefit compared to a standard feedforward architecture is that can model dynamic behavior, where the responses of neurons change with respect to time. The network settles in a stable state, periodic or chaotic behavior. Two problems with RNNs are training and the expensive simulation of small timesteps. However they are not an issue as we set the weights based on the elastica principle and the experiments we run are on relatively small visual fields. \chapter{Design} This paper implements simplified versions of visual field, receptive fields, tuning curves and population coding in a recurrent neural network with orientation selective neurons. We start with a simple model with one receptive field, extend the model to multiple receptive fields, define limited and full connectivity and finally implement the elastica principle as well. In this section the different models are described in detail. In designing the model, I decided to use iterative and incremental development. The simplest models were mostly used for validity checks, rather than any meaningful experiments. Most of the experiments were based on the final version of the model, with full connectivity with weights setup according to the elastica principle. The input our model receives is a matrix of numbers from the interval $0-1$, representing different orientation from $0\degree$ to $180\degree$. The output has the same form and represents what orientations the model perceives. Fig.\ref{input_random} shows a visualization of a sample input to the model. It's important to note that the model returns not only a single matrix with perceived orientations, but multiple ones, representing the state at different timesteps. \plottwofigures{input_random}{input_structure}{\bt{Visualization of sample input(output) to the model} (A) Random orientations. (B) All orientations from $0\degree$ to $180\degree$, for every $1.8\degree$.}{Sample input} For every orientation of the input (every bar in fig.\ref{input_random}), we have a stack of neurons tuned for different orientations. Fig.\ref{stacked_neurons3} illustrates this. The perceived orientation is affected from two factors. First of all to detect a specific orientation, we have a stack of different neurons tuned for different orientations (fig.\ref{stacked_neurons3}, (A)). They all spike with different intensities and their collective response, forms the perceived orientation. Secondly, every single orientation orientation in our visual field, has its own stack of neurons (fig.\ref{stacked_neurons3}, (B)). Based on all those neurons, we can get accurate information about all the orientations (the higher the number of neurons used, the more accurate the perceived orientation is). The complexity comes from the fact that the different 'stacks of neurons' are connected with the nearby stacks. Those connections and how they influence the perceived orientation in a dynamic setting is the main focus of experiments ran. \plottwofigures{stacked_neurons3}{stacked_neurons2}{\bt{Visualization of the orientation selective neurons and their relationship with the presented input.} (A) Presented orientation(left) and responses of the orientation selective neurons(right). The more saturated the color, the stronger the response is. The neurons will spike with higher intensity, depending on the difference of the presented orientation and their preferred orientations. All the responses are combined, giving the final perceived orientation. (B) Schematic representation of the input and orientation selective neurons. Every orientation bar has its own stack of orientation selective neurons (only the first few are shown).}{Overview of the model} \plottwofiguresS{stacked_neurons}{neuron2}{\bt{Two different visualizations of orientation selective neurons} A) Visualization of 6 neurons in a stack form B) 9 orientations in unrolled form. Both of the visualization are for purely illustrative purposes. Visualization A) is used to explain the general model, while visualization B) better explains the connections between the neurons.}{Stack of neurons}{.3} \section{Single orientation} First we implement a visual field with a single orientation. We have a couple of neurons responsible for detecting the orientation (fig.\ref{stacked_neurons}). As described in \cite{keemink2015unified}, we represent those responses as vectors, with direction their preferred orientation and magnitude, the strength of the response with respect to the stimuli. Summing those vectors gives us the perceived orientation. Although used for recording responses from different types of neurons, fig.\ref{populationCoding} shows how population coding works. Black vectors are neural activity from specific neurons, and the red vector is the sum of all those responses. Even at this small scale, some experiments (described later) can be run, which show the relation between number of orientation selective neurons used and the accuracy of the perceived orientation. \section{Two orientations} Next we extend the model so we can feed two orientations and we have orientation selective neurons for the two orientations. We add recurrent connection between the neurons with the same preferred orientations, as showed in fig.\ref{neuron5}, (A), (B). This adds contextual modulation, as the perceived orientation of a single orientation in the visual field is influenced by the other one. The firing rate of the pairs of same orientation selective neurons in the two visual fields is calculated by the differential equations: \begin{equation} \label{model11} \tau_{syn}\cfrac{dr_{1}(t)}{dt}=-r_{1}(t)+in_{1}+w_{12}r_{2} \end{equation} \begin{equation} \label{model12} \tau_{syn}\cfrac{dr_{2}(t)}{dt}=-r_{2}(t)+in_{2}+w_{21}r_{1} \end{equation} where $\tau_{syn}$ is a constant, $\cfrac{dr_{1/2}(t)}{dt}$ is the change of the firing rate with respect to time, $r_{1/2}(t)$ is the current firing rate, $w_{12/21}$ is the strength between the neurons. $in_{1/2}$ is calculated from the tuning curve of the specific neuron for the presented orientation. In our model we will use the von Mises function as in \cite{keemink2015unified}. The von Mises function has the following formula: \eq{A\exp(k\cos2(\alpha_{pref} - \alpha_{actual}))} The different values of $A$ and $k$ are again described in \cite{keemink2015unified}, but ultimately the function with the correct set of parameters gives us the similarly looking tuning curves as in fig.\ref{HubelWiesel}. Finally to calculate the perceived orientations in the visual field by adding all responses from each part of the visual field as vectors. The direction of a vector is the preferred orientation of the given neuron, and the length is the magnitude of the response. Since the preferred orientation are direction independent, they vary from $0$ to $\pi$. As described in \cite{keemink2015unified}, to ensure circularity, we multiply all the responses by $2$, add them together and divide them by $2$ at the end. \eq{\alpha_{perceived}=\cfrac{1}{2}\sum_{i}2\vec{r}_{i}} %\plottwofigures{neuron5}{neuron3}{\bt{Two orientations, with limited connectivity between neurons}} \section{Multiple orientations, limited connectivity} Next we extend the model, so we can have any number of orientations (fig.\ref{neuron1}). Every neuron (except the ones at the end at the visual field) is connected with the eight closest neurons, which have the same preferred orientation as his (fig.\ref{neuron1}). We can extend the formulas \ref{model11} and \ref{model12} to: \begin{equation} \tau_{syn}\cfrac{dr_{i}(t)}{dt}=-r_{i}(t)+in+\sum_{j} w_{ij}r_{j} \end{equation} \plotfigureS{neuron1}{\bt{Any number of orientations, with limited connectivity between neurons} *The connections for only one neuron are shown.}{Limited connectivity}{0.7} \section{Multiple orientations, full connectivity} \label{mult_model} The next modification we do, on single neuron level, is to add full connectivity between all the neurons. We set the weights depending on the closeness of the neurons to each other, as well as the similarity of their preferred orientation. To explain how we setup the weights, let use an example. Let's have a $10x10$ visual field with different orientations, as in fig.\ref{input_random} and $9$ orientations selective neurons. Unrolling the $10x10x9$ matrix, we have a vector of $900$ neurons all together. We can setup $900x900$ weight matrix defining the connections between the neurons. Having some distance and the orientation constants as $\kappa_{distance}$ and $\kappa_{orientation}$, for every two neurons $l$ and $m$, we model the strength of the connection between them as: \eq{d=\sqrt{{(i_{l}-i_{m})}^{2}+{{(j_{l}-j_{m})}^{2}}}} \eq{\delta=min(mod(\alpha_{l}-\alpha_{m},1),mod(\alpha_{m}-\alpha_{l},1))} \eql{w_{i,j}=w_{j,i}=\kappa_{distance}\cfrac{1}{exp(d)} + \kappa_{orientation}\cfrac{1}{exp(\delta)}}{mult_model_formula} Based on the above equations we have the updating of the network as: \begin{equation} \tau_{syn}\cfrac{dr_{i}(t)}{dt}=-r_{i}(t)+in+\sum_{j=0}^{\#neurons}w_{ij}r_{j} \end{equation} We can vectorize our equation (and code), so we have: \begin{equation} \tau_{syn}\cfrac{dr_{i}(t)}{dt}=-r_{i}(t)+in+Wr \end{equation} The strength of the connection between every two neurons $l$ and $m$ is the same as the recurrent connection between $l$ and $m$, so the matrix is symmetric with respect to the main diagonal. The values along the main diagonals are $0$ (a neuron does not have a connection with itself). We can also notice the general trend of having highest values along the main diagonal and then smaller values the further away we go. This is true for different scales of our matrix - the full matrix (a), the first $100x100$ square (b) as well as the first $10x10$ square (c). The three different scales represent the change in orientation, horizontal and vertical position. \plotthreefigures{weight1}{weight2}{weight3}{Weight matrix for a full connectivity model. (A) Full weight matrix. (B) First 100 neurons. (C) First 10 neurons. (D) Scale of the values.}{Sample weight matrix}{1} \section{Elastica principle} The final part is implementing the elastica principle into the model. The only modification we have to do in comparison to the full connectivity model (sec.\ref{mult_model}) is change the equation calculating the weights, or the strength between respective neurons. In the previous model, we were setting based on the difference of the preferred orientations of the two neurons and the distance between them (eq.\ref{mult_model_formula}). \chapter{Implementation} This sections discusses the choice of programming languages and libraries, the benefits and challenges of using them and how they were addressed. During the implementations stages, I went through variety of changes, depending on the current stage of the project. First versions of visual fields, receptive fields, tuning curves and population coding were implemented. Next we implement a model of the input the orientation selective neurons in our V1 cortex receive and how the neurons respond to it. We gradually extend our model, to include more options for changing the connections between two neurons, as well as the form on the input. We use different tools for visualization and address some performance issues of simulating the model and running different experiments. \section{Initial choice of programming language} My first choice of programming language was Matlab. Matlab is a high-level scripting language, highly optimised for linear algebra operations. It is a well suited language for the purposes as it takes a lot of the complexity of memory management, parameter passing, multiple memory spaces, etc, of language like C++ has for example. As matrices and vectors additions and multiplications were the main bottle neck in this project, Matlab provided the necessary performance, while being simple and convenient to use. Moreover as most of the functions in Matlab can receive as an input a single number, vector or matrix, the model we built can be easily extended and tested for different configurations. Their integrated IDE with interpreter, standard debugging tools (breakpoints, continue, step in/out, etc.), workspace of current variables in scope, provided additional convenience in the initial stage of development. \section{Model implementation} I implemented versions of visual stimuli orientations selective neurons in V1 receive, tuning curves and population coding. The visual stimuli was implemented as a field of different bars (or edges, lines) of particular orientation, so a matrix with numbers from $0$ to $\pi$. The tuning curve of a particular neuron is defined as the spike activity when a particular orientation is presented, as a function of its preferred orientation. As mentioned in the previous section most of the functions in Matlab accept numbers, vectors and matrices as their arguments. This makes in particularly useful, as the function can be implemented for a single neuron, tested for expected output, and then the function can be used for vectors or matrices, when running more complicated experiments. As mentioned in the background section, we receive output from different orientation selective neurons about a particular bar of orientation. We use population coding to add their responses to get the final, perceived orientation. We implement population coding by transforming the output of the neurons in vectors. The preferred orientation of every neuron is the direction of the vector, the magnitude of its spiking is the length of the vector. We add all the vectors together to get a new vector, which represents the perceived orientation. The final vector's length and direction represent respectively the magnitude orientation of the final perceived response. As the orientation bars vary from $0$ to $\pi$, we multiply by $2$ the direction of all the neurons, and divide the final direction by $2$, to ensure circularity. We gradually extended the form on the input from a single orientation bar, to two and multiple ones in a form of matrix. We also extend the modulation connections between different neurons. Along different implementations we take advantage of the optimized linear operations in Matlab, and we keep our code vectorized, rather than for loops (with the exception of simulating different time steps of interactions between neurons, as the next state depends on the previous one). \section{Change of development tools} As the work progressed it became clear that Matlab, may not be the best choice of programming language for the project. After running some initial experiments, issues started coming up, which lead to transition to different set of programming tools, which we used for the final experiments. In our model we have different orientations bars, with a group of orientation selective neurons spiking for each bar and influencing the spiking of nearby neurons. It is a high dimensional data, hard to visualize. Moreover as we have dynamic interactions, implement by a recurrent neural network, we have the above mentioned data for every time step of our simulation. As the project grew bigger, some of the disadvantages of the weak code organization of Matlab became apparent, making hard to keep all the code base well structured. After careful consideration I decide to rewrite the work I've done in Python taking advantage of libraries like Holoviews\cite{stevens2010holoviews}, Matplotlib\cite{hunter2007matplotlib} and Numpy. I also started using IPython notebooks\cite{shen2014interactive}. Although the transition process took a couple of weeks, it yield number of advantages outlined below. \textbf{Python} \begin{itemize} \item Scalability - every function can be easily extended, by adding a new parameter and setting a default value, so it does not change the previous behaviour of the function \item Compatibility - Python is compatible with number of useful libraries, some of which used are described below \item Link to previous work - I took advantage of some of the code base of \cite{keemink2015unified}. In particular I used the methods for calculating and visualizing the elastica energy. \end{itemize} \textbf{Holoviews} \begin{itemize} \item Interactive visualizations - building complex interactive visualization, with respect to any number of parameters. In case of our problem, we used it for visualization of perceived orientation with respect to time \end{itemize} \textbf{Matplotlib} \begin{itemize} \item Main tool for static plots - although Holoviews provides some really advanced plotting capabilities, its API is sometimes complicated and tedious to use. Matplotlib is much widely used libraries with rich documentations and examples online. \end{itemize} \textbf{Numpy} \begin{itemize} \item Numerical operations - Numpy provides number of mathematical operations as well as functions for matrices and vectors manipulation. In addition its syntax is almost identical to Matlab, speeding up the transition process. \end{itemize} \textbf{IPython Notebook} \begin{itemize} \item Reproducible research - experiments can be specified and ran in a notebook. Results are shown under every experiment, also giving the option to run part or all of them again. \item Documenting - support from markdown cells (in addition to the code cells for the experiments) with rich formatting, including support for LaTeX. \end{itemize} Using the above stack of software tools greatly improved not only the development process, but also conducting and documenting experiments. \section{Final model changes} After transitioning to Python I incorporated the elastica principle in my model. Give two orientations selective neurons, the elastica principle defines how strongly they should be connected, by calculating their elastica energy. I also extended my model to custom positions of the neurons, rather than the fixed matrix grid. Rather than calculating the locations of the orientations, based on their position in the matrix, one can use a $1xN$ vector to represent all the neurons orientations together with $2xN$ matrix to represent their locations. This allows us to reproduce most of the experiments in \cite{keemink2015unified}, in the dynamic setting of the model. For some of the bigger experiments we run, we also implement a torus for the connections between the neurons. \chapter{Experiments} \section{Elastica energy} Simple experiments, matrix form \section{Static vs Dynamic models} %\subsection{Center and flanker bar} \section{Tilt effects} In this section we explore variety of tilt effects. In all of the experiments we have a center bar and a number of flanker bars around it. We experiment with different number of flankers, vary their position and orientation around the center bar. \begin{figure}[H] \caption{} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.5\linewidth]{fig5_B} \caption{} \end{subfigure}% \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.5\linewidth]{fig5_C} \caption{} \end{subfigure} \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.5\linewidth]{fig5_D} \caption{} \end{subfigure}% \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.5\linewidth]{fig5_F} \caption{} \end{subfigure} \floatfoot{Various tile experiments. a) Vary the orientations of two horizontal flankers. b) Rotate the two flankers around the center bar. c) Vary the orientation of two vertical flankers d) Vary the orientation } \end{figure} \subsection{Tilt effect 1} \plotfigureS{fig5_B}{Tilt Effect 1}{Tilt Effect 1}{0.3} \plotfigureS{matrix}{Weight matrix}{Weight Matrix 1}{0.5} (fix legend) \plotthreefigures{p_cen_b}{d_cen_b}{d_flan_b}{Experienced tilt illusions for different modulation constants. (a) Tilt illusion of the center bar for different flaker orientations. The experiment reproduced is from \cite{keemink2015unified}, fig.5, B (b) Tilt illusion of the center bar for different flanker orientations, in the dynamic mode. (c) Tilt illusion of the flanker bars for different flanker orientations, in a dynamic model}{Experienced tilt illusions}{1} \subsection{Tilt effect 2} \plotfigureS{fig5_C}{Tilt Effect 2}{Tilt Effect 2}{0.3} \plotthreefigures{p_cen_c}{d_cen_c}{d_flan_c}{Experienced tilt illusions for different modulation constants. (a) Tilt illusion of the center bar for different flaker orientations. The experiment reproduced is from \cite{keemink2015unified}, fig.5, C (b) Tilt illusion of the center bar for different flanker orientations, in the dynamic mode. (c) Tilt illusion of the flanker bars for different flanker orientations, in a dynamic model}{Experienced tilt illusions}{1} \subsection{Tilt effect 3} \plotfigureS{fig5_D}{Tilt Effect 3}{Tilt Effect 3}{0.3} \plotthreefigures{p_cen_d}{d_cen_d}{d_flan_d}{Experienced tilt illusions for different modulation constants. (a) Tilt illusion of the center bar for different flaker orientations. The experiment reproduced is from \cite{keemink2015unified}, fig.5, D (b) Tilt illusion of the center bar for different flanker orientations, in the dynamic mode. (c) Tilt illusion of the flanker bars for different flanker orientations, in a dynamic model}{Experienced tilt illusions}{1} \subsection{Tilt effect 4} \plotfigureS{fig5_F}{Tilt Effect 4}{Tilt Effect 4}{0.3} \plotthreefigures{p_cen_f}{d_cen_f}{d_flan_f}{Experienced tilt illusions for different modulation constants. (a) Tilt illusion of the center bar for different flaker orientations. The experiment reproduced is from \cite{keemink2015unified}, fig.5, F (b) Tilt illusion of the center bar for different flanker orientations, in the dynamic mode. (c) Tilt illusion of the flanker bars for different flanker orientations, in a dynamic model}{Experienced tilt illusions}{1} \section{Pop out effects} \begin{figure}[H] \caption{} \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{bar} \end{subfigure}% \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{bar_without} \end{subfigure} \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{bar_torus} \end{subfigure}% \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{line} \end{subfigure} \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{line_without} \end{subfigure}% \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{line_torus} \end{subfigure} \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{random} \end{subfigure}% \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{random_without} \end{subfigure}% \hfill \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1\linewidth]{random_torus} \end{subfigure} \floatfoot{Pop out effect. First column input, second column connections without torus, third column torus} \end{figure} \section{Additive and Multiplicative model} \begin{figure}[H] \caption{} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{2bars3} \end{subfigure}% \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{2bars_2} \end{subfigure} \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{2bars_1} \end{subfigure}% \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{2bars} \end{subfigure} \floatfoot{(Still figuring out how to make the plot clearer. Pop out effect. First column input, second column connections without torus, third column torus} \end{figure} \plotfigureS{2bars}{Experiment setup. Left red bar - center, right red bar - flanker, black bars - orientation selective neurons, blue curves - elastica curves. The position of the center bar is encoded by n orientation selective neurons. The modulation from the flanker is directly calculated from the orientation of the flanker bar, rather than through encoding it with orientation selective neurons. The more saturated the color, the stronger the connection between the orientation selective neuron and the flanker (not dependant on the presented center orientation). The wider the curve, the stronger the response of that neuron (dependent on the presented center orientation.}{Two bars setup}{0.5} \plotfiguresix{el_ener}{h_add}{h_mul}{cen}{ad_comb}{mul_comb}{\bt{Additive and Multiplicative model} (a) Elastica energy (b) h, additive (c) h, multiplicative (d) Central drive (e) Final response for additive model (f) Final response for multiplicative model}{.49}{Additive and Multiplicative mode} \plotfigure{ADD_vs_MULT}{Additive vs Multiplicative model. Although the tilt effects happen at different orientations and the strength of modulation is different, the change in the effect as we vary the flanker orientation is similar.}{AdMp} \section{Recurrent Neural Network} First we explore a simple network with only one neuron. The neuron receives a certain excitation ($in$). The speed with which the neuron changes it's response, depends on the contant $\tau_{syn}$ (the smaller $\tau_{syn}$, the slower the change). We setup the simple recurrent neural network below. \eq{\tau_{syn}\frac{dr(t)}{dt}=-r(t)+in} So every time step the change in the rate of the neuron is: \eq{\frac{dr(t)}{dt}=\cfrac{-r(t)+in}{\tau_{syn}}} \plotfigureS{simple}{The lines do not seem parallel, when it reality they are \cite{vision-computation}}{Simple RNN}{.5} Go in more details and show the first few steps of calculations of $\frac{dr(t)}{dt}$. $\tau_{syn}$ changes how fast the neuron goes to the stable state. \chapter{Evaluation} \chapter{Timeline} \begin{figure} \caption{} \begin{tikzpicture}[timespan={}] % timespan={Day} -> now we have days as reference % timespan={} -> no label is displayed for the timespan % default timespan is 'Week'% \timeline[custom interval=true]{May, Jun, Jul, Aug, Sep, Nov, Oct, Dec, Jan, Feb, Mar} % \timeline[custom interval=true]{3,...,9} -> i.e., from Day 3 to Day 9 % \timeline{8} -> i.e., from Week 1 to Week 8 % put here the phases \begin{phases} \initialphase{involvement degree=4.75cm,phase color=black} \phase{between week=5 and 7 in 0.7,involvement degree=4cm, phase color=black} \phase{between week=7 and 9 in 0.7,involvement degree=2cm, phase color=black} \phase{between week=5 and 9 in 0.7,involvement degree=4cm, phase color=green} \phase{between week=9 and 11 in 0.1,involvement degree=2.25cm} \phase{between week=8 and 11 in 0.7,involvement degree=2.25cm ,phase color=blue!80!cyan} \end{phases} % put here the milestones \addmilestone{at=phase-0.180,direction=90:1cm,text={Project allocation},text options={above}} \addmilestone{at=phase-0.270,direction=270:1cm,text={Sensory Systems (MIT OpenCourseWare)},text options={below}} \addmilestone{at=phase-1.130,direction=130:2cm,text={Literature review},text options={above}} \addmilestone{at=phase-1.230,direction=230:1cm,text={Neural Computation},text options={below}} \addmilestone{at=phase-1.290,direction=290:2cm,text={Machine Learning Practical},text options={below}} \addmilestone{at=phase-2.100,direction=100:3cm,text={More literature review},text options={above}} \addmilestone{at=phase-2.310,direction=310:3cm,text={Neural Information Processing},text options={below}} \addmilestone{at=phase-3.170,direction=170:1cm,text={Started working on Matlab implementation},text options={above}} \addmilestone{at=phase-3.140,direction=140:1cm,text={Visual fields},text options={above}} \addmilestone{at=phase-3.120,direction=120:1cm,text={Tuning curves},text options={above}} \addmilestone{at=phase-3.90,direction=90:1cm,text={Population coding},text options={above}} \addmilestone{at=phase-3.60,direction=60:1cm,text={Simple Dynamics},text options={above}} \addmilestone{at=phase-3.30,direction=30:1.5cm,text={Dynamics with weight matrix},text options={above}} \addmilestone{at=phase-3.270,direction=270:0.5cm,text={Python implementation},text options={below}} \addmilestone{at=phase-3.300,direction=300:0.5cm,text={Elastica principle},text options={below}} \addmilestone{at=phase-4.120,direction=120:0.3cm,text={Matlab experiments},text options={above}} \addmilestone{at=phase-4.310,direction=310:0.3cm,text={Python experiments},text options={below}} \addmilestone{at=phase-5.140,direction=140:0.34cm,text={Interim report},text options={above}} \addmilestone{at=phase-5.50,direction=50:0.34cm,text={Write},text options={above}} \addmilestone{at=phase-5.330,direction=330:0.34cm,text={Write},text options={below}} \addmilestone{at=phase-5.20,direction=20:1cm,text={Final write up},text options={above}} \end{tikzpicture} \label{timeline} \floatfoot{\bt{Timeline of the project}\\\textcolor{gray}{Research}\\\textcolor{green}{Implementation}\\\textcolor{yellow}{Experiments}\\\textcolor{blue}{Write up}} \end{figure} Fig.\ref{timeline} illustrates the work I have done so far and my plan until end of march, when the final deadline for the report is. After the project was allocated to me, I spend some time during the summer watching online courses on neuroscience and sensory systems. Beginning of the year, I took Neural Computation to get even more background. I started implementing all the necessary parts, in order to simulate the model - visual fields, tuning curves, population coding, etc. Afterwards I started implementing dynamics in the system, gradually extending the model. In my final model, I assume full connectivity between all the neurons. The connection at first are modeled based on the distance and difference in preferred orientations between them. My next goal is to incorporate the elastica principle into my model. At first I opted to use Matlab, as I had some experience with it. However with time, as I added some complexity to my model, I realized Matlab is not the base choice for the project. I decided to switch to Python, using Notebooks and Holoviews. Notebooks are a lot better way for structuring the code and write up at the same time. Holoviews was the other main reason, as it provides advanced plotting capabilities on multidimensional data, which is really viable when visualizing the output of recurrent neural networks for different time steps. \chapter{Conclusions} % use the following and \cite{} as above if you use BibTeX % otherwise generate bibtem entries \bibliographystyle{plain} \bibliography{mybib} \end{document}
import { recipes } from '../../data/recipes' import { BotContext } from '../../types' import { InlineKeyboardButton, ExtraEditMessage, ParseMode, } from 'telegraf/typings/telegram-types' import { aggregateIngredients, getAllIngredientsFor, shiftArrayBy, } from './dinnerUtils' const SAVED_OPTIONS_KEY = 'savedOptions' const CHOSEN_OPTIONS_KEY = 'chosenOptions' const PARSE_MODE: ParseMode = 'Markdown' const MAX_OPTIONS = 2 const FINISH_OPTION = 'finish' const MORE_OPTION = 'more...' // TODO: Future, add algorithm to change ordering of these. const createDinnerOptions = (): string[] => recipes.map(r => r.name) const getSavedOptions = (ctx: BotContext): string[] => ctx.session[SAVED_OPTIONS_KEY] ?? [] const getChosenOptions = (ctx: BotContext): string[] => ctx.session[CHOSEN_OPTIONS_KEY] ?? [] const clearOptions = (ctx: BotContext): void => { ctx.session[SAVED_OPTIONS_KEY] = null ctx.session[CHOSEN_OPTIONS_KEY] = null } function createDinnerStr(dinnerOptions: string[] = []): string { return `Here are some dinner options${ dinnerOptions.length > 0 ? '\n\n*Chosen so far*' : '' }${dinnerOptions.map(option => '\n' + option)}\n` } function createInlineKeyboard( savedOptions: string[], ): InlineKeyboardButton[][] { return savedOptions .slice(0, MAX_OPTIONS) .map(option => [ { text: option, callback_data: option, }, ]) .concat([ [ { text: FINISH_OPTION, callback_data: FINISH_OPTION }, { text: MORE_OPTION, callback_data: MORE_OPTION }, ], ]) } const getKeyboardExtraForContext = ( savedOptions: string[], ): ExtraEditMessage => ({ reply_markup: { inline_keyboard: createInlineKeyboard(savedOptions), }, parse_mode: PARSE_MODE, }) export const dinnerHandler = (ctx: BotContext): void => { ctx.session[SAVED_OPTIONS_KEY] = createDinnerOptions() ctx.reply(createDinnerStr(), getKeyboardExtraForContext(getSavedOptions(ctx))) } const addChosenOptionToSession = (ctx: BotContext, option: string): void => { ctx.session[CHOSEN_OPTIONS_KEY] = Array.from( new Set(getChosenOptions(ctx)).add(option), ) const newSavedOptions = getSavedOptions(ctx).filter( savedOption => !option.includes(savedOption), ) ctx.session[SAVED_OPTIONS_KEY] = newSavedOptions } function handleFinishOption(ctx: BotContext): void { const chosenOptions = getChosenOptions(ctx) const ingredients = aggregateIngredients(getAllIngredientsFor(chosenOptions)) const ingredientsMessage = ingredients .map(i => `*${i.name}* ${i.quantity}`) .join('\n') if (chosenOptions.length > 0) { ctx.editMessageText( `*Selected Options*\n${chosenOptions.join('\n')}\n\n` + ingredientsMessage, { parse_mode: PARSE_MODE }, ) } else { ctx.editMessageText('No options selected') } clearOptions(ctx) } function handleMoreOption(ctx: BotContext): void { const chosenOptions = getChosenOptions(ctx) const savedOptions = getSavedOptions(ctx) shiftArrayBy(MAX_OPTIONS, savedOptions) ctx.session[SAVED_OPTIONS_KEY] = savedOptions ctx.editMessageText( createDinnerStr(chosenOptions), getKeyboardExtraForContext(savedOptions), ) } export const dinnerCallback = (ctx: BotContext): void => { const chosenOption = ctx.callbackQuery?.data ?? '' if (chosenOption === FINISH_OPTION) { handleFinishOption(ctx) } else if (chosenOption === MORE_OPTION) { handleMoreOption(ctx) } else { addChosenOptionToSession(ctx, chosenOption) const chosenOptions = getChosenOptions(ctx) ctx.editMessageText( createDinnerStr(chosenOptions), getKeyboardExtraForContext(getSavedOptions(ctx)), ) } }
<template> <div> <div :class="businessObjId ? 'top-block notop' : 'top-block'"> <el-row> <el-col :span="16"> <PmToolbar> <PmToolbarItem v-permission="FuncCode.afc_f_role_add" plain icon="el-icon-plus" @click="openAdd" >新建角色</PmToolbarItem> <PmToolbarItem v-permission="FuncCode.afc_f_role_del" plain :disabled="selections.length == 0" @click="deleteClick" >批量删除</PmToolbarItem> </PmToolbar> </el-col> <el-col :span="8" class="text-right"> <PmSearch ref="searchForm" style="width: 300px" class="float-right" :query.sync="query" default-prop="name" placeholder="搜索角色名称" @search="pmSearch" > <template slot="body"> <el-form-item label="角色名称" prop="name"> <el-input v-model="query.name" v-focus clearable @keypress.native.enter="searchEnter" /> </el-form-item> <el-form-item label="角色编号" prop="code"> <el-input v-model="query.code" clearable @keypress.native.enter="searchEnter" /> </el-form-item> </template> </PmSearch> </el-col> </el-row> </div> <el-table :id="tableId" v-loading="RoleController.queryRolesWithPage.loading" :highlight-current-row="true" :height="autoTableHeight" border stripe :data="gridList" @sort-change="sortChange" @selection-change="selectionChange" > <el-table-column type="selection" width="55" /> <el-table-column sortable="code" label="编号" prop="code" show-overflow-tooltip > <template slot-scope="scope"> <el-link v-if="allow(FuncCode.afc_f_role_edit)" @click="gotoDetail(scope.row, 0)" >{{ scope.row.code }}</el-link> <span v-else>{{ scope.row.code }}</span> </template> </el-table-column> <el-table-column sortable="name" label="名称" prop="name" show-overflow-tooltip /> <el-table-column label="资源权限数量" prop="resAmount" show-overflow-tooltip > <template slot-scope="scope"> <el-link @click="gotoDetail(scope.row, 1)">{{ scope.row.resAmount || 0 }}</el-link> </template> </el-table-column> <el-table-column v-if="type !== 'businessObject'" label="成员数量" prop="memberAmount" show-overflow-tooltip > <template slot-scope="scope"> <el-link @click="gotoDetail(scope.row, 2)">{{ scope.row.memberAmount || 0 }}</el-link> </template> </el-table-column> <el-table-column label="操作" width="150px"> <template slot-scope="{ row }"> <PmToolbar> <PmToolbarItem v-permission="FuncCode.afc_f_role_del" type="text" @click="remove(row)" >删除</PmToolbarItem> </PmToolbar> </template> </el-table-column> </el-table> <Pagination :selections="selections" :page-size="query.limit" :current-page.sync="query.offset" :total="gridTotal" @size-change="changePageSizer" @current-change="changePage" /> <FormDialog :dialog-visible.sync="dialogVisible" v-bind="$props" @success="search" /> </div> </template> <script> import { RoleController } from '@controller' import { BaseVue, Form, List, VueUtil } from '@lib' import FormDialog from '../form.vue' export default { name: 'role', components: { FormDialog }, mixins: [BaseVue, List, Form], props: { type: { type: String, }, businessObjId: { type: String, }, currentAppId: { type: String, default: '' } }, computed: { ...VueUtil(this) .select([RoleController]) .state(), appId() { return (this.$route.query ? this.$route.query.appId : null) || this.currentAppId || null } }, data() { return { tableHeight: 'calc(100vh - 204px)', } }, watch: { businessObjId: { immediate: true, handler(val) { if (val) { this.search() } }, }, type: { immediate: true, handler(val) { if (val) { this.search() } }, }, }, mounted() { this.search() }, activated() { this.search() }, methods: { searchEnter() { if (this.$refs.searchForm) { // 高级搜索 enter this.$refs.searchForm.searchQuery = { ...this.query } this.$refs.searchForm.initOptions() this.$refs.searchForm.visible = false } this.pmSearch() }, async searchBody() { if (this.appId) { // 查询应用角色 const query = this.otherQuery(this.query) const payload = { appId: this.type, ...query } const resp = await this.dispatch( RoleController.queryAppRolesWithPage, payload ) return resp } else { const query = this.otherQuery(this.query) const payload = { type: this.type, ...query } // 业务对象 if (this.type == 'businessObject' && this.businessObjId) { payload.businessObjId = this.businessObjId } const resp = await this.dispatch( RoleController.queryRolesWithPage, payload ) return resp } }, async removeBody(row) { const payload = [row.id] const resp = await this.dispatch(RoleController.deleteByIds, payload) return resp }, // 批量删除 async deleteClick() { this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }) .then(async() => { const payload = this.selections.map((sel) => { return sel.id }) const resp = await this.dispatch(RoleController.deleteByIds, payload) if (!resp.error) { this.pmSearch() this.$msg.success('删除成功') } }) .catch(() => {}) }, gotoDetail(app, tab) { this.$emit('gotoDetail', app, tab, this.$props) }, }, } </script> <style lang="scss" scoped> .notop { padding: 0px 0px 8px 0px !important; } </style>
import React from 'react'; import { Outlet } from 'react-router-dom'; import { Box, Grid, Paper, Toolbar } from "@mui/material"; import { Header } from "./Header/Header"; import { SideBar } from "./SideBar/SideBar"; import { provider, useInstance } from "react-ioc"; import { observer } from "mobx-react-lite"; import NavStore from "../stores/nav.store"; import { styled } from "@mui/material/styles"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import CounterStore from "../stores/store-counter" import WeatherStore from "../stores/weather.store" import ProductStore from "../stores/product.store" import TableViewStore from "../pages/table/stores/table.view-store" import StoreTableModal from "../pages/table/stores/storeTableModal" import { LocalizationProvider } from '@mui/x-date-pickers'; import TodoStore from "../stores/todo.store" const ItemText = styled(Paper)(({theme}) => ({ ...theme.typography.body2, padding: theme.spacing(3), textAlign: 'left', color: theme.palette.text.secondary, })); export const AuthLayout = provider( CounterStore, NavStore, WeatherStore, ProductStore,TableViewStore,StoreTableModal,TodoStore )(observer(() => { const nav = useInstance(NavStore) return ( <LocalizationProvider dateAdapter={AdapterMoment}> <Box sx={{display: 'flex', minHeight: {xs: 'calc(100vh - 64px)', md: 'calc(100vh - 60px)'}}}> <Header /> <SideBar /> <Box component="main" sx={{p: {sm: 0, md: 3}, width: {xs: "100vw", md: `calc(100vw - ${nav.drawerWidth}px)`}}}> <Toolbar /> <Grid container sx={{minHeight: '100%'}}> <Grid item xs={12}> <ItemText sx={{p: nav.paperPadding, minHeight: '100%', overflowX: 'auto'}}> <Outlet /> </ItemText> </Grid> </Grid> </Box> </Box> </LocalizationProvider> ); }));
import axios from '../../src/index' // axios({ // url: '/extend/post', // method: 'post', // data: { // msg: 'hi' // } // }) // // axios.request({ // url: '/extend/post', // method: 'post', // data: { // msg: 'hello' // } // }) // // axios.get('/extend/get') // // axios.options('/extend/options') // // axios.delete('/extend/delete') // // axios.head('/extend/head') // // axios.post('/extend/post', { msg: 'post' }) // // axios.put('/extend/put', { msg: 'put' }) // // axios.patch('/extend/patch', { msg: 'patch' }) // axios({ // url: '/extend/post', // method: 'post', // data: { // msg: 'hi' // } // }) // // axios('/extend/post', { // method: 'post', // data: { // msg: 'hello' // } // }) interface ResponseData<T = any> { code: number result: T message: string } interface User { name: string age: number } function getUser<T>() { return axios<ResponseData<T>>('/extend/user') .then(res => res.data) .catch(err => console.error(err)) } async function test() { const user = await getUser<User>() if (user) { console.log(user.result.name) } } test()
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('slices', function (Blueprint $table) { $table->id(); $table->foreignId('admin_id')->nullable()->constrained(table: 'admins', column: 'id')->cascadeOnDelete(); $table->foreignId('mentor_id')->nullable()->constrained(table: 'mentors', column: 'id')->cascadeOnDelete(); $table->string('title'); $table->string('about'); $table->text('overview'); $table->string('category'); $table->string('duration');; $table->boolean('is_paid')->default(false); $table->decimal('price', 8, 2)->nullable(); $table->string('image_path')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('slices'); } };
import { useState, useEffect } from "react"; import { getAvatarUrl } from "../functions/getAvatarUrl"; import { WalletAdapterNetwork } from "@solana/wallet-adapter-base"; import { useConnection, useWallet } from "@solana/wallet-adapter-react"; import { clusterApiUrl, Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction } from "@solana/web3.js"; import BigNumber from "bignumber.js"; export const useCashApp = () => { // State variables const [avatar, setAvatar] = useState(""); const [userAddress, setUserAddress] = useState("44444444444444444444444444"); const [amount, setAmount] = useState(0); const [receiver, setReceiver] = useState(''); const [transactionPurpose, setTransactionPurpose] = useState(''); const [newTransactionModalOpen, setNewTransactionModalOpen] = useState(false); // Wallet and connection information from wallet adapter const { connected, publicKey, sendTransaction } = useWallet(); const { connection } = useConnection(); // Custom hook for using localStorage with default state const useLoopStorage = (storageKey, fallbackState) => { const [value, setValue] = useState(JSON.parse(localStorage.getItem(storageKey)) ?? fallbackState); useEffect(() => { localStorage.setItem(storageKey, JSON.stringify(value)); }, [value, setValue]); return [value, setValue]; }; // Transaction history stored in localStorage const [transactions, setTransactions] = useLoopStorage("transactions", []); // Get Avatar based on the userAddress useEffect(() => { if (connected) { setAvatar(getAvatarUrl(publicKey.toString())); setUserAddress(publicKey.toString()); } }, [connected]); // Create the transaction to send to our wallet, which can be signed from there const makeTransaction = async (fromWallet, toWallet, amount, reference) => { const network = WalletAdapterNetwork.Devnet; const endpoint = clusterApiUrl(network); const connection = new Connection(endpoint); // Get recent blockhash to include in the transaction const { blockhash } = await connection.getLatestBlockhash('finalized'); const transaction = new Transaction({ recentBlockhash: blockhash, feePayer: fromWallet, // the buyer pays the transaction fee }); // Create instruction to send SOL from owner to recipient const transferInstruction = SystemProgram.transfer({ fromPubkey: fromWallet, lamports: amount.multipliedBy(LAMPORTS_PER_SOL).toNumber(), toPubkey: toWallet, }); transferInstruction.keys.push({ pubkey: reference, isSigner: false, isWritable: false, }); transaction.add(transferInstruction); return transaction; }; // Create the function to RUN the transaction, to be added to the button const doTransaction = async ({ amount, receiver, transactionPurpose }) => { const fromWallet = publicKey; const toWallet = new PublicKey(receiver); const bnAmount = new BigNumber(amount); const reference = Keypair.generate().publicKey; const transaction = await makeTransaction(fromWallet, toWallet, bnAmount, reference); const txnHash = await sendTransaction(transaction, connection); console.log(txnHash); // Create transaction history object const newID = (transactions.length + 1).toString(); const newTransaction = { id: newID, from: { name: publicKey, handle: publicKey, avatar: avatar, verified: true, }, to: { name: receiver, handle: '-', avatar: getAvatarUrl(receiver.toString()), verified: false, }, description: transactionPurpose, transactionDate: new Date(), status: 'Completed', amount: amount, source: '-', identifier: '-', }; setNewTransactionModalOpen(false); setTransactions([newTransaction, ...transactions]); }; return { connected, publicKey, avatar, userAddress, doTransaction, amount, setAmount, receiver, setReceiver, transactionPurpose, setTransactionPurpose, transactions, setTransactions, setNewTransactionModalOpen, newTransactionModalOpen, }; };
--- '$title': العمل مع البيانات عن بُعد $order: 3 description: ماذا لو كانت بياناتك القابلة للربط كبيرة جدًا أو مركَّبة بحيث يتعذر استردادها عند تحميل الصفحة؟ أو ماذا لو كان لكل وحدة حفظ مخزون سعر يستغرق ... toc: 'true' --- ماذا لو كانت بياناتك القابلة للربط كبيرة جدًا أو مركَّبة بحيث يتعذر استردادها عند تحميل الصفحة؟ أو ماذا لو كان لكل وحدة حفظ مخزون سعر يستغرق وقتًا طويلًا للبحث عنه؟ حيث يُعد البحث عن الأسعار لوحدات حفظ المخزون للعناصر غير المرئية عملًا مهدرًا. [tip type="success"] يدعم [`<amp-state>`](../../../../documentation/components/reference/amp-bind.md#state) إحضار البيانات عن بُعد عبر سمة [`src`](../../../../documentation/components/reference/amp-bind.md#attributes)الخاصة بها، حيث يحضر JSON من نقطة نهاية CORS. ويتم تنفيذ عملية الإحضار هذه مرة واحدة وعند تحميل الصفحة، وهو مفيد لضمان حداثة البيانات (خاصة عند عرضها من ذاكرة تخزين مؤقت). ويمكنك أيضًا ربط السمة `src` بالمكون [`<amp-state>`](../../../../documentation/components/reference/amp-bind.md#state). وهذا يعني أن بإمكان إجراء المستخدم تشغيل عملية إحضار بيانات JSON إلى الحالة القابلة للربط الخاصة بالصفحة. [/tip] ## إحضار المقاسات المتوفرة لقميص لنستفد من إمكانية إحضار بيانات عن بًعد للبحث عن أسعار وحدات حفظ المخزون في النموذج لدينا. يحتوي خادم التطوير Express.js لدينا الموجود في `app.js` على نقطة نهاية بالفعل `/shirts/sizesAndPrices?shirt=<sku>` والتي، بالنظر إلى وحدة حفظ مخزون القميص، تقوم بإرجاع المقاسات المتوفرة وسعر كل مقاس. وترسل الاستجابة بتأخير اصطناعي يبلغ ثانية واحدة لمحاكاة زمن انتقال الشبكة. | طلب | استجابة | | ------------------------------------- | -------------------------------------------- | | `GET /shirts/sizesAndPrices?sku=1001` | `{"1001: {"sizes": {"XS": 8.99, "S" 9.99}}}` | وعلى نحو مماثل لبيانات JSON ضمن المكون [`<amp-state>`](../../../../documentation/components/reference/amp-bind.md#state)، يتم دمج البيانات البعيدة التي تم إرجاعها من عمليات الإحضار هذه وإتاحتها ضمن السمات `id` الخاصة بالمكون. على سبيل المثال، يمكن الوصول إلى البيانات التي تم إرجاعها من مثال الرد أعلاه في تعبير: | تعبير | نتيجة | | ---------------------------- | ------ | | `shirts['1001'].sizes['XS']` | `8.99` | ### ربط البيانات والآن، لنطبق هذا الأمر على مثال التجارة الإلكترونية لدينا، أولًا، نقوم بإحضار بيانات هذا القميص عند تحديد وحدة حفظ المخزون. أضف `[src]` ربط للعنصر `amp-state#shirts`: ```html <!-- When `selected.sku` changes, update the `src` attribute and fetch JSON at the new URL. Then, merge that data under `id` ("shirts"). --> <amp-state id="shirts" [src]="'/shirts/sizesAndPrices?sku=' + selected.sku" ></amp-state> ``` ### الإشارة إلى المقاسات غير المتوفرة وبعد ذلك، لنضع وسمًا واضحًا على المقاسات غير المتوفرة على هذا النحو لوحدة حفظ مخزون معينة. وتضيف فئة CSS `"unavailable"` خطًا قطريًا عبر عنصر ما -- يمكننا إضافته إلى العناصر الموجودة ضمن [`amp-selector`](../../../../documentation/components/reference/amp-selector.md) المقابلة للمقاسات غير المتوفرة: ```html <amp-selector name="size"> <table> <tr> <!-- If 'XS' size is available for selected SKU, return empty string. Otherwise, return 'unavailable'. --> <td [class]="shirts[selected.sku].sizes['XS'] ? '' : 'unavailable'"> <div option="XS">XS</div> </td> <td [class]="shirts[selected.sku].sizes['S'] ? '' : 'unavailable'"> <div option="S">S</div> </td> <td [class]="shirts[selected.sku].sizes['M'] ? '' : 'unavailable'"> <div option="M">M</div> </td> <td [class]="shirts[selected.sku].sizes['L'] ? '' : 'unavailable'"> <div option="L">L</div> </td> <td [class]="shirts[selected.sku].sizes['XL'] ? '' : 'unavailable'"> <div option="XL">XL</div> </td> </tr> </table> </amp-selector> ``` والآن، أعد تحميل الصفحة وجربها. سيؤدي تحديد وحدة حفظ المخزون (لون القميص) الجديدة إلى شطب المقاسات غير المتوفرة (بعد مهلة قصيرة). ### تحديد الحالات الأولية هناك مشكلة صغيرة على الرغم من ذلك -- ماذا عن القميص أسود اللون، لون المحدد الافتراضي؟ سنحتاج إلى إضافة بيانات المقاس والسعر للقميص الأسود إلى `amp-state#shirts` نظرًا لأن [`amp-bind`](../../../../documentation/components/reference/amp-bind.md) يعمل فقط استجابة لإجراء المستخدم الصريح: ```html <amp-state id="shirts" [src]="'/shirts/sizesAndPrices?sku=' + selected.sku"> <script type="application/json"> { "1001": { "color": "black", "image": "./shirts/black.jpg", "sizes": { "XS": 8.99, "S": 9.99 } }, <!-- ... --> ``` وسنحتاج إلى تحديث الحالة الافتراضية للعناصر ذات الصلة: ```html <amp-selector name="size"> <table> <tr> <!-- If 'XS' size is available for selected SKU, return empty string. Otherwise, return 'unavailable'. --> <td [class]="shirts[selected.sku].sizes['XS'] ? '' : 'unavailable'"> <div option="XS">XS</div> </td> <td [class]="shirts[selected.sku].sizes['S'] ? '' : 'unavailable'"> <div option="S">S</div> </td> <!-- Add the 'unavailable' class to the next three <td> elements to be consistent with the available sizes of the default SKU. --> <td class="unavailable" [class]="shirts[selected.sku].sizes['M'] ? '' : 'unavailable'" > <div option="M">M</div> </td> <td class="unavailable" [class]="shirts[selected.sku].sizes['L'] ? '' : 'unavailable'" > <div option="L">L</div> </td> <td class="unavailable" [class]="shirts[selected.sku].sizes['XL'] ? '' : 'unavailable'" > <div option="XL">XL</div> </td> </tr> </table> </amp-selector> ``` [tip type="note"] **ملحوظة –** لا يعمل [`amp-bind`](../../../../documentation/components/reference/amp-bind.md) عند تحميل الصفحة -- يعمل فقط استجابة لإجراء المستخدم. وهذا يضمن تحميل الصفحة الأولي بسرعة ثابتة عبر كل الصفحات بصرف النظر عن استخدام [`amp-bind`](../../../../documentation/components/reference/amp-bind.md). [/tip] ## أسعار القميص المتغيرة الآن بعد أن عرضنا المقاسات المتوفرة على نحو صحيح، دعنا نتأكد أيضًا من عرض السعر الصحيح. يتميز متجر AMPPAREL لدينا في كون سعر هذا القميص محددًا من حيث اللون والمقاس. وهذا يعني أننا بحاجة إلى متغير جديد لتتبع المقاس المحدد بواسطة المستخدم. أضف إجراءً جديدًا لعنصر المقاس لدينا [`amp-selector`](../../../../documentation/components/reference/amp-selector.md): ```html <!-- When an element is selected, set the `selectedSize` variable to the value of the "option" attribute of the selected element. --> <amp-selector name="size" on="select:AMP.setState({selectedSize: event.targetOption})" ></amp-selector> ``` لاحظ أننا لا نقوم بتهيئة قيمة العنصر `selectedSize` via the `amp-state#selected`. وهذا لأننا لا نقدم عن قصد مقاسًا محددًا افتراضيًا ونرغب بدلًا عن ذلك في إلزام المستخدم باختيار مقاس. [tip type="tip"] **تلميح –** يمكن استخدام `AMP.setState()` لتحديد المتغيرات الجديدة بالإضافة إلى تعديل تلك الموجودة مسبقًا. وستقوم التعبيرات بتقييم المتغيرات غير المحددة إلى `null`. [/tip] أضف عنصر `<span>` جديدًا من شأنه العمل على التفاف ملصق السعر وتغيير النص الافتراضي إلى "---" نظرًا لعدم وجود تحديد سعر افتراضي. ```html <h6> PRICE : <!-- Display the price of the selected shirt in the selected size if available. Otherwise, display the placeholder text '---'. --> <span [text]="shirts[selected.sku].sizes[selectedSize] || '---'">---</span> </h6> ``` والآن أصبح لدينا أسعار صحيحة! جرِّبها. ## زر ممكَّن على نحو مشروط نحن على وشك الانتهاء! دعنا نعطل زر "إضافة إلى عربة التسوق" عندما يكون المقاس المحدد غير متوفر: ```html <!-- Disable the "ADD TO CART" button when: 1. There is no selected size, OR 2. The available sizes for the selected SKU haven't been fetched yet --> <input type="submit" value="ADD TO CART" disabled class="mdl-button mdl-button--raised mdl-button--accent" [disabled]="!selectedSize || !shirts[selected.sku].sizes[selectedSize]" /> ``` **جرِّبه**: إذا حددت مقاسًا غير متوفر، فلا يمكنك إضافته إلى عربة التسوق.
Support Vector Machines SVM is a classification method. 1. Support Vector Classifier. 2. Support Vector Machine. Data has No Overlap - Separable Data ----------------------------------------- Maximal Margin Classifier: is a optimization problem in the heart. Non-separable Data and Noisy Data ----------------------------------- We use soft margins. Procedures: Maximize :math:`M`, for :math:`\sum \beta_j^2=1` (unit vector), so that .. math:: y_i( \beta_0 + \sum_{k=1}^{p} \beta_{k} x_{ik} ) \geq (1-\epsilon_i)M, with :math:`\epsilon_i \geq 0` and :math:`\sum_{i=1}^n \epsilon_i \leq C`. C is a parameter that is chosen to restrict the method. Feature Expansion ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Construct more variables so that parameter space becomes higher. Effectively, we are constructing a nonlinear hyperplane in the parameter space. **Mathematically speaking, we are reconstructing the true classifier using it's Taylor expansions.** We have talked about Support Vector Classifiers. What is the SVM then? It might be computationial expensive to really work out support vector classfiers. One of the tricks that makes the computation easy is to use inner products. .. math:: f(x_k) = \beta_0 + \sum_{i=1}^n \alpha_i \langle x_k, x_i \rangle. We estimate the parameters :math:`\alpha` and it turns out most of them can be 0. The nonzero ones defines are the actual support vectors that is most important for the classifier. The subset of vectors is selected, by nonzero :math:`\alpha`, and are denoted with :math:`\hat \alpha`. What is the corresponding formalism for the expanded feature space? The solution is kernel and the method becomes SVM. .. math:: K(x_i, x_{i'}) = \left( 1 + \sum_{j=1}^p x_{ij} x_{i'j} \right)^d. One of the popular kernel is radial kernel: .. math:: K(x_i, x_{i'}) = \exp \left( - \gamma \sum_{j=1}^p (x_{ij} - x_{i'j})^2 \right). 1. SVM is better than Logistic Regression when the data is almost separable. 2. LR with ridge method is better than SVM when it's the other way around. References and Notes -----------------------
/* * Copyright 2018-2022 Hazelcast, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hazelcast.msfdemo.acctsvc.business; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.jet.datamodel.Tuple2; import com.hazelcast.jet.pipeline.JournalInitialPosition; import com.hazelcast.jet.pipeline.Pipeline; import com.hazelcast.jet.pipeline.ServiceFactories; import com.hazelcast.jet.pipeline.ServiceFactory; import com.hazelcast.jet.pipeline.Sinks; import com.hazelcast.jet.pipeline.Sources; import com.hazelcast.jet.pipeline.StreamStage; import com.hazelcast.map.EntryProcessor; import com.hazelcast.map.IMap; import org.hazelcast.msf.controller.MSFController; import org.hazelcast.msf.messaging.APIResponse; import org.hazelcast.msfdemo.acctsvc.domain.Account; import org.hazelcast.msfdemo.acctsvc.events.AccountEventTypes; import org.hazelcast.msfdemo.acctsvc.events.AccountOuterClass.AdjustBalanceRequest; import org.hazelcast.msfdemo.acctsvc.events.AdjustBalanceEvent; import org.hazelcast.msfdemo.acctsvc.eventstore.AccountEventStore; import org.hazelcast.msfdemo.acctsvc.service.AccountService; import java.io.File; import java.net.URL; import java.util.AbstractMap; import static com.hazelcast.jet.datamodel.Tuple2.tuple2; public class AdjustBalancePipeline implements Runnable { private static AccountService service; public AdjustBalancePipeline(AccountService service) { AdjustBalancePipeline.service = service; if (service == null) throw new IllegalArgumentException("Service cannot be null"); } @Override public void run() { try { MSFController controller = MSFController.getOrCreateInstance(service.isEmbedded(), service.getClientConfig()); System.out.println("AdjustBalancePipeline.run() invoked, submitting job"); ClassLoader cl = AdjustBalanceEvent.class.getClassLoader(); // In Docker image, jars have been copied to /ext ... File fw = new File("/ext/framework-1.0-SNAPSHOT.jar"); URL framework = fw.toURI().toURL(); File grpc = new File("/ext/account-proto-1.0-SNAPSHOT.jar"); URL grpcdefs = grpc.toURI().toURL(); File svc = new File("/application.jar"); URL service = svc.toURI().toURL(); //System.out.println(">>> Found files? " + fw.exists() + " " + grpc.exists() + " " + svc.exists()); URL[] jobJars = new URL[] { framework, grpcdefs, service }; // Reverted to non-uploading version -- wasn't get all classes properly resolved controller.startJob("AccountService", "AccountService.AdjustBalance", createPipeline(), jobJars, new Class[]{}); } catch (Exception e) { // Happens if our pipeline is not valid e.printStackTrace(); } } private static Pipeline createPipeline() { Pipeline p = Pipeline.create(); String requestMapName = AccountEventTypes.ADJUST.getQualifiedName(); IMap<Long, AdjustBalanceRequest> requestMap = MSFController.getInstance().getMap(requestMapName); String responseMapName = requestMapName + ".Results"; IMap<Long, APIResponse<?>> responseMap = MSFController.getInstance().getMap(responseMapName); // Dummy service creation, purely as a way to retrieve Hazelcast instance and stick it into // Event object where it is needed to initialize SubscriptionManager ServiceFactory<?, HazelcastInstance> hzSF = ServiceFactories.sharedService( (ctx) -> { HazelcastInstance hz = ctx.hazelcastInstance(); return hz; }); StreamStage<Tuple2<Long, AdjustBalanceEvent>> tupleStream = p.readFrom(Sources.mapJournal(requestMap, JournalInitialPosition.START_FROM_OLDEST)) .withIngestionTimestamps() .setName("Read from " + requestMapName) // Create AdjustBalanceEvent object .mapUsingService(hzSF, (hz, entry) -> { //System.out.println("Creating AccountEvent, returning Tuple2"); Long uniqueRequestID = (Long) entry.getKey(); AdjustBalanceRequest request = entry.getValue(); AdjustBalanceEvent event = new AdjustBalanceEvent( request.getAccountNumber(), request.getAmount()); Tuple2<Long,AdjustBalanceEvent> item = tuple2(uniqueRequestID, event); return item; }) .setName("Create AccountEvent.ADJUST"); ServiceFactory<?,IMap<String,Account>> materializedViewServiceFactory = ServiceFactories.iMapService(service.getView().getName()); ServiceFactory<?, AccountEventStore> eventStoreServiceFactory = ServiceFactories.sharedService( (ctx) -> new AccountEventStore(ctx.hazelcastInstance()) ); tupleStream.mapUsingService(eventStoreServiceFactory, (eventStore, tuple) -> { eventStore.append(tuple.f1()); return tuple; // pass thru unchanged }).setName("Persist AdjustBalanceEvent to event store") // Build Materialized View and Publish it .mapUsingService(materializedViewServiceFactory, (viewMap, tuple) -> { AdjustBalanceEvent adjustEvent = tuple.f1(); // How not to do this (race condition) //Account mview = viewMap.get(adjustEvent.getAccountNumber()); //mview.setBalance(mview.getBalance() + adjustEvent.getAmount()); //viewMap.put(adjustEvent.getAccountNumber(), mview); assert adjustEvent != null; Account accountView = viewMap.executeOnKey(adjustEvent.getAccountNumber(), (EntryProcessor<String, Account, Account>) accountEntry -> { Account accountView1 = accountEntry.getValue(); int newBalance = accountView1.getBalance() + adjustEvent.getAmount(); accountView1.setBalance(newBalance); accountEntry.setValue(accountView1); return accountView1; }); return tuple2(tuple.f0(), accountView); }).setName("Update Account Materialized View") // Build API response and publish it .map( tuple -> { Long uniqueID = tuple.f0(); Account view = tuple.f1(); APIResponse<Integer> response = new APIResponse<>(uniqueID, view.getBalance()); //System.out.println("Building and returning API response"); return new AbstractMap.SimpleEntry<Long,APIResponse<Integer>>(uniqueID, response); }).setName("Respond to client") .writeTo(Sinks.map(responseMap)); return p; } }
'use client'; import client from '@/apis/core'; import UserInfo from '@/app/mypage/_components/UserInfo'; import { Button } from '@/components/ui/button'; import { Separator } from '@/components/ui/separator'; import { routes } from '@/constants/routeURL'; import { useRequestPermission } from '@/hooks/useRequestPermission'; import { clearItem, getItem } from '@/utils/storage'; import { ChevronRightIcon } from 'lucide-react'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { useMypageInfo } from './_hooks/useMypageInfo'; const MyPage = () => { let userId: string | undefined; if (typeof window !== 'undefined') userId = getItem<string | undefined>(localStorage, 'userId'); const { myInfo } = useMypageInfo({ userId: Number(userId) }); const { requestPermission } = useRequestPermission(); const router = useRouter(); const handleLogout = async () => { const provider = getItem(localStorage, 'provider'); try { if (provider === 'KAKAO') { await client.post({ url: 'https://kapi.kakao.com/v1/user/logout', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, }); } else if (provider === 'GITHUB') { await client.delete({ url: `https://api.github.com/applications/${process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID}/token`, auth: { username: process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID!, password: process.env.NEXT_PUBLIC_GITHUB_SECRET!, }, data: { access_token: getItem(localStorage, 'token') }, headers: { Accept: 'application/json' }, }); } alert('로그아웃 하였습니다.'); router.replace('/'); } catch (e) { alert('인증이 만료된 사용자입니다. 다시 로그인해주세요.'); router.replace('/signin'); } finally { clearItem(localStorage); } }; const handleAlert = () => { if (confirm('알림을 허용하시겠습니까?')) requestPermission({ userId }); }; const handleDeleteAccount = () => { if (confirm('정말 탈퇴하시겠습니까? 😥')) client.delete({ url: `/users/${getItem(localStorage, 'userId')}` }).then((res) => { console.log(res); alert('탈퇴가 완료되었습니다.'); clearItem(localStorage); router.replace('/'); }); }; const myActivities = [ { title: '내가 찜한 모각코', link: routes.likeMGC, count: myInfo?.likeMogakkoCount }, { title: '현재 참여중인 모각코', link: routes.currentJoinMGC, count: myInfo?.ongoingMogakkoCount, }, { title: '종료된 모각코', link: routes.endJoinMGC, count: myInfo?.completeMogakkoCount, }, { title: '받은 리뷰 평가', link: routes.receivedReviewsAssessment, }, { title: '블랙리스트', link: routes.blackList }, { title: '신고목록', link: routes.reportList }, ]; return ( <> {myInfo ? ( <section> <UserInfo myInfo={myInfo.userInfo} /> <div className="mb-10 flex flex-col gap-4 font-bold"> <p className="text-xl text-main-1">나의 활동</p> {myActivities.map(({ link, title, count }) => ( <div key={link} className="flex flex-col gap-3 text-sm " > <div className="flex justify-between"> <p> {title} {count ?? ''} </p> <Link href={link}> <ChevronRightIcon /> </Link> </div> <Separator /> </div> ))} </div> <div className="mb-10 flex flex-col gap-4 font-bold"> <p className="text-xl text-main-1">내 정보 관리</p> <div className="flex flex-col gap-3 text-sm"> <div className="flex justify-between"> <p>알림 허용</p> <ChevronRightIcon className="cursor-pointer " onClick={handleAlert} /> </div> <Separator /> </div> <div className="flex flex-col gap-3 text-sm"> <div className="flex justify-between"> <p>로그아웃</p> <ChevronRightIcon className="cursor-pointer" onClick={handleLogout} /> </div> <Separator /> </div> <div className="flex flex-col gap-3 text-sm"> <div className="flex justify-between transition-all duration-500 hover:text-red-500"> <p>회원탈퇴</p> <ChevronRightIcon className="cursor-pointer " onClick={handleDeleteAccount} /> </div> <Separator /> </div> </div> </section> ) : ( <div className="flex h-svh w-full items-center justify-center"> <Link href={routes.signin}> <Button onClick={() => clearItem(localStorage)}> 회원가입 시에만 사용할 수 있습니다. </Button> </Link> </div> )} </> ); }; export default MyPage;
package fp.chapter03.exercises import org.junit.jupiter.api.Test import kotlin.test.assertEquals class P0315ReplicateWithTailRec { private tailrec fun replicate(n: Int, element: Int, acc: List<Int> = emptyList()): List<Int> = when { n <= 0 -> acc else -> replicate(n - 1, element, listOf(element) + acc) } @Test fun run() { assertEquals(replicate(3, 5), listOf(5, 5, 5)) } }
package com.example.fitflow.viewmodels.rutina import android.widget.Toast import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.fitflow.dominio.modelos.Actividad import com.example.fitflow.dominio.modelos.Rutina import com.example.fitflow.dominio.repositorio.ActividadesRepositorio import com.example.fitflow.dominio.repositorio.HistorialRepositorio import com.example.fitflow.dominio.repositorio.RutinasRepositorio import com.example.fitflow.estados.EstadoDeDialogo import com.example.fitflow.estados.EstadoDeDropDown import com.example.fitflow.estados.EstadoDeTexto import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class RutinaViewModel @Inject constructor( private val rutinaRepositorio: RutinasRepositorio, private val historialRepositorio: HistorialRepositorio, private val actividadesRepositorio: ActividadesRepositorio, savedStateHandle: SavedStateHandle ) : ViewModel() { private val _rutinas = mutableStateOf(listOf<Rutina>()) val rutinas: State<List<Rutina>> = _rutinas private val _nombre = mutableStateOf( EstadoDeTexto( placeholder = "Nombre de la rutina", ) ) val nombre: State<EstadoDeTexto> = _nombre private val _duracion = mutableStateOf( EstadoDeTexto( placeholder = "Duración de la rutina", ) ) val duracion: State<EstadoDeTexto> = _duracion private val _actividades = mutableStateOf( EstadoDeDropDown( placeholder = "Actividades de la rutina", ) ) val actividades: State<EstadoDeDropDown> = _actividades private val _dialogoVisible = mutableStateOf(EstadoDeDialogo()) val dialogoVisible: State<EstadoDeDialogo> = _dialogoVisible init { viewModelScope.launch { rutinaRepositorio.obtenerTodasRutinas().collect { rutinas -> _rutinas.value = rutinas } } } fun onEvento(evento: RutinaEvento) { when (evento) { is RutinaEvento.IngresarNombre -> { _nombre.value = nombre.value.copy( valor = evento.valor ) } is RutinaEvento.IngresarDuracion -> { _duracion.value = duracion.value.copy( valor = evento.valor.toString() ) } is RutinaEvento.IngresarActividades -> { _actividades.value = actividades.value.copy( listaDeActividades = evento.valor ) } is RutinaEvento.AbrirDialogo -> { _dialogoVisible.value = dialogoVisible.value.copy( visible = true ) } is RutinaEvento.CerrarDialogo -> { _dialogoVisible.value = dialogoVisible.value.copy( visible = false ) } is RutinaEvento.GuardarRutina -> { val nombre = nombre.value.valor val duracion = duracion.value.valor.toInt() val actividades = actividades.value.listaDeActividades if (nombre.isBlank() || duracion == 0 || actividades.isEmpty()) { Toast.makeText( evento.contexto, "Por favor ingresa un nombre, duración y actividades", Toast.LENGTH_SHORT ).show() return } val rutina = Rutina( nombre = nombre, duracion = duracion, actividades = actividades ) viewModelScope.launch { rutinaRepositorio.insertar(rutina) _dialogoVisible.value = dialogoVisible.value.copy( visible = false ) limpiarCampos() } } is RutinaEvento.MostrarListaDeActividades -> { _actividades.value = _actividades.value.copy( estaExpandido = true ) } is RutinaEvento.OcultarListaDeActividades -> { _actividades.value = _actividades.value.copy( estaExpandido = false ) } } } fun obtenerActividades(): Flow<List<Actividad>> = flow { actividadesRepositorio.obtenerTodasActividades().collect { emit(it) } } fun limpiarCampos() { _nombre.value = nombre.value.copy( valor = "" ) _duracion.value = duracion.value.copy( valor = "" ) _actividades.value = actividades.value.copy( listaDeActividades = listOf() ) } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>More CSS Practice</title> </head> <!-- Here I shall be exploring styling my CSS differently: Instead of using Tags which will affect both the parent and the children, I will select the classes of the tags. So instead of the CLASS and not the TAG will be my SELECTOR, then I can bring in my properties and values. --> <!-- So I'm thinking of doing something with FIELDSET and LEGEND tags. First, Let me play with the CSS LAYOUT.--> <h1>MARRIAGE 101</h1> <!-- I just learnt that the SPAN tag is used for in-line styling! Using it with STYLE="" or CLASSES. HOW COOL!--> <h2><span style="font-style: italic;">Two</span> people meet... </h2> <style> h1 { color:red; font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif; } h2 { color:blueviolet; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; } .ex-box { border: 3px solid #aaa; background-color: #eee; height : 200px; width: 200px; display: flex; align-items: center; justify-content: center; float: left; margin-right: 10px; border-radius: 5px; color: blue; font-size: 30px; } .ex-box: last-of-type { clear: right; } .clear { clear: both; } </style> <div class="ex-box">ADI</div> <div class="ex-box">PRISCILLA</div> <div class="clear"></div> <h2>...and become <span style="font-style: italic; font-weight: bolder;">one!</span></h2> <style> .new-ex-box { border: 3px solid #aaa; background-color: #eee; height: 200px; width: 200px; display: flex; align-items: center; justify-content: center; margin-right: auto; margin-left: auto; border-radius: 5px; font-size: 20px; font-weight: bold; color: blue; } </style> <div class="new-ex-box">ADI&PRISCILLA</div> <!-- I love CSS!!! I need to learn more about fonts and colors though.--> <h2>Then the children come in with their different flavours. </h2> <style> .box-1 { border: 1px solid black: color: white; background-color: blue; height: 150px; width: 300px; } .box-2 { border: 1px solid black; color: white; background-color: red; height: 100px; width: 300px; } .box-3 { border: 1 px solid black; color:white; background-color: green; height: 200px; width: 100px; } .floated div { float: left; } .clearfix::after { content: "TO BE CONTINUED..."; clear:both; display: table; color:blueviolet; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-weight: bolder; } </style> <div class="floated"> <div class="box-1">BABY 1</div> <div class="box-2">BABY 2</div> <div class="box-3">BABY 3</div> <div class="clearfix"></div> </div> <!-- We use float to push elements as far left or right, as possible; and when there's not enough space, they move to the next line. So they wrap. There is also FLEX: which squishes things. Both FLOAT and FLEX are laid out in the parent. I could show examples above. .clear and .clearfix can help clear the layout, so that I can input text--> <!-- .flex-container class is another layout and .reverse and flex-container reverse will reverse the boxes: 321. and .column will make it into a column. Also column reverse works. We also have .jc-right to justify right and .jc-left and .jc-center then the property will be justify-content. Also .jc-sb with property justify-content and value space-between. Finally .jc-sa (space around) and .jc-se (space evenly). Next is the align-items property which worries about vertical alignment and not horizontal, like the above. .ai-fe with value flex-end and flex-start as the opposite. Then ai-center, ai-stretch ( here if you have defined height, you need to remove it like this .no-height with property height and value inherit). As for .ai-grow, I gotta try it. There's also flex-wrap for multiple rows and align-self.--> </body> </html>
/* * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup HdfLight * @{ * * @brief Provides APIs for the light service. * * The light module provides a unified interface for the light service to access the light driver. * After obtaining the driver object or proxy, the light service distinguishes light devices by id * and call related APIs to obtain light information, turn on or off a light, or set the blinking mode. * @since 3.1 */ /** * @file ILightInterface.idl * * @brief Declares common APIs of the light module. These APIs can be used to obtain the light id, * turn on or off a light, and set the light brightness and blinking mode. * @since 3.1 */ /** * @brief Defines the basic operations that can be performed on lights. * * The operations include obtaining light information, turning on or off a light, * and setting the light brightness or blinking mode. */ package ohos.hdi.light.v1_0; import ohos.hdi.light.v1_0.LightTypes; interface ILightInterface { /** * @brief Obtains information about all the lights in the system. * * @param info Indicates the vector of the light information. For details, see {@link HdfLightInfo}. * * @return Returns <b>0</b> if the operation is successful. * @return Returns a negative value if the operation fails. * * @since 3.1 */ GetLightInfo([out] struct HdfLightInfo[] info); /** * @brief Turns on available lights in the list based on the specified light id. * * @param lightId Indicates the light id. For details, see {@link HdfLightId}. * * @param effect Indicates the pointer to the lighting effect. For details, see {@link HdfLightEffect}. * * @return Returns <b>0</b> if the operation is successful. * @return Returns <b>-1</b> if the light id is not supported. * @return Returns <b>-2</b> if the blinking setting is not supported. * @return Returns <b>-3</b> if the brightness setting is not supported. * * @since 3.1 */ TurnOnLight([in] int lightId, [in] struct HdfLightEffect effect); /** * @brief Turns off available lights in the list based on the specified light id. * * @param lightId Indicates the light id. For details, see {@link HdfLightId}. * * @return Returns <b>0</b> if the operation is successful. * @return Returns a negative value if the operation fails. * * @since 3.1 */ TurnOffLight([in] int lightId); }
#include "main.h" /** * _pow_recursion - return power of numbers * @x: x power * @y: of y * Return: value */ int _pow_recursion(int x, int y) { if (y < 0) return (-1); else if (y == 0) return (1); else if (y == 1) return (x); else return (x * _pow_recursion(x, y - 1)); }
import React, { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import axios from 'axios'; import '../styles/AddSong.css'; import '../images/EmptyStage.jpg'; const AddSong = () => { const navigate = useNavigate(); const [song, setSong] = useState({ title: '', musician: '', notes: '', spotifyTrackId: '', file: null }); const [query, setQuery] = useState(''); const [searchResults, setSearchResults] = useState([]); const [message, setMessage] = useState(''); const handleSubmit = async (event) => { event.preventDefault(); try { // Submit form data including the file const formData = new FormData(); formData.append('title', song.title); formData.append('musician', song.musician); formData.append('notes', song.notes); formData.append('spotifyTrackId', song.spotifyTrackId); formData.append('file', song.file); const response = await fetch('http://localhost:8080/api/songs/add', { method: 'POST', /// body: JSON.stringify(song), body: formData, }); if (response.ok) { setMessage('New Song Added'); navigate('/SongTable', { state: { key: Date.now()}}); // Navigate to the list of songs page setSong({ title: '', musician: '', notes: '', spotifyTrackId:'' }); // Clear the form fields after successful addition } else { setMessage('Failed to add song'); } } catch (error) { console.error('Error adding song:', error); setMessage('Failed to add song'); } }; const handleFileChange = (event) => { setSong({ ...song, file: event.target.files[0] }); }; const handleSearch = async (searchTerm) => { try { const accessToken = 'BQBfs-Go2pIWQvdm-be5Uk-0cknL3W5jA8WUcquPX33MgWG8NSHMaNsRQqDpwXYQIj0BMCIw478tuWOkP5FOzMqbVaXm02klPdjDJzreGRHxgew0_VFPOWsL1KBhhkdzkDlW1nh1ITVJaypt3DEIMO5N3e_mogVbpTvE5JOxO9Dxyy0qDc50mSiKvXh0TIOF6eIct6AaNUY-Ch295HmJixXk0FCP13USzS5nJ40GNrDhhVjn-yifrkrGEw'; const encodedSearchTerm = encodeURIComponent(searchTerm); // Encode the search term const response = await axios.get('https://api.spotify.com/v1/search', { params: { q: encodedSearchTerm, // Use the encoded search term type: 'track' }, headers: { 'Authorization': `Bearer ${accessToken}` } }); const searchResults = response.data.tracks.items.map(item => ({ id: item.id, name: `${item.name} - ${item.artists.map(artist => artist.name).join(', ')}`, // Concatenate track name and artists spotifyTrackId: item.id })); setSearchResults(searchResults); } catch (error) { console.error('Error searching Spotify:', error); } }; const handleSelectTrack = (spotifyTrackId) => { setSong({ ...song, spotifyTrackId }); }; return ( <div className="background-image-container"> <div className="song-container-big"> <div className="newSong-div"> <h2>Create New Song</h2> <form className="newSongForm" onSubmit={handleSubmit}> <input type="text" value={song.title} onChange={(e) => setSong({ ...song, title: e.target.value })} placeholder="Title" required /> <input type="text" value={song.musician} onChange={(e) => setSong({ ...song, musician: e.target.value })} placeholder="Musician/Show" required /> <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search Spotify" /> <button type="button" onClick={() => handleSearch(query)}>Search</button> <select value={song.spotifyTrackId} onChange={(e) => setSong({ ...song, spotifyTrackId: e.target.value })}> <option value="">Select Track</option> {searchResults.map(result => ( <option key={result.id} value={result.spotifyTrackId}>{result.name}</option> ))} </select> <p>Only JPG files are fully supported.</p> <input type="file" onChange={handleFileChange} required /> <input type="text" value={song.notes} onChange={(e) => setSong({ ...song, notes: e.target.value })} placeholder="Notes" /> <button type="submit" className='create-button'>Create</button> </form> {message && <p>{message}</p>} </div> </div> console.log("hello"); </div> ); }; export default AddSong;
--- title: 深度学习模型优化技术实操:模型剪枝、量化、知识蒸馏与轻量化网络设计 published: 2024-04-30 description: 探索深度学习中的模型优化技术,包括模型剪枝、量化、知识蒸馏和轻量化网络设计,旨在提升模型效率并减少计算资源需求。 tags: [模型优化, 模型剪枝, 量化, 知识蒸馏, 轻量化网络] category: 技术 draft: false --- ## 模型剪枝 模型剪枝是深度学习领域中用于优化神经网络模型的一种技术。它的核心思想是通过移除模型中一些不重要或冗余的参数(比如权重较小或对输出影响较小的神经元),从而减少模型的大小和计算需求,提高模型的运行速度,同时尽量保持模型的性能。模型剪枝通常包括以下几个步骤: 1. **训练原始模型**:首先训练一个深度学习模型直到达到较高的精度。 2. **评估参数重要性**:然后评估模型中每个参数的重要性。这可以通过各种方法来实现,如基于权重的大小、权重的梯度或其他启发式方法(例如参数对输出的影响)。 3. **剪枝**:根据评估的重要性,去除那些重要性低的参数。剪枝可以是结构化的(比如去除整个卷积核或神经元)或非结构化的(随机去除单个权重)。 4. **微调**:剪枝后的模型通常需要通过进一步训练来恢复性能,这个过程称为微调。 剪枝的好处包括: - 减少计算资源需求:模型更小,计算速度更快,能够在计算能力有限的设备上运行。 - 降低能耗:小型化的模型消耗的能量更少,适合于电池供电的移动设备或远程传感器。 - 减少存储需求:模型大小的减少使得存储需求降低,有利于在存储资源受限的设备上部署。 所需库: `torch.nn.utils.prune`模块应用`l1_unstructured`剪枝方法,它基于权重的L1范数来移除权重。我们选择剪枝第一个卷积层的50%权重。执行剪枝后,我们可以查看剪枝后权重中有多少比例是零,这有助于了解剪枝的效果。 ### 模型剪枝的代码示例: ```python import torch import torch.nn.utils.prune as prune import torchvision.models as models model = models.resnet18(pretrained=True) model.eval() # 剪枝第一个卷积层的权重 layer = model.conv1 print("Original weights:", layer.weight.data) # 移除50%的权重 prune.l1_unstructured(layer, name='weight', amount=0.5) # 打印剪枝后的权重 print("Pruned weights:", layer.weight.data) # 查看剪枝后的权重中有多少是零 print("Fraction of weights pruned to zero:", torch.sum(layer.weight == 0).item() / layer.weight.nelement()) ``` ## 另外几种优化模型方法: ##1. 量化 量化是将模型中的浮点数参数转换为低精度(如整数)表示的过程。这样做可以显著减少模型的存储需求和计算复杂性,通常对模型的推理速度有明显的提升,同时也能降低能耗。 ### 使用PyTorch进行动态量化的示例: ```python import torch import torchvision.models as models import torch.quantization # 加载预训练模型 model = models.resnet18(pretrained=True) model.eval() # 指定量化配置为动态量化 model.qconfig = torch.quantization.default_dynamic_qconfig # 准备模型进行量化 quantized_model = torch.quantization.prepare_dynamic(model) # 转换模型进行量化 quantized_model = torch.quantization.convert(quantized_model) print(quantized_model) ``` ##2. 知识蒸馏 知识蒸馏是一种模型压缩技术,通过让一个小的“学生”模型学习一个大的“教师”模型的输出,目的是使小模型能够模拟大模型的行为。这种方法能够让小模型在保持较小体积的同时,尽可能地复现大模型的性能。 ### 简单的知识蒸馏代码示例: ```python mport torch import torch.nn as nn import torch.optim as optim from torchvision.models import resnet18 # 教师模型(更大更复杂) teacher_model = resnet18(pretrained=True) teacher_model.eval() # 学生模型(更简单) student_model = resnet18(pretrained=False) student_model.fc = nn.Linear(512, 1000) # 适应同样的输出层 # 定义损失函数和优化器 criterion = nn.MSELoss() optimizer = optim.Adam(student_model.parameters(), lr=0.001) # 蒸馏过程 for data, target in dataloader: teacher_output = teacher_model(data) student_output = student_model(data) loss = criterion(student_output, teacher_output) optimizer.zero_grad() loss.backward() optimizer.step() ``` ##3. 轻量化网络设计 轻量化网络设计涉及从头开始设计或使用特定的架构技术来创建计算上更有效的模型。这些模型通常使用较少的参数和操作,但是设计得当可以达到与传统模型相似的性能。大部分直接可以用轻量化的迁移学习模型来做,比如经典的MobileNet系列。 ### 代码示例(使用MobileNet): ```python import torchvision.models as models mobilenet = models.mobilenet_v2(pretrained=True) print(mobilenet) ```
let specialItems = document.getElementById("special-items"); let basket = JSON.parse(localStorage.getItem("data")) || []; <!--This generates the cart items--> let generateItems = () => { return (specialItems.innerHTML = shopSpecialItemsData .map((specItem) => { let { id, name, size, desc, price, img } = specItem; let search = basket.find((x) => x.id === id) || []; return ` <div id=product-id-${id} class="card"> <img src=${img} class="card-img-top" alt="lemonade" loading="lazy"> <div class="card-body"> <h5 class="card-title">${name}</h5> <p class="card-text"><em>${desc}</em></p> <div class="price-quantity"> <p class="card-text"><small class="text-body-secondary">${size}: $ ${price}</small></p> <div class="cartButton"> <svg onclick="decrement(${id})" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-left-circle " viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8m15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0m-4.5-.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5z" /> </svg> <div id=${id} class="quantity"> ${search.item === undefined ? 0 : search.item} </div> <svg onclick="increment(${id})" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-right-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0M4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5z" /> </svg> </div> </div> </div> </div>`; }) .join("")); }; generateItems(); let increment = (id) => { let selectedItem = id; let search = basket.find((x) => x.id === selectedItem.id); if (search === undefined) { basket.push({ id: selectedItem.id, item: 1, }); } else { search.item += 1; } localStorage.setItem("data", JSON.stringify(basket)); update(selectedItem.id); }; let decrement = (id) => { let selectedItem = id; let search = basket.find((x) => x.id === selectedItem.id); if (search === undefined) return; else if (search.item === 0) return; else { search.item -= 1; } update(selectedItem.id); basket = basket.filter((x) => x.item !== 0); localStorage.setItem("data", JSON.stringify(basket)); }; let update = (id) => { let search = basket.find((x) => x.id === id); document.getElementById(id).innerHTML = search.item; calculation(); }; let calculation = () => { let cartIcon = document.getElementById("cartAmount"); cartIcon.innerText = basket.map((x) => x.item).reduce((x, y) => x + y, 0); }; calculation();
/* avaScript'te çeşitli operatörler bulunur: Aritmetik Operatörler: + (toplama), - (çıkarma), * (çarpma), / (bölme), % (mod alma). Atama Operatörleri: = (atama), +=, -=, *=, /= (kısa atama). Karşılaştırma Operatörleri: == (eşit mi), != (eşit değil mi), === (aynı tipte ve değerde mi), !==, <, >, <=, >=. Mantıksal Operatörler: && (ve), || (veya), ! (değil). Ternary (Üçlü) Operatör: condition ? expression1 : expression2 (koşul ? ifade1 : ifade2). İkili Operatörler: & (ve), | (veya), ^ (XOR), << (sol kaydırma), >> (sağ kaydırma). */ let x = 10; let y = 5; let sum = x + y; // 15 let isGreater = x > y; // true let result = isGreater ? "x, y'den büyüktür" : "x, y'den küçüktür"; // "x, y'den büyüktür" /* Karşılaştırm Operatörleri */ let now = new Date(); // Geçerli tarih ve saat bilgisini alır console.log(now); let specificDate = new Date("2023-12-31"); // Belirli bir tarih oluşturur console.log(specificDate); let year = now.getFullYear(); // Yılı alır let month = now.getMonth(); // Ayı alır (0'dan başlar) let day = now.getDate(); // Günü alır let hour = now.getHours(); // Saati alır let minute = now.getMinutes(); // Dakikayı alır let second = now.getSeconds(); // Saniyeyi alır //Mantıksal Operatör // && ve işareti operatörü örneği ( ampersand olarak anlandırılıyor) const a = 4 > 3 && 10 > 5 // true && true -> true const b = 4 > 3 && 10 < 5 // true && false -> false const c = 4 < 3 && 10 < 5 // false && false -> false // || boru veya operatör, örnek const d = 4 > 3 || 10 > 5 // true || true -> true const e = 4 > 3 || 10 < 5 // true || false -> true const f = 4 < 3 || 10 < 5 // false || false -> false //! olumsuzlama örnekleri let check = 4 > 3 // true let checked = !(4 > 3) // false let isLightOn = true let isLightOff = !isLightOn // false let isMarried = !false // true //Arttırma Operatörü JavaScript'te, bir değişkende saklanan bir değeri artırmak için artırma operatörünü kullanırız. Artış, artış öncesi veya sonrası olabilir. Her birini görelim: // Öncesi Artış let count = 0 console.log(++count) // 1 console.log(count) // 1 // Sonrası Artış let sayi = 0 console.log(count++) // 0 console.log(count) // 1 // Azaltma Operatörü JavaScript'te, bir değişkende saklanan bir değeri azaltmak için azaltma operatörünü kullanırız. Azaltma, eksiltme öncesi veya sonrası olabilir. Her birini görelim: //Öncesi Azaltma let sayi2 = 0 console.log(--count) // -1 console.log(count) // -1 //Sonrası Azaltma let sayi3 = 0 console.log(count--) // 0 console.log(count) // -1 /* Koşul Operatörü (Ternary - Üçlü ) Üçlü operatör bir koşul yazmaya izin verir. Koşullar yazmanın başka bir yolu da üçlü operatörleri kullanmaktır. Aşağıdaki örneklere bakın */ let isRaining = true isRaining ? console.log('Yağmurluk lazım.') : console.log('Yağmurluğa gerek yok.') isRaining = false isRaining ? console.log('Yağmurluk lazım.') : console.log('Yağmurluğa gerek yok.') //----- let number = 5 number > 0 ? console.log(`${number} is a positive number`) : console.log(`${number} is a negative number`) number = -5 number > 0 ? console.log(`${number} is a positive number`) : console.log(`${number} is a negative number`)
import { relations, sql } from "drizzle-orm"; import { timestamp, varchar } from "drizzle-orm/mysql-core"; import { mySqlTable } from "./_table"; import { addresses } from "./addresses"; import { orders } from "./orders"; import { products } from "./products"; export const users = mySqlTable("users", { id: varchar("id", { length: 256 }).notNull().primaryKey(), name: varchar("name", { length: 255 }).notNull(), email: varchar("email", { length: 255 }).notNull().unique(), imageUrl: varchar("image_url", { length: 255 }).notNull(), major: varchar("major", { length: 255 }), createdAt: timestamp("created_at").default(sql`CURRENT_TIMESTAMP`), updatedAt: timestamp("updated_at").onUpdateNow(), }); export const usersRelations = relations(users, ({ many }) => ({ product: many(products), address: many(addresses), order: many(orders), }));
begin_unit|revision:1.0.0;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|calcite operator|. name|adapter operator|. name|file package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|calcite operator|. name|util operator|. name|Source import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|io operator|. name|input operator|. name|Tailer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|io operator|. name|input operator|. name|TailerListener import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|io operator|. name|input operator|. name|TailerListenerAdapter import|; end_import begin_import import|import name|au operator|. name|com operator|. name|bytecode operator|. name|opencsv operator|. name|CSVParser import|; end_import begin_import import|import name|au operator|. name|com operator|. name|bytecode operator|. name|opencsv operator|. name|CSVReader import|; end_import begin_import import|import name|java operator|. name|io operator|. name|Closeable import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|StringReader import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayDeque import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Queue import|; end_import begin_comment comment|/** * Extension to {@link CSVReader} that can read newly appended file content. */ end_comment begin_class class|class name|CsvStreamReader extends|extends name|CSVReader implements|implements name|Closeable block|{ specifier|protected name|CSVParser name|parser decl_stmt|; specifier|protected name|int name|skipLines decl_stmt|; specifier|protected name|Tailer name|tailer decl_stmt|; specifier|protected name|Queue argument_list|< name|String argument_list|> name|contentQueue decl_stmt|; comment|/** * The default line to start reading. */ specifier|public specifier|static specifier|final name|int name|DEFAULT_SKIP_LINES init|= literal|0 decl_stmt|; comment|/** * The default file monitor delay. */ specifier|public specifier|static specifier|final name|long name|DEFAULT_MONITOR_DELAY init|= literal|2000 decl_stmt|; name|CsvStreamReader parameter_list|( name|Source name|source parameter_list|) block|{ name|this argument_list|( name|source argument_list|, name|CSVParser operator|. name|DEFAULT_SEPARATOR argument_list|, name|CSVParser operator|. name|DEFAULT_QUOTE_CHARACTER argument_list|, name|CSVParser operator|. name|DEFAULT_ESCAPE_CHARACTER argument_list|, name|DEFAULT_SKIP_LINES argument_list|, name|CSVParser operator|. name|DEFAULT_STRICT_QUOTES argument_list|, name|CSVParser operator|. name|DEFAULT_IGNORE_LEADING_WHITESPACE argument_list|) expr_stmt|; block|} comment|/** * Creates a CsvStreamReader with supplied separator and quote char. * * @param source The file to an underlying CSV source * @param separator The delimiter to use for separating entries * @param quoteChar The character to use for quoted elements * @param escape The character to use for escaping a separator or quote * @param line The line number to skip for start reading * @param strictQuotes Sets if characters outside the quotes are ignored * @param ignoreLeadingWhiteSpace If true, parser should ignore * white space before a quote in a field */ specifier|private name|CsvStreamReader parameter_list|( name|Source name|source parameter_list|, name|char name|separator parameter_list|, name|char name|quoteChar parameter_list|, name|char name|escape parameter_list|, name|int name|line parameter_list|, name|boolean name|strictQuotes parameter_list|, name|boolean name|ignoreLeadingWhiteSpace parameter_list|) block|{ name|super argument_list|( operator|new name|StringReader argument_list|( literal|"" argument_list|) argument_list|) expr_stmt|; comment|// dummy call to base constructor name|contentQueue operator|= operator|new name|ArrayDeque argument_list|<> argument_list|() expr_stmt|; name|TailerListener name|listener init|= operator|new name|CsvContentListener argument_list|( name|contentQueue argument_list|) decl_stmt|; name|tailer operator|= name|Tailer operator|. name|create argument_list|( name|source operator|. name|file argument_list|() argument_list|, name|listener argument_list|, name|DEFAULT_MONITOR_DELAY argument_list|, literal|false argument_list|, literal|true argument_list|, literal|4096 argument_list|) expr_stmt|; name|this operator|. name|parser operator|= operator|new name|CSVParser argument_list|( name|separator argument_list|, name|quoteChar argument_list|, name|escape argument_list|, name|strictQuotes argument_list|, name|ignoreLeadingWhiteSpace argument_list|) expr_stmt|; name|this operator|. name|skipLines operator|= name|line expr_stmt|; try|try block|{ comment|// wait for tailer to capture data name|Thread operator|. name|sleep argument_list|( name|DEFAULT_MONITOR_DELAY argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|InterruptedException name|e parameter_list|) block|{ throw|throw operator|new name|RuntimeException argument_list|( name|e argument_list|) throw|; block|} block|} comment|/** * Reads the next line from the buffer and converts to a string array. * * @return a string array with each comma-separated element as a separate entry. * * @throws IOException if bad things happen during the read */ annotation|@ name|Override specifier|public name|String index|[] name|readNext parameter_list|() throws|throws name|IOException block|{ name|String index|[] name|result init|= literal|null decl_stmt|; do|do block|{ name|String name|nextLine init|= name|getNextLine argument_list|() decl_stmt|; if|if condition|( name|nextLine operator|== literal|null condition|) block|{ return|return literal|null return|; block|} name|String index|[] name|r init|= name|parser operator|. name|parseLineMulti argument_list|( name|nextLine argument_list|) decl_stmt|; if|if condition|( name|r operator|. name|length operator|> literal|0 condition|) block|{ if|if condition|( name|result operator|== literal|null condition|) block|{ name|result operator|= name|r expr_stmt|; block|} else|else block|{ name|String index|[] name|t init|= operator|new name|String index|[ name|result operator|. name|length operator|+ name|r operator|. name|length index|] decl_stmt|; name|System operator|. name|arraycopy argument_list|( name|result argument_list|, literal|0 argument_list|, name|t argument_list|, literal|0 argument_list|, name|result operator|. name|length argument_list|) expr_stmt|; name|System operator|. name|arraycopy argument_list|( name|r argument_list|, literal|0 argument_list|, name|t argument_list|, name|result operator|. name|length argument_list|, name|r operator|. name|length argument_list|) expr_stmt|; name|result operator|= name|t expr_stmt|; block|} block|} block|} do|while condition|( name|parser operator|. name|isPending argument_list|() condition|) do|; return|return name|result return|; block|} comment|/** * Reads the next line from the file. * * @return the next line from the file without trailing newline * * @throws IOException if bad things happen during the read */ specifier|private name|String name|getNextLine parameter_list|() throws|throws name|IOException block|{ return|return name|contentQueue operator|. name|poll argument_list|() return|; block|} comment|/** * Closes the underlying reader. * * @throws IOException if the close fails */ annotation|@ name|Override specifier|public name|void name|close parameter_list|() throws|throws name|IOException block|{ block|} comment|/** Watches for content being appended to a CSV file. */ specifier|private specifier|static class|class name|CsvContentListener extends|extends name|TailerListenerAdapter block|{ specifier|final name|Queue argument_list|< name|String argument_list|> name|contentQueue decl_stmt|; name|CsvContentListener parameter_list|( name|Queue argument_list|< name|String argument_list|> name|contentQueue parameter_list|) block|{ name|this operator|. name|contentQueue operator|= name|contentQueue expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|handle parameter_list|( name|String name|line parameter_list|) block|{ name|this operator|. name|contentQueue operator|. name|add argument_list|( name|line argument_list|) expr_stmt|; block|} block|} block|} end_class end_unit
[![build](https://github.com/AhmedBenCharrada/gojob/actions/workflows/build.yml/badge.svg)](https://github.com/AhmedBenCharrada/gojob/actions/workflows/build.yml) [![codecov](https://codecov.io/gh/AhmedBenCharrada/gojob/branch/main/graph/badge.svg?token=18JQESVC3P)](https://codecov.io/gh/AhmedBenCharrada/gojob) --- # GOJOB A small golang library that offers: - A customizable retry function. ```go fn := func(_ context.Context) (string, error) { return "", fmt.Errorf("breaking error") } res, err := gojob.Run( context.TODO(), fn, gojob.WithMaxTries(3), gojob.WithMaxDelay(2*time.Second), gojob.WithExitFn(func(err error) bool { return err.Error() == "breaking error" }), ) ``` - A custom typed sync.Map wrapper. ```go m := gojob.Map[string, string]{} // add item m.Put("key", "value") // get an item v, ok := m.Get("k") // get size size := m.Len() // range through item and handle. m.Range(func(k string, v string) error{ // handle }) // delete an item m.Remove("key") ``` - A custom worker pool. ```go // Create a worker-pool with a max of 30 worker and a job buffer size of 1000. pool := gojob.NewPool(context.TODO(), 30, 1000) // Add 10 workers. err := pool.AddWorkers(10) // Start the worker-pool. pool.Start() // Create a job. job := func(ctx context.Context) { // do something } // Push the job to the worker pool. pErr := pool.Push(job) // Delete 5 workers. dErr = pool.DeleteWorkers(5) // Stop the worker-pool. pool.Stop() ```
class Detail_Posting_Info { final int announcement_id; final String announcement_title; final String created_time; final int writer_id; final int group_id; final String content; Detail_Posting_Info({ required this.announcement_id, required this.announcement_title, required this.created_time, required this.writer_id, required this.group_id, required this.content }); factory Detail_Posting_Info.fromJson(Map<String, dynamic> json) { return Detail_Posting_Info( announcement_id: int.parse(json["announcement_id"].toString()), announcement_title: json["announcement_title"].toString(), created_time: json["created_time"].toString(), writer_id: int.parse(json["writer_id"].toString()), group_id: int.parse(json["group_id"].toString()), content: json["content"].toString(), ); } Map<String, dynamic> toJson() { return { "announcement_id": this.announcement_id, "announcement_title": this.announcement_title, "created_time": this.created_time, "writer_id": this.writer_id, "group_id": this.group_id, "content": this.content, }; } }
import React, { useState, useEffect } from "react"; import Header from "../Components/Header"; import Card from "../Components/Card"; import Pagination from "../Components/Pagination"; import { fetchGamesData } from "../Api/FetchApi"; const Home = () => { const [games, setGames] = useState([]); const [currentPage, setCurrentPage] = useState(1); const itemsPerPage = 10; useEffect(() => { fetchGamesData() .then((data) => setGames(data)) .catch((error) => console.log(error)); }, []); // Calculate the index range for the current page const indexOfLastItem = currentPage * itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage; const currentItems = games.slice(indexOfFirstItem, indexOfLastItem); // Calculate the total number of pages const totalPages = Math.ceil(games.length / itemsPerPage); // Function to handle page changes const onPageChange = (pageNumber) => { if (pageNumber >= 1 && pageNumber <= totalPages) { setCurrentPage(pageNumber); } }; return ( <> <div className="d-flex flex-column min-vh-100"> <Header /> <div className="container mt-5 mb-5 flex-grow-1"> <div className="row justify-content-evenly"> {currentItems.map((game, index) => ( <div className="col-lg-3 col-sm-7 col-md-3 m-2 w-350" key={index}> <Card game={game} /> </div> ))} </div> <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={onPageChange} /> </div> </div> </> ); }; export default Home;
import PropTypes from 'prop-types' import React from 'react' function Button({children, version, type, isDisabled}) { return ( <button type={type} disabled={isDisabled} className={`btn btn-${version}`} > {children} </button> ) } Button.defaultProps = { version: 'primary', type: 'button', isDisabled: false } Button.propTypes = { version: PropTypes.string , type: PropTypes.string, isDisabled: PropTypes.bool, children: PropTypes.node.isRequired } export default Button
from flask import Flask, render_template, request from PIL import Image import PIL import numpy as np app = Flask(__name__) def find_most_common_colors(image_path): # Open the image file image = Image.open(image_path) def find_most_common_colors(image_path, num_colors=5): image = Image.open(image_path) image = image.convert('RGB') # Convert image to RGB mode # Resize the image to a smaller size for faster processing image.thumbnail((200, 200)) # Convert image to a NumPy array image_array = np.array(image) # Flatten the array to a 2D shape flattened_array = image_array.reshape(-1, 3) # Count the occurrence of each color unique_colors, counts = np.unique(flattened_array, axis=0, return_counts=True) # Sort the colors based on their counts in descending order sorted_colors = sorted(zip(unique_colors, counts), key=lambda x: x[1], reverse=True) # Extract the most common colors most_common_colors = sorted_colors[:num_colors] print(most_common_colors) return most_common_colors @app.route('/', methods=['GET', 'POST']) def upload_image(): if request.method == 'POST': if 'image' not in request.files: return render_template('index.html', error='No image file provided.') file = request.files['image'] if not file.filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')): return render_template('index.html', error='Only image files (JPG, PNG, GIF) are allowed.') image_path = 'static/uploaded_image.jpg' try: file.save(image_path) except IOError: return render_template('index.html', error='Error saving the uploaded image.') try: most_common_colors = find_most_common_colors(image_path) except PIL.UnidentifiedImageError: return render_template('index.html', error='Invalid image file.') return render_template('index.html', image_path=image_path, colors=most_common_colors) return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
import { building } from '$app/environment'; export default class Cache { private id: string private cache: Record<string, [any, number]> = {} public constructor(id: string) { this.id = id; if (!building && globalThis.localStorage) { const data = localStorage.getItem(this.storageName); this.cache = data ? JSON.parse(data) : {}; } } public async use<T>(id: string, func: () => Promise<T>, age: number = 0): Promise<T> { const now = Date.now(); const cached = this.cache[id]; if (cached) { const expire = cached[1]; if (expire === -1 || expire > now) return Promise.resolve(cached[0]); } const result = await func(); this.set(id, result, age, now); return result; } public get<T>(id: string): T | undefined { return this.cache[id]?.[0]; } public set<T>(id: string, value: T, age: number = 0, now?: number) { const cantExpire = age === -1; if (age > 0 || cantExpire) { this.cache[id] = [value, cantExpire ? -1 : (now ?? Date.now()) + age]; this.save(); } return value; } public isValid(id: string) { const obj = this.cache[id]; if (!obj) return false; const date = obj[1]; return date === -1 || date > Date.now(); } public invalidate(id: string) { this.log('invalidating', id); delete this.cache[id]; this.save(); } public invalidateAll() { this.log('invalidating all items'); this.cache = {}; this.save(); } private log(...args: string[]) { console.log(`[cache:${this.id}]:`, ...args); } private save() { if (!building && globalThis.localStorage) { localStorage.setItem(this.storageName, JSON.stringify(this.cache)); this.log('saved cache to local storage'); } } private get storageName() { return `cache_${this.id}`; } }
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from icecream import ic class GraphAttentionLayer(nn.Module): """ Simple GAT layer, similar to https://arxiv.org/abs/1710.10903 """ def __init__(self, in_features, out_features, dropout, alpha, concat=True): super(GraphAttentionLayer, self).__init__() self.dropout = dropout self.in_features = in_features self.out_features = out_features self.alpha = alpha self.concat = concat self.W = nn.Parameter(torch.empty(size=(in_features, out_features))) nn.init.xavier_uniform_(self.W.data, gain=1.414) self.a = nn.Parameter(torch.empty(size=(2 * out_features, 1))) # ic(self.a.size()) # [256, 1] -> [2*hid_dim, 1] nn.init.xavier_uniform_(self.a.data, gain=1.414) self.leakyrelu = nn.LeakyReLU(self.alpha) def forward(self, h, adj): Wh = torch.matmul(h, self.W) # h.shape: (node_num, in_features), Wh.shape: (node_num, hid_dim) e = self._prepare_attentional_mechanism_input(Wh) # 16*116*116: original attention matrix without mask and softmax # inner_product: # e = torch.matmul(Wh, Wh.transpose(2, 1)) # gate + inner_product: # e1 = self._prepare_attentional_mechanism_input(Wh) # e2 = torch.matmul(Wh, Wh.transpose(2, 1)) # e2 = F.relu(e2) # e = torch.matmul(e1, e2) zero_vec = -9e15*torch.ones_like(e) # mask matrix attention = torch.where(adj > 0, e, zero_vec) # attention masked attention = F.softmax(attention, dim=2) # attention matrix shape: bs*ns*fs -> [16, 116, 116] attention = F.dropout(attention, self.dropout, training=self.training) # 16*116*116 h_prime = torch.matmul(attention, Wh) # broadcast, h_prime: 16*116*128 if self.concat: return F.elu(h_prime) else: # return h_prime, attention return h_prime, attention # 这个是经过linear层进行类似取平均之后的attention mat, 3*128->128 def _prepare_attentional_mechanism_input(self, Wh): # Wh.shape (N, out_feature) # self.a.shape (2 * out_feature, 1) # Wh1&2.shape (N, 1) # e.shape (N, N) # 验证:得到e的过程中,不同样本互不干扰 Wh1 = torch.matmul(Wh, self.a[:self.out_features, :]) Wh2 = torch.matmul(Wh, self.a[self.out_features:, :]) # broadcast add e = Wh1 + Wh2.transpose(2, 1) # 16*116*116 # e = torch.matmul(Wh1, Wh2.transpose(2, 1)) return self.leakyrelu(e) def __repr__(self): return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')' class SpecialSpmmFunction(torch.autograd.Function): """Special function for only sparse region backpropataion layer.""" @staticmethod def forward(ctx, indices, values, shape, b): assert indices.requires_grad == False a = torch.sparse_coo_tensor(indices, values, shape) ctx.save_for_backward(a, b) ctx.N = shape[0] return torch.matmul(a, b) @staticmethod def backward(ctx, grad_output): a, b = ctx.saved_tensors grad_values = grad_b = None if ctx.needs_input_grad[1]: grad_a_dense = grad_output.matmul(b.t()) edge_idx = a._indices()[0, :] * ctx.N + a._indices()[1, :] grad_values = grad_a_dense.view(-1)[edge_idx] if ctx.needs_input_grad[3]: grad_b = a.t().matmul(grad_output) return None, grad_values, None, grad_b class SpecialSpmm(nn.Module): def forward(self, indices, values, shape, b): return SpecialSpmmFunction.apply(indices, values, shape, b) class SpGraphAttentionLayer(nn.Module): """ Sparse version GAT layer, similar to https://arxiv.org/abs/1710.10903 """ def __init__(self, in_features, out_features, dropout, alpha, concat=True): super(SpGraphAttentionLayer, self).__init__() self.in_features = in_features self.out_features = out_features self.alpha = alpha self.concat = concat self.W = nn.Parameter(torch.zeros(size=(in_features, out_features))) nn.init.xavier_normal_(self.W.data, gain=1.414) self.a = nn.Parameter(torch.zeros(size=(1, 2 * out_features))) nn.init.xavier_normal_(self.a.data, gain=1.414) self.dropout = nn.Dropout(dropout) self.leakyrelu = nn.LeakyReLU(self.alpha) self.special_spmm = SpecialSpmm() def forward(self, input, adj): dv = 'cuda' if input.is_cuda else 'cpu' N = input.size()[0] edge = adj.nonzero().t() h = torch.mm(input, self.W) # h: N x out assert not torch.isnan(h).any() # Self-attention on the nodes - Shared attention mechanism edge_h = torch.cat((h[edge[0, :], :], h[edge[1, :], :]), dim=1).t() # edge: 2*D x E edge_e = torch.exp(-self.leakyrelu(self.a.mm(edge_h).squeeze())) assert not torch.isnan(edge_e).any() # edge_e: E e_rowsum = self.special_spmm(edge, edge_e, torch.Size([N, N]), torch.ones(size=(N, 1), device=dv)) # e_rowsum: N x 1 edge_e = self.dropout(edge_e) # edge_e: E h_prime = self.special_spmm(edge, edge_e, torch.Size([N, N]), h) assert not torch.isnan(h_prime).any() # h_prime: N x out h_prime = h_prime.div(e_rowsum) # h_prime: N x out assert not torch.isnan(h_prime).any() if self.concat: # if this layer is not last layer, return F.elu(h_prime) else: # if this layer is last layer, return h_prime def __repr__(self): return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'
import { MdKeyboardArrowDown, MdKeyboardArrowUp } from "react-icons/md"; import NavBar from "./component/NavBar"; import { Routes , Route} from 'react-router-dom' import CountryCard from "./component/CountryCard"; import axios from "axios"; import { IoSearch } from "react-icons/io5"; import { useEffect, useState } from "react"; import Countryinfo from "./component/Countryinfo"; const App = () => { const [countries, setCountries] = useState({}); const [isActive, setIsActive] = useState(false); useEffect(() => { axios .get("http://localhost:4000/getAllCountries") .then(function (countries) { setCountries(countries.data); }) .catch((err) => console.log(err)); }, []); const onChangeHandler = async (e) => { let keyword = e.target.value; axios .get(`http://localhost:4000/getCountryByName/${keyword}`) .then(function (response) { setCountries(response.data); }) .catch((err) => console.log(err)); }; const dropDownClickHandler = (e) => { const dropDownValue = e.target.textContent; axios.get(`http://localhost:4000/getCountriesByRegion/${dropDownValue}`) .then((response) => { setCountries(response.data) }) } return ( <div className="w-full h-full bg-Light_100-0 dark:bg-Dark_200-0"> <div className="lg:w-[1440px] lg:mx-auto bg-Light_200-0 dark:bg-Dark_200-0 dark:shadow-2xl dark:shadow-slate-700"> <NavBar /> <div className="flex justify-between px-2"> <div className="w-[30rem] h-11 mt-10 py-2 px-4 border flex justify-between hover:shadow-xl rounded bg-Light_200-0 text-Dark_300-0 dark:bg-Dark_100-0 dark:text-Light_200-0 dark:border-Dark_200-0 dark:outline-Dark_200-0 dark:shadow-lg dark:shadow-slate-700 dark:hover:shadow-xl dark:hover:shadow-slate-700"> <IoSearch className="mt-[0.3rem]"/> <input onChange={onChangeHandler} className="outline-none w-[27rem] ml-2 pl-2 placeholder:font-normal font-Nunito bg-Light_200-0 dark:bg-Dark_100-0 " type="text" name="Search" id="Search" placeholder="Search for a country..." /> </div> <div className="mt-10 bg-white border w-60 rounded-tl rounded-tr px-3 py-2 flex justify-between align-middle hover:shadow-xl relative text-Dark_300-0 dark:bg-Dark_100-0 dark:text-Light_200-0 dark:shadow-slate-700 dark:shadow-lg dark:hover:shadow-xl dark:border-Dark_200-0 dark:hover:shadow-slate-700"> <button className="w-full flex justify-between font-Nunito font-medium" onClick={() => setIsActive((prev) => !prev)} > Filter by Region {isActive ? ( <MdKeyboardArrowUp className="mt-1" /> ) : ( <MdKeyboardArrowDown className="mt-1" /> )} </button> {isActive && <div className="bg-white border absolute top-12 flex flex-col items-start rounded-bl rounded-br px-3 py-2 w-60 right-0 left-0 hover:shadow-xl dark:bg-Dark_100-0 dark:border-Dark_200-0"> <div className="py-1 hover:bg-blue-100 w-full px-1 rounded"> <h3 onClick={dropDownClickHandler} id="dropDown" className="dark:hover:text-Dark_300-0">Asia</h3> </div> <div className="py-1 hover:bg-blue-100 w-full px-1 rounded"> <h3 onClick={dropDownClickHandler} id="dropDown" className="dark:hover:text-Dark_300-0">Europe</h3> </div> <div className="py-1 hover:bg-blue-100 w-full px-1 rounded"> <h3 onClick={dropDownClickHandler} id="dropDown" className="dark:hover:text-Dark_300-0">Africa</h3> </div> <div className="py-1 hover:bg-blue-100 w-full px-1 rounded"> <h3 onClick={dropDownClickHandler} id="dropDown" className="dark:hover:text-Dark_300-0">Oceania</h3> </div> <div className="py-1 hover:bg-blue-100 w-full px-1 rounded"> <h3 onClick={dropDownClickHandler} id="dropDown" className="dark:hover:text-Dark_300-0">Antarctic Ocean</h3> </div> </div>} </div> </div> <Routes> <Route path="/" element={<CountryCard data={countries}/>} /> <Route path="/Countryinfo/:_id" element={<Countryinfo />}/> </Routes> </div> </div> ); }; export default App;
import { useState } from 'react'; import Timer from './components/Timer'; import Settings from './components/Settings/Settings'; import SettingsContext from './context/SettingsContext'; import './App.css'; function App() { const [showSettings, setShowSettings] = useState(false); const [workMinutes, setWorkMinutes] = useState(45); const [breakMinutes, setBreakMinutes] = useState(15); return ( <SettingsContext.Provider value={{ workMinutes, breakMinutes, setWorkMinutes, setBreakMinutes, showSettings, setShowSettings, }} > {showSettings ? <Settings /> : <Timer />} </SettingsContext.Provider> ); } export default App;
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouterx.webapp.request; import lombok.Getter; import lombok.Setter; import lombok.ToString; import scouterx.webapp.framework.client.server.ServerManager; import scouterx.webapp.framework.exception.ErrorState; import javax.validation.constraints.NotNull; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; /** * @author Gun Lee (gunlee01@gmail.com) on 2017. 8. 27. */ @Getter @Setter @ToString public class LatestCounterRequest { private final int limitRangeSec = 60 * 60; //1 hour private int serverId; @NotNull @PathParam("counter") private String counter; @NotNull @PathParam("latestSec") private int latestSec; @QueryParam("serverId") public void setServerId(int serverId) { this.serverId = ServerManager.getInstance().getServerIfNullDefault(serverId).getId(); } public void validate() { if (latestSec > limitRangeSec) { throw ErrorState.VALIDATE_ERROR.newBizException("query range should be lower than " + limitRangeSec + " seconds!"); } } }
import { DynamicModule, Module } from '@nestjs/common'; import { DatabaseFileRepository } from '../../../data/repositories/file.repository'; import { DatabaseMusicRepository } from '../../../data/repositories/music.repository'; import { RepositoriesModule } from '../../../data/repositories/repositories.module'; import { CreateMusicUseCase, DeleteMusicUseCase, FindAllMusicUseCase, FindOneMusicUseCase, UpdateMusicFileUseCase, UpdateMusicUseCase, } from '../../../domain/use-cases/music'; import { EnvironmentConfigService } from '../../../infra/config/environment-config/environment-config.service'; import { JwtModule } from '../../../infra/services/jwt/jwt.module'; import { S3ConfigModule } from '../../../infra/services/s3/s3.module'; import { S3Service } from '../../../infra/services/s3/s3.service'; import { EnvironmentConfigModule } from '../../config/environment-config/environment-config.module'; import { CacheConfigModule } from '../../config/redis/cache.module'; import { CacheService } from '../../config/redis/cache.service'; import { LoggerModule } from '../../logger/logger.module'; import { LoggerService } from '../../logger/logger.service'; import { BcryptModule } from '../../services/bcrypt/bcrypt.module'; import { BcryptService } from '../../services/bcrypt/bcrypt.service'; import { UseCaseProxy } from '../usecase-proxy'; @Module({ imports: [ LoggerModule, EnvironmentConfigModule, RepositoriesModule, BcryptModule, CacheConfigModule, JwtModule, S3ConfigModule, ], }) export class MusicUsecasesProxyModule { static GET_MUSIC_USECASES_PROXY = 'getMusicUsecasesProxy'; static GET_MUSICS_USECASES_PROXY = 'getMusicsUsecasesProxy'; static POST_MUSIC_USECASES_PROXY = 'postMusicUsecasesProxy'; static PUT_MUSIC_USECASES_PROXY = 'putMusicUsecasesProxy'; static PUT_MUSIC_FILE_USECASES_PROXY = 'putMusicFileUsecasesProxy'; static DELETE_MUSIC_USECASES_PROXY = 'deleteMusicUsecasesProxy'; static register(): DynamicModule { return { module: MusicUsecasesProxyModule, providers: [ //GET { inject: [DatabaseMusicRepository, CacheService], provide: MusicUsecasesProxyModule.GET_MUSICS_USECASES_PROXY, useFactory: ( repository: DatabaseMusicRepository, cacheService: CacheService, ) => new UseCaseProxy(new FindAllMusicUseCase(repository, cacheService)), }, //GET { inject: [DatabaseMusicRepository, CacheService], provide: MusicUsecasesProxyModule.GET_MUSIC_USECASES_PROXY, useFactory: ( repository: DatabaseMusicRepository, cacheService: CacheService, ) => new UseCaseProxy(new FindOneMusicUseCase(repository, cacheService)), }, //POST { inject: [ LoggerService, DatabaseMusicRepository, DatabaseFileRepository, S3Service, EnvironmentConfigService, ], provide: MusicUsecasesProxyModule.POST_MUSIC_USECASES_PROXY, useFactory: ( logger: LoggerService, repository: DatabaseMusicRepository, fileRepository: DatabaseFileRepository, s3Service: S3Service, environmentConfig: EnvironmentConfigService, ) => new UseCaseProxy( new CreateMusicUseCase( logger, repository, fileRepository, s3Service, environmentConfig, ), ), }, //PUT { inject: [LoggerService, DatabaseMusicRepository, BcryptService], provide: MusicUsecasesProxyModule.PUT_MUSIC_USECASES_PROXY, useFactory: ( logger: LoggerService, repository: DatabaseMusicRepository, ) => new UseCaseProxy(new UpdateMusicUseCase(logger, repository)), }, //PUT { inject: [ LoggerService, DatabaseMusicRepository, DatabaseFileRepository, S3Service, EnvironmentConfigService, ], provide: MusicUsecasesProxyModule.PUT_MUSIC_FILE_USECASES_PROXY, useFactory: ( logger: LoggerService, repository: DatabaseMusicRepository, fileRepository: DatabaseFileRepository, s3Service: S3Service, config: EnvironmentConfigService, ) => new UseCaseProxy( new UpdateMusicFileUseCase( logger, repository, fileRepository, s3Service, config, ), ), }, //DELETE { inject: [ LoggerService, DatabaseMusicRepository, S3Service, EnvironmentConfigService, DatabaseFileRepository, ], provide: MusicUsecasesProxyModule.DELETE_MUSIC_USECASES_PROXY, useFactory: ( logger: LoggerService, repository: DatabaseMusicRepository, s3Service: S3Service, config: EnvironmentConfigService, fileRepository: DatabaseFileRepository, ) => new UseCaseProxy( new DeleteMusicUseCase( logger, repository, s3Service, config, fileRepository, ), ), }, ], exports: [ MusicUsecasesProxyModule.GET_MUSICS_USECASES_PROXY, MusicUsecasesProxyModule.GET_MUSIC_USECASES_PROXY, MusicUsecasesProxyModule.POST_MUSIC_USECASES_PROXY, MusicUsecasesProxyModule.PUT_MUSIC_USECASES_PROXY, MusicUsecasesProxyModule.PUT_MUSIC_FILE_USECASES_PROXY, MusicUsecasesProxyModule.DELETE_MUSIC_USECASES_PROXY, ], }; } }
import React from 'react'; import { mount } from 'enzyme'; import { Provider } from 'react-redux'; import { Header } from '../../../../src/components/v1/DMS/DocumentView'; import renderer from 'react-test-renderer'; import store from '../../../../src/utils/store'; import { authMock, buildingProfileMock, documentDetailsMock, invoiceHeaderProps, invoiceMock, initialStateMock, sitePlansMock } from '../../../../__mocks__'; const initialState = { ...initialStateMock, auth: authMock, buildingProfile: { building: buildingProfileMock }, dms: { currentDocument: invoiceMock }, spNumbers: { orgSpNumbers: sitePlansMock } }; const props = { ...invoiceHeaderProps, ...documentDetailsMock, status: 'under_review', lot: documentDetailsMock.lot, name: documentDetailsMock.name, toggleEditMode: jest.fn(), invoice: invoiceMock.invoice, buildingData: buildingProfileMock, buildingProfile: buildingProfileMock, ownerId: invoiceMock.owner_id, strataManager: buildingProfileMock.strata_manager, currentUser: authMock.currentUser, spList: sitePlansMock, sharedWith: documentDetailsMock.sharedWith, openModal: jest.fn(), setModalType: jest.fn(), setKeepDropdownOpen: jest.fn(), isInvoiceOverrider: true, isUnchangeableSourceType: false }; const mountComponent = (props, state = initialState) => { const mockStore = store(state); return mount( <Provider store={mockStore}> <Header {...props} /> </Provider> ); }; describe('InvoicePreview > Header', () => { describe('Approve invoice button', () => { const target = 'button.approve-invoice-button'; it('will not render', () => { const subject = mountComponent({ ...props, hasVoted: true, canVote: true, isWithCurrentUser: false }); expect(subject.find(target).length).toEqual(0); }); it('will render', () => { const subject = mountComponent({ ...props }); expect(subject.find(target).length).toEqual(1); }); it('can click', () => { const subject = mountComponent({ ...props }); subject.find(target).simulate('click'); expect(props.openModal).toHaveBeenCalledTimes(1); expect(props.setModalType).toHaveBeenCalledWith('approve'); }); }); describe('override approve button', () => { const target = 'button.override-approve-button'; it('will not render', () => { const subject = mountComponent({ ...props }); expect(subject.find(target).length).toEqual(0); }); it('will render', () => { const subject = mountComponent({ ...props, hasVoted: true, canVote: true, isWithCurrentUser: false }); expect(subject.find(target).length).toEqual(1); }); it('can click', () => { const subject = mountComponent({ ...props, hasVoted: true, canVote: true, isWithCurrentUser: false }); subject.find(target).simulate('click'); expect(props.openModal).toHaveBeenCalledTimes(1); }); }); // TODO: this test is breaking because of Tooltip library // Snapshot // it('renders correctly', () => { // const subject = mountComponent({ ...props }); // const tree = renderer.create(subject).toJSON(); // expect(tree).toMatchSnapshot(); // }); });
<!DOCTYPE HTML> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <!-- FontAwesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/fontawesome.min.css" rel="stylesheet" type="text/css"/> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/regular.min.css" rel="stylesheet" type="text/css"/> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" rel="stylesheet" type="text/css"/> <link rel="stylesheet" href="/styles/pages/_style-base.css"> <link rel="stylesheet" href="/styles/pages/_game-pitching.css"> <title th:text="${team.teamNameLong}"></title> </head> <body> <div class="game-pitching-wrapper center-content"> <h3>Pitching Statistics</h3> <table border="1"> <thead> <tr> <th>#</th> <th>Player</th> <th>W</th> <th>L</th> <th>ER</th> <th>IP</th> <th>ERA</th> <th>SV</th> <th>SVO</th> <th>H</th> <th>R</th> <th>HR</th> <th>BB</th> <th>SO</th> <th>AVG</th> <th>WHIP</th> </tr> </thead> <tbody> <tr th:each="tempPitchingDetails : ${gamePitchingDetailsMap}"> <td th:text="${tempPitchingDetails.key.jerseyNumber}"/> <td th:text="${tempPitchingDetails.key.firstName} + ' ' + ${tempPitchingDetails.key.lastName}"/> <td th:text="${tempPitchingDetails.value.wins}"/> <td th:text="${tempPitchingDetails.value.loses}"/> <td th:text="${tempPitchingDetails.value.earnedRuns}"/> <td th:text="${tempPitchingDetails.value.inningsPitched}"/> <td th:text="${tempPitchingDetails.value.earnedRunAverage}"/> <td th:text="${tempPitchingDetails.value.saves}"/> <td th:text="${tempPitchingDetails.value.saveOpportunities}"/> <td th:text="${tempPitchingDetails.value.hits}"/> <td th:text="${tempPitchingDetails.value.runs}"/> <td th:text="${tempPitchingDetails.value.homeRuns}"/> <td th:text="${tempPitchingDetails.value.basesOnBalls}"/> <td th:text="${tempPitchingDetails.value.strikeOuts}"/> <td th:text="${tempPitchingDetails.value.average}"/> <td th:text="${tempPitchingDetails.value.whips}"/> </tr> </tbody> </table> <form action="#" th:action="@{/games/showGameInfo}" method="POST"> <input type="hidden" name="gameId" th:value="${gameId}"/> <button class="btn-link" type="submit"> <i class="far fa-arrow-alt-circle-left"></i> Back </button> </form> </div> </body> </html>
from fastapi import FastAPI, File, UploadFile from DataIntegration import LLM import openai import os # To run app, Use: # uvicorn app:app --reload # api_key = "" # os.environ["OPENAI_API_KEY"] = api_key # openai.api_key = os.environ["OPENAI_API_KEY"] app = FastAPI() model = LLM() @app.get("/") def read_root(): return { "response": "Server is running.\n To read the documentation, go to http://127.0.0.1:8000/docs#/" } """ POST { user_id: , source_name: , url: } or: POST { user_id: , source_name: , file: } """ @app.post("/add_source/") async def add_source( user_id: str, source_name: str, url: str = None, file: UploadFile = None ): if url is not None: return model.add_to_index(user_id, source_name, url) elif file is not None and source_name == "txt": return model.add_to_index(user_id, source_name, file=file) else: return {"response": "Please provide either a URL or a file."} # http://127.0.0.1:8000/get_response/?&user_id=101&prompt=What happend to the Maergo rebrand? # http://127.0.0.1:8000/get_response/?&user_id=101&prompt=How can ecommerce retailers reduce their carbon footprint? """ GET { user_id: , prompt: , } """ @app.get("/get_response/") async def get_response(user_id: str, prompt: str): response = model.generate_response(user_id, prompt) if type(response) == dict: return {"response": response["response"]} elif type(response) == str: return {"response": response} return {"response": response.response} @app.get("/reset_chat/") async def get_response(session: str): model.clear_engine(session) return {"response": "Chat Reset"}
module Printable def print_info puts "Information about the object:" instance_variables.each do |var| puts "#{var}: #{instance_variable_get(var)}" end end end class Person include Printable attr_accessor :name, :age, :gender def initialize(name, age, gender) @name = name @age = age @gender = gender end def introduce puts "Hello, my name is #{@name}, I'm #{@age} years old, and I am #{@gender}." end end obj = Person.new("Pablo", 20, "male") obj.print_info
# dotbackup ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/dotbackup) [![PyPI - Version](https://img.shields.io/pypi/v/dotbackup)](https://pypi.org/project/dotbackup) [![PyPI - Downloads](https://img.shields.io/pypi/dm/dotbackup)](https://pypi.org/project/dotbackup) [![AUR version](https://img.shields.io/aur/version/dotbackup)](https://aur.archlinux.org/packages/dotbackup) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![Lint: flake8](https://img.shields.io/badge/lint-flake8-blueviolet)](https://github.com/PyCQA/flake8) [![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1)](https://pycqa.github.io/isort) [![Test: pytest](https://img.shields.io/badge/test-pytest-orange)](https://pytest.org) [![Codecov](https://codecov.io/gh/jaxvanyang/dotbackup/graph/badge.svg)](https://codecov.io/gh/jaxvanyang/dotbackup) Usually people maintain backup and setup scripts along with their dotfiles. But these scripts always contain a lot of repeat codes, and writing them is not fun! `dotbackup` and `dotsetup` are here to help. With these two tools, you only need to write a simple configuration and they will know how to back up and set up your dotfiles. You can read [dotbackup(1)](dotbackup.1.adoc) and [dotsetup(1)](dotsetup.1.adoc) for details. ## Highlights - Simple configuration. - Custom hooks. - Detailed logs. ## Installation You can install from one of these package managers: - [PyPI](https://pypi.org/project/dotbackup) - [AUR](https://aur.archlinux.org/packages/dotbackup) Installing from a package manager gives you the two commands - `dotbackup` and `dotsetup`, and the manpages. But you can also download this single script: [dotbackup.py](./src/dotbackup.py). In fact, `dotbackup` and `dotsetup` are just shortcut commands of `dotbackup.py`, which means that `dotbackup` is equivalent to `dotbackup.py backup` and `dotsetup` is equivalent to `dotbackup.py setup`. ## Quick Start Write a simple configuration and place it to `~/.config/dotbackup/dotbackup.yml`: ```yml backup_dir: ~/backup apps: vim: files: [~/.vimrc] nvim: files: - ~/.config/nvim/init.lua - ~/.config/nvim/lua ``` Do backup: ```console $ dotbackup INFO: doing vim backup... INFO: copying ~/.vimrc to /home/user/backup/.vimrc... INFO: doing nvim backup... INFO: copying ~/.config/nvim/init.lua to /home/user/backup/.config/nvim/init.lua... INFO: copying ~/.config/nvim/lua to /home/user/backup/.config/nvim/lua... ``` Do setup: ```console $ dotsetup INFO: doing vim setup... INFO: copying /home/user/backup/.vimrc to /home/user/.vimrc... INFO: doing nvim setup... INFO: copying /home/user/backup/.config/nvim/init.lua to /home/user/.config/nvim/init.lua... INFO: copying /home/user/backup/.config/nvim/lua to /home/user/.config/nvim/lua... ``` ## Documentation For more information, please read [dotbackup(1)](dotbackup.1.adoc) and [dotsetup(1)](dotsetup.1.adoc). ## Show Your Support If you're using dotbackup, consider adding the badge to your project's `README.md`: ``` [![dotbackup-managed](https://img.shields.io/badge/dotbackup-managed-blue)](https://github.com/jaxvanyang/dotbackup) ``` [![dotbackup-managed](https://img.shields.io/badge/dotbackup-managed-blue)](https://github.com/jaxvanyang/dotbackup)
<meta charset="utf-8" /> <script src="https://unpkg.com/vue"></script> <div id="app"> <p>{{ titulo }}</p> <button v-on:click="saudacao('oi gente...')"> Muda saudação </button> <p><a :href="site">Google</a></p> <p v-html="link"></p> </div> <!-- Comentário --> <script> new Vue({ el: "#app", data: { titulo: "Boa noite pessoal!!!!", site : "http://www.google.com", link: "<a href='http://www.google.com.br'>Google</a>" }, methods: { saudacao(msg) { this.titulo = msg; } } }) </script>
#!/usr/bin/python3 """This module contains operation function relating to book reserves""" import json from ....authentication.verify_token import oauth2_scheme from ....authentication.verify_token import verify_token from ....cursor.cursor import Cursor from ....cursor.redis_cursor import redis_cursor from ....openapi_meta.tag import Tags from ....pydantic_models.redis import ReserveBookModel from ....schemas.book import Book from ....schemas.librarian import Librarian from ....schemas.user import User from datetime import datetime from fastapi import APIRouter from fastapi import Depends from fastapi import HTTPException from fastapi import status from redis import Redis from typing import Annotated reserve_router = APIRouter() @reserve_router.get("/reserves", status_code=status.HTTP_200_OK, tags=[Tags.book], response_model=dict[str, list[ReserveBookModel]]) async def all_reserves(lib_id: str, token: Annotated[str, Depends(oauth2_scheme)], lib_cursor: Cursor = Depends(Cursor()), red_cursor: Redis = Depends(redis_cursor)): """route to get all book reserves""" token_dict = verify_token(token) if lib_id != token_dict["sub"]: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="access denied") librarian = lib_cursor.get(Librarian, lib_id) if not librarian: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="librarian not found") reserves = red_cursor.get("reserves") try: reserves = json.loads(reserves) reserves_out = {} for user_id, user_reserves in reserves.items(): user_book_list = [] for book_uuid, expire_delta in user_reserves.items(): book = lib_cursor.get(Book, book_uuid) book_dict = book.to_dict() book_dict["expire_date"] = datetime.fromisoformat(expire_delta) user_book_list.append(book_dict) reserves_out[user_id] = user_book_list return reserves_out except TypeError as t: return {} @reserve_router.get("/user-reserves", status_code=status.HTTP_200_OK, tags=[Tags.book], response_model=list[ReserveBookModel]) async def user_reserves(lib_id: str, user_id: str, token: Annotated[str, Depends(oauth2_scheme)], lib_cursor: Cursor = Depends(Cursor()), red_cursor: Redis = Depends(redis_cursor)): """route to get a users book reserves""" token_dict = verify_token(token) if lib_id != token_dict["sub"]: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="access denied") librarian = lib_cursor.get(Librarian, lib_id) if not librarian: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="librarian not found") user = lib_cursor.get(User, user_id) if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="user not found") reserves = red_cursor.get("reserves") try: reserves = json.loads(reserves) user_reserves = reserves.get(user_id) if not user_reserves: return [] user_book_list = [] for book_uuid, expire_delta in user_reserves.items(): book = lib_cursor.get(Book, book_uuid) book_dict = book.to_dict() book_dict["expire_date"] = datetime.fromisoformat(expire_delta) user_book_list.append(book_dict) return user_book_list except TypeError as t: return []
const Book = require("../../../models/social/book"); const bookHandler = require("./handler"); const { validationResult } = require("express-validator"); exports.createBook = async (req, res, next) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { const error = new Error(req.t("validation-failed")); error.statusCode = 422; error.data = errors.array(); throw error; } const BookObject = new Book({ name: req.body.name, description: req.body.description, author: req.body.author, categories: req.body.categories, imageUrl: req.body.imageUrl, pageCount: req.body.pageCount, }); const response = await bookHandler.createBook(BookObject, req.body.author, { bookExists: req.t("already-exists"), authorNotFound: req.t("author-is-not-exists") }); return res.status(201).json({ createdTime: response.createdAt, bookId: response.id }); } catch (error) { if (!error.statusCode) { error.statusCode = 500; } next(error); } }; exports.listBooks = async (req, res, next) => { try { const limit = req.query.limit; const page = req.query.page const response = await bookHandler.getBooks(limit, page); return res.status(200).json(response); } catch (error) { if (!error.statusCode) { error.statusCode = 500; } next(error); } }; exports.bookDetail = async (req, res, next) => { try { const bookId = req.params.id; const response = await bookHandler.findById(bookId, req.t("forbidden-book")); return res.status(200).json(response); } catch (error) { if (!error.statusCode) { error.statusCode = 500; } next(error); } }; exports.readABook = async (req, res, next) => { try { const bookId = req.params.bookId; const userId = req.user.user_id; const result = await bookHandler.readABook(bookId, userId, { forbiddenBook: req.t("forbidden-book"), forbiddenUser: req.t("forbidden-user"), alreadyRead: req.t("already-read-this-book") }); return res.status(201).json(); } catch (error) { if (!error.statusCode) { error.statusCode = 500; } next(error); } }; exports.removeReadBook = async (req, res, next) => { try { const bookId = req.params.bookId; const userId = req.user.user_id; const result = await bookHandler.removeReadBook(bookId, userId, { forbiddenBook: req.t("forbidden-book"), forbiddenUser: req.t("forbidden-user"), userDidNotRead: req.t("user-did-not-read-this-book") }); return res.status(201).json(); } catch (error) { if (!error.statusCode) { error.statusCode = 500; } next(error); } }; exports.listUserBooks = async (req, res, next) => { try { const limit = req.query.limit; const page = req.query.page var userId = req.params.id; if (!userId) { userId = req.user.user_id; } const response = await bookHandler.getUserBooks(limit, page, userId); return res.status(200).json(response); } catch (error) { if (!error.statusCode) { error.statusCode = 500; } next(error); } }; exports.commentToBook = async (req, res, next) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { const error = new Error(req.t("validation-failed")); error.statusCode = 422; error.data = errors.array(); throw error; } const bookId = req.params.bookId; const userId = req.user.user_id; const comment=req.body.comment; const result = await bookHandler.commentToBook(bookId, userId,comment, { forbiddenBook: req.t("forbidden-book"), forbiddenUser: req.t("forbidden-user") }); return res.status(201).json(); } catch (error) { if (!error.statusCode) { error.statusCode = 500; } next(error); } };
'use client'; import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import { FormEventHandler } from 'react'; type Props = { uid: string; }; export default function AddProductForm({ uid }: Props) { console.log(uid); const supabase = createClientComponentClient(); const addProduct: FormEventHandler<HTMLFormElement> = async (e) => { e.preventDefault(); const formData = new FormData(e.currentTarget); const imageFile = formData.get('image') as File; const title = String(formData.get('title')); const description = String(formData.get('description')); const fileExt = imageFile.name.split('.').pop(); const filePath = `${uid}-${Math.random()}.${fileExt}`; let { error: uploadError } = await supabase.storage .from('products') .upload(filePath, imageFile); if (uploadError) { throw uploadError; } const { data } = supabase.storage.from('products').getPublicUrl(filePath); let { error } = await supabase .from('products') .insert({ title, description, image_url: data.publicUrl }); if (error) { alert('Error adding product'); } }; return ( <form onSubmit={addProduct} className="flex gap-4 my-auto flex-col"> <label htmlFor="title">Title (Required)</label> <input type="text" required name="title" id="title" /> <label htmlFor="description">Description (Required)</label> <textarea name="description" required id="description" cols={30} rows={10} /> <label htmlFor="image">Upload Image (Required)</label> <input type="file" accept="image/*" required name="image" id="image" /> <button className="bg-gray-900 py-2 text-gray-100" type="submit"> Create Product </button> </form> ); }
import { DailyDetailModel } from '../../models/DailyDetailModel'; import { ICON_URL } from '../../services/url'; import './DailyDetailStyle.css'; interface DailyDetailProps { timeDetail: DailyDetailModel; tempUnit: string; date: string; time: string; } const DailyDetail = ({ timeDetail, date, time, tempUnit }: DailyDetailProps) => { const tempSymbol = tempUnit === 'metric' ? 'C' : 'F'; const windSpeedUnit = tempUnit === 'metric' ? 'mph' : 'km/h'; return ( <> <div id="data-container" className="d-flex row row-margin-0"> <div className="col-sm-5 col-12 d-flex align-items-start flex-column"> <p className="d-flex m-1 text align-items-end"> <span className="fs-5 m-1">{date} | </span> {time} </p> <div className="d-flex align-items-center"> <p className="fs-1" id="temp"> {' '} {Math.round(timeDetail.main.temp)}°{tempSymbol} </p> <img className="col" alt={'image'} src={`${ICON_URL}${timeDetail.weather[0].icon}@2x.png`} /> </div> </div> <div id="details" className="d-flex col-sm-7 col-12 p-sm-2 p-1 mt-sm-2 mb-sm-0 mb-2"> <div className="col d-flex align-items-start flex-column"> <p className="mb-auto"> Feels-like: {Math.round(timeDetail.main.feels_like)}°{tempSymbol} </p> <p>Humidity: {timeDetail.main.humidity}%</p> </div> <div className="col d-flex align-items-start flex-column"> <p className="mb-auto"> Wind: {timeDetail.wind.speed} {windSpeedUnit} </p> <p>Pressure: {timeDetail.main.pressure} mb</p> </div> </div> </div> </> ); }; export default DailyDetail;
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os from sklearn.ensemble import IsolationForest from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score, precision_recall_curve from sklearn.model_selection import train_test_split from sklearn.inspection import permutation_importance # Create results directory results_dir = 'creditResults' os.makedirs(results_dir, exist_ok=True) # Load dataset data = pd.read_csv('creditcard.csv') # Display basic information about the dataset print(data.info()) print(data.describe()) # Visualize the distribution of the target variable plt.figure(figsize=(6,4)) sns.countplot(x='Class', data=data) plt.title('Class Distribution') plt.savefig(os.path.join(results_dir, 'class_distribution.png')) plt.close() # Visualize data distribution data.hist(figsize=(20, 20), bins=50) plt.savefig(os.path.join(results_dir, 'data_distribution.png')) plt.close() # Correlation matrix to understand relationships corr_matrix = data.corr() plt.figure(figsize=(12,10)) sns.heatmap(corr_matrix, annot=False, cmap='coolwarm') plt.title('Correlation Matrix') plt.savefig(os.path.join(results_dir, 'correlation_matrix.png')) plt.close() # Preprocess data data = data.dropna() # Drop missing values features = data.drop('Class', axis=1) # Features are all columns except the target target = data['Class'] # Target is the 'Class' column # Standardize the features scaler = StandardScaler() features_scaled = scaler.fit_transform(features) # Train/test split X_train, X_test, y_train, y_test = train_test_split(features_scaled, target, test_size=0.2, random_state=16) # Train Isolation Forest model model = IsolationForest(contamination=0.001, random_state=16) model.fit(X_train) # Predict anomalies y_pred_train = model.predict(X_train) y_pred_test = model.predict(X_test) # Convert predictions from {-1, 1} to {0, 1} y_pred_train = [0 if x == 1 else 1 for x in y_pred_train] y_pred_test = [0 if x == 1 else 1 for x in y_pred_test] # Evaluate the model print("Training Data Classification Report") print(classification_report(y_train, y_pred_train)) print("Testing Data Classification Report") print(classification_report(y_test, y_pred_test)) # Confusion Matrix conf_matrix = confusion_matrix(y_test, y_pred_test) print("Confusion Matrix") print(conf_matrix) # Plot Confusion Matrix plt.figure(figsize=(6,4)) sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues') plt.xlabel('Predicted') plt.ylabel('Actual') plt.title('Confusion Matrix') plt.savefig(os.path.join(results_dir, 'confusion_matrix.png')) plt.close() # Additional Evaluation Metrics roc_auc = roc_auc_score(y_test, y_pred_test) print(f"ROC-AUC Score: {roc_auc}") precision, recall, _ = precision_recall_curve(y_test, y_pred_test) plt.plot(recall, precision, marker='.') plt.xlabel('Recall') plt.ylabel('Precision') plt.title('Precision-Recall Curve') plt.savefig(os.path.join(results_dir, 'precision_recall_curve.png')) plt.close() # Feature importance using permutation importance perm_importance = permutation_importance(model, X_test, y_test, n_repeats=10, random_state=42, scoring='accuracy') sorted_idx = perm_importance.importances_mean.argsort() plt.figure(figsize=(12,6)) plt.barh(np.array(features.columns)[sorted_idx], perm_importance.importances_mean[sorted_idx]) plt.xlabel("Permutation Importance") plt.title('Feature Importance (Permutation Importance)') plt.savefig(os.path.join(results_dir, 'feature_importance.png')) plt.close()
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { // $table->id(); $table->uuid('id')->primary(); $table->string('personnel_number'); $table->string('username'); $table->string('full_name'); $table->string('email')->unique(); $table->string('password'); // $table->timestamp('email_verified_at')->nullable(); // $table->enum('gender', ['general', 'male', 'female'])->default('general'); $table->enum('type', ['general', 'employee', 'vessel'])->default('general'); $table->enum('roles', ['admin', 'user', 'vessel'])->default('user'); $table->string('image')->nullable(); $table->string('remarks_user')->nullable(); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } };
<template> <div class="select-font"> <el-collapse accordion> <el-collapse-item name="1"> <template slot="title"> <div class="flex center plr10 space pointer"></div> <span>Font</span> </template> <div class="flex center space plr10"> <span>Font</span> <el-select class="plr10" v-model="value" @change="setFontFamily" placeholder="Select Font" > <el-option v-for="font in fonts" :key="font.value" :label="font.label" :value="font.value" :style="{ fontFamily: font.value }" > </el-option> </el-select> </div> </el-collapse-item> </el-collapse> </div> </template> <script> import { eventBus } from '../../services/eventbus.service.js'; export default { name: 'select-font', props: { cmp: [Object, Array], }, components: {}, data() { return { fonts: [ { value: 'abril', label: 'Abril', }, { value: 'almondNougat', label: 'Almond Nougat', }, { value: 'assistantBold', label: 'Assistant (Bold)', }, { value: 'assistantLight', label: 'Assistant (Light)', }, { value: 'caviarDreams', label: 'Caviar Dreams', }, { value: 'champagneLimousines', label: 'Champagne Limousines', }, { value: 'crimsonText', label: 'Crimson Text', }, { value: 'fredericka', label: 'Fredericka The Great', }, { value: 'raleway', label: 'Raleway', }, { value: 'robotomonoLight', label: 'RobotoMono Light', }, { value: 'robotomono', label: 'RobotoMono', }, { value: 'rubik', label: 'Rubik', }, { value: 'sacramento', label: 'Sacramento', }, { value: 'caudex', label: 'Caudex', }, { value: 'funcyKids', label: 'Funcy Kids', }, { value: 'kulo', label: 'Kulo', }, { value: 'pumpkins', label: 'Pumpkins', }, { value: 'romantika', label: 'Romantika', }, { value: 'sundayMorning', label: 'Sunday Morning', }, ], value: '', }; }, created() { this.value = this.cmp.style.fontFamily ? this.cmp.style.fontFamily : ''; }, methods: { setFontFamily(font) { this.cmp.style.fontFamily = font; eventBus.$emit('update-site'); eventBus.$emit('change-' + this.cmp.type); }, }, watch: { cmp: { deep: true, handler(newVal, oldVal) { if (newVal.id !== oldVal.id) { this.value = this.cmp.style.fontFamily ? this.cmp.style.fontFamily : ''; } }, }, }, }; </script>
/* Evan Smith CIS 554 - M401 Object Oriented Programming in C++ Syracuse University General Library 2 / 9 / 21 This file implements a series of functions to facilitate safe prompting of users and parsing of their responses. */ #include <iostream> #include "UserPrompter.h" using std::cout; using std::cin; //prompt the user using the provided string, then verify that it can be cast to an int. //If bad input provided, reprompt until it's correct int UserPrompter::promptForInt(string prompt) { bool success = false; string userInput = ""; int parsedInt; while (!success) { cout << prompt; cin >> userInput; try { parsedInt = std::stoi(userInput); success = true; } catch (std::exception e) { cout << "Please enter an integer!\n"; } } return parsedInt; } //prompt the user using the provided string, then verify that it can be cast to a double. //If bad input provided, reprompt until it's correct double UserPrompter::promptForDouble(string prompt) { bool success = false; string userInput = ""; double parsedDouble; while (!success) { cout << prompt; cin >> userInput; try { parsedDouble = std::stod(userInput); success = true; } catch (std::exception e) { cout << "Please enter a double!\n"; } } return parsedDouble; }
#include "newickcpp98.h" #include <boost/numeric/conversion/cast.hpp> #include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple_comparison.hpp> #include "fuzzy_equal_to.h" #include "newick.h" #include <set> #include <boost/test/unit_test.hpp> using namespace ribi; BOOST_AUTO_TEST_CASE(ribi_newickcpp98_all) { //Check difference between C++98 and C++0x BOOST_CHECK(newick::CreateValidTrinaryNewicks() == NewickCpp98().CreateValidTrinaryNewicks()); BOOST_CHECK(newick::GetKnownProbabilities() == NewickCpp98().GetKnownProbabilities()); //Check conversions from std::string to std::vector #1 { const std::vector<int> v = newick::StringToNewick("(11,(22,33))"); BOOST_CHECK(v.size() == 7); BOOST_CHECK(v[0]==newick::bracket_open); BOOST_CHECK(v[1]==11); BOOST_CHECK(v[2]==newick::bracket_open); BOOST_CHECK(v[3]==22); BOOST_CHECK(v[4]==33); BOOST_CHECK(v[5]==newick::bracket_close); BOOST_CHECK(v[6]==newick::bracket_close); } //Check if well-formed Newicks are accepted { const std::vector<std::string> v = newick::CreateValidNewicks(); for(const std::string& s: v) { BOOST_CHECK(newick::IsNewick(s)); const std::vector<int> v = newick::StringToNewick(s); BOOST_CHECK(newick::IsNewick(v)); } } //Check if ill-formed Newicks are rejected { #ifndef NDEBUG const std::vector<std::string> v = newick::CreateInvalidNewicks(); for(const std::string& s: v) { #ifdef TRACE_REJECTED_NEWICKS const std::string debug = "I must be rejected: " + s; TRACE(debug); #endif BOOST_CHECK(!newick::IsNewick(s)); //Cannot test if std::vector<int> versions are rejected, //because newick::StringToNewick assumes a valid Newick //const std::vector<int> v = newick::StringToNewick(s); //BOOST_CHECK(!newick::IsNewick(v)); } #endif } //Check conversions from std::string to std::vector #2 { const std::vector<int> v = newick::StringToNewick("((11,22),33)"); BOOST_CHECK(v.size() == 7); BOOST_CHECK(v[0]==newick::bracket_open); BOOST_CHECK(v[1]==newick::bracket_open); BOOST_CHECK(v[2]==11); BOOST_CHECK(v[3]==22); BOOST_CHECK(v[4]==newick::bracket_close); BOOST_CHECK(v[5]==33); BOOST_CHECK(v[6]==newick::bracket_close); } BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(1,(3,1))"))==0); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(3,(1,1))"))==1); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(1,((1,1),(1,1)))"))==3); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(1,((1,1),(2,2)))"))==2); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(1,(2,3))"))==0); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(99,99)"))==1); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(3,(2,2))"))==1); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(2,(2,2))"))==1); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("((3,3),(2,2))"))==2); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("((3,3),(3,3))"))==3); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("((3,3),(3,4))"))==1); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(((3,3),(4,4)),5)"))==2); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(((3,3),(5,5)),5)"))==2); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(((5,5),(5,5)),5)"))==3); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(((5,5),(5,5)),(4,4))"))==4); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(((5,5),(4,4)),(4,4))"))==3); BOOST_CHECK(newick::CalcNumOfSymmetriesBinary(newick::StringToNewick("(((4,4),(4,4)),(4,4))"))==4); BOOST_CHECK(newick::CalcNumOfCombinationsBinary(newick::StringToNewick("(3,(1,1))"))==10); BOOST_CHECK(newick::CalcNumOfCombinationsBinary(newick::StringToNewick("(1,(3,1))"))==20); BOOST_CHECK(newick::CalcNumOfCombinationsBinary(newick::StringToNewick("(1,(1,(1,(1,1))))"))==60); BOOST_CHECK(newick::CalcNumOfCombinationsBinary(newick::StringToNewick("(1,((1,1),(1,1)))"))==15); BOOST_CHECK(bigIntegerToString(newick::FactorialBigInt(1))=="1"); BOOST_CHECK(bigIntegerToString(newick::FactorialBigInt(2))=="2"); BOOST_CHECK(bigIntegerToString(newick::FactorialBigInt(3))=="6"); BOOST_CHECK(bigIntegerToString(newick::FactorialBigInt(4))=="24"); BOOST_CHECK(bigIntegerToString(newick::FactorialBigInt(5))=="120"); BOOST_CHECK(bigIntegerToString(newick::FactorialBigInt(6))=="720"); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1)")) == 1); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(12)")) == 1); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(123)")) == 1); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,2)")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(12,2)")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(123,2)")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,(1,2))")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,(12,2))")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,(123,2))")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("((1,2),3)")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("((12,2),3)")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("((123,2),3)")) == 2); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,2,3)")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(12,2,3)")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(123,2,3)")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,(1,2,3))")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,(12,2,3))")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("(1,(123,2,3))")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("((1,2,3),4)")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("((12,2,3),4)")) == 3); BOOST_CHECK(newick::GetLeafMaxArity(newick::StringToNewick("((123,2,3),4)")) == 3); BOOST_CHECK(fuzzy_equal_to()( 2.0,newick::CalcDenominator(newick::StringToNewick("(1,1)"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 6.0,newick::CalcDenominator(newick::StringToNewick("((1,1),1)"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 26.0,newick::CalcDenominator(newick::StringToNewick("(1,2)"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 32.0,newick::CalcDenominator(newick::StringToNewick("((1,1),2)"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 32.0,newick::CalcDenominator(newick::StringToNewick("(2,(1,1))"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 50.0,newick::CalcDenominator(newick::StringToNewick("((1,1),3)"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 80.0,newick::CalcDenominator(newick::StringToNewick("((1,2),3)"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 80.0,newick::CalcDenominator(newick::StringToNewick("((3,1),2)"),10.0))); BOOST_CHECK(fuzzy_equal_to()( 80.0,newick::CalcDenominator(newick::StringToNewick("((2,3),1)"),10.0))); BOOST_CHECK(fuzzy_equal_to()(102.0,newick::CalcDenominator(newick::StringToNewick("((2,1),4)"),10.0))); BOOST_CHECK(fuzzy_equal_to()(152.0,newick::CalcDenominator(newick::StringToNewick("(2,(1,(3,3)))"),10.0))); BOOST_CHECK(fuzzy_equal_to()(162.0,newick::CalcDenominator(newick::StringToNewick("((2,3),4)"),10.0))); BOOST_CHECK(fuzzy_equal_to()(180.0,newick::CalcDenominator(newick::StringToNewick("((1,2),(3,4))"),10.0))); BOOST_CHECK(fuzzy_equal_to()(180.0,newick::CalcDenominator(newick::StringToNewick("((4,1),(2,3))"),10.0))); BOOST_CHECK(fuzzy_equal_to()(180.0,newick::CalcDenominator(newick::StringToNewick("((3,4),(1,2))"),10.0))); BOOST_CHECK(fuzzy_equal_to()(180.0,newick::CalcDenominator(newick::StringToNewick("((2,3),(4,1))"),10.0))); //Test GetRootBranches { const std::vector<std::vector<int> > v = newick::GetRootBranches(newick::StringToNewick("(1,2)")); BOOST_CHECK(v.size() == 2); BOOST_CHECK(std::find(v.begin(),v.end(), newick::StringToNewick("(1)")) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(), newick::StringToNewick("(2)")) != v.end()); } { const std::vector<std::vector<int> > v = newick::GetRootBranches(newick::StringToNewick("(1,(2,3))")); BOOST_CHECK(v.size() == 2); BOOST_CHECK(std::find(v.begin(),v.end(), newick::StringToNewick("(1)")) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(), newick::StringToNewick("(2,3)")) != v.end()); } { const std::vector<std::vector<int> > v = newick::GetRootBranches(newick::StringToNewick("(1,2,(3,4))")); BOOST_CHECK(v.size() == 3); BOOST_CHECK(std::find(v.begin(),v.end(), newick::StringToNewick("(1)")) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(), newick::StringToNewick("(2)")) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(), newick::StringToNewick("(3,4)")) != v.end()); } //Compare C++98 and C++0x version { const std::vector<std::string> v = newick::CreateValidBinaryNewicks(); for(const std::string& s: v) { const std::vector<int> n = newick::StringToNewick(s); BOOST_CHECK(newick::GetRootBranches(n) == NewickCpp98().GetRootBranches(n)); } } //Check if binary and trinary Newicks are detected correctly { const std::vector<std::string> v = newick::CreateValidBinaryNewicks(); for(const std::string& s: v) { const std::vector<int> n = newick::StringToNewick(s); BOOST_CHECK(newick::IsBinaryNewick(n)); } } //Check if unary Newicks are detected correctly { const std::vector<std::string> v = newick::CreateValidUnaryNewicks(); for(const std::string& s: v) { const std::vector<int> n = newick::StringToNewick(s); BOOST_CHECK( newick::GetLeafMaxArity(n)<=1); BOOST_CHECK( newick::IsUnaryNewick(n)); BOOST_CHECK(!newick::IsBinaryNewick(n)); BOOST_CHECK(!newick::IsTrinaryNewick(n)); } } //Check if binary Newicks are detected correctly { const std::vector<std::string> v = newick::CreateValidBinaryNewicks(); for(const std::string& s: v) { const std::vector<int> n = newick::StringToNewick(s); BOOST_CHECK( newick::GetLeafMaxArity(n)<=2); BOOST_CHECK(!newick::IsUnaryNewick(n)); BOOST_CHECK( newick::IsBinaryNewick(n)); BOOST_CHECK(!newick::IsTrinaryNewick(n)); } } //Check if trinary Newicks are detected correctly { const std::vector<std::string> v = newick::CreateValidTrinaryNewicks(); for(const std::string& s: v) { //TRACE(s); const std::vector<int> n = newick::StringToNewick(s); BOOST_CHECK( newick::GetLeafMaxArity(n)<=3); BOOST_CHECK(!newick::IsUnaryNewick(n)); BOOST_CHECK(!newick::IsBinaryNewick(n)); BOOST_CHECK( newick::IsTrinaryNewick(n)); } } //Test binary Newick { const std::string s("(1,(2,3))"); const std::vector<std::vector<int> > n = newick::GetSimplerNewicks(newick::StringToNewick(s)); //#define DEBUG_1_BO_1_2_3_BC #ifdef DEBUG_1_BO_1_2_3_BC for(const auto& t: n) { TRACE(newick::NewickToString(t)); } #endif BOOST_CHECK(n.size() == 2); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(1,3))")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(2,2))")) != n.end()); } { const std::string s("(1,(2,3,4))"); const std::vector<std::vector<int> > n = newick::GetSimplerNewicks(newick::StringToNewick(s)); BOOST_CHECK(n.size() == 3); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(1,3,4))")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(2,2,4))")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(2,3,3))")) != n.end()); } { const std::string s("(1,(1,3,4))"); const std::vector<std::vector<int> > n = newick::GetSimplerNewicks(newick::StringToNewick(s)); //#define DEBUG_1_BO_1_3_4_BC #ifdef DEBUG_1_BO_1_3_4_BC TRACE(boost::lexical_cast<std::string>(n.size())); for(const auto& t: n) { TRACE(newick::NewickToString(t)); } #endif BOOST_CHECK(n.size() == 4); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(4,4))")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(3,5))")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(1,2,4))")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(),newick::StringToNewick("(1,(1,3,3))")) != n.end()); } { const std::string s("(1,(1,3,4))"); const std::vector<std::pair<std::vector<int>,int> > n = NewickCpp98().GetSimplerNewicksFrequencyPairs(newick::StringToNewick(s)); #ifdef TRACE_GETSIMPLERNEWICKSFREQUENCYPAIRS_1_134 typedef std::pair<std::vector<int>,int> Pair; for(const Pair& p: n) { std::cout << newick::NewickToString(p.first) << '\n'; } #endif BOOST_CHECK(n.size() == 4); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("(1,(4,4))"),1)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("(1,(3,5))"),1)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("(1,(1,2,4))"),3)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("(1,(1,3,3))"),4)) != n.end()); } { const std::string s("((1,1),2)"); const std::vector<std::vector<int> > n = newick::GetSimplerNewicks( newick::StringToNewick(s) ); //#define DEBUG_BO_1_1_BC_2 #ifdef DEBUG_BO_1_1_BC_2 for(const auto& t: n) { TRACE(newick::NewickToString(t)); } #endif BOOST_CHECK(n.size() == 3); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("(2,2)")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("((1,1),1)")) != n.end()); } { const std::string s("((1,1),2)"); typedef std::pair<std::vector<int>,int> Pair; const std::vector<Pair> n = NewickCpp98().GetSimplerNewicksFrequencyPairs(newick::StringToNewick(s)); #ifdef TRACE_GETSIMPLERNEWICKSFREQUENCYPAIRS_11_2 for(const Pair& p: n) { std::clog << newick::NewickToString(p.first) << '\n'; } #endif BOOST_CHECK(n.size() == 3); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("(2,2)"),1)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("((1,1),1)"),2)) != n.end()); } { const std::string s("((2,1),4)"); const std::vector<std::vector<int> > n = newick::GetSimplerNewicks( newick::StringToNewick(s) ); BOOST_CHECK(n.size() == 3); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("(3,4)")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("((1,1),4)")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("((2,1),3)")) != n.end()); } { const std::string s("((2,1),4)"); typedef std::pair<std::vector<int>,int> Pair; const std::vector<Pair> n = NewickCpp98().GetSimplerNewicksFrequencyPairs(newick::StringToNewick(s)); #ifdef TRACE_GETSIMPLERNEWICKSFREQUENCYPAIRS_21_2 for(const Pair& p: n) { TRACE(newick::NewickToString(p.first)); } #endif BOOST_CHECK(n.size() == 3); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("(3,4)"),1)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("((1,1),4)"),2)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("((2,1),3)"),4)) != n.end()); } { const std::string s("((2,3),4)"); const std::vector<std::vector<int> > n = newick::GetSimplerNewicks( newick::StringToNewick(s) ); BOOST_CHECK(n.size() == 3); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("((1,3),4)")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("((2,2),4)")) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), newick::StringToNewick("((2,3),3)")) != n.end()); } { const std::string s("((2,3),4)"); typedef std::pair<std::vector<int>,int> Pair; const std::vector<Pair> n = NewickCpp98().GetSimplerNewicksFrequencyPairs(newick::StringToNewick(s)); #ifdef TRACE_GETSIMPLERNEWICKSFREQUENCYPAIRS_23_4 for(const Pair& p: n) { std::cout << newick::NewickToString(p.first) << '\n'; } #endif BOOST_CHECK(n.size() == 3); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("((1,3),4)"),2)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("((2,2),4)"),3)) != n.end()); BOOST_CHECK(std::find(n.begin(),n.end(), std::make_pair(newick::StringToNewick("((2,3),3)"),4)) != n.end()); } //Compare GetSimplerNewicks and //GetSimplerNewicksFrequencyPairs { const std::vector<std::string> newicks = newick::CreateValidNewicks(); for(const std::string& newick_str: newicks) { const std::vector<int> newick = newick::StringToNewick(newick_str); const std::vector<std::vector<int> > v1 = newick::GetSimplerNewicks(newick); const std::vector<std::pair<std::vector<int>,int> > v2 = newick::GetSimplerNewicksFrequencyPairs(newick); BOOST_CHECK(v1.size() == v2.size()); //Create sets that should be equal std::set<std::vector<int>> s1; std::copy(std::begin(v1), std::end(v1), std::inserter(s1, std::end(s1)) ); std::set<std::vector<int>> s2; std::transform(std::begin(v2), std::end(v2), std::inserter(s2, std::end(s2)), [](const auto& p) { return p.first;} ); BOOST_CHECK(s1 == s2); BOOST_CHECK(newick::GetSimplerNewicksFrequencyPairs(newick) == NewickCpp98().GetSimplerNewicksFrequencyPairs(newick)); } } }
import chalk from "chalk"; import fs from "fs"; import { getWaifuNameFromFileName, calcSpread } from "../logic/logic.shaii"; import { IWaifu, IWaifuRarity, IWaifuRarityName } from "../types"; import logger from "./Logger.shaii"; function loadWaifusFromRarity(rarity: IWaifuRarityName): IWaifu[] { const IWaifus = []; const waifuImages = fs.readdirSync(`./src/assets/waifus/${rarity}`); for (let waifu of waifuImages) { const name = getWaifuNameFromFileName(waifu); IWaifus.push({ name, image: waifu, } as IWaifu); logger.shaii.generic(`Parsed ${chalk.hex("#FFCB6B")(rarity.toUpperCase())} waifu ${chalk.green(name)}`); } return IWaifus; } export const COMMON: IWaifuRarity = { hp: calcSpread(1000), armor: 0, rewards: { xp: calcSpread(100), money: calcSpread(200) }, relativeFrequency: 10, name: "common", color: "#8F93A2", emoji: "👺", waifus: loadWaifusFromRarity("common"), }; export const UNCOMMON: IWaifuRarity = { hp: calcSpread(2500), armor: calcSpread(100), rewards: { xp: calcSpread(250), money: calcSpread(500) }, relativeFrequency: 7, name: "uncommon", color: "#BDDE86", emoji: "🐉", waifus: loadWaifusFromRarity("uncommon"), }; export const RARE: IWaifuRarity = { hp: calcSpread(10000), armor: calcSpread(500), rewards: { xp: calcSpread(1000), money: calcSpread(2000) }, relativeFrequency: 5, name: "rare", color: "#C792EA", emoji: "🔮", waifus: loadWaifusFromRarity("rare"), }; export const LEGENDARY: IWaifuRarity = { hp: calcSpread(25000), armor: calcSpread(1500), rewards: { xp: calcSpread(2500), money: calcSpread(5000) }, relativeFrequency: 2, name: "legendary", color: "#FFCB6B", emoji: "🌟", waifus: loadWaifusFromRarity("legendary"), }; export const MYTHICAL: IWaifuRarity = { hp: calcSpread(50000), armor: calcSpread(2500), rewards: { xp: calcSpread(5000), money: calcSpread(10000) }, relativeFrequency: 1, name: "mythical", color: "#F07178", emoji: "⚜️", waifus: loadWaifusFromRarity("mythical"), };
import React from 'react'; import {connect} from 'react-redux'; import constants from '../../../../constants/constants'; import { goToExpandedDialog, changeChatFavorite, changeChatBlock, changeShowAddChatToCatalogMenu } from "../../../../actions/actionCreator"; import moment from 'moment'; import DialogBox from '../DialogBox/DialogBox'; import styles from './DialogList.module.sass'; const DialogList = ({changeChatFavorite, changeChatBlock, changeShowAddChatToCatalogMenu, chatMode, userId, preview, goToExpandedDialog, removeChat, isFetching}) => { const changeFavorite = (data, event) => { changeChatFavorite(data); event.stopPropagation(); }; const changeBlackList = (data, event) => { changeChatBlock(data); event.stopPropagation(); }; const changeShowCatalogCreation = (event, conversationId) => { changeShowAddChatToCatalogMenu(conversationId); event.stopPropagation(); }; const onlyFavoriteDialogs = (chatPreview, userId) => chatPreview.favoriteList[chatPreview.participants.indexOf(userId)]; const onlyBlockDialogs = (chatPreview, userId) => chatPreview.blackList[chatPreview.participants.indexOf(userId)]; const getTimeStr = (time) => { const currentTime = moment(); if (currentTime.isSame(time, 'day')) return moment(time).format('HH:mm'); else if (currentTime.isSame(time, 'week')) return moment(time).format('dddd'); else if (currentTime.isSame(time, 'year')) return moment(time).format('MM DD'); else return moment(time).format('MMMM DD, YYYY'); }; const renderPreview = (filterFunc) => { const arrayList = []; const sortedPreview = [...preview]; sortedPreview.sort(((a, b) => (moment(b.createdAt) - moment(a.createdAt)))); sortedPreview.forEach((chatPreview) => { const dialogNode = <DialogBox interlocutor={chatPreview.interlocutor} chatPreview={chatPreview} userId={userId} key={chatPreview.id} getTimeStr={getTimeStr} changeFavorite={changeFavorite} changeBlackList={changeBlackList} chatMode={chatMode} catalogOperation={chatMode === constants.CATALOG_PREVIEW_CHAT_MODE ? removeChat : changeShowCatalogCreation} goToExpandedDialog={goToExpandedDialog} isFetching={isFetching} />; if (filterFunc && filterFunc(chatPreview, userId)) { arrayList.push(dialogNode); } else if (!filterFunc) { arrayList.push(dialogNode); } }); return arrayList.length ? arrayList : <span className={styles.notFound}>Not found</span>; }; const renderChatPreview = () => { switch (chatMode) { case constants.FAVORITE_PREVIEW_CHAT_MODE: { return renderPreview(onlyFavoriteDialogs); } case constants.BLOCKED_PREVIEW_CHAT_MODE: { return renderPreview(onlyBlockDialogs); } default: { return renderPreview(); } } }; return ( <div className={styles.previewContainer}> {renderChatPreview()} </div> ) }; const mapStateToProps = (state) => state.chatStore; const mapDispatchToProps = (dispatch) => ({ goToExpandedDialog: (data) => dispatch(goToExpandedDialog(data)), changeChatFavorite: (data) => dispatch(changeChatFavorite(data)), changeChatBlock: (data) => dispatch(changeChatBlock(data)), changeShowAddChatToCatalogMenu: (data) => dispatch(changeShowAddChatToCatalogMenu(data)) }); export default connect(mapStateToProps, mapDispatchToProps)(DialogList);
<template> <div class="app-container"> <el-form ref="duty" :model="duty" :rules="rules" label-width="80px"> <el-form-item label="日期" prop="startTime"> <el-date-picker v-model="duty.startTime" type="date" placeholder="请选择日期" style="width: 430px" ></el-date-picker> </el-form-item> <el-form-item label="星期" prop="week"> <el-input disabled v-model="duty.week" style="width: 430px"></el-input> </el-form-item> <el-form-item label="时间" required> <el-col :span="5"> <el-form-item prop="start"> <el-time-select style="width: 198px" placeholder="起始时间" v-model="duty.start" :picker-options="{ start: '05:00', step: '00:05', end: '23:30', }" > </el-time-select> </el-form-item> </el-col> <!-- <el-col class="line" :span="1">-</el-col> --> <el-col :span="5"> <el-form-item prop="end"> <el-time-select style="width: 198px" placeholder="结束时间" v-model="duty.end" :picker-options="{ start: '05:00', step: '00:05', end: '23:30', minTime: duty.start, }" > </el-time-select> </el-form-item> </el-col> </el-form-item> <el-form-item label="单位" prop="deptId"> <el-select v-model="duty.deptId" placeholder="请选择单位" style="width: 430px" > <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" ></el-option> </el-select> </el-form-item> <el-form-item label="工作内容" prop="content"> <el-input type="textarea" style="width: 430px" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入备注" v-model="duty.content" ></el-input> </el-form-item> <el-form-item label="人员" prop="userId"> <el-select v-model="duty.userId" placeholder="请选择人员" style="width: 430px" > <el-option v-for="item in personList" :key="item.id" :label="item.name" :value="item.id" ></el-option> </el-select> </el-form-item> <el-form-item label="责任人" prop="resUserId"> <el-select v-model="duty.resUserId" placeholder="请选择责任人" style="width: 430px" > <el-option v-for="item in personList" :key="item.id" :label="item.name" :value="item.id" ></el-option> </el-select> </el-form-item> <el-form-item label="地点" prop="pos"> <el-input v-model="duty.pos" style="width: 430px"></el-input> </el-form-item> <el-form-item label="天气预报" prop="weather"> <el-input v-model="duty.weather" style="width: 430px"></el-input> </el-form-item> <el-form-item label="备注" prop="remark"> <el-input type="textarea" style="width: 430px" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入备注" v-model="duty.remark" ></el-input> </el-form-item> <el-form-item> <el-button v-if="$route.params.id" type="primary" @click="updateHandle('duty')" >确定修改</el-button > <el-button v-else type="primary" @click="submitForm('duty')" >立即创建</el-button > <el-button @click="resetForm('duty')">取消</el-button> </el-form-item> </el-form> </div> </template> <script> import { lastDept, getDept } from "@/api/system/dept"; import { selectPerson } from "@/api/insider.js"; import { saveWeekplan, getWeekplanById, updateWeekplan } from "@/api/weekplan" import { dateFormat } from "@/utils/format" export default { data() { return { deptList: [], personList: [], id: this.$route.query.id, duty: { deptId: '', userId: '', startTime: '', remark: '', week: '', content: '', pos: '', weather: '', resUserId: '', // 责任人 start: '', // 开始时间段 end: '', // 结束时间段 }, rules: { startTime: [{ required: true, message: '请选择值班时间', trigger: 'change' }], start: [{ required: true, message: '请选择时间段', trigger: 'change' }], end: [{ required: true, message: '请选择时间段', trigger: 'change' }], // time: [{ required: true, message: '请选择时间段', trigger: 'change' }], deptId: [ { required: true, message: "请选择值班部门", trigger: "change" } ], userId: [ { required: true, message: "请选择值班人员", trigger: "change" } ], resUserId: [ { required: true, message: "请选择责任人", trigger: "change" } ], content: [{ required: true, message: "请输入工作内容", trigger: "blur" }], week: [{ required: true, message: "请输入星期", trigger: "blur" }], pos: [{ required: true, message: "请输入地点", trigger: "blur" }], weather: [{ required: true, message: "请输入天气预报", trigger: "blur" }], } }; }, computed: { changeDeptId() { return this.duty.deptId }, changeStartTime() { return this.duty.startTime }, }, watch: { changeDeptId(val) { // console.log('val', val); this.personList = [] this.duty.userId = '' this.duty.resUserId = '' this.getPersonInfoByDeptId(val) }, changeStartTime(val) { const startDate = new Date(val) switch (startDate.getDay()) { case 1: this.duty.week = '周一' break; case 2: this.duty.week = '周二' break; case 3: this.duty.week = '周三' break; case 4: this.duty.week = '周四' break; case 5: this.duty.week = '周五' break; case 6: this.duty.week = '周六' break; case 0: this.duty.week = '周日' break; } }, }, methods: { async getDeptList() { const res = await lastDept() if (res && res.code == 200 && res.data) { this.deptList = res.data this.resDeptList = res.data } }, async getPersonInfoByDeptId(deptId) { const res = await selectPerson({ deptId, current: 0, size: 999, }) // console.log(res); if (res.code === '200' && res.data) { this.personList = res.data.records } }, submitForm(formName) { this.$refs[formName].validate(valid => { if (valid) { this.addHandle(); } else { console.log("error submit!!"); return false; } }); }, resetForm(formName) { this.$refs[formName].resetFields(); this.$router.go(-1); }, async addHandle() { // const [startTime, endTime] = this.duty.time // const res = await saveWeekplan({ ...this.duty, startTime, endTime }); this.duty.startTime = dateFormat("YYYY-mm-dd", new Date(this.duty.startTime)) const tempStart = new Date(this.duty.startTime + ' ' + this.duty.start) // const tempEnd = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(this.duty.startTime + ' ' + this.duty.end)) let day = '' if (tempStart.getHours() >= 0 && tempStart.getHours() < 12) { day = "上午" } else if (tempStart.getHours() >= 12 && tempStart.getHours() < 18) { day = "下午" } else { day = "晚上" } this.duty.day = day this.duty.time = this.duty.start + '-' + this.duty.end // console.log(this.duty); const res = await saveWeekplan(this.duty); if (res.code === '200') { this.$message({ message: "添加成功", type: "success" }); this.$router.push("/weekplan/weekplanList"); } }, async updateHandle() { // const [startTime, endTime] = this.duty.time // const res = await updateWeekplan({ ...this.duty, startTime, endTime }) this.duty.startTime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(this.duty.startTime)) this.duty.endTime = null const res = await updateWeekplan(this.duty) // console.log(res); if (res && res.code === '200') { this.$message({ message: '修改成功', type: 'success' }) this.$router.go(-1) } else { this.$message({ message: '修改失败', type: 'error' }) console.error(res) } }, }, async mounted() { await this.getDeptList(); const { id } = this.$route.params if (id) { // 修改 const res = await getWeekplanById(id) if (res && res.code === '200') { this.duty.deptId = res.data.deptId setTimeout(() => { this.duty = res.data // this.duty.time = [res.data.startTime, res.data.endTime] }, 1000) } } } }; </script>
import { useEffect, useState } from "react"; import { useAddress, useContract, useDisconnect } from "@thirdweb-dev/react"; import type { NextPage } from "next"; import { EDITION_ADDRESS } from "../constants/addresses"; import styles from "../styles/Home.module.css"; import { magicLink } from "@thirdweb-dev/react"; import { useConnect } from "@thirdweb-dev/react"; import axios from "axios"; import Checkout from "../components/Checkout"; import Signup from "../components/Signup"; const Home: NextPage = () => { const address = useAddress(); const disconnect = useDisconnect(); //These states are passed onto the SignUp Component; const [email, setEmail] = useState<string>(""); const [firstName, setFirstName] = useState<string>(""); const [lastName, setLastName] = useState<string>(""); const [phoneNumber, setPhoneNumber] = useState<string>(""); const [customerId, setCustomerId] = useState<string>(""); //These states are passed onto the Checkout Component const { contract } = useContract(EDITION_ADDRESS, "signature-drop"); const [clientSecret, setClientSecret] = useState(""); const [message, setMessage] = useState<string | null>(null); const connect = useConnect(); const magicLinkConfig = magicLink({ apiKey: process.env.NEXT_PUBLIC_MAGIC_LINK_API_KEY as string, }); useEffect(() => { disconnect(); localStorage.clear(); }, []); useEffect(() => { if (address && customerId) { // Call /api/stripe_intent const paymentIntent = async () => { try { const response = await axios.post("/api/stripe_intent", { address, customerId, }); console.log( "Hello this is: paymentinent: ", response.data.client_secret ); setClientSecret(response.data.client_secret); } catch (err) { console.log(err); } }; paymentIntent(); // Call /api/update_customer const updateCustomer = async () => { try { const response = await axios.post("/api/stripe_intent", { address, customerId, }); console.log( "Hello this is: updateCustomer: ", response.data.client_secret ); setClientSecret(response.data.client_secret); } catch (err) { console.log(err); } }; updateCustomer(); } }, [address, customerId]); const handleLogin = async () => { console.log("I have been clicked"); if (firstName && lastName && phoneNumber && email) { try { const response = await axios.post("/api/create_customer", { firstName, lastName, phoneNumber, email, }); const data = response.data; if (data.alreadyPurchased) { setMessage( "This email has already been used for a successful purchase." ); } else if (data.customerId) { setCustomerId(data.customerId); await connect(magicLinkConfig, { email: email }); } } catch (err) { console.log(err); } } }; return ( <div className={styles.container}> {message && <h2>{message}</h2>} {address ? ( <Checkout email={email} contract={contract} clientSecret={clientSecret} /> ) : ( <> <Signup setEmail={setEmail} setFirstName={setFirstName} setPhoneNumber={setPhoneNumber} setLastName={setLastName} handleLogin={handleLogin} /> </> )} </div> ); }; export default Home;
import random import cv2 import mediapipe as mp import HandTrackingModule as htm import time wCam, hCam = 640,380 cap = cv2.VideoCapture(0) cap.set(3,wCam) cap.set(4,hCam) detector = htm.handDetector(detectionCon=1) tipIds = [4,8,12,16,20] fingerCount = 0 fingers = [] def getUserChoice(userRightHanded): print("Using your Hand and raise up Rock, Paper, or Scissors") totalFingers = 0 startTime = time.time() while time.time() - startTime < 8: success, img = cap.read() if userRightHanded == 1: img = cv2.flip(img, flipCode=1) img = detector.findHands(img) lmList = detector.findPosition(img, draw=False) # print(lmList) if len(lmList) != 0: fingers = [] if lmList[tipIds[0]][1] > lmList[tipIds[0]-1][1]: fingers.append(1) else: fingers.append(0) for id in range(1,5): if lmList[tipIds[id]][2] < lmList[tipIds[id]-2][2]: fingers.append(1) totalFingers = fingers.count(1) cv2.imshow("Screen",img) cv2.waitKey(2) return totalFingers def winnerDecide(num1, num2): if((num1 == 0 and num2 == 1) or (num1 == 2 and num2 == 3) or (num1 == 5 and num2 == 2)): return "TIE!" elif (num1 == 0 and num2 == 3) or (num1 == 2 and num2 == 2)or (num1 == 5 and num2 == 1): return "You Win!" else: return "Computer Wins!" def main(): userRightHanded = 0 playGame = True print("WELCOME TO ROCK PAPER SCISSORS GAME!") # userHand = input("Which hand will you be playing with today? ('L' or 'R')") # userHand = userHand.lower() # print(userHand) # while userHand != "l" or userHand != "r": # userHand = input("INVALID INPUT! Which hand to play with? ('L' or 'R')") # userHand = userHand.lower() # if(userHand == 'l'): # userRightHanded = 1 # break # elif(userHand == 'r'): # userRightHanded = 0 # break while True: user_hand_preference = input("Are you right-handed or left-handed? ('L' or 'R')").lower() if user_hand_preference == "r": userRightHanded = 0 break elif user_hand_preference == "l": userRightHanded = 1 break else: print("Invalid input. Please enter 'l' or 'r'.") while playGame: while True: userChoice = getUserChoice(userRightHanded) if (userChoice == 0): print("Your Choice: ROCK") break elif (userChoice == 5): print("Your Choice: PAPER") break elif (userChoice == 2): print("Your Choice: SCISSORS ") break else: print("INVALID INPUT! Press raise 5 fingers for Paper, 2 for Scissors, and 0 for Rock \n") computerChoice = random.randint(1,3) if (computerChoice == 1): print("Computer Choice: ROCK") elif (computerChoice == 2): print("Computer Choice: PAPER") elif (computerChoice == 3): print("Computer Choice: SCISSORS ") result = winnerDecide(userChoice, computerChoice) print(result) print("Would you like to play again? ('Y' or 'N')") playAgain = input() playAgain = playAgain.lower() while playAgain != "y" or playAgain != "n": print("INVALID INPUT! Play Again? ('Y' or 'N')") playAgain = input() playAgain = playAgain.lower() if (playAgain == "N"): playGame = False for i in range(3, -1, -1): print(f"Countdown: {i} seconds") time.sleep(1) if __name__ == "__main__": main()
package com.example.efashionwearos.retrofit import android.os.Build import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.* import java.util.concurrent.TimeUnit object ServiceBuilder { // it will be changed later on private const val BASE_URL="http://10.0.2.2:90/" var token:String? = null // logging interceptors private val httpLoggingInterceptor=HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) // creating own custom header Interceptor private val headerInterceptor = object : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { var request = chain.request() // let us modify our http request request = request.newBuilder() .addHeader("x-device-type", Build.DEVICE) .addHeader("Accept-Language", Locale.getDefault().language) .build() return chain.proceed(request) } } // create a OkHttp Client instance private val oKHttp=OkHttpClient.Builder() .callTimeout(15,TimeUnit.SECONDS) // comment header interceptor while using unit test .addInterceptor(headerInterceptor) .addInterceptor(httpLoggingInterceptor).build() // create a retrofit builder private val retrofitBuilder = Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(oKHttp) // retrofit instance from retrofit builder private val retrofit = retrofitBuilder.build() // create a generic function which implement a class and return retrofit instance/object of respective class fun <T> buildService(anyClass:Class<T>):T { return retrofit.create(anyClass) } }
import { PayloadAction, createSlice } from "@reduxjs/toolkit"; export type Service = | "keramisk-coating" | "chrome-delete" | "ppf" | "helfoliering" | "solfilm" | "polering"; export interface ServiceState { current?: Service | null | undefined; } const initialState: ServiceState = { current: null, }; export const serviceSlice = createSlice({ name: "service", initialState, reducers: { open(state, action: PayloadAction<Service>) { state.current = action.payload; }, close(state) { state.current = null; }, }, }); export const { close, open } = serviceSlice.actions;
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd" [ <!-- Copyright (c) 1993 - 2004 Tim Riker This package is free software; you can redistribute it and/or modify it under the terms of the license found in the file named COPYING that should have accompanied this file. THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. --> ]> <book> <bookinfo> <title>Voting System</title> <subtitle>Colloborative administration on the field</subtitle> <pubdate>2003-12-04</pubdate> <author> <firstname>Christopher</firstname> <othername>Sean</othername> <surname>Morrison</surname> <affiliation> <address><email>learner AT brlcad DOT org</email></address> </affiliation> </author> <copyright> <year>2003</year> </copyright> <abstract> <para/> </abstract> </bookinfo> <chapter id="filtering"> <sect1> <title>Introduction</title> <para>BZFlag has a voting system in place to request input from the players on a server in order to perform some action. Presently, this action includes a request to kick or ban some other player.</para> <para>Polls should not be started without firm justification. The voting system is not to be used to remove players that are merely annoying, occassionally use unacceptible language, are suspected of cheating, are doing rather well, or even if they have horrible lag. Those are not valid reasons to use the voting system. The voting system is only intended to address blatently abusive cheaters and assclowns (excessive profanity and/or teamkilling) on servers that do not allow such behavior.</para> <para>Players found requesting polls unnecessarily or otherwise abusing the voting system may find themselves getting kicked or banned from the server.</para> </sect1> <sect1> <title>Quick Start</title> <para>You must be registered and identified on most servers to be allowed to use the voting system. /register and /identify are the commands to use.</para> <para>Once identified, you can request a poll to perform some action (temporarily ban another player, for example), by using the /poll command:</para> <para><command>/poll ban Some Player</command></para> <para>If you initiate the poll, a vote will automatically be cast for you, otherwise you can cast a vote in favor of the poll using the /vote command:</para> <para><command>/vote yes</command></para> <para>The poll will last for a certain period of time, and if enough players vote affirmatively, the requested action will eventually be performed. Only players that were on the server when the poll was started may vote in the poll.</para> <para>Server admins can cancel a poll that they do not wish to see continue by issuing the /veto command:</para> <para><command>/veto</command></para> </sect1> <sect1> <title>Guidelines &amp; Tips</title> <para>The following should be kept in mind when using the voting system:</para> <unorderedlist> <listitem><para>Don't request a poll to ban or kick a player unless the player is blatently cheating or being extremely profane.</para></listitem> <listitem><para>If a poll fails to pass, do not lobby for another poll or complain.</para></listitem> <listitem><para>The /vote command accepts a variety of languages (/vote niet).</para></listitem> <listitem><para>You have to identify yourself with a server, by default, before you can request a poll or vote.</para></listitem> <listitem><para>Admins can veto a poll without needing justification. There is a reason they were given that power. Don't complain.</para></listitem> <listitem><para>Don't use the voting system to remove players that 1) lag, 2) are suspected of cheating, 3) are doing rather well with GM or some other weapon, 4) you just don't like, 5) occassionally curse, 6) respawn repeatedly, or 6) you don't want on your team. Calling a vote for any of these reasons may get you kicked immediately.</para></listitem> <listitem><para>Server administrators can control how long a poll will last, how many players must be present, what percentage of affirmative votes must be obtained, and how long before the action is enforced.</para></listitem> <listitem><para>If you leave a server or reconnect while a poll is in progress, your vote fill be cancelled.</para></listitem> <listitem><para>Only players connected to a server when a poll begins may vote.</para></listitem> <listitem><para>Kicks should rarely be used. Bans are preferred (and are only temporary).</para></listitem> </unorderedlist> </sect1> <sect1> <title>Details</title> <para>To interact with the voting system, the interface is currently implemented as three commands. Commands are in the style of the variety of other <quote>slash</quote> commands in BZFlag that may be invoked by sending a message to all with the name of the command preceeded by a slash. For example, invoke a message to all (default key binding is the <quote>n</quote> key) and enter <quote>/lagstats</quote> to get a report of how much each player is lagging.</para> <para>The voting system provides three commands. They are /poll, /vote, and /veto. To use any of the commands, you must have sufficient permission. By default, this means you must have at least identified yourself to the server (via the /identify command). The veto command requires administrator-level permissions by default. Server administrators may, however, override the necessary permission (see Server Configuration below).</para> <para>As soon as sufficient votes are obtained for a poll, the poll is closed and results are reported. Unless the poll is veto'd, a successful poll will have it's action enforced.</para> </sect1> <sect1> <title>poll command</title> <para><command>/poll {action} [playerCallsign]</command></para> <para>The poll command takes at least one argument, which is the requested action. Valid actions include kick, ban, vote, and veto. The kick and ban commands must be followed by the callsign of a player that is presently on the server.</para> <para>Kicks should rarely be used as all the player has to do is reconnect. It may, however, prove useful to remove a player that has a client that is not responding (NR) for a long period of time.</para> <para>Bans are imposed on the player's IP address and are temporary. If the player disconnects before the poll completes and is successful, the ban will still be imposed.</para> <para>The vote and veto actions are provided as for convenience and are the same as calling the corresponding /vote or /veto command directly.</para> </sect1> <sect1> <title>vote command</title> <para><command>/vote {answer}</command></para> <para>The vote command requires one and only one argument. The answer argument should be an affirmative or opposing response, such as <quote>yes</quote> or <quote>no</quote>. The answer may be provided in a variety of languages such as binary, slang, French, German, Italian, Spanish, etc.</para> <para>Players that instigate a poll have an affirmative vote placed automatically.</para> </sect1> <sect1> <title>veto command</title> <para><command>/veto</command></para> <para>The veto command takes no arguments. It will immediately terminate any poll currently in progress. By default, this ability is only permitted to users in the ADMIN group. After a poll closes, there is a configurable veto period that immediately follows before a successful poll's action is enforced.</para> </sect1> <sect1> <title>Server Configuration</title> <para>There are several configuration options available to server operators for controlling the behavior of the voting system. There are options to control how long a poll lasts, how many votes are required, what percentage of affirmative votes makes a poll pass, and how long the veto period lasts.</para> <para>-voteTime {seconds}</para> <para>This option is used to specify how many seconds must pass before a poll will close and players will no longer be able to vote. The vote time is immediately followed by the veto time.</para> <para>-vetoTime {seconds}</para> <para>The veto time option allows specification of how many seconds after a poll closes that authorized players will be able to cancel the poll. This timeframe may be set to zero to cause a successful poll to have it's action performed immediately after a poll completes.</para> <para>-votesRequired {count}</para> <para>As some servers are occassionally sparsely populated, the number of players that must be present and capable of voting may be set using this option. If there are not at least this many players on the server, a poll cannot be started.</para> <para>-votePecentage {percentage}</para> <para>The default voting percentage is a majority (greater than 50%) of the players on a server that must vote affirmatively for a poll to succeed. Servers that desire a vote that is close to unanimous should set the percentage to a higher value.</para> </sect1> <sect1> <title>Permissions</title> <para>Each of the voting system commands have a corresponding bzflag permission identifier. They are POLL, VOTE, and VETO. By default, POLL and VOTE are in the REGISTERED group and VETO is in the ADMIN group. Some servers may choose to <quote>open up</quote> the voting system to unregistered players; this may be done by placing the POLL and VOTE permissions into the DEFAULT group. Likewise, it may be useful to place VETO into a COPS group if one has been defined for <quote>power users</quote>.</para> <para>Consult the bzfs manpage for more details on server configuration options and permission groups.</para> </sect1> </chapter> </book> <!-- Local Variables: --> <!-- mode: SGML --> <!-- tab-width: 8 --> <!-- c-basic-offset: 2 --> <!-- indent-tabs-mode: t --> <!-- End: --> <!-- ex: shiftwidth=2 tabstop=8 -->
import React, { createContext, FC, PropsWithChildren, useContext, useEffect, useReducer, } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; import { Action } from '../@types'; interface UserState { userId?: string; displayName?: string; email?: string; } const initialState = {}; interface UserContext extends UserState {} const initialContext = { ...initialState, }; export interface UserProviderProps { injectedState?: Partial<UserState>; } /* eslint-disable @typescript-eslint/no-redeclare */ const UserContext = createContext<UserContext>(initialContext); export const useUser = () => useContext(UserContext); export const UserConsumer = UserContext.Consumer; interface SetUserAction extends Action<'SET_USER'> { payload: UserState; } type Actions = SetUserAction; const userReducer = (state: UserState, action: Actions): UserState => { switch (action.type) { case 'SET_USER': return { ...state, ...action.payload, }; default: return state; } }; export const UserProvider: FC<PropsWithChildren<UserProviderProps>> = ({ children, injectedState, }) => { const [state, dispatch] = useReducer(userReducer, { ...initialContext, ...injectedState, }); const { user } = useAuth0(); useEffect(() => { if (user) { const displayName = user['https://app.aw-central.com/username'] || user.nickname || ''; dispatch({ type: 'SET_USER', payload: { email: user.email, userId: user.sub, displayName, }, }); } }, [user]); return <UserContext.Provider value={state}>{children}</UserContext.Provider>; };
<!doctype html> <html> <head> <meta charset="utf-8"/> <title>Contact Form</title> <link rel="stylesheet" type="text/css" href="styles.css"> <style> .capitalize:first-letter { text-transform: capitalize; font-family: times; color: #6A5ACD; font-size: 30px; } .navbar { overflow: hidden; background-color: #333; font-family: Arial; } .navbar a { float: left; font-size: 16px; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } .dropdown { float: left; overflow: hidden; } .dropdown .dropbtn { font-size: 16px; border: none; outline: none; color: white; padding: 14px 16px; background-color: inherit; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { float: none; color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } .dropdown-content a:hover { background-color: #ddd; } .dropdown:hover .dropdown-content { display: block; } .active { background-color: #4CAF50; } </style> <script> function fieldEmpty(fieldvalue, errorString) { if (fieldvalue == "") { return (errorString); } else { return ""; // return empty string } } // test if radio button is selected // function radioButtonSelected (radioButtons, errorString) { radioSelected = -1; // for loop: first need an index i to iterate through array of radio buttons; // next we need to decide if to start at beginning or end of array // i=radioButtons.length-1 means we start at end // test if all elements of array ... know if i > -1 that we have still elements to examine // i-- means that we subtract -1 from i for (i=radioButtons.length-1; i > -1; i--) { if (radioButtons[i].checked) { radioSelected = i; i = -1; // set index to -1 so that for loop stops } } // test if we found a selected radio button ... if radioSelected equal to -1, then we have not and return errorString if (radioSelected == -1) { return (errorString); } else { return ""; } } // test how many checkboxes selected // function checkboxesSelected (checkboxes, errorString) { // keep a count of how many checkboxes have been selected ... initially zero // have to use var checkboxesSelected = 0; // because: 1) function is also called "checkboxesSelected" and without explicit var declaration, a name conflict is created. // 2) Good practice to have var when declaring a variable ...not doing it in our JavaScript examples to not add more complexity. var checkboxesSelected = 0; // for loop: first need an index i to iterate through array of checkboxes; // start at beginning of array of checkboxes // i=0 means we start at beginning of array // test if all elements of array have been tested... know if i < checkboxes.length that we have still elements to examine // i-- means that we subtract -1 from i for (i=0; i<checkboxes.length; i++) { // test if current checkbox is checked ... if yes, add 1 to counter if (checkboxes[i].checked) { // increment counter checkboxesSelected += 1; } } // test how many checkboxes have been selected ... // if checkboxesSelected equal to 0, then we have not and return errorString if (checkboxesSelected == 0) { return (errorString); } else { return ""; } } // next several functions that might be useful for Exercise 4 "as is" or you can modify them to achieve the desired effect // function validateUsername (fieldvalue) { if (fieldvalue == "") return "No Username was entered.\n" else if (fieldvalue.length < 5) return "Usernames must be at least 5 characters.\n" else if (/[^a-zA-Z0-9_-]/.test(fieldvalue)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n" return "" } // test length of fieldvalue and whether at least one letter is of a certain type function validatePassword (fieldvalue) { if (fieldvalue == "") return "No Password was entered.\n" else if (fieldvalue.length < 6) return "Passwords must be at least 6 characters.\n" else if (!/[a-z]/.test(fieldvalue) || ! /[A-Z]/.test(fieldvalue) || !/[0-9]/.test(fieldvalue)) return "Passwords require one each of a-z, A-Z and 0-9.\n" return "" } // function validateAge (fieldvalue) { if (isNaN(fieldvalue)) return "No Age was entered.\n" else if (fieldvalue < 18 || fieldvalue > 110) return "Age must be between 18 and 110.\n" return "" } // function validateEmail (fieldvalue) { if (fieldvalue == "") return "No Email was entered.\n" else if (!((fieldvalue.indexOf(".") > 0) && (fieldvalue.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(fieldvalue)) return "The Email address is invalid.\n" return "" } function validateState (fieldvalue) { if (fieldvalue == "") return "Please enter a valid two-letter state abbreviation.\n" else if (fieldvalue.length != "2") return "Please enter a valid two-letter state abbreviation.\n" return "" } // validate function that calls other functions and acculumates errorString and test if this is empty or not // function validate (form) { fail = fieldEmpty(form.firstname.value, "Please enter a first name.\n") // \n creates new line fail += fieldEmpty(form.lastname.value, "Please enter a last name.\n") fail += fieldEmpty(form.address.value, "Please enter a street address.\n") fail += fieldEmpty(form.town.value, "Please enter a town or city.\n") fail += validateState(form.state.value) fail += fieldEmpty(form.zip.value, "Please enter the zip code.\n") fail += radioButtonSelected(form.ContactPreference, "Please choose a membership status.\n") fail += fieldEmpty(form.telephone.value, "Please enter a telephone number.\n") fail += validateEmail(form.email.value) fail += checkboxesSelected(form.Language, "Please choose two or more options from the checkboxes.\n") if (fail == "") return true else { alert(fail); return false } } </script> </head> <body id="pageContent"> <header> <h1>Contact Form</h1> </header> <div class="navbar"> <a href="index.html">Home</a> <div class="dropdown"> <div class="active"> <button class="dropbtn">Information<i class="fa fa-caret-down"></i></button> </div> <div class="dropdown-content"> <a href="info.html">Info</a> <div class="active"> <a href="contact.html">Contact</a> </div> <a href="feedbackform.html">Feedback</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Experience and Projects<i class="fa fa-caret-down"></i></button> <div class="dropdown-content"> <a href="EduExp.html">Experience</a> <a href="projects.html">Projects</a> <a href="AcademicProjects.html">Academic Projects</a> </div> </div> <a href="about.html">About</a> </div> <main> <p class="capitalize">For more information, please fill the below form and I'll get back to you ASAP!!</p> <form method="POST" action="mailto:bhuwan.agarwal@rutgers.edu" onsubmit="return validate(this)"> <fieldset id="personalinfo"> <legend>Personal Information</legend> <label for="firstname">First name:</label> <input type="text" id="firstname"> <label for="lastname">Last name:</label> <input type="text" id="lastname"> <br> <br> <label for="address">Address:</label> <input type="text" id="address" size="75"> <br> <br> <label for="town">Town/City:</label> <input type="text" id="town"> <label for="state">State:</label> <input type="text" id="state" size="2"> <label for="zip">Zip Code:</label> <input type="text" id="zip" size="5"> <br> <br> </fieldset> <fieldset id="contactinfo"> <legend>Contact Information</legend> <label for="telephone">Phone number:</label> <input type="text" id="telephone"> <select id="teltype"> <option value='cell'>Cell</option> <option value='home'>Home</option> <option value='work'>Work</option> </select><br> <br> <label for="email">Email:</label> <input type="email" id="email" size="80"> </fieldset> <fieldset> <legend>Contact Preference</legend> <label>How should I contact you, please choose one of the following preference of contact:</label><br> <input type="radio" name="ContactPreference" value="Email">Email<br> <input type="radio" name="ContactPreference" value="Phone">Phone<br> <input type="radio" name="ContactPreference" value="Mail">Mail<br> </fieldset> <fieldset id="TechLang"> <legend>Interest</legend> <label for="method">Are you interested in learning technical languages?</label> <br> <select id="method"> <option value='Yes'>Yes</option> <option value='No'>No</option> </select> <br> <br> <label>Please select the langauges in which you are interested:</label><br> <input type="checkbox" name="Language" value="C/C++">C/C++<br> <input type="checkbox" name="Language" value="Java">Java<br> <input type="checkbox" name="Language" value=".Net">.Net<br> <input type="checkbox" name="Language" value="Python">Python<br> <input type="checkbox" name="Language" value="R">R<br> <input type="checkbox" name="Language" value="HTML/CSS/JavaScript">HTML/CSS/JavaScript<br> <input type="checkbox" name="Language" value="PHP">PHP<br> <input type="checkbox" name="Language" value="SQL">SQL<br> <input type="checkbox" name="Language" value="None">None<br> </fieldset> <fieldset id="other"> <legend>Comments/Query</legend> <label for="othertext">Please feel free to ask any questions!</label><br> <textarea id="othertext"></textarea> </fieldset> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> </main> <footer> <div class="footer"> <p>Bhuwan Agarwal Copyright <script>new Date().getFullYear()>2010&&document.write(new Date().getFullYear());</script> </p> </div> </footer> </body> </html>
import request from 'supertest'; import nock from 'nock'; import { defaultOptions, nockMode, authToken } from 'test/nockHelper'; import { getServer } from 'test/testServer'; describe('v2Action', () => { const defaultUrl = '/v2/essentials/action'; let app: request.SuperTest<request.Test>; const investorId = 'bec354b9-be6c-472c-a792-9167e3bbf543'; const issuerId = '5754df3d-3959-4aa1-80db-09d6c5858911'; const tokenId = '5594bf56-92e1-4d69-ab85-e7213e0fda84'; const orderId = 422063; beforeAll(() => { const { superTestApp } = getServer(); app = superTestApp; nock.disableNetConnect(); nock.enableNetConnect('127.0.0.1'); nock.back.setMode(nockMode); nock.back.fixtures = __dirname + '/nockFixtures/action'; }); afterEach(() => { nock.restore(); }); describe('GET v2/essentials/action', () => { jest.setTimeout(10000); it('successfully returns list of actions', async () => { const { nockDone } = await nock.back('actions-list.json', defaultOptions); const resp = await app .get( `${defaultUrl}?offset=0&limit=10&tokenId=${tokenId}&userId=${issuerId}`, ) .set('Authorization', `Bearer ${authToken}`) .expect(200); expect(resp.body).toMatchSnapshot(); nockDone(); }); }); describe('GET v2/essentials/action/:orderId', () => { it('successfully returns order details', async () => { const { nockDone } = await nock.back( 'action-details.json', defaultOptions, ); const resp = await app .get(`${defaultUrl}/${orderId}?userId=${investorId}`) .set('Authorization', `Bearer ${authToken}`) .expect(200); expect(resp.body).toMatchSnapshot(); nockDone(); }); }); describe('GET v2/essentials/action/:orderId/transition', () => { it('successfully returns order transition details', async () => { const { nockDone } = await nock.back( 'action-transition-details.json', defaultOptions, ); const resp = await app .get(`${defaultUrl}/${orderId}/transition?userId=${investorId}`) .set('Authorization', `Bearer ${authToken}`) .expect(200); expect(resp.body).toMatchSnapshot(); nockDone(); }); }); });
package com.java.learnspringframework.jakartaEE; import java.util.Arrays; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import jakarta.inject.Inject; import jakarta.inject.Named; @Named class BusinessClass { private Data data; @Inject public void setData(Data data) { System.out.println("Setter injection"); this.data = data; } public Data getData() { return data; } } @Named class Data { } @Configuration @ComponentScan public class JakartaApplication { public static void main(String[] args) { try(var context = new AnnotationConfigApplicationContext(JakartaApplication.class)) { Arrays.stream(context.getBeanDefinitionNames()) .forEach(System.out::println); System.out.println(context.getBean(BusinessClass.class)); } } }
import React, { useState } from "react"; import { useSelector } from "react-redux"; import { NavLink, useNavigate, useParams } from "react-router-dom"; import { cartList } from "../../Redux/Reducer/cartSlice"; import { productList } from "../../Redux/Reducer/productSlice"; import AllProduct from "../Body/AllProduct"; import "./Navbar.css"; const Navbar = () => { const [item, setItem] = useState(); const [search, setSearch] = useState(""); // const { category } = useParams(); const filteritems = (categitem) => { const updateitems = AllProductsData.filter((curElem) => { return curElem.category === categitem; }); setItem(updateitems); }; const AllProductsData = useSelector(productList); const items = useSelector(cartList); const handleSearch = (e) => { setSearch(e.target.value); }; return ( <> <div className="menu-btn"> <i className="fas fa-bars fs-4"> </i> </div> <div className="Container"> <div className="wrapper"> <nav className="main-nav"> <div className="logo"> <NavLink to="/home" onClick={() => setItem()}> LOGO </NavLink> </div> <ul className="main-menu"> <li> <NavLink to="/home" activeclassname="active" onClick={() => setItem()} > Home </NavLink> </li> <li> <NavLink to="/all" activeclassname="active" onClick={() => setItem(AllProductsData)} > all </NavLink> </li> <li> <NavLink to="/mobile" activeclassname="active" onClick={() => filteritems("mobile")} > Mobile </NavLink> </li> <li> <NavLink to="/laptop" activeclassname="active" onClick={() => filteritems("laptop")} > laptop </NavLink> </li> <li> <NavLink to="/watch" activeclassname="active" onClick={() => filteritems("watch")} > watch </NavLink> </li> <li> <NavLink to="/computer" activeclassname="active" onClick={() => filteritems("computer")} > compuer </NavLink> </li> <li> <NavLink to="/accessories" activeclassname="active" onClick={() => filteritems("accessories")} > accessories </NavLink> </li> </ul> <ul className="right-menu"> <li> {/* <NavLink to="#" className="Icon" id="suraj"> <i className="fas fa-search"></i> </NavLink> */} <input type="text" placeholder="search" onChange={handleSearch} /> </li> <li> <NavLink to="#" className="Icon"> <i className="far fa-user-circle"></i> </NavLink> </li> <li> <NavLink to="#" className="Icon"> <i className="fa fa-heart" aria-hidden="true"></i> </NavLink> </li> <li> <NavLink to="/removecart" className="Icon" onClick={() => setItem()} > <div style={{ display: "flex", width: "55px" }}> <i className="fas fa-shopping-cart"></i> <p style={{ fontSize: "20px", color: "#e74c3c", fontWeight: "600", }} > {items.length} </p> </div> </NavLink> </li> </ul> </nav> </div> </div> <AllProduct item={item} search={search} /> </> ); }; export default Navbar;
import React, { useReducer, useCallback } from 'react'; import { Snackbar, Slide, useTheme } from '@material-ui/core'; import { Alert } from '@material-ui/lab'; import SnackMessageContext from '../contexts/SnackMessage'; const DEFAULT_STATE = { isOpen: false, severity: 'info', content: '', }; function reducer(state = DEFAULT_STATE, action) { switch (action.type) { case 'open': return { isOpen: true, severity: action.payload.severity, content: action.payload.content }; case 'close': return { ...state, isOpen: false }; default: return state; } } function SlideTransition(props) { return <Slide {...props} direction="up" />; } export default function SnackMessageProvider({ children }) { const [state, dispatch] = useReducer(reducer, DEFAULT_STATE); const { transitions } = useTheme(); const open = (content, severity) => { dispatch({ type: 'open', payload: { content, severity }}); }; const close = () => { dispatch({ type: 'close' }); }; const closeAndOpen = useCallback((content, severity) => { if (state.isOpen) { close(); window.setTimeout(() => open(content, severity), transitions.duration.leavingScreen); } else { open(content, severity); } }, [state.isOpen]); const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } close(); }; return ( <SnackMessageContext.Provider value={{ open: closeAndOpen, close }}> { children } <Snackbar open={state.isOpen} autoHideDuration={5000} onClose={handleClose} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} TransitionComponent={SlideTransition} > <Alert onClose={handleClose} severity={state.severity}> { state.content } </Alert> </Snackbar> </SnackMessageContext.Provider> ); }
use anyhow::Result; use chrono::{DateTime, Utc}; use dyn_clone::{clone_trait_object, DynClone}; use std::{self, collections::HashMap, net::SocketAddr}; use uuid::Uuid; use crate::model::Hit; use super::{ location_detect::Country, user_agent_detect::{Device, UserAgent, OS}, InitOnce, }; #[derive(Clone, Debug)] pub enum FlowRouterData { Bool(bool), Number(f64), String(&'static str), } impl FlowRouterData { pub fn is_bool(&self, value: bool) -> bool { if let FlowRouterData::Bool(bool_value) = &self { return *bool_value == value; } false } pub fn is_string(&self, value: &str) -> bool { if let FlowRouterData::String(str_value) = &self { return value.eq_ignore_ascii_case(str_value); } false } pub fn is_num(&self, value: f64) -> bool { if let FlowRouterData::Number(num_value) = &self { return *num_value == value; } false } } #[derive(Debug)] pub struct TrackingPipeContext { pub id: Uuid, pub utc: DateTime<Utc>, pub data: HashMap<&'static str, FlowRouterData>, pub client_os: InitOnce<Option<OS>>, pub client_ua: InitOnce<Option<UserAgent>>, pub client_device: InitOnce<Option<Device>>, pub client_country: InitOnce<Option<Country>>, } impl TrackingPipeContext { pub fn new(hit: Hit) -> Self { Self { id: Uuid::new_v4(), utc: Utc::now(), data: HashMap::new(), client_os: InitOnce::default(None), client_ua: InitOnce::default(None), client_device: InitOnce::default(None), client_country: InitOnce::default(None), } } } impl TrackingPipeContext { pub fn is_data_true(&self, bool_key: &'static str) -> bool { let data_value = self.data.get(&bool_key); if let Some(i) = data_value { return i.is_bool(true); } false } /// /// Adds a bool value to the context's data /// pub fn add_bool(&mut self, bool_key: &'static str, value: bool) { let _ = &self.data.insert(bool_key, FlowRouterData::Bool(value)); } /// /// Adds a string value to the context's data /// pub fn add_string(&mut self, bool_key: &'static str, value: &'static str) { let _ = &self.data.insert(bool_key, FlowRouterData::String(value)); } /// /// Adds a num value to the context's data /// pub fn add_num(&mut self, bool_key: &'static str, value: f64) { let _ = &self.data.insert(bool_key, FlowRouterData::Number(value)); } } #[derive(Clone, Debug)] pub struct FlowInRoute { pub scheme: String, pub host: String, pub port: u16, pub path: String, pub query: String, } impl FlowInRoute { pub fn new(scheme: String, host: String, port: u16, path: String, query: String) -> Self { Self { scheme, host, port, path, query, } } } #[derive(Debug)] pub struct FlowRouterContext { pub id: Uuid, pub utc: DateTime<Utc>, pub data: HashMap<&'static str, FlowRouterData>, pub client_os: InitOnce<Option<OS>>, pub client_ua: InitOnce<Option<UserAgent>>, pub client_device: InitOnce<Option<Device>>, pub client_country: InitOnce<Option<Country>>, } impl FlowRouterContext { pub fn new(hit: Hit) -> Self { Self { id: Uuid::new_v4(), utc: Utc::now(), data: HashMap::new(), client_os: InitOnce::default(None), client_ua: InitOnce::default(None), client_device: InitOnce::default(None), client_country: InitOnce::default(None), } } } #[derive(Clone, Debug)] pub struct PerConnHandler { pub local_addr: SocketAddr, pub remote_addr: SocketAddr, pub server_name: String, pub tls_info: Option<TlsInfo>, } #[derive(Clone, Debug)] pub struct TlsInfo { pub sni_hostname: Option<String>, pub alpn_protocol: Option<String>, pub has_certificate: bool, } #[async_trait::async_trait()] pub trait BaseTrackingPipe: DynClone { async fn handle(&self, hit: Hit) -> Result<()>; } clone_trait_object!(BaseTrackingPipe);
interface WeatherDisplayProps { cityName: string; temperature: number; icon: string; mainWheater: string; } function WeatherDisplay(Props: WeatherDisplayProps) { return ( <div className="w-[800px] mt-10 rounded-[30px] flex flex-col items-center gap-2 py-16 bg-[url('../Assets/wheater-images/Cloudy-n2.jpg')] bg-center bg-cover relative md:w-[90%] md:py-8 transition-all duration-300 animate-[showUp_.5s_ease]" > <div className="absolute w-full h-full top-0 rounded-[30px] bg-white bg-opacity-10 backdrop-blur-[x]"></div> <div className="z-10 flex flex-col items-center"> <p className="text-5xl leading-none font-medium text-neutral-50 md:text-3xl delay-1000"> {Props.cityName} </p> <p className="text-9xl leading-none font-light text-neutral-50 md:text-7xl delay-300"> {Math.round(Props.temperature)}º </p> <div className="flex items-center mt-2 delay-100"> <img className="max-w-[100px] md:max-w-[40px]" src={`http://openweathermap.org/img/wn/${Props.icon}@4x.png`} alt={Props.mainWheater} /> <span className="text-5xl leading-none font-medium text-neutral-50 md:text-3xl"> {Props.mainWheater} </span> </div> </div> </div> ); } export default WeatherDisplay;
import 'package:floor/floor.dart'; import 'package:proodonto/app/shared/enum_types.dart'; @Entity(tableName: "anamnesis") class Anamnesis { @PrimaryKey(autoGenerate: true) int? id; int? recordNumber; String? patientCPF; String? complain; String? diseaseHistory; String? diseases; String? currentTreatment; String? forWhat; bool? pregnancy; bool? breastfeeding; String? howManyMonth; bool? prenatalExam; String? medicalRecommendations; bool? useMedicine; String? whichMedicines; String? doctorName; String? allergy; String? surgery; bool? hasHealingProblem; String? healingProblemSituation; bool? hasProblemWithAnesthesia; String? problemWithAnesthesiaSituation; bool? hasBleedingProblem; String? bleedingProblemSituation; bool? hasRheumaticFever; bool? hasKidneyProblem; bool? hasRespiratoryProblem; bool? hasJointProblem; bool? hasHighBloodPressureProblem; bool? hasHeartProblem; bool? hasGastricProblem; bool? hasAnemia; bool? hasDiabetes; bool? hasNeurologicalProblems; InfectiousDiseases? infectiousDiseases; bool? underwentChemotherapy; String? chemotherapyDate; bool? hasOnychophagy; bool? hasMouthPiece; bool? hasBruxism; bool? isSmoker; String? cigaretteType; int? howManyCigarette = 0; bool? isAlcoholic; String? drinkType; String? otherHabits; String? familyBackground; bool? hasAnxiety; bool? dentalTreatment; String? lastVisitToTheDentist; String? negativeExperience; String? whatKindOfTreatment; String? brushNumber; String? brushType; bool? useDentalFloss; bool? hasDryMouthFeeling; bool? feelBurning; String? otherDiseases; Anamnesis({ this.id, this.recordNumber, this.patientCPF, this.complain, this.diseaseHistory, this.diseases, this.currentTreatment, this.forWhat, this.pregnancy, this.howManyMonth, this.prenatalExam, this.medicalRecommendations, this.useMedicine, this.whichMedicines, this.doctorName, this.allergy, this.surgery, this.hasHealingProblem, this.healingProblemSituation, this.hasProblemWithAnesthesia, this.problemWithAnesthesiaSituation, this.hasBleedingProblem, this.bleedingProblemSituation, this.hasRheumaticFever, this.hasKidneyProblem, this.hasRespiratoryProblem, this.hasJointProblem, this.hasHighBloodPressureProblem, this.hasHeartProblem, this.hasGastricProblem, this.hasAnemia, this.hasDiabetes, this.hasNeurologicalProblems, this.infectiousDiseases, this.underwentChemotherapy, this.hasOnychophagy, this.hasMouthPiece, this.hasBruxism, this.isSmoker, this.cigaretteType, this.isAlcoholic, this.drinkType, this.otherHabits, this.familyBackground, this.hasAnxiety, this.dentalTreatment, this.lastVisitToTheDentist, this.negativeExperience, this.whatKindOfTreatment, this.brushNumber, this.brushType, this.useDentalFloss, this.hasDryMouthFeeling, this.chemotherapyDate, this.howManyCigarette, this.breastfeeding, this.feelBurning, this.otherDiseases, }); @override String toString() { return 'Anamnesis{id: $id, recordNumber: $recordNumber, patientCPF: $patientCPF, complain: $complain, diseaseHistory: $diseaseHistory, diseases: $diseases, currentTreatment: $currentTreatment, forWhat: $forWhat, pregnancy: $pregnancy, breastfeeding: $breastfeeding, howManyMonth: $howManyMonth, prenatalExam: $prenatalExam, medicalRecommendations: $medicalRecommendations, useMedicine: $useMedicine, whichMedicines: $whichMedicines, doctorName: $doctorName, allergy: $allergy, surgery: $surgery, hasHealingProblem: $hasHealingProblem, healingProblemSituation: $healingProblemSituation, hasProblemWithAnesthesia: $hasProblemWithAnesthesia, problemWithAnesthesiaSituation: $problemWithAnesthesiaSituation, hasBleedingProblem: $hasBleedingProblem, bleedingProblemSituation: $bleedingProblemSituation, hasRheumaticFever: $hasRheumaticFever, hasKidneyProblem: $hasKidneyProblem, hasRespiratoryProblem: $hasRespiratoryProblem, hasJointProblem: $hasJointProblem, hasHighBloodPressureProblem: $hasHighBloodPressureProblem, hasHeartProblem: $hasHeartProblem, hasGastricProblem: $hasGastricProblem, hasAnemia: $hasAnemia, hasDiabetes: $hasDiabetes, hasNeurologicalProblems: $hasNeurologicalProblems, infectiousDiseases: $infectiousDiseases, underwentChemotherapy: $underwentChemotherapy, hasOnychophagy: $hasOnychophagy, hasMouthPiece: $hasMouthPiece, hasBruxism: $hasBruxism, isSmoker: $isSmoker, cigaretteType: $cigaretteType, isAlcoholic: $isAlcoholic, drinkType: $drinkType, otherHabits: $otherHabits, familyBackground: $familyBackground, hasAnxiety: $hasAnxiety, dentalTreatment: $dentalTreatment, lastVisitToTheDentist: $lastVisitToTheDentist, negativeExperience: $negativeExperience, whatKindOfTreatment: $whatKindOfTreatment, brushNumber: $brushNumber, brushType: $brushType, useDentalFloss: $useDentalFloss, hasDryMouthFeeling: $hasDryMouthFeeling, feelBurning: $feelBurning}'; } }
#include <stdlib.h> #include "dog.h" /** * init_dog - a function to initialize a variable of type struct dog * @d: a variable of type struct dog * @name: name * @age: age * @owner: owner argument * * Description: initialize struct dog with the provided values */ void init_dog(struct dog *d, char *name, float age, char *owner) { if (d == NULL) d = malloc(sizeof(struct dog)); d->name = name; d->owner = owner; d->age = age; }
import app from 'flarum/admin/app'; import Page from 'flarum/common/components/Page'; import Button from 'flarum/common/components/Button'; export default class ClientsPage extends Page { translationPrefix = 'foskym-oauth-center.admin.clients.'; clients = []; oninit(vnode) { super.oninit(vnode); this.fields = [ 'client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'client_name', 'client_desc', 'client_icon', 'client_home' ]; app.store.find('oauth-clients').then(r => { this.clients = r; this.fields.map(key => console.log(this.clients[0][key])) m.redraw(); }); } view() { return ( <div class={"OAuthCenter-clientsPage"}> { m('.Form-group', [ m('table', [ m('thead', m('tr', [ this.fields.map(key => m('th', app.translator.trans(this.translationPrefix + key))), m('th'), ])), m('tbody', [ this.clients.map((client, index) => m('tr', [ this.fields.map(key => m('td', m('input.FormControl', { type: 'text', value: client[key]() || '', onchange: (event) => { this.saveClientInfo(index, key, event.target.value); }, })) ), m('td', Button.component({ className: 'Button Button--icon', icon: 'fas fa-times', onclick: () => { this.clients[index].delete(); this.clients.splice(index, 1); }, })), ])), m('tr', m('td', { colspan: 9, }, Button.component({ className: 'Button Button--block', onclick: () => { const client = app.store.createRecord('oauth-clients'); const client_id = this.randomString(32); const client_secret = this.randomString(32); client.save({ client_id: client_id, client_secret: client_secret, }).then(this.clients.push(client)); }, }, app.translator.trans(this.translationPrefix + 'add_button')))), ]), ]), ]) } </div> ); } randomString(len) { len = len || 32; let $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let maxPos = $chars.length; let pwd = ''; for (let i = 0; i < len; i++) { //0~32的整数 pwd += $chars.charAt(Math.floor(Math.random() * (maxPos + 1))); } return pwd; } saveClientInfo(index, key, value) { console.log(index, key, value); this.clients[index].save({ [key]: value, }); } }
class Solution { public: int minCostClimbingStairs(vector<int>& cost) { vector<int> dp = vector<int>(cost.size()+1);//+1 becuase we need a base case cost where we are at the top //this dp table corresponds to the reverse cost, i.e. the dp[0] is the cost where we are at the top dp[0] = 0;//base case 1, hey we are already at the top, so the cost is zero dp[1] = cost[cost.size()-1]; //base case 2, the cost if we have only one stair int dpIndx = 2; for(int i = cost.size()-2; i>=0; i--){ //cost[i]+dp[dpIndx-1]: if we climb 1 setp //cost[i]+dp[dpIndx-2]: if we climb 2 setps dp[dpIndx] = min((cost[i]+dp[dpIndx-1]),(cost[i]+dp[dpIndx-2])); dpIndx++; } //we need to do this check becuase we can start from either index 0 or 1 int ans = min (dp[dp.size()-1],dp[dp.size()-2]); return ans; } };
import { useState } from "react"; import { StyleSheet, Text, View, Button, TextInput } from "react-native"; export default function App() { const [enteredGoalText, setEnderedGoalText] = useState(""); const [courseGoals, setCourseGoals] = useState([]); //this function will fetch the user input function goalInputHandler(enteredText) { setEnderedGoalText(enteredText) } //this function will run when the Add button will be clicked function addGoalHandler() { //here we will use setCourseGoals to update our goals in todo-list. Then in the end we will take our existing goals and append a new one by using the spread operator(...) to spread existing course goals into this new array so that existing goals can be kept, then I will add new goal by using enteredGoalText as a new goal setCourseGoals((currentCourseGoals)=>[ ...currentCourseGoals, enteredGoalText ]) } return ( <View style={styles.appContainer}> <View style={styles.inputContainer}> <TextInput style={styles.textInput} placeholder="Your course goal!" onChangeText={goalInputHandler}/> <Button title="Add Goal" onPress={addGoalHandler} /> </View> <View style={styles.goalsContainer}> {courseGoals.map((goal)=> ( <View key={goal} style={styles.goalItem} > <Text style={styles.goalText}>{goal}</Text> </View> ))} </View> </View> ); } const styles = StyleSheet.create({ appContainer: { flex: 1, paddingTop: 50, paddingHorizontal: 16, }, inputContainer: { flex: 1, flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 24, borderBottomWidth: 1, borderBottomColor: "#cccccc", }, textInput: { borderWidth: 1, borderColor: "#cccccc", width: "70%", marginRight: 8, padding: 8, }, goalsContainer: { flex: 5, }, goalItem: { margin: 8, padding:8, borderRadius: 6, backgroundColor: '#5e0acc', color:'white' }, goalText:{ color: 'white' } });
const { Product } = require('../../models'); const { limitOffsetPageNumber } = require('../../utils/pagination'); const ViewProduct = async ({ id, status, createdby, name, category, sort, select, page, size }) => { try { const queryObject = {}; // ======= Filters Queries ======= if (id) { queryObject._id = id; } if (status !== undefined) { queryObject.status = status.toLowerCase() === 'true'; } if (createdby) { queryObject.createdby = createdby; } if (name) { queryObject.name = { $regex: new RegExp(name, 'i') }; } if (category) { queryObject.category = category; } let apiData = Product.find(queryObject); let ObjCount = await Product.countDocuments(queryObject); // ======== Short , Select ====== if (sort) { let sortFix = sort.replace(',', ' '); apiData = apiData.sort(sortFix); } else { apiData = apiData.sort({ createdAt: -1 }); } if (select) { let selectFix = select.split(',').join(' '); apiData = apiData.select(selectFix); } // ===== Pagination and limits ==== const { limit, offset } = limitOffsetPageNumber(page, size); apiData = apiData.skip(offset).limit(limit); const Products = await apiData .populate('category') .populate({ path: 'sub_products', }) .exec(); return { Products, total: ObjCount }; } catch (error) { throw new Error('An error occurred while fetching products: ' + error.message); } }; module.exports = ViewProduct;
import { createPortal } from 'react-dom' import { Icon } from '@iconify/react' import { zodResolver } from '@hookform/resolvers/zod' import { FormProvider, useForm } from 'react-hook-form' import { z } from 'zod' import { Input } from '../../components/Form/Input' import { ErrorMessage } from '../../components/Form/ErrorMessage' import { useState } from 'react' import { useNavigate } from 'react-router-dom' import * as Toast from '../../components/Toast' import api from '../../lib/axios' const adminFormSchema = z.object({ email: z.string().email('Email inválido').nonempty('Obrigatório'), password: z.string().nonempty('Obrigatório'), }) export function AdminLogin() { const [isLoading, setIsLoading] = useState(null) const [error, setError] = useState(null) const navigate = useNavigate() const formAdmin = useForm({ resolver: zodResolver(adminFormSchema), }) const { handleSubmit, formState: { errors }, } = formAdmin async function handleLoginAdmin(data) { try { setIsLoading(() => true) const { data: authentication } = await api.post('/authentication', { email: data.email, password: data.password, }) setIsLoading(() => false) setError(() => false) const token = { userId: authentication.userId, token: authentication.token, } localStorage.setItem('@ecoSempre-v1:token', JSON.stringify(token)) navigate('/admin', { replace: true, }) } catch (err) { setIsLoading(() => false) setError(() => err) } } return ( <main className="grid place-content-center border min-h-screen"> <div className="flex flex-col gap-4 bg-white shadow-[0px_4px_53px_0px_rgba(45,43,43,0.13);] rounded py-14 px-10 w-[32rem] font-roboto"> <h1 className="font-bold text-3xl text-center font-inter text-gray-800"> Login </h1> <form onSubmit={handleSubmit(handleLoginAdmin)} className="flex flex-col gap-4 mt-3" > <FormProvider {...formAdmin}> <Input.Root> <Input.Field aria-label="Email" name="email" placeholder="Digite seu email" autoComplete="off" /> {errors.email && ( <ErrorMessage className="!static"> {errors.email.message} </ErrorMessage> )} </Input.Root> <Input.Root> <Input.Field aria-label="Senha" type="password" name="password" placeholder="Digite sua senha" /> {errors.password && ( <ErrorMessage className="!static"> {errors.password.message} </ErrorMessage> )} </Input.Root> </FormProvider> <button type="submit" className={`bg-green-300 py-2 w-full rounded text-white transition-colors hover:bg-blue disabled:hover:bg-green-300 disabled:opacity-70 disabled:cursor-not-allowed ${ isLoading && 'animate-pulse' }`} disabled={isLoading} > <span className="font-bold leading-10 text-sm">ENTRAR</span> </button> </form> </div> {error && !isLoading && createPortal( <Toast.Root> <Toast.Content forceMount={isLoading}> <div className="flex p-3 gap-3 mr-8"> <Icon icon="material-symbols:error" className="w-6 h-6" color="#DD425A" /> <div className="flex flex-col gap-2 flex-1"> <Toast.Title className="font-medium text-gray-800"> {error.request.status === 0 ? 'Erro ao tentar se conectar no servidor' : 'Email ou senha incorretos!'} </Toast.Title> <Toast.Description className="text-sm text-gray-800"> {error.request.status === 0 ? 'Aguarde alguns minutos ou tente novamente mais tarde.' : 'Verifique se as informações inseridas estão corretas ou tente novamente mais tarde.'} </Toast.Description> </div> </div> </Toast.Content> </Toast.Root>, document.body, )} </main> ) }
import * as fs from 'fs' import {asPair} from '../utils' import {ChangerDescriptor, VersionChanger} from '.' export class RegexPattern implements VersionChanger { private readonly match: RegExp private readonly path: string static createFromDesc({info: pattern, path}: ChangerDescriptor): RegexPattern { if (!pattern || !path) throw new Error(`regex-pattern requires both pattern and path`) return new RegexPattern({ pattern, path }) } private constructor(arg: {pattern: string; path: string}) { const [pre, suf] = asPair(arg.pattern, '$1', false) if (suf == null) throw new Error(`regex-pattern: pattern does not includes $1`) new RegExp(pre) new RegExp(suf) this.match = new RegExp(`(?<prefix>${pre})(?<version>.*)(?<suffix>${suf})`) this.path = arg.path } async loadVersion(): Promise<string> { const source = await fs.promises.readFile(this.path, { encoding: 'utf-8' }) const matchResult = source.match(this.match) if (!matchResult) throw new Error(`no such region matches ${this.match}`) if (!matchResult.groups) throw new Error(`logic failure ${this.match}`) return matchResult.groups.version } async setVersion(version: string): Promise<void> { const source = await fs.promises.readFile(this.path, { encoding: 'utf-8' }) const replaced = source.replace(this.match, `$<prefix>${version}$<suffix>`) await fs.promises.writeFile(this.path, replaced, {encoding: 'utf-8'}) } toString(): string { return `regex-pattern.ts(at ${this.path} via ${this.match})` } }
FactoryBot.define do factory :user do nickname { Faker::JapaneseMedia::DragonBall.character } email { Faker::Internet.free_email } password { '1a' + Faker::Internet.password(min_length: 6, mix_case: true) } password_confirmation { password } family_name { Gimei.name.last } first_name { Gimei.name.first } family_name_kana { Gimei.name.last.katakana } first_name_kana { Gimei.name.first.katakana } birthday { Faker::Date.birthday } end end
Table of Contents: [1.0] - Developer's section [1.1] - Notes [1.2] - File types [1.3] - Lattice structures [1.4] - Boundaries [2.0] - Documentation [2.1] - def buildNumpy [2.2] - class Lammps [2.2.1] - def buildLammps [2.3] - class Xyz [2.3.1] - def buildXyz [2.4] - class Block [2.4.1] - def numUcell [2.4.2] - def numAtomsUcell [2.4.3] - def numAtoms [2.4.4] - def Lx [2.4.5] - def Ly [2.4.6] - def Lz [2.5] - def printBasis [2.6] - def kpt [2.7] - def cubicKptSym ----------------------------- [1.0] - Developer's section [1.1] - Any changes to the documentation of this package should be reflected in this file as well as the doc strings of the module, with the exception of example code which should only be included in this file. [1.2] - File types File types Supported: lammmps (alpha) xyz (alpha) Planned: gulp Suggested: [1.3] - Lattice structures Supported: sc (simple cubic) fcc (face centered cubic) bcc (body centered cubic) diamond Planned: Suggested: [1.4] - Boundaries Supported: Multiple boundaries in z direction Boundary spacing relative to block periodic boundary Planned: Suggested: Multiple boundaries in x, y, and z directions -KDP [2.0] - Documentation [2.1] - def buildNumpy This creates numpy array based on the blocks provided lattice.Numpy.buildNumpy(blocks) Parameters ---------- blocks : list of type Block The blocks used to build the numpy array. Blocks should be put in order of origin to z-direction max. Returns ---------- Numpy : numpy array A numpy array of shape (numAtoms, 3) and type float is returned. [2.2] - class Lammps Creates and object that represents a single lammps file ntpy.lattice.Lammps(file_name) Parameters ---------- file_name : str The name of the lammps file [2.2.1] - def buildLammps This creates and writes the lammps file based on the blocks provided ntpy.lattice.Lammps.buildLammps(blocks) Parameters ---------- blocks : list of type Block The blocks used to build the lammps file. Blocks should be put in order of origin to z-direction max. noisy : bool, optional If true, then function will print out lammps details, otherwise the function will be quiet (default). [2.3] - class Xyz Creates an object that represents a single xyz file. ntpy.lattice.Xyz(file_name) Parameters ---------- file_name : str The name of the xyz file [2.3.1] - def buildXyz This creates and writes the xyz file based on the blocks provided ntpy.lattice.Xyz.buildXyz(blocks) Parameters ---------- blocks : list of type Block The blocks used to build the lammps file. Blocks should be put in order of origin to z-direction max. noisy : bool, optional If true, then function will print out Xyz details, otherwise the function will be quiet (default). [2.4] - class Block Defines a singular lattice that can linearly interfaced with other lattices ntpy.lattice.Block(lat_vector, lat_type, dim, bd_space=0, atom_mass=None, atom_type=None) Parameters ---------- lat_vector : list of type float The lattice constants for the x, y, and z directions lat_type : str The type of lattice to be constructed. Currently only 'sc', 'fcc', 'bcc', and 'diamond' are supported dim : list of type int The dimensions of the lattice in the x, y, and z directions. Dimensions are in units of lattice units. bd_space : float, optional The amount of space added at the terminating z boundary of the lattice. The space added is relative to the standard periodic foundary of the lattice. A negative value reduces the amount of space at the boundary. atom_mass : list of type float, optional The atom masses corresponding to the atoms in the basis vector. If only one mass is used then only one mass need be supplied. For a listing of the basis vector for each lattice type used by this module, use the lattice function "basis_print". Required for lammps files. atom_type : list of type str, optional The atom types of the lattice. Required for xyz files. [2.4.1] - def numUcell Int of the number of unit cells of the Block. [2.4.2] - def numAtomsUcell Int of the number of atoms in the unit cell. [2.4.3] - def numAtoms Int of the number of atoms in the Block. [2.4.4] - def Lx Float of the length of the Block in the x-direction. [2.4.5] - def Ly Float of the length of the Block in the y-direction. [2.4.6] - def Lz Float of the length of the Block in the z-direction. [2.5] - def printBasis Prints the basis vectors defined in this module for reference ntpy.lattice.printBasis(lat_type) Parameters ---------- lat_type : str The type of lattice to be constructed. Currently only 'sc', 'fcc', 'bcc', and 'diamond' are supported [2.6] - def kpt Creates an Lennard-Jones k-point list using either conventional or primative lattice vectors. ntpy.lattice.kpt(dim, conv=False) Parameters ---------- dim : array of type int An array that contains the number of unitcells in all three directions. conv : bool, optional If true, then k-points will be created using conventional lattice vector, otherwise the k-points will be created using primative lattice vector (default). Returns ---------- kpt : array of type float The array of k points in the shape of (numKpts, 3). [2.7] - def cubicKptSym Reduces the k-point list based on cubic symmetries. ntpy.lattice.cubicKptSym(kpt) Parameters ---------- kpt : numpy array of type float An array that contains the k-point list in any order. Array should be of shape (numKpts, 3). Returns ---------- irrKpt : numpy array of type float An array that contains the irreducible k-points irrKptCnt : numpy array of type int An array that contains the number of k-points reduced into one irreducible k-point degen : numpy array of type int An array the length of numKpts that relates the index of the original k-points to their equivalent index in irrKpt. E.g. degen[6] = 2 yeilds kpt[6,:] is symmetric to irrKpt[2,:].
/// Add color for default, focus, hover, and active states. /// /// @group 03-links /// /// @param {Color} $color - The default color. /// @param {Color} $color-hover - The hover color. /// @param {Color} $color-active [$color-hover] - The active color. /// @param {Color} $color-visited [$color] - The visited color. /// /// @example - scss Sample Usage /// a { /// @include link($color-primary, $color-accent); /// } /// /// @example - html /// <a href="#">Read More</a> @mixin link($color, $color-hover, $color-active: $color-hover, $color-visited: $color) { color: $color; &:visited { color: $color-visited; } &:focus, &:hover { color: $color-hover; } &:active { color: $color-active; } } /// Create decorative links with the `:after` pseudo element. /// /// @group 03-links /// /// @param {String} $content ['\2192'] - The content of the `:after` pseudo element. /// @param {Color} $color [currentColor] - The default main link color. /// @param {Color} $color-hover [currentColor] - The hover main link color. /// @param {Color} $color-active [$color-hover] - The active main link color. /// @param {Color} $color-visited [$color] - The visited main link color. /// @param {Color} $after-color [$color] - The `:after` default color. /// @param {Color} $after-color-hover [$after-color] - The hover `:after` color. /// @param {Color} $after-color-active [$after-color] - The active `:after` color. /// @param {Color} $after-color-visited [$after-color] - The visited `:after` color. /// /// @example - scss Sample Usage /// .link--fancy { /// @include decorative-link($content: '\00BB', $after-color: $color-accent); /// } /// /// @example - html /// <a href="#" class="link-fancy">Read More</a> @mixin decorative-link( $content: '\2192', $color: null, $color-hover: $color, $color-active: $color, $color-visited: $color, $after-color: currentColor, $after-color-hover: $after-color, $after-color-active: $after-color, $after-color-visited: $after-color ) { @if $color != null { @include link($color, $color-hover, $color-active, $color-visited); } &:after { color: $after-color; content: $content; display: inline-block; margin-left: em(5); transition: transform 0.3s ease-in-out; } &:visited { &:after { color: $after-color-visited; } } &:focus, &:hover { &:after { color: $after-color-hover; transform: translateX(em(10)); } } &:active { &:after { color: $after-color-active; } } }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; class Solution { public int[] topKFrequent(int[] nums, int k) { // Create frequency map of elements HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < nums.length; i++) { hm.put(nums[i], hm.getOrDefault(nums[i], 0) + 1); } // Create buckets to store elements with the same frequency List<Integer>[] buckets = new List[nums.length + 1]; for (int key : hm.keySet()) { int freq = hm.get(key); if (buckets[freq] == null) { buckets[freq] = new ArrayList<>(); } buckets[freq].add(key); } // Populate the result array with the top k frequent elements int[] res = new int[k]; int index = 0; // Initialize index to track position in res array for (int i = buckets.length - 1; i >= 0; i--) { if (buckets[i] != null) { for (int j = 0; j < buckets[i].size(); j++) { res[index++] = buckets[i].get(j); // Add elements from buckets to res if (index == k) { // Stop if k elements have been added return res; } } } } return res; // Return res even if less than k elements are found } }
type ListApiStatus = "ok" | "fail"; interface IListResult { listData?: any[]; total?: number; isLast?: boolean; // status: ListApiStatus; } interface IListOperationResult { // status: ListApiStatus; data?: any; } interface IGetListParams { pageSize: number; pageNum: number; type: GetListType; [key: string]: any; } /** * @description 控制获取列表接口是初始化数据,还是翻页操作。 */ type GetListType = "initial" | "loadMore"; interface IBehaviorWithList { /** * @description 注入data的名称 */ namespace: string; /** * @description 默认每页数量 */ defaultPageSize?: number; /** * @description 每项数据的唯一标识,默认【id】 */ key?: string; /** * @description 是否滚动到底部自动下一页,不用手动调用nextPageBehavior */ isAutoNextPage?: boolean; /** * @description 是否自动在onLoad中初始化第一页数据,不用手动调用getListBehavior */ isAutoLoad?: boolean; /** * @description 获取列表数据的接口,调用成功时必须返回{isLast:boolean,listData:array,total:number} */ getListApi: (params: Omit<IGetListParams, "type">) => Promise<IListResult>; /** * @description 新增数据的接口 */ addItemApi?: (data: any) => Promise<IListOperationResult>; /** * @param data:更新的数据 * @description 参数data必须包含唯一标识取参数key的值,默认为【id】 */ updateItemApi?: (data: any) => Promise<IListOperationResult>; /** * @description 删除数据的接口 */ deleteItemApi?: (id: any) => Promise<IListOperationResult>; } export interface BehaviorWithListInjectData<L = unknown> { pageSize?: number; pageNum?: number; listData?: L[]; total?: number; isLast?: boolean; } export interface BehaviorWithListInjectOption { /** * @description 下一页操作 */ nextPageBehavior?: (extraData?: Record<string, any>) => void; onSearchBehavior?: (searchData: Record<string, any>) => void; /** * @description 获取列表数据的方法 */ getListBehavior?: (params?: IGetListParams) => void; /** * @description 修改列表数据的方法 */ updateItemBehavior?: (data: any) => Promise<any>; /** * @description 添加列表数据的方法 */ addItemBehavior?: (data: any) => Promise<any>; /** * @description 删除列表数据的方法 */ deleteItemBehavior?: (id: any) => Promise<any>; //获取列表需要的额外的page data listExtraData?: string[]; } /** * * @description 注入列表的增、删、改、查逻辑的behavior */ const BehaviorWithList = (params: IBehaviorWithList) => { const { key = "id", namespace, isAutoNextPage, isAutoLoad, defaultPageSize = 10, getListApi, deleteItemApi, updateItemApi, addItemApi, } = params; return Behavior({ definitionFilter(defFields: any) { const onReachBottom = defFields?.methods?.onReachBottom; const onLoad = defFields?.methods?.onLoad; const getListExtraData = (pageData: Record<string, any>) => { const listExtraData = defFields?.listExtraData as string[]; if (listExtraData && listExtraData.length > 0) { return Object.entries(pageData).reduce( (total: Record<string, any>, [key, val]) => { if (listExtraData.includes(key)) { total[key] = val; } return total; }, {} ); } return {}; }; if (isAutoNextPage && defFields.methods) { defFields.methods.onReachBottom = function () { this.nextPageBehavior({ ...getListExtraData(this.data) }); onReachBottom && onReachBottom.call(this); }; } if (isAutoLoad && defFields.methods) { defFields.methods.onLoad = async function () { onLoad && (await onLoad.call(this)); wx.nextTick(() => { //onLoad中如果想要注入listExtraData中定义的data,并保持和页面一致,页面中的onLoad必须为async方法,内部保持同步的方式写代码 this.getListBehavior({ pageNum: 1, pageSize: defaultPageSize, type: "initail", ...getListExtraData(this.data), }); }); }; } }, data: { [namespace]: { pageSize: defaultPageSize ?? 10, pageNum: 1, listData: [], total: 0, isLast: false, isFetchNext: false, isFetchInit: false, }, _searchData: {}, }, methods: { /** * @description 获取下一页数据 * @param extraData Record<string, any>【将会被注入到获取列表数据的接口参数中】 */ nextPageBehavior(extraData?: Record<string, any>) { const { pageNum, pageSize, isFetchNext, isLast } = this.data[namespace]; if (!isLast && !isFetchNext) { this.getListBehavior({ ...extraData, pageNum: pageNum + 1, pageSize, type: "loadMore", }); } }, onSearchBehavior(searchData: Record<string, any> = {}) { const { pageSize } = this.data[namespace]; this.getListBehavior({ pageNum: 1, pageSize, type: "initial", ...searchData, }); this.setData({ _searchData: searchData, }); }, /** * @description 获取列表数据 * @param params pageSize?: number; pageNum: number; type?: 'initial' | 'loadMore', ...otherParams */ async getListBehavior(params?: IGetListParams) { const { listData, isFetchNext, isFetchInit } = this.data[namespace]; const { pageNum, pageSize, type, ...extraData } = params ?? { type: "initial", pageSize: defaultPageSize, pageNum: 1, }; if (!isFetchNext && !isFetchInit) { if (type === "initial") { this.setData({ [namespace]: { ...this.data[namespace], isFetchInit: true }, }); } if (type === "loadMore") { this.setData({ [namespace]: { ...this.data[namespace], isFetchNext: true }, }); } try { const data = await getListApi({ pageNum, pageSize, ...extraData, ...this.data._searchData, }); if ( typeof data.isLast !== "boolean" || !(data.listData instanceof Array) || typeof data.total !== "number" ) { throw new Error( "请在【getListApi】返回成功的情况下返回{isLast:boolean,listData:array,total:number}数据" ); } const updateData = { ...this.data[namespace], ...(data ?? {}), isFetchNext: false, isFetchInit: false, pageNum, pageSize, }; if (type === "initial") { this.setData({ [namespace]: updateData, }); } else { this.setData({ [namespace]: { ...updateData, listData: listData.concat(data.listData), }, }); } } catch (error) { console.log(error); throw new Error(error); } } }, /** * @description 更新数据的方法 * @param data 更新的数据 */ async updateItemBehavior(data: any) { const { listData } = this.data[namespace]; try { const res = await updateItemApi?.(data); const updateIdx = listData.findIndex( (item: any) => item[key] === data[key] ); if (updateIdx !== -1) { listData[updateIdx] = { ...listData[updateIdx], data }; this.setData({ [namespace]: { ...this.data[namespace], listData: [...listData], }, }); } return res?.data; } catch (error) { console.log(error); throw new Error(error); } }, /** * @description 新增数据的方法 * @param data 新增的数据 */ async addItemBehavior(data: any) { try { const res = await addItemApi?.(data); this.getListBehavior(); return res?.data; } catch (error) { console.log(error); throw new Error(error); } }, /** * @description 删除数据的方法 * @param id 删除数据的id */ async deleteItemBehavior(id: any) { const { listData, pageSize, pageNum, isLast } = this.data[namespace]; try { const res = await deleteItemApi?.(id); const deleteIdx = listData.findIndex((item: any) => item[key] === id); if (deleteIdx !== -1) { //删除本地数据 listData.splice(deleteIdx, 1); if (!isLast) { //如果不是最后一页,将会请求当前页的最后一条数据补齐列表,保证页码准确 const { total, isLast, listData: newListData } = await getListApi( { pageSize: 1, pageNum: pageNum * pageSize, } ); if (newListData?.[0]) { listData.push(newListData[0]); this.setData({ [namespace]: { ...this.data[namespace], listData: [...listData], total, isLast, }, }); } else { this.setData({ [namespace]: { ...this.data[namespace], listData: [...listData], }, }); } } else { this.setData({ [namespace]: { ...this.data[namespace], listData: [...listData], }, }); } } return res?.data; } catch (error) { console.log(error); throw new Error(error); } }, }, }); }; export default BehaviorWithList;
<template> <v-form ref="form" v-model="userValid" class="text-center"> <v-text-field v-model="user.facebookId" :counter="0" :rules="userRules.facebookId" :label="userLabel.facebookId"></v-text-field> <v-text-field v-model="user.googleId" :counter="0" :rules="userRules.googleId" :label="userLabel.googleId"></v-text-field> <v-text-field v-model="user.email" :counter="0" :rules="userRules.email" :label="userLabel.email" required></v-text-field> <v-text-field v-model="user.password" :counter="50" :rules="userRules.password" :label="userLabel.password"></v-text-field> <v-text-field v-model="user.photo" :counter="0" :rules="userRules.photo" :label="userLabel.photo"></v-text-field> <v-text-field v-model="user.displayName" :counter="0" :rules="userRules.displayName" :label="userLabel.displayName" required></v-text-field> <v-text-field v-model="user.telephone" :counter="30" :rules="userRules.telephone" :label="userLabel.telephone"></v-text-field> <v-text-field type="date" v-model="user.birthDate" :rules="userRules.birthDate" :label="userLabel.birthDate"></v-text-field> <v-radio-group v-model="user.gender"> <v-radio v-for="option in genderItems" :key="option" :label="`${option}`" :value="option"></v-radio> </v-radio-group> <v-btn :disabled="!userValid" color="success" class="mr-4" @click="onSubmitUser">Submit</v-btn> </v-form> </template> <script> export default { data: () => ({ userValid: true, genderItems: ["Male", "Female", "Other"], user: { facebookId: undefined, googleId: undefined, email: undefined, password: undefined, photo: undefined, displayName: undefined, telephone: undefined, birthDate: undefined, gender: "Other", passwordChangedAt: undefined, passwordResetToken: undefined, passwordResetExpires: undefined, isActive: undefined, }, userRules: { facebookId: [], googleId: [], email: [ v => !!v || `${this.userLabel.email} es requerido!`, ], password: [ v => (v && v.length >= 8) || 'password debe tener al menos 8 caracteres!', v => (v && v.length < 50) || 'password debe tener menos de 50 caracteres!', ], photo: [], displayName: [ v => !!v || `${this.userLabel.displayName} es requerido!`, ], telephone: [ v => (v && v.length >= 5) || 'telephone debe tener al menos 5 caracteres!', v => (v && v.length < 30) || 'telephone debe tener menos de 30 caracteres!', ], birthDate: [], }, userLabel: { facebookId: "FacebookId", googleId: "GoogleId", email: "Email", password: "Password", photo: "Photo", displayName: "DisplayName", telephone: "Telephone", birthDate: "BirthDate", gender: "Gender", passwordChangedAt: "PasswordChangedAt", passwordResetToken: "PasswordResetToken", passwordResetExpires: "PasswordResetExpires", isActive: "IsActive", }, }), methods: { async onSubmitUser() {}, }, }; </script> <style></style>
using Application.Contracts; using Application.DTO.PostDTO.DTO; using Application.Exceptions; using Application.Features.PostFeature.Requests.Queries; using Application.Response; using AutoMapper; using MediatR; namespace Application.Features.PostFeature.Handlers.Queries; public class GetPostsByTagHandler : IRequestHandler<GetPostsByTagQuery, BaseResponse<List<PostResponseDTO>>> { private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; public GetPostsByTagHandler( IUnitOfWork unitOfWork,IMapper mapper ) { _mapper = mapper; _unitOfWork = unitOfWork; } public async Task<BaseResponse<List<PostResponseDTO>>> Handle(GetPostsByTagQuery request, CancellationToken cancellationToken) { var result = await _unitOfWork.PostRepository.GetByTagName(request.TagName); if(result ==null){ throw new NotFoundException("Tag Not found"); } return new BaseResponse<List<PostResponseDTO>> { Success = true, Message = "Posts are retrieved successfully", Value = _mapper.Map<List<PostResponseDTO>>(result) }; } }
/* ----------------------------------------------------------------------- * * * Copyright 2000-2008 H. Peter Anvin - All Rights Reserved * Copyright 2009 Intel Corporation; author: H. Peter Anvin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, Inc., 675 Mass Ave, Cambridge MA 02139, * USA; either version 2 of the License, or (at your option) any later * version; incorporated herein by reference. * * ----------------------------------------------------------------------- */ /* * x86 MSR access device * * This device is accessed by lseek() to the appropriate register number * and then read/write in chunks of 8 bytes. A larger size means multiple * reads or writes of the same register. * * This driver uses /dev/cpu/%d/msr where %d is the minor number, and on * an SMP box will direct the access to CPU %d. */ #include <linux/module.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/smp.h> #include <linux/smp_lock.h> #include <linux/major.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/cpu.h> #include <linux/notifier.h> #include <linux/uaccess.h> #include <asm/processor.h> #include <asm/msr.h> #include <asm/system.h> static struct class *msr_class; static loff_t msr_seek(struct file *file, loff_t offset, int orig) { loff_t ret; struct inode *inode = file->f_mapping->host; mutex_lock(&inode->i_mutex); switch (orig) { case 0: file->f_pos = offset; ret = file->f_pos; break; case 1: file->f_pos += offset; ret = file->f_pos; break; default: ret = -EINVAL; } mutex_unlock(&inode->i_mutex); return ret; } static ssize_t msr_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { u32 __user *tmp = (u32 __user *) buf; u32 data[2]; u32 reg = *ppos; int cpu = iminor(file->f_path.dentry->d_inode); int err = 0; ssize_t bytes = 0; if (count % 8) return -EINVAL; /* Invalid chunk size */ for (; count; count -= 8) { err = rdmsr_safe_on_cpu(cpu, reg, &data[0], &data[1]); if (err) break; if (copy_to_user(tmp, &data, 8)) { err = -EFAULT; break; } tmp += 2; bytes += 8; } return bytes ? bytes : err; } static ssize_t msr_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { const u32 __user *tmp = (const u32 __user *)buf; u32 data[2]; u32 reg = *ppos; int cpu = iminor(file->f_path.dentry->d_inode); int err = 0; ssize_t bytes = 0; if (count % 8) return -EINVAL; /* Invalid chunk size */ for (; count; count -= 8) { if (copy_from_user(&data, tmp, 8)) { err = -EFAULT; break; } err = wrmsr_safe_on_cpu(cpu, reg, data[0], data[1]); if (err) break; tmp += 2; bytes += 8; } return bytes ? bytes : err; } static long msr_ioctl(struct file *file, unsigned int ioc, unsigned long arg) { u32 __user *uregs = (u32 __user *)arg; u32 regs[8]; int cpu = iminor(file->f_path.dentry->d_inode); int err; switch (ioc) { case X86_IOC_RDMSR_REGS: if (!(file->f_mode & FMODE_READ)) { err = -EBADF; break; } if (copy_from_user(&regs, uregs, sizeof regs)) { err = -EFAULT; break; } err = rdmsr_safe_regs_on_cpu(cpu, regs); if (err) break; if (copy_to_user(uregs, &regs, sizeof regs)) err = -EFAULT; break; case X86_IOC_WRMSR_REGS: if (!(file->f_mode & FMODE_WRITE)) { err = -EBADF; break; } if (copy_from_user(&regs, uregs, sizeof regs)) { err = -EFAULT; break; } err = wrmsr_safe_regs_on_cpu(cpu, regs); if (err) break; if (copy_to_user(uregs, &regs, sizeof regs)) err = -EFAULT; break; default: err = -ENOTTY; break; } return err; } static int msr_open(struct inode *inode, struct file *file) { unsigned int cpu = iminor(file->f_path.dentry->d_inode); struct cpuinfo_x86 *c = &cpu_data(cpu); int ret = 0; lock_kernel(); cpu = iminor(file->f_path.dentry->d_inode); if (cpu >= nr_cpu_ids || !cpu_online(cpu)) { ret = -ENXIO; /* No such CPU */ goto out; } c = &cpu_data(cpu); if (!cpu_has(c, X86_FEATURE_MSR)) ret = -EIO; /* MSR not supported */ out: unlock_kernel(); return ret; } /* * File operations we support */ static const struct file_operations msr_fops = { .owner = THIS_MODULE, .llseek = msr_seek, .read = msr_read, .write = msr_write, .open = msr_open, .unlocked_ioctl = msr_ioctl, .compat_ioctl = msr_ioctl, }; static int __cpuinit msr_device_create(int cpu) { struct device *dev; dev = device_create(msr_class, NULL, MKDEV(MSR_MAJOR, cpu), NULL, "msr%d", cpu); return IS_ERR(dev) ? PTR_ERR(dev) : 0; } static void msr_device_destroy(int cpu) { device_destroy(msr_class, MKDEV(MSR_MAJOR, cpu)); } static int __cpuinit msr_class_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { unsigned int cpu = (unsigned long)hcpu; int err = 0; switch (action) { case CPU_UP_PREPARE: err = msr_device_create(cpu); break; case CPU_UP_CANCELED: case CPU_UP_CANCELED_FROZEN: case CPU_DEAD: msr_device_destroy(cpu); break; } return err ? NOTIFY_BAD : NOTIFY_OK; } static struct notifier_block __refdata msr_class_cpu_notifier = { .notifier_call = msr_class_cpu_callback, }; static char *msr_devnode(struct device *dev, mode_t *mode) { return kasprintf(GFP_KERNEL, "cpu/%u/msr", MINOR(dev->devt)); } static int __init msr_init(void) { int i, err = 0; i = 0; if (__register_chrdev(MSR_MAJOR, 0, NR_CPUS, "cpu/msr", &msr_fops)) { printk(KERN_ERR "msr: unable to get major %d for msr\n", MSR_MAJOR); err = -EBUSY; goto out; } msr_class = class_create(THIS_MODULE, "msr"); if (IS_ERR(msr_class)) { err = PTR_ERR(msr_class); goto out_chrdev; } msr_class->devnode = msr_devnode; for_each_online_cpu(i) { err = msr_device_create(i); if (err != 0) goto out_class; } register_hotcpu_notifier(&msr_class_cpu_notifier); err = 0; goto out; out_class: i = 0; for_each_online_cpu(i) msr_device_destroy(i); class_destroy(msr_class); out_chrdev: __unregister_chrdev(MSR_MAJOR, 0, NR_CPUS, "cpu/msr"); out: return err; } static void __exit msr_exit(void) { int cpu = 0; for_each_online_cpu(cpu) msr_device_destroy(cpu); class_destroy(msr_class); __unregister_chrdev(MSR_MAJOR, 0, NR_CPUS, "cpu/msr"); unregister_hotcpu_notifier(&msr_class_cpu_notifier); } module_init(msr_init); module_exit(msr_exit) MODULE_AUTHOR("H. Peter Anvin <hpa@zytor.com>"); MODULE_DESCRIPTION("x86 generic MSR driver"); MODULE_LICENSE("GPL");
const multer = require("multer"); const sharp = require("sharp"); const cloudinary = require("cloudinary").v2; const AppError = require("../utils/appError"); const catchAsync = require("../utils/catchAsync"); //* Multer Configuration ******************************************* const multerStorage = multer.memoryStorage(); const multerFilter = (req, file, cb) => { if (file.mimetype.startsWith("image")) { cb(null, true); } else { cb(new AppError("Not an image! Please upload images only.", 400), false); } }; const upload = multer({ storage: multerStorage, fileFilter: multerFilter }); //* cloudinary Configuration *************************************** cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, }); //* cloudinary Upload ********************************************** const cloudinaryUpload = async (buffer, filename, next, type) => new Promise((resolve) => { cloudinary.uploader .upload_stream( { folder: `natours-${type}`, public_id: filename, }, (error, result) => { if (error) { return next(new AppError("Error uploading image", 500)); } resolve(result.secure_url); } ) .end(buffer); }); //* Middlewares **************************************************** //* Upload user photo ********************************************** exports.uploadUserPhoto = upload.single("photo"); //* Resize user photo ********************************************** exports.resizeUserPhoto = catchAsync(async (req, res, next) => { if (req.file?.fieldname !== "photo") return next(); const resizedImageBuffer = await sharp(req.file.buffer) .resize(500, 500) .toFormat("jpeg") .jpeg({ quality: 90 }) .toBuffer(); req.photo = await cloudinaryUpload( resizedImageBuffer, `user-${req.params.id}-${Date.now()}`, next, "users" ); next(); }); //* Upload tour photos ********************************************* exports.uploadTourPhotos = upload.fields([ { name: "imageCover", maxCount: 1 }, { name: "images", maxCount: 3 }, ]); //* Resize tour photos ********************************************* exports.resizeTourPhotos = catchAsync(async (req, res, next) => { if (!req.files) return next(); // Cover Image resizing if (req.files.imageCover) { const resizedImageCoverBuffer = await sharp(req.files.imageCover[0].buffer) .resize(2000, 1333) .toFormat("jpeg") .jpeg({ quality: 90 }) .toBuffer(); req.body.imageCover = await cloudinaryUpload( resizedImageCoverBuffer, `tour-${req.params.id}-${Date.now()}-cover`, next, "tours" ); } // Tour images resizing if (req.files.images) { if (!req.body.images) req.body.images = []; if (typeof req.body.images === "string") req.body.images = [req.body.images]; await Promise.all( req.files.images.map(async (file, index) => { const image = await sharp(file.buffer) .resize(2000, 1333) .toFormat("jpeg") .jpeg({ quality: 90 }) .toBuffer(); req.body.images.push( await cloudinaryUpload( image, `tour-${req.params.id}-${Date.now()}-${index + 1}`, next, "tours" ) ); }) ); } next(); });
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Fonts --> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet"> <!-- Scripts --> @vite(['resources/sass/app.scss', 'resources/js/app.js']) </head> <body> <div id="app"> <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm"> <div class="container"> <a class="navbar-brand" href="{{ url('/home') }}"> {{ config('app.name', 'Laravel') }} </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!-- Left Side Of Navbar --> <ul class="navbar-nav me-auto"> </ul> <!-- Right Side Of Navbar --> <ul class="navbar-nav ms-auto"> <!-- Authentication Links --> @guest @if (Route::has('login')) <li class="nav-item"> <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a> </li> @endif @if (Route::has('register')) <li class="nav-item"> <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a> </li> @endif @else <li><a class="nav-link" href="{{ route('home') }}">Dashboard</a></li> {{-- navbar Menu --}} <li class="nav-item dropdown"> <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> Menu </a> {{-- users --}} <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown"> @can('role-list') <a class="dropdown-item" href="{{ route('roles.index') }}"> Manage Role </a> @endcan @can('user-list') <a class="dropdown-item" href="{{ route('users.index') }}"> Manage Users </a> @endcan @can('tahunajaran-list') <a class="dropdown-item" href="{{ route('tahunajaran.index') }}"> Manage Tahun Ajaran </a> @endcan @can('kelas-list') <a class="dropdown-item" href="{{ route('kelas.index') }}"> Manage Kelas </a> @endcan @can('siswa-list') <a class="dropdown-item" href="{{ route('siswas.index') }}"> Manage Siswa </a> @endcan @can('log-list') <a class="dropdown-item" href="{{ route('log.index') }}"> Activity Log </a> @endcan </div> {{-- end --}} </li> {{-- menu --}} {{-- navbar Auth User --}} <li class="nav-item dropdown"> <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> {{ Auth::user()->name }} </a> <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown"> <a href="{{ route('user.profile') }}" class="dropdown-item">Profile</a> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none"> @csrf </form> </div> </li> {{-- end --}} @endguest </ul> </div> </div> </nav> <main class="py-4"> <div class="container"> @yield('css') @yield('content') @yield('scripts') </div> </main> </div> </body> </html>
import { DataTypes } from 'sequelize'; export default function (sequelize) { const regularSchedule = sequelize.define( 'regularSchedule', { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, day: { type: DataTypes.TEXT, allowNull: false, validate: { notEmpty: true, isIn: [[ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]], } }, importHash: { type: DataTypes.STRING(255), allowNull: true, validate: { len: [0, 255], }, }, }, { indexes: [ { unique: true, fields: ['importHash', 'tenantId'], where: { deletedAt: null, }, }, { unique: true, fields: ['day', 'tenantId'], where: { deletedAt: null, }, }, ], timestamps: true, paranoid: true, }, ); regularSchedule.associate = (models) => { models.regularSchedule.belongsToMany(models.musicTrack, { as: 'musicTrack', constraints: false, through: 'regularScheduleMusicTrackMusicTrack', }); models.regularSchedule.belongsTo(models.tenant, { as: 'tenant', foreignKey: { allowNull: false, }, }); models.regularSchedule.belongsTo(models.user, { as: 'createdBy', }); models.regularSchedule.belongsTo(models.user, { as: 'updatedBy', }); }; return regularSchedule; }