text
stringlengths
184
4.48M
# https://leetcode.com/problems/fair-distribution-of-cookies/ """ How to solve: Check all the possible distributions and return the minimum of max of each distribution """ class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: if k == len(cookies): # each student gets one bag and the minimum unfairness is max of cookies return max(cookies) # keep students arr where ith student gets some m amount of total cookies students = [0] * k result = inf def backtrack(index): nonlocal result, students, cookies # now we distribute the index th bag of cookies # if all the cookies are distributed, get unfairness for this distribution if index == len(cookies): unfairness = max(students) result = min(result, unfairness) return # give this bag to each student one by one for i in range(k): # give this bag of cookie to the index th student students[i] += cookies[index] # go to the next bag of cookies backtrack(index + 1) # take the cookies back. students[i] -= cookies[index] backtrack(0) return result
package br.edu.ifsp.aluno.garagecarroom.ui import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider import br.edu.ifsp.aluno.garagecarroom.data.Car import br.edu.ifsp.aluno.garagecarroom.viewmodel.CarViewModel import com.google.android.material.snackbar.Snackbar import androidx.navigation.fragment.findNavController import br.edu.ifsp.aluno.garagecarroom.R import br.edu.ifsp.aluno.garagecarroom.databinding.FragmentAddBinding class AddFragment : Fragment() { private var _binding: FragmentAddBinding? = null private val binding get() = _binding!! lateinit var viewModel: CarViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider(this).get(CarViewModel::class.java) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentAddBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val menuHost: MenuHost = requireActivity() menuHost.addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.add_menu, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { // Handle the menu selection return when (menuItem.itemId) { R.id.action_salvarContato -> { val carModel = binding.commonLayout.modelET.text.toString() val carYear = binding.commonLayout.yearET.text.toString() val carColor = binding.commonLayout.colorET.text.toString() val car = Car(0,carModel, carYear, carColor) viewModel.insert(car) Snackbar.make(binding.root, "Novo carro inserido", Snackbar.LENGTH_SHORT).show() findNavController().popBackStack() true } else -> false } } }, viewLifecycleOwner, Lifecycle.State.RESUMED) } }
# -*- coding: utf-8 -*- # # This file is part of the invenio-remote-user-data package. # Copyright (C) 2023, MESH Research. # # invenio-remote-user-data is free software; you can redistribute it # and/or modify it under the terms of the MIT License; see # LICENSE file for more details. from flask import current_app as app from invenio_access.permissions import system_identity from invenio_accounts.models import Role, User from invenio_accounts.proxies import current_accounts from invenio_pidstore.errors import PIDDoesNotExistError from invenio_users_resources.proxies import current_groups_service from invenio_records_resources.resources.errors import PermissionDeniedError from invenio_users_resources.services.groups.results import ( GroupItem, GroupList, ) # from invenio_records_resources.services.uow import unit_of_work # , RecordCommitOp from invenio_records_resources.services.records.components import ( ServiceComponent, ) from pprint import pformat from typing import Union, Optional # TODO: Most of these operations use the invenio_accounts datastore # directly. The invenio-users-resources groups service may be appropriate, # but it seems not to support the same kind of record operations. class GroupRolesComponent(ServiceComponent): """Service component for groups.""" def __init__(self, service, *args, **kwargs): super().__init__(service, *args, **kwargs) def get_roles_for_remote_group( self, remote_group_id: str, idp: str ) -> list[Role]: """Get the Invenio roles for a remote group.""" query_string = f"{idp}---{remote_group_id}|" query = current_accounts.datastore.role_model.query.filter( Role.id.contains(query_string) ) local_groups = query.all() return local_groups @staticmethod def get_current_members_of_group(group_name: str) -> list[User]: """fetch a list of the users assigned the given group role""" my_group_role = current_accounts.datastore.find_role(group_name) app.logger.debug(f"got group role {my_group_role}") return [user for user in my_group_role.users] def get_current_user_roles(self, user: Union[str, User]) -> list: """_summary_ Args: user (Union[str, User]): _description_ Returns: list: _description_ """ return_user = user if isinstance(user, str): return_user = current_accounts.datastore.find_user(email=user) if return_user is None: raise RuntimeError(f'User "{user}" not found.') return return_user.roles def find_or_create_group( self, group_name: str, **kwargs ) -> Optional[Role]: """Search for a group with a given name and create it if it doesn't exist.""" my_group_role = current_accounts.datastore.find_or_create_role( name=group_name, **kwargs ) current_accounts.datastore.commit() if my_group_role is not None: app.logger.debug( f'Role for group "{group_name}" found or created.' ) else: raise RuntimeError( f'Role for group "{group_name}" not found or created.' ) return my_group_role def create_new_group(self, group_name: str, **kwargs) -> Optional[Role]: """Create a new group with the given name (and optional parameters).""" my_group_role = current_accounts.datastore.create_role( name=group_name, **kwargs ) current_accounts.datastore.commit() if my_group_role is not None: app.logger.info(f'Role "{group_name}" created successfully.') else: raise RuntimeError(f'Role "{group_name}" not created.') return my_group_role def delete_group(self, group_name: str, **kwargs) -> bool: """Delete a group role with the given name. returns: bool: True if the group was deleted successfully, otherwise False. """ deleted = False my_group_role = current_accounts.datastore.find_role(group_name) if my_group_role is None: raise RuntimeError(f'Role "{group_name}" not found.') else: try: current_accounts.datastore.delete(my_group_role) current_accounts.datastore.commit() app.logger.info(f'Role "{group_name}" deleted successfully.') deleted = True # FIXME: This is a hack to catch the AttributeError that # is thrown when the deleted role is not found in the post-commit # cleanup. except AttributeError as a: app.logger.error(a) deleted = True except Exception as e: raise RuntimeError( f'Role "{group_name}" not deleted. {pformat(e)}' ) return deleted def add_user_to_group(self, group_name: str, user: User, **kwargs) -> bool: """Add a user to a group.""" app.logger.debug(f"got group name {group_name}") user_added = current_accounts.datastore.add_role_to_user( user, group_name ) current_accounts.datastore.commit() if user_added is False: raise RuntimeError("Cannot add user to group role.") else: user_str = user.email if isinstance(user, User) else user app.logger.info( f'Role "{group_name}" added to user"{user_str}" successfully.' ) return user_added def find_group(self, group_name: str) -> Optional[Role]: """Find a group role with the given name.""" my_group_role = current_accounts.datastore.find_role(group_name) if my_group_role is None: app.logger.debug(f'Role "{group_name}" not found.') else: app.logger.debug(f'Role "{group_name}" found successfully.') return my_group_role def remove_user_from_group( self, group_name: Union[str, Role], user: Union[str, User], **kwargs ) -> bool: """Remove a group role from a user. args: group_name: The name of the group to remove the user from, or the Role object for the group. user: The user object to remove from the group, or the user's email address. """ user = ( user if isinstance(user, User) else current_accounts.datastore.get_user_by_id(user) ) group_name = ( group_name if isinstance(group_name, str) else group_name.id ) app.logger.debug(f"removing from user {user.email}") app.logger.debug(user.roles) removed_user = current_accounts.datastore.remove_role_from_user( user, group_name ) current_accounts.datastore.commit() if removed_user is False: app.logger.debug( "Role {group_name} could not be removed from user." ) else: app.logger.info( f'Role "{group_name}" removed from user "{user.email}"' "successfully." ) return removed_user
import "bootstrap/dist/css/bootstrap.min.css"; import { Route, Routes } from "react-router-dom"; import Login from "./pages/Login"; import Profile from "./pages/Profile"; import Users from "./pages/Users"; import NavBar from "./components/NavBar"; import PrivateRoute from "./utils/PrivateRoute"; import PublicRoute from "./utils/PublicRoute"; import { Toaster } from "react-hot-toast"; import Layout from "./Layout"; import AddUsers from "./pages/AddUsers"; function App() { return ( <> <NavBar /> <Routes> <Route element={<AddUsers />} path="/add" /> <Route element={<Layout />} path="/"> <Route element={<PublicRoute />}> <Route path="login" element={<Login />} /> </Route> <Route element={<PrivateRoute />}> <Route path="profile" element={<Profile />} /> <Route path="users" element={<Users />} /> </Route> </Route> </Routes> <Toaster position="bottom-right" /> </> ); } export default App;
Question: Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Test Case 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] Test Case 2: Input: numRows = 1 Output: [[1]] Constraints: 1 <= numRows <= 30 Logics:- class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new LinkedList<>(); List<Integer> row, pre = null; for(int i = 0; i < numRows; i++){ row = new LinkedList<Integer>(); for(int j = 0; j <= i; j++){ if(j == 0 || j == i) row.add(1); else row.add(pre.get(j-1)+pre.get(j)); } pre = row; res.add(row); } return res; } }
import logging from datetime import datetime from typing import List from fastapi import Query from pydantic import BaseModel from sqlalchemy import text import models from helpers.exceptions import ValidationError, NotFoundError, AuthorizationError from helpers.permissions import permission_access from helpers.response import FailureResponse, exception_quieter, SuccessResponse from repositories.helpers import BaseRepository from schemas import sales as schemas from signals import pre_save, post_save, pre_delete class SaleRepository(BaseRepository): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.model = models.Sale @staticmethod def query_parameters(paid: bool = Query(default=None, title="paid", description="filter by paid or non paid sales"), search: str = Query(default=None, title="search", description="search for customer and/or location"), date_ordered_start: datetime = Query(default=None, title="date_ordered_start", description=" start date for date ordered"), date_ordered_stop: datetime = Query(default=None, title="ate_ordered_stop", description="end date for date ordered"), date_paid_start: datetime = Query(default=None, title="date_paid_start", description=" start date for date paid"), date_paid_stop: datetime = Query(default=None, title="date_paid_stop", description="end date for date paid") ): if date_ordered_start: date_ordered_start = datetime.strptime(str(date_ordered_start), "%Y-%m-%d %H:%M:%S", ) if date_ordered_stop: date_ordered_stop = datetime.strptime(str(date_ordered_stop), "%Y-%m-%d %H:%M:%S", ) if date_paid_start: date_paid_start = datetime.strptime(str(date_paid_start), "%Y-%m-%d %H:%M:%S", ) if date_paid_stop: date_paid_stop = datetime.strptime(str(date_paid_stop), "%Y-%m-%d %H:%M:%S", ) return {"paid": paid, "search": search, "date_ordered_stop": date_ordered_stop, "date_ordered_start": date_ordered_start, "date_paid_stop": date_paid_stop, "date_paid_start": date_paid_start, } @exception_quieter async def create(self, item: schemas.CreateSale, **kwargs): data = item.model_dump() orders = data.pop("orders") product_ids = [order['product_id'] for order in orders] product_count = self.db.query(models.Product).filter(models.Product.id.in_(product_ids)).count() if len(product_ids) != product_count: raise ValidationError(detail="You have non existent products in this orders") data["date_ordered"] = datetime.now() sale = self.model(**data) await pre_save.send(sale) self.db.add(sale) self.db.commit() self.db.refresh(sale) orders = [models.Order(**order, sale_id=sale.id) for order in orders] self.db.bulk_save_objects(orders) self.db.commit() self.db.refresh(sale) await post_save.send(sale, created=True) return SuccessResponse(message="Sale created successfully") async def update(self, id: int, new_data: BaseModel): return FailureResponse(message="Sale cannot be updated") @exception_quieter async def add_orders(self, id:int, orders: List[schemas.OrderItem]): sale:models.Sale = await self.get(id=id) if not sale: raise NotFoundError(detail="This Sale does not exist") if sale.paid: raise ValidationError(detail="This sale is already paid for. Please create another sale.") orders = [models.Order(**order.model_dump(), sale_id=id) for order in orders] product_ids = [order.product_id for order in orders] product_count = self.db.query(models.Product).filter(models.Product.id.in_(product_ids)).count() if len(product_ids) != product_count: raise ValidationError(detail="You have non existent products in this orders") self.db.bulk_save_objects(orders) self.db.commit() self.db.refresh(sale) return SuccessResponse(message="Orders added successfully") @exception_quieter async def remove_orders(self, id:int, order_ids: List[int]): sale: models.Sale = await self.get(id=id) if not sale: raise NotFoundError(detail="This Sale does not exist") if sale.paid: raise ValidationError(detail="This sale is already paid for and cannot be edited") querystring = text("delete from orders where sale_id = :id and id in :order_ids") self.db.execute(querystring, {"id": id, "order_ids": order_ids}) self.db.commit() self.db.refresh(sale) return SuccessResponse(message="Selected Orders have been removed successfully") @exception_quieter async def mark_paid(self, id:int): sale: models.Sale = await self.get(id=id) if not sale: raise NotFoundError(detail="This Sale does not exist") if sale.paid: return sale await pre_save.send(sale) querystring = text("update sales set paid = true, date_paid = :now where id = :id") self.db.execute(querystring, {"id": id, "now": datetime.now()}) self.db.commit() self.db.refresh(sale) await post_save.send(sale, created=False) return SuccessResponse(message="Sale has been successfully marked as paid") @exception_quieter @permission_access(admin=False, staff=False) async def delete(self, id: int, **kwargs): sale = await self.get(id=id) if not sale: raise NotFoundError(detail="This Sale does not exist") if sale.paid: raise ValidationError(detail="This sale has been paid for and therefore cannot be deleted") if self.user.customer_id == sale.customer_id: raise AuthorizationError(detail="You are not the owner of this sale") await pre_delete.send(sale) querystring = text("delete from sales where id = :id") self.db.execute(querystring, {"id": id}) self.db.commit() return SuccessResponse(status=204) async def get_by_id(self, id: int): querystring = text("select * from sales_view where id = :id ;") sale_detail = dict(self.db.execute(querystring, {"id": id}).mappings().first()) querystring = text("select * from orders_view where sale_id = :id ;") orders = self.db.execute(querystring, {"id": id}).mappings().all() sale_detail["orders"] = orders return sale_detail async def get_all(self, skip: int = 0, limit: int = 100, search:str=None, paid:bool=None, date_ordered_start:datetime=None, date_ordered_stop:datetime=None, date_paid_start:datetime=None, date_paid_stop:datetime=None): querystring = "select * from sales_view" params = dict() if search: querystring = f"{querystring} {'where' if 'where' not in querystring else 'and'} location ilike :search or customer ilike :search" params["search"] = f"%{search}%" if paid is not None: querystring = f"{querystring} {'where' if 'where' not in querystring else 'and'} paid = :paid" params["paid"] = paid if date_ordered_start and date_ordered_stop: querystring = f"{querystring} {'where' if 'where' not in querystring else 'and'} date_ordered >= :date_ordered_start and date_ordered <= :date_ordered_end" params["date_ordered_start"] = date_ordered_start params["date_ordered_end"] = date_ordered_stop if date_paid_start and date_paid_stop: querystring = f"{querystring} {'where' if 'where' not in querystring else 'and'} date_paid >= :date_paid_start and date_paid <= :date_paid_end" params["date_paid_start"] = date_paid_start params["date_paid_end"] = date_paid_stop count = self.db.execute(text(f"{querystring.replace('select *', 'select count(*)', 1)};"), params).mappings().first()["count"] querystring = f"{querystring} offset :skip limit :limit ;" params["skip"] = skip params["limit"] = limit return {"count": count, "results": self.db.execute(text(querystring), params).mappings().all()} @exception_quieter @permission_access(customer=False, admin=False) async def mark_order_as_delivered(self, order_id:int): order = self.db.query(models.Order).filter(models.Order.id == order_id).first() if not order: raise NotFoundError(detail="This order does not exist") if order.staff_id is None: raise NotFoundError(detail="This order has no staff assigned to it") if order.staff_id != self.user.staff_id: raise AuthorizationError(detail="You are not assigned to this order") querystring = "update orders set delivered = true, date_delivered = :now where id = :order_id ;" self.db.execute(text(querystring), {"order_id": order_id, "now": datetime.now()}) self.db.commit() return SuccessResponse(message="This order has been successfully marked as delivered") @exception_quieter @permission_access(customer=False, staff=False) async def assign_staff_to_orders(self, staff_id:int, order_ids:List[int]): orders_with_staffs = self.db.query(models.Order).filter(models.Order.id.in_(order_ids), models.Order.staff_id != None).count() > 0 if orders_with_staffs: raise ValidationError(detail="Some selected orders already have staffs assigned to them") delivered_orders = self.db.query(models.Order).filter(models.Order.id.in_(order_ids), models.Order.delivered == True).count() > 0 if delivered_orders: raise ValidationError(detail="Some selected orders are already delivered and cannot be updated") querystring = "update orders set staff_id = :staff_id where id in :ids ;" self.db.execute(text(querystring), {"staff_id": staff_id, "ids": order_ids}) self.db.commit() return SuccessResponse(message="Staffs have been successfully assigned to selected orders") @exception_quieter @permission_access(customer=False, staff=False) async def remove_staff_from_orders(self, staff_id: int, order_ids: List[int]): delivered_orders = self.db.query(models.Order).filter(models.Order.id.in_(order_ids), models.Order.delivered == True).count() > 0 if delivered_orders: raise ValidationError(detail="Some selected orders are already delivered and cannot be updated") querystring = "update orders set staff_id = NULL where id in :ids ;" self.db.execute(text(querystring), {"staff_id": staff_id, "ids": order_ids}) self.db.commit() return SuccessResponse(message="Staffs have been successfully removed from the selected orders")
package leetcode.editor.cn; //给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。你可以按 任意顺序 返回答案。 // // // // 进阶:你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现? // // // // 示例 1: // // //输入:nums = [1,2,1,3,2,5] //输出:[3,5] //解释:[5, 3] 也是有效的答案。 // // // 示例 2: // // //输入:nums = [-1,0] //输出:[-1,0] // // // 示例 3: // // //输入:nums = [0,1] //输出:[1,0] // // // 提示: // // // 2 <= nums.length <= 3 * 10⁴ // -2³¹ <= nums[i] <= 2³¹ - 1 // 除两个只出现一次的整数外,nums 中的其他数字都出现两次 // // Related Topics 位运算 数组 👍 596 👎 0 class _260_只出现一次的数字III { public static void main(String[] args) { Solution solution = new _260_只出现一次的数字III().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[] singleNumber(int[] nums) { int xorsum = 0; for (int num : nums) { xorsum ^= num; } // 综上,可以通过获取最低有效位把两个数分开 // 防止溢出 // 因为二进制有正负0,负零用于多表示一位负数,这个负数如果取相反数,会产生溢出,所以不能用 a & (-a) 取最低有效位 // 负0的特点是第一位是1,其余位是0,所以它的最低有效位就是自己 // MIN_VALUE 的特点就是最高位是1 int lsb = (xorsum == Integer.MIN_VALUE ? xorsum : xorsum & (-xorsum)); int type1 = 0, type2 = 0; for (int num : nums) { if ((num & lsb) != 0) { type1 ^= num; } else { type2 ^= num; } } return new int[]{type1, type2}; } } //leetcode submit region end(Prohibit modification and deletion) }
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:test_msib1/auth/view/login.dart'; import 'package:test_msib1/core/dependency/dependency.dart'; import 'package:test_msib1/core/widget/custom-error-alert.dart'; import 'package:test_msib1/data/datasource/user-data.dart'; import 'package:test_msib1/data/model/user-model.dart'; import '../../core/theme/theme.dart'; class ProfileController extends GetxController { RxString tokens = ''.obs; Rx<UserModel> userData = UserModel().obs; Future saveToken({required String token}) async { SharedPreferences preferences = await SharedPreferences.getInstance(); preferences.setString('token', token); tokens(token); update(); } Future getUserData() async { final data = await UserDataSource(token: tokens.value).getUserData(); if (data != null) { Map<String, dynamic> user = data as Map<String, dynamic>; userData(UserModel.fromJson(user)); } else { getUserData(); } } void logout() async { Get.defaultDialog( title: 'KONFIRMASI', titleStyle: TextStyle(color: black, fontSize: 16, fontWeight: FontWeight.bold), content: Text( 'Apakah kamu yakin ingin logout?', textAlign: TextAlign.center, style: TextStyle(color: black, fontSize: 13), ), confirm: ElevatedButton( style: ElevatedButton.styleFrom(backgroundColor: blue), onPressed: () { Get.back(); Confirmlogout(); }, child: Text( 'Yakin', style: TextStyle( color: white, fontSize: 15, fontWeight: FontWeight.w500), )), cancel: ElevatedButton( style: ElevatedButton.styleFrom(backgroundColor: white), onPressed: () { Get.back(); }, child: Text( 'Batal', style: TextStyle( color: black, fontSize: 15, fontWeight: FontWeight.w500), ))); } Future Confirmlogout() async { SharedPreferences preferences = await SharedPreferences.getInstance(); final data = await UserDataSource(token: tokens.value).logout(); if (data != null) { home.jumlahBuku(0); preferences.remove('token'); Get.offAll(LoginView()); } else { snacbar( title: 'Kesalahan', messege: 'Ups sepertinya ada yang salah, coba kembali'); } } }
import { useDispatch } from 'react-redux'; import { RiDeleteBinLine, RiEdit2Line } from 'react-icons/ri'; import { addCurrentTodo, deleteTodo } from 'reduxTodo/todoSlice'; import { Text } from 'components'; import style from './Todo.module.css'; export const Todo = ({ id, counter, text }) => { const dispatch = useDispatch(); const handleDelete = () => { dispatch(deleteTodo(id)); }; return ( <div className={style.box}> <Text textAlign="center" marginBottom="20"> TODO #{counter} </Text> <Text>{text}</Text> <button className={style.deleteButton} type="button" onClick={handleDelete} > <RiDeleteBinLine size={24} /> </button> <button className={style.editButton} type="button" onClick={() => dispatch(addCurrentTodo({ id, text }))} > <RiEdit2Line size={24} /> </button> </div> ); };
import React from 'react' import "./ProjectContainer.css"; import { Element } from 'react-scroll'; import Project from '../Project/Project'; const ProjectContainer = () => { const projects=[ { img:"https://i.pinimg.com/originals/7f/b1/f1/7fb1f193435815a86c8484f82b9589e1.jpg", title:"Instagram", desc:"I Like Instagram", link:"www.google.com", }, { img:"https://i.pinimg.com/originals/7f/b1/f1/7fb1f193435815a86c8484f82b9589e1.jpg", title:"LinkedIn", desc:"I Like LinkedIn", link:"www.google.com", }, { img:"https://i.pinimg.com/originals/7f/b1/f1/7fb1f193435815a86c8484f82b9589e1.jpg", title:"Twitter", desc:"I Like Twitter", link:"www.google.com", }, { img:"https://i.pinimg.com/originals/7f/b1/f1/7fb1f193435815a86c8484f82b9589e1.jpg", title:"FaceBook", desc:"I Like FaceBook", link:"www.google.com", }, { img:"https://i.pinimg.com/originals/7f/b1/f1/7fb1f193435815a86c8484f82b9589e1.jpg", title:"Telegram", desc:"I Like Telegram", link:"www.google.com", }, { img:"https://i.pinimg.com/originals/7f/b1/f1/7fb1f193435815a86c8484f82b9589e1.jpg", title:"Gitgub", desc:"I Like Gitgub", link:"www.google.com", }, ]; return ( <Element className="projectcontainer" id="projects"> <h1>Projects</h1> <p> Here are some projects which I done for making lives of people easy. </p> <div className="projectcontainer__project"> { projects.map((project,index)=> { return( <Project key={index} img={project.img} title={project.title} desc={project.desc} link={project.link} /> ); }) } </div> </Element> ) }; export default ProjectContainer
package ru.eco.automan.dao import androidx.room.Dao import androidx.room.Query import ru.eco.automan.models.Brand import ru.eco.automan.models.Paragraph /** * Интерфейс, позволяющий получить доступ к пунктам правил ПДД, хранящихся в базе данных * @see Paragraph */ @Dao interface ParagraphDao { /** * Метод для получения списка всех пунктов Правил Дорожного Движения * @return Список всех пунктов */ @Query("SELECT * FROM paragraph") fun getAllParagraphs(): List<Paragraph> /** * Метод для получения пунктов ПДД по ID-номеру главы * @param chapterId ID-номер главы * @return Список пунктов входящих в эту главу */ @Query("SELECT * FROM paragraph WHERE chapter_id=:chapterId") fun getParagraphsByChapterId(chapterId: Int): List<Paragraph> }
package edument.perl6idea.annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import edument.perl6idea.psi.Perl6PackageDecl; import edument.perl6idea.psi.Perl6RoutineDecl; import org.jetbrains.annotations.NotNull; public class UselessMethodDeclarationAnnotator implements Annotator { @Override public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { if (element instanceof Perl6RoutineDecl routine) { // Check that we've got a method. String kind = routine.getRoutineKind(); if (!kind.equals("method") && !kind.equals("submethod")) return; // Check it is has-scoped (the default for methods) and has a name. if (!routine.getScope().equals("has")) return; PsiElement nameIdentifier = routine.getNameIdentifier(); if (nameIdentifier == null) return; // Potentially useless; see if it's in a package. Perl6PackageDecl packageDecl = PsiTreeUtil.getParentOfType(routine, Perl6PackageDecl.class); boolean canHaveMethods = false; if (packageDecl != null) { String packageKind = packageDecl.getPackageKind(); canHaveMethods = !(packageKind.equals("module") || packageKind.equals("package")); } if (!canHaveMethods) holder.newAnnotation(HighlightSeverity.WARNING, packageDecl == null ? "Useless declaration of a method outside of any package" : "Useless declaration of a method in a " + packageDecl.getPackageKind()) .range(nameIdentifier) .create(); } } }
import React, { Component } from 'react'; /* import MyList from "./MyList"; */ import Button from './Button'; import Alert from './Alert'; class App extends Component { constructor(props) { super(props) this.state = { showModal: false, isDisableButton: false, } } changeTitle = (value) => { this.setState({ title: value }) } changeShowComponent = () => { this.setState((state) => ( { showModal: !state.showModal, isDisableButton: !state.isDisableButton } )) } render() { return ( /* // comentado test my list <div className='main'> <MyList> <li>Supimpa</li> <li>De Mais</li> SUPIMPA 2.0 - Melhor palavra! <button type="button" onClick={() => alert('show')} >test</button> </MyList> </div> */ <div className='main'> <Button content="Clique aqui" isDisable={this.state.isDisableButton} showComponent={this.changeShowComponent} value='Título Show' /> {this.state.showModal && <Alert hideComponent={this.changeShowComponent} contentTitle="Modal" content="Coloque qualquer coisa aqui." />} </div> ) } } export default App;
/* * Copyright 2020 SIA Joom * * 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 com.joom.lightsaber.processor.analysis import com.joom.grip.Grip import com.joom.grip.mirrors.ClassMirror import com.joom.grip.mirrors.MethodMirror import com.joom.grip.mirrors.Type import com.joom.grip.mirrors.getObjectTypeByInternalName import com.joom.grip.mirrors.isInterface import com.joom.grip.mirrors.isStatic import com.joom.grip.mirrors.signature.GenericType import com.joom.lightsaber.processor.ErrorReporter import com.joom.lightsaber.processor.model.Contract import com.joom.lightsaber.processor.model.ContractProvisionPoint import com.joom.lightsaber.processor.model.Dependency interface ContractParser { fun parseContract(type: Type.Object): Contract } class ContractParserImpl( private val grip: Grip, private val analyzerHelper: AnalyzerHelper, private val errorReporter: ErrorReporter, private val projectName: String ) : ContractParser { private val contractsByTypes = HashMap<Type.Object, Contract>() override fun parseContract(type: Type.Object): Contract { return contractsByTypes.getOrPut(type) { val mirror = grip.classRegistry.getClassMirror(type) parseContract(mirror) } } private fun parseContract(mirror: ClassMirror): Contract { val implementationType = getObjectTypeByInternalName(mirror.type.internalName + "\$Lightsaber\$Contract\$$projectName") val qualifier = analyzerHelper.findQualifier(mirror) val dependency = Dependency(GenericType.Raw(mirror.type), qualifier) if (!isValidContract(mirror)) { return Contract(mirror.type, implementationType, dependency, emptyList()) } val childContracts = mirror.interfaces.map { parseContract(it) } val provisionPoints = mirror.methods.mapNotNullTo(ArrayList()) { tryParseContractProvisionPoint(mirror, it) } return Contract(mirror.type, implementationType, dependency, mergeContractProvisionPoints(mirror.type, provisionPoints, childContracts)) } private fun isValidContract(mirror: ClassMirror): Boolean { if (!mirror.isInterface) { errorReporter.reportError("Contract must be an interface: ${mirror.type.className}") return false } if (mirror.signature.typeVariables.isNotEmpty()) { errorReporter.reportError("Contract cannot have type parameters: ${mirror.type.className}") return false } return true } private fun tryParseContractProvisionPoint(mirror: ClassMirror, method: MethodMirror): ContractProvisionPoint? { if (method.isStatic) { return null } if (method.signature.typeVariables.isNotEmpty()) { errorReporter.reportError("Contract's method cannot have type parameters: ${mirror.type.className}.${method.name}") return null } if (method.parameters.isNotEmpty()) { errorReporter.reportError("Contract's method cannot have parameters: ${mirror.type.className}.${method.name}") return null } val injectee = analyzerHelper.convertMethodResultToInjectee(method) return ContractProvisionPoint(mirror.type, method, injectee) } private fun mergeContractProvisionPoints( type: Type.Object, provisionPoints: Collection<ContractProvisionPoint>, childContracts: Collection<Contract> ): Collection<ContractProvisionPoint> { val provisionPointsByName = createProvisionPointMap(type, provisionPoints) val provisionPointMapForChildContracts = createProvisionPointMapForChildContracts(type, provisionPointsByName.keys, childContracts) val allProvisionPointsByName = provisionPointMapForChildContracts + provisionPointsByName return allProvisionPointsByName.values } private fun createProvisionPointMap(type: Type.Object, provisionPoints: Collection<ContractProvisionPoint>): Map<String, ContractProvisionPoint> { val provisionPointGroupsByName = provisionPoints.groupBy { it.method.name } val provisionPointsByName = linkedMapOf<String, ContractProvisionPoint>() provisionPointGroupsByName.forEach { (name, provisionPoints) -> if (provisionPoints.size > 1) { val provisionPointsString = provisionPoints.joinToString(separator = "\n") { provisionPoint -> " ${provisionPoint.method.signature.returnType} $name()" } errorReporter.reportError("Interface ${type.className} contains conflicting methods:\n$provisionPointsString") } provisionPointsByName[name] = provisionPoints.first() } return provisionPointsByName } private fun createProvisionPointMapForChildContracts( type: Type.Object, parentProvisionPointNames: Set<String>, childContracts: Collection<Contract> ): Map<String, ContractProvisionPoint> { val provisionPointGroupsByName = childContracts .asSequence() .flatMap { contract -> contract.provisionPoints.asSequence() } .filter { it.method.name !in parentProvisionPointNames } .groupBy { it.method.name } val provisionPointsByName = linkedMapOf<String, ContractProvisionPoint>() provisionPointGroupsByName.forEach { (name, provisionPoints) -> if (provisionPoints.size > 1 && !provisionPoints.allEqualBy { it.injectee }) { val provisionPointsString = provisionPoints.joinToString(separator = "\n") { provisionPoint -> val qualifier = provisionPoint.injectee.dependency.qualifier?.type?.className?.let { "@$it " } " $qualifier${provisionPoint.method.signature.returnType} $name() from ${provisionPoint.container.className}" } errorReporter.reportError("Interface ${type.className} inherits conflicting methods:\n$provisionPointsString") } provisionPointsByName[name] = provisionPoints.first() } return provisionPointsByName } private inline fun <T, K> Iterable<T>.allEqualBy(selector: (T) -> K): Boolean { if (this is Collection && size < 1) { return true } val iterator = iterator() if (!iterator.hasNext()) { return true } val element = selector(iterator.next()) while (iterator.hasNext()) { if (element != selector(iterator.next())) { return false } } return true } }
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router" import NProgress from 'nprogress' // Layouts import Default from '../layouts/Default.vue' import Error from '../layouts/Error.vue' // Pages import Home from '../page/Home.vue' // routes import accountRoute from "./account" import applicationRoute from "./application" const routes: RouteRecordRaw[] = [ { path: '/', component: Default, children: [{ path: '', component: Home }] }, { ...applicationRoute }, { ...accountRoute }, { path: '/:pathMatch(.*)*', component: Error } ] const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), linkActiveClass: 'active', linkExactActiveClass: 'active--exact', routes, }); router.beforeEach((to, from, next) => { let authRequired = to.meta.authRequired; let token = localStorage.token; if (authRequired && !token) { next({ path: '/account/login' }); } else { next(); } next() if (!NProgress.isStarted()) { NProgress.start(); } }); router.afterEach((to, from) => { NProgress.done(); }); export default router
public class ThisDetail { public static void main(String[] args) { T t1 = new T(); } } //1、this关键字可以用来访问本类的属性、方法、构造器 //2、this用于区分当前类的属性和局部变量 //3、访问成员方法的语法:this.方法名(参数列表) //4、访问构造器语法:this(参数列表);注意只能在构造器中使用(即只能在构造器中调用访问另外一个构造器) //5、this不能在类定义的外部使用,只能在类定义的方法中使用。 class T{ public T(){ //注意:如果有访问构造器语法:this(参数列表);必须放置在第一条语句 //这里访问T(String name),并且语句必须放在第一条语句 this("jake"); System.out.println("T() 构造器"); } public T(String name){ System.out.println("T(String name) 构造器"); } public void f1(){ System.out.println("f1()方法"); } public void f2(){ System.out.println("f2()方法"); f1(); this.f1(); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Runtime.InteropServices.JavaScript.JSType; namespace _03_OOP2_cv_060_Utvary { //Vytvořte třídu PlechovkaBarvy //bude v konstruktoru dostávat desetinná čísla objem a vydatnost, která si uloží.Čísla znamenají, kolik mililitrů v "pixle" je a kolik je třeba mililitrů na cm². //bude mít veřejnou metodu ToString(), která bude vracet něco jako "Plechovka barvy, zbývá jí ještě na 60 cm²". //bude mít veřejnou metodu Obarvi(), která obrdží IUtvar a pokud je v plechovce dost barvy na jeho obarvení, sníží svůj objem a vrátí true (úspěch), jinak si ponechá původní objem a vrátí false (neúspěch) //Vytvořte instanci plechovky a vyzkoušejte obarvit všechny útvary z pole.Udělejte si pole větší, abyste vyzkoušeli i to, že plechovka dojde. internal class PlechovkaBarvy { private double _objem; private double _vydatnost; public PlechovkaBarvy(double objem, double vydatnost) { _objem = objem; _vydatnost = vydatnost; } public override string ToString() { return $"Plechovka barvy, zbývá jí ještě na {_objem * _vydatnost} cm2"; } public bool Obarvi(IUtvar utvar) { double spotreba = utvar.GetObsah() / _vydatnost; //v mililitrech if (spotreba > _objem) return false; _objem -= spotreba; return true; } } }
'use client'; import React, { useState } from 'react'; import { useRouter } from 'next/navigation'; import { DataTable } from '@/components/ui/data-table'; import { Button } from '@/components/ui/button'; import { Separator } from '@/components/ui/separator'; import SectionHeading from '@/components/sectionHeading'; import { suppliers, SuppliersColumns } from './columns'; import { PiPenBold, PiPlusCircleBold } from 'react-icons/pi'; interface Suppliers { data: SuppliersColumns[]; } const SuppliersList: React.FC<Suppliers> = ({ data }) => { const router = useRouter(); const [selectedSupplier, setSelectedSupplier] = useState<SuppliersColumns | null>(null); const handleRowClick = (supplier: SuppliersColumns) => { setSelectedSupplier(supplier); }; const buttonText = selectedSupplier ? 'Edit supplier' : 'Add supplier'; const route = selectedSupplier ? `suppliers/${selectedSupplier.id}` : 'suppliers/new'; return ( <div> <div className="mx-4 my-1 flex justify-between items-center"> <div> <SectionHeading title="Suppliers" description="Manage your suppliers" /> </div> <Button onClick={() => router.push(route)}> <span className="me-1"> {selectedSupplier ? ( <PiPenBold /> ) : ( <PiPlusCircleBold /> )} </span> {buttonText} </Button> </div> <Separator /> <div className="m-2 border-2 min-h-full rounded-lg p-2 border-gray-200 bg-slate-100 "> <DataTable data={data} columns={suppliers} onRowClick={handleRowClick} selectedProduct={selectedSupplier} ></DataTable> </div> </div> ); }; export default SuppliersList;
<manpage uramdb(5) "URAM Database File Format"> <section SYNOPSIS> <itemlist> <toproject {package require simlib [version]}> <section DESCRIPTION> uramdb(5) defines a database format used for initializing instances of <xref uram(n)>. Note that <xref uram(n)> does not require that uramdb(5) be used; it is a convenience for testing and development. <xref uramdb(n)> parses uramdb(5) files into SQL tables in an <xref sqldocument(n)> database. run-time database. The syntax of the file mirrors the SQL <xref "DATABASE SCHEMA">. <section "BASIC SYNTAX"> A uramdb(5) file is a text file which defines the contents of a number of SQL tables. This section describes the file's syntax; see <xref TABLES> for an example of each uramdb(5) table. The uramdb(5) file may contain comments and <b>table</b> statements. A comment is a line of text beginning with the "#" character: <pre> # This is a comment. </pre> <subsection "Table Syntax"> A <b>table</b> statement defines the content of a single database table; each table consists of zero or more records. The <b>table</b> statement has this syntax: <pre> <b>table</b> <i>tableName</i> { <i>record</i> <i>record</i> . . . } </pre> <subsection "Records and Keys"> The records of each table are identified by the table's key fields. Each record in the <b>uramdb_civ_g</b> table, for example, defines a single civilian group; the key field, <b>g</b>, is the name of the group. This name must be unique for each record in the table. Some tables have two or even three key fields. The <b>uramdb_hrel</b> table, for example, contains the horizontal relationship values; it has two keys, <b>f</b> and <b>g</b>, each of which is the name of a group. Each record is defined by a <b>record</b> statement, which has this syntax: <pre> <b>table</b> <i>tableName</i> { <b>record</b> <i>keyName</i> <i>keyValue</i> ... { <i>field</i> <i>field</i> . . . } . . . } </pre> <subsection Fields> In addition to its key field or fields, most tables also have one or more data fields. Field values are defined using the <b>field</b> statement, which has this syntax: <pre> <b>table</b> <i>tableName</i> { <b>record</b> <i>keyName</i> <i>keyValue</i> ... { <b>field</b> <i>fieldName</i> <i>fieldValue</i> <b>field</b> <i>fieldName</i> <i>fieldValue</i> . . . } . . . } </pre> Field values containing whitespace must be quoted with double quotes or curly brackets. By convention, double quotes are used for short strings and curly brackets for structured values (e.g., lists) and for text which spills onto more than one line. See the example for each of the uramdb(5) <xref TABLES> to see what each form looks like in practice. <section CONCERNS> One of the tables (<b>uramdb_sat</b>) depend on the following sets of concerns; the symbolic name of each concern is shown in parentheses. <deflist> <def "Autonomy (AUT)"> Does the group feel it can maintain order and govern itself with a stable government and a viable economy? <def "Quality of Life (QOL)"> QOL includes the physical plants that provide services, including water, power, public transportation, commercial markets, hospitals, etc. and those things associated with these services such as sanitation, health, education, employment, food, clothing, and shelter. <def "Culture (CUL)"> Does the group feel that its culture and religion, including cultural and religious sites and artifacts, are respected or denigrated? <def "Physical Safety (SFT)"> Do members of the group fear for their lives, both from hostile attack and from collateral damage from CF activities? This fear includes environmental concerns such as life threatening disease, starvation, and dying of thirst. </deflist> <section TABLES> <subsection uramdb_a> This table defines actors within the playbox. URAM tracks vertical relationships of groups with actors. <b>Constraints:</b> <ul> <li> The table must define at least one actor. </ul> <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>a</td> <td>n/a</td> <td> <b>Key Field.</b> A symbolic name for the actor. The name may consist of uppercase letters, digits, and underscores only--no white space or other punctuation. </td> </tr> </table> For example, <pre> table uramdb_a { record a JOE {} record a BOB {} } </pre> <subsection uramdb_n> This table defines neighborhoods within the playbox. URAM tracks civilian satisfaction within each neighborhood for the groups who live there. Table <b>uramdb_mn</b> describes the relationships between the different neighborhoods. <b>Constraints:</b> <ul> <li> The table must define at least one neighborhood. </ul> <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>n</td> <td>n/a</td> <td> <b>Key Field.</b> A symbolic name for the neighborhood. The name may consist of uppercase letters, digits, and underscores only--no white space or other punctuation. </td> </tr> </table> For example, <pre> table uramdb_n { record n N1 {} record n N2 {} } </pre> <subsection uramdb_mn> This table contains neighborhood proximities. This table has two keys, <b>m</b> (the name of the first neighborhood) and <b>n</b> (the name of the second neighborhood). If the table is omitted from the uramdb(5) input, the <xref sqldocument(n)> table will be populated with default values for all pairs of neighborhoods. <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>m</td> <td>n/a</td> <td> <b>Key Field.</b> The first neighborhood name, as defined in the <b>uramdb_n</b> table. </td> </tr> <tr> <td>n</td> <td>n/a</td> <td> <b>Key Field.</b> The second neighborhood name, as defined in the <b>uramdb_n</b> table. </td> </tr> <tr> <td>proximity</td> <td> HERE if <b>m</b> == <b>n</b>, REMOTE otherwise</td> <td> The value is the proximity of neighborhood <b>n</b> to neighborhood <b>m</b> from the point of view of residents of <b>m</b>. The <b>proximity</b> measures the psychological distance between the neighborhoods, as perceived by the residents. Proximity can have any of the following <xref simtypes(n) eproximity> values: <fromproject {::simlib::eproximity html}> Note that proximity need not be symmetric. </td> </tr> </table> The following example states that all neighborhoods are <b>REMOTE</b> from each other, except for those explicitly mentioned as being <b>NEAR</b>. <pre> table uramdb_mn { record m N1 n N2 { field proximity NEAR } record m N2 n N1 { field proximity NEAR } } </pre> <subsection uramdb_civ_g> The <b>uramdb_civ_g</b> table defines the complete set of civilian groups. The table has a single key field, the group name, <b>g</b>. <b>Constraints:</b> <ul> <li> The table must contain at least one group. <li> Group names must be unique across all group types. </ul> <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>g</td> <td>n/a</td> <td> <b>Key Field.</b> A symbolic name for the group. The name may consist of uppercase letters, digits, and underscores only--no white space or other punctuation. </td> </tr> <tr> <td>n</td> <td>n/a</td> <td> The neighborhood in which the group resides, as defined in the <b>uramdb_n</b> table. </td> </tr> <tr> <td>pop</td> <td>n/a</td> <td> The population of the group. </td> </tr> </table> The following example defines a CIV group. <pre> table uramdb_civ_g { record g SUNB { field n N1 field pop 10000 } . . . } </pre> <subsection uramdb_frc_g> The <b>uramdb_frc_g</b> table defines the complete set of force groups. The table has a single key field, the group name, <b>g</b>. <b>Constraints:</b> <ul> <li> The table must contain at least one group. <li> Group names must be unique across all group types. </ul> <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>g</td> <td>n/a</td> <td> <b>Key Field.</b> A symbolic name for the group. The name may consist of uppercase letters, digits, and underscores only--no white space or other punctuation. </td> </tr> </table> The following example defines a FRC group. <pre> table uramdb_frc_g { record g BLUE { } . . . } </pre> <subsection uramdb_org_g> The <b>uramdb_org_g</b> table defines the complete set of force groups. The table has a single key field, the group name, <b>g</b>. <b>Constraints:</b> <ul> <li> Group names must be unique across all group types. </ul> <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>g</td> <td>n/a</td> <td> <b>Key Field.</b> A symbolic name for the group. The name may consist of uppercase letters, digits, and underscores only--no white space or other punctuation. </td> </tr> </table> The following example defines an ORG group. <pre> table uramdb_org_g { record g USAID { } . . . } </pre> <subsection uramdb_hrel> This table contains the horizontal relationship data for all pairs of groups. This table has two keys, <b>f</b> (the name of the first group) and <b>g</b> (the name of the second group). If the table is omitted from the uramdb(5) input, the <xref sqldocument(n)> table will be populated with default values for all pairs of groups. <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>f</td> <td>n/a</td> <td> <b>Key Field.</b> The first group name, as defined in any of the group tables. </td> </tr> <tr> <td>g</td> <td>n/a</td> <td> <b>Key Field.</b> The second group name, as defined in any of the group tables. </td> </tr> <tr> <td>hrel</td> <td> 1.0 if <b>f</b> == <b>g</b>, and 0.0 otherwise.</td> <td> The relationship between the two groups from group <b>f</b>'s point of view (the relationship need not be symmetric). The value is a <xref simtypes(n) qaffinity> value and may range from -1.0 to +1.0. The following symbolic constants may be used during data entry: <fromproject {::simlib::qaffinity html}> </td> </tr> </table> For example, <pre> table uramdb_hrel { record f SUNB g SHIA { field hrel -0.3 } . . . } </pre> <subsection uramdb_vrel> This table contains the vertical relationship data for all groups with all actors. This table has two keys, <b>g</b> (the name of the group) and <b>a</b> (the name of the actor). If the table is omitted from the uramdb(5) input, the <xref sqldocument(n)> table will be populated with default values for all pairs of groups. <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>f</td> <td>n/a</td> <td> <b>Key Field.</b> The first group name, as defined in any of the group tables. </td> </tr> <tr> <td>g</td> <td>n/a</td> <td> <b>Key Field.</b> The second group name, as defined in any of the group tables. </td> </tr> <tr> <td>vrel</td> <td>0.0</td> <td> The relationship between the group and actor from the group's point of view. The value is a <xref simtypes(n) qaffinity> value and may range from -1.0 to +1.0. The following symbolic constants may be used during data entry: <fromproject {::simlib::qaffinity html}> </td> </tr> </table> For example, <pre> table uramdb_vrel { record g SUNB a JOE { field vrel -0.3 } . . . } </pre> <subsection uramdb_sat> This table contains the initial satisfaction data for all civilian groups and all concerns. This table has two keys, <b>g</b> (the group name) and <b>c</b> (the concern name, see <xref CONCERNS>). If the table is omitted from the uramdb(5) input, the <xref sqldocument(n)> table will be populated with default values for all valid combinations of group and concern. <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>g</td> <td>n/a</td> <td> <b>Key Field.</b> A civilian group name, as defined in the <b>uramdb_civ_g</b> table. </td> </tr> <tr> <td>c</td> <td>n/a</td> <td> <b>Key Field.</b> A concern name, as defined in <xref CONCERNS>. </td> </tr> <tr> <td>sat</td> <td>0.0</td> <td> The initial satisfaction at time 0.0, a numeric or symbolic <xref simtypes(n) qsat> value: <fromproject {::simlib::qsat html}> </td> </tr> <tr> <td>saliency</td> <td>1.0</td> <td> The saliency (importance) of this concern to this group, a numeric or symbolic <xref simtypes(n) qsaliency> value: <fromproject {::simlib::qsaliency html}> </td> </tr> </table> For example, <pre> table uramdb_sat { record g SUNB c AUT { field sat -61 field saliency 1 } record g SUNB c CUL { field sat -30 field saliency 1 } . . . } </pre> <subsection uramdb_coop> This table contains the initial cooperation data for each CIV group/FRC group pair. This table has two keys, <b>f</b> (the name of the civilian group) and <b>g</b> (the name of the force group). If the table is omitted from the uramdb(5) input, the <xref sqldocument(n)> table will be populated with default values for all pairs of groups. <table> <tr> <th>Field</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>f</td> <td>n/a</td> <td> <b>Key Field.</b> The civilian group name, as defined in the <b>uramdb_civ_g</b> table. </td> </tr> <tr> <td>g</td> <td>n/a</td> <td> <b>Key Field.</b> The force group name, as defined in the <b>uramdb_frc_g</b> table. </td> </tr> <tr> <td>coop</td> <td> 50.0</td> <td> The probability that group <b>f</b> will cooperate with (provide information to) group <b>g</b>. The value is a <xref simtypes(n) qcooperation> value and may range from -100.0 to +100.0. The following symbolic constants may be used during data entry: <fromproject {::simlib::qcooperation html}> </td> </tr> </table> For example, <pre> table uramdb_coop { record f SUNB g BLUE { field coop 25.0 } record f SUNB g OPFOR { field coop 75.0 } . . . } </pre> <section "DATABASE SCHEMA"> The <xref uramdb(n)> parser defines the following SQL schema which will receive the <xref uramdb(5)> data: <listing> <fromproject {::simlib::uramdb sqlsection schema}> </listing> <section AUTHOR> Will Duquette <section HISTORY> uramdb(5) is a descendent of a number of database formats for <xref uram(n)> and its ancestors. </manpage>
import React, { useState, useEffect, useContext } from 'react'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; import { useData } from '../UserContext'; // import { UserContext } from '../UserContext'; function Quiz() { // app state const { data, updateData } = useData(); const [activeQuestion, setActiveQuestion] = useState(0); const [timer, setTimer] = useState(60); const [result, setResult] = useState(false) const [ans, setAns] = useState([]) const [userData, setUserdata] = useState([]); const [questions, setQuestions] = useState([]); const navigate = useNavigate() //UseEffect Hook for Api call and data useEffect(() => { axios.get("https://opentdb.com/api.php?amount=15").then((res) => { const { data } = res; if (data.results) { const Result = data.results.map((question) => ({ question: question.question, answers: [...question.incorrect_answers, question.correct_answer], })); console.log("Result", Result) setQuestions(Result); } setUserdata(res?.data?.results); }); }, []); console.log("questions", userData) console.log("Ans", ans) //onclick Handlers const handleAnswerClick = (selectedOption) => { const questionData = userData[activeQuestion]; console.log("ActiveQuestion", questionData); console.log("selectedOption", questionData?.question + selectedOption); const updatedAns = [...ans, { Answer: selectedOption, Question: questionData?.question }]; setAns(updatedAns); if (activeQuestion < userData.length - 1) { setActiveQuestion(activeQuestion + 1); } else if (activeQuestion === userData.length - 1) { const updatedData = { userSelected: updatedAns, userData: userData, }; updateData(updatedData); navigate("/report"); } }; console.log(result) return ( <> <div className='text-[60px] font-bold pl-[10px] bg-[#1414143d] '>Quizzly</div> <hr className='mt-[1px] bg-[black] h-[3px]' /> <div className='flex items-center justify-evenly pt-[100px]'> <div className='bg-[#1414143d] w-[60%] pl-[10px] rounded-lg '> <div className='text-[30px] font-bold text-zinc-800'>Question {activeQuestion + 1}</div> <div className='font-sans text-[32px]'>{userData[activeQuestion]?.question}</div> <ul className='flex w-[80%] justify-evenly'> {questions[activeQuestion]?.answers?.map((option, index) => ( <li className='flex' key={index} onClick={() => handleAnswerClick(option)}> <button className='rounded-md bg-[#6dd4fdf2] border-[1px] tracking-wider text-[15px] border-zinc-600 mr-[15px] w-[150px] cursor-pointer active:bg-[#c4bbf0] border-0 py-[15px] px-8'>{option}</button> </li> ))} </ul> </div> <div className="mark-box w-[30%] bg-[#32327b3d] rounded-md"> <div className="card mb-3"> <div className="card-body" style={{ display: "flex", padding: 10, flexWrap: "wrap" }} > {userData.map((item, index) => ( <div key={index} className="question-no" style={{ display: "flex", justifyContent: "center", alignItems: "center", height: 40, width: 50, marginTop: "20px", marginLeft: "20px", marginBottom: "5px", border: "1px solid black", borderRadius: "5px", cursor: "pointer", backgroundColor: index === activeQuestion ? "#94cfe7" : item?.selected ? "grey" : "#EAEAEA" }} onClick={() => setActiveQuestion(index)} > {index + 1} </div> ))} </div> </div> </div> </div> <div className='flex pl-[46px] pt-[20px]'> <button onClick={handleAnswerClick} className='rounded-sm font-bold bg-[#0179a9] cursor-pointer active:bg-[#c4bbf0] text-[white] border-0 py-[15px] px-8'> NEXT </button> </div> </> ); } export default Quiz;
package com.devsuperior.assistencia.recources; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.devsuperior.assistencia.dto.ServicoDTO; import com.devsuperior.assistencia.services.ServicoService; @RestController @RequestMapping(value="/servicos") public class ServicoResource { @Autowired private ServicoService service; @GetMapping(value="/{id}") public ResponseEntity<ServicoDTO> findById(@PathVariable Long id){ ServicoDTO dto = service.findById(id); return ResponseEntity.ok(dto); } @GetMapping public ResponseEntity <List<ServicoDTO>> findAll(){ List <ServicoDTO> lista = service.findAll(); return ResponseEntity.ok(lista); } }
import '../styles/styles.css' import { useMap } from '@vis.gl/react-google-maps'; // Function to get the price sign based on the locale function getLocalePriceSign() { switch(navigator.language) { case "en-GB": return "£"; case "en-US": return "$"; case "de-DE": case "fr-FR": case "it-IT": case "es-ES": return "€"; default: return "£"; } } // Function to get the measurement unit based on the locale function getLocaleDistanceMeasurement() { switch(navigator.language) { case "en-GB": case "de-DE": case "fr-FR": case "it-IT": case "es-ES": return "km"; case "en-US": default: return "mi"; } } // Function to transform Googles price level enum to a price indicator, based on users locale function googlePriceLevelToSymbol(priceLevel) { let priceSign = getLocalePriceSign(); switch(priceLevel) { case "PRICE_LEVEL_INEXPENSIVE": return priceSign; case "PRICE_LEVEL_MODERATE": return priceSign.repeat(2); case "PRICE_LEVEL_EXPENSIVE": return priceSign.repeat(3); case "PRICE_LEVEL_VERY_EXPENSIVE": return priceSign.repeat(4); default: return priceLevel; } } function ResultWidget({pubObject, setSelectedPub}) { let distance = (pubObject.distance / 1000).toFixed(2); let price = googlePriceLevelToSymbol(pubObject.price); return ( <button className="resultWrapper" onClick={() => setSelectedPub(pubObject)}> <h1 className='resultTitle' style={{fontSize: "larger"}}>{pubObject.name}</h1> <div className='partition'> <svg viewBox="0 0 415 36" fill="none" xmlns="http://www.w3.org/2000/svg"> <line y1="0.5" x2="415" y2="0.5" stroke="white"/> <line x1="270.5" y1="10" x2="270.5" y2="36" stroke="white"/></svg> </div> <div className='HCDWrapper'> {/* Hours, Cost, Distance*/ } <table> <tbody> <tr> <th scope='col'>Hours</th> <th scope='col'>Cost</th> <th scope='col'>Distance</th> </tr> <tr> <td>{pubObject.hours}</td> <td>{price}</td> <td className="bold">{distance}{getLocaleDistanceMeasurement()}</td> </tr> </tbody> </table> {/* <table> <tr> <th scope='col'></th> <th scope='col'></th> <th scope='col'></th> </tr> </table> */} </div> <h1 className="resultRating">{pubObject.rating}&#9733;</h1> </button> ); }; export default ResultWidget;
use object::player; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; mod view; use view::board_view; mod object; use object::rays; mod settings; use settings::*; // importing all constants fn main() -> Result<(), String> { let sdl_context: sdl2::Sdl = sdl2::init()?; let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem .window("RAYCASTER", SCREEN_WIDTH * 2, SCREEN_HEIGHT) .build() .unwrap(); let mut canvas = window.into_canvas().build().unwrap(); let screen_area = Rect::new(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); let board_view: board_view::Renderer = board_view::Renderer { screen_area, // shorthand intialization }; // Creating a player's instance let mut player: player::Player = player::Player { x: 300.0, y: 300.0, a: 0.0, // at angle 0, it faces exactly right dx: 5.0, dy: 0.0, }; // The game loop let mut running = true; let mut event_queue = sdl_context.event_pump().unwrap(); let mut rays: Vec<rays::Ray> = Vec::new(); let mut player_moved = true; let mut keys: [u32; 4] = [0, 0, 0, 0]; while running { for event in event_queue.poll_iter() { match event { Event::Quit { .. } => { running = false; } Event::KeyDown { keycode: Some(key), .. } => match key { Keycode::Left => { keys[0] = 1; } Keycode::Right => { keys[1] = 1; } Keycode::Up => { keys[2] = 1; } Keycode::Down => { keys[3] = 1; } _ => {} }, Event::KeyUp { keycode: Some(key), .. } => match key { Keycode::Left => { keys[0] = 0; } Keycode::Right => { keys[1] = 0; } Keycode::Up => { keys[2] = 0; } Keycode::Down => { keys[3] = 0; } _ => {} }, _ => {} } let sum_arr: u32 = keys.iter().sum(); if sum_arr != 0 { player_moved = true; if keys[0] == 1 { player.a -= 0.2; player.dx = player.a.cos() * 10.0; player.dy = player.a.sin() * 10.0; } if keys[1] == 1 { player.a += 0.2; player.dx = player.a.cos() * 10.0; player.dy = player.a.sin() * 10.0; } if keys[2] == 1 { // collision detection let y1 = ((player.y + player.dy) / CELL_SIZE).floor() as usize; let x1 = ((player.x + player.dx) / CELL_SIZE).floor() as usize; if MAP[y1][x1] != 1 { player.y += player.dy; player.x += player.dx; player_moved = true; } if keys[3] == 1 { // collision detection let y1 = ((player.y - player.dy) / CELL_SIZE).floor() as usize; let x1 = ((player.x - player.dx) / CELL_SIZE).floor() as usize; if MAP[y1][x1] != 1 { player.y -= player.dy; player.x -= player.dx; player_moved = true; } } } } } player.check_angle(); // keeps angle btw 0 and 2PI if player_moved { rays.clear(); // for multiple rays for i in 0..NUM_RAYS { let mut ray: rays::Ray = rays::Ray { sx: player.x, sy: player.y, // Initial values of these don't matter ra: 0.0, rx: 0.0, ry: 0.0, ri: i, proj_height: 0.0, depth: 0.0, }; rays::Ray::handle_events(&mut ray, &mut player, &mut rays, i); } player_moved = false; } // the thing wrong here is that if i don't clear the screen with the background color, some pretty nasty stuff happens, // for which I have absolutely no idea why it happens // Render Stuff canvas.set_draw_color(Color::RGB(30, 30, 30)); // background color canvas .fill_rect(Rect::new(0, 0, SCREEN_WIDTH * 2, SCREEN_HEIGHT)) .ok() .unwrap(); board_view.render(&mut canvas); for ray in &mut rays { ray.draw_3D(&mut canvas); ray.draw_2D(&mut canvas); } player.draw(&mut canvas); canvas.present(); } Ok(()) // successful execution, doesn't need to return anything, so its empty }
import glob import os import platform import time import librosa import numpy as np import pandas as pd from pydub import AudioSegment from tqdm import tqdm def get_emotions_dictionary(): return { '01': 'neutral', '02': 'calm', '03': 'happy', '04': 'sad', '05': 'angry', '06': 'fear', '07': 'disgust', '08': 'surprised' } def get_actors(): actors = { '01': '1', '02': '2', '03': '3', '04': '4', '05': '5', '06': '6', '07': '7', '08': '8', '09': '9', '10': '10', '11': '11', '12': '12', '13': '13', '14': '14', '15': '15', '16': '16', '17': '17', '18': '18', '19': '19', '20': '20', '21': '21', '22': '22', '23': '23', '24': '24' } return actors def get_tess_emotions(): # defined tess emotions to test on TESS dataset only return ['angry', 'disgust', 'fear', 'ps', 'happy', 'sad'] def get_ravdess_emotions(): # defined RAVDESS emotions to test on RAVDESS dataset only return ['neutral', 'calm', 'angry', 'happy', 'disgust', 'sad', 'fear', 'surprised'] def get_observed_emotions(): return ['sad', 'angry', 'happy', 'disgust', 'surprised', 'neutral', 'calm', 'fear'] # Function to perform voice activity detection def detect_voice_activity(audio_file_path, silence_threshold=40): audio = AudioSegment.from_wav(audio_file_path) voice_segments = [] current_segment = [] for sample in audio: if abs(sample.dBFS) > silence_threshold: current_segment.append(sample) elif len(current_segment) > 0: voice_segments.append(AudioSegment(current_segment)) current_segment = [] return voice_segments def extract_mffcs_with_vad(file_name, n_fft=8192): """ Performs voice activity detection on a given sample. After that performs the calculation of supra-segment features based on MFCC to obtain a characteristic vector. Output: The resulting mean MFCC and standard deviation of MFCC provides a measure of the average squared deviation of each MFCC feature across timeline. """ # Process voice segments and extract MFCCs X, sample_rate = librosa.load(file_name) mfccs = librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40, n_fft=n_fft).T # VAD mfccs = mfccs[:,1:] # exclude coeff 0 mel_frame_power = np.sum(mfccs**2,axis=1)/mfccs.shape[1] mel_uttr_power = np.sum(mel_frame_power)/mfccs.shape[0] r1,r2 = 5, 0.5 vad_threshold = r1 + r2*np.log10(mel_uttr_power) vad_out = mel_frame_power>vad_threshold #voice_segments = detect_voice_activity(file_name) mfcc_features = mfccs[vad_out,:] # for ind in range(vad_out): # if vad_out: # mfcc_features.append(mfccs[ind,:]) mean_mfcc = np.mean(mfcc_features, axis=0) sd_mfcc = np.std(mfcc_features, axis=0) if np.sum(np.isnan(sd_mfcc))>0: print('NaN!') return mean_mfcc, sd_mfcc def extract_feature(file_name, mfcc_flag, n_fft=8192): """ Performing the calculation of supra-segment features based on MFCC to obtain a characteristic vector. Output: The resulting mean MFCC and standard deviation of MFCC provides a measure of the average squared deviation of each MFCC feature across timeline. """ X, sample_rate = librosa.load(file_name) if mfcc_flag: mfccs = librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40, n_fft=n_fft).T # default n_fft = 2048 (window size) mean_mfcc = np.mean(mfccs, axis=0) sd_mfcc = np.std(mfccs, axis=0) return mean_mfcc, sd_mfcc else: return None def dataset_options(): # choose datasets ravdess = True tess = False ravdess_speech = False ravdess_song = False n_fft = 2048 # 2048 -- default (others: 32768 / 8192 / 4096) data = {'ravdess': ravdess, 'ravdess_speech': ravdess_speech, 'ravdess_song': ravdess_song, 'tess': tess} print(data) return data, n_fft def build_dataset(use_vad=False): X, y, ID = [], [], [] # feature to extract mfcc = True data, n_fft = dataset_options() paths = [] if data['ravdess']: if platform.system() == "Windows": paths.append("data/ravdess-emotional-speech-audio/audio_speech_actors_01-24/**/*.wav") else: paths.append("data/ravdess-emotional-speech-audio/audio_speech_actors_01-24/**/*.wav") elif data['ravdess_speech']: paths.append("./data/ravdess-emotional-speech-audio/audio_speech_actors_01-24/Actor_*/*.wav") elif data['ravdess_song']: paths.append("./data/ravdess-emotional-song-audio/audio_song_actors_01-24/Actor_*/*.wav") for path in paths: for file in tqdm(glob.glob(path)): file_name = os.path.basename(file) splited_file_name = file_name.split("-") emotion = get_emotions_dictionary()[ splited_file_name[2]] # to get emotion according to filename. dictionary emotions is defined above. if emotion not in get_observed_emotions(): # options observed_emotions - RAVDESS and TESS, ravdess_emotions for RAVDESS only continue actor = np.array(get_actors()[splited_file_name[6].split(".")[0]]) if use_vad: mean_mfcc, sd_mfcc = extract_mffcs_with_vad(file, n_fft=n_fft) else: mean_mfcc, sd_mfcc = extract_feature(file, mfcc, n_fft=n_fft) feature = np.hstack((mean_mfcc, sd_mfcc)) X.append(feature) y.append(emotion) ID.append(actor) if data['tess']: for file in glob.glob( "./data/toronto-emotional-speech-set-tess/tess toronto emotional speech set data/TESS Toronto emotional speech set data/*AF_*/*.wav"): file_name = os.path.basename(file) emotion = file_name.split("_")[2][:-4] # split and remove .wav if emotion == 'ps': emotion = 'surprised' if emotion not in get_observed_emotions(): # options observed_emotions - RAVDESS and TESS, ravdess_emotions for RAVDESS only continue feature = extract_feature(file, mfcc) X.append(feature) y.append(emotion) return {"X": X, "y": y, "ID": ID} def generate_csv_dataset(use_vad=False): """ Generates a data set containing combined features matrix (MFCCs and standard deviation of MFCC), class labels and actor IDs :return: X - features, y = class_labels, IDs = actor id """ start_time = time.time() _, n_fft = dataset_options() print(f'INFO: n_fft={n_fft}') dataset = build_dataset(use_vad) print("--- Data loaded. Loading time: %s seconds ---" % (time.time() - start_time)) X = pd.DataFrame(dataset["X"]) y = pd.DataFrame(dataset["y"]) ID = pd.DataFrame(dataset["ID"]) # Standardize data X = (X - X.mean()) / X.std() print("X.shape = ", X.shape) print("y.shape = ", y.shape) print("ID.shape = ", ID.shape) if use_vad: X_path = f'data/feature_vector_based_mean_mfcc_and_std_mfcc_nfft_{n_fft}_vad.csv' else: X_path = f'data/feature_vector_based_mean_mfcc_and_std_mfcc_nfft_{n_fft}.csv' y_path = f'data/y_labels_{n_fft}.csv' ID_path = f'data/IDs_{n_fft}.csv' X.to_csv(X_path) y.to_csv(y_path) ID.to_csv(ID_path) return X_path, y_path, ID_path def load_dataset(should_generate_dataset=False, use_vad=False, X_path='data/feature_vector_based_mean_mfcc_and_std_mfcc.csv', y_path='data/y_labels.csv', ID_path='data/IDs.csv'): if should_generate_dataset: X_path, y_path, ID_path = generate_csv_dataset(use_vad) starting_time = time.time() # data = pd.read_csv('./data/characteristic_vector_using_mfcc_and_mean_square_deviation_20230722.csv') X = pd.read_csv(X_path) X = X.drop('Unnamed: 0', axis=1) y = pd.read_csv(y_path) y = y.drop('Unnamed: 0', axis=1) ID = pd.read_csv(ID_path) ID = ID.drop('Unnamed: 0', axis=1) print("data loaded in " + str(time.time() - starting_time) + "ms") print(X.head()) print("X.shape = ", X.shape) print("X.columns = ", X.columns) return X, y, ID def get_k_fold_group_member(): return { '0': {2, 5, 14, 15, 16}, '1': {3, 6, 7, 13, 18}, '2': {10, 11, 12, 19, 20}, '3': {8, 17, 21, 23, 24}, '4': {1, 4, 9, 22} } def get_custom_k_folds(X, y, ID, group_members): X_k_fold = dict() y_k_fold = dict() for k, members in group_members.items(): fold_X = pd.DataFrame() fold_y = pd.DataFrame() for actor_ID in members: inds = ID[ID['0'] == actor_ID].index.tolist() fold_X = pd.concat([fold_X, X.loc[inds, :]]) fold_y = pd.concat([fold_y, y.loc[inds, :]]) X_k_fold[k] = fold_X y_k_fold[k] = fold_y return X_k_fold, y_k_fold
from PySide6.QtWidgets import ( QVBoxLayout, QWidget, QPushButton, QTextEdit, QLabel, QFileDialog, ) from PySide6.QtGui import QPalette, QColor from PySide6.QtCore import Qt import base64 class CriptografarScreen(QWidget): def __init__(self, parent): super().__init__() self.parent = parent self.pastaPath = "" self.setMouseTracking(True) self.inicializadorUi() # Inicializador desta interface def inicializadorUi(self): layout = QVBoxLayout() style = """ font-size: 14px; font-weight: bold; """ label = QLabel("Digite o texto para ser criptografado:") layout.addWidget(label) self.erroLabel = QLabel("") self.erroLabel.setStyleSheet(style) layout.addWidget(self.erroLabel) self.textoEdit = QTextEdit() layout.addWidget(self.textoEdit) self.label2 = QLabel("") # Deixa o texto clicavel self.label2.setTextInteractionFlags( Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard ) self.label2.setStyleSheet("font-size: 14px;") layout.addWidget(self.label2) openDirButton = QPushButton("Selecionar Diretório") openDirButton.setFixedHeight(35) openDirButton.clicked.connect(self.openDiretorio) layout.addWidget(openDirButton) cripButton = QPushButton("Gerar arquivo criptografado") cripButton.setFixedHeight(40) cripButton.clicked.connect(self.criptografar) layout.addWidget(cripButton) voltarButton = QPushButton("Voltar ao Menu") voltarButton.clicked.connect(self.parent.showVoltarMenu) voltarButton.setFixedHeight(30) layout.addWidget(voltarButton) self.setLayout(layout) def openDiretorio(self): options = QFileDialog.Options() options |= QFileDialog.ShowDirsOnly self.pastaPath = QFileDialog.getExistingDirectory( self, "Selecionar Diretório", "", options=options ) # Metodo de condição, codificação e criptografia def criptografar(self): texto = self.textoEdit.toPlainText() if not texto.strip(): palette = QPalette() palette.setColor(QPalette.WindowText, QColor("red")) self.erroLabel.setPalette(palette) self.erroLabel.setText("Digite algo para ser criptografado!!") elif not self.pastaPath.strip(): palette = QPalette() palette.setColor(QPalette.WindowText, QColor("red")) self.erroLabel.setPalette(palette) self.erroLabel.setText("Escolha a pasta para salvar o arquivo!") else: texto_codificado = base64.b64encode(texto.encode("utf-8")) self.chave = texto_codificado.decode("utf-8") self.erroLabel.setText("") texto_crip = CriptografarScreen.cifra_de_vigenere(texto, self.chave) self.label2.setText(f"Sua chave de criptografia é: {self.chave}") arquivo = open(f"{self.pastaPath}/codificado.txt", "w") arquivo.write(texto_crip) arquivo.close() palette = QPalette() palette.setColor(QPalette.WindowText, QColor("green")) self.erroLabel.setPalette(palette) self.erroLabel.setText("As informações foram criptografadas!") # Metodo de criptografia def cifra_de_vigenere(texto, chave): resultado = [] # Pega cada caractere do texto digitado for i in range(len(texto)): # Verifica se o caractere é uma letra if texto[i].isalpha(): # Verifica se o caractere do texto é maiusculo ou minusculo e retorna o numero unicode texto_offset = ord("a") if texto[i].islower() else ord("A") # Verifica se o caractere da chave é maiusculo ou minusculo e retorna o numero unicode chave_offset = ord("a") if chave[i % len(chave)].islower() else ord("A") # Calcula a quantidade de deslocamento deslocamento = ( # Pega o numero unicode do carectere ord(texto[i]) - texto_offset + ord(chave[i % len(chave)]) - chave_offset ) % 26 # Ele soma o codigo unicode do caractere digitado e do deslocamento, depois converte em letra resultado.append(chr(deslocamento + texto_offset)) else: resultado.append(texto[i]) return "".join(resultado)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <link rel="stylesheet" href="<c:url value="/resources/css/bootstrap.min.css"/>"> <link rel="stylesheet" href="<c:url value="/resources/fonts/JosefinSans-Thin.ttf"/>"> <link rel="stylesheet" href="<c:url value="/resources/fonts/glyphicons-halflings-regular.ttf"/>"> <link rel="stylesheet" href="<c:url value="/resources/fonts/glyphicons-halflings-regular.woff"/>"> <link rel="stylesheet" href="<c:url value="/resources/fonts/glyphicons-halflings-regular.woff2"/>"> <link rel="stylesheet" href="<c:url value="/resources/css/addCar.css"/>"> <title>Mechanic ${pageContext.request.userPrincipal.name}</title> </head> <body> <br><br><br> <div class="container"> <div class="row"> <div class="col-md-5 toppad pull-right col-md-offset-3"> <a href="<c:url value="/"/>" >Home</a> <a href="<c:url value="/logout"/>" >Logout</a> </div> <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xs-offset-0 col-sm-offset-0 col-md-offset-3 col-lg-offset-3 toppad" > <div class="panel panel-info"> <div class="panel-heading"> <c:if test="${pageContext.request.userPrincipal.name != null}"> <h3 class="panel-title" align="center">User: ${pageContext.request.userPrincipal.name}</h3> </c:if> </div> <div class="panel-body"> <div class="row"> <div class="col-md-3 col-lg-3 " align="center"><img alt="User Pic" src="<c:url value="/resources/image/userpic.png"/>" class="img-circle img-responsive"> </div> <div class=" col-md-9 col-lg-9 "> <table class="table table-user-information"> <tbody> <tr> <th>User level:</th> <td>Mechanic</td> </tr> <tr> <th>First Name:</th> <td>${firstName}</td> </tr> <tr> <tr> <th>Last Name:</th> <td>${lastName}</td> </tr> <tr> <th>E-mail:</th> <td><a href="#">${email}</a></td> </tbody> </table> <div class="btn-group" align="center"> <button class="btn btn-primary btn-sm open_window_add_order">Add Orders</button> <button class="btn btn-info btn-sm open_window_show_order">Show Orders</button> </div> </div> </div> </div> <div class="panel-footer"> <a data-original-title="Write Message" data-toggle="tooltip" type="button" class="btn btn-sm btn-primary"><i class="glyphicon glyphicon-envelope"></i></a> <span class="pull-right"> <a href="#" data-original-title="Edit this user" data-toggle="tooltip" type="button" class="btn btn-sm btn-warning"><i class="glyphicon glyphicon-edit"></i></a> <a href="#" data-original-title="Remove this user" data-toggle="tooltip" type="button" class="btn btn-sm btn-danger"><i class="glyphicon glyphicon-remove"></i></a> </span> </div> </div> </div> </div> </div> <script type="text/javascript" src="<c:url value="/resources/js/lib/bootstrap.min.js"/>"></script> <script type="text/javascript" src="<c:url value="/resources/js/lib/jquery-1.11.3.min.js"/>" ></script> <script type="text/javascript" src="<c:url value="/resources/js/orderForMechanic.js"/>" ></script> <script type="text/javascript"> $(document).ready(function(){ $('.popup_add_order .close_popup, .overlay').click(function (){ $('.popup_add_order, .overlay').css({'opacity':'0', 'visibility':'hidden'}); }); $('.open_window_add_order').click(function (e){ $('.popup_add_order, .overlay').css({'opacity':'1', 'visibility':'visible'}); e.preventDefault(); }); $('.popup_show_order .close_popup, .overlay').click(function (){ $('.popup_show_order, .overlay').css({'opacity':'0', 'visibility':'hidden'}); }); $('.open_window_show_order').click(function (e){ $('.popup_show_order, .overlay').css({'opacity':'1', 'visibility':'visible'}); e.preventDefault(); }); $(window).load(function () { showOrder(); }); $("#addOrder").click(function () { addToTable(); }); }); </script> <div class="overlay" title="Add order"></div> <div class="popup_add_order"> <div class="row centered-form"> <form role="form" class="form-horizontal"> <div class="form-group"> <label class="col-sm-3 control-label">Username:</label> <div class="col-sm-7"> <input type=text class="form-control input-sm" id="username" placeholder="Enter the user"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Car:</label> <div class="col-sm-7"> <input type=text class="form-control input-sm" id="carId" placeholder="Enter the car of user"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Breaking:</label> <div class="col-sm-7"> <textarea class="form-control input-sm" id="breaking" cols="40" rows="3" placeholder="Enter the Breaking"></textarea> </div> </div> <div class="form-group"> <div class="col-sm-3" align="right"> <button type="button" id = "addOrder" class="btn btn-info btn-primary">Add</button> </div> <div class="col-sm-7"> <div class="close_popup" align="right"> <button type="button" id = "closePopup" class="btn btn-info btn-success">Close</button> </div> </div> </div> </form> </div> <%-- <form action="#" method="get"> <div class="form-group"> <label class="col-sm-3 control-label">Пользователь:</label> <div class="col-sm-7"> <select name="userId" id="userId" class="form-control"> <option value="0">- выберите пользователя -</option> </select> </div> <label class="col-sm-3 control-label">Машины:</label> <div class="col-sm-7"> <select name="carId" id="carId" disabled="disabled" class="form-control"> <option value="0">- выберите машину -</option> </select> </div> </div> </form>--%> </div> <div class="overlay" title="Show lits of order">Show lits of order</div> <div class="popup_show_order"> <div class = "center" id="addOrders"> <div class="container"> <table class="table table-bordered" id="OrderDataTable"> <thead> <tr class="text-center"> <th class="text-center">ID</th> <th class="text-center">User</th> <th class="text-center">Mark</th> <th class="text-center">Color</th> <th class="text-center">Vin</th> <th class="text-center">Miles</th> <th class="text-center">Breaking</th> <th class="text-center">Status</th> <th class="text-center" colspan="2">Action</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <div class="close_popup" align="right"> <button type="button" class="btn btn-info btn-success">Close</button> </div> </div> </body> </html>
<div class="container"> <div class="row"> <div class="col-xs-12"> <button class="btn btn-primary" (click)="onlyOdd = !onlyOdd">Only show odd numbers</button> <br><br> <ul class="list-group"> <div *ngIf="onlyOdd"> <li class="list-group-item" *ngFor="let odd of oddNumbers" [ngClass]="{odd: odd % 2 !== 0}" [ngStyle]="{backgroundColor: odd % 2 !== 0 ? 'green' : 'yellow'}"> {{odd}} </li> </div> <!-- <div *ngIf="!onlyOdd"> <li class="list-group-item" [ngClass]="{odd: even % 2 == 0}" [ngStyle]="{backgroundColor: even % 2 !== 0 ? 'red' : 'yellow'}" *ngFor="let even of evenNumbers"> {{even}} </li> </div> <ng-template [ngIf] = "!onlyOdd"> <div> <li class="list-group-item" [ngClass]="{odd: even % 2 == 0}" [ngStyle]="{backgroundColor: even % 2 !== 0 ? 'red' : 'yellow'}" *ngFor="let even of evenNumbers"> {{even}} </li> </div> </ng-template> --> <div *appUnless="onlyOdd"> <li class="list-group-item" [ngClass]="{odd: even % 2 == 0}" [ngStyle]="{backgroundColor: even % 2 !== 0 ? 'red' : 'yellow'}" *ngFor="let even of evenNumbers"> {{even}} </li> </div> </ul> <p appBasicHighlight>This is Basic Highlight Directive!</p> <p [appBetterHighlight] ="'green'" [defaultColor]="'yellow'">This is Better Highlight Directive!</p> <!-- Use of ngSwitch structural directive --> <div [ngSwitch]="value"> <p *ngSwitchCase="5">This is 5</p> <p *ngSwitchCase="10">This is 10</p> <p *ngSwitchCase="100">This is 100</p> <p *ngSwitchDefault>This is default value</p> </div> </div> </div> </div>
package com.buurbak.api.trailers.model; import com.buurbak.api.images.model.Image; import com.buurbak.api.users.model.Address; import com.buurbak.api.users.model.Customer; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; import java.util.List; @Entity @Getter @Setter @NoArgsConstructor public class TrailerOffer { @Id @GeneratedValue @Column(columnDefinition = "uuid") private UUID id; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(nullable = false) private Customer owner; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(nullable = false) private TrailerType trailerType; @ManyToMany(fetch = FetchType.LAZY) @JoinColumn(nullable = false) private Collection<Accessoire> accessoire = new ArrayList<>(); @Column(nullable = false) private int length; @Column(nullable = false) private int height; @Column(nullable = false) private int width; @Column(nullable = false) private int weight; @Column(nullable = false) private int capacity; @Column(nullable = false) private String name; @Column(columnDefinition = "text", length = 1200, nullable = false) private String description; @Column(columnDefinition = "text", nullable = false) private String licensePlate; @Column(columnDefinition = "text", nullable = false) private String driversLicenseType; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "addressId", referencedColumnName = "id") private Address address; @Column(nullable = false) private double latitude; @Column(nullable = false) private double longitude; @Column(nullable = false) private double nearbyLatitude; @Column(nullable = false) private double nearbyLongitude; private String stripeProductId; @OneToOne private Image coverImage; @ElementCollection private List<String> images = new ArrayList<>(); @CreationTimestamp @Column(updatable = false) private LocalDateTime createdAt; @UpdateTimestamp private LocalDateTime updatedAt; private boolean deleted = false; public TrailerOffer(Customer owner, TrailerType trailerType, int length, int height, int width, int weight, int capacity, String description, String licensePlate, String driversLicenseType, Address address, double latitude, double longitude, double nearbyLatitude, double nearbyLongitude, String stripeProductId, Image coverImage) { this.owner = owner; this.trailerType = trailerType; this.length = length; this.height = height; this.width = width; this.weight = weight; this.capacity = capacity; this.description = description; this.licensePlate = licensePlate; this.driversLicenseType = driversLicenseType; this.address = address; this.latitude = latitude; this.longitude = longitude; this.nearbyLatitude = nearbyLatitude; this.nearbyLongitude = nearbyLongitude; this.stripeProductId = stripeProductId; this.coverImage = coverImage; } }
#pragma once #include <d3d11.h> #include "Vertex.h" #include <wrl/client.h> // Used for ComPtr - a smart pointer for COM objects using namespace DirectX; class Mesh { private: // ComPtr's to the vertex and index buffers and device Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> indexBuffer; int indexCount; public: // Constructor Mesh(Vertex* vertices, int vertexCount, unsigned int* indices, int indexCount, Microsoft::WRL::ComPtr<ID3D11Device> device); // Ctor for loading mesh from file Mesh(const char* objFile, Microsoft::WRL::ComPtr<ID3D11Device> device); ~Mesh(); // Returns vertex buffer ptr Microsoft::WRL::ComPtr<ID3D11Buffer> GetVertexBuffer(); // Returns index buffer ptr Microsoft::WRL::ComPtr<ID3D11Buffer> GetIndexBuffer(); // Returns index count for mesh int GetIndexCount(); // Sets buffers and tells DirectX to draw the correct number of indices void Draw(Microsoft::WRL::ComPtr<ID3D11DeviceContext> context); // Creates meshes. Used for both CTORS void CreateMesh(Vertex* vertices, int vertexCount, unsigned int* indices, int indexCount, Microsoft::WRL::ComPtr<ID3D11Device> device); // Calculates tangents void CalculateTangents(Vertex* verts, int numVerts, unsigned int* indices, int numIndices); };
require 'httparty' require 'benchmark' namespace :load_test do desc 'Make API requests and measure performance' task :test_performance do api_url = 'http://127.0.0.1:3000/articles?query=error' # Replace with your API endpoint num_requests = 1000 # Adjust as needed def make_api_request(api_url) begin response = HTTParty.get(api_url) return true # Request successful rescue StandardError => e puts "Request failed: #{e.message}" return false # Request failed end end successful_requests = 0 threads = [] time_elapsed = Benchmark.realtime do num_requests.times do threads << Thread.new do if make_api_request(api_url) successful_requests += 1 end end end threads.each { |t| t.join } end puts "Successful Requests: #{successful_requests} out of #{num_requests}" puts "Requests per second: #{num_requests / time_elapsed}" end end
const express = require("express"); // Importa o framework Express const uuid = require("uuid"); // Importa o pacote uuid para gerar IDs únicos const port = 3001; // Define a porta em que o servidor irá escutar const app = express(); // Cria uma instância do aplicativo Express app.use(express.json()); // Habilita o uso de JSON para análise do corpo da requisição /* - Query params => meuSite.com/users?name=natalia&age=37 // FILTROS - Route params => /users/2 // BUSCAR, DELETAR OU ATUALIZAR ALGO ESPECÍFICO */ const users = []; // Middleware para verificar se um usuário com um determinado ID existe const checkUserId = (request, response, next) => { const { id } = request.params; // Obtém o ID do usuário a ser atualizado dos parâmetros da rota const index = users.findIndex((user) => user.id === id); // Encontra o índice do usuário a ser atualizado no array de usuários // Verifica se o usuário foi encontrado if (index < 0) { return response.status(404).json({ error: "User not found" }); // Retorna um erro 404 (Não encontrado) se o usuário não existir } // Adiciona as informações do usuário e seu índice à requisição para uso posterior request.userIndex = index; request.userId = id; next(); // Chama o próximo middleware ou rota }; // Rota para obter todos os usuários app.get("/users", (request, response) => { // Retorna todos os usuários em formato JSON return response.json({ users }); }); // Rota para criar um novo usuário app.post("/users", (request, response) => { const { name, age } = request.body; // Extrai o nome e a idade do corpo da requisição const user = { id: uuid.v4(), name, age }; // Cria um novo usuário com um ID único usando o pacote uuid users.push(user); // Adiciona o novo usuário ao array de usuários return response.status(201).json({ users }); // Retorna o status 201 (Criado) e o array atualizado de usuários em formato JSON }); // Rota para atualizar um usuário existente app.put("/users/:id", checkUserId, (request, response) => { const { name, age } = request.body; // Extrai o novo nome e idade do corpo da requisição const index = request.userIndex; const id = request.userId; const updatedUser = { id, name, age }; // Cria um objeto representando o usuário atualizado users[index] = updatedUser; // Atualiza o usuário no array de usuários return response.json({ updatedUser }); // Retorna o usuário atualizado em formato JSON }); // Define uma rota para deletar um usuário com base no ID app.delete("/users/:id", checkUserId, (request, response) => { const index = request.userIndex; users.splice(index, 1); // Remove o usuário do array de usuários return response.status(204).json(); // Retorna uma resposta de sucesso }); // Inicia o servidor na porta especificada app.listen(port, () => { console.log(`🚀Server started on port ${port}`); });
"use client"; import { FaFilter } from "react-icons/fa"; import { IoIosClose } from "react-icons/io"; import { CiSearch } from "react-icons/ci"; import ProjectTile from "@/components/project-tile"; import React, { useEffect, useState } from "react"; import { api } from "@/trpc/react"; import { useRouter, useSearchParams } from "next/navigation"; import Chat from "@/components/chatbot"; import { ScoringAlgorithm } from "@/utils/scoring-algorithm"; const filter = ( selectedTags: string[], search: string, project: any, type?: string, ) => { return ( (selectedTags.length === 0 || project.tags ?.split(",") .some((tag: any) => selectedTags.includes(tag))) && (project.name.toLowerCase().includes(search.toLowerCase()) || project.description?.toLowerCase().includes(search.toLowerCase())) && (type === undefined || type === "" || type === "other" || project.type === type) ); }; const sortingAlgo = ( projectA: any, projectB: any, user: any, sort: "likes" | "views" | "comments" | "recent" | "score", ) => { if (ScoringAlgorithm(projectA, user) > ScoringAlgorithm(projectB, user)) { return -1; } else if ( ScoringAlgorithm(projectA, user) < ScoringAlgorithm(projectB, user) ) { return 1; } if (sort === "likes") { if (projectA.likes.length > projectB.likes.length) { return -1; } if (projectA.likes.length < projectB.likes.length) { return 1; } } if(sort === "recent") { const dateA = new Date(projectA.createdAt).getTime(); const dateB = new Date(projectB.createdAt).getTime(); console.log(dateA, dateB); if (dateA < dateB) { return 1; } if (dateA > dateB) { return -1; } } return 0; }; export default function ProjectFilterPage({ isSignedIn, userId, user, }: { isSignedIn: boolean; userId: string; user: any; }) { const projects = api.project.fetchAll.useQuery(); const githubTrendingProjects = api.project.fetchGithubTrending.useQuery(); const [search, setSearch] = useState(""); const router = useRouter(); const searchParams = useSearchParams(); const searchQuery = searchParams.get("search"); const searchTags = searchParams.get("tags"); const searchType = searchParams.get("type"); const [projectType, setProjectType] = useState<string | undefined>(""); // const [showGithubProjects, setShowGithubProjects] = useState(false); const [tab, setTab] = useState<"projects" | "github" | "chatbot">("projects"); const [currentTag, setCurrentTag] = useState<string>(""); const [selectedTags, setSelectedTags] = useState<string[]>([]); const [sort, setSort] = useState< "likes" | "views" | "comments" | "recent" | "score" >("score"); const githubSearchedProjects = api.project.fetchGithubSearch.useQuery({ query: search, }); const removeTag = (index: number) => { setSelectedTags(selectedTags.filter((_, i) => i !== index)); }; useEffect(() => { if (searchTags) { setSelectedTags(searchTags.split(",")); } }, [searchTags]); useEffect(() => { if (searchType) { setProjectType(searchType); } }, [searchType]); useEffect(() => { if (searchQuery) { setSearch(searchQuery); } }, [searchQuery]); return ( <div className={`relative mt-20 flex min-h-[91dvh] flex-col bg-base-200 p-8 sm:flex-row`} > <div className={`top-8 mb-8 mr-8 h-fit w-full sm:sticky sm:w-fit`}> <div className={`rounded-xl border border-base-content/10 px-4 py-8`}> <h3 className={`mb-6 text-center text-xl font-bold`}> <FaFilter className={`mr-2 inline-block text-lg text-base-content/50`} /> Filter Projects </h3> <hr className={`mb-4 border-base-content/10`} /> <label className={`label text-sm`}>Project Type</label> <select className={`select select-bordered select-sm mb-4 w-full text-sm`} value={projectType} onChange={(e) => { setProjectType(e.target.value); }} > <option disabled={true} value=""> Select project type </option> <option value="web">Web App</option> <option value="api">API</option> <option value="mobile">Mobile App</option> <option value="game">Game</option> <option value="ai">Artificial Intelligence</option> <option value="ml">Machine Learning</option> <option value="desktop">Desktop App</option> <option value="other">Other</option> </select> <label className={`label text-sm`}>Technologies</label> <input className={`input input-bordered input-sm w-full min-w-52`} placeholder={`e.g React`} value={currentTag} onChange={(e) => setCurrentTag(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { setSelectedTags([...selectedTags, currentTag]); setCurrentTag(""); } }} /> {selectedTags.length > 0 && ( <ul className={`mt-4 flex flex-wrap items-center justify-end space-x-4`} > {selectedTags.map( (tag, index) => tag != "" && ( <li key={index}> <span className="badge text-nowrap"> {tag} <IoIosClose className={`ml-1 text-lg hover:cursor-pointer hover:bg-base-200`} onClick={() => removeTag(index)} /> </span> </li> ), )} </ul> )} <label className={`label mt-4 text-sm`}>Sort by</label> <select className={`select select-bordered select-sm w-full text-sm`} value={sort} onChange={(e) => { setSort(e.target.value as any); }} > <option disabled={true} value=""> Sort by </option> <option value="score">Recommended</option> <option value="likes">Most liked</option> <option value="recent">Most recent</option> </select> <button className={`btn btn-neutral mt-8 w-full`} onClick={() => { setSelectedTags([]); setCurrentTag(""); setProjectType(""); router.replace("/projects"); }} > Clear Filters </button> </div> <hr className={`mb-4 border-base-content/10`} /> {tab === "github" ? ( <button onClick={() => { setTab("projects"); }} className={`btn btn-outline btn-neutral w-full border-base-content/30`} > Back to Projects </button> ) : ( <button onClick={() => { setTab("github"); }} className={`btn btn-outline btn-neutral w-full border-base-content/30`} > Trending Github Projects </button> )} <p className={`mt-6 text-sm font-semibold text-base-content/70`}> Having issues? </p> {tab === "chatbot" ? ( <button onClick={() => { setTab("projects"); }} className={`btn btn-accent mt-1 w-full`} > Ask Chatbot </button> ) : ( <button onClick={() => { setTab("chatbot"); }} className={`btn btn-outline btn-accent mt-1 w-full`} > Ask Chatbot </button> )} </div> <div className={`w-full`}> {tab !== "chatbot" && ( <div className={`w-full`}> <input className={`input input-bordered mb-8 w-full`} placeholder={`Search Projects...`} value={search} onChange={(e) => setSearch(e.target.value)} /> <button className={`btn btn-square btn-ghost absolute right-8`}> <CiSearch className={`text-xl`} /> </button> </div> )} <div className={`grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3`} > {projects.data === undefined ? ( <p className={`col-span-3 mt-36 text-center text-sm text-base-content/70`} > Loading... </p> ) : ( <> {tab === "projects" && projects.data ?.filter((project) => filter(selectedTags, search, project, projectType), ) .sort((a, b) => sortingAlgo(a, b, user, sort)) .map( (project, index) => project && ( <ProjectTile id={project.id} searchedQuery={search} key={index} type={project.type ?? undefined} title={project.name} description={project.description ?? ""} image={project.image ?? ""} tags={project.tags?.split(",") ?? []} searchedTags={selectedTags} isSignedIn={isSignedIn} selectedTags={selectedTags} score={ScoringAlgorithm(project, user)} /> ), )} {tab !== "chatbot" && githubSearchedProjects.data && githubSearchedProjects.data.map((project, index) => ( <ProjectTile id={undefined} searchedQuery={search} key={index} title={project.name} description={project.description ?? ""} tags={project.topics ?? []} searchedTags={selectedTags} image={""} isSignedIn={isSignedIn} isGithubProject={true} repoUrl={project.html_url} // @ts-ignore score={ScoringAlgorithm(project, user)} /> ))} {tab === "github" && !search && githubTrendingProjects.data && githubTrendingProjects.data.map((project, index) => ( <ProjectTile id={undefined} searchedQuery={search} key={index} title={project.name} description={project.description ?? ""} tags={project.topics ?? []} searchedTags={selectedTags} image={""} isSignedIn={isSignedIn} isGithubProject={true} repoUrl={project.html_url} // @ts-ignore score={ScoringAlgorithm(project, user)} /> ))} </> )} </div> {tab === "chatbot" && ( <Chat userId={userId} projects={projects} isSignedIn={isSignedIn} /> )} {projects.data && projects.data.filter((project) => filter(selectedTags, search, project)) .length === 0 && !githubSearchedProjects.data ? ( <p className={`flex min-h-[60dvh] items-center justify-center text-base-content/70`} > Loading projects from other sources... </p> ) : ( <></> )} </div> </div> ); }
<% content_for(:whole_page) do %> <h2 class="text-center">My Workouts (past 7 days)</h2> <div class="col-md-7 col-xs-12"> <% unless @exercises.empty? %> <table class="table tabel-striped"> <thead> <tr> <th>Duration (min)</th> <th>Workout Details</th> <th>Activity Date</th> <th colspan="3"></th> </tr> </thead> <tbody> <% @exercises.each do |exercise| %> <tr> <td><%= exercise.duration %></td> <td><%= truncate(exercise.workout, length:100) %></td> <td><%= exercise.workout_date %></td> <td><%= link_to "Show", [current_user, exercise] %></td> <td><%= link_to "Edit", [:edit, current_user, exercise] %></td> <td><%= link_to "Delete", [current_user, exercise], method: :delete, data: { confirm: 'are you sure'} %></td> </tr> <% end %> </tbody> </table> <% else %> <div class="alert alert-info message-font text-center" role='alert'> No Workouts </div> <% end %> <div class="row"> <div class="col-md-8 col-xs-12"> <%= link_to "New Workout", new_user_exercise_path(current_user), class:'btn btn-primary'%> </div> </div> <%= content_tag :div, '', id:"chart", data: {workouts: @exercises} %> </div> <div class="col-md-5 col-xs-12"> <div id='chat-window' class="col-md-12"> <header class='text-center'> Channel: <%= current_room.name %> </header> <div class="col-md-2" id="followers"> <% @followers.each do |follower| %> <%= link_to follower.user.full_name, user_exercises_path(current_user, roomId: follower.user.room.id), class:"followers" %> <br> <% end %> </div> <div class="col-md-10" id="messages-box"> <div id='chat-box' data-channel='rooms' data-room-id=<%= current_room.id %>> <% @messages.each do |message|%> <%= render partial: 'shared/message', locals: {message: message}%> <% end %> </div> <div id="form-box"> <%= form_for @message do |f| %> <%= f.text_field :body, id:"message-field", class:"form-control pull-left" %> <%= f.submit 'Post', class:"btn btn-default", id: "post-btn"%> <% end %> </div> </div> </div> <h2 class='text-center'><%= current_user.full_name%>'s Friends</h2> <% if current_user.friends.any?%> <% @friends.each do |friend| %> <div class="col-md-offset-3 col-md-6 friend_name"> <%= link_to friend.full_name, friendship_path(current_user.current_friendship(friend)) %> </div> <div class="col-md-3"> <div class="btn-unfollow"> <%= link_to "Unfollow", friendship_path(current_user.current_friendship(friend)), method: :delete, data:{confirm:"Are you sure?"}, class: "btn btn-danger link" %> </div> </div> <% end%> <% else %> Search for others to add as friends. <% end%> <% end %> </div>
package com.geek.entity; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.util.Date; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "actors") public class Actors { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; @Column(name = "first_name", length = 200) private String firstName; @Column(name = "last_name", length = 200) private String lastName; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthDate; @Enumerated(EnumType.STRING) private Genders gender; @ManyToMany(mappedBy = "actors", cascade = { CascadeType.ALL }) private Set<Movie> movies = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Genders getGender() { return gender; } public void setGender(Genders gender) { this.gender = gender; } public Set<Movie> getMovies() { return movies; } public void setMovies(Set<Movie> movies) { this.movies = movies; } public String getFullName() { return getFirstName() + " " + getLastName(); } }
import { executeQuery } from "@/app/nextauth/MySQLConnection"; import { NextResponse } from "next/server"; import path from "path"; import { writeFile } from "fs/promises"; export async function POST(req) { const body = await req.formData(); const dataString = body.get('data'); const { product_name, product_detail, product_type, product_price, product_quantity } = JSON.parse(dataString); const product_img = body.get('product_img'); const buffer = Buffer.from(await product_img.arrayBuffer()); const filename = Date.now() + product_img.name.replaceAll(" ", "_") if (!product_name || !product_detail || !product_type || !product_price || !product_quantity || !product_img) { return NextResponse.json({ message: 'Missing some input data' }, { status: 400 }, { success: false }) } try { const check = "SELECT * FROM products WHERE product_name = ?" const query = await executeQuery(check, [product_name]) if (query.length > 0) { return NextResponse.json({ message: 'Product already exists' }, { status: 400 }, { sucess: false }) } const insert = "INSERT INTO products (product_name,product_detail,product_type,product_price,product_quantity,product_img) VALUES (?,?,?,?,?,?)" const query2 = await executeQuery(insert, [ product_name, product_detail, product_type, product_price, product_quantity, filename, ]) if (query2.affectedRows === 1) { await writeFile( path.join(process.cwd(), "public/products/" + filename), buffer ); } return NextResponse.json({ message: 'Product added successfully' }, { status: 201 }, { success: true }) } catch (err) { return NextResponse.json({ message: 'Have some trouble, Please try again..' }, { status: 500 }, { success: false }) } }
/* * clientlistmodel.cpp * Copyright (C) 2016 Michał Garapich <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "clientlistmodel.h" #include "core/atc.h" #include "core/pilot.h" #include "core/servertracker.h" #include "misc/roles.h" #include <functional> using namespace Vatsinator::Core; namespace Vatsinator { namespace Misc { ClientListModel::ClientListModel(QObject* parent) : QAbstractListModel(parent) {} ClientListModel::~ClientListModel() {} void ClientListModel::setSorted(bool sorted) { m_sorted = sorted; if (sorted) { std::sort(m_clients.begin(), m_clients.end(), [](auto a, auto b) { return a->callsign() < b->callsign(); }); // section by type - ATCs first, flights second std::stable_sort(m_clients.begin(), m_clients.end(), [](auto a, auto b) { if (qobject_cast<const Atc*>(a)) { return qobject_cast<const Atc*>(b) == nullptr; } else { return false; } }); } } int ClientListModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return m_clients.count(); } int ClientListModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 3; } QVariant ClientListModel::data(const QModelIndex& index, int role) const { switch (role) { case Qt::TextAlignmentRole: return Qt::AlignCenter; case Qt::ToolTipRole: return m_clients.at(index.row())->realName(); case Qt::DisplayRole: switch (index.column()) { case 0: return m_clients.at(index.row())->callsign(); case 1: return m_clients.at(index.row())->realName(); case 2: if (qobject_cast<const Atc*>(m_clients.at(index.row()))) { return QStringLiteral("ATC"); } else if (qobject_cast<const Pilot*>(m_clients.at(index.row()))) { return QStringLiteral("PILOT"); } default: return QVariant(); } case CallsignRole: return m_clients.at(index.row())->callsign(); case RealNameRole: return m_clients.at(index.row())->realName(); case TypeRole: if (qobject_cast<const Atc*>(m_clients.at(index.row()))) { return QStringLiteral("ATC"); } else if (qobject_cast<const Pilot*>(m_clients.at(index.row()))) { return QStringLiteral("PILOT"); } case InstanceRole: if (const Atc* atc = qobject_cast<const Atc*>(m_clients.at(index.row()))) return QVariant::fromValue<Atc*>(const_cast<Atc*>(atc)); else if (const Pilot* pilot = qobject_cast<const Pilot*>(m_clients.at(index.row()))) return QVariant::fromValue<Pilot*>(const_cast<Pilot*>(pilot)); else return QVariant(); case FrequencyRole: if (const Atc* atc = qobject_cast<const Atc*>(m_clients.at(index.row()))) { return atc->frequency(); } else { return QVariant(); } case DepartureRole: if (const Pilot* p = qobject_cast<const Pilot*>(m_clients.at(index.row()))) return QVariant::fromValue(p->departure()); else return QVariant(); case DestinationRole: if (const Pilot* p = qobject_cast<const Pilot*>(m_clients.at(index.row()))) return QVariant::fromValue(p->destination()); else return QVariant(); default: return QVariant(); } } QVariant ClientListModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return tr("Callsign"); case 1: return tr("Name"); case 2: return QString(); default: return QVariant(); } } else { return QVariant(); } } QHash<int, QByteArray> ClientListModel::roleNames() const { auto roles = QAbstractListModel::roleNames(); roles[CallsignRole] = "callsign"; roles[RealNameRole] = "realName"; roles[TypeRole] = "type"; roles[InstanceRole] = "instance"; roles[FrequencyRole] = "frequency"; roles[DepartureRole] = "departure"; roles[DestinationRole] = "destination"; return roles; } ClientListModel* ClientListModel::clients(const AirportObject* airport, QObject* parent) { ClientListModel* m = new ClientListModel(parent); if (airport) { auto adder = std::bind(&ClientListModel::add, m, std::placeholders::_1); std::for_each(airport->asSet().constBegin(), airport->asSet().constEnd(), adder); auto conn = connect(airport, &AirportObject::clientAdded, adder); connect(m, &QObject::destroyed, [conn]() { QObject::disconnect(conn); }); } return m; } ClientListModel* ClientListModel::clients(const FirObject* fir, QObject* parent) { ClientListModel* m = new ClientListModel(parent); if (fir) { auto adder = std::bind(&ClientListModel::add, m, std::placeholders::_1); std::for_each(fir->asSet().constBegin(), fir->asSet().constEnd(), adder); auto conn = connect(fir, &FirObject::clientAdded, adder); connect(m, &QObject::destroyed, [conn]() { QObject::disconnect(conn); }); } return m; } ClientListModel*ClientListModel::pilots(const ServerTracker* server, QObject* parent) { ClientListModel* m = new ClientListModel(parent); if (server) { auto adder = [m](Client* c) { if (qobject_cast<Pilot*>(c)) m->add(c); }; auto clients = server->clients(); std::for_each(clients.constBegin(), clients.constEnd(), adder); auto conn = connect(server, &ServerTracker::clientAdded, adder); connect(m, &QObject::destroyed, [conn]() { QObject::disconnect(conn); }); } return m; } void ClientListModel::add(const Client* client) { Q_ASSERT(client); beginInsertRows(QModelIndex(), m_clients.count(), m_clients.count()); m_clients << client; endInsertRows(); connect(client, &QObject::destroyed, this, &ClientListModel::remove, Qt::DirectConnection); } void ClientListModel::remove(QObject* obj) { Q_ASSERT(obj); for (int i = 0; i < m_clients.size(); ++i) { if (m_clients.at(i) == obj) { beginRemoveRows(QModelIndex(), i, i); m_clients.removeAt(i); endRemoveRows(); return; } } Q_UNREACHABLE(); } }} /* namespace Vatsinator::Misc */
// @ts-check export function Size(width,height) { this.width=width ?? 80; this.height=height ?? 60; }; Size.prototype.resize = function(newWidth,newHeight) { this.width=newWidth; this.height=newHeight; }; export function Position(x,y) { this.x=x ?? 0; this.y=y ?? 0; }; Position.prototype.move = function(newX,newY) { this.x=newX; this.y=newY; }; export class ProgramWindow { constructor() { this.screenSize = new Size(800,600); this.size = new Size(); this.position = new Position(); } resize(newSize) { // sanity check input let w = Math.max(newSize.width, 1); let h = Math.max(newSize.height, 1); // how much space is available let wRemain = 800 - this.position.x; let hRemain = 600 - this.position.y; if (wRemain < w) { w = wRemain; } if (hRemain < h) { h = hRemain; } this.size = new Size(w,h); } move(newPosition) { // sanity check input let x = Math.max(newPosition.x, 0); let y = Math.max(newPosition.y, 0); // will this fit at the new position let wRemain = 800 - (newPosition.x + this.size.width); let hRemain = 600 - (newPosition.y + this.size.height); if (wRemain < 0) { x = x + wRemain; } if (hRemain < 0) { y = y + hRemain; } this.position = new Position(x,y); } } export function changeWindow(newWindow) { newWindow.resize(new Size(400,300)); newWindow.move(new Position(100,150)); return newWindow; }
import React, { useState } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, ScrollView } from 'react-native'; import { COLORS, FONTS } from '../../constant/theme'; type DiscountCategory = 'all' | 'ewamall' | 'shop' | 'partner'; interface TabNavigationProps { onSelectTab: (tab: DiscountCategory) => void; } const TabNavigation: React.FC<TabNavigationProps> = ({ onSelectTab }) => { const [selectedTab, setSelectedTab] = useState<DiscountCategory>('all'); const handleTabPress = (tab: DiscountCategory) => { setSelectedTab(tab); onSelectTab(tab); }; return ( <View style={styles.container}> <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.scrollContainer}> <TouchableOpacity style={styles.tab} onPress={() => handleTabPress('all')}> <Text style={[styles.tabText, selectedTab === 'all' && styles.tabTextActive]}>Tất cả (554)</Text> </TouchableOpacity> <TouchableOpacity style={styles.tab} onPress={() => handleTabPress('ewamall')}> <Text style={[styles.tabText, selectedTab === 'ewamall' && styles.tabTextActive]}>EWAMall (487)</Text> </TouchableOpacity> <TouchableOpacity style={styles.tab} onPress={() => handleTabPress('shop')}> <Text style={[styles.tabText, selectedTab === 'shop' && styles.tabTextActive]}>Shop (63)</Text> </TouchableOpacity> <TouchableOpacity style={styles.tab} onPress={() => handleTabPress('partner')}> <Text style={[styles.tabText, selectedTab === 'partner' && styles.tabTextActive]}>Đối tác(1)</Text> </TouchableOpacity> </ScrollView> </View> ); }; const styles = StyleSheet.create({ container: { borderBottomWidth: 1, borderBottomColor: '#ddd', backgroundColor: COLORS.white, }, scrollContainer: { flexDirection: 'row', alignItems: 'center', }, tab: { paddingVertical: 10, paddingHorizontal: 15, }, tabText: { fontSize: 14, fontFamily: FONTS.roboto_regular, color: COLORS.black, }, tabTextActive: { fontSize: 14, fontFamily: FONTS.roboto_bold, color: COLORS.primary, textDecorationLine: 'underline', textDecorationColor: COLORS.primary, }, }); export default TabNavigation;
package com.example.userlib.Services; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.example.userlib.Impl.Booking.Booking; import com.example.userlib.Impl.GiveAway.BookGivenAway; import com.example.userlib.Impl.User.UserImpl; import com.example.userlib.Impl.book.Book; import com.example.userlib.Repository.BookGiveAwayRepository; import com.example.userlib.Repository.BookRepository; import com.example.userlib.Repository.BookingRepository; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class BookServiceTest { @Mock private BookRepository bookRepository; @Mock private BookGiveAwayRepository bookGiveAwayRepository; @Mock private BookingRepository bookingRepository; @InjectMocks private BookService bookService; private UserImpl user; private Book book; private String testString; private Long Id; private BookGivenAway bookGivenAway; @BeforeEach void setUp() { user = new UserImpl(); book = new Book(1L, "test", "test", new Date(), 1, 1); bookGivenAway = new BookGivenAway(user,book, LocalDate.now(), LocalDate.now()); testString = "test"; Id = 1L; } @Test void testFindByTitle() { List<Book> books = new ArrayList<>(); books.add(book); when(bookRepository.findAllByString(testString)).thenReturn(Arrays.asList(book)); List<Book> result = bookService.findByTitle(testString); assertEquals(result, books); } @Test void testFindAll() { List<Book> books = new ArrayList<>(); books.add(book); when(bookRepository.findAll()).thenReturn(Arrays.asList(book)); List<Book> result = bookService.findAll(); assertEquals(result, books); } @Test void testReturnBook(){ when(bookGiveAwayRepository.findBookGivenAwayById(Id)).thenReturn( bookGivenAway ); bookService.returnBook(Id); verify(bookRepository).save(book); verify(bookGiveAwayRepository).deleteById(Id); } @Test void testReturnBookByBlocked(){ Booking booking = new Booking(user, book, LocalDate.now(), LocalDate.now()); bookService.returnBooks(booking); verify(bookingRepository).deleteById(booking.getId()); verify(bookRepository).save(book); } }
import argparse import pandas as pd def csv_to_fasta(csv_file, output_fasta_file): """ Function to convert a CSV file to a FASTA file """ # The FASTA file is stored at the same directoey as the csv file # The FASTA file has the same name (different extension) as the csv file df = pd.read_csv(csv_file) # Read the CSV file into a DataFrame with open(output_fasta_file, 'w') as fasta_file: for index, row in df.iterrows(): # Iterate through each row in the DataFrame header = f'>{index + 1}' # Create the FASTA header using the row index sequence = ''.join([str(int(val)) if val.is_integer() else str(val) for val in row.values]) # Concatenate the values in the row to form the sequence fasta_file.write(f'{header}\n{sequence}\n') # Write the header and sequence to the FASTA file if __name__ == "__main__": parser = argparse.ArgumentParser(description='Path to a CSV file.') parser.add_argument('csv_file', type=str, help='The path to the input file (either CSV or FASTA).') args = parser.parse_args() output_fasta_file_path = args.csv_file.rsplit('.', 1)[0] + '.fa' # Generate the output FASTA file path by replacing the extension csv_to_fasta(args.csv_file, output_fasta_file_path) # Convert the CSV file to a FASTA file
# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require_relative '../config/environment' # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! require 'factory_bot_rails' require 'webmock/rspec' require 'simplecov' SimpleCov.start Rails.root.glob('spec/support/**/*.rb').sort.each { |f| require f } # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e abort e.to_s.strip end RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_paths = [ Rails.root.join('spec/fixtures') ] # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # You can uncomment this line to turn off ActiveRecord support entirely. # config.use_active_record = false # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, type: :controller do # # ... # end # # The different available types are documented in the features, such as in # https://rspec.info/features/6-0/rspec-rails config.infer_spec_type_from_file_location! config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") config.include Rails.application.routes.url_helpers, type: :request # Devise helpers config.infer_spec_type_from_file_location! config.include Devise::Test::ControllerHelpers, type: :controller config.include Devise::Test::ControllerHelpers, type: :view config.include Devise::Test::IntegrationHelpers, type: :system config.include Devise::Test::IntegrationHelpers, type: :request end
package M_sort; // N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오. // 첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수가 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다. // 첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다. import java.util.Scanner; public class Main_2750_2 { private static int[] mergeSort(int[] arr){ if(arr.length > 1){ int[] fArray = new int[arr.length/2]; int[] bArray = new int[arr.length - arr.length/2]; for(int i = 0; i < fArray.length; i++) fArray[i] = arr[i]; for(int i = 0; i < bArray.length; i++) bArray[i] = arr[fArray.length + i]; fArray = mergeSort(fArray); bArray = mergeSort(bArray); arr = mergeArray(fArray, bArray); } return arr; } private static int[] mergeArray(int[] arr1, int[] arr2){ int pos1 = 0; int pos2 = 0; int[] arr = new int[arr1.length + arr2.length]; for(int i = 0; i < arr.length; i++){ if(pos1 == arr1.length){ arr[i] = arr2[pos2]; pos2++; }else if(pos2 == arr2.length){ arr[i] = arr1[pos1]; pos1++; }else if(arr1[pos1] > arr2[pos2]){ arr[i] = arr2[pos2]; pos2++; }else{ arr[i] = arr1[pos1]; pos1++; } } return arr; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int cnt = sc.nextInt(); int[] arr = new int[cnt]; for(int i = 0; i < cnt; i++) arr[i] = sc.nextInt(); arr = mergeSort(arr); for(int i = 0; i < cnt; i++) System.out.println(arr[i]); sc.close(); } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Email; using OrchardCoreContrib.Email.Hotmail.Drivers; using OrchardCoreContrib.Email.Hotmail.ViewModels; using System.Threading.Tasks; namespace OrchardCoreContrib.Email.Hotmail.Controllers { public class AdminController : Controller { private readonly IAuthorizationService _authorizationService; private readonly INotifier _notifier; private readonly ISmtpService _smtpService; private readonly IHtmlLocalizer H; public AdminController( IHtmlLocalizer<AdminController> htmlLocalizer, IAuthorizationService authorizationService, INotifier notifier, ISmtpService smtpService) { H = htmlLocalizer; _authorizationService = authorizationService; _notifier = notifier; _smtpService = smtpService; } [HttpGet] public async Task<IActionResult> Index() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageHotmailSettings)) { return Forbid(); } return View(); } [HttpPost, ActionName(nameof(Index))] public async Task<IActionResult> IndexPost(HotmailSettingsViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageHotmailSettings)) { return Forbid(); } if (ModelState.IsValid) { var message = CreateMessageFromViewModel(model); var result = await _smtpService.SendAsync(message); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError("*", error.ToString()); } } else { await _notifier.SuccessAsync(H["Message sent successfully"]); return Redirect(Url.Action("Index", "Admin", new { area = "OrchardCore.Settings", groupId = HotmailSettingsDisplayDriver.GroupId })); } } return View(model); } private MailMessage CreateMessageFromViewModel(HotmailSettingsViewModel testSettings) { var message = new MailMessage { To = testSettings.To, Bcc = testSettings.Bcc, Cc = testSettings.Cc, ReplyTo = testSettings.ReplyTo }; if (!string.IsNullOrWhiteSpace(testSettings.Sender)) { message.Sender = testSettings.Sender; } if (!string.IsNullOrWhiteSpace(testSettings.Subject)) { message.Subject = testSettings.Subject; } if (!string.IsNullOrWhiteSpace(testSettings.Body)) { message.Body = testSettings.Body; } return message; } } }
(ns chord.keys (:require [hollow.util :as u] [clojure.set :refer [subset?]])) (def key->offset {"C" 0 "C#" 1 "Db" 1 "D" 2 "D#" 3 "Eb" 3 "E" 4 "F" 5 "F#" 6 "Gb" 6 "G" 7 "G#" 8 "Ab" 8 "A" 9 "A#" 10 "Bb" 10 "B" 11}) (def major-note-differences '(4 3)) (def minor-note-differences '(3 4)) (defn generic-chord-validator [chord-note-differences] (let [note-offsets (reduce #(conj %1 (+ %2 (last %1))) [0] chord-note-differences) chord-size (count note-offsets)] (fn [notes] (let [note-count (count notes)] (if (and (<= note-count chord-size) (some (fn [i] (subset? (set (map #(- % (apply min notes)) notes)) (set (map #(- % (nth note-offsets i)) (drop i note-offsets))))) (range (dec chord-size)))) (or (= note-count chord-size) (set notes)) #{}))))) (defn specific-chord-validator [chord-note-differences] (fn [base-note] (fn [notes] (let [offset (key->offset base-note) offset-notes (map #(- % offset) notes) proper-notes (filter (comp (set (reduce #(conj %1 (+ %2 (last %1))) [0] chord-note-differences)) #(mod % 12)) offset-notes)] (if (apply = (map #(quot % 12) proper-notes)) (let [valid-notes (set (map (partial + offset) proper-notes))] (or (and (= notes valid-notes) (= (count valid-notes) 3)) valid-notes)) #{}))))) (def generic-major-chord-validator (generic-chord-validator major-note-differences)) (def generic-minor-chord-validator (generic-chord-validator minor-note-differences)) (def major-chord-validator (specific-chord-validator major-note-differences)) (def minor-chord-validator (specific-chord-validator minor-note-differences))
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:kebut_kurir/core/theme/app_theme.dart'; import 'package:kebut_kurir/core/widgets/asset_image_widget.dart'; import 'package:kebut_kurir/core/widgets/button_custom_widget.dart'; enum ButtonDirection { VERTICAL, HORIZONTAL } class CustomDialog extends StatelessWidget { final String title; final String? subTitle; final String? asset; final ButtonDirection? buttonDirection; final bool? reverseButton; final String? primaryButtonText; final String? secondaryButtonText; final void Function()? onTapPrimary; final Function(dynamic)? onTapSecondary; const CustomDialog({ Key? key, required this.title, this.subTitle, this.asset, this.onTapPrimary, this.onTapSecondary, this.primaryButtonText, this.secondaryButtonText, this.reverseButton = false, this.buttonDirection = ButtonDirection.VERTICAL, }) : super(key: key); @override Widget build(BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.r), ), elevation: 0, backgroundColor: Colors.transparent, child: Material( child: Container( width: MediaQuery.of(context).size.width, padding: const EdgeInsets.all(16), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.r), color: Colors.white, ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ if (asset != null && asset != '') ...<Widget>[ AssetImageWidget( assets: asset!, height: 128, width: 128, fit: BoxFit.contain, ), SizedBox( height: 16.h, ), ], Text( title, textAlign: TextAlign.center, style: AppTheme.textStyle.blackTextStyle.copyWith( fontSize: AppTheme.textConfig.size.l, fontWeight: AppTheme.textConfig.weight.semiBold, ), ), if (subTitle != null && subTitle != '') ...<Widget>[ SizedBox( height: 16.h, ), Text( subTitle!, textAlign: TextAlign.center, style: AppTheme.textStyle.blackTextStyle.copyWith( fontSize: AppTheme.textConfig.size.n, ), ), ], SizedBox( height: 12.h, ), if (buttonDirection == ButtonDirection.HORIZONTAL) ...<Widget>[ Row( children: <Widget>[ Visibility( visible: !reverseButton! ? primaryButtonText != null && primaryButtonText != '' : secondaryButtonText != null && secondaryButtonText != '', child: Expanded( child: ButtonCustom( paddingVer: 8.h, borderRadius: 6.r, paddingHor: 12.w, text: !reverseButton! ? primaryButtonText! : secondaryButtonText!, textColor: !reverseButton! ? AppTheme.colors.primaryColor : const Color(0xFF42526D), buttonColor: !reverseButton! ? AppTheme.colors.secondaryColor : AppTheme.colors.whiteColor, onTap: () { if (!reverseButton!) { if (onTapPrimary != null) { onTapPrimary!(); } } else { if (onTapSecondary != null) { onTapSecondary!(""); } } }, ), ), ), const SizedBox( width: 6, ), Visibility( visible: !reverseButton! ? secondaryButtonText != null && secondaryButtonText != '' : primaryButtonText != null && primaryButtonText != '', child: Expanded( child: ButtonCustom( paddingVer: 8.h, paddingHor: 12.w, borderRadius: 6.r, text: !reverseButton! ? secondaryButtonText! : primaryButtonText, textColor: !reverseButton! ? AppTheme.colors.secondaryColor : const Color(0xFF42526D), buttonColor: !reverseButton! ? AppTheme.colors.whiteColor : AppTheme.colors.primaryColor, onTap: () { if (!reverseButton!) { if (onTapSecondary != null) { onTapSecondary!(""); } } else { if (onTapPrimary != null) { onTapPrimary!(); } } }, ), ), ), ], ) ] else ...<Widget>[ primaryButtonText != null ? Visibility( visible: primaryButtonText != null && primaryButtonText != '', child: ButtonCustom( paddingVer: 8.h, paddingHor: 12.w, borderRadius: 6.r, text: primaryButtonText!, textColor: AppTheme.colors.whiteColor, buttonColor: onTapPrimary != null ? AppTheme.colors.primaryColor : AppTheme.colors.greyColor, onTap: onTapPrimary, ), ) : const SizedBox.shrink(), Visibility( visible: secondaryButtonText != null && secondaryButtonText != '', child: ButtonCustom( paddingVer: 8.h, paddingHor: 12.w, borderRadius: 6.r, text: secondaryButtonText ?? '', textColor: AppTheme.colors.whiteColor, buttonColor: onTapSecondary != null ? AppTheme.colors.primaryColor : AppTheme.colors.greyColor, onTap: () => onTapSecondary, ), ) ], ], ), ), ), ); } }
<!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"> <script src="https://cdn.tailwindcss.com"></script> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&family=Whisper&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="../static/css/style.css"> <title>AppointMED</title> </head> <body> <div class="navbar"> <img class="header-logo" src="../static/images/AppointMED.svg" alt="AppointMED logo"> <div class="navbar-elements"> <a class="nav-element border-transparent rounded-full hover:border-emerald-500" href="/home">Home</a> <a class="nav-element border-transparent rounded-full hover:border-emerald-500" href="/about">About</a> </div> </div> <div id="main" class="flex"> <form id="search" method="post" action="/home"> <div id="search-input"> <div id="doctor-name"> <span class="material-icons material-icons-outlined"> search</span> <input class="style:none" placeholder="Search Doctor..." type="search" name="doctor-name" id="doctor-name"> </div> <select name="doctor-specialty" id="doctor-specialty"> <option value="">All</option> <option value="dermatologist">Dermatologist</option> <option value="allergist">Allergist</option> <option value="cardiologist">Cardiologist</option> <option value="gastroenterologist">Gastroenterologist</option> </select> </div> <div id="doctors"> {% for doctor in doctors %} <a href="/Schedule/{{doctor['doc_id']}}"> <div class="doctor cursor-pointer border-gray-300" data-geo="{{ doctor['lat'] }},{{ doctor['lng'] }}"> <div class="doctor-photo-wrapper"> <span class="doctor-photo material-icons material-symbols-outlined"> account_circle_full </span> </div> <div class="doctor-name"> <p style="font-weight: bolder;">Dr. {{ doctor['first_name'] }} {{ doctor['last_name'] }}</p> <div class="review"> <span class="star material-icons material-symbols-outlined">star</span> <span class="star material-icons material-symbols-outlined">star</span> <span class="star material-icons material-symbols-outlined">star</span> <span class="star material-icons material-symbols-outlined">star</span> <span class="star material-icons material-symbols-outlined">star</span> </div> </div> <div class="doctor-specialty"> {% for specialty in doctor['specialties'] %} {{ specialty }} {% endfor %} </div> </div> </a> {% endfor %} </div> <div class="rounded-full" id="submit"> <input class="cursor-pointer" type="submit" value="Search"> </div> </form> <script src="../static/js/script.js"></script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsJY7KojcXDneWqXV1h0J891NbgFrdglE&map_ids=122517338e1e4a8&callback=initMap"></script> <div id="map-view"> <div id="map"></div> </div> </div> </body> </html>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context=".academy.AddCourseActivity"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_margin="15dp" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.AppCompatTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="1dp" android:gravity="center" android:text="Add New Course" android:textColor="@color/colorPrimary" android:textSize="20dp" android:textStyle="bold" /> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:textColorHint="@color/colorAccent" app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout"> <AutoCompleteTextView android:id="@+id/course_Topic" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Topic" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:textColorHint="@color/colorAccent" app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout"> <EditText android:id="@+id/course_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:textColorHint="@color/colorAccent" app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout"> <EditText android:id="@+id/course_overview" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="OverView" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:textColorHint="@color/colorAccent" app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout"> <EditText android:id="@+id/course_Link" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Course Link" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:textColorHint="@color/colorAccent" app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout"> <EditText android:id="@+id/course_hours" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint=" Hours" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:textColorHint="@color/colorAccent" app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout"> <EditText android:id="@+id/course_price" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Price" /> </android.support.design.widget.TextInputLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:orientation="horizontal"> <android.support.v7.widget.AppCompatTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:text="Certified: " android:textAlignment="center" android:textColor="@color/colorPrimary" android:textSize="18dp" /> <RadioGroup android:id="@+id/radioGenderGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginBottom="15dp" android:orientation="horizontal"> <RadioButton android:id="@+id/radio_yes" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Yes" /> <RadioButton android:id="@+id/radio_no" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/radio_yes" android:layout_alignLeft="@+id/radioGroup1" android:text="No" /> </RadioGroup> </LinearLayout> <Button android:id="@+id/add_new_course_Button" style="?android:textAppearanceSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="25dp" android:layout_marginBottom="15dp" android:background="@color/colorPrimary" android:text="Add" android:textAllCaps="false" android:textColor="@android:color/white" android:textSize="20dp" android:textStyle="bold" /> </LinearLayout> </ScrollView> </LinearLayout>
[TOC] ##### 简要描述 - 获取用户信息,可以获取普通用户、群聊、公众号的信息。 - 可以传入单个wxid或wxid列表,单次调用不应超过20个wxid。 - 请注意,参数为string和参数为list时的返回结构有差别。 ##### 请求URL - ` http://127.0.0.1:8000/api/` ##### 请求方式 - POST ##### 参数 |参数名|必选|类型|说明| |:---- |:---|:----- |----- | |type |是 |int | 接口编号 | |userName |是 |string, list | 用户wxid或wxid列表 | ##### 请求示例 ``` { "type": 10015, "userName": "filehelper", } ``` ``` { "type": 10015, "userName": "wxid_xxx", "chatroomUserName": "xxx@chatroom", } ``` ``` { "type": 10015, "userName": ["filehelper", "gh_xxx", "wxid_xxx"] } ``` ##### 返回示例 ``` { "error_code": 10000, "description": "", "data": { "status": 0, "desc": "", "data": [] } } ``` ##### 返回参数说明 |参数名|类型|说明| |:----- |:-----|----- | |error_code |int |错误代码 | |description|string|错误描述| |data|json|业务数据| ##### 备注 - 更多返回错误代码请看首页的错误代码描述
import * as React from "react"; import Box from "@mui/material/Box"; import { DataGrid } from "@mui/x-data-grid"; import axios from "axios"; import { useAuth } from "../../context/User"; import dayjs from "dayjs"; // import "./summary.css"; const columns = [ { field: "leaveid", headerName: "ID", width: 90 }, { field: "startdate", headerName: "Start date", width: 150, valueGetter: (params) => `${dayjs(params.row.startdate).format("DD/MM/YYYY")}` }, { field: "enddate", headerName: "End date", width: 150, valueGetter: (params) => `${dayjs(params.row.enddate).format("DD/MM/YYYY")}` }, { field: "reason", headerName: "Reason", width: 110 }, { field: "leavestatus", headerName: "Status", description: "This column has a value getter and is not sortable.", width: 160, valueGetter: (params) => `${params.row.leavestatus || "Pending"}` } ]; // const rows = [ // { id: 1, lastName: "Snow", firstName: "Jon", age: 35 }, // { id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 }, // { id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 }, // { id: 4, lastName: "Stark", firstName: "Arya", age: 16 }, // { id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null }, // { id: 6, lastName: "Melisandre", firstName: null, age: 150 }, // { id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 }, // { id: 8, lastName: "Frances", firstName: "Rossini", age: 36 }, // { id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 }, // { id: 10, lastName: "Roxie", firstName: "Harvey", age: 65 }, // { id: 11, lastName: "Roxie", firstName: "Harvey", age: 65 }, // { id: 12, lastName: "Roxie", firstName: "Harvey", age: 65 }, // { id: 13, lastName: "Roxie", firstName: "Harvey", age: 65 }, // { id: 14, lastName: "Roxie", firstName: "Harvey", age: 65 }, // { id: 15, lastName: "Roxie", firstName: "Harvey", age: 65 }, // { id: 16, lastName: "Roxie", firstName: "Harvey", age: 65 } // ]; export default function LeaveStatus() { const [rows, setRows] = React.useState([]); const { user } = useAuth(); React.useEffect(() => { axios .get(`http://localhost:4000/employee/leave/${user.user.employeeid}`) .then((res) => { console.log("first", res); setRows(res.data); }); }, []); return ( <section className="summary"> <div className="summary-box"> <h1 style={{ height: "40px", display: "flex", alignItems: "center", padding: "10px", color: "rgba(0, 0, 0, 0.8)" }} > Attendance history </h1> <Box sx={{ height: 400, width: "100%", background: "white" }}> <DataGrid getRowId={(row) => row.leaveid} rows={rows} columns={columns} pageSize={5} rowsPerPageOptions={[5]} /> </Box> </div> </section> ); }
#define _CRT_SECURE_NO_WARNINGS #include <cstring> #include "fridge.h" namespace seneca { Fridge::Fridge() { m_capacity = 0; m_model = nullptr; m_food = nullptr; m_cntFoods = 0; } Fridge::Fridge(const char* model, int capacity) { *this = Fridge(); setModel(model, capacity); } Fridge::Fridge(const Food* foods, int cntFoods, const char* model, int capacity) { *this = Fridge(); setModel(model, capacity); if (m_model != NULL) { for (int i = 0; i < cntFoods; i++) { addFood(foods[i]); } } } void Fridge::setModel(const char* model, int capacity) { if (model[0] != '\0' && capacity >= 10) { delete[] m_model; m_model = nullptr; int numChar = 0; while (model[numChar] != '\0') { numChar++; } m_model = new char[numChar + 1]; std::strcpy(m_model, model); m_capacity = capacity; } } bool Fridge::addFood(const Food& aFood) { if ((getContentWeight() + aFood.m_weight) <= m_capacity) { Food* tempFood = new Food[m_cntFoods + 1]; if (m_food != nullptr) // if the fridge already have food in it { for (int i = 0; i < m_cntFoods; i++) { tempFood[i] = m_food[i]; } } tempFood[m_cntFoods] = aFood; delete[] m_food; m_food = tempFood; m_cntFoods++; return true; } else { return false; } } int Fridge::getContentWeight() const { int totalWeight = 0; for (int i = 0; i < m_cntFoods; i++) { totalWeight += m_food[i].m_weight; } return totalWeight; } bool Fridge::isFull() const { if (getContentWeight() >= (0.9 * (double) m_capacity)) { return true; } else { return false; } } bool Fridge::hasFood(const char* theFood) const { bool hasFood = false; if (theFood == NULL && m_cntFoods > 0) { hasFood = true; } else { int i = m_cntFoods - 1; while (i > -1) { const char* existingFood = m_food[i].m_name; hasFood = (strcmp(existingFood, theFood) == 0); // check if specified food is already in fridge if (hasFood) { break; } i--; } } return hasFood; } void Fridge::display(std::ostream& out) const { if (m_model == NULL) { out << "The fridge object is in an empty state.\n"; } else { //out.fill(' '); out.width(19); out << "Fridge model: " << m_model << std::endl; out.width(19); out << "Fridge capacity: " << m_capacity << "kg" << std::endl; out.width(19); out << "Fill percentage: " << (getContentWeight() / (double) m_capacity) * 100 << "% full" << std::endl; out << "The list of foods:" << std::endl; for (int i = 0; i < m_cntFoods; i++) { out.width(4); //width will only apply to the statement/line below out << "- "; out << m_food[i].m_name << " (" << m_food[i].m_weight << "kg)"; out << std::endl; } } } Fridge::~Fridge() { delete[] m_model; m_model = nullptr; delete[] m_food; m_food = nullptr; } }
\section{Neural estimation of mutual information} \label{sec.mine} In this section, we recall the neural estimation of mutual information following \cite{BBROBCH18mut}. Let $\spaceX \subset \Rd$ and $\spaceY \subset \R^{e}$ represent sample spaces. Let $X$ and $Y$ be random variables taking values in $\spaceX$ and $\spaceY$ respectively. Let $\Prob_{XY}$ denote the joint distribution of $X$ and $Y$; and let $\Prob_{X} \otimes \Prob_{Y}$ denote the product of the marginal laws of $X$ and $Y$. The mutual information $I(X; Y)$ of $X$ and $Y$ is defined as the Kullback-Leibler divergence between $\Prob_{XY}$ and $\Prob_{X} \otimes \Prob_{Y}$. Using the Donsker-Varadhan representation of the Kullback-Leibler divergence (see \cite{DV83asy}), we can write \begin{equation} \label{eq.dvrepresentationofmutualinfo} I(X; Y) = \sup_{f} \quad \Expectation_{\Prob_{XY}} \left[ f(X, Y) \right] - \log \left( \Expectation_{\Prob_{X} \otimes \Prob_{Y}} \left[ \exp(f(X, Y)) \right] \right), \end{equation} where $\Expectation_{\Prob_{XY}}$ denotes expectation with respect to $\Prob_{XY}$, $\Expectation_{\Prob_{X} \otimes \Prob_{Y}}$ denotes expectation with respect to $\Prob_{X} \otimes \Prob_{Y}$, and the supremum is taken over all measurable functions $f: \spaceX \times \spaceY \rightarrow \R$ such that the two expectations are finite. Given samples \begin{equation} \label{eq.jointsamples} (x_1, y_1), \dots, (x_n, y_n), \end{equation} from the joint distribution of $X$ and $Y$, we can use the representation in equation \eqref{eq.dvrepresentationofmutualinfo} to estimate the mutual information of the two random variables. Indeed, we can represent the functions $f$ in equation \eqref{eq.dvrepresentationofmutualinfo} via a neural network $f_\theta$ parametrised by $\theta \in \Theta$, and then run gradient ascend in the parameter space $\Theta$ to maximise the emprirical objective functional of equation \eqref{eq.dvrepresentationofmutualinfo}, where the first expectation is replaced by \begin{equation*} \frac{1}{n}\sum_{i=1}^{n} f(x_i, y_i), \end{equation*} and the second expectation is replaced by \begin{equation*} \frac{1}{n}\sum_{i=1}^{n} \exp\left( f(x_i, y_{\sigma(i)}) \right), \end{equation*} where $\sigma$ is a permutation used to shuffle the $Y$-samples and hence turn the samples of equation \eqref{eq.jointsamples} into samples from $\Prob_{X} \otimes \Prob_{Y}$. The described approach to estimate the mutual information $I(X; Y)$ is at the core of MINE, and we will rely on this method to construct a feature selection filter.
// _foundation /*MAIN STYLES*/ //mix-ins @mixin flexandcenter { display: flex; justify-content: center; } body { background-image: radial-gradient(#fff, #c2c2c2); font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; display: flex; flex-direction: column; // min-height: 100vh; // margin: 0; } header { font-weight: bold; display: flex; flex-direction: column; align-items: center; h1 { @include flexandcenter(); width: 15%; font-size: 28px; margin: 20px 0 0 0; padding: 40px 0; color: #DFDFDF; border-radius: 35% 80% 35% 80%; text-shadow: 0px 0px 1px #181818; box-shadow: 0px 0px 20px #181818; background-image: linear-gradient(to bottom right, red, green, blue); } nav { width: 100%; ul { display: flex; justify-content: space-around; padding: 20px; li { font-size: 22px; a { text-decoration: none; } a:hover { text-decoration: underline; } } } } } // main { // flex: 1; // } footer { // flex-shrink: 0; display: flex; align-items: center; margin: 2%; padding: 20px 60px; background-color: #181818; height: 80px; #socials_list { width: 75%; @include flexandcenter(); justify-content: flex-start; // background-color: red; } #others_list { width: 50%; @include flexandcenter(); // background-color: purple; } nav { ul { display: flex; li { margin: 0 10px 0 10px; a { text-decoration: none; box-shadow: 0px 1px 10px #ffffff; border-radius: 20px; padding: 10px; color: purple; transition: 1s; } } a:hover { box-shadow: none; background-color: #DFDFDF; } } } }
#ifndef VERTEX_ARRAY_H #define VERTEX_ARRAY_H #include <glad/glad.h> #include <glfw/glfw3.h> #include "VertexBuffer.hpp" namespace engine { /** * @class VertexArray * @brief OpenGL Vertex Array Object. */ class VertexArray { private: /// ID of the Vertex Array Object. GLuint id { 0 }; public: /** * @brief Constructor for VertexArray. * Generates the VAO. */ VertexArray(); /** * @brief Destructor for VertexArray. * Deletes the VAO. */ ~VertexArray(); /** * @brief Sets the attribute pointer for the vertex array. * @param layout The layout location of the attribute. * @param numOfValues The number of values in the attribute. * @param pointerVal The offset of the first component of the attribute. */ void setAttribPointer(GLuint layout, GLuint numOfValues, GLuint pointerVal); /** * @brief Binds the VAO. */ void bind(); /** * @brief Unbinds the VAO. */ void unbind(); /** * @brief Draws the vertices in the VAO. * @param numOfVertices The number of vertices to draw. * @param primitive The type of primitive to draw. Defaults to GL_TRIANGLES. */ void drawVertices(GLuint numOfVertices, GLenum primitive = GL_TRIANGLES); /** * @brief Draws the elements in the VAO. * @param numOfIndices The number of indices to draw. * @param primitive The type of primitive to draw. Defaults to GL_TRIANGLES. */ void drawIndices(GLuint numOfIndices, GLenum primitive = GL_TRIANGLES); }; } #endif
import { createSlice } from '@reduxjs/toolkit' import blogService from '../services/blogs' const blogSlice = createSlice({ name: 'blogs', initialState: [], reducers: { createBlog(state, action) { //receives blog object as payload state.concat(action.payload) }, updateBlog(state, action) { const updatedBlog = action.payload state.map((blog) => blog.id !== updatedBlog.id ? blog : updatedBlog) }, deleteBlog(state, action) { const toRemoveId = action.payload state.filter((blog) => blog.id !== toRemoveId) }, getAllBlogs(state, action) { return action.payload }, makeNewComment(state, action) { //receibes a blog as a payload const blogWithComment = action.payload state.map((blog) => blog.id !== blogWithComment.id ? blog : blogWithComment) } } }) export const { createBlog, updateBlog, deleteBlog, getAllBlogs, makeNewComment } = blogSlice.actions export const fetchBlogs = () => { return async dispatch => { const blogs = await blogService.getAll() dispatch(getAllBlogs(blogs)) } } export const createNewBlog = content => { return async dispatch => { const newBlog = await blogService.create(content) dispatch(createBlog(newBlog)) const allBlogs = await blogService.getAll() dispatch(getAllBlogs(allBlogs)) } } export const updateBlogLikes = (id, blogObject) => { return async dispatch => { const updatedBlog = await blogService.update(id, blogObject) dispatch(updateBlog(updatedBlog)) const allBlogs = await blogService.getAll() dispatch(getAllBlogs(allBlogs)) } } export const removeBlog = (id) => { return async dispatch => { await blogService.remove(id) dispatch(deleteBlog(id)) const allBlogs = await blogService.getAll() dispatch(getAllBlogs(allBlogs)) } } export const createComment = (comment, id) => { return async dispatch => { const createdComment = await blogService.createComment(comment, id) dispatch(makeNewComment(createdComment)) const allBlogs = await blogService.getAll() dispatch(getAllBlogs(allBlogs)) } } export default blogSlice.reducer
import { useRouter } from 'next/router' import { ApiService } from '@/services/ApiService' import { CookieService } from '@/utils/CookieService' import { createContext, ReactNode, useCallback, useState } from 'react' interface IUserLoginDTO { username: string password: string } interface IUserGetResponse { id: number username: string nome: string email: string } interface IUserCreateDTO { username: string email: string password: string } interface UserContextData { user: IUserGetResponse | null error: string | null isLogged: boolean isLoading: boolean login(userLogin: IUserLoginDTO): Promise<void> create(userData: IUserCreateDTO): Promise<void> logout(): Promise<void> checkUserIsLogged(): Promise<boolean> } export const UserContext = createContext({} as UserContextData) interface UserContextProviderProps { children: ReactNode } export function UserProvider({ children }: UserContextProviderProps) { const [user, setUser] = useState<IUserGetResponse | null>(null) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState<string | null>(null) const router = useRouter() const isLogged = !!user const logout = useCallback(async (): Promise<void> => { try { destroyCookies() setUser(null) setError(null) await router.push('/login') } catch (error) { console.log(error) } }, [router]) const checkUserIsLogged = useCallback(async (): Promise<boolean> => { try { if (!hasCookies()) { resetStates() return false } const responseValidateOrError = await ApiService.token.validate() if (responseValidateOrError.isLeft()) { throw responseValidateOrError.value } const user = CookieService.get({ name: 'USER', }) setUser(JSON.parse(user)) return true } catch (error) { setUser(null) console.log(error) return false } finally { setIsLoading(false) } }, []) const hasCookies = (): boolean => { return ( CookieService.has({ name: 'TOKEN' }) && CookieService.has({ name: 'USER' }) ) } const resetStates = () => { setIsLoading(true) setUser(null) setError(null) } const login = useCallback( async ({ username, password }: IUserLoginDTO): Promise<void> => { try { setError(null) setIsLoading(true) const token = await getToken({ username, password }) setTokenCookie(token) const user = await getUser() setUserCookie(user) await router.push('/conta') setUser(user) } catch (error) { if (error instanceof Error) setError('Usuário inválido') setUser(null) console.log(error) } finally { setIsLoading(false) } }, [router], ) const setUserCookie = (user: IUserGetResponse) => { CookieService.set({ name: 'USER', value: JSON.stringify(user), }) } const setTokenCookie = (token: string) => { CookieService.set({ name: 'TOKEN', value: token, }) } const getToken = async ({ username, password, }: IUserLoginDTO): Promise<string> => { const { data: token } = await ApiService.token.get({ username, password, }) return token } const getUser = async (): Promise<IUserGetResponse> => { const { data: user } = await ApiService.user.get() return user } const create = useCallback( async (userData: IUserCreateDTO) => { try { await ApiService.user.post(userData) await login({ username: userData.username, password: userData.password, }) } catch { setError('Erro ao criar usuário') } }, [login], ) const destroyCookies = (): void => { CookieService.destroy({ name: 'TOKEN' }) CookieService.destroy({ name: 'USER' }) } return ( <UserContext.Provider value={{ user, login, create, logout, checkUserIsLogged, error, isLoading, isLogged, }} > {children} </UserContext.Provider> ) }
import { BasicApiResponse } from '@src/api/types'; import { IProfileData, ProfileModuleState } from '@src/store/profile/types'; import StoreModule from '../module'; /** * Детальная информация о пользователе */ class ProfileState extends StoreModule<ProfileModuleState> { initState(): ProfileModuleState { return { data: {} as IProfileData, waiting: false, // признак ожидания загрузки }; } /** * Загрузка профиля * @return {Promise<void>} */ async load() { // Сброс текущего профиля и установка признака ожидания загрузки this.setState({ data: {} as IProfileData, waiting: true, }); const { data } = await this.services.api.request<BasicApiResponse<IProfileData>>({ url: `/api/v1/users/self` }); // Профиль загружен успешно this.setState({ data: data.result, waiting: false, }, 'Загружен профиль из АПИ'); } } export default ProfileState;
<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"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap" rel="stylesheet"> <title>Document</title> </head> <body> <style> :root { --font: 'Space Mono', monospace; --space-half: 0.5rem; --space-1: 1rem; --space-1-5: 1.5rem; --space-2: 2rem; --border-radius: 0.4rem; --color-white: #fff; --font-size-larger: 1.8rem; } * { font-family: var(--font); color: var(--color-black); text-transform: capitalize; } a { display: block; } html, body { padding: var(--space-2); } .grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 2rem; margin-bottom: var(--space-2); } @media (max-width: 1000px) { .grid { grid-template-columns: 1fr 1fr; } } @media (max-width: 500px) { .grid { grid-template-columns: 1fr; } } .card { box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.25); padding: var(--space-half); border-radius: var(--border-radius); } .card .frame { padding-top: 100%; position: relative; border-radius: var(--border-radius); overflow: hidden; } .card .frame>* { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .card .frame.medium>* { position: absolute; top: -100%; left: -100%; width: 300%; height: 300%; transform: scale(0.3333333); } .card .frame.big>* { position: absolute; top: -150%; left: -150%; width: 400%; height: 400%; transform: scale(0.25); } .card .info .link { cursor: pointer; border-radius: var(--border-radius); display: inline-block; padding: var(--space-half) var(--space-1); } .card .info .title { text-align: center; border-radius: var(--border-radius); padding: var(--space-1) 0; display: flex; justify-content: center; } /*------------------------------------------------------- | utility -------------------------------------------------------*/ .m-t-1 { margin-top: 1rem; } .m-t-2 { margin-top: 2rem; } .m-t-3 { margin-top: 3rem; } .p-05 { padding: 0.5rem; } .p-1 { padding: 1rem; } .p-2 { padding: 2rem; } .font-larger{ font-size: var(--font-size-larger); } .no-text-decoration{ text-decoration: none; } .card .info .link1:hover { background: rgba(31, 31, 31, 0.5); } .card .info .link2:hover { background: #afc8c9; } </style> <div class="grid"> <template> <div class="card"> <div class="frame "> <iframe src="./week_9/game_cards/" frameborder="0"></iframe> </div> <div class="info p-05"> <div class="p title m-t-1 font-larger">project title</div> <div class="p m-t-1"> <a class="link1 link m-t-1 no-text-decoration" href="#" target="_blank">Open Project</a> <a class="link2 link github m-t-1 no-text-decoration" href="#" target="_blank">View code</a> </div> </div> </div> </template> </div> <div class="count"></div> <div class="projects"></div> <script> // select any element // var element = document.querySelector('.grid') // console.log(element) // make a template var template = document.querySelector('template') // console.log(template) // for(var i = 0; i < 50 ; i += 1){ // // console.log(i) // } async function callApi() { var rawData = await fetch('./projects.json') // console.log(rawData) var data = await rawData.json() // console.log(data) // sort projects backwards data.projects.reverse() var i = 0 // var oneProject = [data.projects[0]] for (var item of data.projects) { console.log("test", item.frame) var clone = template.content.cloneNode(true) var frame = item.frame // console.log(this.frame) //change the frame size var frameSize = clone.querySelector('.frame') console.log(frameSize) frameSize.classList.add(item.frame) // change iFrame url var iFrame = clone.querySelector('iFrame') watchForContentWindowDisableConsoleLog(iFrame) // set the project title var title = clone.querySelector('.title') title.innerHTML = item.name // set the project url var url = clone.querySelector('a') // console.log(url) url.href = item.link // set the github url var github = clone.querySelector('.github') // console.log(github) github.href = `https://github.com/zackmann360/javascript_practice/tree/main/${item.link}` iFrame.setAttribute('src', item.link) var container = document.querySelector('.grid') container.append(clone) i += 1 } } callApi() // function for turning console log off. function watchForContentWindowDisableConsoleLog(iFrame) { var interval = setInterval(function (arg1) { if (arg1.contentWindow) { arg1.contentWindow.console.log = function () { } clearInterval(interval) } }, 1, iFrame) } // Call api practice async function callApiPractice() { var rawData = await fetch('./projects.json') var data = await rawData.json() // console.log(data) // loop over projects for (var item of data.projects) { // console.log(item.name) // create a link for each var links = document.createElement('a') links.innerHTML = item.name links.href = item.link // append them to the container document.querySelector('.projects').append(links) } // display the count // console.log(data.projects.length) var count = data.projects.length var countContainer = document.querySelector('.count') countContainer.innerHTML = "Count: " + count } callApiPractice() </script> </body> </html>
--- alias: Successive Over Relaxation (SOR) --- This is the preq: [Jacobi, Gauss Sediel Iterations](../AMATH%20581%20Scientific%20Computing/Jacobi,%20Gauss%20Sediel%20Iterations.md). Here is more advanced coverage of the same topic. --- ### **Intro** You must read the document listed above to proceed. Stationary iterative method refers to methods that just iterate with a matrix that approximately the inverse of the matrix $A$, in hope to solving the system $Ax - b$ by minimizing the residual. Here is a list of the common methods: * Jacobi Iteration: in the prereq. * Gauss Seidel: in the prereq. * Successive Over Relaxation: About to come next. Consider the factorization of matrix $A$ into 3 parts, the diagonal, strict lower diagonal, and the strict upper diagonal parts of the matrix: $$ A = L + D + U $$ Then the system $Ax = b$ can be written as: $$ \begin{aligned} (D + wL)x &= wb - (wU + (w - 1)D)x \\ Dx + wLx &= wb - wUx + (w - 1)Dx \\ wDx + wLx + wUx &= wb \\ wAx &= wb \end{aligned} $$ Here, the choice of $w$ is in between $(1, 2]$. That is a reasonable range to parameterize the above equation. Finally the above equation can be put into an iterative formula as: $$ \begin{aligned} x_{n + 1} &= \underbrace{w(D + wL)^{-1}b}_{= c} \underbrace{- (D + wL)^{-1}(wU + (w - 1)D)}_{M} x \end{aligned} $$ Observe that, when $w = 1$, we have: $$ \begin{aligned} (D + L)x_{n + 1} &= b - Ux_{n} \end{aligned} $$ This is directly the *Gauss Sediel Method*. However, no choice of parameter on $w$ can recover the Jacobi Iterations. Take note that, in the case of sparse matrix, it might be easier to back solve than using the inverse. **Note:** Different conventions of naming these quantities exists sometimes $w$ above is actually the $w^{-1}$ in some literature. **References**: Greenbaum's 2021 class, and her Iterative Method book. --- ### **Intuitive Understanding of the Matter** To gain a better understanding, we have to simplifies the system into another form. $$ \begin{aligned} (D + wL)x_{n + 1} &= wb - (wU + (w - 1)D)x_k \\ (w^{-1}D + L)x_{n + 1} &= b - (U + (1 - w^{-1})D)x_k \\ &= b - Ux_k - (1 - w^{-1})Dx_k \\ &= b - Ux_k - Dx_k + w^{-1}Dx_k \\ &= b - Ux_k - Dx_k + w^{-1}Dx_k - Lx_k + Lx_k \\ &= b - (U + D + L)x_k + (w^{-1}D + L)x_k \\ &= b - Ax_k + (w^{-1}D + L)x_k \end{aligned} $$ If we define $M = (w^{-1}D + L)$, then hope is that the matrix $M\approx A$ and $M^{-1}$ is very easy to compute, so that we have the following expression: $$ \begin{aligned} Mx_{n + 1} &= b - Ax_k + Mx_k \\ x_{n + 1} &= M^{-1}r_k + x_k \end{aligned} $$ Ideally speaking, $M^{-1}r_k$ approximate the quantity $A^{-1}b - x_k$, or the error of the current guess $x_k$. If by the choice of $M$ it achieved it, (Which it will for SOR), then the iterations formula converges. In fact, when it converges, we have: $$ \begin{aligned} x_{n + 1} &= M^{-1}r_k + x_k \\ A^{-1}b - x_{n + 1} &= A^{-1}b - M^{-1}r_k - x_k \\ e_{k + 1} &= e_k - M^{-1}(b - Ax_k) \text{ where : } e_k = A^{-1}b - x_k \\ e_{k + 1} &= e_k - M^{-1}A(A^{-1}b - x_k) \\ e_{k + 1} &= e_k - M^{-1}Ae_k \\ e_{k + 1} &= (I - M^{-1}A)e_k \\ e_{k + 1} &= (I - M^{-1}A)^{k + 1}e_0 \end{aligned} $$ The spectral radius of the matrix $I - M^{-1}A$ will determine the convergence of the error. **Staionary Iterative Convergence Theorem** > For any choice of $M$, the iterative scheme $x_{k + 1} = M^{-1}r_k + x_k$ convergence for all initial guess if and only if $\Vert (I - M^{-1}A)^k\Vert$ convergences to zero. The theorem is an IFF type of statement, which one direction is easy, but the other direction is not. If the norm converges, then the erro does, but the other way around is not so obvious. **Field of values** If the field of value of the matrix $I - M^{-1}A$ is strictly less than one, then it STILL converges, but might not be monotonically under certain norm measure. --- ### **Convergence Rate Statement** Before one can make any claim, we need to put the iterations proceudure into the form of $x_{k + 1} = Gx_{k} + c$. Then, we can make the claim that, if the [Spectral Radius](../AMATH%20584%20Numerical%20Linear%20Algebra/Matrix%20Theory/Spectral%20Radius.md) of the matrix $G$ is less than unity, then the iterative scheme will inevitability converge for all initial guess. In fact the converse is also true. The statement that we wish to prove would be: **Convergence and Spectral Radius** > If the iterations matrix $G$ for the stationary scheme has a spectral radius that is less than unity iff and only if the stationary scheme converges for all initial guesses. **Optimal Relaxation Factor for SOR Method** > The spectrum of the iterative matrix is in the scale of $1 - \mathcal{O}(h)$ for the optimal sor relaxation factor, given as $w_{opt} = 1/\sqrt{1 - \rho(G_J)}$ where $G_J$ is the Jacobi Iteration Matrix.
import React, { useState, useEffect } from "react"; import axios from "axios"; import "./App.css"; import image from './img/linear_reg_img.png'; function App() { const [squareFeet, setSquareFeet] = useState(""); const [bedrooms, setBedrooms] = useState(""); const [bathrooms, setBathrooms] = useState(""); const [year, setyear] = useState(""); const [prediction, setPrediction] = useState(null); const [dataSample, setDataSample] = useState([]); const [showSampleData, setShowSampleData] = useState(false); const [modelAccuracy, setModelAccuracy] = useState(null); useEffect(() => { const fetchDataSample = async () => { try { const response = await axios.get("http://localhost:8000/api/data_sample/"); setDataSample(response.data.data_sample); } catch (error) { console.error("There was an error fetching the data sample!", error); } }; fetchDataSample(); const fetchModelAccuracy = async () => { try { const response = await axios.get("http://localhost:8000/api/model_accuracy/"); setModelAccuracy(response.data.mean_squared_error); } catch (error) { console.error("There was an error fetching the model accuracy!", error); } }; fetchModelAccuracy(); }, []); const handleSubmit = async (e) => { e.preventDefault(); const inputData = `${squareFeet},${bedrooms},${bathrooms},${year}`; try { const response = await axios.post( "http://localhost:8000/api/predict/", `input_data=${inputData}`, { headers: { "Content-Type": "application/x-www-form-urlencoded" } } ); setPrediction(response.data.prediction); } catch (error) { console.error("There was an error making the request!", error); } }; const toggleSampleData = () => { setShowSampleData(!showSampleData); }; return ( <div className="App"> <header className="App-header"> <h1>Housing Price Predictor</h1> <section className="section-content"> <h2>About Linear Regression</h2> <img src={image} alt="Linear Regression" /> <p> Linear regression is an algorithm that provides a linear relationship between an independent variable and a dependent variable to predict the outcome of future events. It is a statistical method used in data science and machine learning for predictive analysis. </p> <p> The independent variable is also the predictor or explanatory variable that remains unchanged due to the change in other variables. However, the dependent variable changes with fluctuations in the independent variable. The regression model predicts the value of the dependent variable, which is the response or outcome variable being analyzed or studied. </p> <h3>Linear Regression Formula</h3> <p> The equation of a simple linear regression model is: </p> <p> y = β<sub>0</sub> + β<sub>1</sub>x<sub>1</sub> + β<sub>2</sub>x<sub>2</sub> + ... + β<sub>n</sub>x<sub>n</sub> </p> <p> Here, y is the predicted value, x<sub>1</sub>, x<sub>2</sub>, ..., x<sub>n</sub> are the feature values, β<sub>0</sub> is the intercept, and β<sub>1</sub>, β<sub>2</sub>, ..., β<sub>n</sub> are the coefficients for the features. </p> <h3>Applications of Linear Regression</h3> <p> Linear regression is widely used in various fields including finance, economics, and the social sciences. It is often used for: </p> <ul> <li>Predicting stock prices</li> <li>Estimating real estate values</li> <li>Forecasting sales</li> <li>Modeling the relationship between variables in scientific research</li> </ul> </section> <section className="section-content"> <h2>Data Sample</h2> <button onClick={toggleSampleData}> {showSampleData ? "Hide Sample Data" : "See Sample Data"} </button> {showSampleData && ( <table> <thead> <tr> <th>Square Feet</th> <th>Bedrooms</th> <th>Bathrooms</th> <th>YearBuilt</th> <th>Price</th> </tr> </thead> <tbody> {dataSample.length > 0 ? ( dataSample.map((row, index) => ( <tr key={index}> <td>{row.SquareFeet}</td> <td>{row.Bedrooms}</td> <td>{row.Bathrooms}</td> <td>{row.YearBuilt}</td> <td>{row.Price}</td> </tr> )) ) : ( <tr> <td colSpan="5">No data available</td> </tr> )} </tbody> </table> )} </section> <section className="section-content"> <h2>Predict Housing Price</h2> <form onSubmit={handleSubmit}> <div> <label>Square Feet:</label> <input type="number" value={squareFeet} onChange={(e) => setSquareFeet(e.target.value)} required /> </div> <div> <label>Bedrooms:</label> <input type="number" value={bedrooms} onChange={(e) => setBedrooms(e.target.value)} required /> </div> <div> <label>Bathrooms:</label> <input type="number" value={bathrooms} onChange={(e) => setBathrooms(e.target.value)} required /> </div> <div> <label>Year Built:</label> <input type="number" value={year} onChange={(e) => setyear(e.target.value)} required /> </div> <button type="submit">Predict</button> </form> </section> {prediction !== null && ( <section className="section-content"> <h2>Prediction Result</h2> <h3>The predicted housing price is: {prediction}</h3> </section> )} {modelAccuracy !== null && ( <section className="section-content"> <h2>Model Accuracy</h2> <h3>The mean squared error of the model is: {modelAccuracy}</h3> </section> )} </header> </div> ); } export default App;
// // UITextFieldViewRepresentable.swift // OTUS_HW01 // // Created by Александр Касьянов on 02.09.2022. // import UIKit import SwiftUI struct UITextFieldViewRepresentable: UIViewRepresentable { @Binding var text: String func makeUIView(context: Context) -> some UIView { let textField = getTextField() textField.delegate = context.coordinator return textField } func updateUIView(_ uiView: UIViewType, context: Context) { } func makeCoordinator() -> Coordinator { return Coordinator(text: $text) } private func getTextField() -> UITextField { let textField = UITextField(frame: .zero) textField.placeholder = "You may type something here" return textField } class Coordinator: NSObject, UITextFieldDelegate { @Binding var text: String init(text: Binding<String>) { self._text = text } func textFieldDidChangeSelection(_ textField: UITextField) { text = textField.text ?? "" } } }
import React, {useState, useEffect} from 'react' import {Link ,useNavigate,useParams} from 'react-router-dom'; import { Row, Col, Button, Card, ListGroup, Image, Form} from 'react-bootstrap'; import Rating from '../components/Rating'; import {useDispatch, useSelector} from 'react-redux' import { createProductReview, listProductDetails } from '../actions/productActions'; import Loader from '../components/Loader' import Message from '../components/Message' import { PRODUCT_CREATE_REVIEW_RESET } from '../constants/productConstants'; const ProductScreen = () => { const [qty, setQty] = useState(1) const [rating, setRating] = useState(0) const [comment, setComment] = useState('') const history = useNavigate(); let params = useParams(); const dispatch = useDispatch() const productDetails = useSelector((state) => state.productDetails) const { loading, error, product } = productDetails const userLogin = useSelector((state) => state.userLogin) const { userInfo } = userLogin const productReviewCreate = useSelector((state) => state.productReviewCreate) const { success: successProductReview, error: errorProductReview } = productReviewCreate useEffect(() => { if(successProductReview){ alert('Review Submitted') setRating(0) setComment('') dispatch({ type: PRODUCT_CREATE_REVIEW_RESET}) } dispatch(listProductDetails(params.id)) },[dispatch, params.id, successProductReview]) const addToCartHandler = () => { history(`/cart/${params.id}?qty=${qty}`) } const submitHandler = (e) => { e.preventDefault() dispatch( createProductReview(params.id, { rating, comment }) ) } return ( <> <Link className='btn btn-light my-3' to='/'>Go Back</Link> {loading ? ( <Loader /> ) : error ? ( <Message variant='danger'>{error}</Message> ) : ( <Row> <Col md={6}> <Image src={product.image} alt={product.name} fluid /> </Col> <Col md={3}> <ListGroup variant='flush'> <ListGroup.Item> <h3>{product.name}</h3> </ListGroup.Item> <ListGroup.Item> <Rating value={product.rating} text={`${product.numReviews} reviews`} /> </ListGroup.Item> <ListGroup.Item> Price : ${product.price} </ListGroup.Item> <ListGroup.Item> Description : {product.description} </ListGroup.Item> </ListGroup> </Col> <Col md={3}> <Card> <ListGroup variant='flush'> <ListGroup.Item> <Row> <Col> Price: </Col> <Col> <strong>${product.price}</strong> </Col> </Row> </ListGroup.Item> <ListGroup.Item> <Row> <Col> Status: </Col> <Col> <strong>{product.countInStock > 0 ? 'In Stock' : 'Out of Stock'}</strong> </Col> </Row> </ListGroup.Item> {product.countInStock > 0 && ( <ListGroup.Item> <Row> <Col>Qty</Col> <Col> <Form.Control as='select' value={qty} onChange={(e) => setQty(e.target.value)} > {[...Array(product.countInStock).keys()].map( (x) => ( <option key={x + 1} value={x + 1}> {x + 1} </option> ) )} </Form.Control> </Col> </Row> </ListGroup.Item> )} <ListGroup.Item> <Button onClick={addToCartHandler} className='btn-block' disabled={product.countInStock === 0}>Add To Cart</Button> </ListGroup.Item> </ListGroup> </Card> </Col> </Row> ) } <Row> <Col md={6}><h3>Reviews</h3> {product.reviews.length === 0 && <Message>No Reviews</Message>} <ListGroup variant="flush"> {product.reviews.map((review) => ( <ListGroup.Item key={review.rating} > <strong>{review.name}</strong> <Rating value={review.rating} /> <p>{review.createdAt.substring(0,10)}</p> <p>{review.comment}</p> </ListGroup.Item> ))} <h4>Write a Customer Review</h4> {errorProductReview && ( <Message variant='danger'>{errorProductReview}</Message> )} {userInfo ? ( <Form onSubmit={submitHandler} > <Form.Group controlId='rating'> <Form.Label>Rating</Form.Label> <Form.Control as='select' value={rating} onChange={(e) => setRating(e.target.value)} > <option value="1">1- Poor</option> <option value="2">2- Fair</option> <option value="3">3- Average</option> <option value="4">4- Very Good</option> <option value="5">5- Excellent</option> </Form.Control> </Form.Group> <Form.Group controlId='comment'> <Form.Label>Comment</Form.Label> <Form.Control as='textarea' row='3' value={comment} onChange={(e) => setComment(e.target.value)} ></Form.Control> </Form.Group> <Button className="mt-3" type='submit' variant='primary'> Submit </Button> </Form> ) : ( <Message> Please <Link to='/login'>sign in</Link> to write a review{' '} </Message>) } </ListGroup> </Col> </Row> </> ) } export default ProductScreen
class VersionCode: def __init__(self, version_str: str): try: splits = version_str.split('.') if len(splits) != 3: raise RuntimeError('Not a valid version code') self._major = int(splits[0]) self._minor = int(splits[1]) self._patch = int(splits[2]) except Exception as e: raise RuntimeError('Not a valid version code') @property def major(self) -> int: return self._major @property def minor(self) -> int: return self._minor @property def patch(self) -> int: return self._patch def is_same_patch(self, other: "VersionCode") -> bool: if self.major != other.major: return False if self.minor != other.minor: return False return True def __eq__(self, other: "VersionCode") -> bool: if self.major != other.major: return False if self.minor != other.minor: return False if self.patch != other.patch: return False return True def __gt__(self, other: "VersionCode") -> bool: if self.major > other.minor: return True if self.minor > other.minor: return True if self.patch > other.patch: return True return False def __lt__(self, other: "VersionCode") -> bool: if self.major < other.minor: return True if self.minor < other.minor: return True if self.patch < other.patch: return True return False def __ge__(self, other): return self == other or self > other def __le__(self, other): return self == other or self < other def __hash__(self): return hash(str(self)) def __str__(self): return f"{self.major}.{self.minor}.{self.patch}"
import { defineManifest } from '@crxjs/vite-plugin'; import pkg from '../package.json'; export default defineManifest({ manifest_version: 3, name: "__MSG_appName__", default_locale: "en", description: "__MSG_appDescription__", version: pkg.version, content_scripts: [ { js: ["src/content-script/index.ts"], matches: ["<all_urls>"], run_at: "document_start", }, ], background: { service_worker: "src/background/index.ts", }, icons: { "16": "src/ui/assets/images/logo/chrome-16.png", "32": "src/ui/assets/images/logo/chrome-32.png", "48": "src/ui/assets/images/logo/chrome-48.png", "128": "src/ui/assets/images/logo/chrome-128.png", }, action: { default_popup: "index.html", default_icon: { "16": "src/ui/assets/images/logo/chrome-16.png", "32": "src/ui/assets/images/logo/chrome-32.png", "48": "src/ui/assets/images/logo/chrome-48.png", "128": "src/ui/assets/images/logo/chrome-128.png", }, default_title: "__MSG_appName__", }, permissions: ["storage", "unlimitedStorage", "activeTab"], short_name: "__MSG_appName__", devtools_page: "src/devtools/devtools.html", content_security_policy: { extension_pages: "script-src 'self' 'wasm-unsafe-eval' http://localhost; object-src 'self';", }, minimum_chrome_version: "88", });
// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer) // SPDX-License-Identifier: Apache-2.0 import { Checkbox, Radio, Tooltip, chakra } from "@open-pioneer/chakra-integration"; import { ChangeEvent, useId, useMemo } from "react"; export interface SelectComponentProps { mode?: "checkbox" | "radio"; toolTipLabel?: string; className?: string; "aria-label"?: string; isIndeterminate?: boolean; isChecked?: boolean; isDisabled?: boolean; onChange?: (event: ChangeEvent<HTMLInputElement>) => void; } export function SelectComponent({ mode = "checkbox", toolTipLabel, ...props }: SelectComponentProps) { const Component = mode === "checkbox" ? Checkbox : SelectRadio; const renderedComponent = useMemo(() => { return <Component {...props} />; }, [Component, props]); if (!toolTipLabel) { return renderedComponent; } return ( <Tooltip label={toolTipLabel} placement="right" closeOnClick={false}> <chakra.span /* wrap into span to fix tooltip around checkbox, see https://github.com/chakra-ui/chakra-ui/issues/6353 not using "shouldWrapChildren" because that also introduces a _focusable_ span (we only want the checkbox) */ > {renderedComponent} </chakra.span> </Tooltip> ); } function SelectRadio(props: Omit<SelectComponentProps, "mode">) { const id = useId(); const { isIndeterminate, ...rest } = props; void isIndeterminate; // ignored, not supported by radio button /** Name seems to be required for screen reader tabbing support. */ return <Radio name={id} {...rest} />; }
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter', pure: false // just needs to be used when the data change. The pure pipe works when input change, but the inpure // pipe change on every change detection / source data change. }) export class FilterPipe implements PipeTransform { transform(value: any, filterString: string, propName: string): any { // The pipe receives the value and needs to return a value of the same TYPE, modified or not. You can use the // arguments passed to construct the output logic. if (value.length === 0 || filterString === '') { return value; } const resultArray = []; for (const item of value) { if (item[propName] === filterString) { resultArray.push(item); } } return resultArray; } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://www.zkoss.org/jsp/zul" prefix="z" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <z:component name="mywindow" extends="window" class="org.zkoss.jspdemo.MyWindow" title="test" border="normal"/> <z:component name="username" inline="true" macroURI="/test/macro.zul" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Dynamic Component Test</title> </head> <body> <h1>In page Dynamic Component usage</h1> <p>You can define a zk component in a JSP page, for example:</p> <ol> <li>&lt;z:component name=&quot;mywindow&quot; extends=&quot;window&quot; class=&quot;org.zkoss.jspdemo.MyWindow&quot; title=&quot;test&quot; border=&quot;normal&quot;/&gt;</li> <li>&lt;z:component name=&quot;username&quot; inline=&quot;true&quot; macroURI=&quot;/test/macro.zul&quot; /&gt;</li> </ol> <p>Then, you can use it in your jsp page like this:<br/> &lt;z:ui tag=&quot;mywindow&quot; &gt;<br/> &lt;z:ui tag=&quot;username&quot; /&gt;<br/>&lt;/z:ui&gt;<br/> </p> <z:page id="includee"> <z:ui tag="mywindow" > <z:window id="main"> <z:button label="Add Item"> <z:attribute name="onClick"> new Label("Added at "+new Date()).setParent(main); new Separator().setParent(main); </z:attribute> <z:attribute name="onCreate"> new Label("Added at "+new Date()).setParent(main); new Separator().setParent(main); </z:attribute> </z:button> <z:ui tag="username" label="this is label!" text="this is text!"/> </z:window> </z:ui> </z:page> </body> </html>
document.addEventListener("DOMContentLoaded", function () { var IngredientTracker = []; const ingredientSelect = document.getElementById("ingredientSelect"); const trackMealForm = document.getElementById("trackMealForm"); const intakeRecordsContainer = document.querySelector(".intake-records"); function displayIngredientTrackerData() { intakeRecordsContainer.innerHTML = ""; // Replace ${userId} with the actual user ID const userId = localStorage.getItem("loggedInUserId"); fetch(`http://localhost:3000/api/mealIngredientTracker/${userId}`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { IngredientTracker = data; console.log('displayIngredientTracker data:', IngredientTracker); data.forEach(element => { element.nutrients = JSON.parse(element.Nutrients); addIntakeRecordToDOM(element, element.MealIngredientTrackerID) }) }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); } document.getElementById("registerIngredientTrackerIntakeButton").addEventListener("click", async function () { const mealName = ingredientSelect.options[ingredientSelect.selectedIndex].value; const mealWeight = document.getElementById("mealWeight").value; const mealDate = document.getElementById("mealDate").value; const mealTime = document.getElementById("mealTime").value; const drinkVolume = document.getElementById("drinkVolume").value; const drinkTime = document.getElementById("drinkTime").value; console.log({ mealDate }) // Antag at vi bruger den valgte opskrift til at beregne næringsindholdet direkte let selectedMealData = allIngredients.find(elm => elm.foodName == mealName); console.log(selectedMealData) if (!selectedMealData) { alert("Selected meal data not found!"); return; } let nutrientValues = await getNutrientValues(selectedMealData.foodID, mealWeight); selectedMealData.nutrientValues = nutrientValues; const nutrients = calculateNutrients(selectedMealData, mealWeight); // sætter timestamp for måltid const [hoursOfMeal, minutesOfMeal] = mealTime.split(':'); const currentMealDate = new Date(); currentMealDate.setHours(parseInt(hoursOfMeal, 10)); currentMealDate.setMinutes(parseInt(minutesOfMeal, 10)); // sætter timestamp for drink const [hoursOfDrink, minutesOfDrink] = drinkTime.split(':'); const currentDrinkDate = new Date(); currentDrinkDate.setHours(parseInt(hoursOfDrink, 10)); currentDrinkDate.setMinutes(parseInt(minutesOfDrink, 10)); const userId = localStorage.getItem("loggedInUserId"); const mealRecord = { ingredientsID: selectedMealData.foodID, mealName: mealName, weight: mealWeight, timeOfMeal: currentMealDate, nutrients: nutrients, drinkVolume: drinkVolume, drinkTime: currentDrinkDate, time: mealTime, date: mealDate, userID: userId }; const timestamp = new Date().toISOString().replace(/[-:.T]/g, ""); const trackedMealKey = `trackedMeal-${timestamp}`; localStorage.setItem(trackedMealKey, JSON.stringify(mealRecord)); // Gem tracked meals i et array let trackedMeals = JSON.parse(localStorage.getItem('trackedMeals')) if (trackedMeals) { trackedMeals.push(mealRecord); localStorage.setItem('trackedMeals', JSON.stringify(trackedMeals)); } else { let trackedMeals = [mealRecord] localStorage.setItem('trackedMeals', JSON.stringify(trackedMeals)); } addMealTracker(mealRecord, "POST") }); // Asynkron funktion til at hente næringsværdier for en bestemt ingrediens async function getNutrientValues(foodID, amount) { // Henter individuelle næringsværdier let carbsValue = await fetchNutritionValue(foodID, "1220"); let proteinValue = await fetchNutritionValue(foodID, "1110"); let fatValue = await fetchNutritionValue(foodID, "1310"); let kcalValue = await fetchNutritionValue(foodID, "1030"); let waterValue = await fetchNutritionValue(foodID, "1620"); // Returnerer næringsværdier justeret for mængde return { kulhydrater: (carbsValue / 100) * amount, protein: (proteinValue / 100) * amount, fedt: (fatValue / 100) * amount, kalorier: (kcalValue / 100) * amount, vand: (waterValue / 100) * amount }; }; // Asynkron funktion til at hente næringsværdier baseret på fødevareID og sortKey async function fetchNutritionValue(foodID, sortKey) { try { // Laver et API-kald for at hente næringsværdier const response = await fetch(`https://nutrimonapi.azurewebsites.net/api/FoodCompSpecs/ByItem/${foodID}/BySortKey/${sortKey}`, { method: 'GET', headers: { 'X-API-Key': '168935' } }); // Tjekker for fejl i svaret if (!response.ok) { throw new Error(`API-opkald fejlede: ${response.status}`); } // Parser svaret til JSON const data = await response.json(); // Tjekker om data indeholder de ønskede værdier if (data.length > 0 && data[0].resVal) { return parseFloat(data[0].resVal); // Konverterer resultatet til et flydende tal } else { throw new Error('Næringsdata ikke fundet i svaret'); } } catch (error) { console.error("Fejl ved hentning af næringsdata:", error); return 0; // Returnerer en standardværdi, justér efter behov } }; // Funktion til at hente og vise ingredienser function fetchAndDisplayIngredients() { fetch("https://nutrimonapi.azurewebsites.net/api/FoodItems", { headers: { "X-API-Key": "168935" } }) .then(response => response.json()) .then(data => { allIngredients = data; allIngredients.forEach(el => { const option = new Option(el.foodName, el.foodName); ingredientSelect.appendChild(option); }) console.log(allIngredients.slice(0, 5)); }) .catch(error => console.error("Error fetching data:", error)); }; async function addMealTracker(mealtrackerObj, type) { let url = `http://localhost:3000/api/mealIngredientTracker`; if (mealtrackerObj.MealIngredientTrackerID) { url += `/${mealtrackerObj.MealIngredientTrackerID}` } fetch(url, { method: type, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(mealtrackerObj) }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { console.log("back", data) trackMealForm.reset(); displayIngredientTrackerData(); }) .catch(error => { console.error('There was a problem with adding meal:', error); }); } // Udfører initial visning af ingredienser fetchAndDisplayIngredients(); displayIngredientTrackerData(); function calculateNutrients(mealData, weight) { console.log({ mealData }) let totalNutrients = { kcal: 0, protein: 0, fat: 0, fibre: 0 }; totalNutrients.kcal += (mealData?.nutrientValues.kalorier || 0) * weight / 100; totalNutrients.protein += (mealData?.nutrientValues.protein || 0) * weight / 100; totalNutrients.fat += (mealData?.nutrientValues.fedt || 0) * weight / 100; totalNutrients.fibre += (mealData?.nutrientValues.fibre || 0) * weight / 100; return totalNutrients; } function _calculateNutrients(mealData, weight) { console.log({ mealData }) let totalNutrients = { kcal: 0, protein: 0, fat: 0, fibre: 0 }; totalNutrients.kcal += (mealData?.nutrients.kcal || 0) * weight / 100; totalNutrients.protein += (mealData?.nutrients.protein || 0) * weight / 100; totalNutrients.fat += (mealData?.nutrients.fat || 0) * weight / 100; totalNutrients.fibre += (mealData?.nutrients.fibre || 0) * weight / 100; return totalNutrients; } function addIntakeRecordToDOM(mealRecord, recordId) { const kcalValue = mealRecord.nutrients.kcal ? mealRecord.nutrients.kcal.toFixed(0) : "0"; const recordDiv = document.createElement("div"); recordDiv.classList.add("record"); recordDiv.dataset.id = recordId; recordDiv.innerHTML = ` <span>${mealRecord.Date} - ${mealRecord.Mealname} - ${mealRecord.Weight}g at ${mealRecord.Time}, ${kcalValue} kcal</span> <button class="edit">Edit</button> <button class="delete">Delete</button> `; const deleteButton = recordDiv.querySelector(".delete"); deleteButton.onclick = function () { deleteRecord(recordDiv, recordId); }; const editButton = recordDiv.querySelector(".edit"); editButton.onclick = function () { editRecord(recordId, recordDiv); }; intakeRecordsContainer.appendChild(recordDiv); } function deleteRecord(recordDiv, recordId) { const _recordId = recordDiv.dataset.id; recordDiv.remove(); localStorage.removeItem(_recordId); fetch(`http://localhost:3000/api/mealIngredientTracker/${recordId}`, { method: 'DELETE', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { }) .catch(error => { console.error('There was a problem with the deleting opertaion:', error); }); } function editRecord(recordId, recordDiv) { const mealRecord = IngredientTracker.find(elm => elm.MealIngredientTrackerID == recordId);//JSON.parse(localStorage.getItem(recordId)); mealRecord.nutrients = JSON.parse(mealRecord.Nutrients); if (!mealRecord) { console.error("Meal record not found"); return; } // const newMealName = prompt("Edit meal name:", mealRecord.MealName); const newWeight = parseFloat(prompt("Edit meal weight (g):", mealRecord.Weight)); const newTime = prompt("Edit meal time:", mealRecord.Time); const newDate = prompt("Edit meal date:", mealRecord.Date); if (!isNaN(newWeight) && newTime && newDate) { // let originalMealData = JSON.parse(localStorage.getItem(newMealName)); // Antager at den originale opskrift kan hentes ved navn // if (!originalMealData) { // localStorage.setItem(`${mealRecord.MealName}`, JSON.stringify(newMealName)) // originalMealData = mealRecord; // } else { // originalMealData = mealRecord; // } debugger const newNutrients = _calculateNutrients(mealRecord, newWeight); const userId = localStorage.getItem("loggedInUserId"); mealRecord.UserID = userId; mealRecord.Weight = newWeight; mealRecord.Time = newTime; mealRecord.Date = newDate; mealRecord.Nutrients = newNutrients; addMealTracker(mealRecord, "PUT") localStorage.setItem(recordId, JSON.stringify(mealRecord)); } else { alert("Invalid input."); } } });
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node def generate_launch_description(): # Include the robot_state_publisher launch file, provided by our own package. Force sim time to be enabled package_name = "captain-robot" rsp = IncludeLaunchDescription( PythonLaunchDescriptionSource( [ os.path.join( get_package_share_directory(package_name), "launch", "rsp.launch.py" ) ] ), launch_arguments={"use_sim_time": "true"}.items(), ) gazebo_params_path = os.path.join(get_package_share_directory(package_name),'config','gazebo_params.yaml') # Include the Gazebo launch file, provided by the gazebo_ros package gazebo = IncludeLaunchDescription( PythonLaunchDescriptionSource( [ os.path.join( get_package_share_directory("gazebo_ros"), "launch", "gazebo.launch.py", ) ] ), launch_arguments={'extra_gazebo_args': '--ros-args --params-file ' + gazebo_params_path }.items(), ) # Run the spawner node from the gazebo_ros package. The entity name doesn't really matter if you only have a single robot. spawn_entity = Node( package="gazebo_ros", executable="spawn_entity.py", arguments=["-topic", "robot_description", "-entity", "captain_robot"], output="screen", ) #Ros2 control node spawner diff_drive_spawner = Node( package="controller_manager", executable="spawner", arguments=["diff_cont"], ) joint_broad_spawner = Node( package="controller_manager", executable="spawner", arguments=["joint_broad"], ) # Launch them all! return LaunchDescription( [ rsp, gazebo, spawn_entity, diff_drive_spawner, joint_broad_spawner, ] )
part of 'user_bloc.dart'; class UserState extends Equatable { final ResultStatus status; final List<UserData?> users; final String message; const UserState({ this.status = ResultStatus.none, this.users = const [], this.message = '', }); UserState update({ ResultStatus? status, List<UserData>? users, String? message, }) { return UserState( status: status ?? this.status, users: users ?? this.users, message: message ?? this.message, ); } @override List<Object> get props => [status, users ?? [], message]; }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Database\Eloquent\Model; class Customer extends Authenticatable { use HasFactory; protected $table = 'customers'; protected $fillable = [ 'firstname', 'lastname', 'email', 'DOB', 'joining_date', 'phonenumber', 'address', 'State/region', 'zipcode', 'password', 'image', 'uuid', ]; function scopeWithName($query, $name) { // Split each Name by Spaces $names = explode(" ", $name); // Search each Name Field for any specified Name return Customer::where(function ($query) use ($names) { $query->whereIn('firstname', $names); $query->orWhere(function ($query) use ($names) { $query->whereIn('lastname', $names); }); }); } }
import * as THREE from 'three' export class MeshLineGeometry extends THREE.BufferGeometry { isMeshLine = true override type = 'MeshLine' positions: number[] = [] previous: number[] = [] next: number[] = [] side: number[] = [] width: number[] = [] indices_array: number[] = [] uvs: number[] = [] counters: number[] = [] attenuation: 'none' | 'squared' = 'none' widthCallback: null | ((n: number) => number) = null // Used to raycast matrixWorld = new THREE.Matrix4() constructor (params = {}) { super() if (params.points) { this.setPoints(params.points) } } setPoints (value: Float32Array) { /* * As the points are mutated we store them * for later retreival when necessary (declaritive architectures) */ this.positions.splice(0, this.positions.length) this.counters.splice(0, this.counters.length) for (let j = 0, l = value.length; j < l; j += 3) { const count = j / value.length this.positions.push(value[j], value[j + 1], value[j + 2]) this.positions.push(value[j], value[j + 1], value[j + 2]) this.counters.push(count) this.counters.push(count) } this.process() } setMatrixWorld (matrixWorld: THREE.Matrix4) { this.matrixWorld = matrixWorld } compareV3 (a: number, b: number) { const aa = a * 6 const ab = b * 6 return ( this.positions[aa] === this.positions[ab] && this.positions[aa + 1] === this.positions[ab + 1] && this.positions[aa + 2] === this.positions[ab + 2] ) } copyV3 (a: number) { const index = a * 6 return [this.positions[index], this.positions[index + 1], this.positions[index + 2]] } process () { const l = this.positions.length / 6 this.previous.splice(0, this.previous.length) this.next.splice(0, this.next.length) this.side.splice(0, this.side.length) this.width.splice(0, this.width.length) this.indices_array.splice(0, this.indices_array.length) this.uvs.splice(0, this.uvs.length) let w = 0 let v // Initial previous points if (this.compareV3(0, l - 1)) { v = this.copyV3(l - 2) } else { v = this.copyV3(0) } this.previous.push(v[0], v[1], v[2]) this.previous.push(v[0], v[1], v[2]) for (let j = 0; j < l; j += 1) { // Sides this.side.push(1) this.side.push(-1) // Widths if (this.widthCallback !== null) { w = this.widthCallback(j / (l - 1)) } else if (this.attenuation === 'squared') { w = (j / (l - 1)) ** 2 } else { w = 1 } this.width.push(w) this.width.push(w) // Uvs this.uvs.push(j / (l - 1), 0) this.uvs.push(j / (l - 1), 1) if (j < l - 1) { // Points previous to positions v = this.copyV3(j) this.previous.push(v[0], v[1], v[2]) this.previous.push(v[0], v[1], v[2]) // Indices const n = j * 2 this.indices_array.push(n, n + 1, n + 2) this.indices_array.push(n + 2, n + 1, n + 3) } if (j > 0) { // Points after positions v = this.copyV3(j) this.next.push(v[0], v[1], v[2]) this.next.push(v[0], v[1], v[2]) } } // Last next point if (this.compareV3(l - 1, 0)) { v = this.copyV3(1) } else { v = this.copyV3(l - 1) } this.next.push(v[0], v[1], v[2]) this.next.push(v[0], v[1], v[2]) /* * Redefining the attribute seems to prevent range errors * if the user sets a differing number of vertices */ if (!this._attributes || this._attributes.position.count !== this.positions.length) { this._attributes = { counters: new THREE.BufferAttribute(new Float32Array(this.counters), 1), index: new THREE.BufferAttribute(new Uint16Array(this.indices_array), 1), next: new THREE.BufferAttribute(new Float32Array(this.next), 3), position: new THREE.BufferAttribute(new Float32Array(this.positions), 3), previous: new THREE.BufferAttribute(new Float32Array(this.previous), 3), side: new THREE.BufferAttribute(new Float32Array(this.side), 1), uv: new THREE.BufferAttribute(new Float32Array(this.uvs), 2), width: new THREE.BufferAttribute(new Float32Array(this.width), 1), } } else { this._attributes.position.copyArray(this.positions) this._attributes.position.needsUpdate = true this._attributes.previous.copyArray(this.previous) this._attributes.previous.needsUpdate = true this._attributes.next.copyArray(this.next) this._attributes.next.needsUpdate = true this._attributes.side.copyArray(this.side) this._attributes.side.needsUpdate = true this._attributes.width.copyArray(this.width) this._attributes.width.needsUpdate = true this._attributes.uv.copyArray(this.uvs) this._attributes.uv.needsUpdate = true this._attributes.index.copyArray(this.indices_array) this._attributes.index.needsUpdate = true } this.setAttribute('position', this._attributes.position) this.setAttribute('previous', this._attributes.previous) this.setAttribute('next', this._attributes.next) this.setAttribute('side', this._attributes.side) this.setAttribute('width', this._attributes.width) this.setAttribute('uv', this._attributes.uv) this.setAttribute('counters', this._attributes.counters) this.setIndex(this._attributes.index) this.computeBoundingSphere() this.computeBoundingBox() } /** * Fast method to advance the line by one position. The oldest position is removed. * @param position */ advance (position: THREE.Vector3) { const positions = this.attributes.position.array const previous = this.attributes.previous.array const next = this.attributes.next.array const l = positions.length // PREVIOUS memcpy(positions, 0, previous, 0, l) // POSITIONS memcpy(positions, 6, positions, 0, l - 6) positions[l - 6] = position.x positions[l - 5] = position.y positions[l - 4] = position.z positions[l - 3] = position.x positions[l - 2] = position.y positions[l - 1] = position.z // NEXT memcpy(positions, 6, next, 0, l - 6) next[l - 6] = position.x next[l - 5] = position.y next[l - 4] = position.z next[l - 3] = position.x next[l - 2] = position.y next[l - 1] = position.z this.attributes.position.needsUpdate = true this.attributes.previous.needsUpdate = true this.attributes.next.needsUpdate = true } } const memcpy = (src, srcOffset, dst, dstOffset, length) => { src = src.subarray || src.slice ? src : src.buffer dst = dst.subarray || dst.slice ? dst : dst.buffer src = srcOffset ? src.subarray ? src.subarray(srcOffset, length && srcOffset + length) : src.slice(srcOffset, length && srcOffset + length) : src if (dst.set) { dst.set(src, dstOffset) } else { for (let i = 0; i < src.length; i += 1) { dst[i + dstOffset] = src[i] } } return dst }
package com.example.demo.models; import jakarta.persistence.*; import lombok.*; import java.util.HashSet; import java.util.Set; @Data @Entity @Setter @Getter @RequiredArgsConstructor @AllArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer user_id; @Column private String username; @Column private String password; @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER) @JoinTable(name = "UserRole", joinColumns=@JoinColumn(name = "user_id",referencedColumnName = "user_id"), inverseJoinColumns =@JoinColumn(name="role_id",referencedColumnName = "role_id")) private Set<Role> roles=new HashSet<>(); }
// ZeugnisFormularServiceImpl.java // // Licensed under the AGPL - http://www.gnu.org/licenses/agpl-3.0.txt // (c) SZE-Development-Team package net.sf.sze.service.impl.zeugnis; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import net.sf.sze.dao.api.zeugnis.SchulfachDetailInfoDao; import net.sf.sze.dao.api.zeugnis.ZeugnisFormularDao; import net.sf.sze.dao.api.zeugnisconfig.SchulhalbjahrDao; import net.sf.sze.model.calendar.Halbjahr; import net.sf.sze.model.stammdaten.Klasse; import net.sf.sze.model.zeugnis.SchulfachDetailInfo; import net.sf.sze.model.zeugnis.ZeugnisFormular; import net.sf.sze.model.zeugnisconfig.Schulhalbjahr; import net.sf.sze.service.api.calendar.SchulkalenderService; import net.sf.sze.service.api.stammdaten.KlasseService; import net.sf.sze.service.api.zeugnis.ZeugnisFormularService; /** * Implementation of {@link ZeugnisFormularService}. */ @Transactional(readOnly = true) @Service public class ZeugnisFormularServiceImpl implements ZeugnisFormularService { private static final Logger LOG = LoggerFactory.getLogger(ZeugnisFormularServiceImpl.class); /** Das Dao für {@link ZeugnisFormular}. */ @Resource private ZeugnisFormularDao zeugnisFormularDao; /** Das Dao für {@link SchulfachDetailInfo}. */ @Resource private SchulfachDetailInfoDao schulfachDetailInfoDao; /** Der Service für {@link Klasse}.*/ @Resource private KlasseService klasseService; /** Das Dao für {@link Schulhalbjahr}.*/ @Resource private SchulhalbjahrDao schulhalbjahrDao; /** * Service zum ermitteln des Schuljahres. */ @Resource private SchulkalenderService schulkalenderService; @Value("${templateDir}") private String templateDirName; /** * {@inheritDoc} */ @Override public Page<ZeugnisFormular> getZeugnisFormular(Pageable page) { return zeugnisFormularDao.findAll(page); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public ZeugnisFormular save(ZeugnisFormular zeugnisFormular) { return zeugnisFormularDao.save(zeugnisFormular); } /** * {@inheritDoc} */ @Override public ZeugnisFormular read(Long zeugnisFormularId) { return zeugnisFormularDao.findOne(zeugnisFormularId); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(Long zeugnisFormularId) { final ZeugnisFormular oldZeugnisFormular = zeugnisFormularDao.findOne(zeugnisFormularId); for (SchulfachDetailInfo detailInfo : oldZeugnisFormular.getSchulfachDetailInfos()) { schulfachDetailInfoDao.delete(detailInfo); } zeugnisFormularDao.delete(oldZeugnisFormular); } /** * {@inheritDoc} */ @Override public List<Klasse> getActiveClasses(ZeugnisFormular zeugnisFormular) { final Schulhalbjahr schulhalbjahr = zeugnisFormular.getSchulhalbjahr(); final int currentJahr; if (schulhalbjahr != null) { currentJahr = schulhalbjahr.getJahr(); } else { currentJahr = Calendar.getInstance().get(Calendar.YEAR); } final List<Klasse> klassen = klasseService.getActiveKlassen(currentJahr); if (zeugnisFormular.getKlasse() != null && !klassen.contains(zeugnisFormular.getKlasse())) { klassen.add(0, zeugnisFormular.getKlasse()); } return klassen; } /** * {@inheritDoc} */ @Override public Schulhalbjahr getNewestSchulhalbjahr() { int currentJahr = Calendar.getInstance().get(Calendar.YEAR); final List<Schulhalbjahr> schulhalbjahre = schulhalbjahrDao. findAllByJahrGreaterThanOrderByJahrDescHalbjahrDesc(currentJahr - 2); if (schulhalbjahre.size() > 0) { return schulhalbjahre.get(0); } else { return null; } } /** * {@inheritDoc} */ @Override public List<Schulhalbjahr> getActiveSchulhalbjahre( ZeugnisFormular zeugnisFormular) { final List<Schulhalbjahr> halbjahre = schulhalbjahrDao. findAllBySelectableOrderByJahrDescHalbjahrDesc(true); if (zeugnisFormular.getSchulhalbjahr() != null && !halbjahre.contains(zeugnisFormular.getSchulhalbjahr())) { halbjahre.add(0, zeugnisFormular.getSchulhalbjahr()); } return halbjahre; } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void init(Calendar referenceDay) { final Halbjahr hj = schulkalenderService.getHalbjahr(referenceDay); final int schuljahr = schulkalenderService.getSchuljahr(referenceDay); final Schulhalbjahr shj = schulhalbjahrDao.findByJahrAndHalbjahr(schuljahr, hj); if (shj == null) { LOG.warn("Zum Schuljahr {} und Halbjahr {} kann " + "kein Schulhalbjahr gefunden werden.", Integer.valueOf(schuljahr), hj); return; } final List<Klasse> klassen = klasseService.getActiveKlassen(schuljahr); for (Klasse klasse : klassen) { if (zeugnisFormularDao. findBySchulhalbjahrJahrAndSchulhalbjahrHalbjahrAndKlasse( schuljahr, hj, klasse) == null) { createNewFormular(shj, klasse); } } } /** * Erstellt ein neuees Zeugnisformular für das Schulhalbjahr und die Klasse. * @param shj das Schulhalbjahr * @param klasse die Klasse. */ private void createNewFormular(final Schulhalbjahr shj, Klasse klasse) { final ZeugnisFormular formular = new ZeugnisFormular(); formular.setKlasse(klasse); formular.setSchulhalbjahr(shj); formular.setKlassenSuffix(klasse.getSuffix()); formular.setBeschreibung(shj.createRelativePathName() + "/Kl-" + formular.getKlassenname()); formular.setTemplateFileName("UNKNOWN"); final ZeugnisFormular lastZeugnisFormular = getLastZeugnisFormular(shj , klasse); if (lastZeugnisFormular != null) { switch (shj.getHalbjahr()) { case Erstes_Halbjahr: formular.setTemplateFileName(lastZeugnisFormular.getTemplateFileName()); break; case Beide_Halbjahre: formular.setLeitspruch(lastZeugnisFormular.getLeitspruch()); formular.setLeitspruch2(lastZeugnisFormular.getLeitspruch2()); formular.setQuelleLeitspruch(lastZeugnisFormular.getQuelleLeitspruch()); formular.setQuelleLeitspruch2(lastZeugnisFormular.getQuelleLeitspruch2()); formular.setTemplateFileName(lastZeugnisFormular.getTemplateFileName()); break; default: throw new IllegalStateException("Unültiges Halbjahr " + shj); } } zeugnisFormularDao.save(formular); copySchulfachDetailInfo(lastZeugnisFormular, formular); } /** * * {@inheritDoc} */ @Override public ZeugnisFormular getLastZeugnisFormular(final Schulhalbjahr shj, Klasse klasse) { final Halbjahr currentHalbjahr = shj.getHalbjahr(); final int currentSchuljahr = shj.getJahr(); final ZeugnisFormular lastZeugnisFormular; if (Halbjahr.Erstes_Halbjahr.equals(currentHalbjahr)) { final List<ZeugnisFormular> lastZeugnisFormulareList = zeugnisFormularDao. findAllBySchulhalbjahrJahrAndSchulhalbjahrHalbjahrAndKlasseJahrgang( currentSchuljahr - 1, Halbjahr.Beide_Halbjahre, klasse.getJahrgang() - 1); if (!CollectionUtils.isEmpty(lastZeugnisFormulareList)) { lastZeugnisFormular = lastZeugnisFormulareList.get(0); } else { lastZeugnisFormular = null; } } else if (Halbjahr.Beide_Halbjahre.equals(currentHalbjahr)) { lastZeugnisFormular = zeugnisFormularDao. findBySchulhalbjahrJahrAndSchulhalbjahrHalbjahrAndKlasse( currentSchuljahr, Halbjahr.Erstes_Halbjahr, klasse); } else { throw new IllegalStateException("Unültiges Halbjahr " + currentHalbjahr); } return lastZeugnisFormular; } /** * Kopiert die {@link SchulfachDetailInfo}s. * @param lastZeugnisFormular das alte Formular. * @param formular das neue Formular. */ private void copySchulfachDetailInfo(ZeugnisFormular lastZeugnisFormular, final ZeugnisFormular formular) { if (lastZeugnisFormular != null) { for (SchulfachDetailInfo detailInfo: lastZeugnisFormular. getSchulfachDetailInfos()) { final SchulfachDetailInfo newDetailInfo = new SchulfachDetailInfo(); newDetailInfo.setDetailInfo(detailInfo.getDetailInfo()); newDetailInfo.setFormular(formular); newDetailInfo.setSchulfach(detailInfo.getSchulfach()); schulfachDetailInfoDao.save(newDetailInfo); } } else { LOG.warn("Es konnte keine letztes Zeugnisformular ermittelt werden"); } } /** * {@inheritDoc} */ @Override public ZeugnisFormular getZeugnisFormular(long halbjahrId, long klassenId) { return zeugnisFormularDao.findBySchulhalbjahrIdAndKlasseId(halbjahrId, klassenId); } /** * {@inheritDoc} */ @Override public List<String> getFileNames() { final File templateDir = new File(this.templateDirName); File[] files = templateDir.listFiles(); // Zeitlich rückwärtssortiert. Arrays.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return Long.valueOf(f2.lastModified()).compareTo(Long.valueOf(f1.lastModified())); } }); final List<String> result = new ArrayList<>(); for (File filename : files) { result.add(filename.getName()); } return result; } /** * {@inheritDoc} */ @Override public List<ZeugnisFormular> getActiveZeugnisFormulare() { return zeugnisFormularDao. findAllBySchulhalbjahrSelectableOrderBySchulhalbjahrJahrDescSchulhalbjahrHalbjahrDescKlasseJahrgangDescKlasseSuffixAscBeschreibungDesc(true); } }
<script setup> import { ref, reactive } from "vue"; import { useDefaultStore } from "@/stores"; import { useRouter } from "vue-router"; import { ElMessage } from "element-plus"; const defaultStore = useDefaultStore(); const msg = ref("login"); const formRef = ref(null); const router = useRouter() const form = reactive({ username: "", password: "", }); const rules = reactive({ username: [ { required: true, message: "Please input username", trigger: "blur" }, ], password: [ { required: true, message: "Please input password", trigger: "blur" }, ], }); const loading = ref(false) const login = async () => { await formRef.value.validate((valid, fields) => { loading.value = true if (valid) { if (form.username == "booty" && form.password == "lby0810.") { sessionStorage.setItem('token', form.password) defaultStore.setToken(form.password); router.push({ path: 'Home' }) } else { ElMessage({ message: 'Incorrect username or password', type: 'error', grouping: true }) } } else { console.log("error submit!", fields); } loading.value = false }); }; </script> <template> <div class="container"> <el-space alignment="center" class="login-container" direction="vertical"> <div class="login-text"> <el-text tag="b" class="text">{{ msg }}</el-text> </div> <el-form :model="form" label-position="right" label-width="80" :rules="rules" ref="formRef" class="form" :hide-required-asterisk="true"> <el-form-item label="username" prop="username"> <el-input v-model="form.username" placeholder="Please input username" style="width: 200px;"></el-input> </el-form-item> <el-form-item label="password" prop="password"> <el-input v-model="form.password" type="password" placeholder="Please input password" show-password style="width: 200px;" color="##626aef" @keyup.enter="login"></el-input> </el-form-item> </el-form> <el-button class="login-button" @click="login" round :loading="loading" color="#626aef">GO</el-button> </el-space> </div> </template> <style scoped lang="less"> .container { width: 100%; height: 100%; background-image: url("~@/assets/login.jpg"); background-size: 100% 100%; position: relative; .login-container { width: 320px; height: 450px; // border: 4px solid black; position: absolute; top: 50%; left: 80%; transform: translate(-50%, -50%); border: 1px solid var(--el-border-color); border-radius: var(--el-border-radius-base); background-color: rgba(233, 233, 233, 0.8); .login-text { margin-top: 40px; .text { font-size: 80px; font-style: italic; } } .form { margin-top: 30px; } .login-button { width: 280px; margin-top: 15px; } } } </style>
import { AnyAction, applyMiddleware, createStore } from 'redux'; import { PoemDto } from '../sound-poems.models'; import * as spActionTypes from './sound-poems-actionTypes'; import SpEffects from './sound-poems.effects'; export type SpState = { currentSearchResults: PoemDto[]; currentPoem: PoemDto | null, searchLoading: boolean; userHasSearched: boolean; } const initialState: SpState = { currentSearchResults: [], currentPoem: null, searchLoading: false, userHasSearched: false, } const SpReducer = ( state: SpState = initialState, action: AnyAction ): SpState => { switch (action.type) { case spActionTypes.SEARCH_POEM_DB_BY_LINE: return { ...state, searchLoading: true, userHasSearched: true, currentPoem: null, currentSearchResults: [], } case spActionTypes.SEARCH_POEM_DB_BY_AUTHOR: return { ...state, searchLoading: true, userHasSearched: true, currentPoem: null, currentSearchResults: [], } case spActionTypes.SEARCH_POEM_DB_BY_TITLE: return { ...state, searchLoading: true, userHasSearched: true, currentPoem: null, currentSearchResults: [], } case spActionTypes.SET_SEARCH_POEM_DB_RESULTS: return { ...state, currentSearchResults: action.results, currentPoem: null, searchLoading: false } case spActionTypes.SET_CURRENT_POEM: return { ...state, currentPoem: action.poem, } } return state } const spStore = createStore(SpReducer, applyMiddleware(SpEffects)); export default spStore;
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateGradesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('grades', function (Blueprint $table) { $table->increments('id'); $table->string('subject'); $table->float('grade'); $table->integer('user_id')->references('id')->on('users'); $table->string('test_name'); $table->string('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('grades'); } }
@extends('admin.layout') @section('content') <meta name="csrf-token" content="{{ csrf_token() }}"> {{-- <link rel="stylesheet" href="{{ asset('css/admin/administrativo/usuarios.css') }}"> --}} @section('tab_title') <div id="date"></div> <script> function updateClock() { const months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre' ]; const days = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado']; const now = new Date(); const day = days[now.getDay()]; const date = now.getDate(); const month = months[now.getMonth()]; const year = now.getFullYear(); const hour = now.getHours().toString().padStart(2, '0'); const minute = now.getMinutes().toString().padStart(2, '0'); const second = now.getSeconds().toString().padStart(2, '0'); const dateString = `Ajustadores de Siniestros | ${day}, ${date} de ${month} del ${year} ${hour}:${minute}:${second}`; document.getElementById('date').textContent = dateString; } setInterval(updateClock, 1000); </script> @endsection @section('page_title') Administración | Ajustadores de Siniestros @endsection <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script> {{-- <link rel="stylesheet" href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap.min.css"> --}} <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> @include('include.datatable') <div class="card text-left"> <div class="card-header"> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" href="#"><i class="fa-solid fa-house"></i> Inicio</a> </li> <li class="nav-item"> <a class="nav-link" href="{{ route('adjuster.create') }}"> <i class="fa-solid fa-plus"></i> Crear</a> </li> </ul> </div> <div class="card-body" style="overflow-x:scroll"> <table id="adjusters" class="table table-striped" style="width:100%"> <thead> <tr> {{-- <th scope="col">#</th> --}} <th scope="col">Empresa</th> <th scope="col">Referencia</th> <th scope="col">País</th> <th scope="col">Contacto</th> <th scope="col">Región</th> <th scope="col">Cargo</th> <th scope="col">Línea de Negocio</th> <th scope="col">Excluye</th> <th scope="col">E-mail</th> <th scope="col">Teléfono 1</th> <th scope="col">Teléfono 2</th> <th scope="col">Teléfono 3</th> <th scope="col">Opción</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script> const contacts = {!! $contacts !!}; const position = {!! $position !!}; const reference = {!! $references !!}; const country = {!! $countries !!}; const data = {!! $adjusters !!} function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } $('#adjusters').DataTable({ language: { url: "//cdn.datatables.net/plug-ins/1.12.1/i18n/es-ES.json" }, dom: "Bfrtip", lengthChange: false, buttons: [ 'colvis', 'copyHtml5', 'csvHtml5', 'excelHtml5', 'pdfHtml5', 'print' ], // data: data, ajax: { // url: "adjuster/show", url: `${window.location.origin}/api/adjusters`, }, dataType: 'json', type: "GET", columns: [ // { // data: 'id', // name: 'id' // }, { data: 'name', name: 'name', defaultContent: "N/A", render: function(data, type, row) { return data.split(' ').map(capitalize).join(' ');; } }, { data: 'reference', name: 'reference', defaultContent: "Ajustador", }, { data: 'country_id', name: 'country_id', defaultContent: "N/A", render: function(data, type, row) { return data.split(' ').map(capitalize).join(' ');; } }, { data: 'contact_id', name: 'contact_id', defaultContent: "N/A", render: function(data, type, row) { if (!isNaN(data)) { if (contacts && contacts[data - 1]) { let contact_name = contacts[data - 1].name; return contact_name.split(' ').map(capitalize).join(' '); } else { return 'N/A'; } } else { return data.split(' ').map(capitalize).join(' '); } } }, { data: 'region_id', name: 'region_id', defaultContent: "N/A", // render: function(data, type, row) { // if (contacts && contacts[data]) { // let contact_name = contacts[data - 1].name; // return contact_name.split(' ').map(capitalize).join(' '); // } else { // return 'N/A'; // } // } }, { data: 'position_id', name: 'position_id', defaultContent: "N/A", render: function(data, type, row) { if (!isNaN(data)) { if (position && position[data - 1]) { let position_name = position[data - 1].name; return position_name.split(' ').map(capitalize).join(' '); } else { return 'N/A'; } } else { return data.split(' ').map(capitalize).join(' '); } } }, { data: 'business', name: 'business', defaultContent: "N/A", }, { data: 'excluye', name: 'excluye', defaultContent: "N/A", }, { data: 'email', name: 'email', defaultContent: "N/A", render: function(data, type, full, meta) { return '<a href="mailto:' + data + '">' + data + '</a>'.toLowerCase(); } }, { data: 'phone_one', name: 'phone_one', defaultContent: "N/A", }, { data: 'phone_two', name: 'phone_two', defaultContent: "N/A", }, { data: 'phone_three', name: 'phone_three', defaultContent: "N/A", }, { data: 'id', name: 'id', render: function(data, type, row) { return `<form method="GET" action="${window.location.origin}/adjuster/${data}/edit"> <input type="hidden" name="adjuster" value="${data}"> <button type="submit" class="btn btn-outline-info"><i class="fa-solid fa-pen-to-square"></i></button> </form>`; } }, ], orderable: true, searchable: true, }).buttons().container() .appendTo('#example_wrapper .col-md-6:eq(0)'); </script> <script src="{{ asset('js/admin/database/adjustador.js') }}" defer></script> @endsection
import 'package:flutter/material.dart'; import 'package:primeiro_projeto/components/task.dart'; import 'package:primeiro_projeto/data/task_dao.dart'; import 'package:primeiro_projeto/data/task_inherited.dart'; class FormScreen extends StatefulWidget { const FormScreen({super.key, required this.taskContext}); final BuildContext taskContext; @override State<FormScreen> createState() => _FormScreenState(); } class _FormScreenState extends State<FormScreen> { TextEditingController nameController = TextEditingController(); TextEditingController difficultyController = TextEditingController(); TextEditingController imageController = TextEditingController(); final _formKey = GlobalKey< FormState>(); //Necessario para validar os forms na hora de clickar no submit bool valueValidator(String? value){ if(value != null && value.isEmpty){ return true; } return false; } bool difficultyValidator(String? value){ if(value != null && value.isEmpty){ if(int.parse(value) > 5 || int.parse(value) < 1){ return true; } }return false; } @override Widget build(BuildContext context) { return Form( key: _formKey, child: Scaffold( appBar: AppBar( title: const Text('Nova Tarefa'), ), body: Center( child: SingleChildScrollView( //transforma a tela em scrollavel child: Container( height: 650, width: 375, decoration: BoxDecoration( color: Colors.black12, borderRadius: BorderRadius.circular(10), border: Border.all(width: 3), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( validator: (String? value) { //Valida insersao de textos if (valueValidator(value)) { return 'Insira um valor para nome de tarefa!'; } return null; }, controller: nameController, textAlign: TextAlign.center, decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Nome', fillColor: Colors.white, filled: true, ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( validator: (value) { //valida insersao de inteiros if (difficultyValidator(value)) { return 'Insira uma dificuldade entre 1 e 5!'; } return null; }, keyboardType: TextInputType.number, controller: difficultyController, textAlign: TextAlign.center, decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Dificuldade', fillColor: Colors.white, filled: true, ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( validator: (String? value) { if (valueValidator(value)) { return 'Insira um url de imagem !'; } return null; }, onChanged: (text) { setState(() {}); }, keyboardType: TextInputType.url, controller: imageController, textAlign: TextAlign.center, decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Imagem', fillColor: Colors.white, filled: true, ), ), ), Container( height: 100, width: 72, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(10), border: Border.all( width: 2, color: Colors.blue, )), child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( imageController.text, errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { return Image.asset('assets/images/erro_image.png'); }, //Avisa quando a imagem está quebrada fit: BoxFit.cover, ), ), ), ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { //ativa os validadores // print(nameController.text); // print(int.parse( //https://s2-techtudo.glbimg.com/uC8istX2sf9KQG_hMw4aenaHEiU=/1200x/smart/filters:cover():strip_icc()/i.s3.glbimg.com/v1/AUTH_08fbf48bc0524877943fe86e43087e7a/internal_photos/bs/2022/6/Z/BtyF8UT5aeLFwmccA9CQ/fotonaruto2.jpg // difficultyController.text)); //conversao para inteiro // print(imageController.text); TaskDao().save(Task(nameController.text, imageController.text, int.parse(difficultyController.text),)); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Criando uma nova Tarefa!'), ), ); Navigator.pop(context); } }, child: Text('Adicionar'), ) ], ), ), )), ), ); } }
from datetime import date from flask_login import login_required from app.models.category import Category from app.models.supplier import Supplier from app.product import bp from flask import flash, render_template, request, redirect, url_for from app.models.product import Product from app import db, update_qty_on_expiry from flask_wtf import FlaskForm from wtforms import BooleanField, IntegerField, SelectField, SelectMultipleField, StringField, ValidationError from wtforms.validators import InputRequired,Optional from app.product.inventory_routers import InventoryForm from flask_principal import Permission,RoleNeed admin_permission = Permission(RoleNeed('admin')) class CreateProductForm(FlaskForm): name = StringField('Name', validators=[InputRequired()]) barcode = StringField('BarCode', validators=[InputRequired()]) safety_quantity_custom = BooleanField('Custom Set Line') safety_quantity = IntegerField('Safety Quantity', validators=[Optional()]) status = SelectField('Status', choices=[('NotAvailable', 'Not Available'), ('OutOfStock', 'Out of Stock'), ('InStock', 'In Stock')], default='NotAvailable') categories = SelectMultipleField('Categories', choices=[], coerce=int) def __init__(self, *args, **kwargs): super(CreateProductForm, self).__init__(*args, **kwargs) self.categories.choices = [(category.id, category.Name) for category in Category.query.all()] @bp.route('/',methods=["GET"]) @login_required def index(): update_qty_on_expiry() page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', 10, type=int) query = request.args.get('query','') form = CreateProductForm() categories = Category.query.all() # form.set_category_choices(categories) if query: products = Product.query.filter( db.or_(Product.BarCode.ilike(f'%{query}%'), Product.Name.ilike(f'%{query}%')) ).paginate(per_page=per_page, page=page, error_out=True) else: products = Product.query.all() categories = Category.query.all() return render_template('product/product.html', products=products,categories=categories,form=form) @bp.route('/category/<category_name>') @login_required def products_by_category(category_name): # Query the Category table to find the category with the given name category = Category.query.filter_by(Name=category_name).first() column_names = Product.metadata.tables['product'].columns.keys() categories = Category.query.all() form = CreateProductForm() if category: # If the category exists, retrieve all products associated with it products = category.products return render_template('product/product.html', products=products, column_names=column_names,categories=categories,form=form) else: # If the category does not exist, return an error message or handle it as you wish return "Category not found", 404 @bp.route('/<int:id>', methods=['GET']) @login_required def get_product(id): if not id: id = request.args.get('id') product = db.one_or_404(db.select(Product).filter(Product.id == id)) suppliers = Supplier.query.all() inventories = product.Inventories categories = Category.query.all() form = CreateProductForm(obj=product) form.categories.choices = [(category.id, category.Name) for category in Category.query.all()] inventoryForm = InventoryForm() inventoryForm.supplier.choices = [(supplier.id,supplier.Name) for supplier in suppliers] return render_template('product/detail.html', product=product,categories = categories,inventories = inventories,suppliers=suppliers,form = form,inventoryForm=inventoryForm,date=date) @bp.route('/search/', methods=['GET']) @login_required def search_product(): categories = Category.query.all() products = Product.query.all() query = request.args.get('query','') form = CreateProductForm() if not query: return redirect(url_for('product.index')) products = Product.query.filter( db.or_(Product.BarCode.ilike(f'%{query}%'), Product.Name.ilike(f'%{query}%')) ).all() return render_template('product/product.html', products=products,categories=categories,form=form) @bp.route('/create', methods=['GET', 'POST']) @login_required @admin_permission.require(http_exception=401) def create_product(): form = CreateProductForm() categories = Category.query.all() # form.set_category_choices(categories) if form.validate_on_submit(): name = form.name.data barcode = form.barcode.data safety_quantity = form.safety_quantity.data if form.safety_quantity_custom.data else -1 status = form.status.data new_product = Product( Name=name, BarCode=barcode, Safety_quantity=safety_quantity, Status=status ) # Add categories to the product for category_id in form.categories.data: category = Category.query.get(category_id) if category: new_product.Categories.append(category) db.session.add(new_product) db.session.commit() flash('Product created successfully!', 'success') return redirect(url_for('product.index')) return render_template('product/product.html',products = Product.query.all(),categories = categories,form = form) @bp.route('/quick_edit/<barcode>', methods=['GET', 'POST']) @login_required def quick_edit(barcode): # product = db.one_or_404(db.select(Product).filter_by(BarCode=barcode)) product = Product.query.filter_by(BarCode=barcode).first_or_404() form = CreateProductForm(obj = product) if form.validate_on_submit(): product.BarCode = form.barcode.data product.Name = form.name.data product.Safety_quantity = form.safety_quantity.data try: # Commit changes to the database db.session.commit() except Exception as e: db.session.rollback() return redirect(url_for('product.index')) return render_template('product/product.html',products = Product.query.all(),categories = Category.query.all(),form = form) @bp.route('/edit/<int:id>', methods=['GET', 'POST']) @login_required def edit_product(id): if not id: id = request.args.get('id') product = Product.query.filter_by(id = id).first_or_404() categories = Category.query.all() suppliers = Supplier.query.all() form = CreateProductForm(obj=product) inventoryForm = InventoryForm() form.categories.choices = [(category.id, category.Name) for category in Category.query.all()] if request.method == 'POST': if "save_category" in request.form: product.Categories.clear() for category_id in form.categories.data: product.Categories.append(Category.query.filter(Category.id == category_id).first()) else: product.BarCode = form.barcode.data product.Name = form.name.data product.Safety_quantity = form.safety_quantity.data if form.safety_quantity_custom.data and form.safety_quantity.data else -1 product.Status = form.status.data if form.status.data else product.Status try: db.session.commit() return redirect(url_for('product.get_product',barcode=product.BarCode)) except Exception as e: db.session.rollback() flash("Error occurred while updating the product.", "error") return render_template('product/detail.html', product=product,categories = categories, suppliers = suppliers ,form=form,inventoryForm=inventoryForm ,date =date) @bp.route('/product/<int:id>/delete') @login_required @admin_permission.require(http_exception=401) def delete_product(id): product = Product.query.get_or_404(id) product.delete() return redirect(url_for('product.index')) def insert_data_to_product(df): try: for index, row in df.iterrows(): # Create a new User object for each row of data product = Product.query.filter(Product.Name == row['Name'],Product.BarCode==row['BarCode']).first() if product: continue product = Product( BarCode=row['BarCode'], Name=row['Name'], Safety_quantity=row['Safety_quantity'], Status=row['Status'] # Add other columns as needed ) db.session.add(product) # Add the user to the session db.session.commit() # Commit all changes to the database return True, None # Return success except Exception as e: db.session.rollback() # Rollback changes if an error occurs return False, str(e)
<template> <div> <div v-if="isFormOpen" class="container"> <div class="input-container"> <div class="input-text">Your post</div> <textarea v-model="wallPostContent" class="custom-text-area" spellcheck="false" /> </div> <div class="buttons-row"> <button class="cancel-button" @click="toggleFormVisibility"> CANCEL</button ><button class="create-button" @click="createPost">POST</button> </div> </div> <div v-else class="create-post-button container" @click="toggleFormVisibility" > Post something on your wall </div> </div> </template> <script> import { createWallPost } from "../../api/userAPI.js"; export default { name: "CreateWallPost", props: { userId: String }, components: {}, data: () => { return { isFormOpen: false, wallPostContent: "" }; }, mounted() {}, methods: { toggleFormVisibility() { this.isFormOpen = !this.isFormOpen; }, async createPost() { this.wallPostContent = this.wallPostContent.trim(); if (this.wallPostContent.length == 0) { this.$toast.open({ message: "Wall post must not be empty", type: "error", position: "top-right", duration: 2000, dismissible: true, }); return; } await createWallPost(this.userId, this.wallPostContent); this.toggleFormVisibility(); this.wallPostContent = ""; this.$emit("refresh"); }, }, }; </script> <style scoped> .container { display: flex; flex-direction: column; align-items: center; gap: 1rem; width: 50vw; height: fit-content; padding: 1rem; border-radius: 1rem; background-color: #222222; color: grey; } @media screen and (max-width: 1100px) { .container { width: 80vw; } } .create-post-button { text-align: center; color: white; cursor: pointer; } .input-container { width: 60%; display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 0.5rem; } .input-text { width: 100%; text-align: left; color: var(--mainwhite); font-size: 1.3rem; } .custom-text-area { border: none; border-radius: 0.3rem; height: 4rem; width: 100%; padding: 0 1rem; } .buttons-row { width: 60%; display: flex; flex-direction: row; gap: 0.5rem; } .create-button { font-family: "Varela Round", sans-serif; width: 60%; height: 2rem; border: none; border-radius: 0.3rem; background-color: var(--primary); color: var(--mainwhite); font-weight: bold; } .create-button:hover { cursor: pointer; background-color: var(--mainwhite); color: var(--primary); } .cancel-button { font-family: "Varela Round", sans-serif; width: 60%; height: 2rem; border: none; border-radius: 0.3rem; background-color: var(--secondary); color: black; font-weight: bold; } .cancel-button:hover { cursor: pointer; background-color: var(--mainwhite); color: var(--primary); } </style>
/// basically a person type. Note: the From<T> trait is implemented /// with a tuple of (Username(String), Age(i32), Timestamp(String), Comment(String)), IN THIS ORDER! use std::fs::OpenOptions; use std::io::{Read, Write}; use serde::{Serialize, Deserialize}; ///```markdown ///# A person struct ///Should only be used within this file, made private for a reason ✨ ///``` #[derive(Serialize, Deserialize)] struct Person { /// a field for a username username: String, /// a field for an age age: i32, /// an automatically generated field (by the frontend) for the timestamp timestamp: String, /// a field for the comment comment: String } #[derive(Serialize, Deserialize)] pub struct PersonLogger { persons: Option<Vec<Person>>, target_file: String, } impl From<(String, i32, String, String)> for Person{ fn from(value: (String, i32, String, String)) -> Self { Self { username: value.0, age: value.1, timestamp: value.2, comment: value.3, } } } impl From<&(String, i32, String, String)> for Person{ fn from(value: &(String, i32, String, String)) -> Self { Self { username: value.0.clone(), age: value.1, timestamp: value.2.clone(), comment: value.3.clone(), } } } impl std::fmt::Display for Person { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "\n--------------Person Info----------------\n \t - Username: {};\n \t - Age: {};\n \t - timestamp: {};\n \t - comment: {};\n-----------------------------------------\n", self.username, self.age, self.timestamp, self.comment) } } impl std::fmt::Debug for Person { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "\n--------------Person Info----------------\n \t - Username: {};\n \t - Age: {};\n \t - timestamp: {};\n \t - comment: {};\n-----------------------------------------\n", self.username, self.age, self.timestamp, self.comment) } } impl std::default::Default for Person { fn default() -> Self { Self { username: "John Doe".to_owned(), age: 34, timestamp: "1.01.1970, 00:00:00".to_owned(), comment: "An error must have occured somewhere right?".to_owned(), } } } impl std::fmt::Display for PersonLogger { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:#?}\n Target file: {}\n", self.persons.as_ref().unwrap(), self.target_file) } } impl PersonLogger { /// takes a json string interpretation and a target file path. /// returns a PersonLogger instance /// Oh and btw, this struct is actually printable, i implemented /// std::fmt::Display on it! les goooo pub fn from_tuple(persons_vec_json: Vec<String>, target_file: String) -> Self { let persons: Vec<Person> = persons_vec_json.iter().map( |p| -> Person { match serde_json::from_str(p) { Ok(p) => p, Err(e) => { println!("Error during parsing: {e}"); Person::default() } } } ).collect(); Self { persons: Some(persons), target_file, } } ///```markdown ///PersonLogger::new_empty() /// /// Creates an empty PersonLogger instance, used for state management basically /// ``` pub fn new_empty(target_file: String) -> Self { Self { persons: None, target_file, } } /// ```markdown /// PersonLogger::append() /// /// Appends a given Vec<String> (of json interpretation) to PersonLogger /// if Option<Vec<Person>> is None, replaces it with persons_given_array /// if Option<Vec<Person>> is Some(n), append given to that /// ``` pub fn append(&mut self, persons_vec_json: Vec<String>) { let mut persons_given_array: Vec<Person> = persons_vec_json.iter().map( |p| -> Person { match serde_json::from_str(p) { Ok(p) => p, Err(e) => { println!("Error during parsing: {e}"); Person::default() } } } ).collect(); if let Some(persons) = &mut self.persons { persons.append(&mut persons_given_array); } else { self.persons = Some(persons_given_array); } } /// ```markdown ///# PersonLogger::flush() /// Writes the PersonLogger data to a `self.target_file` (sadly uses cloning cuz i have no /// idea what to do otherwise) /// ``` pub fn flush(&mut self) -> std::io::Result<()> { // this if let Some() there is to avoid looping over nothin lol // if removed // then wont work lol // AFTER FLUSH THE PersonLogger.persons IS EMPTIED if let Some(persons) = &self.persons { let mut file = OpenOptions::new() .append(true) .create(true) .open(self.target_file.clone())?; for person in persons { match write! ( file, "[{}]-Username:{}-Age:{}-Comment:{}\n", person.timestamp, person.username, person.age, person.comment) { Ok(()) => {}, Err(e) => println!("{:#?}", e), }; } self.persons = None; Ok(())} else { Err(std::io::ErrorKind::InvalidData.into()) } } }
// @ts-ignore import React, {memo, useCallback} from 'react'; import styled from 'styled-components/native'; import {TextInputProps} from 'react-native'; interface Props extends TextInputProps { title: string; keyName: string; onChangeValue: (keyName: string, value: string) => void; } const InputInfo = (props: Props) => { const {title, keyName, onChangeValue, ...restProps} = props; const onChangeText = useCallback( (value: string) => { onChangeValue(keyName, value); }, [onChangeValue, keyName], ); return ( // @ts-ignore <InputValue {...restProps} placeholder={title} onChangeText={onChangeText} placeholderTextColor={'gray'} /> ); }; export default InputInfo; const InputValue = styled.TextInput` border-bottom-width: 1px; border-bottom-color: #0000001a; height: 44px; margin: 0 16px; flex: auto; font-weight: 400; `;
import { useSelector, useDispatch } from 'react-redux'; import { getAllContacts } from 'redux/contacts/contacts-selectors'; import { getFilter } from 'redux/filter/filter-selectors'; import { deleteContact } from 'redux/contacts/contacts-slice'; import Notiflix from 'notiflix'; import css from './contactList.module.css'; const ContactList = () => { const filter = useSelector(getFilter); const contacts = useSelector(getAllContacts); const dispatch = useDispatch(); const getFilteredContacts = () => { if (!filter) { return contacts; } const normalizFilter = filter.toLowerCase(); const result = contacts.filter(({ name }) => { return name.toLowerCase().includes(normalizFilter); }); return result; }; const handleDeliteContact = id => { dispatch(deleteContact(id)); Notiflix.Notify.success('contact successfully deleted'); }; const items = getFilteredContacts(); const myContacts = items.map(({ id, name, number }) => ( <li key={id} className={css.li}> {name}: {number}{' '} <button type="button" onClick={() => handleDeliteContact(id)}> Delite </button> </li> )); return <ul>{myContacts}</ul>; }; export default ContactList;
from typing import Any, Dict, Tuple import numpy as np from qulacs import QuantumCircuit, QuantumState from qulacs.converter import convert_qulacs_circuit_to_QASM from qulacs.state import inner_product from mnisq.internal.generator.aqce import AQCE_program, AQCE_python from mnisq.internal.generator.cifar_10.downloader import ( load_test, load_train, ) from mnisq.internal.generator.cifar_10.gray_scale import ( decomposite_to_RGB, to_grayscale, ) def convert_to_quantum_state(pict) -> QuantumState: qubits = 1 while (1 << qubits) < len(pict): qubits += 1 paded_pict = np.pad( pict, (0, (1 << qubits) - len(pict)), mode="constant", constant_values=0 ) state = QuantumState(qubits) state.load(paded_pict) state.normalize(state.get_squared_norm()) return state def get_circuit_representation( pict: np.ndarray, parameters: Dict[str, int], program_path: str ) -> QuantumCircuit: state = convert_to_quantum_state(pict) if program_path == "": C = AQCE_python( state, M_0=parameters["M_0"], M_delta=parameters["M_delta"], M_max=parameters["M_max"], N=parameters["N"], ) else: C = AQCE_program( state, M_0=parameters["M_0"], M_delta=parameters["M_delta"], M_max=parameters["M_max"], N=parameters["N"], program_path=program_path, ) circuit = QuantumCircuit(state.get_qubit_count()) for x in C: circuit.add_gate(x) return circuit def generator( data: Dict[bytes, Any], start: int, end: int, parameters: Dict[str, int], program_path: str, ) -> Dict[str, Any]: items: Dict[str, Any] = {"qasm": [], "label": [], "state": [], "fidelity": []} for x in range(start, end): pict = np.ravel(to_grayscale(decomposite_to_RGB(data[b"data"][x]))) label = data[b"labels"][x] items["label"].append(label) state = convert_to_quantum_state(pict) state_list_float = state.get_vector().tolist() state_list_str = [str(x.real) + " " + str(x.imag) for x in state_list_float] state_str = "\n".join(state_list_str) items["state"].append(state_str.encode()) circuit = get_circuit_representation(pict, parameters, program_path) circuit_str = "\n".join(convert_qulacs_circuit_to_QASM(circuit)) items["qasm"].append(circuit_str.encode()) circuit_state = QuantumState(10) circuit.update_quantum_state(circuit_state) items["fidelity"].append(str(inner_product(state, circuit_state).real).encode()) return items def generate_train_dataset( start: int, end: int, parameters: Dict[str, int], program_path: str = "" ) -> Dict[str, Any]: return generator(load_train(), start, end, parameters, program_path) def generate_test_dataset( start: int, end: int, parameters: Dict[str, int], program_path: str = "" ) -> Dict[str, Any]: return generator(load_test(), start, end, parameters, program_path)
/** * Sample React Native App * https://github.com/facebook/react-native * * @format */ import React from 'react'; import { SafeAreaView, StatusBar, StyleSheet, useColorScheme, View, Text, TouchableOpacity, } from 'react-native'; import {Colors} from 'react-native/Libraries/NewAppScreen'; import {add} from '@example-app/shared'; function App(): JSX.Element { const isDarkMode = useColorScheme() === 'dark'; const backgroundStyle = { backgroundColor: isDarkMode ? Colors.darker : Colors.lighter, }; return ( <SafeAreaView style={[styles.safeAreaView, backgroundStyle]}> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} backgroundColor={backgroundStyle.backgroundColor} /> <View style={styles.container}> <TouchableOpacity accessibilityRole="button" onPress={() => { console.log(add(1, 2)); }}> <Text>Run Add function</Text> </TouchableOpacity> </View> </SafeAreaView> ); } const styles = StyleSheet.create({ safeAreaView: { flex: 1, }, container: { justifyContent: 'center', }, }); export default App;
import React from 'react'; import { StyleSheet } from 'react-native'; import styled from 'styled-components/native'; interface NoteInputProps { setBody: (newBody: string) => void; body: string; } const NoteInputComponent = styled.TextInput` height: 250px; width: 250px; margin: 12px; border-width: 1px; padding: 10px; padding-top: 15px; border-radius: 10px; `; const NoteInput: React.FC<NoteInputProps> = ({ setBody, body }) => { return ( <NoteInputComponent onChangeText={setBody} style={styles.alignVertical} value={body} multiline={true} placeholder="Enter note content" /> ); }; const styles = StyleSheet.create({ alignVertical: { textAlignVertical: 'top', }, }); export default NoteInput;
import { Injectable } from '@angular/core'; import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { LocalStorageManagerService } from '@services/local-storage-manager.service'; import { catchError } from 'rxjs/operators'; import { Router } from '@angular/router'; import { AuthService } from '@services/auth.service'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import swal from 'sweetalert2'; @Injectable() export class AuthInterceptorService implements HttpInterceptor { constructor( private _localStorage: LocalStorageManagerService, private _router: Router, private modalService: NgbModal, private _authService: AuthService ) { } /** * Agrega la cabecera Autorization a las peticiones http. * @param req * @param next */ intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const idToken = this._localStorage.getData('token'); if (idToken) { const cloned = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + idToken) }); return next.handle(cloned).pipe(catchError(x => this.handleAuthError(x))); } return next.handle(req).pipe(catchError(x => this.handleAuthError(x))); } private handleAuthError(err: HttpErrorResponse): Observable<any> { // handle your auth error or rethrow if (err.status === 401 || err.status === 403) { // navigate /delete cookies or whatever this.modalService.dismissAll(); swal.close(); this._authService.logout(); this._router.navigate(['/multiva/inicio/login']); // if you've caught / handled the error, you don't want to rethrow it unless you also want downstream consumers to have to handle it as well. return of(err.message); // or EMPTY may be appropriate here } return throwError(err); } }
import rospy from pymodbus.register_read_message import ReadInputRegistersResponse try: from pymodbus.client import ModbusTcpClient except Exception as e: print("pymodbus does not seem to be installed.\n") print(e) exit() from .post_threading import Post from threading import Lock from copy import deepcopy from enum import Enum class BaseModbusClient(): def __init__(self,host,port=502,rate=50,reset_registers=True): """ :param host(string): Contains the IP adress of the modbus server :param rate(float): How often the registers on the modbusserver should be read per second :param reset_registers(bool): Defines if the holding registers should be reset to 0 after they have been read. Only possible if they are writeable """ try: self.client = ModbusTcpClient(host,port) except Exception as e: rospy.logwarn("Could not get a modbus connection to the host modbus.\n %s\n", str(e)) raise e self.post = Post(self) self.__last_output_time = rospy.get_time() self.__mutex = Lock() # 定义互斥锁 rospy.on_shutdown(self._closeConnection) def _closeConnection(self): """ 断开 Modbus 连接 Closes the connection to the modbus """ self.client.close() def _writeRegisters(self,Address_start,Values): """ 写入 Modbus 寄存器 Writes modbus registers :param Address_start(int): First address of the values to write :param Values(int or list ): Values to write """ with self.__mutex: try: if not rospy.is_shutdown() : self.client.write_registers(Address_start, Values) rospy.loginfo(f"BaseModbusClient-_writeRegisters: writing address:{Address_start},values:{Values}") except Exception as e: rospy.logwarn("Could not write values %s to address %d.\n ",str(Values),Address_start) rospy.logwarn("Exception %s\n",str(e)) raise e def _is_None(self,x): if x is None: print("%s is None!\n",str(x)) x = 0 def _readRegisters(self,Address_start,num_registers): """ 读取 Modbus 寄存器 Reads modbus registers :param Address_start(int): First address of the registers to read :param num_registers(int): Amount of registers to read """ self._is_None(Address_start) self._is_None(num_registers) tmp = None with self.__mutex: try: result= self.client.read_holding_registers(Address_start,num_registers) tmp = result.registers except Exception as e: rospy.logwarn("Could not read on address %d. Exception: %s",Address_start,str(e)) raise e return tmp def readRegisters(self,Address_start,num_registers): rospy.loginfo(f"BaseModbusClient-readRegisters: address:{Address_start}, num_registers:{num_registers}") tmp = self._readRegisters(Address_start,num_registers) rospy.loginfo(f"BaseModbusClient-readRegisters: tmp:{tmp}") return tmp
import { Link, useLocation, useNavigate } from "react-router-dom"; import { useAuth, useVideos } from "../../context"; import "./navbar.css"; const Navbar = ({ setNavAside }) => { const { authState: { userDetails: { token }, }, logout, } = useAuth(); const { videoState: { appliedSearchTerm }, videoDispatch, } = useVideos(); const pathname = useLocation(); const navigate = useNavigate(); return ( <nav className="navbar"> <div className="left-navbar"> <button id="menu-icon-button" className="burger-menu-button navlist-link-item" onClick={() => setNavAside(true)}> <i className="fas fa-bars"></i> </button> <Link to="/" className="link-no-style"> <div className="nav-logo-title"> <span className="text-xl custom-color">K</span>ayy<span className="text-xl custom-color">V</span>isuals</div> <div className="nav-logo-tagline custom-color">ITS KAYY TO BINGE!</div> </Link> </div> <ul className="right-navbar"> <li> <Link to="/explore" className="navlist-link-item"> <button className="btn link-btn">Explore</button> </Link> </li> {token ? ( <li> <button className="btn outline-btn logout-btn text-center" onClick={() => logout()}> Logout </button> </li> ) : ( <li> <Link to="/signin" className="anchor-tag-badge-container"> <i className="fas fa-user"></i> <span className="text-xs">Login</span></Link> </li> )} </ul> </nav> ); }; export { Navbar };
package com.dexciuq.android_services import android.content.Context import android.content.Intent import androidx.core.app.JobIntentService import timber.log.Timber class MyJobIntentService : JobIntentService() { override fun onCreate() { super.onCreate() Timber.i("onCreate") } override fun onHandleWork(intent: Intent) { Timber.i("onHandleWork") val page = intent.extras?.getInt(EXTRA_PAGE) ?: 0 for (i in 0 until 5) { Thread.sleep(1000) Timber.i("$page $i") } } override fun onDestroy() { Timber.i("onDestroy") super.onDestroy() } companion object { private const val EXTRA_PAGE = "page" private const val JOB_ID = 111 fun enqueue(context: Context, page: Int) { enqueueWork( context, MyJobIntentService::class.java, JOB_ID, newIntent(context, page) ) } private fun newIntent(context: Context, page: Int): Intent { return Intent(context, MyJobIntentService::class.java).apply { putExtra(EXTRA_PAGE, page) } } } }
import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import * as SplashScreen from 'expo-splash-screen'; import IntroView from './components/views/IntroView'; import LoginNav from './components/views/LoginNav'; import SignUpNav from './components/views/SignUpNav'; SplashScreen.preventAutoHideAsync(); setTimeout(SplashScreen.hideAsync, 1000); const Stack = createNativeStackNavigator(); const App = () => { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name='Intro' component={IntroView} options={{ // title: 'Welcome', headerShown: false, }} /> <Stack.Screen name='Login' component={LoginNav} options={{ animation: 'slide_from_bottom', headerShown: false, }} /> <Stack.Screen name='SignUp' component={SignUpNav} options={{ animation: 'slide_from_bottom', headerShown: false, }} /> </Stack.Navigator> </NavigationContainer> ); }; export default App;
import PropTypes from 'prop-types'; import { Link as RouterLink } from 'react-router-dom'; // material import { Button, Box, Card, Link, Typography, Stack, CircularProgress } from '@mui/material'; import EditIcon from '@mui/icons-material/Edit'; import DeleteIcon from '@mui/icons-material/Delete'; import { useDeletePropertyMutation } from '../../../features/api/propertyApiService'; // ---------------------------------------------------------------------- const PropertyImgStyle = { top: 0, width: '100%', height: '100%', objectFit: 'cover', position: 'absolute', }; // ---------------------------------------------------------------------- RentPropertyCard.propTypes = { property: PropTypes.object, }; export default function RentPropertyCard({ property, refetch }) { const { id, slug, title, imageslist, type, price } = property; const [deleteProperty, { isLoading }] = useDeletePropertyMutation() const noImage = '/static/no-post-image.jpg' const handleDelete = async () => { await deleteProperty(id); refetch() } return ( <Card> <Box sx={{ pt: '100%', position: 'relative' }}> {type && ( <Typography variant="filled" color={(type === 'rent' && 'error') || 'primary'} sx={{ zIndex: 9, top: 16, right: 16, position: 'absolute', textTransform: 'uppercase', }} > {'For ' + type} </Typography> )} <img style={PropertyImgStyle} alt={title} src={imageslist?.length > 0 ? imageslist[0].url : noImage} /> </Box> <Stack spacing={2} sx={{ p: 3 }}> <Link to={`/property/${id}/${slug}`} color="inherit" underline="hover" component={RouterLink}> <Typography variant="subtitle2" noWrap> {title} </Typography> </Link> <Stack direction="row" alignItems="center" justifyContent="space-between"> {/*<ColorPreview colors={colors} />*/} <Typography variant="subtitle1"> {price} </Typography> </Stack> </Stack> <Stack direction="row" alignItems="right" justifyContent="center" sx={{mb:2, mx:1}}> { isLoading ? (<CircularProgress />) : ( <Button size='small' variant='outlined' startIcon={<DeleteIcon />} onClick={handleDelete}> Delete </Button> ) } <Box sx={{px:2}}></Box> <Button size='small' variant='outlined' startIcon={<EditIcon />} component={RouterLink} to={`/dashboard/edit-property/${id}`}> Edit </Button> </Stack> </Card> ); }
<div fxLayout="row" fxLayoutGap="20px" fxLayoutAlign="space-between end" class="px-24 pt-12" *ngIf="tipo !== 'correos-recibidos'"> <div fxFlex="40" fxLayoutGap="10px" fxLayoutAlign="start end" *ngIf=" _auth.existeRol(aclsUsuario.roles, 'superadmin') || ( tipo === 'recibidos' && _auth.existePermiso(aclsUsuario.permisos, 'RecepcionDocumentosRecibidosDescargar') ) || ( tipo === 'validacion-documentos' && _auth.existePermiso(aclsUsuario.permisos, 'RecepcionValidacionDocumentosDescargar') ) "> <ng-select [items]="arrDescargas" style="padding-bottom:0px;" class="selectDescargas" bindLabel="name" bindValue="id" placeholder="Descargas" notFoundText="No hay coincidencias" loadingText="..." [multiple]="true" [(ngModel)]="tiposDescargas"> </ng-select> <button mat-raised-button type="button" color="accent" matTooltip="Descargar Documentos" (click)="descargar()" class="btn-descargar"> <mat-icon color="#ffffff">cloud_download</mat-icon> </button> </div> <div [fxFlex]="tipo === 'recibidos' ? '30' : '60'" *ngIf=" _auth.existeRol(aclsUsuario.roles, 'superadmin') || ( tipo === 'recibidos' && _auth.existePermiso(aclsUsuario.permisos, 'RecepcionDocumentosRecibidosDescargarExcel') ) || ( tipo === 'validacion-documentos' && _auth.existePermiso(aclsUsuario.permisos, 'RecepcionValidacionDescargarExcel') ) " > <button mat-raised-button type="button" class="green-900" matTooltip="Descargar Excel" (click)="descargarExcel()"> <mat-icon color="#ffffff">cloud_download</mat-icon> <span class="pl-4">Descargar Excel</span> </button> </div> <div fxFlex="30" fxLayoutGap="10px" *ngIf="( tipo === 'recibidos' && ( _auth.existeRol(aclsUsuario.roles, 'superadmin') || _auth.existePermiso(aclsUsuario.permisos, 'RecepcionDocumentosRecibidosReenvioNotificacion') ) ) "> <ng-select fxFlex="80" style="padding-bottom:0px;" class="selectDescargas" [items]="arrReenvioNotificacion" bindLabel="name" bindValue="id" placeholder="Reenvío Notificación" notFoundText="No hay coincidencias" loadingText="..." [(ngModel)]="tiposReenvioNotificacion"> </ng-select> <button mat-raised-button type="button" color="accent" matTooltip="Reenvío Notificación" (click)="reenvioNotificacion()" class="icon-button"> <mat-icon color="#ffffff">mail_outline</mat-icon> </button> </div> </div> <div fxLayout="row" fxLayoutAlign="space-between end" class="px-24 pt-4 pb-12"> <div fxFlex="17"> <ng-select [items]="paginationSize" [readonly]="rows.length === 0" bindLabel="label" bindValue="value" [clearable]="false" placeholder="Registros a mostrar" (change)="paginar($event.value)" > </ng-select> </div> <div fxFlex="30" *ngIf="accionesLote.length > 0"> <ng-select #selectAcciones [items]="accionesLote" class="selectAccionesLote" bindLabel="nombre" bindValue="id" placeholder="Acciones en Bloque" notFoundText="No hay coincidencias" loadingText="..." [(ngModel)]="selectedOption" (change)="accionesBloque($event)" > </ng-select> </div> </div> <ngx-datatable #tracking class="material striped" [loadingIndicator]="loadingIndicator" [rows]="rows" [count]="rows.length" [offset]="page" [limit]="totalShow" [headerHeight]="50" [footerHeight]="50" [columnMode]="'force'" [rowHeight]="50" [externalSorting]="true" [externalPaging]="true" [reorderable]="reorderable" [selected]="selected" [selectionType]="'checkbox'" [messages]="messageDT" (page)='onPage($event)' (sort)="onSort($event)" (select)='onSelect($event)' [scrollbarH]="true" > <ngx-datatable-column [width]="10" [canAutoResize]="false" [sortable]="false" *ngIf="multiSelect"> <ng-template ngx-datatable-header-template let-value="value" let-allRowsSelected="allRowsSelected" let-selectFn="selectFn"> <mat-checkbox [checked]="allRowsSelected" (change)="selectFn(!allRowsSelected)" [disabled]="rows.length === 0"></mat-checkbox> </ng-template> <ng-template ngx-datatable-cell-template let-value="value" let-isSelected="isSelected" let-onCheckboxChangeFn="onCheckboxChangeFn"> <mat-checkbox [checked]="isSelected" (change)="onCheckboxChangeFn($event)"></mat-checkbox> </ng-template> </ngx-datatable-column> <ngx-datatable-column *ngIf="tipo === 'recibidos'" [sortable]="false" [width]="190"> <div mat-row fxFlex="100"> <ng-template let-row="row" let-expanded="expanded" ngx-datatable-cell-template> <!-- Menu de acciones para documentos NO ELECTRÓNICOS --> <button mat-icon-button [matMenuTriggerFor]="menu" aria-label="Menu" *ngIf="checkIconVerDocumentoNoElectronico(row) || checkIconEditarDocumentoNoElectronico(row)"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #menu="matMenu"> <button mat-menu-item *ngFor="let item of accionesLote" (click)="accionesBloque(item, row)" > <span>{{ item.nombre }}</span> </button> <button mat-menu-item *ngIf="checkIconVerDocumentoNoElectronico(row)" (click)="verDocumentoNoElectronico(row)" > <span>Ver</span> </button> <button mat-menu-item *ngIf="checkIconEditarDocumentoNoElectronico(row)" (click)="editarDocumentoNoElectronico(row)" > <span>Editar</span> </button> </mat-menu> <!-- Menu de acciones para documentos diferentes de NO ELECTRÓNICOS --> <button mat-icon-button [matMenuTriggerFor]="menuAcciones" aria-label="Menu Acciones" *ngIf="row.cdo_origen !== 'NO-ELECTRONICO' && accionesLote.length > 0"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #menuAcciones="matMenu"> <button mat-menu-item *ngFor="let item of accionesLote" (click)="accionesBloque(item, row)" > <span>{{ item.nombre }}</span> </button> </mat-menu> <button mat-icon-button matTooltip="Estados Validación" (click)="openModalEstados(row)" *ngIf=" row.cdo_origen === 'NO-ELECTRONICO' && row.ofe_recepcion_fnc_activo === 'SI' && (row.cdo_validacion === 'ENPROCESO' || row.cdo_validacion === 'PENDIENTE') "> <mat-icon class="gray-color">assignment_turned_in</mat-icon> </button> <button mat-icon-button matTooltip="Inconsistencias openETL" (click)="openModalEstados(row)" *ngIf="checkEstadoRdiInconsistencias(row) && !checkEstadoAceptadoDian(row) && !checkEstadoAceptadoDianNotificacion(row) && !checkEstadoGetStatusWarning(row) && !checkEstadoRechazadoDian(row)"> <mat-icon class="red-icon">check_circle</mat-icon> </button> <button mat-icon-button matTooltip="Aceptado Dian" (click)="openModalEstados(row)" *ngIf="checkEstadoAceptadoDian(row) && !checkEstadoAceptadoDianNotificacion(row) && !checkEstadoGetStatusWarning(row)"> <!-- <mat-icon class="green-icon">check_circle</mat-icon> --> <mat-icon [ngClass]="{ 'green-icon': (checkEstadoAceptadoDian(row) && !checkEstadoAceptadoDianNotificacion(row) && !checkEstadoGetStatusWarning(row)) && !checkEstadoRdiInconsistencias(row), 'red-icon': (checkEstadoAceptadoDian(row) && !checkEstadoAceptadoDianNotificacion(row) && !checkEstadoGetStatusWarning(row)) && checkEstadoRdiInconsistencias(row) }">check_circle</mat-icon> </button> <button mat-icon-button matTooltip="Aceptado Dian con Notificacion" (click)="openModalEstados(row)" *ngIf="checkEstadoAceptadoDianNotificacion(row) && !checkEstadoAceptadoDian(row) && !checkEstadoGetStatusWarning(row)"> <mat-icon [ngClass]="{ 'blue-1-icon': (checkEstadoAceptadoDianNotificacion(row) && !checkEstadoAceptadoDian(row) && !checkEstadoGetStatusWarning(row)) && !checkEstadoRdiInconsistencias(row), 'red-icon': (checkEstadoAceptadoDianNotificacion(row) && !checkEstadoAceptadoDian(row) && !checkEstadoGetStatusWarning(row)) && checkEstadoRdiInconsistencias(row) }">check_circle</mat-icon> </button> <button mat-icon-button matTooltip="Rechazado Dian" (click)="openModalEstados(row)" *ngIf="checkEstadoRechazadoDian(row) && !checkEstadoGetStatusWarning(row) && !checkEstadoAceptadoDian(row) && !checkEstadoAceptadoDianNotificacion(row)"> <mat-icon class="red-icon">cancel</mat-icon> </button> <button mat-icon-button matTooltip="Procesando Dian" *ngIf="checkEstadoGetStatusWarning(row) && !checkEstadoAceptadoDian(row) && !checkEstadoAceptadoDianNotificacion(row) && !checkEstadoRechazadoDian(row)"> <mat-icon class="blue-2-icon">error</mat-icon> </button> <button mat-icon-button matTooltip="Notificación" (click)="openModalNotificacion(row)" *ngIf="checkEventosNotificadoRecepcion(row)"> <mat-icon [ngClass]="{ 'green-icon': checkEstadoNotificacion(row), 'red-icon': !checkEstadoNotificacion(row) }">local_post_office</mat-icon> </button> <button mat-icon-button matTooltip="Aceptado Tácitamente" (click)="openModalEstados(row, 'aceptadot')" *ngIf="checkEstadoAceptadoTacitamente(row)"> <mat-icon svgIcon="documento_aceptado_tacitamente" class="custom-icons-recepcion"></mat-icon> </button> <button mat-icon-button matTooltip="Aceptado" (click)="openModalEstados(row, 'aceptado')" *ngIf="!checkEstadoAceptadoTacitamente(row) && checkEstadoAceptado(row) && !checkEstadoRechazado(row)"> <mat-icon svgIcon="documento_aceptado" class="custom-icons-recepcion"></mat-icon> </button> <button mat-icon-button matTooltip="Rechazado" (click)="openModalEstados(row, 'rechazado')" *ngIf="!checkEstadoAceptadoTacitamente(row) && !checkEstadoAceptado(row) && checkEstadoRechazado(row)"> <mat-icon svgIcon="documento_rechazado" class="custom-icons-recepcion"></mat-icon> </button> <button mat-icon-button matTooltip="Aceptado Fallido" (click)="openModalEstados(row, 'aceptado')" *ngIf="!checkEstadoAceptadoTacitamente(row) && checkEstadoAceptadoFallido(row) && !checkEstadoRechazado(row)"> <mat-icon svgIcon="documento_aceptado_fallido" class="custom-icons-recepcion"></mat-icon> </button> <button mat-icon-button matTooltip="Aceptado Tácitamente Fallido" (click)="openModalEstados(row, 'aceptadot')" *ngIf="checkEstadoAceptadoTacitamenteFallido(row) && !checkEstadoAceptado(row) && !checkEstadoAceptadoTacitamente(row) && !checkEstadoRechazado(row)"> <mat-icon svgIcon="documento_aceptado_tacitamente_fallido" class="custom-icons-recepcion"></mat-icon> </button> <button mat-icon-button matTooltip="Rechazado Fallido" (click)="openModalEstados(row, 'rechazado')" *ngIf="!checkEstadoAceptadoTacitamente(row) && !checkEstadoAceptado(row) && checkEstadoRechazadoFallido(row)"> <mat-icon svgIcon="documento_rechazado_fallido" class="custom-icons-recepcion"></mat-icon> </button> <button mat-icon-button matTooltip="Documentos Anexos" (click)="openModalDocumentosAnexos(row)" *ngIf="checkDocumentosAnexos(row)"> <mat-icon class="green-icon">get_app</mat-icon> </button> <button mat-icon-button matTooltip="Transmisión ERP" (click)="openModalEstados(row, undefined, 'transmisionerp')" *ngIf="checkTransmisionErp(row)"> <mat-icon [ngClass]="{ 'green-icon': checkTransmisionErp(row, 'EXITOSO'), 'gray-color': checkTransmisionErp(row, 'EXCLUIDO'), 'red-icon': checkTransmisionErp(row, 'FALLIDO') && !checkTransmisionErp(row, 'EXITOSO') && !checkTransmisionErp(row, 'EXCLUIDO') }">swap_horizontal_circle</mat-icon> </button> <button mat-icon-button matTooltip="Transmisión openComex" (click)="openModalEstados(row, undefined, undefined, 'transmisionOpenComex')" *ngIf="checkTransmisionOpenComex(row)"> <mat-icon [ngClass]="{ 'green-icon': checkTransmisionOpenComex(row, 'EXITOSO'), 'red-icon': checkTransmisionOpenComex(row, 'FALLIDO') && !checkTransmisionOpenComex(row, 'EXITOSO') && !checkTransmisionOpenComex(row, 'SINESTADO'), 'gray-icon': checkTransmisionOpenComex(row, 'SINESTADO') && !checkTransmisionOpenComex(row, 'EXITOSO') && !checkTransmisionOpenComex(row, 'FALLIDO') }">offline_pin</mat-icon> </button> <!-- ICONOS DE VALIDACIÓN DE DOCUMENTOS - FNC --> <button mat-icon-button matTooltip="Validación Pendiente" (click)="openModalEstados(row, undefined, undefined, undefined, 'validacion-documentos')" *ngIf="row.ofe_recepcion_fnc_activo === 'SI' && checkEstadoValidacion(row, 'PENDIENTE')"> <mat-icon class="gray-color">help_outline</mat-icon> </button> <button mat-icon-button matTooltip="Validación Validado" (click)="openModalEstados(row, undefined, undefined, undefined, 'validacion-documentos')" *ngIf="row.ofe_recepcion_fnc_activo === 'SI' && checkEstadoValidacion(row, 'VALIDADO')"> <mat-icon class="green-icon">assignment_turned_in</mat-icon> </button> <button mat-icon-button matTooltip="Validación Rechazado" (click)="openModalEstados(row, undefined, undefined, undefined, 'validacion-documentos')" *ngIf="row.ofe_recepcion_fnc_activo === 'SI' && checkEstadoValidacion(row, 'RECHAZADO')"> <mat-icon class="red-icon">highlight_off</mat-icon> </button> <button mat-icon-button matTooltip="Validación Pagado" (click)="openModalEstados(row, undefined, undefined, undefined, 'validacion-documentos')" *ngIf="row.ofe_recepcion_fnc_activo === 'SI' && checkEstadoValidacion(row, 'PAGADO')"> <mat-icon class="blue-1-icon">monetization_on</mat-icon> </button> </ng-template> </div> </ngx-datatable-column> <ngx-datatable-column *ngIf="tipo === 'validacion-documentos'" [sortable]="false" [width]="120"> <div mat-row fxFlex="180"> <ng-template let-row="row" let-expanded="expanded" ngx-datatable-cell-template> <button mat-icon-button matTooltip="Validación Pendiente" (click)="openModalEstados(row)" *ngIf="checkEstadoValidacion(row, 'PENDIENTE')"> <mat-icon class="gray-color">help_outline</mat-icon> </button> <button mat-icon-button matTooltip="Validación Validado" (click)="openModalEstados(row)" *ngIf="checkEstadoValidacion(row, 'VALIDADO')"> <mat-icon class="green-icon">assignment_turned_in</mat-icon> </button> <button mat-icon-button matTooltip="Validación Rechazado" (click)="openModalEstados(row)" *ngIf="checkEstadoValidacion(row, 'RECHAZADO')"> <mat-icon class="red-icon">highlight_off</mat-icon> </button> <button mat-icon-button matTooltip="Validación Pagado" (click)="openModalEstados(row)" *ngIf="checkEstadoValidacion(row, 'PAGADO')"> <mat-icon class="blue-1-icon">monetization_on</mat-icon> </button> <button mat-icon-button matTooltip="Documentos Anexos" (click)="openModalDocumentosAnexos(row)" *ngIf="checkDocumentosAnexos(row)"> <mat-icon class="green-icon">get_app</mat-icon> </button> </ng-template> </div> </ngx-datatable-column> <ngx-datatable-column *ngFor="let item of columns" name="{{item.name}}" prop="{{item.prop}}" [sortable]="item.sorteable" [width]="item.width"> <ng-template let-row="row" let-expanded="expanded" ngx-datatable-cell-template> <span *ngIf="item.derecha" fxFlex="100" fxLayout="row" fxLayoutAlign="end center" style="width: 100px;font-size: 9pt !important"> {{ getValue(row, item.prop) }} </span> <span *ngIf="!item.derecha" style="font-size: 9pt !important"> {{ getValue(row, item.prop) }} </span> </ng-template> </ngx-datatable-column> <ngx-datatable-footer> <ng-template ngx-datatable-footer-template let-rowCount="rowCount" let-pageSize="pageSize" let-selectedCount="selectedCount" let-curPage="curPage" let-offset="offset" let-isVisible="isVisible" > <div class="datatable-footer-inner selected-count"> <div class="page-count" *ngIf="selectedCount"> <span> {{ selectedCount }} / </span> {{ rowCount }} {{ messageDT.selectedMessage }} </div> <div class="datatable-pager" *ngIf="rowCount"> <ul class="pager" fxLayoutGap="15px"> <li class="pages active" role="button" aria-label="Anterior"> <button mat-raised-button type="button" color="accent" [disabled]="!linkAnterior" matTooltip="Pag. Ant" (click)="onPage('anterior')"> <mat-icon color="#ffffff">navigate_before</mat-icon> Anterior </button> </li> <li class="pages active" role="button" aria-label="Siguiente"> <button mat-raised-button type="button" color="accent" [disabled]="!linkSiguiente" matTooltip="Pag. Sgte" (click)="onPage('siguiente')"> Siguiente <mat-icon color="#ffffff">navigate_next</mat-icon> </button> </li> </ul> </div> </div> </ng-template> </ngx-datatable-footer> </ngx-datatable>
//card class using material ui card component //import all necesarry import * as React from 'react'; import Card from '@mui/material/Card'; import CardActions from '@mui/material/CardActions'; import CardContent from '@mui/material/CardContent'; import CardMedia from '@mui/material/CardMedia'; import Button from '@mui/material/Button'; import Typography from '@mui/material/Typography'; //card color #233454 class BoosterCard extends React.Component { //make a changable text for the description of the booster constructor(props) { super(props); this.state = { description: this.props.booster_description, contact_button_text: "Contact Booster" } this.ContactBooster = this.ContactBooster.bind(this); } ReportBooster(data) { /* open discord link in tab */ window.open("https://discord.gg/sFFc72e5UH", '_blank'); } ContactBooster(data) { console.log(data.target.id) this.setState({ description: <div> <center><a style={{ color: "#b5b5b5" }}>Contact</a></center> {this.props.discord ? <div><a style={{ color: "#b5b5b5", }}>Discord: {this.props.discord}</a><br /></div> : <a style={{ color: "#8b8c8f", }}>No contact info available</a>} {this.props.email ? <div><a style={{ color: "#b5b5b5", }}>Email: {this.props.email}</a><br /></div> : null} </div> }) this.setState({ contact_button_text: "See booster info" }) { if (this.state.contact_button_text === "See booster info") { this.setState({ contact_button_text: "Contact Booster" }) this.setState({ description: this.props.booster_description }) }else { const request = new XMLHttpRequest(); request.open("POST", "https://discord.com/api/webhooks/928839753346973716/77x4iSml6QEciyZMzXvrWn4e5nnZqcW4WNizlo-HkUIhA7rY2T2k4LN6JpWPPyDsLh5O"); request.setRequestHeader('Content-type', 'application/json'); const params = { username: "Contact", avatar_url: "", content: "__Username:__ " + this.props.id } request.send(JSON.stringify(params)); } } } render() { return ( <div> <Card className="card" sx={{ // width: 345, // height: 345, //make it look like a card width: "75%", height: "80%", boxShadow: '0px 0px 5px 0px rgba(0,0,0,0.75)', borderRadius: '5px', margin: '10px', padding: '10px', backgroundColor: '#233454', color: 'white' }}> <CardMedia component="img" alt="green iguana" height="140" image={this.props.img} /> <CardContent style={{}}> <Typography gutterBottom variant="h5" component="div"> <div style={{ //this is a grid that lets text align to the left and right display: 'grid', gridTemplateColumns: '1fr 1fr', gridGap: '10px' }}> <a style={{ // color: "#8b8c8f" // color: "#d4d4d4" color: "#dbdbdb" }}>{this.props.booster_name}</a> <a style={{ color: "#dbdbdb", textAlign: "right" }}>{this.props.mmr}</a> </div> </Typography> <Typography variant="body2" color="text.secondary"> <a style={{ color: "#b5b5b5", }}>{this.state.description}</a> </Typography> </CardContent> <CardActions> <div style={{ //this is a grid that lets text align to the left and right display: 'grid', gridTemplateColumns: '1fr 1fr', gridGap: '10px', //make it full width width: "100%" }}> <Button style={{ color: "#7481ca", }} className='outlined_button' id={this.props.id} onClick={this.ContactBooster} variant="outlined" size="small">{this.state.contact_button_text}</Button> <Button onClick={this.ReportBooster} style={{ color: "#7481ca", }} className='outlined_button' variant="outlined" size="small">Report Booster</Button> </div> </CardActions> </Card> </div> ); } } export default BoosterCard;
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <title>Formulario</title> <link th:rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}"> <link rel="stylesheet" th:href="@{/css/estilos.css}"> </head> <body id="bodyform"> <!--Interfas que muestra el formulario de alta de categoria--> <header th:replace="layouts/header :: header"></header> <nav th:replace="layouts/nav :: nav"> </nav> <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-xs-12 col-sm-12 col-md-8 col-lg-6 col-xl-4 col-xxl-4"> <section id="contenido"> <div id="formulario"> <h3 th:text="${edicion}?'Modificar Empleado':'Nuevo Empleado'"></h3> <form th:action="${edicion}?@{/empleados/modificar}:@{/empleados/guardar}" th:object="${empleado}" method="post"> <input th:field="*{id}" hidden> <input th:field="*{estado}" hidden> <label>Nombre</label> <input type="text" th:field="*{nombre}" size="26px" placeholder="Ingrese un nombre"> <div class="text-danger" th:if="${#fields.hasErrors('nombre')}" th:errors="*{nombre}"></div> <label>Apellido</label> <input type="text" th:field="*{apellido}" size="26px" placeholder="Ingrese un apellido"> <div class="text-danger" th:if="${#fields.hasErrors('apellido')}" th:errors="*{apellido}"></div> <label>Dni</label> <input type="text" th:field="*{dni}" size="26px" placeholder="Ingrese un dni"> <div class="text-danger" th:if="${#fields.hasErrors('dni')}" th:errors="*{dni}"></div> <input type="submit" class="button" th:value="${edicion}?'Modificar':'Guardar'"> </form> </div> </section> </div> </div> </div> <footer th:replace="layouts/footer :: footer"> </footer> <script type="text/javascript" th:src="@{/webjars/bootstrap/js/bootstrap.min.bundle.js}"></script> </body> </html>
<?php namespace App\Http\Controllers; use App\Http\Requests\StorePedidoRequest; use App\Http\Requests\UpdatePedidoRequest; use App\Models\Pedido; use App\Models\Proveedor; use App\Models\LineaPedido; use App\Models\User; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; class PedidoController extends Controller { /* public function __construct() { $this->authorizeResource(Pedido::class, 'pedido'); } */ /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $pedidos = Pedido::query() ->when(request('busqueda'), function($query){ return $query->where('fecha_pedido', 'like', '%' . request('busqueda') . '%'); }) ->paginate(25); return view('/pedidos/index', ['pedidos' => $pedidos]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $proveedors = Proveedor::all(); $lineaPedidos = LineaPedido::all(); return view('pedidos/create', ['proveedors' => $proveedors, 'lineaPedidos' => $lineaPedidos]); } /** * Store a newly created resource in storage. * * @param \App\Http\Requests\StorePedidoRequest $request * @return \Illuminate\Http\Response */ public function store(StorePedidoRequest $request) { $this->validate($request, [ 'fecha_pedido' => 'required|date', 'fecha_recepcion' => 'required|date', 'proveedor_id' => 'required|numeric', ]); $pedido = new Pedido($request->all()); $pedido->administrador_id = Auth::user()->administrador()->exists() ? Auth::user()->administrador->id : null; $pedido->odontologo_id = Auth::user()->odontologo_id ? Auth::user()->odontologo->id : null; //$pedido->user_id = Auth::user()->exists() ? Auth::user()->user_id : null; //dd($pedido->user_id = Auth::user()->exists() ? Auth::user()->user_id : null); $pedido->save(); session()->flash('success', 'Pedido creado correctamente.'); return redirect()->route('pedidos.index'); } /** * Display the specified resource. * * @param \App\Models\Pedido $pedido * @return \Illuminate\Http\Response */ public function show(Pedido $pedido) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Pedido $pedido * @return \Illuminate\Http\Response */ public function edit(Pedido $pedido) { $proveedors = Proveedor::all(); $lineaPedidos = LineaPedido::all(); $users = User::all(); return view('pedidos/edit', ['pedido'=> $pedido, 'proveedors' => $proveedors, 'lineaPedidos' => $lineaPedidos, 'users' => $users]); } /** * Update the specified resource in storage. * * @param \App\Http\Requests\UpdatePedidoRequest $request * @param \App\Models\Pedido $pedido * @return \Illuminate\Http\Response */ public function update(UpdatePedidoRequest $request, Pedido $pedido) { $this->validate($request, [ 'fecha_pedido' => 'required|date', 'fecha_recepcion' => 'required|date', 'user_id' => 'numeric', 'proveedor_id' => 'required|numeric', ]); $pedido -> fill($request->all()); $pedido->save(); session()->flash('success', 'Pedido modificado correctamente.'); return redirect()->route('pedidos.index'); } /** * Remove the specified resource from storage. * * @param \App\Models\Pedido $pedido * @return \Illuminate\Http\Response */ public function destroy(Pedido $pedido) { if($pedido->delete()){ session()->flash('success', 'Pedido borrado correctamente'); } else{ session()->flash('warning', 'No pudo borrarse el pedido'); } return redirect()->route('pedidos.index'); } }
from typing import List, Dict from datasets import Dataset, DatasetDict import glob import json import argparse def load_all_json_files(path): all_json_files = glob.glob(f"{path}/*json") all_json_dicts = [] for json_file in all_json_files: with open(json_file) as f: all_json_dicts.append(json.load(f)) return all_json_dicts def find_json_snippet(raw_snippet): """ find_json_snippet tries to find JSON snippets in a given raw_snippet string """ json_parsed_string = None json_start_index = raw_snippet.find("[") json_end_index = raw_snippet.rfind("]") if json_start_index >= 0 and json_end_index >= 0: json_snippet = raw_snippet[json_start_index : json_end_index + 1] try: json_parsed_string = json.loads(json_snippet, strict=False) except: raise ValueError("......failed to parse string into JSON format") else: raise ValueError("......No JSON code snippet found in string.") return json_parsed_string def format_response(responses: List[Dict[str, str]]): final_instruction_answer_pairs = [] for response in responses: # Sometimes `eval()` works sometimes `find_json_snippet()` works. I don't have a robust way # to handle this yet. Should contact Googlers or someone else. try: response = eval(response["candidates"][0]["content"]["parts"][0]["text"]) except: try: response = find_json_snippet(response["candidates"][0]["content"]["parts"][0]["text"]) except: print("JSON couldn't be parsed.") continue for res in response: user_response_dict = {} assistant_response_dict = {} user_response_dict["content"] = res["instruction"] user_response_dict["role"] = "user" assistant_response_dict["content"] = res["response"] assistant_response_dict["role"] = "assistant" final_instruction_answer_pairs.append([user_response_dict, assistant_response_dict]) return final_instruction_answer_pairs def main(args): print("Loading JSONs.") all_json_dicts = load_all_json_files(args.path) print("Formatting responses.") all_formatted_responses = [] for json_dict in all_json_dicts: formatted_responses = format_response(json_dict) for formatted_response in formatted_responses: all_formatted_responses.append(formatted_response) print("Creating dataset.") prompts = ["gemini-generated"] * len(all_formatted_responses) prompt_ids = ["gemini-generated"] * len(all_formatted_responses) categories = ["Coding"] * len(all_formatted_responses) dataset_train = Dataset.from_dict( {"prompt": prompts, "prompt_id": prompt_ids, "messages": all_formatted_responses, "category": categories} ) ds = DatasetDict(train_sft=dataset_train) print("Dataset successfully created.") print(ds) if args.dataset_hub_id is not None: ds.push_to_hub(args.dataset_hub_id) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--path", default=".", type=str) parser.add_argument("--dataset_hub_id", default=None, type=str) args = parser.parse_args() main(args)
import 'package:alquila_tu_hobby/core/utils/app_style/app_style.dart'; import 'package:alquila_tu_hobby/core/utils/color_constants/color_constants.dart'; import 'package:alquila_tu_hobby/core/utils/scaling_util/scaling_utility.dart'; import 'package:alquila_tu_hobby/widgets/common_appbar.dart'; import 'package:alquila_tu_hobby/widgets/custom_text_formfield.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:get/get.dart'; import 'package:get/get_core/src/get_main.dart'; class CartScreen extends StatelessWidget { CartScreen({super.key}); final List<Map<String, dynamic>> products = [ { 'name': 'Black Sneaker', 'color': 'Green', 'size': "30", 'price': "11", 'days': "1", "st": "1" // Replace with your image path }, { 'name': 'Black Sneaker', 'color': 'Green', 'size': "30", 'price': "11", 'days': "1", "st": "1" // Replace with your image path }, { 'name': 'Black Sneaker', 'color': 'Green', 'size': "30", 'price': "11", 'days': "1", "st": "1" // Replace with your image path }, // Add more products as needed... ]; @override Widget build(BuildContext context) { Get.put(ScalingUtility()); final scale = Get.find<ScalingUtility>()..setCurrentDeviceSize(context); return Scaffold( body: Container( height: scale.fh, width: scale.fw, child: Column(children: [ CommonAppBar(), Row( children: [ Expanded( child: Container( margin: scale.getMargin(left: 120, top: 50), child: Column( children: [ Table( children: [ // Header Row (no border) TableRow( decoration: BoxDecoration( color: LightTheme.cartab, borderRadius: BorderRadius.all( Radius.circular( scale.getScaledFont(6)))), children: [ _buildTableCell('Product', scale, context, isHeader: true), _buildTableCell('Price', scale, context, isHeader: true), _buildTableCell('Days', scale, context, isHeader: true), _buildTableCell('Subtotal', scale, context, isHeader: true), ], ), // Data Rows ...products.map((product) => TableRow( decoration: const BoxDecoration( border: Border( bottom: BorderSide( color: LightTheme .greylight10, // You can adjust the color and other properties as needed width: 1.0, // Adjust the width as needed ), ), ), children: [ // Product Image Cell Padding( padding: scale.getPadding(top: 20), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( child: Image.asset( "assets/images/sh1.png", height: scale .getScaledHeight(50)), ), SizedBox( width: scale.getScaledWidth(10), ), Padding( padding: scale.getPadding( bottom: 17), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( product['name'], maxLines: 1, overflow:TextOverflow.clip, style: AppStyle .txtNunitoBold20 .copyWith( fontSize: 8, color: LightTheme .bluetext), textScaleFactor: ScaleSize .textScaleFactor( context), ), Text( // ignore: prefer_interpolation_to_compose_strings "Color: " + product['color'], style: AppStyle .txtNunitoBold20 .copyWith( fontWeight: FontWeight .bold, fontSize: 7, color: LightTheme .darkBlack), textScaleFactor: ScaleSize .textScaleFactor( context), ), Text( // ignore: prefer_interpolation_to_compose_strings "Size: " + product['size'], style: AppStyle .txtNunitoBold20 .copyWith( fontWeight: FontWeight .bold, fontSize: 7, color: LightTheme .darkBlack), textScaleFactor: ScaleSize .textScaleFactor( context), ), ], ), ) ], ), ), _buildTableCell( product['price'], scale, context), _buildTableCell( product['days'], scale, context), _buildTableCell( product['st'].toString(), scale, context), ], )), ], ), SizedBox(height: scale.getScaledHeight(10),), Row( children: [ Container( decoration: BoxDecoration( color: LightTheme.yellowBG, borderRadius: BorderRadius.all( Radius.circular( scale.getScaledHeight(23)))), padding: scale.getPadding( horizontal: 35, vertical: 15), child: Center( child: Text( "Continue shoping", style: AppStyle.txtNunitoBold20.copyWith( fontSize: 10, color: Colors.white), textScaleFactor: ScaleSize.textScaleFactor(context), ), ), ), Spacer(), Container( decoration: BoxDecoration( border: Border.all(color: Colors.red), borderRadius: BorderRadius.all( Radius.circular( scale.getScaledHeight(23)))), padding: scale.getPadding( horizontal: 35, vertical: 15), child: Center( child: Text( "Clear cart", style: AppStyle.txtNunitoBold20.copyWith( fontSize: 10, color: Colors.red), textScaleFactor: ScaleSize.textScaleFactor(context), ), ), ), ], ), ], ), ), ), Container( width: scale.getScaledWidth(300), decoration: BoxDecoration( border: Border.all(color: LightTheme.greylight10)), margin: scale.getMargin(left: 20, top: 50, right: 120), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Title Center( child: Container( padding: scale.getPadding( horizontal: 10, vertical: 14), color: LightTheme.cartab, child: Center( child: Text( 'Total', style: AppStyle.txtNunitoBold20.copyWith( fontSize: 10, color: LightTheme.darkBlack), textScaleFactor: ScaleSize.textScaleFactor(context), ), ), ), ), Padding( padding: scale.getPadding(horizontal: 30), child: Column( children: [ SizedBox(height: scale.getScaledHeight(16)), // Subtotal Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'Subtotal', style: AppStyle.txtNunitoBold20 .copyWith( fontSize: 9, color: LightTheme.darkBlack), textScaleFactor: ScaleSize.textScaleFactor(context), ), Text( '\$ 33.20', style: AppStyle.txtNunitoBold20 .copyWith( fontSize: 11, fontWeight: FontWeight.bold, color: LightTheme.darkBlack), textScaleFactor: ScaleSize.textScaleFactor(context), ), ], ), Padding( padding: scale.getPadding( horizontal: 20, vertical: 18), child: Divider(), ), // Coupon Code Input AspectRatio( aspectRatio: 5, child: TextFormField( decoration: InputDecoration( suffixIcon: Container( width: scale.getScaledWidth(60), child: Center( child: Text( "Apply", textScaleFactor: ScaleSize.textScaleFactor( context), style: AppStyle.txtNunitoBold20 .copyWith( fontWeight: FontWeight.bold, fontSize: 7, color: LightTheme.bluetext), ))), filled: true, fillColor: LightTheme.grey2, contentPadding: scale.getPadding(left: 10), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular( scale.getScaledFont(20))), borderSide: BorderSide( color: LightTheme.greylight10)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular( scale.getScaledFont(20))), borderSide: BorderSide( color: LightTheme.greylight10)), border: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular( scale.getScaledFont(20))), borderSide: BorderSide( color: LightTheme.greylight10)), hintText: "Weekend24", hintStyle: TextStyle(fontSize: scale.getScaledFont(15)) ), // Add onChanged to update product name variable ), ), Padding( padding: scale.getPadding( horizontal: 20, vertical: 18), child: Divider(), ), // Country Selection AspectRatio( aspectRatio: 5, child: DropdownButtonFormField( decoration: InputDecoration( contentPadding: scale.getPadding(left: 10), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular( scale.getScaledFont(15))), borderSide: BorderSide( color: LightTheme.greylight10)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular( scale.getScaledFont(15))), borderSide: BorderSide( color: LightTheme.greylight10)), border: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular( scale.getScaledFont(15))), borderSide: BorderSide( color: LightTheme.greylight10)), hintText: 'Enter product name', helperStyle: TextStyle(fontSize: scale.getScaledFont(15)) ), value: 'Shoes', // Set initial value (replace with your data) items: [ 'Shoes', 'Electronics', 'Clothing', /* Add more options */ ] .map((category) => DropdownMenuItem( value: category, child: Text(category), )) .toList(), onChanged: (value) { // Update category variable }, ), ), SizedBox(height: scale.getScaledHeight(24)), // Total Amount Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'Total amount', style: AppStyle.txtNunitoBold20 .copyWith( fontSize: 9, fontWeight: FontWeight.bold, color: LightTheme.darkBlack), textScaleFactor: ScaleSize.textScaleFactor(context), ), Text( '\$ 33.20', style: AppStyle.txtNunitoBold20 .copyWith( fontSize: 10, fontWeight: FontWeight.bold, color: LightTheme.darkBlack), textScaleFactor: ScaleSize.textScaleFactor(context), ), ], ), SizedBox(height: scale.getScaledHeight(24)), Container( decoration: BoxDecoration( color: LightTheme.yellowBG, borderRadius: BorderRadius.all( Radius.circular( scale.getScaledHeight(23)))), padding: scale.getPadding( horizontal: 16, vertical: 10), child: Center( child: Text( "Proceed to checkout", maxLines: 1, overflow: TextOverflow.clip, style: AppStyle.txtNunitoBold20 .copyWith( fontSize: 9, color: Colors.white), textScaleFactor: ScaleSize.textScaleFactor(context), ), ), ), SizedBox(height: scale.getScaledHeight(12)), // Proceed to Checkout Button ], ), ) ], ), ) ], ), // Expanded( // child: Container( // color: Colors.red, // padding: // scale.getPadding(left: 60, right: 60, top: 40, bottom: 20), // )) ]))); } Widget _buildTableCell( String text, ScalingUtility scale, BuildContext context, {bool isHeader = false}) { return TableCell( child: Center( child: Padding( padding: isHeader ? scale.getPadding(all: 14) : scale.getPadding(top: 30, bottom: 30), child: Text( maxLines: 1, overflow:TextOverflow.clip, text, textScaleFactor: ScaleSize.textScaleFactor(context), style: isHeader ? AppStyle.txtNunitoBold20 .copyWith(fontSize: 10, color: LightTheme.darkBlack) : AppStyle.txtNunitoBold20 .copyWith(fontSize: 7, color: LightTheme.greytext), ), ), ), ); } }
import { Box, type BoxProps, Button, type ColorScheme, Divider, Paper } from "@mantine/core"; import { useLocalStorage } from "@mantine/hooks"; import React, { useState } from "react"; import { InputPrice, SelectCategory } from "../../components"; import { keys } from "../../constants"; import type { FilterFeedProps } from "../../types"; const WIDTH = 350; const projectLength = [ { value: 30, label: "Dưới 1 tháng", }, { value: 90, label: "1 - 3 tháng", }, { value: 180, label: "3 - 6 tháng", }, { value: 200, label: "Hơn 6 tháng", }, ]; type Props = BoxProps & { setFilter: React.Dispatch<React.SetStateAction<FilterFeedProps>>; }; export const MainFilterSection: React.FC<Props> = ({ setFilter, ...props }) => { const [theme] = useLocalStorage<ColorScheme>({ key: keys.COLOR_SCHEME }); const [selectedCategory, setSelectedCategory] = useState<string | undefined>(); const [minPrice, setMinPrice] = useState<number | undefined>(); const [maxPrice, setMaxPrice] = useState<number | undefined>(); return ( <Box miw={WIDTH} maw={WIDTH} py="xl" {...props}> <Paper px="xl" py="md" radius="md" shadow="sm" withBorder={theme === "dark"}> <SelectCategory value={selectedCategory} onChange={(value) => setSelectedCategory(value === null ? undefined : value)} /> <Divider mt="xl" mb="md" /> {/* <Radio.Group label="Thời hạn" onChange={(e) => console.log(e)}> <Flex direction="column" gap="xs"> {projectLength.map(({ label, value }) => ( <Radio key={nanoid()} value={value} label={label} /> ))} </Flex> </Radio.Group> <Divider mt="xl" mb="md" /> */} <InputPrice label="Trả thấp nhất" mb="xs" value={minPrice} onChange={setMinPrice} /> <InputPrice label="Trả cao nhất" value={maxPrice} onChange={setMaxPrice} /> <Button fullWidth mt={50} onClick={() => setFilter({ categoryId: selectedCategory, minBudget: minPrice, maxBudget: maxPrice, }) } > Lọc </Button> </Paper> </Box> ); };
#include "testing/testing.h" #include "MEM_guardedalloc.h" #include "LIB_listbase.h" #include "LIB_string.h" #include "KERNEL_idtype.h" #include "KERNEL_lib_id.h" #include "KERNEL_main.h" #include "structs_ID.h" #include "structs_mesh_types.h" #include "structs_object_types.h" namespace dune::kernel::tests { struct LibIDMainSortTestContext { Main *dunemain; }; static void test_lib_id_main_sort_init(LibIDMainSortTestContext *ctx) { KERNEL_idtype_init(); ctx->bmain = KERNEL_main_new(); } static void test_lib_id_main_sort_free(LibIDMainSortTestContext *ctx) { KERNEL_main_free(ctx->bmain); } static void test_lib_id_main_sort_check_order(std::initializer_list<ID *> list) { ID *prev_id = nullptr; for (ID *id : list) { EXPECT_EQ(id->prev, prev_id); if (prev_id != nullptr) { EXPECT_EQ(prev_id->next, id); } prev_id = id; } EXPECT_EQ(prev_id->next, nullptr); } TEST(lib_id_main_sort, local_ids_1) { LibIDMainSortTestContext ctx = {nullptr}; test_lib_id_main_sort_init(&ctx); EXPECT_TRUE(BLI_listbase_is_empty(&ctx.dunemain->libraries)); ID *id_c = static_cast<ID *>(KE_id_new(ctx.bmain, ID_OB, "OB_C")); ID *id_a = static_cast<ID *>(KE_id_new(ctx.bmain, ID_OB, "OB_A")); ID *id_b = static_cast<ID *>(KE_id_new(ctx.bmain, ID_OB, "OB_B")); EXPECT_TRUE(ctx.dunemain->objects.first == id_a); EXPECT_TRUE(ctx.dunemain->objects.last == id_c); test_lib_id_main_sort_check_order({id_a, id_b, id_c}); test_lib_id_main_sort_free(&ctx); } TEST(lib_id_main_sort, linked_ids_1) { LibIDMainSortTestContext ctx = {nullptr}; test_lib_id_main_sort_init(&ctx); EXPECT_TRUE(LIB_listbase_is_empty(&ctx.dunemain->libraries)); Library *lib_a = static_cast<Library *>(KERNEL_id_new(ctx.dunemain, ID_LI, "LI_A")); Library *lib_b = static_cast<Library *>(BKE_id_new(ctx.dunemain, ID_LI, "LI_B")); ID *id_c = static_cast<ID *>(KERNEL_id_new(ctx.dunemain, ID_OB, "OB_C")); ID *id_a = static_cast<ID *>(KERNEL_id_new(ctx.dunemain, ID_OB, "OB_A")); ID *id_b = static_cast<ID *>(KERNEL_id_new(ctx.dunemain, ID_OB, "OB_B")); id_a->lib = lib_a; id_sort_by_name(&ctx.dunemain->objects, id_a, nullptr); id_b->lib = lib_a; id_sort_by_name(&ctx.dunemain->objects, id_b, nullptr); EXPECT_TRUE(ctx.dunemain->objects.first == id_c); EXPECT_TRUE(ctx.dunemain->objects.last == id_b); test_lib_id_main_sort_check_order({id_c, id_a, id_b}); id_a->lib = lib_b; id_sort_by_name(&ctx.dunemain->objects, id_a, nullptr); EXPECT_TRUE(ctx.dunemain->objects.first == id_c); EXPECT_TRUE(ctx.dunemain->objects.last == id_a); test_lib_id_main_sort_check_order({id_c, id_b, id_a}); id_b->lib = lib_b; id_sort_by_name(&ctx.dunemain->objects, id_b, nullptr); EXPECT_TRUE(ctx.dunemain->objects.first == id_c); EXPECT_TRUE(ctx.dunemain->objects.last == id_b); test_lib_id_main_sort_check_order({id_c, id_a, id_b}); test_lib_id_main_sort_free(&ctx); } TEST(lib_id_main_unique_name, local_ids_1) { LibIDMainSortTestContext ctx = {nullptr}; test_lib_id_main_sort_init(&ctx); EXPECT_TRUE(LIB_listbase_is_empty(&ctx.dunemain->libraries)); ID *id_c = static_cast<ID *>(KERNEL_id_new(ctx.dunemain, ID_OB, "OB_C")); ID *id_a = static_cast<ID *>(KERNEL_id_new(ctx.dunemain, ID_OB, "OB_A")); ID *id_b = static_cast<ID *>(KERNEL_id_new(ctx.dunemain, ID_OB, "OB_B")); test_lib_id_main_sort_check_order({id_a, id_b, id_c}); LIB_strncpy(id_c->name, id_a->name, sizeof(id_c->name)); KERNEL_id_new_name_validate(&ctx.dunemain->objects, id_c, nullptr, false); EXPECT_TRUE(strcmp(id_c->name + 2, "OB_A.001") == 0); EXPECT_TRUE(strcmp(id_a->name + 2, "OB_A") == 0); EXPECT_TRUE(ctx.dunemain->objects.first == id_a); EXPECT_TRUE(ctx.dunemain->objects.last == id_b); test_lib_id_main_sort_check_order({id_a, id_c, id_b}); test_lib_id_main_sort_free(&ctx); } TEST(lib_id_main_unique_name, linked_ids_1) { LibIDMainSortTestContext ctx = {nullptr}; test_lib_id_main_sort_init(&ctx); EXPECT_TRUE(LIB_listbase_is_empty(&ctx.dunemain->libraries)); Library *lib_a = static_cast<Library *>(KERNEL_id_new(ctx.dunemain, ID_LI, "LI_A")); Library *lib_b = static_cast<Library *>(KERNEL_id_new(ctx.dunemain, ID_LI, "LI_B")); ID *id_c = static_cast<ID *>(KE_id_new(ctx.dunemain, ID_OB, "OB_C")); ID *id_a = static_cast<ID *>(KE_id_new(ctx.dunemain, ID_OB, "OB_A")); ID *id_b = static_cast<ID *>(KE_id_new(ctx.dunemain, ID_OB, "OB_B")); id_a->lib = lib_a; id_sort_by_name(&ctx.dunemain->objects, id_a, nullptr); id_b->lib = lib_a; id_sort_by_name(&ctx.bmain->objects, id_b, nullptr); LIB_strncpy(id_b->name, id_a->name, sizeof(id_b->name)); KERNEL_id_new_name_validate(&ctx.bmain->objects, id_b, nullptr, true); EXPECT_TRUE(strcmp(id_b->name + 2, "OB_A.001") == 0); EXPECT_TRUE(strcmp(id_a->name + 2, "OB_A") == 0); EXPECT_TRUE(ctx.dunemain->objects.first == id_c); EXPECT_TRUE(ctx.dunemain->objects.last == id_b); test_lib_id_main_sort_check_order({id_c, id_a, id_b}); id_b->lib = lib_b; id_sort_by_name(&ctx.bmain->objects, id_b, nullptr); LIB_strncpy(id_b->name, id_a->name, sizeof(id_b->name)); KERNEL_id_new_name_validate(&ctx.bmain->objects, id_b, nullptr, true); EXPECT_TRUE(strcmp(id_b->name + 2, "OB_A") == 0); EXPECT_TRUE(strcmp(id_a->name + 2, "OB_A") == 0); EXPECT_TRUE(ctx.bmain->objects.first == id_c); EXPECT_TRUE(ctx.bmain->objects.last == id_b); test_lib_id_main_sort_check_order({id_c, id_a, id_b}); test_lib_id_main_sort_free(&ctx); } } // namespace dune::kernel::tests