text
stringlengths
184
4.48M
import yaml import pandas as pd with open("params.yaml") as conf_file: CONFIG = yaml.safe_load(conf_file) CONSTRUCTOR_STATUSES = [ "engine", "transmission", "clutch", "electrical", "hydraulics", "gearbox", "radiator", "suspension", "brakes", "overheating", "mechanical", "tyre", "driver seat", "puncture", "driveshaft", "retired", "fuel pressure", "front wing", "water pressure", "refuelling", "wheel", "throttle", "steering", "technical", "electronics", "broken wing", "heat shield fire", "exhaust", "oil leak", "wheel rim", "water leak", "fuel pump", "track rod", "oil pressure", "pneumatics", "engine fire", "tyre puncture", "out of fuel", "wheel nut", "handling", "rear wing", "fire", "fuel system", "oil line", "fuel rig", "launch control", "fuel", "power loss", "safety", "drivetrain", "ignition", "chassis", "battery", "halfshaft", "crankshaft", "safety concerns", "not restarted", "alternator", "differential", "wheel bearing", "physical", "vibrations", "underweight", "safety belt", "oil pump", "fuel leak", "injection", "distributor", "turbo", "cv joint", "water pump", "spark plugs", "fuel pipe", "oil pipe", "axle", "water pipe", "magneto", "supercharger", "engine misfire", "ers", "power unit", "brake duct", "seat", "debris", "cooling system", "undertray" ] DRIVER_STATUSES = [ "collision", "collision damage", "accident", "disqualified", "spun off", "107% rule", "did not qualify", "stalled", "did not prequalify", "damage" ] MISC_STATUSES = [ "driver unwell", "eye injury", "fatal accident", "illness", "injured", "injury", "not classified", "withdrew", "excluded" ] POINTS_MAP = { 1: 25, 2: 18, 3: 15, 4: 12, 5: 10, 6: 8, 7: 6, 8: 4, 9: 2, 10: 1 } def create_features(): '''Exports features data to 'interim' data folder for creating model''' pre_df = pd.read_csv(CONFIG["data"]["preprocessed_path"]) # infer positions for non-finishers using qualifying position car_df = pre_df[["year", "round", "grid"]].drop_duplicates() car_df["mapPosition"] = car_df.groupby(["year", "round"]).cumcount() + 1 cle_df = pre_df.merge(car_df, on=["year", "round", "grid"], how="left") # create points scored with inferred positions cle_df["mapPoints"] = cle_df["mapPosition"].map(POINTS_MAP).fillna(0) # relabel race finish status sta_df = pd.read_csv(CONFIG["data"]["status_csv"]) cle_df = cle_df.merge(sta_df, on="statusId", how="left") cle_df["status"] = cle_df["status"].apply(str.lower) cle_df["status"] = cle_df["status"].apply(map_status) # remove columns no longer needed cle_df = cle_df.drop(columns=["grid", "position", "statusId"]) # export data cle_df.to_csv(CONFIG["data"]["features_path"], index=False) def map_status(status: str) -> str: if status == "finished" or "lap" in status: return "finished" elif status in DRIVER_STATUSES: return "driver retirement" elif status in CONSTRUCTOR_STATUSES: return "constructor retirement" elif status in MISC_STATUSES: return "misc retirement" else: return status if __name__=="__main__": create_features()
<template> <div> <form class="bootbox-form" id="dzongkhagId"> <div class="card-body"> <div class="row form-group"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <label>Dzongkhag/Thromde:<span class="text-danger">*</span></label> <select class="form-control select2" id="dzo_id" v-model="form.grand_parent_field_id"> <option v-for="(item, index) in dzo_list" :key="index" v-bind:value="item.id">{{ item.name }}</option> </select> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <label>Gewog:<span class="text-danger">*</span></label> <select class="form-control" id="parent_field" v-model="form.parent_field" :class="{ 'is-invalid': form.errors.has('parent_field') }"> <option v-for="(item, index) in gewog_list" :key="index" v-bind:value="item.id">{{ item.name }}</option> </select> <has-error :form="form" field="parent_field"></has-error> </div> </div> <div class="row form-group"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <label>Village Name:<span class="text-danger">*</span></label> <input class="form-control" v-model="form.name" :class="{ 'is-invalid': form.errors.has('name') }" id="name" @change="remove_err('name')" type="text"> <has-error :form="form" field="name"></has-error> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <label>Code:<span class="text-danger">*</span></label> <input readonly class="form-control" v-model="form.code" :class="{ 'is-invalid': form.errors.has('code') }" id="code" @change="remove_err('code')" type="text"> <has-error :form="form" field="code"></has-error> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <label class="required">Status:</label> <br> <label><input v-model="form.status" type="radio" value="1" /> Active</label> <label><input v-model="form.status" type="radio" value="0" /> Inactive</label> </div> </div> </div> <div class="card-footer text-right"> <button type="button" @click="formaction('reset')" class="btn btn-flat btn-sm btn-danger"><i class="fa fa-redo"></i> Reset</button> <button type="button" @click="formaction('save')" class="btn btn-flat btn-sm btn-primary"><i class="fa fa-save"></i> Save</button> </div> </form> </div> </template> <script> export default { data() { return { dzo_list:[], gewog_list:[], form: new form({ id: '', name: '', grand_parent_field_id:'', parent_field:'', code:'', status:'', record_type:'village', action_type:'edit', }) } }, methods: { remove_err(field_id){ if($('#'+field_id).val()!=""){ $('#'+field_id).removeClass('is-invalid'); } }, loaddzolist(uri = 'masters/loadGlobalMasters/all_active_dzongkhag'){ axios.get(uri) .then(response => { let data = response; this.dzo_list = data.data.data; }) .catch(function (error) { console.log("Error......"+error) }); }, getgewoglist(){ let dzoId=$('#dzo_id').val(); if(dzoId==undefined){ dzoId=this.$route.params.data.dzothroughgewog.id; } let uri = 'masters/all_active_gewog_under_dzongkhag/dzongkhag/'+dzoId; axios.get(uri) .then(response =>{ let data = response; this.gewog_list = data.data.data; }) .catch(function (error){ console.log("Error:"+error) }); }, formaction: function(type){ if(type=="reset"){ this.form.name= ''; this.form.code=''; this.form.status= 1; } if(type=="save"){ this.form.post('/masters/saveGlobalMasters',this.form) .then(() => { Toast.fire({ icon: 'success', title: 'Details updated successfully' }) this.$router.push('/list_village'); }) .catch(() => { console.log("Error......") }) } }, }, created() { this.loaddzolist(); this.getgewoglist(); this.form.name=this.$route.params.data.name; this.form.grand_parent_field_id=this.$route.params.data.dzothroughgewog.id; this.form.parent_field=this.$route.params.data.gewog.id; this.form.status=this.$route.params.data.status; this.form.code=this.$route.params.data.code; this.form.id=this.$route.params.data.id; $('#parent_field').val('this.$route.params.data.majorgroup.id'); }, mounted(){ $('.select2').select2(); $('.select2').select2({ theme: 'bootstrap4' }); $('.select2').on('select2:select', function (){ if($(this).attr('id')=="dzo_id"){ Fire.$emit('changeval') } }); Fire.$on('changeval',()=> { this.getgewoglist(); }); } } </script>
/* Imports: */ var express = require('express'); var bodyParser = require('body-parser'); var path = require('path'); var expressValidator = require('express-validator'); var mongojs = require('mongojs'); var db = mongojs('customerapp', ['users']); var ObjectId = mongojs.ObjectId; var app = express(); /* var logger = function(req, res, next) { console.log('Logging...'); next(); } app.use(logger); */ /* View engine: */ app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); /* Body parser middleware: */ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); /* Set static path: */ app.use(express.static(path.join(__dirname, 'public'))); /* Global vars */ app.use(function(req, res, next) { res.locals.errors = null; next(); }); /* Express validator middleware: */ app.use(expressValidator({ errorFormatter: function(param, msg, value) { var namespace = param.split('.'); var root = namespace.shift(); var formParam = root; while(namespace.length) { formParam += '[' + namespace.shift() + ']'; } return { param: formParam, msg: msg, value: value }; } })); /* GET users: */ app.get('/', function(req, res) { db.users.find(function(err, docs) { console.log(docs); res.render('index', { title: 'customers', users: docs }); }); }); /* POST users: */ app.post('/users/add', function(req, res) { req.checkBody('first_name', 'First name is required').notEmpty(); req.checkBody('last_name', 'Last name is required').notEmpty(); req.checkBody('email', 'Email is required').notEmpty(); var errors = req.validationErrors(); if (errors) { res.render('index', { title: 'customers', users: users, errors: errors }); } else { var newUser = { first_name: req.body.first_name, last_name: req.body.last_name, email: req.body.email }; db.users.insert(newUser, function(err, result) { if (err) { console.log('Insertion error: ' + err); } else { res.redirect('/'); } }); } }); /* DELETE users: */ app.delete('/users/delete/:id', function(req, res) { db.users.remove({_id: ObjectId(req.params.id)}, function(err, result) { if (err) { console.log('Deletion error: ' + err); } else { res.redirect('/'); console.log('works') } }); }); app.listen(3000, function() { console.log('Server started on port 3000'); });
import { useEffect, useState, useContext } from 'react' import { Navigate, useNavigate } from 'react-router-dom' import TaskContext from '../contexts/TaskContext' export default function HomeList() { const {tarefas, listaTarefas, removeTarefa} = useContext(TaskContext) const [loading, setLoading] = useState(false) const navigate = useNavigate() useEffect(() => { async function carrega() { setLoading(true) await listaTarefas() setLoading(false) } carrega() }, []) function handleEditar(key){ navigate('/editar/' + key) } async function handleRemover(key){ await removeTarefa(key) } return ( <> {loading ? <h3>Aguarde...</h3> : <ol> {tarefas.map((tarefa, key) => <li key={key}>{tarefa.nome} - {tarefa.prioridade} <button onClick={() => handleEditar(tarefa.key)}>Editar</button> <button onClick={() => handleRemover(tarefa.key)}>Remover</button> </li>)} </ol> } </> ) }
import { PageContainer } from '@ant-design/pro-layout'; import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons'; import { ActionType, ProColumns, ProTable, TableDropdown, ProForm, ProFormText } from '@ant-design/pro-components'; import { Button, Dropdown, Menu, Space, Tag, Switch, message, Modal } from 'antd'; import React, { useRef, useState } from 'react'; import request from 'umi-request'; import { history } from 'umi'; import { getDrivers } from '@/services/user'; import { deleteDriver } from '@/services/user'; import { changeWork } from '@/services/user'; import Edit from './components/edit'; import Create from './components/add'; import FormItem from 'antd/lib/form/FormItem'; const Index = () => { const actionRef = useRef(); const [editID, setEditId] = useState(undefined); const [isModalVisible, setIsModalVisible] = useState(false); const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false); const handleWorkDriver = async (DriverID) => { const response = await changeWork(DriverID); if (response.status === 'ok') { message.success('修改成功'); } else { message.error('修改失败'); } } const isShowModal = (state) => { setIsModalVisible(state); } const isShowModalEdit = (state, id) => { setEditId(id); setIsModalVisibleEdit(state); } const getData = async (params) => { const response = await getDrivers(); if (response.status === 1) { message.error('身份认证已失效,请重新登录'); history.replace('/login'); } return getDrivers(params) } const deleteDate = async(params)=>{ const response = await deleteDriver(params); if(response.status ==='ok'){ message.success('删除成功'); actionRef.current.reload(); } else{ message.error('删除失败,请检查路线中是否含有该驾驶员信息!'); } } const columns = [ { title: '编号', dataIndex: 'DriverID', }, { title: '姓名', dataIndex: 'DriverName', }, { title: '电话', dataIndex: 'DriverPhone', hideInSearch: true, }, { title: '是否上班', dataIndex: 'is_work', hideInSearch: true, render: (_, record) => <Switch checkedChildren="驾驶中" unCheckedChildren="休息中" defaultChecked={record.is_work === 1} onChange={async () => handleWorkDriver(record.DriverID)} /> }, { title: '编辑', hideInSearch: true, render: (_, record) => <a onClick={() => isShowModalEdit(true, record.DriverID)}>编辑</a> }, { title: '删除', hideInSearch: true, render: (_, record) => <a onClick={() => deleteDate(record.DriverID)}>删除</a> }, ]; return ( <PageContainer> <ProTable columns={columns} actionRef={actionRef} cardBordered request={async (params = {}) => getData(params)} columnsState={{ persistenceKey: 'pro-table-singe-demos', persistenceType: 'localStorage', /* onChange(value) { console.log('value: ', value); }, */ }} rowKey="id" search={{ labelWidth: 'auto', }} pagination={{ pageSize: 10, }} dateFormatter="string" headerTitle="驾驶员列表" toolBarRender={() => [ <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => isShowModal(true)}> 新建 </Button>, ]} /> <Create actionRef={actionRef} isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible} isShowModal={isShowModal} /> { !isModalVisibleEdit ? '' : <Edit actionRef={actionRef} isModalVisible={isModalVisibleEdit} setIsModalVisible={setIsModalVisibleEdit} isShowModal={isShowModalEdit} editID={editID} /> } </PageContainer> ) } export default Index
<%@page import="java.util.ArrayList"%> <%@page import="kr.co.jboard1.bean.ArticleBean"%> <%@page import="java.util.List"%> <%@page import="java.sql.ResultSet"%> <%@page import="kr.co.jboard1.config.SQL"%> <%@page import="java.sql.PreparedStatement"%> <%@page import="java.sql.Connection"%> <%@page import="kr.co.jboard1.config.DBConfig"%> <%@page import="kr.co.jboard1.bean.MemberBean"%> <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <% //세션체크 및 사용자 정보객체 구하기 MemberBean mb = (MemberBean) session.getAttribute("member"); if(mb == null){ response.sendRedirect("/Jboard1/user/login.jsp"); return; // 아래 로직실행을 못하게 프로그램을 여기서 종료 } // 1, 2단계 Connection conn = DBConfig.getConnection(); // 3단계 PreparedStatement psmt = conn.prepareStatement(SQL.SELECT_ARTICLES); // 4단계 ResultSet rs = psmt.executeQuery(); // 5단계 - 결과셋 처리 List<ArticleBean> articles = new ArrayList<>(); while(rs.next()){ ArticleBean article = new ArticleBean(); article.setSeq(rs.getInt(1)); article.setParent(rs.getInt(2)); article.setComment(rs.getInt(3)); article.setCate(rs.getString(4)); article.setTitle(rs.getString(5)); article.setContent(rs.getString(6)); article.setFile(rs.getInt(7)); article.setHit(rs.getInt(8)); article.setUid(rs.getString(9)); article.setRegip(rs.getString(10)); article.setRdate(rs.getString(11)); article.setNick(rs.getString(12)); articles.add(article); } // 6단계 rs.close(); psmt.close(); conn.close(); %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>글목록</title> <link rel="stylesheet" href="/Jboard1/css/style.css"> </head> <body> <div id="wrapper"> <section id="board" class="list"> <h3>글목록</h3> <article> <p> <%= mb.getNick() %>님 반갑습니다. <a href="/Jboard1/user/proc/logout.jsp" class="logout">[로그아웃]</a> </p> <table border="0"> <tr> <th>번호</th> <th>제목</th> <th>글쓴이</th> <th>날짜</th> <th>조회</th> </tr> <% for(ArticleBean article : articles){ %> <tr> <td><%= article.getSeq() %></td> <td><a href="/Jboard1/view.jsp?seq=<%= article.getSeq() %>"><%= article.getTitle() %></a>&nbsp;[<%= article.getComment() %>]</td> <td><%= article.getNick() %></td> <td><%= article.getRdate().substring(2, 10) %></td> <td><%= article.getHit() %></td> </tr> <% } %> </table> </article> <!-- 페이지 네비게이션 --> <div class="paging"> <a href="#" class="prev">이전</a> <a href="#" class="num current">1</a> <a href="#" class="num">2</a> <a href="#" class="num">3</a> <a href="#" class="next">다음</a> </div> <!-- 글쓰기 버튼 --> <a href="/Jboard1/write.jsp" class="btnWrite">글쓰기</a> </section> </div> </body> </html>
package browser; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import io.github.bonigarcia.wdm.WebDriverManager; public class ExplicitWaitExx { public static void main(String[] args) { // Step1: Open browser. WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); // Step2: implicit wait driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Step3: Open application. driver.get("https://chercher.tech/practice/explicit-wait-sample-selenium-webdriver"); // Step4: Click on Link -- driver.findElement(By.xpath("//button[@id='alert']")).click(); // Step5: Explicit wait. WebDriverWait wait = new WebDriverWait(driver, 10); // 5 sec wait.until(ExpectedConditions.alertIsPresent()); // Step6: Handle the alert. driver.switchTo().alert().accept(); } }
package com.kiran.blog_app_rest.payload; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class CommentDto { private Long id; @NotEmpty(message = "Please provide at least 1 character") private String name; @NotBlank(message = "Email cannot be blank") @Email(message = "Please provide a valid email address") private String email; @NotEmpty(message = "Please provide at least 1 character") private String body; }
<%= stylesheet_link_tag 'appposts', :media => "all" ,'data-turbolinks-track': 'reload' %> <% provide(:title, 'Webサービス登録') %> <div class="container"> <h2>Webサービスを登録する</h2> <p>全ての項目を入力して<span class="btn btn-success">Webサービスを登録する</span>をクリックしてください</p> <div class="web-service-post"> <%= form_for @apppost do |f| %> <div class="service-post-contents col-md-6 col-md-offset-1"> <ul> <%= render 'shared/error_messages_post' %> <li><%= f.label :app_name, "Webサービス名" %></li> <li><%= f.text_field :app_name, class: "form-control" %></li> <li><%= f.label :url, "登録サイトのURL" %></li> <li><%= f.text_area :url, class: "form-control" %></li> <!-- <li><%#= f.label :category, "カテゴリ" %></li>--> <!-- <li><%#= f.collection_select :category, Category.all, :id, :name ,:prompt => "カテゴリを選択してください" %></li>--> <li><%= f.label :category_id, "カテゴリ" %></li> <li><%= f.collection_select :category_id, Category.all, :id, :name ,:prompt => "カテゴリを選択してください" %></li> <li><%= f.label :app_image, "表示するサムネイル" %></li> <li><%= f.file_field :app_image, class: "form-control" %></li> <li><%= f.label :author, "製作会社・製作社名" %></li> <li><%= f.text_field :author, class: "form-control" %></li> <li><%= f.label :description, "Webサービスの概要" %></li> <li><%= f.text_area :description, class: "form-control" %></li> <li><%= f.submit "Webサービスを登録する", class: "btn btn-success" %></li> </ul> </div> <% end %> </div> </div>
import { Test, TestingModule } from '@nestjs/testing'; import { UsersService } from './users.service'; import { PrismaService } from '../prisma.service'; import { User } from '@prisma/client'; describe('UsersService', () => { let service: UsersService; let prismaService: PrismaService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [UsersService, PrismaService], }).compile(); service = module.get<UsersService>(UsersService); prismaService = module.get<PrismaService>(PrismaService); }); it('should be defined', () => { expect(service).toBeDefined(); }); describe('create', () => { it('should create a user', async () => { // returned password is hashed in real situation const newUser: User = { id: 'asd', username: 'asd', password: 'asd', roleId: 'asd', createdAt: new Date(), updatedAt: new Date(), }; // Mock the create method of PrismaService jest.spyOn(prismaService.user, 'create').mockResolvedValue(newUser); // Call the create method of UsersService const result = await service.create(newUser); // Check if the result matches the new User expect(result).toEqual(newUser); }); }); describe('findAll', () => { it('should return an array of users', async () => { const mockUsers: User[] = [ { id: 'asd', username: 'asd', password: 'asd', roleId: 'asd', createdAt: new Date(), updatedAt: new Date(), }, { id: 'asd', username: 'asd', password: 'asd', roleId: 'asd', createdAt: new Date(), updatedAt: new Date(), }, ]; // Mock the findMany method of PrismaService jest.spyOn(prismaService.user, 'findMany').mockResolvedValue(mockUsers); // Call the findAll method of UsersService const result = await service.findAll(); // Check if the result matches the mock Users expect(result).toEqual(mockUsers); }); }); describe('findOne', () => { it('should return a user by id', async () => { const userId = 'asd'; const mockUser: User = { id: 'asd', username: 'asd', password: 'asd', roleId: 'asd', createdAt: new Date(), updatedAt: new Date(), }; // Mock the findUnique method of PrismaService jest.spyOn(prismaService.user, 'findUnique').mockResolvedValue(mockUser); // Call the findOne method of UsersService const result = await service.findOne(userId); // Check if the result matches the mock User expect(result).toEqual(mockUser); }); it('should throw an error if User is not found', async () => { const userId = '999'; // Non-existent User id // Mock the findUnique method of PrismaService to return null jest.spyOn(prismaService.user, 'findUnique').mockResolvedValue(null); // Call the findOne method of UsersService const result = await service.findOne(userId); // Check if the result is null expect(result).toBeNull(); }); }); describe('update', () => { it('should update a user', async () => { const userId = 'asd'; const updatedUser: User = { id: 'asd', username: 'asd', password: 'asd', roleId: 'asd', createdAt: new Date(), updatedAt: new Date(), }; // Mock the update method of PrismaService jest.spyOn(prismaService.user, 'update').mockResolvedValue(updatedUser); // Call the update method of UsersService const result = await service.update(userId, updatedUser); // Check if the result matches the updated User expect(result).toEqual(updatedUser); }); }); describe('remove', () => { it('should remove a user', async () => { const userId = 'asd'; const deletedUser: User = { id: 'asd', username: 'asd', password: 'asd', roleId: 'asd', createdAt: new Date(), updatedAt: new Date(), }; // Mock the delete method of PrismaService jest.spyOn(prismaService.user, 'delete').mockResolvedValue(deletedUser); // Call the remove method of UsersService const result = await service.remove(userId); // Check if the result matches the deleted User expect(result).toEqual(deletedUser); }); }); describe('findOneUsername', () => { it('should return a user by username', async () => { const username = 'asd'; const mockUser: User = { id: 'asd', username: 'asd', password: 'asd', roleId: 'asd', createdAt: new Date(), updatedAt: new Date(), }; // Mock the findUnique method of PrismaService jest.spyOn(prismaService.user, 'findUnique').mockResolvedValue(mockUser); // Call the findOneUsername method of UsersService const result = await service.findOneUsername(username); // Check if the result matches the mock User expect(result).toEqual(mockUser); }); it('should return null if user is not found', async () => { const username = 'nonexistentuser'; // Mock the findUnique method of PrismaService to return null jest.spyOn(prismaService.user, 'findUnique').mockResolvedValue(null); // Call the findOneUsername method of UsersService const result = await service.findOneUsername(username); // Check if the result is null expect(result).toBeNull(); }); }); });
<script setup lang="ts"> import type { Form } from "@/types/Forms"; import { ShowChosen } from "@/components"; import { computed, onMounted, reactive, ref, watch } from "vue"; import proteinas from "@/utils/proteinas"; // TODO: depois pensar em passar esse proteinLimit como uma props de um componente pai. Dessa forma, terá opções de marmita, como marmita de 27 reais que tem direito a X proteinas, Y acompanhamentos e etc. const proteinLimit = 3; const props = defineProps<{ modelValue: Form; }>(); const proteinForm = reactive({ fraMilanesa: 0, fraAssado: 0, figaAce: 0, bisSuiAce: 0, fraMolho: 0, }); const emit = defineEmits<{ (e: "update:modelValue", newForm: Form): void; }>(); const proteinasFormated = computed(() => { return Object.entries(proteinas); }); watch(proteinForm, (obj) => { let newForm: Form = props.modelValue; newForm.proteinas = { ...obj }; emit("update:modelValue", newForm); }); const proteinsChosen = computed(() => { return Object.values(proteinForm).reduce( (previous, currentValue) => previous + currentValue, 0 ); }); watch(props.modelValue, (newProps) => { Object.assign(proteinForm, newProps.proteinas); }); onMounted(() => { Object.assign(proteinForm, props.modelValue.proteinas); }); </script> <template> <div> <ShowChosen :all="proteinLimit" :chosen="proteinsChosen"></ShowChosen> <el-form-item prop="proteinas"> <div class="d-flex justify-content-between w-100 mb-3" v-for="[key, label] in proteinasFormated" > <label>{{ label }}</label> <el-input-number v-model="proteinForm[key]" :min="0" :max="proteinsChosen >= proteinLimit ? proteinForm[key] : undefined" /> </div> </el-form-item> </div> </template> <style></style>
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css"> <link href="https://fonts.googleapis.com/css2?family=Mulish:wght@200&family=Roboto&display=swap" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/1.1.3/hamburgers.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100&family=Open+Sans+Condensed:wght@300&family=Titillium+Web:wght@200&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{{ asset('css/app.css') }}"/> <link rel="stylesheet" href="{{ asset('css/burgers.css') }}"/> <title>Surf Store @yield('title')</title> </head> <body> @include('layouts.header') <main class="py-4"> <div> @if(Session::has('errors')) {!! implode('', $errors->all('<div class="btn btn-danger site-info">:message</div>')) !!} @endif @if(session('success')) <div class="btn btn-success site-info">{{ session('success') }}</div> @endif @if(session('info')) <div class="btn btn-info site-info">{{ session('info') }}</div> @endif </div> <div style="margin-top: 180px; margin-bottom: 180px;"> @yield('content') </div> </main> @include('layouts.footer') <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/dropzone.js" crossorigin="anonymous"></script> <script src="https://cdn.ckeditor.com/4.14.0/standard/ckeditor.js"></script> <script src="{{ asset('js/app.js') }}" defer></script> </body> </html>
# MacOS Setting up a development box. ## Profile Info .zprofile : z-shell configuration sourced when logging into account (bash see .bash_profile). Sets environment variables, aliases, etc. .zshrc : new terminal window configuration (bash see .bashrc). Sets shell specific aliases, and custom prompts. - Use shift + command + . to toggle hidden files. - ## Development Tools to Install ## git Just comes for free! ### SVN (Subversion) - [Homebrew Site](https://formulae.brew.sh/formula/subversion) - [Subversion Site](https://subversion.apache.org/) - [SVN Tech Notes](svn.md) ``` brew install subversion ``` ### NVM, Node.js, NPM - [Node.js Tech Notes](node.md) ``` nvm install 18.12 // to align with the current projects. nvm list // to see what else is installed ``` ### SKDMan (Java, maven) - [SDKMan Installation](https://sdkman.io/install) ``` curl -s "https://get.sdkman.io" | bash sdk install java 16-open // Align with current project (I know, I know) sdk install java 17-open // If I want to bring current project up to the LTS sdk install java 21-open // If I want to get up to the most recent LTS sdk install maven 3.9.6 // Align with current projects ``` Install setting.xml at ~/.m2/settings.xml ``` mvn package -U // Makes sure to import all packages and required libraries ``` Setup a virtual /Pro...Suite at ~/Development/Pro...SuiteSynthetic and add /etc/synthetic.conf as: ``` Pro...Suite{1 tab, not spaces}/User/daveb/Development/Pro...SuiteSynthetic ``` Reboot ### Jetbrains - [Toolbox](https://www.jetbrains.com/toolbox-app/) To install and manage the other jetbrain tools. - [IntelliJ Idea](https://www.jetbrains.com/idea/) Make sure the appropriate Java and Maven are already installed and active. Check out the projects into a folder, open that via Idea, and let it analyse the project. Verify the - [WebStorm](https://www.jetbrains.com/webstorm/) - [PyCharm](https://www.jetbrains.com/pycharm/) ### Docker - [Docker](https://www.docker.com) - [DockerHub](https://hub.docker.com) Run through the tutorial to make sure everything is working... Build test-suite-interface Build test-suite-service #### Mongodb #### Mariadb ## Usage
// Copyright 2022 Google LLC // // 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 diff contains code for diffing sync-enabled resources, not // necessarily known at compile time. package diff import ( admissionv1 "k8s.io/api/admission/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/klog/v2" "kpt.dev/configsync/pkg/core" "kpt.dev/configsync/pkg/declared" "kpt.dev/configsync/pkg/lifecycle" "kpt.dev/configsync/pkg/metadata" "kpt.dev/configsync/pkg/status" "kpt.dev/configsync/pkg/syncer/differ" "kpt.dev/configsync/pkg/syncer/reconcile" "sigs.k8s.io/controller-runtime/pkg/client" ) // Operation indicates what action should be taken if we detect a difference // between declared configuration and the state of the cluster. type Operation string const ( // NoOp indicates that no action should be taken. NoOp = Operation("no-op") // Create indicates the resource should be created. Create = Operation("create") // Update indicates the resource is declared and is on the API server, so we should // calculate a patch and apply it. Update = Operation("update") // Delete indicates the resource should be deleted. Delete = Operation("delete") // Error indicates the resource's management annotation in the API server is invalid. Error = Operation("error") // Abandon indicates the resource's management annotation should be removed from the API Server. Abandon = Operation("abandon") // ManagementConflict represents the case where Declared and Actual both exist, // but the Actual one is managed by a Reconciler that supersedes this one. ManagementConflict = Operation("management-conflict") ) // Diff is resource where Declared and Actual do not match. // Both Declared and Actual are client.Object. type Diff struct { // Declared is the resource as it exists in the repository. Declared client.Object // Actual is the resource as it exists in the cluster. Actual client.Object } // Operation returns the type of the difference between the repository and the API Server. func (d Diff) Operation(scope declared.Scope, syncName string) Operation { switch { case d.Declared != nil && d.Actual == nil: // Create Branch. // // We have a declared resource, but nothing on the cluster. So we need to // figure out whether we want to create the resource. return d.createType() case d.Declared != nil && d.Actual != nil: // Update Branch. // // We have a declared and actual resource, so we need to figure out whether // we update the resource. return d.updateType(scope, syncName) case d.Declared == nil && d.Actual != nil: // Delete Branch. // // There is no declaration for the resource, but the resource exists on the // cluster, so we need to figure out whether we delete the resource. return d.deleteType(scope, syncName) default: // d.Declared == nil && d.Actual == nil: // Do nothing. // // We have a undeclared resource and nothing on the cluster. // This could mean that git changed after the delete was detected, // but it's more likely the delete was detected durring an apply run. return NoOp } } func (d Diff) createType() Operation { switch { case differ.ManagementEnabled(d.Declared): // Managed by ConfigSync and it doesn't exist, so create it. // For this case, we can also use `differ.ManagedByConfigSync`, since // the parser adds the `configsync.gke.io/resource-id` annotation to // all the resources in declared.Resources. return Create case differ.ManagementDisabled(d.Declared): // The resource doesn't exist but management is disabled, so take no action. return NoOp default: // There's an invalid management annotation, so there is an error in our logic. return Error } } func (d Diff) updateType(scope declared.Scope, syncName string) Operation { // We don't need to check for owner references here since that would be a // nomos vet error. Note that as-is, it is valid to declare something owned by // another object, possible causing (and being surfaced as) a resource fight. canManage := CanManage(scope, syncName, d.Actual, admissionv1.Update) switch { case differ.ManagementEnabled(d.Declared) && canManage: if d.Actual.GetAnnotations()[metadata.LifecycleMutationAnnotation] == metadata.IgnoreMutation && d.Declared.GetAnnotations()[metadata.LifecycleMutationAnnotation] == metadata.IgnoreMutation { // The declared and actual object both have the lifecycle mutation // annotation set to ignore, so we should take no action as the user does // not want us to make changes to the object. // // If the annotation is on the actual object but not the one declared in // the repository, the update, which uses SSA, would not remove the annotation // from the actual object. However, Config Sync would not respect the annotation // on the actual object since the annotation is not declared in the git repository. // // If the annotation is on the declared object but not the actual one // on the cluster, we need to add it to the one in the cluster. return NoOp } return Update case differ.ManagementEnabled(d.Declared) && !canManage: // This reconciler can't manage this object but is erroneously being told to. return ManagementConflict case differ.ManagementDisabled(d.Declared) && canManage: if metadata.HasConfigSyncMetadata(d.Actual) { manager := d.Actual.GetAnnotations()[metadata.ResourceManagerKey] if manager == "" || manager == declared.ResourceManager(scope, syncName) { return Abandon } } return NoOp case differ.ManagementDisabled(d.Declared) && !canManage: // Management is disabled and the object isn't owned by this reconciler, so // there's nothing to do. return NoOp default: return Error } } func (d Diff) deleteType(scope declared.Scope, syncName string) Operation { // Degenerate cases where we never want to take any action. switch { case !metadata.HasConfigSyncMetadata(d.Actual): // This object has no Nomos metadata, so there's nothing to do. return NoOp case len(d.Actual.GetOwnerReferences()) > 0: // This object is owned by something else. // It may be copying our metadata, so we don't have anything to check. return NoOp case !CanManage(scope, syncName, d.Actual, admissionv1.Delete): // We can't manage this and there isn't a competing declaration for it so, // nothing to do. return NoOp case !differ.ManagedByConfigSync(d.Actual): // d.Actual is not managed by Config Sync, so take no action. return NoOp } // Anything below here has Nomos metadata and is manageable by this reconciler, // and is managed by Config Sync. switch { case lifecycle.HasPreventDeletion(d.Actual): // We aren't supposed to delete this, so just abandon it. // It is never valid to have ACM metadata on non-ACM-managed objects. return Abandon case differ.IsManageableSystemNamespace(d.Actual): // This is a special Namespace we never want to remove. return Abandon default: // The expected path. Delete the resource from the cluster. return Delete } } // UnstructuredActual returns the actual as an unstructured object. func (d Diff) UnstructuredActual() (*unstructured.Unstructured, status.Error) { if d.Actual == nil { return nil, nil } // We just want Unstructured, NOT sanitized. Sanitized removes required fields // such as resourceVersion, which are required for updates. return reconcile.AsUnstructured(d.Actual) } // UnstructuredDeclared returns the declared as an unstructured object. func (d Diff) UnstructuredDeclared() (*unstructured.Unstructured, status.Error) { if d.Declared == nil { return nil, nil } return reconcile.AsUnstructuredSanitized(d.Declared) } // ThreeWay does a three way diff and returns the FileObjectDiff list. // Compare between previous declared and new declared to decide the delete list. // Compare between the new declared and the actual states to decide the create and update. func ThreeWay(newDeclared, previousDeclared, actual map[core.ID]client.Object) []Diff { var diffs []Diff // Delete. for coreID, previousDecl := range previousDeclared { if _, ok := newDeclared[coreID]; !ok { toDelete := Diff{ Declared: nil, Actual: previousDecl, } diffs = append(diffs, toDelete) } } // Create and Update. for coreID, newDecl := range newDeclared { if actual, ok := actual[coreID]; !ok { toCreate := Diff{ Declared: newDecl, Actual: nil, } diffs = append(diffs, toCreate) } else if IsUnknown(actual) { klog.Infof("Skipping diff for resource in unknown state: %s", coreID) } else { toUpdate := Diff{ Declared: newDecl, Actual: actual, } diffs = append(diffs, toUpdate) } } return diffs } // GetName returns the metadata.name of the object being considered. func (d *Diff) GetName() string { if d.Declared != nil { return d.Declared.GetName() } if d.Actual != nil { return d.Actual.GetName() } // No object is being considered. return "" }
/* * Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved. * * 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.ngapps.phototime.core.database.model.tasks import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey import com.ngapps.phototime.core.model.data.task.ScheduledTimeResource import com.ngapps.phototime.core.model.data.task.TaskResource /** * Defines an Pt task resource. */ @Entity(tableName = "task_resources") data class TaskResourceEntity( @PrimaryKey val id: String, val title: String, val description: String, val photos: List<String>, val category: String, @Embedded val scheduledTime: ScheduledTimeEntity, val contacts: List<String>, val note: String, ) data class ScheduledTimeEntity( val start: String, val notification: String ) fun ScheduledTimeEntity.asExternalModel() = ScheduledTimeResource( start = start, notification = notification, ) fun TaskResourceEntity.asExternalModel() = TaskResource( id = id, category = category, title = title, description = description, photos = photos, scheduledTime = scheduledTime.asExternalModel(), contacts = contacts, note = note, )
""" A mixin for all agents that can dispatch KeyEvents. """ # Python standard library from typing import Callable, Union from inspect import signature # Dependencies on other PyTT components from util.interface.api import * # Internal dependencies on modules within the same component from .KeyEventType import KeyEventType from .KeyEvent import KeyEvent from .KeyEventListener import KeyEventListener from .KeyEventHandler import KeyEventHandler ########## # Public entities class KeyEventProcessorMixin: """ A mix-in class that can process key events. """ ########## # Construction def __init__(self): """ The class constructor - DON'T FORGET to call from the constructors of the derived classes that implement this mixin. """ # TODO make list elements WEAK references to actual listeners self.__key_listeners = [] ########## # Operations def add_key_listener(self, l: Union[KeyEventListener, KeyEventHandler]) -> None: """ Registers the specified listener or handler to be notified when a key event is processed. A given listener can be registered at most once; subsequent attempts to register the same listener again will have no effect. """ assert ((isinstance(l, Callable) and len(signature(l).parameters) == 1) or isinstance(l, KeyEventHandler)) if l not in self.__key_listeners: self.__key_listeners.append(l) def remove_key_listener(self, l: Union[KeyEventListener, KeyEventHandler]) -> None: """ Un-registers the specified listener or handler to no longer be notified when a key event is processed. A given listener can be un-registered at most once; subsequent attempts to un-register the same listener again will have no effect. """ assert ((isinstance(l, Callable) and len(signature(l).parameters) == 1) or isinstance(l, KeyEventHandler)) if l in self.__key_listeners: self.__key_listeners.remove(l) @property def key_listeners(self) -> list[Union[KeyEventListener, KeyEventHandler]]: """ The list of all key event listeners registered so far. """ return self.__key_listeners.copy() def process_key_event(self, event : KeyEvent) -> bool: """ Called to process a KeyEvent. @param self: The EventProcessor on which the method has been called. @param event: The key event to process. @return: True if the event was processed, else false. """ assert isinstance(event, KeyEvent) # TODO if the event has NOY been processed, the default # implementation should dispatch it to the "parent" event # processor. for l in self.key_listeners: try: if isinstance(l, KeyEventHandler): match event.event_type: case KeyEventType.KEY_DOWN: l.on_key_down(event) case KeyEventType.KEY_UN: l.on_key_up(event) case KeyEventType.KEY_CHAR: l.on_key_char(event) else: l(event) except Exception as ex: pass # TODO log the exception return event.processed
import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class ChangeUsernamePage extends StatefulWidget { const ChangeUsernamePage({Key? key}) : super(key: key); @override _ChangeUsernamePageState createState() => _ChangeUsernamePageState(); } class _ChangeUsernamePageState extends State<ChangeUsernamePage> { String _newUsername = ''; String _newName = ''; String _errorMessage = ''; bool _isLoading =false; final _formKey = GlobalKey<FormState>(); void _saveChanges(BuildContext context) { final form = _formKey.currentState; if (form!.validate()) { form.save(); setState(() { _isLoading = true; }); _updateUserInformation(); setState(() { _isLoading = false; }); Navigator.pop(context, _newUsername); } } Future<void> _updateUserInformation() async { try { final user = FirebaseAuth.instance.currentUser; if (user != null) { final userId = user.uid; // Check if the new username already exists in Firestore final usernameSnapshot = await FirebaseFirestore.instance .collection('users') .where('username', isEqualTo: _newUsername) .get(); if (usernameSnapshot.docs.isNotEmpty) { setState(() { _errorMessage = 'Username already exists'; }); return; // Exit the function if there's an error } // Update the user's username and name in Firestore await FirebaseFirestore.instance.collection('users').doc(userId).update({ 'username': _newUsername, 'Name': _newName, }); setState(() { _errorMessage = ''; }); Navigator.of(context).pop(); // Return to the previous page } } catch (e) { setState(() { _errorMessage = 'An error occurred. Please try again later.'; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Change Username and Name', style: TextStyle( color: Theme.of(context).brightness == Brightness.dark ? Colors.white : Colors.black)), iconTheme: IconThemeData( color: Theme.of(context).brightness == Brightness.dark ? Colors.white : Colors.black), backgroundColor: Theme.of(context).colorScheme.secondary, ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'Change Username:', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), TextFormField( onChanged: (value) { setState(() { _newUsername = value; }); }, decoration: const InputDecoration( hintText: 'Enter new username', ), validator: (value) { if (value?.isEmpty ?? true) { return 'Please enter a new username'; } return null; }, ), const SizedBox(height: 16.0), const Text( 'Change Name:', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), TextFormField( onChanged: (value) { setState(() { _newName = value; }); }, decoration: const InputDecoration( hintText: 'Enter new name', ), validator: (value) { if (value?.isEmpty ?? true) { return 'Please enter a new name'; } return null; }, ), const SizedBox(height: 16.0), ElevatedButton( key: const Key('saveChangesButton'), onPressed: () => _saveChanges(context), style: ElevatedButton.styleFrom( backgroundColor: Colors.black, // Background color ), child: const Text('Save Changes'), ), if (_errorMessage.isNotEmpty) Text( _errorMessage, style: const TextStyle(color: Colors.red), ), ], ), ), ); } }
const mongoose = require('mongoose'); const productSchema = new mongoose.Schema({ title:{ type:String, required:true, trim:true, }, slug:{ type:String, required:true, unique:true, lowercase: true, }, description:{ type:String, required:true, }, price:{ type:Number, required:true, }, category:{ type: String, required: true, }, brand:{ type:String, required: true, }, quantity:{ type:Number, required:true, }, sold:{ type:Number, default: 0, }, images:[ { public_id: String, url: String, } ], color:[{type: mongoose.Schema.Types.ObjectId, ref:"Color"}], tags:String, ratings:[{ star:Number, comment:String, postedby: {type: mongoose.Types.ObjectId, ref:"User"} }], totalRating: { type:String, default: 0, }, }, { timestamps: true, }); //Export the model module.exports = mongoose.model('Product', productSchema);
import { Link, useNavigate } from "react-router-dom"; import { AuthContext } from "../../context/AuthContextProvider"; import { useContext, useState } from "react"; import avengers_logo from "../../assets/avengers_logo.png"; const Navbar = () => { const { user, userLogout } = useContext(AuthContext); const [showUsername, setShowUsername] = useState(false); let navigate = useNavigate(); const logoutHandler = () => { userLogout() .then(() => { navigate("/login"); }) .catch((err) => { console.log(err); }); }; return ( <div className="navbar bg-base-100 sticky top-0 z-20"> <div className="navbar-start"> <div className="dropdown"> <label tabIndex={0} className="btn btn-ghost lg:hidden"> <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h8m-8 6h16" /> </svg> </label> <ul tabIndex={0} className="menu menu-compact dropdown-content mt-3 p-2 shadow bg-base-100 rounded-box w-52" > <li> <Link to="/">Home</Link> </li> <li tabIndex={0}> <Link className="justify-between" to="/toys"> All Toys </Link> </li> {user && ( <> <li> <Link to="/addtoy">Add A Toy</Link> </li> <li> <Link to="/mytoys">My Toys</Link> </li> </> )} <li> <Link to="/blog">Blogs</Link> </li> </ul> </div> <img src={avengers_logo} className="w-8" alt="" /> <Link className="btn btn-ghost normal-case text-xl" to="/"> Marvel Toyverse </Link> </div> <div className="navbar-center hidden lg:flex"> <ul className="menu menu-horizontal px-1"> <li> <Link to="/">Home</Link> </li> <li tabIndex={0}> <Link to="/toys">All Toys</Link> </li> {user && ( <> <li> <Link to="/addtoy">Add A Toy</Link> </li> <li> <Link to="/mytoys">My Toys</Link> </li> </> )} <li> <Link to="/blog">Blogs</Link> </li> </ul> </div> <div className="navbar-end"> {!user ? ( <Link className="btn bg-[#ed1d24] hover:bg-red-700 rounded-full border-0" to="/login" > Login </Link> ) : ( <div className="dropdown dropdown-end"> <label tabIndex={0} className="btn btn-ghost btn-circle avatar"> <div className="w-10 rounded-full"> <img src={user?.photoURL} onMouseOver={() => setShowUsername(true)} onMouseLeave={() => setShowUsername(false)} /> </div> </label> <ul tabIndex={0} className="mt-3 p-2 shadow menu menu-compact dropdown-content bg-base-100 rounded-box w-52" > <li> <Link className="justify-between">{user?.displayName}</Link> </li> <li> <Link>{user?.email}</Link> </li> <li> <button onClick={logoutHandler}>Logout</button> </li> </ul> </div> )} {showUsername && ( <div className="toast toast-top toast-end mt-14"> <div className="alert alert-info"> <div> <span>{user?.displayName}</span> </div> </div> </div> )} </div> </div> ); }; export default Navbar;
<!DOCTYPE html> <head> <meta charset="utf-8"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Real Estate Website Landing Page</title> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/slick/slick.css"/> <link href="immobilien.css" type="text/css" rel="Stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/95dc93da07.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/slick/slick.min.js"></script> </head> <body> <div id ="header-hero-container"> <header> <div class="flex container"> <a id="logo" href="#">STATED:</a> <!--# is link destination ?--> <nav> <button id="nav-toogle" class="hamburger-menu"> <!--the button tag define a clickable buttom--> <span class="strip"></span> <span class="strip"></span> <span class="strip"></span> </button> <ul id="nav-menü"> <li><a href="#" class="active">Home</a></li> <li><a href="http://www.google.com" targer="_blank">Properties</a></li> <li><a href="#">Agent</a></li> <li><a href="#">About</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li id="close-flyout"><span class="fas fa-times"></span></li> <!--the span tag is an inline container used to mark up a part of atext or a part of a document --> </ul> </nav> </div> </header> <section id="hero"> <div class="fade"></div><!--the div tag definie a division or section in an html document . the div tag is used as a container for html element --> <div class="hero-text"> <h1>Buy and sell real estate properties</h1> <p>Lorem ipsum dolor sit amet consectectur adipisicing elit. Laboriosam assumenda ea quo cupiditate facere deleniti fuga officia</p> </div> </section> </div> <section class="how-it-work"> <div class="container"> <h2>How It Work</h2> <div class="flex"> <div> <span class="fas fa-home"></span> <h4>Find a property.</h4> <p>Lorem ipsum dolor sit amet consectectur adipisicing elit.</p> </div> <div> <span class="fas fa-dollar-signe"></span> <h4>Buy a property.</h4> <p>Lorem ipsum dolor sit amet consectectur adipisicing elit.</p> </div> <div> <span class="fas fa-chart-line"></span> <h4>Inversting</h4> <p>Lorem ipsum dolor sit amet consectectur adipisicing elit.</p> </div> </div> </div> </section> <section id="properties"> <div class="container"> <h2>Properties</h2> <div id="properties-slider" class="slick"> <div> <img src="https://onclickwebdesign.com/wp-content/uploads/property_1.jpg" alt="Property 1"/> <div class="property-detail"> <p class="price">$3,400,000</p> <span class="beds">6 beds</span> <span class="baths">4 baths</span> <span class="sqft">4,250 sqft</span> <address> <!--the adresse tag definie the contact information for the author/owner of a document or article --> 480 12th , unit 14 , san Francisco , CA </address> </div> </div> <div> <img src="https://onclickwebdesign.com/wp-content/uploads/property_2.jpg" alt="Property 1"/> <div class="property-detail"> <p class="price">$3,400,000</p> <span class="beds">6 beds</span> <span class="baths">4 baths</span> <span class="sqft">4,250 sqft.</span> <address> <!--the adresse tag definie the contact information for the author/owner of a document or article --> 480 12th , unit 14 , san Francisco , CA </address> </div> </div> <div> <img src="https://onclickwebdesign.com/wp-content/uploads/property_3.jpg" alt="Property 1"/> <div class="property-detail"> <p class="price">$3,400,000</p> <span class="beds">6 beds</span> <span class="baths">4 baths</span> <span class="sqft">4,250 sqft.</span> <address> <!--the adresse tag definie the contact information for the author/owner of a document or article --> 480 12th , unit 14 , san Francisco , CA </address> </div> </div> <div> <img src="https://onclickwebdesign.com/wp-content/uploads/property_4.jpg" alt="Property 1"/> <div class="property-detail"> <p class="price">$3,400,000</p> <span class="beds">6 beds</span> <span class="baths">4 baths</span> <span class="sqft">4,250 sqft.</span> <address> <!--the adresse tag definie the contact information for the author/owner of a document or article --> 480 12th , unit 14 , san Francisco , CA </address> </div> </div> <div> <img src="https://onclickwebdesign.com/wp-content/uploads/property_1.jpg" alt="Property 1"/> <div class="property-detail"> <p class="price">$3,400,000</p> <span class="beds">6 beds</span> <span class="baths">4 baths</span> <span class="sqft">4,250 sqft.</span> <address> <!--the adresse tag definie the contact information for the author/owner of a document or article --> 480 12th , unit 14 , san Francisco , CA </address> </div> </div> </div> <button class="rounded"> View All Property Listing </button> </div> </section> <section id="argents"> <div class="container"> <h2>Agents</h2> <p class="large-paragrah">Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus minima neque tempora reiciendis.</p> <div class="flex"> <div class="card"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_1.jpg" alt="Realtor 1"/> <h3>Kariara Spencer</h3> <p>Real Estate Agent</p> </div> <div class="card"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_2.jpg" alt="Realtor 1"/> <h3>Dave Simpson</h3> <p>Real Estate Agent</p> </div> <div class="card"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_3.jpg" alt="Realtor 1"/> <h3>Ben Thompson</h3> <p>Real Estate Agent</p> </div> <div class="card"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_4.jpg" alt="Realtor 1"/> <h3>Kyla Stewart</h3> <p>Real Estate Agent</p> </div> <div class="card"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_5.jpg" alt="Realtor 1"> <h3>Rich Moffatt</h3> <p>Real Estate Agent</p> </div> <div class="card"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_6.jpg" alt="Realtor 1"/> <h3>Stuart Redman</h3> <p>Real Estate Agent</p> </div> </div> </div> </section> <section class="the-best"> <div class="flex container"> <img src="https://onclickwebdesign.com/wp-content/uploads/property_1.jpg" alt="property 1"/> <div> <h2>We Are thr Best Real Estate Company</h2> <p class="large-paragrah">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> <p>>Est qui eos quasi ratione nostrum excepturi id recusandae fugit omnis ullam pariatur itaque nisi voluptas impedit Quo suscipit omnis iste velit maxime.</p> <ul> <li>Placeat maxime anini minus</li> <li>Placeat maxime anini minus</li> <li>Placeat maxime anini minus</li> <li>Placeat maxime anini minus</li> <li>Placeat maxime anini minus</li> </ul> <button class="rounded">Learn More</button> </div> </div> </section> <section id="services"> <div class="container"> <h2>Services</h2> <div class="flex"> <div> <div class="fas fa-home"></div> <div class="services-card-right"> <h3>Search Property</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis quis molestiae vitae eligendi at.</p> <a href="#">Learn More</a> </div> </div> <div class="fas fa-dollar-sign"></div> <div class="services-card-right"> <h3> Buy Property</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis quis molestiae vitae eligendi at.</p> <a href="#">learn More</a> </div> </div> <div class="fas fa-chart-line"></div> <div class="services-card-right"> <h3>Inversting</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis quis molestiae vitae eligendi at.</p> <a href="#">learn More</a> </div> </div> <div class="fas fa-building"></div> <div class="services-card-right"> <h3>List a Property</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis quis molestiae vitae eligendi at.</p> <a href="#">learn More</a> </div> </div> <div class="fas fa-search"></div> <div class="services-card-right"> <h3>Property Locator</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis quis molestiae vitae eligendi at.</p> <a href="#">learn More</a> </div> </div> <div class="fas fa-mobile-alt"></div> <div class="services-card-right"> <h3>Stated Apps</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis quis molestiae vitae eligendi at.</p> <a href="#">learn More</a> </div> </div> </div> </div> </section> <section id="testmonials"> <div class="container"> <h2>what our client are saying</h2> <div id="testmonials-slider"> <div> <blockquote> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Officia nostrum vitae explicabo dolore ratione. Quia iure quod ipsa blanditiis sint nulla a nam veritatis ex eos. Dicta molestiae dolorum laudantium.</p> </blockquote> <div class="testmonials-caption"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_7.jpg" alt="Client 7"/> <p>Nick Andros</p> </div> </div> <div> <blockquote> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Officia nostrum vitae explicabo dolore ratione. Quia iure quod ipsa blanditiis sint nulla a nam veritatis ex eos. Dicta molestiae dolorum laudantium.</p> </blockquote> <div class="testmonials-caption"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_5.jpg" alt="Client 7"/> <p>Larry Underwood</p> </div> </div> <div> <blockquote> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Officia nostrum vitae explicabo dolore ratione. Quia iure quod ipsa blanditiis sint nulla a nam veritatis ex eos. Dicta molestiae dolorum laudantium.</p> </blockquote> <div class="testmonials-caption"> <img src="https://onclickwebdesign.com/wp-content/uploads/person_8.jpg" alt="Client 7"/> <p>Fran Goldsmith</p> </div> </div> </div> </div> </section> <section id="contact"> <div class="container"> <h2>Contact Us</h2> <div class="flex"> <div id="form-container"> <form> <!--the form tag is used to created an HTML for user input. the form element can contain one or more of the following form element (input , label ,...)--> <label for="name">Name</label> <input type="text" id="name"/><!--the input tag specifies an input field where the user can enter data . the input element is the most important form element --> <label for="email">Email</label> <input type="text" id="email"/> <label for="subject">Subject</label> <input type="text" id="subject"/> <label for="message">Message</label> <textarea id="message" >Write your message here..</textarea> <bottom class="rounded">Send Message</bottom> </form> </div> <div id="address-container"> <label>Adress</label> <address> 20377 Evergreen Terrace Mountain View , California, USA </address> <label>Phone</label> <a href="#">232-232-2323</a> <label>Email Adresse </label> <a href="#">[email protected]</a> </div> </div> </div> </section> <footer> <div class="flex container"> <div class="footer-about"> <h5>About Stated</h5> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque facere laudantium magnam voluptatum autem. Amet aliquid nesciunt veritatis aliquam</p> </div> <div class="footer-quick-links"> <h5>Quik Links</h5> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Service</a></li> <li><a href="#">testmonials</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> <div class="footer-subscribe"> <h5 class="follow-us">Follow Us</h5> <ul> <li><a href="#"><span class="fab fa-facebook"></span></a></li> <li><a href="#"><span class="fab fa-instagram"></span></a></li> <li><a href="#"><span class="fab fa-twitter"></span></a></li> <li><a href="#"><span class="fab fa-linkedin-in"></span></a></li> </ul> </div> </div> <small> Copyright © 2019 All rights reserved | This template is made with <span class="fa fa-heart"></span> by <a href="https://colorlib.com">Colorlib</a> </small> </footer> <script src="script.js"></script> </body> </html>
import styles, { layout } from '../config/styles' import { features } from '../constants' import Button, { ButtonLogIn } from './Button' import { motion } from 'framer-motion' const FeaturedCard = ({ icon, title, content }) => { return ( <motion.div initial="hidden" whileInView="visible" viewport={{ once: true, amount: 0.5 }} transition={{ duration: 0.7 }} variants={{ hidden: { opacity: 0, x: 50 }, visible: { opacity: 1, x: 0 } }} className={'flex flex-row p-6 rounded-[20px] mb-1 last-of-type:mb-0 feature-card'} > <div className={`w-[64px] h-[64px] rounded-full ${styles.flexCenter} bg-shadowBlue`} > <img src={icon} alt="star" className="w-[50%] h-[50%] object-contain" /> </div> <div className="flex-1 flex flex-col ml-3"> <h1 className="font-gothan font-bold text-white text-[23px] leading-[23.4px] mb-2"> {title} </h1> <p className="font-gotham-book text-white text-[16px] leading-[24px]"> {content} </p> </div> </motion.div> ) } export default function Business () { return ( <section id="kii-explorer" className={layout.section}> <motion.div initial="hidden" whileInView="visible" viewport={{ once: true, amount: 0.5 }} transition={{ duration: 0.7 }} variants={{ hidden: { opacity: 0, x: -50 }, visible: { opacity: 1, x: 0 } }} className={layout.sectionInfo}> <h2 className={styles.heading2}> Leading the Way in Currency{' '} <br className="sm:block hidden" /> and Crypto Exchange </h2> <p className={`${styles.paragraph} max-w-[470px] mt-5`}> We have our own blockchain network and we have the best platform for exchange between currencies and cryptocurrencies. </p> <div className="flex gap-4"> <Button styles="mt-10" /> <ButtonLogIn styles="mt-10" /> </div> </motion.div> <div className={`${layout.sectionImg} flex-col`}> {features.map(feature => ( <FeaturedCard {...feature} key={feature.id} /> ))} </div> </section> ) }
import 'package:hive/hive.dart'; import 'package:json_annotation/json_annotation.dart'; part 'sets.g.dart'; @HiveType(typeId: 2) @JsonSerializable() class Sets { @HiveField(0) final int count; @HiveField(1) final int weight; Sets({required this.count, required this.weight}); Sets copyWith({int? count, int? weight}) { return Sets(count: count ?? this.count, weight: weight ?? this.weight); } factory Sets.fromJson(Map<String, dynamic> json) => _$SetsFromJson(json); Map<String, dynamic> toJson() => _$SetsToJson(this); }
import * as Djs from "discord.js" import * as UseScope from "./use_scope" export interface ReplyOptions extends Djs.BaseMessageOptions { tts?: boolean // TODO ephemeralIfPossible } type ContextGeneralSource = UseScope.AllScopedCommandInteraction | Djs.Message export abstract class Context<SourceT extends ContextGeneralSource = ContextGeneralSource, InGuild extends boolean = boolean> { public source: SourceT constructor(source: SourceT) { this.source = source } public isSourceMessage(): this is this & {source: Djs.Message<InGuild>} { return this.source instanceof Djs.Message } public abstract reply(args: string | ReplyOptions): Promise<Djs.Message> } type ContextGuildSource = UseScope.GuildCommandInteraction | Djs.Message<true> export class ContextGuild extends Context<ContextGuildSource, true> { public guild: Djs.Guild public channel: Djs.GuildTextBasedChannel public member: Djs.GuildMember constructor(source: ContextGuildSource) { super(source) this.guild = source.guild this.channel = source.channel if (source.member === null) throw new Error("Member is null.") this.member = source.member } public override async reply(args: string | ReplyOptions) { if (this.source instanceof Djs.ChatInputCommandInteraction) { return await this.source.followUp(args) } else { // TODO reply chain return await this.source.channel.send(args) } } } type ContextDMSource = UseScope.DMCommandInteraction | Djs.Message<false> export class ContextDM extends Context<ContextDMSource, true> { public user: Djs.User constructor(source: ContextDMSource) { super(source) if (source instanceof Djs.ChatInputCommandInteraction) { this.user = source.user } else if (source instanceof Djs.Message) { this.user = source.author } else { throw new Error("Invalid source.") } } public override async reply(args: string | ReplyOptions) { if (this.source instanceof Djs.ChatInputCommandInteraction) { return await this.source.followUp(args) } else { // TODO reply chain return await this.user.send(args) } } }
(load "./src/lib/util.scm") (define new-withdraw (let ((balance 100)) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")))) (define (make-withdraw balance) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds"))) (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) ; message passing style (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request: MAKE-ACCOUNT" m)))) dispatch) (define random-init nil) (define rand (let ((x random-init)) (lambda () (set! x (rand-update x)) x))) (define (estimate-pi trials) (sqrt (/ 6 (monte-carlo trials cesaro-test)))) (define (cesaro-test) (= (gcd (rand) (rand)) 1)) (define (monte-carlo trials experiment) (define (iter trials-remaining trials-passed) (cond ((= trials-remaining 0) (/ trials-passed trials)) ((experiment) (iter (- trials-remaining 1) (+ trials-passed 1))) (else (iter (- trials-remaining 1) trials-passed)))) (iter trials 0))
document.addEventListener('DOMContentLoaded', function() { const estadosECidades = { "AC": ["Rio Branco"], "AL": ["Maceió"], "AP": ["Macapá"], "AM": ["Manaus"], "BA": ["Salvador"], "CE": ["Fortaleza"], "DF": ["Brasília"], "ES": ["Vitória"], "GO": ["Goiânia"], "MA": ["São Luís"], "MT": ["Cuiabá"], "MS": ["Campo Grande"], "MG": ["Belo Horizonte"], "PA": ["Belém"], "PB": ["João Pessoa"], "PR": ["Curitiba"], "PE": ["Recife"], "PI": ["Teresina"], "RJ": ["Rio de Janeiro"], "RN": ["Natal"], "RS": ["Porto Alegre"], "RO": ["Porto Velho"], "RR": ["Boa Vista"], "SC": ["Florianópolis"], "SP": ["São Paulo"], "SE": ["Aracaju"], "TO": ["Palmas"] }; const estadoSelect = document.getElementById('estado'); const cidadeSelect = document.getElementById('cidade'); // Preenche o select de estados for (const estado in estadosECidades) { const option = document.createElement('option'); option.value = estado; option.textContent = estado; estadoSelect.appendChild(option); } // Atualiza o select de cidades quando um estado é selecionado estadoSelect.addEventListener('change', function() { cidadeSelect.innerHTML = '<option value="">Selecione a cidade</option>'; const cidades = estadosECidades[estadoSelect.value]; if (cidades) { cidades.forEach(function(cidade) { const option = document.createElement('option'); option.value = cidade; option.textContent = cidade; cidadeSelect.appendChild(option); }); } }); // Consulta de CEP document.getElementById('cepForm').addEventListener('submit', function(event) { event.preventDefault(); const estado = estadoSelect.value; const cidade = cidadeSelect.value; const logradouro = document.getElementById('logradouro').value; const url = `https://viacep.com.br/ws/${estado}/${cidade}/${logradouro}/json/`; fetch(url) .then(response => response.json()) .then(data => { const resultadoDiv = document.getElementById('resultado'); resultadoDiv.innerHTML = ''; if (data.length === 0) { resultadoDiv.innerHTML = 'Nenhum CEP encontrado.'; } else { data.forEach(endereco => { const enderecoElem = document.createElement('p'); const complemento = endereco.complemento ? ` (${endereco.complemento})` : ''; const complemento2 = endereco.complemento2 ? ` - Numeração: ${endereco.complemento2}` : ''; enderecoElem.textContent = `CEP: ${endereco.cep} - Logradouro: ${endereco.logradouro}${complemento}${complemento2}`; resultadoDiv.appendChild(enderecoElem); }); } }) .catch(error => { console.error('Erro ao consultar o CEP:', error); const resultadoDiv = document.getElementById('resultado'); resultadoDiv.innerHTML = 'Erro ao consultar o CEP.'; }); }); });
<template> <div class="markdown-body"> <p class="text-2xl pb-5 pt-5 ml-5 text-sans text-white">{{ title }}</p> <div class="p-5"> <div v-if="items.length == 0"> <span class="text-white">No snapshots taken yet</span> </div> <div v-else> <div class="wrapper"> <div v-for="item in items" class="item"> <div class="polaroid"> <img :src="'/images/'+item.filename+'.png'" /> <div class="caption"> <a :href="item.url">Learn</a> </div> </div> </div> </div> </div> </div> </div> </template> <script> import { getItems } from "../../../utils/helpers"; const items = require("../../../utils/items.json"); export default { created() { this.showCameraItems(); }, data() { this.$root.$on("item_added", id => { this.showCameraItems(); }); return { title: "Camera Roll", items: [] }; }, methods: { showCameraItems() { var ids = getItems(); this.items = ids.map(id => items.find(item => item.id == id)); return items; } } }; </script> <style scoped> .wrapper { width: 80%; text-align: center; } .polaroid { background: #fff; padding: 1rem; -webkit-box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); -moz-box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); } .polaroid > img { max-width: 100%; height: auto; } .caption { font-size: 1.8rem; text-align: center; line-height: 2em; } .item .polaroid:before { content: ""; position: absolute; z-index: -1; transition: all 0.4s; } .item:nth-of-type(2n + 1) { transform: scale(0.8, 0.8) rotate(5deg); transition: all 0.35s; } .item:nth-of-type(2n + 1) .polaroid:before { transform: rotate(6deg); height: 20%; width: 47%; bottom: 30px; right: 12px; box-shadow: 0 2.1rem 2rem rgba(0, 0, 0, 0.4); } .item:nth-of-type(2n + 2) { transform: scale(0.8, 0.8) rotate(-5deg); transition: all 0.35s; } .item:nth-of-type(2n + 2) .polaroid:before { transform: rotate(-6deg); height: 20%; width: 47%; bottom: 30px; left: 12px; box-shadow: 0 2.1rem 2rem rgba(0, 0, 0, 0.4); } .item:hover { filter: none; transform: scale(1, 1) rotate(0deg); transition: all 0.4s; } .item:hover .polaroid:before { content: ""; position: absolute; z-index: -1; transform: rotate(0deg); height: 60%; width: 60%; bottom: 0%; right: 10%; box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.2); transition: all 0.35s; } </style>
import { Inject, Injectable, Logger } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, In } from 'typeorm'; import { MessageQueueJob } from 'src/engine/integrations/message-queue/interfaces/message-queue-job.interface'; import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity'; import { DataSourceEntity } from 'src/engine/metadata-modules/data-source/data-source.entity'; import { MessageQueue } from 'src/engine/integrations/message-queue/message-queue.constants'; import { MessageQueueService } from 'src/engine/integrations/message-queue/services/message-queue.service'; import { InjectObjectMetadataRepository } from 'src/engine/object-metadata-repository/object-metadata-repository.decorator'; import { EnvironmentService } from 'src/engine/integrations/environment/environment.service'; import { MessageChannelRepository } from 'src/modules/messaging/common/repositories/message-channel.repository'; import { MessageChannelWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel.workspace-entity'; import { MessagingMessageListFetchJobData, MessagingMessageListFetchJob, } from 'src/modules/messaging/message-import-manager/jobs/messaging-message-list-fetch.job'; @Injectable() export class MessagingMessageListFetchCronJob implements MessageQueueJob<undefined> { private readonly logger = new Logger(MessagingMessageListFetchCronJob.name); constructor( @InjectRepository(Workspace, 'core') private readonly workspaceRepository: Repository<Workspace>, @InjectRepository(DataSourceEntity, 'metadata') private readonly dataSourceRepository: Repository<DataSourceEntity>, @Inject(MessageQueue.messagingQueue) private readonly messageQueueService: MessageQueueService, @InjectObjectMetadataRepository(MessageChannelWorkspaceEntity) private readonly messageChannelRepository: MessageChannelRepository, private readonly environmentService: EnvironmentService, ) {} async handle(): Promise<void> { const workspaceIds = ( await this.workspaceRepository.find({ where: this.environmentService.get('IS_BILLING_ENABLED') ? { subscriptionStatus: In(['active', 'trialing', 'past_due']), } : {}, select: ['id'], }) ).map((workspace) => workspace.id); const dataSources = await this.dataSourceRepository.find({ where: { workspaceId: In(workspaceIds), }, }); const workspaceIdsWithDataSources = new Set( dataSources.map((dataSource) => dataSource.workspaceId), ); for (const workspaceId of workspaceIdsWithDataSources) { await this.enqueueSyncs(workspaceId); } } private async enqueueSyncs(workspaceId: string): Promise<void> { try { const messageChannels = await this.messageChannelRepository.getAll(workspaceId); for (const messageChannel of messageChannels) { if (!messageChannel?.isSyncEnabled) { continue; } await this.messageQueueService.add<MessagingMessageListFetchJobData>( MessagingMessageListFetchJob.name, { workspaceId, connectedAccountId: messageChannel.connectedAccountId, }, ); } } catch (error) { this.logger.error( `Error while fetching workspace messages for workspace ${workspaceId}`, ); this.logger.error(error); return; } } }
<!-- Notes on using the CrowdFlower Instructions <h3><strong>Overview</strong></h3> <!-- BEGIN CUSTOMIZABLE OVERVIEW SECTION --> REPLACE - Rules: The goal of the research is to categorize tweets in different types of sexist categories and non-sexist categories.The information gathered will be used to examine and explain sexism in online platforms. <h3><strong>Steps</strong></h3> <!-- BEGIN CUSTOMIZABLE PROCESS SECTION --> REPLACE - Rules: <ol> <li>please read each sentence carefully. These sentences are in fact tweets </li> <li> please note that you need to categorize the tweets just based on the presented definitions. <li> if one tweet can be classified in two categories, see which part of the sentence is more centric and has focus on</li> <li>There are totally 5 categories.</li> <li>for each category please read the definition, examples and hints carefully</li> <li>consider that tweets are randomly toward a female or male</li> <li>Some of the tweets have hashtags that give you the context.</li> <li>There are no wrong or right answers. Each tweet can be categorized just in one category.</li> <li>read each sentence and put a number which represents the corresponding category in front of the sentence</li> <ul> <li><u>Indirect harassment (#1)</u>:These tweets are around 1. stereotypic and traditional believes about women. or 2. show the inferiority of men over women. Or 3. are indirectly sexist and doesn’t have any swear words.</li> <li>Examples:</li> <li>A wise woman builds her house but a foolish woman tears it down with her hands. </li> <li>Yes, we get it. You’re pretty. Tone down the self promo and just cook.</li> <li>It’s less of #adaywithoutwomen and more of a day without feminists, which to be quite honest, sounds lovely.</li></ul> <ul> <li><u>Information threat (#2): </u>threats toward women that their information will be stolen and revealed or will be misused.</li> <li>Examples:</li> <li>if you are seriously gonna try to change gamin, I will hack your account and put gay porn everywhere. </li> <li>I have all your names and ledger. 5000$ a month or I torch you all over the web, forever.</li></ul> <ul> <li><u>Sexual harassment (#3): </u>these tweets are 1. contain insulting words, name calling, words of anger and violence.2. force toward sex.</li> <li>Examples:</li> <li>damn girls, you are fine. </li> <li>f..k that cunt, I would with my fist.</li> </ul> <ul> <li><u>Physical Harassment (#4): </u>these tweets are about 1. Threats on female biology attributes, beauty of women.2. considering women as se objects.3. implying sense of ignorance or lack of attractiveness. 4. Implying lack of physical or mental ability of women. 5. Using humor toward the female body. Tweets can contain insulting words or violence.</li> <li><u>Hint:</u></li> female body getting disease, pain, breaks, disgusted. Comments on weight, breast size, hotness, lack of hotness. <li>Examples:</li> <li>Just putting it out there, you deserve all those deaths you are getting. </li> <li>don’t pull the gender card. You are not being harassed because you are a woman. It is because you are an ignorant cunt.</li> <li>the menus look like they were made by a 5 year-old little girl. In this case just the mental age of a 5-year-old girl I guess.</li> </ul> <ul> <li><u>Not sexist (#5): </u>these tweets are not in the previous categories and are not sexist.</li> </ul> </ol> <!-- END CUSTOMIZABLE PROCESS SECTION --> <hr> <h3><strong>Rules and Tips</strong></h3> <!-- BEGIN CUSTOMIZABLE RULES AND TIPS SECTION --> REPLACE - Rules: Use green headers for positive/"DO THIS", yellow for warning/"be careful of", red for bad/"DO NOT". <!-- BEGIN DO THIS SECTION --> <h4 style="color:#8cc63e;"><strong>Do This</strong></h4> REPLACE: imagine that they were the author of the post. <ul> </ul> <br> <hr> <h3><strong>Examples</strong></h3> <hr> <h3><strong>Thank You!</strong></h3> <!-- BEGIN CUSTOMIZABLE THANK YOU SECTION --> REPLACE - Rules: Dear Contributor, thank you for your careful work in this job! You've helped our organization improve with your contributions today! <!-- END CUSTOMIZABLE THANK YOU SECTION -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FabricJS editor</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> <link rel="stylesheet" href="./style.css"> <script src="https://unpkg.com/[email protected]/dist/fabric.min.js"></script> </head> <body class="w-100 min-vh-100 d-flex flex-column"> <header class="w-100 shadow bg-secondary-light"> <ul class="nav nav-pills p-2 d-flex flex-col-gap-1"> <li class="nav-item"> <button class="nav-link active" id="btn-select"><i class="bi bi-arrows-move"></i> <small>Selection</small></button> </li> <li class="nav-item"> <button class="nav-link" id="btn-shapes"><i class="bi bi-square-fill"></i> <small>Shapes</small></button> </li> <li class="nav-item"> <button class="nav-link" id="btn-text"><i class="bi bi-cursor-text"></i> <small>Text</small></button> </li> <li class="nav-item"> <button class="nav-link" id="btn-settings"><i class="bi bi-gear"></i> <small>Settings</small></button> </li> </ul> </header> <main class="w-100 flex-grow-1 position-relative d-flex"> <section class="position-absolute top-0 start-0 bg-secondary-dark shadow h-100 w-20" id="left-menu"> <p class="fs-3 text-center mx-2">Title</p> <hr class="mx-3"> <section id="left-sub-menu"></section> <button id="btn-collapse" class="btn bg-secondary-dark"><i></i></button> </section> <section class="flex-grow-1 d-flex align-items-center justify-content-center"> <canvas id="fabric"></canvas> </section> <section class="position-absolute top-0 end-0 bg-secondary-dark shadow h-100 w-20" id="right-menu"> <p class="fs-3 text-center mx-2">Layers</p> <hr class="mx-3"> <section id="right-sub-menu"> <ul class="list-group list-group-flush"></ul> <div class="d-flex"> <button class="btn btn-primary shadow-sm flex-grow-1 mx-2 mt-3" onclick="addNewLayer()">Add layer</button> </div> </section> <button id="btn-collapse" class="btn bg-secondary-dark"><i></i></button> </section> </main> <footer> </footer> <script> let canvas = new fabric.Canvas("fabric"); canvas.originalH = canvas.height; canvas.originalW = canvas.width; let leftMenu = document.getElementById("left-menu"); let rightMenu = document.getElementById("right-menu"); let shapes = [ { name: "square", svg: `<svg viewBox="-10 -10 120 120"><polygon points="0 0, 0 100, 100 100, 100 0" stroke-width="8" stroke="currentColor" fill="none"></polygon></svg>` }, { name: "diamond", svg: `<svg viewBox="-8 -8 120 120"><polygon fill="none" stroke-width="8" stroke="currentColor" points="50 0, 85 50, 50 100, 15 50"></polygon></svg>` }, { name: "circle", svg: `<svg viewBox="-2 -2 100 100"><circle cx="50" cy="50" r="40" stroke="currentColor" stroke-width="8" fill="none"></circle></svg>`, } ] canvas.on("selection:created", function (e) { let activeObject = canvas.getActiveObject(); ShowSelectionMenu(activeObject); }) canvas.on("selection:created", function (e) { let activeObject = canvas.getActiveObject(); ShowSelectionMenu(activeObject); }) canvas.on("object:modified", function (e) { canvas.renderAll(); }) let buttons = { select: document.getElementById("btn-select"), shapes: document.getElementById("btn-shapes"), text: document.getElementById("btn-text"), settings: document.getElementById("btn-settings"), } let activeButton = buttons.select; for(const button of Object.values(buttons)) { button.addEventListener("click", function() { setButtonActive(button); changeMode(); }); } function setButtonActive(button) { button.classList.add("active"); activeButton.classList.remove("active"); activeButton = button; } leftMenu.querySelector("#btn-collapse").addEventListener("click", function() { if(leftMenu.classList.contains("slide-collapse")) { leftMenu.classList.remove("slide-collapse"); leftMenu.classList.add("slide-expand"); } else { leftMenu.classList.remove("slide-expand"); leftMenu.classList.add("slide-collapse"); } }); rightMenu.querySelector("#btn-collapse").addEventListener("click", function() { if(rightMenu.classList.contains("slide-collapse")) { rightMenu.classList.remove("slide-collapse"); rightMenu.classList.add("slide-expand"); } else { rightMenu.classList.remove("slide-expand"); rightMenu.classList.add("slide-collapse"); } }); let layers = []; let curLayerId = 0; let layerList = rightMenu.querySelector("#right-sub-menu ul"); addNewLayer(); function addNewLayer() { let newIndex = layers.length layers.splice(0, 0, { id: newIndex, objects: [], locked: false, visible: true }); addLayerHTML(newIndex); updateLayerHtmlOrder(); ChangeActiveLayer(newIndex); } function addLayerHTML(id) { // <li class="list-group-item bg-unset" data-layer-id="0"> // <div class="d-flex align-items-center flex-col-gap-1"> // <span class="flex-grow-1">Layer name</span> // <div class="btn-group" role="group" aria-label="Layer buttons"> // <button type="button" class="btn btn-outline-secondary" onclick="ChangeLockState(this)"><i class="bi bi-lock"></i></button> // <button type="button" class="btn btn-outline-secondary" onclick="ChangeVisibility(this)"><i class="bi bi-eye"></i></button> // </div> // </div> // </li> let item = document.createElement("li"); item.classList.add("list-group-item", "bg-unset", "border-0"); item.setAttribute("data-layer-id", id); item.addEventListener("click", () => ChangeActiveLayer(id)); let layerHolder = document.createElement("div"); layerHolder.classList.add("d-flex", "align-items-center", "flex-col-gap-1"); let layerName = document.createElement("span"); layerName.classList.add("flex-grow-1"); layerName.innerText = `Layer ${id + 1}`; let buttonGroup = document.createElement("div"); buttonGroup.classList.add("btn-group"); buttonGroup.role = "group"; buttonGroup.ariaLabel = "Layer buttons"; let btnLock = document.createElement("button"); btnLock.type = "button"; btnLock.name = "lock"; btnLock.classList.add("btn", "btn-outline-secondary"); btnLock.addEventListener("click", () => ChangeLockState(id)); let btnLockIcon = document.createElement("i"); btnLockIcon.classList.add("bi", "bi-unlock"); let btnVisible = document.createElement("button"); btnVisible.type = "button"; btnVisible.name = "visible" btnVisible.classList.add("btn", "btn-outline-secondary"); btnVisible.addEventListener("click", () => ChangeVisibility(id)); let btnVisibleIcon = document.createElement("i"); btnVisibleIcon.classList.add("bi", "bi-eye"); let btnUp = document.createElement("button"); btnUp.type = "button"; btnUp.classList.add("btn", "btn-outline-secondary"); btnUp.addEventListener("click", () => MoveLayerUp(id)); let btnUpIcon = document.createElement("i"); btnUpIcon.classList.add("bi", "bi-arrow-up"); let btnDown = document.createElement("button"); btnDown.type = "button"; btnDown.classList.add("btn", "btn-outline-secondary"); btnDown.addEventListener("click", () => MoveLayerDown(id)); let btnDownIcon = document.createElement("i"); btnDownIcon.classList.add("bi", "bi-arrow-down"); btnLock.appendChild(btnLockIcon); btnVisible.appendChild(btnVisibleIcon); btnUp.appendChild(btnUpIcon); btnDown.appendChild(btnDownIcon); buttonGroup.appendChild(btnLock); buttonGroup.appendChild(btnVisible); buttonGroup.appendChild(btnUp); buttonGroup.appendChild(btnDown); layerHolder.appendChild(layerName); layerHolder.appendChild(buttonGroup); item.appendChild(layerHolder); layerList.appendChild(item); } function updateLayerHtmlOrder() { for(const child of layerList.children) { let id = child.getAttribute("data-layer-id"); child.style.order = layers.findIndex(l => l.id == id); } } function ChangeLockState(id) { let layer = layers.find(l => l.id == id); layerList.querySelector(`li[data-layer-id="${id}"] button[name="lock"] i`).classList.toggle("bi-lock"); layerList.querySelector(`li[data-layer-id="${id}"] button[name="lock"] i`).classList.toggle("bi-unlock"); layer.locked = !layer.locked; updateLock(layer); } function ChangeVisibility(id) { let layer = layers.find(l => l.id == id); layerList.querySelector(`li[data-layer-id="${id}"] button[name="visible"] i`).classList.toggle("bi-eye"); layerList.querySelector(`li[data-layer-id="${id}"] button[name="visible"] i`).classList.toggle("bi-eye-slash"); layer.visible = !layer.visible; updateVisibility(layer); } function ChangeActiveLayer(id) { let curLayer = layers.find(l => l.id == curLayerId); let layer = layers.find(l => l.id == id); layerList.querySelector(`li[data-layer-id="${curLayerId}"]`).classList.remove("layer-active"); updateSelectables(curLayer, false); curLayerId = id; layerList.querySelector(`li[data-layer-id="${curLayerId}"]`).classList.add("layer-active"); updateSelectables(layer, true); } function MoveLayerUp(id) { let layer = layers.find(l => l.id == id); let layerIndex = layers.indexOf(layer); if(layerIndex === 0) return; let nextLayer = layers[layerIndex - 1]; moveLayerAbove(layer, nextLayer); updateLayerHtmlOrder(); } function MoveLayerDown(id) { let layer = layers.find(l => l.id == id); let layerIndex = layers.indexOf(layer); if(layerIndex === layers.length - 1) return; let nextLayer = layers[layerIndex + 1]; moveLayerAbove(nextLayer, layer); updateLayerHtmlOrder(); } function updateLock(layer) { for(const obj of layer.objects) { obj.set({ lockMovementX: layer.locked, lockMovementY: layer.locked, lockRotation: layer.locked, lockScalingX: layer.locked, lockScalingY: layer.locked, lockUniScaling: layer.locked, lockSkewingX: layer.locked, lockSkewingY: layer.locked, lockScalingFlip: layer.locked }) } } function updateVisibility(layer) { for(const obj of layer.objects) { obj.opacity = layer.visible ? 1 : 0; obj.evented = layer.visible; obj.selectable = layer.visible; } canvas.renderAll(); } function updateSelectables(layer, selectable) { for(const obj of layer.objects) { obj.evented = selectable; obj.selectable = selectable; } } function moveLayerAbove(layer, targetLayer) { let targetLayerZ = canvas.getObjects().indexOf(targetLayer.objects[targetLayer.objects.length - 1]); for(const obj of layer.objects) { canvas.moveTo(obj, targetLayerZ + layer.objects.indexOf(obj)); } array_move(layers, layers.indexOf(layer), layers.indexOf(targetLayer)); canvas.renderAll(); } function changeMode() { switch(activeButton) { case buttons.shapes: ShowShapesMenu(); break; case buttons.text: ShowTextMenu(); break; case buttons.settings: ShowSettingsMenu(); break; } } function ShowShapesMenu() { leftMenu.querySelector("p").innerText = "Shapes"; let submenu = leftMenu.querySelector("#left-sub-menu"); submenu.innerHTML = ` <div class="flex-row-gap-1 flex-col-gap-1 d-flex flex-wrap mx-2 justify-content-start" id="submenu"></div> `; for(const shape of shapes) { let div = document.createElement("div"); let button = document.createElement("button"); button.classList.add("btn", "btn-primary", "text-white"); button.dataset.shape = shape.name; button.innerHTML = `<svg viewBox="0 0 10 10" width="20">${shape.svg}</svg>`; button.addEventListener("click", function() { CreateFabricSVG(shape.svg); }); div.appendChild(button); submenu.querySelector("#submenu").appendChild(div); } } function CreateFabricSVG(svg) { fabric.loadSVGFromString(svg, (objects, options) => { let obj = fabric.util.groupSVGElements(objects, options) obj.strokeUniform = true obj.strokeLineJoin = 'miter' obj.scaleToWidth(100) obj.scaleToHeight(100) obj.set({ left: 0, top: 0 }) addObjectToCanvas(obj); }) } function addObjectToCanvas(obj) { let layer = layers.find(l => l.id == curLayerId); if(layer.objects.length != 0) { let insertIdx = canvas.getObjects().indexOf(layer.objects[layer.objects.length - 1]) + 1; canvas.insertAt(obj, insertIdx, false); } else canvas.add(obj); canvas.renderAll(); layer.objects.push(obj); } function ShowSettingsMenu() { leftMenu.querySelector("p").innerText = "Settings"; let submenu = leftMenu.querySelector("#left-sub-menu"); submenu.innerHTML = ` <div class="d-flex flex-row-gap-1 flex-column" id="canvas-settings"></div> <div class="d-flex flex-row-gap-1 flex-column mt-3" id="canvas-background"></div> ` addNumberField(submenu.querySelector("#canvas-settings"), "Canvas Width", canvas.width, 1, (value) => { canvas.setWidth(value); canvas.originalW = value; }); addNumberField(submenu.querySelector("#canvas-settings"), "Canvas Height", canvas.height, 1, (value) => { canvas.setHeight(value); canvas.originalH = value; }); addImageUpload(submenu.querySelector("#canvas-background"), "Background Image", (dataUri) => { fabric.Image.fromURL(dataUri, (img) => { img.set({ left: 0, top: 0 }) img.scaleToHeight(canvas.originalH) img.scaleToWidth(canvas.originalW) canvas.setBackgroundImage(img) canvas.renderAll() }) }); } function addNumberField(parent, title, initialValue, minValue, callback) { let div = document.createElement("div"); div.classList.add("d-flex", "justify-content-between", "mx-3", "align-items-center"); let label = document.createElement("label"); label.innerText = title; label.classList.add("fs-5"); div.appendChild(label); let input = document.createElement("input"); input.type = "number"; input.min = minValue; input.value = initialValue; input.addEventListener("change", function() { callback(input.value); }); div.appendChild(input); parent.appendChild(div); } function ShowSelectionMenu(object) { setButtonActive(buttons.select); leftMenu.querySelector("p").innerText = "Selection"; let submenu = leftMenu.querySelector("#left-sub-menu"); submenu.innerHTML = ` <div class="d-flex flex-row-gap-1 flex-column" id="colors"></div> `; addColorPicker(submenu.querySelector("#colors"), "Stroke Color", object.stroke, (color) => { object.set({stroke: `#${color.toHex()}`}); canvas.renderAll(); }) addColorPicker(submenu.querySelector("#colors"), "Fill Color", object.fill, (color) => { object.set({fill: `#${color.toHex()}`}); canvas.renderAll(); }) } function addColorPicker(parent, title, initialValue, callback) { let div = document.createElement("div"); div.classList.add("d-flex", "justify-content-between", "mx-3", "align-items-center"); let label = document.createElement("label"); label.innerText = title; label.classList.add("fs-5"); div.appendChild(label); let input = document.createElement("input"); input.type = "color"; input.value = initialValue; input.addEventListener("change", function() { callback(new fabric.Color(input.value)); }); div.appendChild(input); parent.appendChild(div); } function processImageFile(file) { return new Promise((resolve) => { let reader = new FileReader() reader.onload = (f) => { resolve(f.target.result); } reader.readAsDataURL(file) }) } function addImageUpload(parent, title, callback, allowedTypes=["image/jpeg", "image/jpg", "image/png"]) { let div = document.createElement("div"); div.classList.add("d-flex", "justify-content-between", "mx-3", "align-items-center"); let label = document.createElement("label"); label.innerText = title; label.classList.add("fs-5"); div.appendChild(label); let button = document.createElement("button"); button.classList.add("btn", "btn-primary"); button.innerHTML = `<i class="bi bi-cloud-arrow-up"></i> Upload`; button.addEventListener("click", () => { let modal; let input = document.createElement("input"); input.classList.add("hidden"); input.type = "file"; input.accept = allowedTypes.join(","); input.addEventListener("change", () => { if (input.files.length === 0) return; if(!allowedTypes.includes(input.files[0].type)) return; processImageFile(input.files[0]) .then((data) => { callback(data); input.remove(); modal.remove(); }); }) modal = createFileDropModal(allowedTypes, input, (file) => { processImageFile(file) .then((data) => { callback(data); input.remove(); modal.remove(); }) }); document.body.appendChild(input); }) div.appendChild(button); parent.appendChild(div); } function createFileDropModal(allowedTypes, input, callback) { let modal = document.createElement("div"); modal.classList.add("modal", "d-block"); modal.innerHTML = ` <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Select an image</h5> <button type="button" id="btn-close" class="btn-close" aria-label="Close"></button> </div> <div class="modal-body"> <div class="d-flex justify-content-center flex-column"> <p> Click here to select an image or drop an image file </p> <p class="text-center"><small id="modal-message"></small></p> </div> </div> </div> </div> `; modal.querySelector("#modal-message").innerText = `(Only ${allowedTypes.map(t => t.split("/")[1].toUpperCase()).join(", ")} images are supported.)`; modal.querySelector("#btn-close").addEventListener("click", (e) => { e.preventDefault(); modal.remove(); input.remove(); }); modal.querySelector(".modal-body").addEventListener("click", (e) => { input.click(); }); modal.querySelector(".modal-body").addEventListener("dragover", (e) => { e.preventDefault(); e.stopPropagation(); }); modal.querySelector(".modal-body").addEventListener("dragleave", (e) => { e.preventDefault(); e.stopPropagation(); }); modal.querySelector(".modal-body").addEventListener("drop", (e) => { e.preventDefault(); e.stopPropagation(); if (e.dataTransfer) { if (e.dataTransfer.files.length) { let files = e.dataTransfer.files callback(files[0]); } } }); document.body.appendChild(modal); return modal; } function array_move(arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length + 1; while (k--) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); }; </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> </body> </html>
use crate::postgres_config::PostgresConfig; use chrono::{TimeZone, Utc}; use log::*; use mango_feeds_connector::metrics::{MetricType, MetricU64, Metrics}; use postgres_query::Caching; use service_mango_fills::*; use services_mango_lib::postgres_configuration::PostgresConfiguration; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Duration, }; use tokio_postgres::Client; async fn postgres_connection( config: &PostgresConfig, metric_retries: MetricU64, metric_live: MetricU64, exit: Arc<AtomicBool>, ) -> anyhow::Result<async_channel::Receiver<Option<tokio_postgres::Client>>> { let (tx, rx) = async_channel::unbounded(); let config = config.clone(); let lib_config = PostgresConfiguration { connection_string: config.connection_string.clone(), allow_invalid_certs: config.allow_invalid_certs, tls: config.tls.clone(), }; let mut initial = Some(services_mango_lib::postgres_connection::connect(&lib_config).await?); let mut metric_retries = metric_retries; let mut metric_live = metric_live; tokio::spawn(async move { loop { // don't acquire a new connection if we're shutting down if exit.load(Ordering::Relaxed) { warn!("shutting down fill_event_postgres_target..."); break; } let (client, connection) = match initial.take() { Some(v) => v, None => { let result = services_mango_lib::postgres_connection::connect(&lib_config).await; match result { Ok(v) => v, Err(err) => { warn!("could not connect to postgres: {:?}", err); tokio::time::sleep(Duration::from_secs( config.retry_connection_sleep_secs, )) .await; continue; } } } }; tx.send(Some(client)).await.expect("send success"); metric_live.increment(); let result = connection.await; metric_retries.increment(); metric_live.decrement(); tx.send(None).await.expect("send success"); warn!("postgres connection error: {:?}", result); tokio::time::sleep(Duration::from_secs(config.retry_connection_sleep_secs)).await; } }); Ok(rx) } async fn update_postgres_client<'a>( client: &'a mut Option<postgres_query::Caching<tokio_postgres::Client>>, rx: &async_channel::Receiver<Option<tokio_postgres::Client>>, config: &PostgresConfig, ) -> &'a postgres_query::Caching<tokio_postgres::Client> { // get the most recent client, waiting if there's a disconnect while !rx.is_empty() || client.is_none() { tokio::select! { client_raw_opt = rx.recv() => { *client = client_raw_opt.expect("not closed").map(postgres_query::Caching::new); }, _ = tokio::time::sleep(Duration::from_secs(config.fatal_connection_timeout_secs)) => { error!("waited too long for new postgres client"); std::process::exit(1); }, } } client.as_ref().expect("must contain value") } async fn process_update(client: &Caching<Client>, update: &FillUpdate) -> anyhow::Result<()> { let market = &update.market_key; let seq_num = update.event.seq_num as i64; let fill_timestamp = Utc.timestamp_opt(update.event.timestamp as i64, 0).unwrap(); let price = update.event.price; let quantity = update.event.quantity; let slot = update.slot as i64; let write_version = update.write_version as i64; if update.status == FillUpdateStatus::New { // insert new events let query = postgres_query::query!( "INSERT INTO transactions_v4.perp_fills_feed_events (market, seq_num, fill_timestamp, price, quantity, slot, write_version) VALUES ($market, $seq_num, $fill_timestamp, $price, $quantity, $slot, $write_version) ON CONFLICT (market, seq_num) DO NOTHING", market, seq_num, fill_timestamp, price, quantity, slot, write_version, ); let _ = query.execute(&client).await?; } else { // delete revoked events let query = postgres_query::query!( "DELETE FROM transactions_v4.perp_fills_feed_events WHERE market=$market AND seq_num=$seq_num", market, seq_num, ); let _ = query.execute(&client).await?; } Ok(()) } pub async fn init( config: &PostgresConfig, metrics_sender: Metrics, exit: Arc<AtomicBool>, ) -> anyhow::Result<async_channel::Sender<FillUpdate>> { // The actual message may want to also contain a retry count, if it self-reinserts on failure? let (fill_update_queue_sender, fill_update_queue_receiver) = async_channel::bounded::<FillUpdate>(config.max_queue_size); let metric_con_retries = metrics_sender.register_u64( "fills_postgres_connection_retries".into(), MetricType::Counter, ); let metric_con_live = metrics_sender.register_u64("fills_postgres_connections_alive".into(), MetricType::Gauge); // postgres fill update sending worker threads for _ in 0..config.connection_count { let postgres_account_writes = postgres_connection( config, metric_con_retries.clone(), metric_con_live.clone(), exit.clone(), ) .await?; let fill_update_queue_receiver_c = fill_update_queue_receiver.clone(); let config = config.clone(); let mut metric_retries = metrics_sender.register_u64("fills_postgres_retries".into(), MetricType::Counter); tokio::spawn(async move { let mut client_opt = None; loop { // Retrieve up to batch_size updates let mut batch = Vec::new(); batch.push( fill_update_queue_receiver_c .recv() .await .expect("sender must stay alive"), ); while batch.len() < config.max_batch_size { match fill_update_queue_receiver_c.try_recv() { Ok(update) => batch.push(update), Err(async_channel::TryRecvError::Empty) => break, Err(async_channel::TryRecvError::Closed) => { panic!("sender must stay alive") } }; } info!( "updates, batch {}, channel size {}", batch.len(), fill_update_queue_receiver_c.len(), ); let mut error_count = 0; loop { let client = update_postgres_client(&mut client_opt, &postgres_account_writes, &config) .await; let mut results = futures::future::join_all( batch.iter().map(|update| process_update(client, update)), ) .await; let mut iter = results.iter(); batch.retain(|_| iter.next().unwrap().is_err()); if !batch.is_empty() { metric_retries.add(batch.len() as u64); error_count += 1; if error_count - 1 < config.retry_query_max_count { results.retain(|r| r.is_err()); warn!("failed to process fill update, retrying: {:?}", results); tokio::time::sleep(Duration::from_secs(config.retry_query_sleep_secs)) .await; continue; } else { error!("failed to process account write, exiting"); std::process::exit(1); } }; break; } } }); } Ok(fill_update_queue_sender) }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateContactsSiteTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contacts_site', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->string('name', 50); $table->string('phone', 20); $table->string('email', 50); $table->integer('contact_reason'); $table->text('message'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contacts_site'); } }
import faker from "@faker-js/faker"; import { IMovieTrending } from "@/src/domain/models/movies"; import { HttpStatusCode } from "@/src/data/protocols/http"; import { UnexpectedError } from "@/src/domain/errors/enexpected-error"; import { OverloadedError } from "@/src/domain/errors/server-overloaded"; import { mockMovieTrending } from "@/tests/domain/mocks/mock-movie-trending"; import { RemoteMovieTrending } from "@/src/data/usecases/movie/remote-movie-trending"; import { HttpClientSpy } from "../../mocks/mock-http-client"; type SutTypes = { sut: RemoteMovieTrending; httpClientSpy: HttpClientSpy<IMovieTrending[]>; }; const makeSut = (url: string = faker.internet.url()): SutTypes => { const httpClientSpy = new HttpClientSpy<IMovieTrending[]>(); const sut = new RemoteMovieTrending(url, httpClientSpy); return { sut, httpClientSpy, }; }; describe("RemoteMoviePopular", () => { test("Shoul call HttpPostClient with correct Url", async () => { const url = `some_url`; const { sut, httpClientSpy } = makeSut(url); await sut.exec(); expect(httpClientSpy.url).toBe(url); }); test("Shoul call HttpPostClient with correct Url and Genres", async () => { const url = `some_url`; const { sut, httpClientSpy } = makeSut(url); await sut.exec("comedy"); expect(httpClientSpy.url).toBe(url + "?genres=comedy"); }); test("Should throw an error if httpClient returns 401", () => { const { sut, httpClientSpy } = makeSut(); httpClientSpy.response = { statusCode: HttpStatusCode.unauthorized, }; const promise = sut.exec("movie"); expect(promise).rejects.toThrow(new UnexpectedError()); }); test("Should throw an message error if httpClient returns 503", () => { const { sut, httpClientSpy } = makeSut(); httpClientSpy.response = { statusCode: HttpStatusCode.serverOverload, }; const promise = sut.exec(); expect(promise).rejects.toThrow(new OverloadedError()); }); test("Should return an MoviePopularInfo if HttpPostClient returns 200", async () => { const { sut, httpClientSpy } = makeSut(); const httpResult = mockMovieTrending(); httpClientSpy.response = { statusCode: HttpStatusCode.ok, body: httpResult, }; const account = await sut.exec("movie"); expect(account).toEqual(httpResult); }); });
import enums from "#utils/enums.mjs"; import {HttpStatus} from "#structs/route.mjs"; import {getModel} from "#db/index.mjs"; import {UniqueConstraintError, ValidationError} from "sequelize"; import {randomString} from "#utils/strings.mjs"; export async function createSession (res, payload) { const { name, gender, skin, csp } = payload // Presence if (!name) return res.status(HttpStatus.BAD_REQUEST).json('No session name provided!') if (!gender) return res.status(HttpStatus.BAD_REQUEST).json('No gender provided!') if (!skin) return res.status(HttpStatus.BAD_REQUEST).json('No skin provided!') if (!csp) return res.status(HttpStatus.BAD_REQUEST).json('No CSP provided!') // Authenticity if (!enums.genders.includes(gender)) return res.status(HttpStatus.BAD_REQUEST).json(`"${gender}" is not a valid gender value!`) if (!enums.skins.includes(skin)) return res.status(HttpStatus.BAD_REQUEST).json(`"${skin}" is not a valid skin value!`) if (!enums.csps.includes(csp)) return res.status(HttpStatus.BAD_REQUEST).json(`"${csp}" is not a valid CSP value!`) const code = randomString(8) // Create try { const character = await getModel('character').findOne({ where: { skin, csp, gender } }) if (!character) return res.status(HttpStatus.NOT_FOUND).json() const stats = await getModel('statistic').findAll() res.status(HttpStatus.CREATED).json(await getModel('session').create({ code, name, characterName: character.name })) if (stats.length !== 0) for (let s of stats) { await getModel('sessionStat').create({ sessionCode: code, statisticId: s.id, score: s.defaultScore }) } } catch (e) { if (e instanceof UniqueConstraintError) return res.status(HttpStatus.CONFLICT).json(`Session "${code}" already exists!"`) if (e instanceof ValidationError) return res.status(HttpStatus.BAD_REQUEST).json(e) res.status(HttpStatus.INTERNAL_ERROR).json(e) } } export async function getSession (res, payload) { if (!payload) return res.status(HttpStatus.BAD_REQUEST).json('No code provided!') try { const resSession = await getModel('session').findByPk(payload) if (!resSession) return res.status(HttpStatus.NOT_FOUND).json() const session = resSession.toJSON() session.resume = await getModel('sessionStat').findAll({ where: { sessionCode: payload } }) res.json(session) } catch (e) { res.status(HttpStatus.INTERNAL_ERROR).json(e) } } export async function deleteSession (res, payload) { if (!payload) return res.status(HttpStatus.BAD_REQUEST) const model = getModel('session') try { const session = await model.findByPk(payload) if (!session) return res.status(HttpStatus.NOT_FOUND).json() await model.destroy({ where: { code: payload } }) res.json(session) } catch (e) { res.status(HttpStatus.INTERNAL_ERROR).json(e) } }
local Component = require("scripts/utilities/component") local HealthExtensionInterface = require("scripts/extension_systems/health/health_extension_interface") local PropHealthExtension = class("PropHealthExtension") PropHealthExtension.init = function (self, extension_init_context, unit) self._unit = unit self._health = math.huge self._max_health = math.huge self._is_dead = false self._unkillable = false self._invulnerable = false self._speed_on_hit = 5 self._breed_white_list = nil self._ignored_colliders = {} end PropHealthExtension.setup_from_component = function (self, max_health, invulnerable, unkillable, breed_white_list, ignored_collider_actor_names, speed_on_hit) self._max_health = max_health self._health = max_health self._invulnerable = invulnerable self._unkillable = unkillable self._speed_on_hit = speed_on_hit self._breed_white_list = breed_white_list if ignored_collider_actor_names then local unit = self._unit for ii = 1, #ignored_collider_actor_names do local actor = Unit.actor(unit, ignored_collider_actor_names[ii]) self._ignored_colliders[actor] = true end end end PropHealthExtension.pre_update = function (self, unit, dt, t) self._was_hit_by_critical_hit_this_render_frame = false end PropHealthExtension.set_dead = function (self) self._health = 0 if not self._unkillable then self._is_dead = true HEALTH_ALIVE[self._unit] = nil end Component.event(self._unit, "died") end local function _add_force_on_parts(actor, mass, speed, attack_direction) local direction = attack_direction if not direction then local random_x = math.random() * 2 - 1 local random_y = math.random() * 2 - 1 local random_z = math.random() * 2 - 1 local random_direction = Vector3(random_x, random_y, random_z) random_direction = Vector3.normalize(random_direction) direction = random_direction end Actor.add_impulse(actor, direction * mass * speed) end PropHealthExtension.add_damage = function (self, damage_amount, permanent_damage, hit_actor, damage_profile, attack_type, attack_direction, attacking_unit) if self._ignored_colliders[hit_actor] then return end if self:_can_receive_damage(attacking_unit) then local max_health = self._max_health local health = self._health - damage_amount health = math.clamp(health, 0, max_health) self._health = health if hit_actor and Actor.is_dynamic(hit_actor) then _add_force_on_parts(hit_actor, Actor.mass(hit_actor), self._speed_on_hit, attack_direction) end Component.event(self._unit, "add_damage", damage_amount, hit_actor, attack_direction) if self._health <= 0 then self:set_dead() end end end PropHealthExtension.add_heal = function (self, heal_amount, heal_type) return end PropHealthExtension.set_last_damaging_unit = function (self, last_damaging_unit, hit_zone_name, last_hit_was_critical) self._last_damaging_unit = last_damaging_unit self._last_hit_zone_name = hit_zone_name self._last_hit_was_critical = last_hit_was_critical self._was_hit_by_critical_hit_this_render_frame = self._was_hit_by_critical_hit_this_render_frame or last_hit_was_critical end PropHealthExtension.last_damaging_unit = function (self) return self._last_damaging_unit end PropHealthExtension.last_hit_zone_name = function (self) return self._last_hit_zone_name end PropHealthExtension.last_hit_was_critical = function (self) return self._last_hit_was_critical end PropHealthExtension.was_hit_by_critical_hit_this_render_frame = function (self) return self._was_hit_by_critical_hit_this_render_frame end PropHealthExtension.max_health = function (self) return self._max_health end PropHealthExtension.current_health = function (self) return self._health end PropHealthExtension.current_health_percent = function (self) if self._max_health <= 0 then return 0 end return 1 - self._health / self._max_health end PropHealthExtension.damage_taken = function (self) return 0 end PropHealthExtension.permanent_damage_taken = function (self) return 0 end PropHealthExtension.permanent_damage_taken_percent = function (self) return 0 end PropHealthExtension.total_damage_taken = function (self) return 0 end PropHealthExtension.health_depleted = function (self) return self._health <= 0 end PropHealthExtension.is_alive = function (self) return not self._is_dead end PropHealthExtension.is_unkillable = function (self) return self._is_unkillable end PropHealthExtension.is_invulnerable = function (self) return self._is_invulnerable end PropHealthExtension.set_unkillable = function (self, should_be_unkillable) self._unkillable = should_be_unkillable end PropHealthExtension.set_invulnerable = function (self, should_be_invulnerable) self._invulnerable = should_be_invulnerable end PropHealthExtension.num_wounds = function (self) return 1 end PropHealthExtension.max_wounds = function (self) return 1 end PropHealthExtension._can_receive_damage = function (self, attacking_unit) if attacking_unit == self._unit then return true end if self._is_dead or self._invulnerable then return false end if not self._breed_white_list then return true end local unit_data_extension = ScriptUnit.has_extension(attacking_unit, "unit_data_system") if unit_data_extension then local breed_name = unit_data_extension:breed_name() local key = table.find(self._breed_white_list, breed_name) local can_damage = key ~= nil if can_damage then return true end end return false end implements(PropHealthExtension, HealthExtensionInterface) return PropHealthExtension
# Codebook for Getting Data Project Content 1. Variables Description 2. Steps taken for the transformation to tidy.txt dataset 1. Variables Description Feature Selection The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals tAcc-XYZ and tGyro-XYZ. These time domain signals (prefix 't' to denote time) were captured at a constant rate of 50 Hz. Then they were filtered using a median filter and a 3rd order low pass Butterworth filter with a corner frequency of 20 Hz to remove noise. Similarly, the acceleration signal was then separated into body and gravity acceleration signals (tBodyAcc-XYZ and tGravityAcc-XYZ) using another low pass Butterworth filter with a corner frequency of 0.3 Hz. Subsequently, the body linear acceleration and angular velocity were derived in time to obtain Jerk signals (tBodyAccJerk-XYZ and tBodyGyroJerk-XYZ). Also the magnitude of these three-dimensional signals were calculated using the Euclidean norm (tBodyAccMag, tGravityAccMag, tBodyAccJerkMag, tBodyGyroMag, tBodyGyroJerkMag). Finally a Fast Fourier Transform (FFT) was applied to some of these signals producing fBodyAcc-XYZ, fBodyAccJerk-XYZ, fBodyGyro-XYZ, fBodyAccJerkMag, fBodyGyroMag, fBodyGyroJerkMag. (Note the 'f' to indicate frequency domain signals). These signals were used to estimate variables of the feature vector for each pattern: '-XYZ' is used to denote 3-axial signals in the X, Y and Z directions. tBodyAcc-XYZ tGravityAcc-XYZ tBodyAccJerk-XYZ tBodyGyro-XYZ tBodyGyroJerk-XYZ tBodyAccMag tGravityAccMag tBodyAccJerkMag tBodyGyroMag tBodyGyroJerkMag fBodyAcc-XYZ fBodyAccJerk-XYZ fBodyGyro-XYZ fBodyAccMag fBodyAccJerkMag fBodyGyroMag fBodyGyroJerkMag The set of variables that were estimated from these signals are: mean(): Mean value std(): Standard deviation 2. Steps taken for the transformation to tidy.txt dataset -activity and subject data added to the text and train datasets -activity converted from numeric to descriptive text -renamed variables to descriptive text -merged the dataset using rbind as the number of variables between the two sets are identical -created a subset of in order to focus on the mean and standard deviation of the measurements -created a tidy data set with the average of each variable for each activity and each subject
import { presetPalettes, presetDarkPalettes } from '@ant-design/colors'; import type { ArcoColorType } from '@arco-design/color'; import { getPresetColors } from '@arco-design/color'; export interface Options { /** * 决定根据何种算法生成调色板,arco的质感更加浪漫,ant则偏向务实 * * @default 'arco' */ type?: 'arco' | 'ant'; /** * 当你需要给css变量定义前缀,以区分不同组件库的cssVar时传入 * * @default '' */ cssVarPrefix?: string; } interface NormalizePalettesRecord { /** * red\blue\yellow\gold\... */ from: 'arco' | 'ant'; name: string; mode: 'light' | 'dark'; primary: string; colors: string[]; } const getArcoNormalizePalettesRecordItem = ( name: string, mode: 'light' | 'dark', item: ReturnType<typeof getPresetColors>[ArcoColorType], ): NormalizePalettesRecord => { return { from: 'arco', name, colors: item[mode], mode: mode, primary: item['primary'], }; }; export function getNormalizePresetPalettes(type: 'arco' | 'ant'): NormalizePalettesRecord[] { if (type === 'arco') { const preset = getPresetColors(); return Object.keys(preset).reduce<NormalizePalettesRecord[]>((prev, curr) => { prev.push(getArcoNormalizePalettesRecordItem(curr, 'light', preset[curr as ArcoColorType])); prev.push(getArcoNormalizePalettesRecordItem(curr, 'dark', preset[curr as ArcoColorType])); return prev; }, []); } else if (type === 'ant') { let res: NormalizePalettesRecord[] = []; Object.keys(presetPalettes).forEach((key) => { const lightItem = presetPalettes[key]; const darkItem = presetDarkPalettes[key]; res.push({ from: 'ant', mode: 'light', name: key, primary: lightItem['primary'] as string, colors: lightItem, }); res.push({ from: 'ant', mode: 'dark', name: key, primary: darkItem['primary'] as string, colors: darkItem, }); delete lightItem['primary']; delete darkItem['primary']; }); return res; } throw new Error('暂时只支持arco和ant的预设调色板'); }
<%-- Document : crear-usuario Created on : 23-sep-2019, 1:04:43 Author : helmuthluther --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@include file="../html/style-sheets.html" %> <link href="../css/style.css" rel="stylesheet" type="text/css"> <title>Modificar Perfil</title> </head> <body class="<c:choose> <c:when test="${tipo == 1}"> fondoAdministrador </c:when> <c:when test="${tipo == 2}"> fondoEditor </c:when> <c:when test="${tipo == 3}"> fondoSuscriptor </c:when> </c:choose>"> <header> <%@include file="../html/style-sheets.html" %> <link href="../css/style.css" rel="stylesheet" type="text/css"> <c:choose> <c:when test="${tipo == 1}"> <%@include file="../html/barra-navegacion-administrador.html"%> </c:when> <c:when test="${tipo == 2}"> <%@include file="../html/barra-navegacion-editor.html"%> </c:when> <c:when test="${tipo == 3}"> <%@include file="../html/barra-navegacion-suscriptor.html"%> </c:when> </c:choose> </header> <div class="container-fluid"> <section class="main row"> <aside class="col-md-4"></aside> <form class="col-md-4" action="/SistemaWebDeRevistas/jsp/ControladorModificarPerfil" enctype="multipart/form-data" method="POST"> <div class="form-group" hidden> <input type="text" class="form-control" id="nombreUsuario" name="nombreUsuario" placeholder="Ingresar nombre de usuario" maxlength="50" value="${perfilSolicitado.nombreUsuario}" required> </div> <center><h2 class="etiquetaBlanca"><c:out value="${perfilSolicitado.nombreUsuario}"></c:out></h2></center> <!--DATOS PERFIL --> <div class="form-group"> <label class="campoObligatorio"> * </label> <label for="nombre" class="etiquetaBlanca">Nombre</label> <input type="text" class="form-control" id="nombre" name="nombre" placeholder="Ingresar nombre" maxlength="50" value="${perfilSolicitado.nombre}" required> </div> <div class="form-group"> <label class="campoObligatorio"> * </label> <label for="apellido" class="etiquetaBlanca">Apellido</label> <input type="text" class="form-control" id="apellido" name="apellido" placeholder="Ingresar apellido" maxlength="50" value="${perfilSolicitado.apellido}" required> </div> <div class="form-group"> <label for="hobbies" class="etiquetaBlanca">Foto de Perfil</label> <br> <input type="file" class="etiquetaBlanca" name="fotoPerfil" accept="image/*"> <br> </div> <div class="form-group"> <label for="hobbies" class="etiquetaBlanca">Hobbies</label> <textarea class="form-control" aria-label="With textarea" id="hobbies" name="hobbies" placeholder="Ingresar hobbies"><c:out value="${perfilSolicitado.hobbies}"></c:out> </textarea> </div> <div class="form-group"> <label for="temasInters" class="etiquetaBlanca">Temas de Interes</label> <textarea class="form-control" aria-label="With textarea" id="temasInteres" name="temasInteres" placeholder="Ingresar temas de interes"><c:out value="${perfilSolicitado.temasInteres}"></c:out></textarea> </div> <div class="form-group"> <label for="descripcion" class="etiquetaBlanca">Descripcion</label> <textarea class="form-control" aria-label="With textarea" id="descripcion" name="descripcion" placeholder="Ingresar descripcion"><c:out value="${perfilSolicitado.descripcion}"></c:out></textarea> </div> <div class="form-group"> <label for="gustos" class="etiquetaBlanca">Gustos</label> <textarea class="form-control" aria-label="With textarea" id="gustos" name="gustos" placeholder="Ingresar gustos"><c:out value="${perfilSolicitado.gustos}"></c:out></textarea> </div> <div> <center> <a href="/SistemaWebDeRevistas/jsp/ControladorPerfil" class="btn btn-danger">Cancelar</a> <button type="submit" class="btn btn-success">Aceptar</button> </center> </div> <br><br> </form> <aside class="col-md-4"></aside> </section> </div> <%@include file="../html/footer.html"%> <%@include file="../html/modal-costo-global.html"%> <%@include file="../html/modal-porcentaje-pago.html"%> <!-- ARCHIVOS JS --> <%@include file="../html/scripts.html" %> </body> </html>
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "Collider.generated.h" UCLASS() class BOSSSHOOTER_API ACollider : public APawn { GENERATED_BODY() public: // Sets default values for this pawn's properties ACollider(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; UPROPERTY(VisibleAnywhere, Category = "Mesh") class UStaticMeshComponent* MeshComponent; FORCEINLINE UStaticMeshComponent* GetMeshComponent() { return MeshComponent; } FORCEINLINE void SetStaticMeshComponent(UStaticMeshComponent* NewMeshComponent) { MeshComponent = NewMeshComponent; } UPROPERTY(VisibleAnywhere, Category = "Mesh") class USphereComponent* SphereComponent; FORCEINLINE USphereComponent* GetSphereComponent() { return SphereComponent; } FORCEINLINE void SetSphereComponent(USphereComponent* NewSphereComponent) { SphereComponent = NewSphereComponent; } UPROPERTY(VisibleAnywhere, Category = "CameraVariables") class UCameraComponent* Camera; FORCEINLINE UCameraComponent* GetCamera() { return Camera; } FORCEINLINE void SetCamera(UCameraComponent* NewCamera) { Camera = NewCamera; } UPROPERTY(VisibleAnywhere, Category = "CameraVariables") class USpringArmComponent* SpringArm; FORCEINLINE USpringArmComponent* GetSpringArm() { return SpringArm; } FORCEINLINE void SetSpringArm(USpringArmComponent* NewSpringArm) { SpringArm = NewSpringArm; } UPROPERTY(VisibleAnywhere, Category = "Movement") class UColliderMovementComponent* MyMovementComponent; virtual UPawnMovementComponent* GetMovementComponent() const override; private: void MoveForward(float Value); void MoveRight(float Value); void LookUp(float Value); void Turn(float Value); FVector2D CameraInput; };
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { Set<List<Integer>>set = new HashSet<>(); int n = nums.length; for(int i = 0; i<n; i++){ int sum = 0; for(int j = i+1; j<n; j++){ for(int z = j + 1; z<n; z++){ for(int y = z+1; y<n; y++){ if(nums[i]+nums[j]+nums[z]+nums[y] == target){ List<Integer> li = Arrays.asList(nums[i], nums[j], nums[z], nums[y]); Collections.sort(li); set.add(li); } } } } } return new ArrayList<>(set); } } ------------------------------- class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); int n = nums.length; for(int i = 0; i<n-3; i++){ if(i != 0 && nums[i-1] == nums[i]){ continue; } for(int j = i+1; j<n-2; j++){ if(j != i+1 && nums[j-1] == nums[j]){ continue; } int left = j+1, right = n-1; while(left < right){ int sum = nums[i] + nums[j] + nums[left] + nums[right]; if(sum > target){ right--; }else if(sum < target){ left++; }else{ List<Integer> combination = new ArrayList<>(); combination.add(nums[i]); combination.add(nums[j]); combination.add(nums[left]); combination.add(nums[right]); left++; right--; list.add(combination); while(left < right && nums[left] == nums[left-1]){ left++; } while(right > left && nums[right] == nums[right+1]){ right--; } } } } } return list; } }
# Regents.R # This is for reconciling regents scores in the regents workbook, powerschool, and the accountability workbook # Note: Run "Regents Workbook.R" first. # Save the raw versions in case the raw data is needed later (e.g., restarting this script without rerunning MainScript) R.bs = Regents.bestScores R.bs.ne = Regents.bestScores.NE R.bc = Regents.bestCategory R.bc.ne = Regents.bestCategory.NE Workbook.sub = Workbook PS = powerschoolraw #------------------------------------# #### Set the exams and categories #### #------------------------------------# Exams = testLookup$Code nExam = length(Exams) Categories = unique(testLookup$Category) nCat = length(Categories) #---------------------------------------------------------# #### Make Workbook.sub score matrix and session matrix #### #---------------------------------------------------------# # Remove blank rows and unnecessary columns # this line should keep the student ID and all of the regents scaled scores, performance levels, and exam year/terms PSexamnames = unique(testLookup$PowerSchool) column_names = CharCartProd(x = testLookup$Workbook, y = c("Scaled.Score", "Exam.Year.and.Term"), groupBy = 2) column_names = c("Local.ID.(optional)", column_names) if(!(all(column_names %in% colnames(Workbook.sub)))){ print("There's a problem with the column names") } Workbook.sub = Workbook.sub[,column_names] # subset the workbook to the relevant columns Workbook.sub$USF.HistoryExam.Year.and.Term = as.character(Workbook.sub$USF.HistoryExam.Year.and.Term) colnames(Workbook.sub)[1] = "ID" # change the first column to be named ID studentlist = as.double(Workbook.sub$ID) # this needs to be a double precision because some ID's are very long n = length(studentlist) # this is the number of students # Set up matrices to hold scores and sessions from the workbook, using student ID's as row names and exam names as column names wkbkMatrix = matrix(numeric(0), n, nExam, F, list(studentlist, Exams)) wkbkSessions = matrix(character(0), n, nExam, F, list(studentlist, Exams)) Workbook.sub[which(Workbook.sub == "E", arr.ind = T)] = 64.9 # Load in the actual scores and sessions cols = 2*(1:nExam) #the scores are in columns 2, 4, 6, etc. for (i in studentlist){ wkbkMatrix[rownames(wkbkMatrix) == i,] = as.numeric(Workbook.sub[Workbook.sub$ID == i,cols]) wkbkSessions[which(rownames(wkbkSessions) == i),] = as.character(Workbook.sub[which(Workbook.sub$ID == i),cols+1]) } # /for #-------------------------------------------------------------# #### Make Regents Database score matrix and session matrix #### #-------------------------------------------------------------# R.bs.ne$ExamCode = testLookup$Code[match(R.bs.ne$Exam, testLookup$Database)] R.bs.ne = R.bs.ne[!is.na(R.bs.ne$ExamCode),] colnames(R.bs.ne)[1] = "ID" # Set up the matrices to hold scores and sessions from the database with student IDs and rownames and exam names as column names dbMatrix = matrix(integer(0), n, nExam, F, list(studentlist, Exams)) dbSessions = matrix(character(0), n, nExam, F, list(studentlist, Exams)) # load in the actual scores and sessions for(thisStudent in studentlist){ for(thisExam in Exams){ thisScoreValue = R.bs.ne$ScoreValue[R.bs.ne$ExamCode == thisExam & R.bs.ne$ID == thisStudent] if(length(thisScoreValue) != 0){ thisSession = R.bs.ne$SessionName[R.bs.ne$ExamCode == thisExam & R.bs.ne$ID == thisStudent] thisRow = which(rownames(dbMatrix) == thisStudent) thisColumn = which(colnames(dbMatrix) == thisExam) dbMatrix[thisRow,thisColumn] = thisScoreValue dbSessions[thisRow,thisColumn] = thisSession } } } # /for # Note: if you get warnings here, there is likely a problem with the order of the columns in the database output # Are there other problems? Check it out: # studentlist[!(studentlist %in% R.bs$ID)] # R.bs$ID[!(R.bs$ID %in% studentlist)] # View(Workbookraw.xlsx[Workbookraw.xlsx$`Local.ID.(optional)` %in% R.bs$ID[!(R.bs$ID %in% studentlist)],]) #---------------------------------------------# #### Compare Regents Database and Workbook #### #---------------------------------------------# # Create a Compare Matrix with the best scores CompMat = CreateCompareMatrix(studentlist, Exams, dbMatrix, wkbkMatrix) if(!(identical(colnames(dbMatrix), colnames(wkbkMatrix)) & identical(colnames(dbMatrix), colnames(CompMat)))){ message("ERROR! There is a problem the order of the columns in the matrices.") } # Create a list of things that need to be updated in the database if(sum(!MbetterComp(CompMat, dbMatrix) & !is.na(CompMat))){ # if any best scores not in the database temp = which(!MbetterComp(CompMat, dbMatrix) & !is.na(CompMat), arr.ind = T) # create matrix of locations (row & col) badDB = data.frame(ID = rownames(temp), Exam = Exams[temp[,2]]) # create a list of the... something? write.csv(badDB,file = paste0(OutFolder,"ScoresMissingFromDataBase.csv")) # export the file print("Resolve the scores missing from the Database") } else { print("No scores missing from the Database") } # Note: # Take a look at the ScoresMissingFromDatabase.csv file # Those are instances in which a student has a score in the workbook but not in the database # Check if there are any best scores not in the workbook, and if so, create output to be pasted into the Workbook if(sum(!MbetterComp(CompMat, wkbkMatrix) & !is.na(CompMat)) > 0){ print(which(!MbetterComp(CompMat, wkbkMatrix) & !is.na(CompMat), arr.ind = T)) wkbkOutput = data.frame(ID = rownames(CompMat)) # set up the output object temp = CompMat # create a temporary version of the best scores matrix rownames(temp) = NULL # get rid of the rownames in temp so it can be merged with the output object wkbkOutput = cbind(wkbkOutput, temp) # merge the best scores with the output object, so that it has student ID's rownames(wkbkMatrix) = NULL # get rid of row names from everything rownames(dbMatrix) = NULL rownames(wkbkSessions) = NULL rownames(dbMatrix) = NULL for (i in 1:nExam){ # for each exam, wkbkOutput[,nExam+1+i] = NA # add a column for it in the output object grabRows = which(wkbkOutput[,1+i] == wkbkMatrix[,i]) # find which scores are consistent with the Workbook.sub wkbkOutput[grabRows,nExam+1+i] = wkbkSessions[grabRows,i] # get Workbook sessions and insert in output object grabRows = which(wkbkOutput[,1+i] == dbMatrix[,i]) # find which scores are consistent with the database wkbkOutput[grabRows,nExam+1+i] = dbSessions[grabRows,i] # get sessions from database and insert in output object names(wkbkOutput)[nExam+1+i] = paste0(names(wkbkOutput)[1+i], # name new column by test name plus the word session " Session") } #end of for loop # Add old math exam columns colNams = colnames(wkbkOutput) # get wkbkOutput column names mathcols = paste0("OldMath",1:2) # Names of columns to add colNams = c(colNams[1:2], mathcols, colNams[3:length(colNams)]) # reorder the column names wkbkOutput[,mathcols] = "" # add blank columns wkbkOutput = wkbkOutput[,colNams] # reorder the columns of wkbkOutput mathcolsSession = paste0(mathcols, " Session") wkbkOutput[,mathcolsSession] = "" # add blank columns colNams = colnames(wkbkOutput) # Add columns for the exemptions scoreColNames = colNams[2:((length(colNams) + 1)/2)] SessionColNames = paste0(scoreColNames, " Session") exemptioncolnames = paste0(scoreColNames, "_Exemption") wkbkOutput[,exemptioncolnames] = "" # add blank columns # Assemble the output with the columns in the correct order allColNams = "ID" for(thisCol in 1:length(scoreColNames)){ allColNams = c(allColNams, scoreColNames[thisCol], SessionColNames[thisCol], exemptioncolnames[thisCol]) } wkbkOutput = wkbkOutput[,allColNams] # Load exemptions R.bs.exemptions = R.bs[R.bs$Score == "E",] rownames(R.bs.exemptions) = NULL R.bs.exemptions$wkbkExportColumn = testLookup$Code[match(R.bs.exemptions$Exam, testLookup$Database)] if(sum(is.na(R.bs.exemptions$wkbkExportColumn)) > 0){ print("There's a problem with the lookup of testlookup$Database and R.bs.exemptions$Exam") } for(thisRow in 1:nrow(R.bs.exemptions)){ outColumn = paste0(R.bs.exemptions$wkbkExportColumn[thisRow],"_Exemption") outRow = wkbkOutput$ID == R.bs.exemptions$StudentNumber[thisRow] wkbkOutput[outRow, outColumn] = R.bs.exemptions$SessionName[thisRow] } # Write the output for (i in 1:ncol(wkbkOutput)){wkbkOutput[,i] = as.character(wkbkOutput[,i])} # convert everything to character wkbkOutput = DFna.to.empty(wkbkOutput) # replace NA values with blanks write.csv(wkbkOutput, paste0(OutFolder,"PasteThisIntoTheWorkBook.csv")) # export the file print("paste scores into the workbook") } else { print("Workbook is fine") } # Note: You can paste all scores and dates at once. #---------------------------------------------------------# #### Make category score matrix from the CompMat #### #---------------------------------------------------------# R.bc.ne = R.bc.ne[R.bc.ne$Category %in% testLookup$Category,] colnames(R.bc.ne)[1] = "ID" CatBest = matrix(data = numeric(0), n, nCat, F, list(studentlist, Categories)) for(thisStudent in studentlist){ for(thisCategory in Categories){ thisScoreValue = R.bc.ne$ScoreValue[R.bc.ne$Category == thisCategory & R.bc.ne$ID == thisStudent] if(length(thisScoreValue) != 0){ thisRow = which(rownames(CatBest) == thisStudent) thisColumn = which(colnames(CatBest) == thisCategory) CatBest[thisRow,thisColumn] = thisScoreValue } } } # /for #-------------------------------# #### Make PowerSchool matrix #### #-------------------------------# colnames(PS)[1] = "ID" # change the name of the ID variable to ID psMatrix = matrix(integer(0), n, nCat) # set up the matrix to hold the scores rownames(psMatrix) = studentlist # in the matrix, name the rows according to the student ID colnames(psMatrix) = Categories # in the matrix, name the columns according to the exam name psCategoryNames = testLookup$PowerSchool[match(Categories, testLookup$Category)] # match category names to PS field names PS.limited = PS[,c("ID",psCategoryNames)] PS.limited[which(PS.limited == "E", arr.ind = T)] = "64.9" str(PS.limited) sort(unique(unlist(PS.limited[,psCategoryNames]))) for (thisStu in studentlist){ # for each student if (thisStu %in% PS$ID){ # if student is in powerschool data, load scores into the appropriate row in the powerschool score matrix psMatrix[rownames(psMatrix) == thisStu,] = as.numeric(PS.limited[PS.limited$ID == thisStu,psCategoryNames]) } # /if } # /for loop #-------------------------------------------------------# #### Compare CategoryOutput and PowerSchool matrices #### #-------------------------------------------------------# # set up the matrix with the best category scores CatCompMat = CreateCompareMatrix(studentlist, Categories, psMatrix, CatBest) psMatrix[rownames(psMatrix) == "192011812",] CatBest[rownames(CatBest) == "192011812",] CatCompMat[rownames(CatCompMat) == "192011812",] # Create list of scores that are missing from PowerSchool # These are scores for which we have a record, but are not showing in PS if(sum(!MbetterComp(CatCompMat, psMatrix) & !is.na(CatCompMat))){ # if any best scores not in PowerSchool temp = which(!MbetterComp(CatCompMat, psMatrix) & !is.na(CatCompMat), arr.ind = T) # make matrix of locations (row and col) badPS = data.frame( # make output w/ stud ID's & exam cat ID = as.double(rownames(temp)), Categories = as.character(Categories[temp[,2]]), stringsAsFactors = FALSE) badPS$psScore = psMatrix[cbind(temp[,"row"],temp[,"col"])] # pull scores in PowerSchool badPS$dbScore = CatCompMat[cbind(temp[,"row"],temp[,"col"])] # pull scores that in the Database badPS$First = Workbook$First.Name[match(badPS$ID,Workbook$`Local.ID.(optional)`)] # pull in the first name badPS$Last = Workbook$Last.Name[match(badPS$ID,Workbook$`Local.ID.(optional)`)] # pull in the last name badPS$Session = "" # create column to hold test session name # This loop is supposed to add in test sessions for (i in 1:nrow(badPS)){ thisrow = which(studentlist == badPS$ID[i]) # Determine this student's row of the dbMatrix examset = Exam2CatTable$Exam[Exam2CatTable$Category == badPS$Categories[i]] # Determine the exam(s) relevant to thiscategory thiscolumn = which(colnames(dbMatrix) %in% examset) # Determine the column(s) relevant to this exam if(length(thiscolumn) == 1){ # If the category has only one exam, badPS$Session[i] = dbSessions[thisrow, thiscolumn] # grab that session. } else { # If the category has multiple exams, score = badPS$dbScore[i] # grab the score. usethisone = which(dbMatrix[thisrow,thiscolumn] == score) # Grab the col(s) w/ that score for that student usethisone = usethisone[1] # If score appears more than once, use first one badPS$Session[i] = dbSessions[thisrow,thiscolumn[usethisone]] # Grab the session } # /if-else } # /for loop write.csv(badPS,file = paste0(OutFolder, "ScoresMissingFromPowerSchool.csv")) # export the file print("Enter scores in PowerSchool") } else { print("No scores to add to PowerSchool") } #end of if-else statement # Note: If needed, go through the ScoresMissingFromPowerSchool.csv file. #------------------------------------------------------------------------------------# #### Create a list of things that need to be updated in the database/Workbook #### #------------------------------------------------------------------------------------# # These are PowerSchool scores for which we have no record in the database or Workbook.sub # Someone put them in PS, but never gave them to the data office # CatBest is the set of best scores taken from the Workbook.sub and Regents Database # CatCompMat is the set of best scores taken from the Workbook.sub, Database, and PowerSchool temp = !MbetterComp(CatCompMat, CatBest) if(sum(temp) > 0){ # if there are any best scores not in the database temp = which(temp, arr.ind = TRUE) # create a list of the locations (row and column) badWork = data.frame( # create the output object with student ID's and exam categories ID = as.double(rownames(temp)), Categories = as.character(Categories[temp[,2]]), stringsAsFactors = FALSE) badWork$psScore = psMatrix[cbind(temp[,"row"],temp[,"col"])] # pull scores in PowerSchool badWork$dbScore = CatBest[cbind(temp[,"row"],temp[,"col"])] # pull scores in the Database badWork$First = Workbook$First.Name[match(badWork$ID, Workbook$`Local.ID.(optional)`)] # pull in the first name badWork$Last = Workbook$Last.Name[match(badWork$ID, Workbook$`Local.ID.(optional)`)] # pull in the last name badWork$Session = "" # create test session name column for (i in 1:nrow(badWork)){ thisrow = which(studentlist == badWork$ID[i]) thiscolumn = which(substr(colnames(dbMatrix), 1, nchar(badWork$Categories[i])) == badWork$Categories[i]) if(length(thiscolumn) == 1){ badWork$Session[i] = dbSessions[thisrow, thiscolumn] } else { score = badWork$dbScore[i] usethisone = which(dbMatrix[thisrow,thiscolumn] == score)[1] badWork$Session[i] = dbSessions[thisrow,thiscolumn[usethisone]] } # /if-else } # /for loop write.csv(badWork,file = paste0(OutFolder, "ScoresInPowerSchoolButNowhereElse.csv")) # export the file print("There are mysterious PowerSchool scores") } else { print("No mysterious PowerSchool scores found") } #----------------------------------------------------------------------------------------------------------# #### Create a subset of the score database that refers to only those students who have score mismatches #### #----------------------------------------------------------------------------------------------------------# # Note: this part is usually unnecessary and generally unhelpful if(exists("badWork") + exists("badPS") == 2){ studentsToUse = unique(c(badWork$ID, badPS$ID)) } else if(exists("badWork")){ studentsToUse = unique(c(badWork$ID)) } else if(exists("badPS")){ studentsToUse = unique(c(badPS$ID)) } else { studentsToUse = NA } # /if-else-else-else if(!all(is.na(studentsToUse))){ badStudents = R.bsraw[which(R.bsraw$StudentNumber %in% studentsToUse),] badStudents$First = Workbook$First.Name[match(badStudents$StudentNumber, Workbook$`Local.ID.(optional)`)] badStudents$Last = Workbook$Last.Name[match(badStudents$StudentNumber, Workbook$`Local.ID.(optional)`)] vars = names(badStudents) x = length(vars) badStudents = badStudents[,c(vars[x-1], vars[x], vars[1:(x-2)])] badStudents = DFna.to.empty(badStudents) write.csv(badStudents, file = paste0(OutFolder,"ScoresAndSessionsForStudentsWithScoreIssues.csv")) # export the file print("Look at the composite file for students with score issues") } else { print("There are no issues to resolve") } # /if-else
import getMonday from "../utils/getMonday"; const DatabaseController = () => { const init = () => { // Add key to store projects if (!localStorage.getItem("projects")) { localStorage.setItem("projects", JSON.stringify([])); } // Create inbox project if not existing if (JSON.stringify(getProjectByName("Inbox")) === "{}") { createProject({ id: "Inbox", name: "Inbox", timeCreated: (new Date()).getTime(), }) } // Add key to store tasks if (!localStorage.getItem("tasks")) { localStorage.setItem("tasks", JSON.stringify([])); } }; const createProject = project => { let projects = getAllProjects(); projects.push(project); localStorage.setItem("projects", JSON.stringify(projects)); }; const getProjectById = id => { const projects = JSON.parse(localStorage.getItem("projects")); const result = projects.filter(project => project.id === id); if (result.length === 0) { return {}; } else { return result[0]; } }; const getProjectByName = name => { const projects = JSON.parse(localStorage.getItem("projects")); const result = projects.filter(project => project.name === name); if (result.length === 0) { return {}; } else { return result[0]; } }; const getAllProjects = () => { return JSON.parse(localStorage.getItem("projects")); }; const updateProject = (oldProject, newProject) => { let projects = getAllProjects(); for (let i = 0; i < projects.length; i++) { if (projects[i].id === oldProject.id) { projects[i] = newProject; } } localStorage.setItem("projects", JSON.stringify(projects)); }; const deleteProject = id => { // Delete the project let projects = getAllProjects(); projects = projects.filter(project => project.id !== id); localStorage.setItem("projects", JSON.stringify(projects)); // Delete the tasks in the project let tasks = getTasksByProjectId(id); tasks.forEach(task => { deleteTask(task.id); }); }; const createTask = task => { let tasks = getAllTasks(); tasks.push(task); localStorage.setItem("tasks", JSON.stringify(tasks)); }; const getAllTasks = () => { return JSON.parse(localStorage.getItem("tasks")); }; const getTasksByProjectId = projectId => { const tasks = getAllTasks(); const result = tasks.filter(task => task.projectId === projectId); return result; }; const getTaskById = id => { const tasks = getAllTasks(); for (let task of tasks) { if (task.id === id) { return task; } } return {}; }; const getOverdueTasks = today => { let tasks = getAllTasks(); tasks = tasks.filter(task => task.dueDate < today.getTime()); return tasks; }; const getTasksByDueDate = date => { let tasks = getAllTasks(); tasks = tasks.filter(task => { const dueDate = new Date(task.dueDate); return dueDate.getDate() === date.getDate() && dueDate.getMonth() === date.getMonth() && dueDate.getFullYear() === date.getFullYear(); }); return tasks; }; const getTasksOfTheWeek = date => { let tasks = getAllTasks(); const monday = getMonday(date); const sunday = new Date(monday); sunday.setDate(sunday.getDate() + 7); sunday.setMilliseconds(sunday.getMilliseconds() - 1); tasks = tasks.filter(task => task.dueDate >= monday.getTime() && task.dueDate <= sunday.getTime()); return tasks; }; const updateTask = (oldTask, newTask) => { let tasks = getAllTasks(); for (let i = 0; i < tasks.length; i++) { if (tasks[i].id === oldTask.id) { tasks[i] = newTask; } } localStorage.setItem("tasks", JSON.stringify(tasks)); }; const deleteTask = id => { let tasks = getAllTasks(); tasks = tasks.filter(task => task.id !== id); localStorage.setItem("tasks", JSON.stringify(tasks)); } return { init, getProjectById, getProjectByName, getAllProjects, createProject, updateProject, deleteProject, createTask, getAllTasks, getTasksByProjectId, getTaskById, getOverdueTasks, getTasksByDueDate, getTasksOfTheWeek, updateTask, deleteTask, }; }; export default DatabaseController;
import React, { FC, PropsWithChildren, createContext, useCallback, useContext, useEffect, useRef, useState, } from 'react'; import { start, isStarted, onMessage, newNode, peerID, connect, stop, Config, StoreQuery, ContentFilter, storeQuery, filterSubscribe, FilterSubscription, WakuMessage, lightpushPublish, dnsDiscovery, } from '@waku/react-native'; import {useAccount} from 'wagmi'; import {Party} from '../protos'; import {Alert} from 'react-native'; interface WakuContext { nodeStarted: boolean; createParty: (title: string) => Promise<void>; parties: any[]; sponsorParty: (value: string) => Promise<void>; } const context = createContext<WakuContext | null>(null); const getQRTopic = (address: string) => `/wakuparty/1/qr-test-${address}/proto`; const getNotificationTopic = (address: string) => { return `/wakuparty/1/notification-test-${address}/proto`; }; const nodeConfig = new Config(); nodeConfig.relay = false; nodeConfig.filter = true; export const WakuProvider: FC<PropsWithChildren> = ({children}) => { const [nodeStarted, setIsNodeStarted] = useState(false); const {address, status} = useAccount(); const [isPeersConnecting, setIsPeersConnecting] = useState<boolean | null>( null, ); const [parties, setParies] = useState<any[]>([]); const [qrTopic, setQRTopic] = useState(''); const updateParties = useCallback(async () => { const isLoaded = await isStarted(); if (!isLoaded) { return; } if (!qrTopic || isPeersConnecting !== false) { return; } const query = new StoreQuery(); console.log(`[Query] Loading Parties for topic ${qrTopic}`); query.contentFilters.push(new ContentFilter(qrTopic)); const result = await storeQuery(query); setParies(result.messages ?? []); console.log('[Query] Loaded all parties'); }, [qrTopic, isPeersConnecting]); useEffect(() => { if (status !== 'connected') { return; } const _topic = getQRTopic(address); setQRTopic(_topic); }, [address, status]); const onMessageRecieve = (message: any) => { console.log(message, 'message'); }; const isLoadedRef = useRef(false); useEffect(() => { if (isPeersConnecting === null) { return; } if (isPeersConnecting === false) { updateParties(); } }, [isPeersConnecting, updateParties]); useEffect(() => { if (!address) { return; } setIsPeersConnecting(true); const loadWaku = async () => { let isLoaded; isLoaded = await isStarted(); isLoadedRef.current = isLoaded.valueOf(); if (!isLoaded) { await newNode(nodeConfig); await start(); isLoaded = await isStarted(); const _peers = await dnsDiscovery( 'enrtree://AO47IDOLBKH72HIZZOXQP6NMRESAN7CHYWIBNXDXWRJRZWLODKII6@test.wakuv2.nodes.status.im', '1.1.1.1', ); console.log(`[Peers] ${JSON.stringify(_peers)} via DNS`); if (_peers.length === 0) { Alert.alert('No Peers found through DNS Discovery'); return; } for await (const peer of _peers) { for await (const multiAddress of peer.addrs) { try { await connect(multiAddress, 5000); console.log('[Connection] Connected to Peer'); } catch (err) { console.log(err); console.log('[Connection] Peer connection error'); } } } const filter = new FilterSubscription(); filter.contentFilters.push(new ContentFilter(getQRTopic(address))); await filterSubscribe(filter); onMessage(onMessageRecieve); console.log('[Filter] Connected'); } setIsNodeStarted(isLoaded.valueOf()); console.log(`Node Started - Peer ID ${await peerID()}`); setIsPeersConnecting(false); }; loadWaku(); return () => { if (!isLoadedRef.current) { return; } stop(); }; }, [address]); const createParty = useCallback( async (title: string) => { if (!address) { return; } const message = new WakuMessage(); message.contentTopic = getQRTopic(address); message.payload = Party.encode({ message: title, address: address, }).finish(); console.log(`[Message] ${title} - topic:${message.contentTopic}`); const x = await lightpushPublish(message); console.log(`[Response] - PushID ${x}`); }, [address], ); const sponsorParty = useCallback(async (value: string) => {}, []); return ( <context.Provider value={{nodeStarted, createParty, parties, sponsorParty}}> {children} </context.Provider> ); }; export const useWaku = () => { const _context = useContext(context); if (!_context) { throw new Error('WakuProvider not found'); } return _context; };
<?php namespace common\models; use Yii; /** * This is the model class for table "block_rec". * * @property int $id * @property string $name * @property string $color * @property int|null $status */ class BlockRec extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'block_rec'; } /** * {@inheritdoc} */ public function rules() { return [ [['name', 'color'], 'required'], [['status'], 'integer'], [['name', 'color'], 'string', 'max' => 255], [['name'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Название', 'color' => 'Цвет', 'status' => 'Статус', ]; } }
#ifndef UTILS_HANDLER_DISPATCHER_H_ #define UTILS_HANDLER_DISPATCHER_H_ #pragma once #include <memory> #include <string> #include <unordered_map> using std::shared_ptr; using std::string; using std::unordered_map; template <class HandlerType> class HandlerDispatcher { HandlerDispatcher(const HandlerDispatcher&) = delete; HandlerDispatcher& operator=(const HandlerDispatcher&) = delete; public: void Install(shared_ptr<HandlerType> handler) { handlers_[handler->HandlerName()] = std::static_pointer_cast<HandlerType>(handler); } shared_ptr<HandlerType> FindHandler(const string& name) const { auto it = handlers_.find(name); if (it != handlers_.end()) return it->second; return nullptr; } private: unordered_map<string, shared_ptr<HandlerType>> handlers_; }; #endif // UTILS_HANDLER_DISPATCHER_H_
(ns ttt.t-core (:use midje.sweet) (:use [ttt.core])) (fact (:board (init-position)) => '[- - -, - - -, - - -]) (fact (possible-moves (init-position)) => (range 0 9)) (fact (:board (move (init-position) 0)) => '[x - -, - - -, - - -]) (fact (other-turn 'x) => 'o) (fact (other-turn 'o) => 'x) (fact (:dim (init-position)) => 3) (fact (:dim (init-position '[- - -, - - -, - - -] 'x)) => 3) (fact (:turn (init-position)) => 'x) (fact (:turn (move (init-position) 0)) => 'o) (fact (:depth (init-position)) => 0) (fact (:depth (move (init-position) 0)) => 1) (fact (possible-moves (move (init-position) 0)) => (range 1 9)) (fact (win-lines {:board [0 1 2 3 4 5 6 7 8 9] :dim 3}) => '((0 1 2) (3 4 5) (6 7 8) [0 3 6] [1 4 7] [2 5 8] (0 4 8) (2 4 6))) ;;-------------------------------------------------- ;; win? ;;-------------------------------------------------- (fact (win? (init-position) 'x) => falsey) (fact (win? {:board '[x x x o o - - - -] :dim 3} 'x) => truthy) (fact (win? {:board '[x x - o o o - - -] :dim 3} 'o) => truthy) (fact (win? {:board '[x o x o o - x x x] :dim 3} 'x) => truthy) (fact (win? {:board '[x - o x o - x - -] :dim 3} 'x) => truthy) (fact (win? {:board '[o x - o x - - x -] :dim 3} 'x) => truthy) (fact (win? {:board '[- o x - o x - - x] :dim 3} 'x) => truthy) (fact (win? {:board '[x - o o x - - - x] :dim 3} 'x) => truthy) (fact (win? {:board '[- o x o x - x - -] :dim 3} 'x) => truthy) ;;-------------------------------------------------- ;; blocked? ;;-------------------------------------------------- (fact (blocked? {:board '[- o x o x - x - -] :dim 3}) => falsey) (fact (blocked? {:board '[x o x o o x x x o] :dim 3}) => truthy) ;;-------------------------------------------------- ;; evaluate-leaf ;;-------------------------------------------------- (fact (evaluate-leaf (init-position '[x - - - - - - - -] 'o)) => nil) (fact (evaluate-leaf (init-position '[x - o x o - x - -] 'o)) => 100) (fact (evaluate-leaf (init-position '[x o - x o x - o x] 'x)) => -100) (fact (evaluate-leaf (init-position '[x o x o o x - x o] 'o)) => 0) ;;-------------------------------------------------- ;; negamax ;;-------------------------------------------------- (binding [evaluate-leaf (fn [node] (if (= (class node) java.lang.Long) node nil)) find-children (fn [node] node)] (fact (negamax 4 -100 100 1) => 4) (fact (negamax [4] -100 100 1) => 4) (fact (negamax [4 5] -100 100 1) => 5) (fact (negamax [4 5 6 7] -100 5 1) => 4) (fact (negamax [4 5 6 7] -5 100 -1) => -4) ;; got this one from wikipedia on alpha-beta pruning (fact (negamax [[[[5 6] [7 4 5]] [[3]]] [[[6] [6 9]]] [[[5]] [[9 8] [6]]]] -100 100 1) => 6)) ;;-------------------------------------------------- ;; evaluate ;;-------------------------------------------------- (fact (evaluate (init-position '[x x o - x - - - o] 'o)) => -99) (fact (evaluate (init-position '[x - o - x - - - o] 'x)) => 0) (fact (evaluate (init-position '[x - o - x x - - o] 'o)) => 0) (fact (evaluate (init-position '[x - o x o - - - -] 'x)) => 99) (fact (evaluate (init-position '[x o o - o x - - x] 'o)) => -99) ;;-------------------------------------------------- ;; best-move ;;-------------------------------------------------- (fact (best-move (init-position '[o - x - o x - - -] 'x)) => 8) (fact (best-move (init-position '[x o x - o - - - -] 'o)) => 7) (fact (best-move (init-position '[x o - - x - - - -] 'o)) => 8) (fact (best-move (init-position '[x o - - - - - - -] 'x)) => 3) (fact (time (best-move (init-position '[- - - - - - - - -] 'x))) => 0) ;;-------------------------------------------------- ;; random-best-move ;;-------------------------------------------------- (fact (random-best-move (init-position)) => #(and (<= 0 %) (<= % 8)))
import { Color } from "../src/mygame/data/color" describe("color", () => { test("create a color from hex", () => { let color = Color.fromHex(0xaabbcc) expect(color.red).toBe(0xaa) expect(color.green).toBe(0xbb) expect(color.blue).toBe(0xcc) }) test("create a color from rgb values", () => { let color = Color.fromRgb255(0xaa, 0xbb, 0xcc) expect(color.red).toBe(0xaa) expect(color.green).toBe(0xbb) expect(color.blue).toBe(0xcc) }) test("color to hex", () => { let color = Color.fromRgb255(0xaa, 0xbb, 0xcc) // casted to a string to make result easier to read expect(color.asHex().toString(16)).toBe("aabbcc") }) })
import { createBrowserSubscription, createCassiopeia } from '@cassiopeia/vue' import '@unocss/reset/normalize.css' import { createPinia, type StateTree } from 'pinia' import 'uno.css' import { createSSRApp } from 'vue' import { createMemoryHistory, createRouter, createWebHistory } from 'vue-router' import App from './components/app.vue' import Calendar from './components/calendar.vue' import { useCepheusStore } from './hooks/use-cepheus-store' import { SSRContext } from 'vue/server-renderer' declare const INITIAL_STATE: Record<string, StateTree> export async function createApp(context?: SSRContext) { const pinia = createPinia() if (!import.meta.env.SSR) pinia.state.value = INITIAL_STATE const router = createRouter({ history: import.meta.env.SSR ? createMemoryHistory() : createWebHistory(), routes: [ { path: '/', component: Calendar }, { path: '/constraint', component: async () => await import('./components/constraint.vue') }, { path: '/swatches', component: async () => await import('./components/home.vue') }, { path: '/fitting', component: async () => await import('./components/canvas.vue') }, { path: '/triangle', component: async () => await import('./components/triangle.vue') }, { path: '/text', component: async () => await import('./components/text.vue') } ] }) const cepheusStore = useCepheusStore(pinia) const cepheus = await cepheusStore.createCepheus(context?.cepheus) const cassiopeia = createCassiopeia({ plugins: [cepheus] }) if (!import.meta.env.SSR) { cassiopeia.subscribe(createBrowserSubscription()) } const app = createSSRApp(App) .use(router) .use(pinia) .use(cepheus) .use(cassiopeia) return { app, cassiopeia, cepheusStore, pinia, router } }
<div class="header bg-gradient-danger pb-8 pt-5 pt-md-8"> <div class="container-fluid"> <div class="header-body"> <div class="row"> <div class="col"> <div class="card shadow"> <div class="card-header bg-transparent"> <h3 class="mb-0">Overview</h3> </div> <div [formGroup]="menuForm" class="card-body" *ngIf="menus$ | async as menus"> <mat-form-field > <mat-label>Menu</mat-label> <mat-select formControlName="menuId" *ngIf="menus[0]._id" (selectionChange)="onMenuChange($event)"> <mat-option *ngFor="let menu of menus" [value]="menu._id"> {{ menu.title }} </mat-option> </mat-select> </mat-form-field> <mat-tree class="col-md-8" [dataSource]="dataSource" [treeControl]="treeControl"> <!-- This is the tree node template for leaf nodes --> <mat-tree-node class="rm-pd " *matTreeNodeDef="let node" matTreeNodePadding> <!-- use a disabled button to provide padding for tree leaf --> <button mat-icon-button disabled></button> <a *ngIf="node.level == 0" routerLink="/">{{node.name}}</a> <a *ngIf="node.level == 1" routerLink="/">{{node.name}}</a> </mat-tree-node> <!-- This is the tree node template for expandable nodes --> <mat-tree-node class="mat-card" *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding> <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'toggle ' + node.name"> <mat-icon class="mat-icon-rtl-mirror"> {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}} </mat-icon> </button> <a *ngIf="node.level == 0" routerLink="/">{{node.name}}</a> <a *ngIf="node.level == 1" routerLink="/">{{node.name}}</a> </mat-tree-node> </mat-tree> </div> </div> </div> </div> </div> </div> </div>
import { createProductMedium, createNavigation } from "./generateTemplate"; import { mockCatalogueIntroData } from "./mockData"; import { getProductsBysubcatagory } from "./requests"; document.addEventListener('DOMContentLoaded', async () => { const cookie = document.cookie.split(';'); const cookieMap: Array<{ name: string, value: string }> = []; cookie.forEach( cookieElement => { const [cookieName, cookieValue] = cookieElement.split('='); const element = { name: cookieName, value: cookieValue } cookieMap.push(element); } ) const category = decodeURI(cookieMap.filter(cookieElement => cookieElement.name.trim() === 'category')[0].value); const name = decodeURI(cookieMap.filter(cookieElement => cookieElement.name.trim() === 'name')[0].value); const catalog = mockCatalogueIntroData.filter(item => item.title === category)[0]; document.querySelector('.catalog').appendChild(createNavigation(catalog)); Array.from(document.querySelectorAll('.catalogueItem')).forEach( element => { if (element.innerHTML.toLowerCase() != name.toLocaleLowerCase()) { element.classList.remove('current'); } } ) Array.from(document.querySelectorAll('.catalogueItem')).forEach( element => { if (element.innerHTML.toLowerCase() == name.toLocaleLowerCase()) { element.classList.add('current'); } } ) const productsContent = document.createElement('div'); productsContent.setAttribute('class', 'productsContent'); const products = await getProductsBysubcatagory(name); products.forEach( async product => { const productElement = await createProductMedium(product); productsContent.appendChild(productElement); } ) document.querySelector('.catalog').appendChild(productsContent); }) window.addEventListener( "pageshow", function ( event ) { var historyTraversal = event.persisted || (typeof window.performance != "undefined" && window.performance.navigation.type === 2 ); if ( historyTraversal ) { window.location.reload(); } });
"use client"; import {type FC} from 'react'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; interface ModalProps { title: string; description: string; isOpen: boolean; onClose: () => void; children?: React.ReactNode; } const Modal: FC<ModalProps> = ( { title, children, description, isOpen, onClose } ) => { const onChange = (open: boolean): void => { if (!open) { onClose(); } }; return ( <> <Dialog open={isOpen} onOpenChange={onChange}> <DialogContent> <DialogHeader> <DialogTitle>{title}</DialogTitle> <DialogDescription> {description} </DialogDescription> </DialogHeader> <div> {children} </div> </DialogContent> </Dialog> </> ); }; export default Modal;
#### pyenv > 다양한 파이썬 버전/배포판을 손쉽게 관리하기 위함. > Scoop 을 통한 pyenv 패키지가 설치 되었다고 가정합니다. ```bash # 설치 가능한 파이썬 버전/배포판 내역을 다시 읽습니다. pyenv update # 설치 가능한 파이썬 버전/배포판 출력 pyenv install --list # 지정 버전/이름의 파이썬을 설치 pyenv install 3.10.6 # 지정 버전을 디폴트(글로벌) 버전으로 설정 pyenv global 3.10.6 # (파워쉘 고유명령) python 경로가 pyenv 내에 있음을 확인 get-command pyenv python --version > Python 3.10.6 # 혹은 특정 프로젝트에서 다른 파이썬 버전을 사용할려면, 프로젝트 루트 경로에서 아래 명령을 수행 # .python-version 파일이 생성됩니다. 디렉토리를 벗어나면 global 버전을 따릅니다. # 물론 지정된 파이썬 버전은 먼저 설치되어있어야 합니다. pyenv install 3.10.6 pyenv local 3.10.6
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete'; import { ActivatedRoute, Router } from '@angular/router'; import { Observable, map, mergeMap } from 'rxjs'; import { Area } from 'src/app/core/model/area.model'; import { Autor } from 'src/app/core/model/autor.model'; import { Categoria } from 'src/app/core/model/categoria.model'; import { Editorial } from 'src/app/core/model/editorial.model'; import { Libro } from 'src/app/core/model/libro.model'; import { AreaService } from 'src/app/service/area.service'; import { AuthService } from 'src/app/service/auth.service'; import { AutorService } from 'src/app/service/autor.service'; import { CategoriaService } from 'src/app/service/categoria.service'; import { EditorialService } from 'src/app/service/editorial.service'; import { LibroService } from 'src/app/service/libro.service'; import Swal from 'sweetalert2'; @Component({ selector: 'app-libro-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'], }) export class LibroFormComponent implements OnInit { libro: Libro = new Libro(); areas: Area[] = []; categorias: Categoria[] = []; editoriales: Editorial[] = []; errors = { codigo: '', titulo: '', grado: '', area: '', categoria: '', editorial: '', autores: '', }; autocompleteControl = new FormControl(''); filteredAutores: Observable<Autor[]>; constructor( private libroService: LibroService, private areaService: AreaService, private categoriaService: CategoriaService, private editorialService: EditorialService, private autorService: AutorService, private authService: AuthService, private router: Router, private activedRoute: ActivatedRoute ) {} ngOnInit(): void { this.chargeLibro(); this.filteredAutores = this.autocompleteControl.valueChanges.pipe( map((value) => (typeof value === 'string' ? value : '')), mergeMap((value) => (value ? this._filter(value || '') : [])) ); this.categoriaService .getAll() .subscribe((categorias) => (this.categorias = categorias)); this.editorialService .getAll() .subscribe((editoriales) => (this.editoriales = editoriales)); this.areaService.getAll().subscribe((areas) => (this.areas = areas)); } chargeLibro(): void { this.activedRoute.params.subscribe((params) => { const id = params['id']; if (id) { this.libroService.getOne(id).subscribe((libro) => (this.libro = libro)); } }); } limpiar(): void { this.errors = { codigo: '', titulo: '', grado: '', area: '', categoria: '', editorial: '', autores: '', }; this.libro.autores = []; } save(): void { this.libroService.save(this.libro).subscribe({ next: (libro) => { this.router .navigate([this.routerLink() + '/libros/detail', libro.id]) .then(() => { Swal.fire({ icon: 'success', title: 'Libro guardado correctamente.', text: `Libro ${libro.titulo} ha sido guardado.`, }); }); }, error: (e) => { this.errors = e.error.errors; }, }); } update(): void { this.libroService.update(this.libro).subscribe({ next: (libro) => { this.router .navigate([this.routerLink() + '/libros/detail', libro.id]) .then(() => { Swal.fire({ icon: 'success', title: 'Libro actualizado correctamente.', text: `Libro ${libro.titulo} ha sido guardado.`, }); }); }, error: (err) => { this.errors = err.error.errors; }, }); } compareArea(area1: Area, area2: Area): boolean { if (area1 === undefined && area2 === undefined) { return true; } return area1 == null || area2 == null ? false : area1.id === area2.id; } compareCategoria(categoria1: Categoria, categoria2: Categoria): boolean { if (categoria1 === undefined && categoria2 === undefined) { return true; } return categoria1 == null || categoria2 == null ? false : categoria1.id === categoria2.id; } compareEditorial(editorial1: Editorial, editorial2: Editorial): boolean { if (editorial1 === undefined && editorial2 === undefined) { return true; } return editorial1 == null || editorial2 == null ? false : editorial1.id === editorial2.id; } private _filter(value: string): Observable<Autor[]> { const filterValue = value.toLowerCase(); return this.autorService.getAllByNombreAndApellido(filterValue); } byNombreOrApellido(autor?: Autor): string { return autor ? autor.nombre : ''; } existItem(id: number): boolean { let exist = false; this.libro.autores.forEach((autor: Autor) => { if (id === autor.id) { exist = true; } }); return exist; } selectAutor(event: MatAutocompleteSelectedEvent): void { const autor = event.option.value as Autor; if (!this.existItem(autor.id)) { this.libro.autores.push(autor); this.autocompleteControl.setValue(''); event.option.focus(); event.option.deselect(); } } deleteAutor(id: number): void { this.libro.autores = this.libro.autores.filter( (autor: Autor) => id !== autor.id ); } routerLink(): string { return this.authService.hasRol('ROLE_ADMIN') ? '/admin' : '/user'; } }
package xyz.kurozero.notes.ui.activities import android.app.Activity import android.app.DatePickerDialog import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.EditText import android.widget.Toast import com.afollestad.materialdialogs.MaterialDialog import com.arellomobile.mvp.MvpAppCompatActivity import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.ProvidePresenter import xyz.kurozero.notes.R import xyz.kurozero.notes.mvp.model.Note import xyz.kurozero.notes.mvp.presenters.NotePresenter import xyz.kurozero.notes.mvp.views.NoteView import xyz.kurozero.notes.utils.formatDate import kotlinx.android.synthetic.main.activity_note.* import java.util.* class NoteActivity : MvpAppCompatActivity(), NoteView { companion object { var forDate: Date = Date() const val NOTE_DELETE_ARG = "note_id" fun buildIntent(activity: Activity, noteId: Long): Intent { val intent = Intent(activity, NoteActivity::class.java) intent.putExtra(NOTE_DELETE_ARG, noteId) return intent } } @InjectPresenter lateinit var presenter: NotePresenter private var noteDeleteDialog: MaterialDialog? = null private var noteInfoDialog: MaterialDialog? = null @ProvidePresenter fun provideHelloPresenter(): NotePresenter { val noteId = intent.extras.getLong(NOTE_DELETE_ARG, -1) return NotePresenter(noteId) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_note) forDate = Date() etForDate.setText(formatDate(Date())) val cal = Calendar.getInstance() val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> cal.set(Calendar.YEAR, year) cal.set(Calendar.MONTH, monthOfYear) cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) forDate = cal.time etForDate.setText(formatDate(cal.time)) } etForDate.setOnClickListener { DatePickerDialog(this@NoteActivity, dateSetListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show() } etTitle.onFocusChangeListener = View.OnFocusChangeListener { view, hasFocus -> if (hasFocus) { val editText = view as EditText editText.setSelection((editText.text.length)) } } } override fun showNote(note: Note) { etForDate.setText(formatDate(note.forDate)) etTitle.setText(note.title) etText.setText(note.text) } override fun showNoteInfoDialog(noteInfo: String) { noteInfoDialog = MaterialDialog.Builder(this) .title(R.string.note_info) .positiveText(R.string.ok) .content(noteInfo) .onPositive { _, _ -> presenter.hideNoteInfoDialog() } .cancelListener { presenter.hideNoteInfoDialog() } .show() } override fun hideNoteInfoDialog() { noteInfoDialog?.dismiss() } override fun showNoteDeleteDialog() { noteDeleteDialog = MaterialDialog.Builder(this) .title(getString(R.string.note_deletion_title)) .content(getString(R.string.note_deletion_message)) .positiveText(getString(R.string.yes)) .negativeText(getString(R.string.no)) .onPositive { _, _ -> presenter.hideNoteDeleteDialog() presenter.deleteNote() } .onNegative { _, _ -> presenter.hideNoteDeleteDialog() } .cancelListener { presenter.hideNoteDeleteDialog() } .show() } override fun hideNoteDeleteDialog() { noteDeleteDialog?.dismiss() } override fun onNoteSaved() { Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show() } override fun onNoteDeleted() { Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show() finish() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.note, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuSaveNote -> presenter.saveNote(etTitle.text.toString(), etText.text.toString(), forDate) R.id.menuDeleteNote -> presenter.showNoteDeleteDialog() R.id.menuNoteInfo -> presenter.showNoteInfoDialog() } return super.onOptionsItemSelected(item) } }
// Copyright (c) 2021-2022 THL A29 Limited // // This source code file is made available under MIT License // See LICENSE for details import React, { useState, useEffect } from 'react'; import cn from 'classnames'; import { isEmpty, pick, isArray } from 'lodash'; import { saveAs } from 'file-saver'; import { Dropdown, Menu, Tooltip, Modal, message, Upload, Button } from 'coding-oa-uikit'; import EllipsisH from 'coding-oa-uikit/lib/icon/EllipsisH'; import { getScanDir, addScanDir, delAllScanDir, importScanDir, getSysPath, } from '@src/services/schemes'; import { SCAN_TYPES, PATH_TYPES } from '../constants'; import List from './cus-list'; import SysList from './sys-list'; import AddModal from './modal'; import style from './style.scss'; const initialPager = { count: 0, pageStart: 0, pageSize: 10, }; interface PathProps { orgSid: string; teamName: string; repoId: number; schemeId: number; } const Path = (props: PathProps) => { const { orgSid, teamName, repoId, schemeId } = props; const [tab, setTab] = useState('cus'); const [cusList, setCusList] = useState([]); const [pager, setPager] = useState(initialPager); const { pageSize, pageStart } = pager; const [visible, setVisible] = useState(false); const [importModalVsb, setImportModalVsb] = useState(false); const [importModalData, setImportModalData] = useState([]); const [sysList, setSysList] = useState([]); useEffect(() => { getListData(initialPager.pageStart, initialPager.pageSize); schemeId && getSysList(); }, [schemeId]); /** * 获取自定义过滤路径 * @param offset * @param limit */ const getListData = (offset: number = pageStart, limit: number = pageSize) => { if (schemeId) { getScanDir(orgSid, teamName, repoId, schemeId, { offset, limit }).then((response) => { setPager({ pageSize: limit, pageStart: offset, count: response.count, }); setCusList(response.results || []); }); } }; /** * 获取系统过滤路径 */ const getSysList = () => { getSysPath(orgSid, teamName, repoId, schemeId, { exclude: 1, }).then((response: any) => { const res = response.results || []; getSysPath(orgSid, teamName, repoId, schemeId).then((response: any) => { setSysList(res.concat((response?.results ?? []).map((item: any) => ({ ...item, switch: true, })))); }); }); }; /** * 导出路径配置 */ const exportScanDir = () => { getScanDir(orgSid, teamName, repoId, schemeId, { limit: pager.count }).then((response: any) => { const res = response?.results?.map((item: object) => pick(item, ['dir_path', 'path_type', 'scan_type'])) ?? []; const blob = new Blob([JSON.stringify(res)], { type: 'text/plain;charset=utf-8' }); saveAs(blob, 'path_confs.json'); message.success('导出成功'); }); }; /** * 批量导入路径配置 */ const importScanDirHandle = (dirs: object) => { importScanDir(orgSid, teamName, repoId, schemeId, dirs).then((response: any) => { message.success(`${response.detail || '导入成功'}`); getListData(initialPager.pageStart, pageSize); setImportModalVsb(false); }); }; /** * 手动上传处理 * @param file */ const handleUpload = (file: any) => { if (file) { const reader = new FileReader(); reader.readAsText(file, 'UTF-8'); reader.onload = function () { setImportModalVsb(true); if (this.result) { setImportModalData(JSON.parse(this.result as string)); } }; } return false; }; /** * 添加过滤路径 * @param data */ const onAdd = (data: any) => { addScanDir(orgSid, teamName, repoId, schemeId, data).then(() => { getListData(pageStart, pageSize); message.success('添加成功'); setVisible(false); }); }; /** * 清空过滤路径 */ const onDelAll = () => { Modal.confirm({ title: '清空自定义过滤路径', content: '确定清空该分析方案的所有过滤路径配置?', onOk: () => { delAllScanDir(orgSid, teamName, repoId, schemeId).then(() => { message.success('清空成功'); getListData(initialPager.pageStart, pageSize); }); }, }); }; return ( <div className={style.path}> <div className={style.header}> <div className={style.tab}> <span className={cn(style.tabItem, { [style.active]: tab === 'cus' })} onClick={() => setTab('cus')} > 自定义 </span> <span className={cn(style.tabItem, { [style.active]: tab === 'sys' })} onClick={() => setTab('sys')} > 系统默认 </span> </div> {tab === 'cus' && ( <div className={style.operation}> <Button onClick={() => setVisible(true)}>添加过滤路径</Button> <Dropdown placement='bottomRight' overlay={ <Menu className={style.menu} onClick={({ domEvent }) => domEvent.stopPropagation()}> <Menu.Item key='import'> <Upload beforeUpload={handleUpload} fileList={[]} > <Tooltip placement="left" overlayClassName={style.importTooltip} getPopupContainer={() => document.body} title={ <span> 配置提示:<br /> 参数:dir_path表示路径;<br /> path_type表示路径类型,1为通配符,2为正则表达式;<br /> scan_type表示过滤类型,1为只分析,2为只屏蔽;<br /> [{'{"dir_path": "xxx", "path_type": 1, "scan_type": 1}'},…] </span> }> <span>导入路径配置</span> </Tooltip> </Upload> </Menu.Item> { !isEmpty(cusList) && ([ <Menu.Item key='export' onClick={exportScanDir}>导出路径配置</Menu.Item>, <Menu.Item key='delAll' onClick={onDelAll} className={style.delAll} >一键清空路径配置</Menu.Item>, ]) } </Menu> }> <Button className={style.more} onClick={(e: any) => e.stopPropagation()}> <EllipsisH /> </Button> </Dropdown> <Modal visible={importModalVsb} title='批量添加过滤路径' className={style.importModal} onCancel={() => setImportModalVsb(false)} onOk={(e) => { e.stopPropagation(); importScanDirHandle({ scandirs: importModalData }); }} > <ul className={style.pathContent}> { isArray(importModalData) && importModalData.map((item: any, index: number) => ( <li key={`index-${index}`}> <span title={item.dir_path}>{item.dir_path}</span> <span>{PATH_TYPES[item.path_type] || item.path_type}</span> <span>{SCAN_TYPES[item.scan_type] || item.scan_type}</span> </li> )) } </ul> <p>共:{importModalData.length}条路径</p> </Modal> </div> )} </div> <AddModal isEditModal={false} visible={visible} onHide={() => setVisible(false)} onUpdateScanDir={onAdd} /> {tab === 'sys' ? ( <SysList orgSid={orgSid} teamName={teamName} repoId={repoId} schemeId={schemeId} data={sysList} getListData={getSysList} /> ) : ( <List orgSid={orgSid} teamName={teamName} repoId={repoId} schemeId={schemeId} data={cusList} pager={pager} getListData={getListData} /> )} </div> ); }; export default Path;
// ItinerariesComponent.jsx import React, { useState, useEffect } from "react"; import axios from "axios"; // Import axios import "./ItinariesComponent.css"; import Navbar from "../Navbar/Navbar.js"; import "./ItinariesComponent.css"; const ItinerariesComponent = ({ history }) => { const [itineraries, setItineraries] = useState([]); const [searchTerm, setSearchTerm] = useState(""); useEffect(() => { // Use axios to fetch data axios .get("http://localhost:4000/api/itinerary") .then((response) => { if (Array.isArray(response.data.data)) { setItineraries(response.data.data); } console.log(response.data.data); }) .catch((error) => { console.error("Error fetching data:", error); }); }, []); const handleInputChange = (event) => { const value = event.target.value; setSearchTerm(value); // You can call other functions here or do further processing based on the value searchItineraries(value); }; const formatDate = (dateString) => { const options = { year: "2-digit", month: "2-digit", day: "2-digit" }; return new Date(dateString).toLocaleDateString("en-GB", options); }; const searchItineraries = (term) => { // Search the itineraries or make an API call based on the term axios .get("http://localhost:4000/api/itinerary?destination=" + term) .then((response) => { if (Array.isArray(response.data.data)) { setItineraries(response.data.data); } console.log(response.data.data); }) .catch((error) => { console.error("Error fetching data:", error); }); }; const itineraryRedirect = (itineraryId) => { history.push(`/itinerary/${itineraryId}`); }; return ( <div className="itineraries-main"> {/* <Navbar /> */} <section className="search-section"> <input type="text" className="search-input" placeholder="Search for Itineraries" value={searchTerm} onChange={handleInputChange} /> </section> <section className="itineraries-section"> <h2 style={{ fontSize: "18px" }}>Travel Itineraries</h2> {itineraries.map((itinerary, index) => ( <div key={index} className="card" onClick={() => itineraryRedirect(itinerary._id)} > <img src={itinerary.imageUrl} alt="Itinerary" /> <div className="card-info"> <p className="location"> <span role="img" aria-label="pin"> 📍 </span>{" "} {itinerary.destination} </p> <p className="date"> <span role="img" aria-label="calendar"> 📅 </span>{" "} {formatDate(itinerary.startDate)}- {formatDate(itinerary.endDate)}{" "} </p> </div> </div> ))} </section> <footer>{/* Footer content goes here */}</footer> </div> ); }; export default ItinerariesComponent;
package com.example.storyapp.ui.authentication.register import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.findNavController import com.example.storyapp.R import com.example.storyapp.databinding.FragmentRegisterBinding import com.example.storyapp.ui.custom.EmailEditText import com.example.storyapp.ui.custom.MyCustomButtonRegister import com.example.storyapp.ui.custom.NameEditText import com.example.storyapp.ui.custom.PasswordEditText import com.example.storyapp.utils.PrimaryViewModelFactory import com.example.storyapp.utils.Result class RegisterFragment : Fragment() { private lateinit var myButtonRegister: MyCustomButtonRegister private lateinit var nameEditText: NameEditText private lateinit var emailEditText: EmailEditText private lateinit var passwordEditText: PasswordEditText private var isNameTextChanged = false private var isEmailTextChanged = false private var isPasswordTextChanged = false private val factory: PrimaryViewModelFactory by lazy { PrimaryViewModelFactory.getInstance(requireActivity()) } private val viewModel: RegisterViewModel by viewModels { factory } private var _binding: FragmentRegisterBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment _binding = FragmentRegisterBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) myButtonRegister = binding.btnSignup nameEditText = binding.edRegisterName emailEditText = binding.edRegisterEmail passwordEditText = binding.edRegisterPassword nameEditText.addTextChangedListener(object : TextWatcher { // dipanggil ketika text belum dirubah // alasan method ini kosong dikarenakan tidak ada efek yg ditampilkan sebelum text dirubah override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } // dipanggil ketika text sedang mengalami perubahan override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { isNameTextChanged = true checkBothTextChanged() } // dipanggil ketika text sudah dirubah override fun afterTextChanged(s: Editable) { } }) emailEditText.addTextChangedListener(object : TextWatcher { // dipanggil ketika text belum dirubah // alasan method ini kosong dikarenakan tidak ada efek yg ditampilkan sebelum text dirubah override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } // dipanggil ketika text sedang mengalami perubahan override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { isEmailTextChanged = true checkBothTextChanged() } // dipanggil ketika text sudah dirubah override fun afterTextChanged(s: Editable) { } }) passwordEditText.addTextChangedListener(object : TextWatcher { // dipanggil ketika text belum dirubah // alasan method ini kosong dikarenakan tidak ada efek yg ditampilkan sebelum text dirubah override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } // dipanggil ketika text sedang mengalami perubahan override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { isPasswordTextChanged = true checkBothTextChanged() } // dipanggil ketika text sudah dirubah override fun afterTextChanged(s: Editable) { } }) myButtonRegister.setOnClickListener { val nameRegister = nameEditText.text.toString() val emailRegister = emailEditText.text.toString() val passwordRegister = passwordEditText.text.toString() postRegister(nameRegister,emailRegister,passwordRegister) } playAnimation() } private fun playAnimation() { val title = ObjectAnimator.ofFloat(binding.tvTitleSignup, View.ALPHA, 1f).setDuration(100) val nameEditTextLayout = ObjectAnimator.ofFloat(binding.edRegisterName, View.ALPHA, 1f).setDuration(100) val emailEditTextLayout = ObjectAnimator.ofFloat(binding.edRegisterEmail, View.ALPHA, 1f).setDuration(100) val passwordEditTextLayout = ObjectAnimator.ofFloat(binding.edRegisterPassword, View.ALPHA, 1f).setDuration(100) val register = ObjectAnimator.ofFloat(binding.btnSignup, View.ALPHA, 1f).setDuration(100) AnimatorSet().apply { playSequentially( title, nameEditTextLayout, emailEditTextLayout, passwordEditTextLayout, register ) startDelay = 100 }.start() } private fun checkBothTextChanged() { if (isNameTextChanged && isEmailTextChanged && isPasswordTextChanged) { setMyButtonEnable() } } private fun setMyButtonEnable() { val nameValue = nameEditText.text val emailValue = emailEditText.text val passwordValue = passwordEditText.text myButtonRegister.isEnabled = nameValue != null && nameValue.toString().isNotEmpty() && emailValue != null && emailValue.toString().isNotEmpty() && passwordValue != null && passwordValue.toString().isNotEmpty() } private fun postRegister(name: String,email: String,password: String){ viewModel.postRegister(name,email,password).observe(viewLifecycleOwner){result-> when(result) { is Result.Loading -> { binding.progressBarRegister.visibility = View.VISIBLE } is Result.Success -> { binding.progressBarRegister.visibility = View.GONE Toast.makeText(context, "message is :$result", Toast.LENGTH_LONG).show() view?.findNavController()?.navigate(R.id.action_registerFragment_to_loginFragment2) } is Result.Error -> { binding.progressBarRegister.visibility = View.GONE Toast.makeText(context, result.error, Toast.LENGTH_LONG).show() } } } } }
<!DOCTYPE html> <html lang="es"> <head> <!-- Metadatos --> <meta charset="utf-8" /> <meta name="author" content="Piano House" /> <meta name="description" content="Tienda online de instrumentos musicales" /> <meta name="keywords" content="Instrumento, Sonido, Audio, Musica, Voz, Posadas, Misiones" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Titulo --> <title>Piano House</title> <!-- Favicon --> <link rel="icon" type="image/x-icon" href="images/logo-main.png" /> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" /> <!-- CSS --> <link rel="stylesheet" href="css/style.css" /> <!-- Google Fonts --> <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=Nunito&family=Poppins&family=Quicksand:wght@500&family=Rubik+Dirt&family=Ubuntu:wght@300&display=swap" rel="stylesheet"> </head> <body> <header></header> <!-- Barra de Navegacion --> <nav class="navbar navbar-expand-md navbar-light py-1"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar-toggler" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar-toggler"> <a class="navbar-brand" href="../index.html"> <img src="./images/logo-main.png" width="50" alt="Logo de la pagina" /> <span class="logo-text">Piano House</span> </a> <ul class="navbar-nav d-flex justify-content-center align-items-center"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="index.html">Inicio</a> </li> <li class="nav-item"> <a class="nav-link" href="pages/productos.html">Productos</a> </li> <li class="nav-item"> <a class="nav-link" href="pages/acerca-de.html">Acerca De</a> </li> <li class="nav-item"> <a class="nav-link" href="pages/carrito.html">Carrito</a> </li> </ul> </div> </div> </nav> <main></main> <!-- Contenido --> <section class="container align-items-stretch"> <div id="carouselExampleAutoplaying" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="images/inicio-carousel-1.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="images/inicio-carousel-2.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="images/inicio-carousel-3.jpg" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <br><br> <div class="card border border-0"> <div class="row g-0"> <div class="col-md-7 card-body px-5 py-5"> <h5 class="card-title">¡Bienvenido a nuestra tienda de instrumentos musicales!</h5> <p class="card-text lh-base">Donde tu pasión por la música se encuentra con una amplia gama de opciones para expresar tu creatividad y talento! Nos enorgullece ofrecer a músicos de todos los niveles y estilos una cuidadosa selección de instrumentos de alta calidad que no solo cumplirán con tus expectativas, sino que también elevarán tu experiencia musical a nuevas alturas.</p> </div> <div class="col-md-5"> <img src="images/inicio-card-1.jpg" class="img-fluid rounded-end" alt="..."> </div> </div> </div> <br> <div class="card border border-0"> <div class="row g-0"> <div class="col-md-5"> <img src="images/inicio-card-2.jpg" class="img-fluid rounded-start" alt="..."> </div> <div class="col-md-7 card-body px-5 py-5"> <h5 class="card-title">¡Explora nuestro catálogo diverso!</h5> <p class="card-text lh-base">Abarca desde guitarras y teclados hasta baterías y equipos de grabación. Nos dedicamos a proporcionar no solo productos excepcionales, sino también un servicio personalizado que te guiará en cada paso de tu viaje musical. Ya seas un principiante emocionado por dar los primeros acordes o un músico experimentado en busca de la última tecnología, estamos aquí para inspirarte y ayudarte a encontrar el instrumento perfecto que se ajuste a tu estilo y necesidades. ¡Sumérgete en la magia de la música con nosotros y déjanos ser tu socio en la creación de melodías inolvidables!</p> </div> </div> </div> </section> <br><br> <!-- Footer --> <footer class="seccion-oscura d-flex flex-column align-items-center justify-content-center"> <p class="footer-texto text-center">¡Seguinos en nuestras redes sociales!</p> <div class="iconos-redes-sociales d-flex flex-wrap align-items-center justify-content-center"> <a href="https://instagram.com/" target="_blank" rel="noopener noreferrer"> <i class="bi bi-instagram"></i> </a> <a href="https://www.youtube.com/" target="_blank" rel="noopener noreferrer"> <i class="bi bi-youtube"></i> </a> <a href="https://web.whatsapp.com/%F0%9F%8C%90/es" target="_blank" rel="noopener noreferrer"> <i class="bi bi-whatsapp"></i> </a> <a href="https://twitter.com/?lang=es" target="_blank" rel="noopener noreferrer"> <i class="bi bi-twitter-x"></i> </a> <a href="https://www.facebook.com/?locale=es_LA" target="_blank" rel="noopener noreferrer"> <i class="bi bi-facebook"></i> </a> <a href="https://github.com/Dario-Ferreyra/bootcampFrontEnd-UTN-Silicon" target="_blank" rel="noopener noreferrer"> <i class="bi bi-github"></i> </a> </div> <div class="derechos-de-autor">Creado por Ferreyra Dario (2023) &#169;</div> </footer> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </body> </html>
module; #include <cstdlib> #include <iostream> #ifdef __cpp_lib_generator #include <generator> #endif export module CoroutineLibrary; using namespace std; export class CoroutineLibrary { #ifdef __cpp_lib_generator static auto generateRandom(int randomNumbers) noexcept { std::cout << "Generating random numbers" << std::endl; for (int i = 0; i < randomNumbers; i++) { co_yield rand(); } } #endif static void generateRandoms() noexcept { #ifdef __cpp_lib_generator std::cout << "Running Coroutine Library" << std::endl; std::cout << "Coroutine Library is available" << std::endl; for (auto i : generateRandom(10)) { std::cout << "Random number is " << i << std::endl; } #else std::cout << "Coroutine Library is not available" << std::endl; return; #endif } public: static void Run() { std::cout << "-------------------CoroutineLibrary----------------" << std::endl; generateRandoms(); } };
#pragma once /*- -*- THE C STANDARD LIBRARY -*- -*/ #include <stddef.h> #include <string.h> /*- -*- THE C++ STANDARD LIBRARY -*- -*/ #include <algorithm> #include <initializer_list> #include <stdexcept> #include <functional> /*- -*- REINVENTING THE WHEEL LIBRARY -*- -*/ #include "iterator.tcc" /** * @brief Classes that inherit from parents can be forward declared, but the * inheritance itself must only go in the class definition proper. * * However, default values must go in the forward declarations! */ namespace crim { /** * @brief A somewhat generic growable array that can be templated over. * * This is not meant for you to use in your programs, rather it is * meant to be used by templates to inherit basic functionality to * allow method chaining from child classes. * * Most likely you'll be using this with other templates. * You'll need to pass the templated name, e.g: * * `template<CharT>class string : base_dyarray<string<CharT>, CharT>` * * @details This utilizes the Continuous Recurring Template Pattern (CRTP). * * Imagine it like a template class for template classes, where * descendent templates inherit & specialize from this. At the same * time, they get access to method chaining. * * Although it can get ugly and verbose, this allows us to reuse * implementation and method chaining of child classes! * * For more information, see: https://stackoverflow.com/a/56423659 * * @tparam DerivedT The derived class's name, usually the templated name. * @tparam ElemT Buffer's element type. * @tparam AllocT Desired allocator, based off of `std::allocator`. */ template< class DerivedT, class ElemT, class AllocT = std::allocator<ElemT> > class base_dyarray; }; template<class DerivedT, class ElemT, class AllocT> class crim::base_dyarray { private: friend DerivedT; // allows access private and protected members of caller! DerivedT &derived_cast() { return static_cast<DerivedT &>(*this); } DerivedT &derived_cast() const { return static_cast<DerivedT const&>(*this); } using Malloc = std::allocator_traits<AllocT>; protected: static constexpr size_t DYARRAY_START_CAPACITY = 16; static constexpr size_t DYARRAY_MAX_CAPACITY = 0xFFFFFFFF; // 1-based. AllocT m_malloc; size_t m_nlength; // Number of elements written to buffer currently. size_t m_ncapacity; // Number of elements that buffer could hold. ElemT *m_pbuffer; // Heap-allocated 1D array of the specified type. iterator<ElemT> m_iterator; /* -*- CONSTRUCTORS, DESTRUCTORS -*- */ // NOTICE: These are protected to avoid users calling these by themselves! // See: https://www.reddit.com/r/cpp/comments/lhvkzs/comment/gn3nmsx/ // Primary delegated constructor. base_dyarray(size_t n_length, size_t n_capacity, ElemT *p_memory) : m_malloc{} , m_nlength{n_length} , m_ncapacity{n_capacity} , m_pbuffer{p_memory} , m_iterator(m_pbuffer, m_nlength) {} // Default constructor, zeroes out the memory. base_dyarray() : base_dyarray(0, 0, nullptr) {} /** * @brief Secondary delegated constructor which takes care of allocating * the correct amount of memory. It in turn delegates to the * primary delegated constructor. */ base_dyarray(size_t n_length, size_t n_capacity) : base_dyarray(n_length, n_capacity, Malloc::allocate(m_malloc, n_capacity)) {} /** * @brief Constructor for "array literals" (curly brace literals) which * are really implemented via `std::initializer_list` objects. * * This copies all the elements of the list into our buffer. * * Upon an append/push_back, this will likely cause a realloc. */ base_dyarray(std::initializer_list<ElemT> list) : base_dyarray(list.size(), list.size()) { // this->begin() should be the non-const version even if we're const std::copy(list.begin(), list.end(), begin()); } /** * @brief Copy-constructor, it allocates enough memory for the buffer * hold `src`'s data buffer, then it deep-copies them. */ base_dyarray(const base_dyarray &src) : base_dyarray(src.length(), src.capacity()) { // this->begin() should be the non-const version even if we're const std::copy(src.begin(), src.end(), begin()); } /** * @brief Move-constructor, does a shallow copy of `tmp`, which is a * temporary value/expression (usually an rvalue). * * `tmp` itself has its internal buffer set to `nullptr` after * copying so that upon its destruction, the memory isn't freed! * * @note [See here for help.](https://learn.microsoft.com/en-us/cpp/cpp/move-constructors-and-move-assignment-operators-cpp?view=msvc-170) */ base_dyarray(base_dyarray &&tmp) : base_dyarray(tmp.length(), tmp.capacity(), tmp.begin()) { tmp.reset(); } /** * @brief Destroys all constructed objects in the buffer for the range * `m_pbuffer[0 ... length()-1]`. * * We do this before deallocating the pointer so we can call * destructors for non-trivially destructible objects. * * @note Anything past `length()` should be uninitialized so there's no * need to manually destroy `m_pbuffer[length()-1 ... capacity()]`. */ ~base_dyarray() { // Malloc::deallocate doesn't accept nullptr so let's avoid that. // Conditional jump or move depends on uninitizlised value(s)? if (m_pbuffer != nullptr) { // Destroy all constructed objects we have, because memory is hard. for (size_t i = 0; i < length(); i++) { Malloc::destroy(m_malloc, &m_pbuffer[i]); } // Only after instances are destroyed can we get rid of the pointer. Malloc::deallocate(m_malloc, m_pbuffer, capacity()); } } private: /** * @brief Effectively zeroes out the memory. * * Primarily to erase `m_pbuffer` of temporary instances so that * when they're destroyed the memory pointed is safe from deletion. * * @warning Assumes you've taken care of freeing/moving memory properly! */ void reset() { m_nlength = 0; m_ncapacity = 0; m_pbuffer = nullptr; m_iterator.set_range(nullptr, 0); } public: /* -*- NON-CONST DATA ACCESS METHODS -*- */ /** * @brief Read-write element access from the internal buffer. * * @exception `std::out_of_range` if requested index is out of bounds. * Should also work for negative indexes as they'll overflow. */ ElemT &at(size_t index) { if (index > m_nlength) { throw std::out_of_range("Requested base_dyarray index is invalid!"); } return m_pbuffer[index]; } /** * @brief Read-write element access from the internal buffer. * * @exception `std::out_of_range` if requested index is out of bounds. * Should also work for negative indexes as they'll overflow. */ ElemT &operator[](size_t index) { return at(index); } /** * @brief Read-write pointer to the start of the internal buffer. * * This is mainly meant for strings, where the buffer is usually * (or supposed to be) nul-terminated. * * @warning Be careful with updating the buffer this way! If you get into * trouble, all I can say is good luck! */ ElemT *data() { return m_pbuffer; } /* -*- CONST DATA ACCESS METHODS -*- */ /** * @brief See if begin and end iterators point to the exact same address. * * This is because on empty initialization, they do! But once at * least one element is pushed back, the end pointer increments. */ bool empty() const { return m_iterator.empty(); } /** * @brief Gets number of elements written to the internal buffer. For * strings, this count (likely) already excludes nul-termination. */ size_t length() const { return m_nlength; } /** * @brief Gets number of elements our buffer can hold at most currently. * In other words, this is how much space is allocated for the * buffer right now. */ size_t capacity() const { return m_ncapacity; } /** * @brief Maximum allowable elements the buffer can be allocated for. * * @note static constexpr member functions cannot be const functions. */ static constexpr size_t max_length() { return DYARRAY_MAX_CAPACITY; } /** * @brief Read-only pointer to the internal buffer. Useful for strings. * For string classes, this should return nul terminated data. * * @note See [cppreference.com.](https://en.cppreference.com/w/cpp/container/vector/data) */ const ElemT *data() const { return m_pbuffer; } /* -*- ITERATORS -*- */ /** * @brief Get a read-write iterator that points to the very first element * in the buffer. */ ElemT *begin() { return m_iterator.begin(); } /** * @brief Get a read-write iterator that points to an address 1 past the * last written element. * * @warning Don't dereference this if you know what's good for you! */ ElemT *end() { return m_iterator.end(); } /** * @brief Get a read-only iterator that points to the very first element * in the buffer. */ const ElemT *begin() const { return m_iterator.begin(); } /** * @brief Get a read-only iterator that points to an address 1 past the * last written element. * * @warning Don't dereference this if you know what's good for you! */ const ElemT *end() const { return m_iterator.end(); } /* -*- DATA COPYING AND MOVEMENT -*- */ // Assignment operator overloads cannot be called from the child directly. // You'll need a wrapper like `crim::string &operator=(crim::string &&src)`. DerivedT &copy(const base_dyarray &src) { // Don't copy ourselves, copying overlapping memory won't end well. if (this != &src) { // Clear any constructed instances and heap-allocated memory. this->~base_dyarray(); // Deep-copy only up to last written index to avoid unitialized // memory. std::copy calls copy-constructor for each non-trivial. m_pbuffer = Malloc::allocate(m_malloc, src.capacity()); std::copy(src.begin(), src.end(), begin()); m_nlength = src.m_nlength; m_ncapacity = src.m_ncapacity; m_iterator.set_range(m_pbuffer, m_nlength); } return derived_cast(); } DerivedT &move(base_dyarray &&src) { // If we try to move ourselves, we'll destroy the same buffer! if (this != &src) { // Clear any constructed instances and heap-allocated memory. // Causes a conditional jump/move based on uninitialised value(s) this->~base_dyarray(); // Do a shallow copy, since `src` will be destroyed shortly anyway. m_pbuffer = src.begin(); m_nlength = src.length(); m_ncapacity = src.capacity(); m_iterator = src.m_iterator; // `src.m_pbuffer` is set to null so it's safe from deletion now. src.reset(); } return derived_cast(); } public: /* -*- BUFFER MANIPULATION -*- */ /** * @brief Moves `entry` to the top of the internal buffer. That is, it is * move-assigned to the index after the previously written element. * * It's mainly helpful for objects with a clear move-assigment, * such as by overloading the `=` operator. For example, see: * `crim::dystring &operator=(crim::dystring &&)`. * * @note We take an rvalue reference so `entry` itself maybe invalidated! * This function only really works with temporary values. */ DerivedT &push_back(ElemT &&entry) { // `entry`, being named, "decays" to an lvalue reference so do this // so we can call the move constructor. return push_back_helper([&]() { m_pbuffer[m_nlength++] = std::move(entry); }); } /** * @brief Copies `entry` by value to the top of the internal buffer. That * is, its copy-constructor (or a default one) is called to assign * that value to the index after the previously written element. * * @note We take a const lvalue reference so that we do not need to * overload for const and non-const, as we do not intend to modify * `entry` in any way. */ DerivedT &push_back(const ElemT &entry) { return push_back_helper([&]() { m_pbuffer[m_nlength++] = entry; }); } private: /** * @brief Simple wrapper to help us generalize for either: * `const ElemT &` (constant lvalue reference, named instance) * `ElemT &&` (writeable rvalue reference, temporary instance) * * @param assign_fn A lambda function or a callback function. Capture * everything by reference (and `this` by value) then * do whatever you need in the function body. */ DerivedT &push_back_helper(std::function<void(void)> assign_fn) { if (m_nlength > DYARRAY_MAX_CAPACITY) { throw std::length_error("Reached crim::base_dyarray::MAXLENGTH!"); } else if (m_nlength + 1 > m_ncapacity) { // All the cool kids seem to grow their buffers by doubling it! resize(empty() ? DYARRAY_START_CAPACITY : m_ncapacity * 2); } // Important if non-trivial constructors/heap-allocations are involved! Malloc::construct(m_malloc, &m_pbuffer[m_nlength]); // Lets us generalize for const lvalue reference or rvalue reference. assign_fn(); // Don't try to dereference unitialized memory and get its address! m_iterator.m_end++; return derived_cast(); } public: /** * @brief Reallocates memory for the buffer by extension or narrowing. * * @details Similar to C's `realloc`. Cleans up the old memory as well. * Updates internals for you accordingly so you don't have to! * * @param new_size New requested buffer size, may be greater or lesser. * * @warning For strings, this may not guarantee nul termination! */ DerivedT &resize(size_t n_newsize) { // This is stupid so don't even try :) if (n_newsize == m_ncapacity) { return derived_cast(); } ElemT *p_dummy = Malloc::allocate(m_malloc, n_newsize); // Need for later so we deallocate the correct number of elements. size_t n_oldsize = m_ncapacity; // Does the new size extend the buffer or not? // true: Use current `m_index` since any farther is uninitialized. // false: Buffer was shortened, so `n_newsize` *is* the last index. m_nlength = (n_newsize > m_ncapacity) ? m_nlength : n_newsize; m_ncapacity = n_newsize; /** * @brief Move, not copy, previous buffer into current since it's a * lil bit faster. * * @details p_dummy[i] = std::move(m_pbuffer[i]) isn't enough! Since it, * p_dummy[i], is uninitialized, calling a move-assignment will * read uninitialized memory which Valgrind warns us about. * * We *could* use the new and cool C++17 features: * `std::uninitialized_move(begin(), end(), p_dummy)` * `std::uninitialized_move_n(begin(), length(), p_dummy)` * * @note It turns out that in the definition for Malloc::construct(), * the 3rd parameter is actually varargs which serve as the * instance's constructor arguments. * * Here, we (probably) want to force the move-constructor. */ for (size_t i = 0; i < m_nlength; i++) { Malloc::construct(m_malloc, &p_dummy[i], std::move(m_pbuffer[i])); } // Since previous contents were moved no need to explicitly destroy // Also: Malloc::deallocate shouldn't accept `nullptr`! if (m_pbuffer != nullptr) { Malloc::deallocate(m_malloc, m_pbuffer, n_oldsize); } m_pbuffer = p_dummy; m_iterator.set_range(m_pbuffer, m_nlength); return derived_cast(); } /** * @brief Copies the last written element and gives it back to you. * * It decrements the `m_nlength` counter and `m_end` iterator. * * The index at which the element was is destroyed just to be safe. * * @attention This can be shadowed, e.g. strings set index's value to 0. */ ElemT pop_back() { ElemT top = m_pbuffer[m_nlength - 1]; // copy by value // Destructor only takes care of up to m_nlength elements, so need this! Malloc::destroy(m_malloc, m_pbuffer + m_nlength - 1); m_iterator.m_end--; m_nlength--; return top; } /** * @brief Deletes/frees buffer, resets the index counter and iterators. * * @note `m_ncapacity` is unaffected. Actually, after freeing the current * buffer we reallocate fresh, unitialized memory of the same size! */ DerivedT &clear() { // Destroy all created objects and free our pointer's allocated memory. this->~base_dyarray(); m_pbuffer = Malloc::allocate(m_malloc, m_ncapacity); m_nlength = 0; m_iterator.set_range(m_pbuffer); return derived_cast(); } };
class User{ constructor(email, name){ this.email = email; this.name = name; this.score = 0; } login(){ console.log(this.email, 'just logged in'); return this; } logout(){ console.log(this.email, 'just logged out'); return this; } updateScore(){ this.score++; console.log(this.email, 'score is now', this.score) return this; } } let userOne = new User('[email protected]', 'Ryu'); let userTwo = new User('[email protected]', 'Yoshi'); userOne.login().updateScore().updateScore().logout(); // the 'new' keyword // - creates a new empty object {} // - sets the value of 'this' to be the new empty object // - calls the constructor method
import './index.css' import 'epfl-elements/dist/css/elements.min.css' type Callback = () => void; type MetaboxProps = { eventTitle?: string; metaboxDetails?: Array<any>; onClickFn?: Callback; labelButton?: string; organizer?: Array<any>; } export function Metabox ({ eventTitle, metaboxDetails, onClickFn, labelButton, organizer, }: MetaboxProps) { const getOrganizer = () => //Get data of organizer (organizer || []).map(item => <div className="mt-3"> <p className="mb-2">{item.label}</p> <div className="avatar-teaser"> <a className="avatar-teaser-img" href={item.link}> <img src={item.srcImage} alt={item.altImage}/> </a> <div className="avatar-teaser-body"> <p>{item.personName}</p> </div> </div> </div> ) // Add a button and onClick option const getButtonAction = () => <div className="mt-auto align-self-end"> <button className="btn btn-primary" onClick={() => onClickFn && onClickFn()}>{labelButton}</button> </div> const getMetaboxDetails = () => //Get Content of Metabox Table <> <div className="border col-md-5 bg-gray-100"> <div className="d-flex flex-column py-3 bg-gray-20"> <h4>{eventTitle}</h4> <table className="table h-100 metabox"> <tbody> { /* Get data to fill the table. If there is a link map, then it will put the data in <a> tag inside <td> tag If not, it puts the data in the <td> tag */ (metaboxDetails || []).map ((item, i) => item.key && <tr> <td>{item.key}</td> {item.link ? <td key={i}><a href={item.link}>{item.value}</a></td> : <td key={i}>{item.value}</td>} </tr> ) } </tbody> </table> {getOrganizer()} {getButtonAction()} </div> </div> </> //Return all Metabox data return ( <> {metaboxDetails && getMetaboxDetails()} {!metaboxDetails && console.error("The component must have the metaboxDetails array to work")} </> ) }
import numpy as np import matplotlib.pyplot as plt #A1: Develop the above perceptron in your own code (don’t use the perceptron model available from package). Use the initial weights as provided below. W0 = 10, W1 = 0.2, w2 = -0.75, learning rate (α) = 0.05. Use Step activation function to learn the weights of the network to implement above provided AND gate logic. The activation function is demonstrated below.Identify the number of epochs needed for the weights to converge in the learning process. Make a plot of the epochs against the error values calculated (after each epoch, calculate the sum-square error against all training samples).(Note: Learning is said to be converged if the error is less than or equal to 0.002. Stop the learning after 1000 iterations if the convergence error condition is not met.) # AND gate input-output pairs X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) Y = np.array([0, 0, 0, 1]) # Initial weights W = np.array([10, 0.2, -0.75]) # Learning rate alpha = 0.05 # Step activation function def step_function(x): return 1 if x >= 0 else 0 # Perceptron function def perceptron(x, w): return step_function(np.dot(x, w)) # Calculate sum-square error def calculate_error(y_true, y_pred): return np.sum((y_true - y_pred) ** 2) # Training the perceptron error_values = [] epochs = 0 max_epochs = 1000 convergence_error = 0.002 while True: error = 0 for i in range(len(X)): y_pred = perceptron(np.insert(X[i], 0, 1), W) delta = Y[i] - y_pred W += alpha * delta * np.insert(X[i], 0, 1) error += calculate_error(Y[i], y_pred) error_values.append(error) epochs += 1 if error <= convergence_error or epochs >= max_epochs: break # Plotting plt.plot(range(1, epochs + 1), error_values) plt.xlabel('Epochs') plt.ylabel('Error') plt.title('Epochs vs Error') plt.grid(True) plt.show() print("Number of epochs needed for convergence:", epochs) print("Learned weights:", W)
import { Request, Response } from "express"; import { File } from "./file.entity"; import fileService from "./file.service"; import { verifyTokenMiddleware } from "../middlewares/verifyTokenMiddleware"; import userService from "../User/user.service"; import { FileProps, FileType } from "./file.types"; import fileManager from "./file.manager"; import fileUpload from "express-fileupload"; import customJSONStringifier from "./utils/customJSONStringifier"; import userController from "../User/user.controller"; import shareService from "../Share/share.service"; import { UserRole } from "../User/user.types"; const uuidv4 = require("uuid").v4; class FileController { constructor() {} public async createNewDir(req: Request, res: Response) { try { const token = req.headers.authorization?.split(" ")[1]; const { name, type, parentId }: FileProps = req.body; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const candidate = await userService.getUserById(userData.id); if (!candidate) return res.status(403).json({ message: "Error: User not found" }); const parent = await fileService.getFileById(parentId); let file = new File(); file.name = `${name}${type !== FileType.DIR ? `.${type}` : ``}`; file.user = candidate; file.type = type; file.childs = []; file.shared = []; file.root = false; file.path = file.name; // `${file.name}${ // file.type !== FileType.DIR ? `.${file.type}` : `` // }`; if (parent) { file.path = `${parent.path}\\${file.path}`; file.parent = parent; parent.childs.push(file); } await fileManager.createDirOrFile(file); const newFile = await fileService.createNewFile(file); if (!newFile) return res.status(400).json({ message: "Error: File wasn't created" }); return res.status(200).send(customJSONStringifier(newFile)); } catch (e) { console.log(e); res.status(400).json({ message: `Error: ${e}` }); } } public async deleteFile(req: Request, res: Response) { const token = req.headers.authorization?.split(" ")[1]; const { id }: { id: string } = req.body; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const candidate = await userService.getUserById(userData.id); if (!candidate) return res.status(403).json({ message: "Error: User not found" }); const fileToDelete = await fileService.getFileById(id); if (!fileToDelete) return res.status(400).json({ message: "Error: File not found" }); if (fileToDelete.user.id !== candidate.id) return res .status(400) .json({ message: "Error: You have no permissions" }); await fileManager.recursiveDelete( process.env.FILES_PATH + `\\${fileToDelete.user.id}\\${fileToDelete.path}` ); const deleted = await fileService.recursiveDelete(id); if (deleted) { candidate.usedSpace = BigInt(candidate.usedSpace) - BigInt(deleted.size); await userService.saveUser(candidate); res.status(200).send(customJSONStringifier(deleted)); } } public async fetchFiles(req: Request, res: Response) { try { const token = req.headers.authorization?.split(" ")[1]; const { parentId } = req.query; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const user = await userService.getUserById(userData.id); if (!user) return res.status(403).json({ message: "Error: User not found" }); const parent = await fileService.getFileById(`${parentId}`); if (!parent) return res.status(404).json({ message: "Error: Directory not found" }); const files = await fileService.fetchFiles({ user, parent, }); if (!files) return res.status(404).json({ message: "Error: Files not found" }); return res.status(200).send(customJSONStringifier(files)); } catch (e) { console.log(e); res.status(400).json({ message: `Error: ${e}` }); } } public async uploadFile(req: Request, res: Response) { try { const uploadedFile = req.files?.file as fileUpload.UploadedFile; if (!uploadedFile) return res.status(400).json({ message: "Error: File not found" }); const token = req.headers.authorization?.split(" ")[1]; const { parentId }: { parentId: string } = req.body; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const candidate = await userService.getUserById(userData.id); if (!candidate) return res.status(403).json({ message: "Error: User not found" }); const parent = await fileService.getFileById(parentId); if (candidate.diskSpace - candidate.usedSpace < uploadedFile.size) return res .status(400) .json({ message: "Error: Need more storage space" }); candidate.diskSpace = BigInt(candidate.diskSpace); candidate.usedSpace = BigInt(candidate.usedSpace) + BigInt(uploadedFile.size); let filePath = ""; if (parent) { filePath = process.env.FILES_PATH + `\\${candidate.id}\\${parent.path}\\${uploadedFile.name}`; } else { filePath = process.env.FILES_PATH + `\\${candidate.id}\\${uploadedFile.name}`; } if (fileManager.checkIsExists(filePath)) return res.status(400).json({ message: "Error: File already exists" }); const uplName = uploadedFile.name.split(".").reverse().pop(); const type = uploadedFile.name.split(".").pop() as FileType; if (type && !Object.values(FileType).includes(type as FileType)) { return res.status(400).json({ message: "Error: Unknown type of file" }); } if (!uplName) { return res.status(400).json({ message: "Error: Wrong file name" }); } uploadedFile.mv(filePath); let file = new File(); file.name = uploadedFile.name; file.user = candidate; file.type = type; file.size = BigInt(uploadedFile.size); file.access_link = ""; file.childs = []; file.shared = []; file.root = false; file.path = uploadedFile.name; if (parent) { file.path = `${parent.path}\\${file.path}`; file.parent = parent; parent.childs.push(file); } await userService.userRepository.save(candidate); const newFile = await fileService.createNewFile(file); if (!newFile) return res.status(400).json({ message: "Error: File wasn't created" }); return res.status(200).send(customJSONStringifier(newFile)); } catch (e) { console.log(e); res.status(400).json({ message: `Error: ${e}` }); } } public async downloadFile(req: Request, res: Response) { try { const downloadId = req.query.id ?? ""; if (!downloadId) return res.status(400).json({ message: "Error: Incorrect files id" }); const downloadingFile = await fileService.getFileById(`${downloadId}`); if (!downloadingFile) { return res.status(400).json({ message: "Error: File not found" }); } const token = req.headers.authorization?.split(" ")[1]; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const candidate = await userService.getUserById(userData.id); if (!candidate) return res.status(403).json({ message: "Error: User not found" }); const filePath = process.env.FILES_PATH + "\\" + candidate.id + downloadingFile.path; if (fileManager.checkIsExists(filePath)) { console.log(filePath); const name = `${downloadingFile.name}.${downloadingFile.type}`; console.log(name); return res.status(200).download(filePath, name); } return res.status(400).json({ message: "Error: File not found" }); } catch (e) { console.log(e); res.status(500).json({ message: e }); } } public async downloadSharedFile(req: Request, res: Response) { try { const downloadId = req.query.id ?? ""; if (!downloadId) return res.status(400).json({ message: "Error: Incorrect files id" }); const downloadingFile = await fileService.getFileById(`${downloadId}`); if (!downloadingFile) { return res.status(400).json({ message: "Error: File not found" }); } const token = req.headers.authorization?.split(" ")[1]; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const candidate = await userService.getUserById(userData.id); if (!candidate) return res.status(403).json({ message: "Error: User not found" }); console.log("Downloading: ", downloadingFile); const isKnownShare = await shareService.checkIsNewShare( downloadingFile.user.id, candidate.id, downloadingFile.id ); console.log("isKnownShare: ", isKnownShare); if (!isKnownShare) return res .status(400) .json({ message: "Error: You don't have permissions" }); const filePath = process.env.FILES_PATH + "\\" + downloadingFile.user.id + downloadingFile.path; if (fileManager.checkIsExists(filePath)) { console.log(filePath); const name = `${downloadingFile.name}.${downloadingFile.type}`; console.log(name); return res.status(200).download(filePath, name); } return res.status(400).json({ message: "Error: File not found" }); } catch (e) { console.log(e); res.status(500).json({ message: e }); } } public async uploadAvatar(req: Request, res: Response) { try { const uploadedAvatar = req.files?.file as fileUpload.UploadedFile; if (!uploadedAvatar) return res.status(400).json({ message: "Error: Bad Request" }); const token = req.headers.authorization?.split(" ")[1]; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const candidate = await userService.getUserById(userData.id); if (!candidate) return res.status(404).json({ message: "Error: User not found" }); if (candidate.avatar.length) await fileManager.deleteAvatar(candidate.avatar); const avatarName = uuidv4() + ".jpg"; uploadedAvatar.mv(process.env.STATIC_PATH + `\\${avatarName}`); candidate.avatar = avatarName; await userService.userRepository.save(candidate); return res.status(200).send({ avatar: avatarName }); } catch (e) { console.log(e); res.status(400).json({ message: `Error: ${e}` }); } } public async deleteAvatar(req: Request, res: Response) { try { const token = req.headers.authorization?.split(" ")[1]; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const candidate = await userService.getUserById(userData.id); if (!candidate) return res.status(404).json({ message: "Error: User not found" }); await fileManager.deleteAvatar(candidate.avatar); candidate.avatar = ""; await userService.userRepository.save(candidate); return res .status(200) .send({ message: "Avatar was deleted successfully" }); } catch (e) { console.log(e); res.status(400).json({ message: `Error: ${e}` }); } } public async uploadContactAvatar(req: Request, res: Response) { try { const uploadedAvatar = req.files?.file as fileUpload.UploadedFile; const contactId: string = req.body.id; if (!uploadedAvatar || !contactId) return res.status(400).json({ message: "Error: Bad Request" }); const token = req.headers.authorization?.split(" ")[1]; const userData = verifyTokenMiddleware(token ?? ""); if (!userData) return res.status(403).json({ message: "Error: Token was expired" }); const adminCandidate = await userService.getUserById(userData.id); if (!adminCandidate) return res.status(404).json({ message: "Error: User not found" }); if (adminCandidate.role !== UserRole.ADMIN) return res .status(403) .json({ message: "Error: You do not have permissions" }); const candidate = await userService.getUserById(contactId); if (!candidate) return res.status(404).json({ message: "Error: Contact not found" }); if (candidate.avatar.length) await fileManager.deleteAvatar(candidate.avatar); const avatarName = uuidv4() + ".jpg"; uploadedAvatar.mv(process.env.STATIC_PATH + `\\${avatarName}`); candidate.avatar = avatarName; await userService.userRepository.save(candidate); return res.status(200).send({ avatar: avatarName }); } catch (e) { console.log(e); res.status(400).json({ message: `Error: ${e}` }); } } } export default new FileController();
public class EditDist { //O(n+m) public static int editDistance(String str1, String str2) { int n = str1.length(); int m = str2.length(); int dp[][] = new int[n + 1][m + 1]; // initialize for (int i = 0; i < n + 1; i++) { for (int j = 0; j < m + 1; j++) { if (i == 0) { dp[i][j] = j; } if (j == 0) { dp[i][j] = i; } } } //bottom up for(int i=1; i<n+1; i++){ for(int j=1; j<m+1; j++){ if(str1.charAt(i-1)== str2.charAt(j-1)){ //same dp[i][j]= dp[i-1][j-1]; }else{ //diff int add= dp[i][j-1]+1; int del= dp[i-1][j]+1; int rep= dp[i-1][j-1]+1; dp[i][j]= Math.min(add, Math.min(del,rep)); } } } return dp[n][m]; } public static void main(String[] args) { String word1 = "intention"; String word2 = "execution"; //5 System.out.println(editDistance(word1, word2)); } }
import { Body, Controller, Post, Get, UploadedFiles, UseGuards, UseInterceptors, Patch, Param, Delete, } from '@nestjs/common'; import { PostsService } from '../services/posts.service'; import { AuthGuard } from '@nestjs/passport'; import { FilesInterceptor } from '@nestjs/platform-express'; import { CurrentUser } from 'src/auth/decorators/loggedIn-user.decorator'; import { CreatePostDto, UpdatePostDto } from '../dto/posts.dto'; import { PostsDocument } from '../schemas/posts.schema'; import { UserDocument } from 'src/user/schemas/user.schema'; import { ReactionDto, UpdateReactionDTO } from '../dto/reaction.dto'; import { multerOptions } from 'src/common/utils/cloudinary/multer'; @Controller('posts') export class PostsController { constructor(private postService: PostsService) {} @UseGuards(AuthGuard('jwt')) @UseInterceptors(FilesInterceptor('files', 4, multerOptions)) @Post() async Create( @Body() payload: CreatePostDto, @CurrentUser() user: UserDocument, @UploadedFiles() files: Array<Express.Multer.File>, ) { return await this.postService.create(payload, user._id, files); } @Get('findAll') async getAll(): Promise<PostsDocument[]> { return await this.postService.getAll(); } @Get('videos') async getAllVideos(): Promise<PostsDocument[]> { return await this.postService.getAllVideos(); } @Get(':id') async getById(@Param('id') id: string): Promise<PostsDocument> { return await this.postService.getById(id); } @UseGuards(AuthGuard('jwt')) @UseInterceptors(FilesInterceptor('files', 4, multerOptions)) @Patch('update/:id') async update( @Param('id') id: string, @Body() payload: UpdatePostDto, @CurrentUser() user: UserDocument, @UploadedFiles() files: Array<Express.Multer.File>, ) { return await this.postService.updatePost(id, payload, user, files); } @UseGuards(AuthGuard('jwt')) @Patch('update-reactions') async updateReaction( @Body() payload: UpdateReactionDTO, @CurrentUser() user: UserDocument, ) { return await this.postService.updatePostReaction(payload, user); } @UseGuards(AuthGuard('jwt')) @Delete(':id') async DeleteById(@Param('id') id: string, @CurrentUser() user: any) { return await this.postService.DeleteById(id, user); } @UseGuards(AuthGuard('jwt')) @Get('my-posts') async MyPost(@CurrentUser() user: any) { return await this.postService.MyPosts(user); } //like post handle @UseGuards(AuthGuard('jwt')) @Patch('reaction') async React(@Body() payload: ReactionDto, @CurrentUser() user: UserDocument) { return await this.postService.reactToPost(payload, user); } }
// // CityDetailPresenter.swift // MyWeather // // Created by Rustam Nigmatzyanov on 21.08.2021. // import Foundation // Presenter - отвечает за преобразование сырых данных и передает данные для отображения // заголовки для таблицы private enum Title: String, CaseIterable { case name = "Город" case country = "Страна" case temp = "Температура (Цельсий)" case description = "Описание" case pressure = "Атмосферное давление (гПа)" case humidity = "Влажность (%)" case windSpeed = "Скорость ветра (м/с)" case windDeg = "Направление ветра (градусы)" case clouds = "Облачность (%)" case sunrise = "Время восхода" case sunset = "Время заката" } // протокол для взаимодейстия с Interactor protocol CityWeatherPresenterProtocol { // функция для преобразования сырых данных в данные для отображения func transformData(with result: CityWeather.Data) } class CityWeatherPresenter: CityWeatherPresenterProtocol { // переменная для взаимодействия с view controller // weak - чтобы не было цикла памяти weak var controller: CityWeatherViewControllerProtocol? // переменная для форматирования UTC-данных с сервера // (!!!)вынесем в отдельное свойство, чтобы создать экземпляр dateFormatter один раз, т.к. это очень затратно private lazy var dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" return dateFormatter }() // функция для передачи данных во view controller func transformData(with result: CityWeather.Data) { switch result { // передаем данные для отображения во vc case let .presentInfo(weather): transformWeather(weather) // передаем заголовок во vc case let .presentTitle(city): controller?.showState(with: .showTitle(city.name)) } } // функция для преобразования сырых данных в данные для отображения и передачи их во view controller private func transformWeather(_ weahter: Weather) { guard let name = weahter.name, let country = weahter.sys?.country, let temp = weahter.main?.temp, let description = weahter.weather, let pressure = weahter.main?.pressure, let humidity = weahter.main?.humidity, let windSpeed = weahter.wind?.speed, let windDeg = weahter.wind?.deg, let clouds = weahter.clouds?.all, let sunrise = weahter.sys?.sunrise, let sunset = weahter.sys?.sunset, let weatherDescription = description.first?.weatherDescription else { return } var model = [String]() model.append(name) model.append(country) model.append(String(Int(round(temp)))) model.append(weatherDescription) model.append(String(pressure)) model.append(String(humidity)) model.append(String(windSpeed)) model.append(String(windDeg)) model.append(String(clouds)) model.append(dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(sunrise)))) model.append(dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(sunset)))) let titles = Title.allCases // формируем viewModels let viewModels: [WeatherViewModel] = titles.enumerated().compactMap { guard let value = model[safe: $0.offset] else { return nil } // создаем элемент массива viewModels return .init(title: $0.element.rawValue, value: value) } // обновляем UI DispatchQueue.main.async { [weak self] in // передаем viewModel во view controller self?.controller?.showState(with: .showInfo(viewModels)) } } }
import React from "react"; import { Container, Image, Button } from "react-bootstrap"; import CityForm from './CityForm.jsx'; import Listy from './Listy.jsx'; import AlertComp from './AlertComp.jsx'; import Weather from './Weather.jsx'; import MovieCards from "./MovieCards.jsx"; import FoodList from "./FoodList.jsx"; import axios from "axios"; import 'bootstrap/dist/css/bootstrap.min.css'; class Explorer extends React.Component { constructor(props) { super(props); this.state = { displayCity: false, displayWeather: false, displayMovies: false, displayFood: false, searchQuery: '', city: {}, lat: '', lon: '', mapurl: {}, error: null, Forecast: {}, Movies: {}, Food: {} } } handleSearch = (e) => { e.preventDefault(); const { searchQuery } = this.state; const serverURL = import.meta.env.VITE_SERVER || 'http://localhost:3001'; // Make the API request to the server (backend) to avoid exposing the key axios.get(`${serverURL}/api/location?searchQuery=${searchQuery}`) .then(async (response) => { const cityData = response.data[0]; //console.log('CityData:', cityData); console.log(response.data.timestamp); this.setState({ city: cityData, lat: cityData.lat, lon: cityData.lon, code: cityData.address.country_code, displayCity: true, error: null }); const mapurlResponse = await axios.get(`${serverURL}/api/mapurl?lat=${cityData.lat}&lon=${cityData.lon}`); const mapurl = mapurlResponse.data; this.setState({ mapurl }); }) .catch(error => { console.error('Error:', error); this.setState({ error: `An error occurred: ${error.message}. Code: ${error.code}.` }); }); } showList = async () => { try { const { searchQuery, city: { lon, lat } } = this.state; const serverURL = import.meta.env.VITE_SERVER || 'http://localhost:3001'; const res = await axios.get(`${serverURL}/weather?searchQuery=${searchQuery}&lon=${lon}&lat=${lat}`); //console.log(res); this.setState({ Forecast: res.data, displayWeather: true, error: null }); } catch (error) { console.error('Error:', error); this.setState({ error: `An error occurred: ${error.message}. Code: ${error.code}.` }); } } showListWB = () => { const { city: { lon, lat } } = this.state; const serverURL = import.meta.env.VITE_SERVER || 'http://localhost:3001'; axios.get(`${serverURL}/weatherbits?lon=${lon}&lat=${lat}`) .then((res) => { //console.log(res); this.setState({ Forecast: res.data, displayWeather: true, displayMovies: false, displayFood: false, error: null }); }) .catch((error) => { console.error('Error:', error); this.setState({ error: `An error occurred: ${error.message}. Code: ${error.code}.` }); }); } showListMovies = () => { const { searchQuery } = this.state; const serverURL = import.meta.env.VITE_SERVER || 'http://localhost:3001'; axios.get(`${serverURL}/movies?q=${searchQuery}`) .then((res) => { //console.log(res); this.setState({ Movies: res.data, displayWeather: false, displayFood: false, displayMovies: true, error: null }); }) .catch((error) => { console.error('Error:', error); this.setState({ error: `An error occurred: ${error.message}. Code: ${error.code}.` }); }); } showListFood = () => { const { lat, lon } = this.state; const serverURL = import.meta.env.VITE_SERVER || 'http://localhost:3001'; axios.get(`${serverURL}/food?lon=${lon}&lat=${lat}`) .then((res) => { //console.log(res); this.setState({ Food: res.data, displayWeather: false, displayMovies: false, displayFood: true, error: null }); }) .catch((error) => { console.error('Error:', error); this.setState({ error: `An error occurred: ${error.message}. Code: ${error.code}.` }); }); } handleInputChange = async (e) => { this.setState({ searchQuery: e.target.value }); } render() { return ( <> <Container id="jade"> <CityForm handleSearch={this.handleSearch} searchQuery={this.state.searchQuery} handleInputChange={this.handleInputChange} /> {this.state.displayCity && Object.keys(this.state.city).length > 0 && ( <> <Image src={this.state.mapurl} alt={this.state.city.display_name} rounded id="map" /> <Listy city={this.state.city} /> </> )} {this.state.error && ( <AlertComp errormessage={this.state.error} /> )} </Container> <Container id="extras"> <div className="btn-group" id="extrasearch" role="group"> <Button variant="info" size="md" id="weatherbutton" onClick={this.showListWB}>Show me my Forecast.</Button> <Button variant='info' size="md" id="moviebutton" onClick={this.showListMovies} > Show me movies! </Button> <Button variant='info' size="md" id="foodbutton" onClick={this.showListFood} > Show me restaurants! </Button> </div> {this.state.displayWeather && ( <Weather Forecast={this.state.Forecast} /> )} {this.state.displayMovies && ( <MovieCards Movies={this.state.Movies} /> )} {this.state.displayFood && ( <FoodList Food={this.state.Food} /> )} {this.state.error && ( <AlertComp errormessage={this.state.error} /> )} </Container> </> ); } } export default Explorer;
#ifndef TECTONIC_GAMECAMERA_H #define TECTONIC_GAMECAMERA_H #include "camera/Camera.h" #include "meta/Signal.h" #include "meta/Slot.h" /** * Represents a controllable game camera. Usually only one per scene. * This camera can be controlled with keyboard and mouse by calling handleKeyEvent and handleMouseEvent. * * @brief Controllable camera. */ class GameCamera : public Camera { public: GameCamera() = default; /** * @brief Handles an incoming key event and moves the camera accordingly. * @param key Key to handle. */ void handleKeyEvent(u_short key); /** * Calculates a new angle for the camera to rotate to. * The class stores the previous mouse local_position and by calculating a difference with the current local_position * it gets a new angle of the camera. * * @brief Handles a mouse movement and orients the camera accordingly. * @param x Current mouse X local_position. * @param y Current mouse Y local_position. */ void handleMouseEvent(double x, double y); /** * Enables or disables cursor for the camera. * It needs to set m_firstMouse to true so that camera wont snap between previous positions. */ Slot<bool> slt_cursorEnabled{[this](bool isEnabled){ m_cursorEnabled = isEnabled; m_firstMouse = true; }}; private: float m_speed = 0.05f; float m_sensitivity = 0.001f; bool m_firstMouse = true; glm::vec2 m_lastMousePos = glm::vec2(0.0f, 0.0f); bool m_cursorEnabled = false; }; #endif //TECTONIC_GAMECAMERA_H
document.addEventListener("DOMContentLoaded", function () { const itemsPerPage = 6; let currentPage = 1; async function displayRepositories() { try { const repositories = [ { "name": "QuantumFluxAnalyzer", "description": "A cutting-edge quantum computing library for flux analysis and simulation.", "technologies": ["JavaScript", "HTML", "CSS"] }, { "name": "NebulaCraft", "description": "Build your own galaxy with NebulaCraft - a framework for celestial body generation in games.", "technologies": ["Python", "OpenGL", "Unity"] }, { "name": "CipherVault", "description": "Secure your data with state-of-the-art encryption using CipherVault - a data protection toolkit.", "technologies": ["Java", "Cryptography", "Spring"] }, { "name": "BioGenomeHarmony", "description": "Explore the harmony of biological data with BioGenomeHarmony, a genomics analysis toolkit.", "technologies": ["R", "Bioinformatics", "Biopython"] }, { "name": "SynthWaveComposer", "description": "Compose retro-futuristic music with SynthWaveComposer, your go-to synthesizer library.", "technologies": ["C++", "Digital Signal Processing", "Audio Synthesis"] }, { "name": "DronePilotPro", "description": "Take control with DronePilotPro - an advanced API for drone automation and navigation.", "technologies": ["ROS", "Python", "Computer Vision"] }, { "name": "VirtualBotanist", "description": "Grow your virtual garden with VirtualBotanist, a plant simulation and growth library.", "technologies": ["JavaScript", "Three.js", "WebGL"] }, { "name": "CryptoRover", "description": "Navigate the blockchain universe with CryptoRover - your guide to cryptocurrency exploration.", "technologies": ["Solidity", "Blockchain", "Smart Contracts"] }, { "name": "SpaceTimeNavigator", "description": "Chart your course through the fabric of spacetime with SpaceTimeNavigator, a physics simulation toolkit.", "technologies": ["Python", "Physics Simulation", "NumPy"] }, { "name": "MindForgeAI", "description": "Forge intelligent systems with MindForgeAI - an artificial intelligence development framework.", "technologies": ["Python", "Machine Learning", "TensorFlow"] }, { "name": "AquaSimulator", "description": "Dive into underwater simulations with AquaSimulator - a realistic aquatic environment API.", "technologies": ["Java", "Swing", "Physics Simulation"] }, { "name": "AstroMeshConnect", "description": "Connect celestial bodies in your applications with AstroMeshConnect - a space network API.", "technologies": ["C#", "Unity", "Networking"] }, { "name": "CryptoCanvas", "description": "Paint the blockchain with CryptoCanvas - a decentralized digital art creation toolkit.", "technologies": ["JavaScript", "IPFS", "Blockchain"] }, { "name": "BioSculptor", "description": "Sculpt your genetic code with BioSculptor - a genetic engineering and manipulation library.", "technologies": ["Python", "Biotechnology", "CRISPR"] }, { "name": "QuantumMindReader", "description": "Peek into the quantum realm of thoughts with QuantumMindReader - a mind-reading API.", "technologies": ["C++", "EEG", "Quantum Computing"] }, { "name": "CodeCraftersGuild", "description": "Join the guild of code crafters with CodeCraftersGuild - a collaborative coding environment.", "technologies": ["JavaScript", "Node.js", "Collaboration Tools"] }, { "name": "SolarWindMapper", "description": "Map solar wind patterns with SolarWindMapper - a solar physics data analysis toolkit.", "technologies": ["Python", "Data Visualization", "Space Physics"] }, { "name": "RoboChefMaster", "description": "Master the art of robotic cooking with RoboChefMaster - a culinary automation API.", "technologies": ["Python", "Robotics", "Cooking Algorithms"] }, { "name": "CryptoSentinel", "description": "Safeguard your digital assets with CryptoSentinel - a blockchain security toolkit.", "technologies": ["Solidity", "Security Auditing", "Smart Contracts"] }, { "name": "WarpDriveEngine", "description": "Power your applications to warp speed with WarpDriveEngine - a high-performance computing library.", "technologies": ["C++", "Parallel Computing", "CUDA"] }, { "name": "BioSynthComposer", "description": "Compose music inspired by biology with BioSynthComposer - a bio-inspired music generation API.", "technologies": ["Python", "Music Theory", "Genetic Algorithms"] }, { "name": "DroneGuardian", "description": "Guard the skies with DroneGuardian - a drone security and surveillance toolkit.", "technologies": ["Java", "Drone SDK", "Computer Vision"] }, { "name": "QuantumFinanceWizard", "description": "Navigate the quantum landscape of finance with QuantumFinanceWizard - a financial analytics API.", "technologies": ["R", "Quantitative Finance", "Quantum Computing"] }, { "name": "RetroPixelPainter", "description": "Paint retro pixel art with RetroPixelPainter - a nostalgic digital art creation toolkit.", "technologies": ["JavaScript", "Canvas", "Pixel Art"] }, { "name": "SpaceRiftExplorer", "description": "Explore the cosmic rifts with SpaceRiftExplorer - a space exploration and mapping API.", "technologies": ["C#", "Unity", "Astronomy"] }, { "name": "CryptoTraderElite", "description": "Trade cryptocurrencies like a pro with CryptoTraderElite - an advanced trading algorithm toolkit.", "technologies": ["Python", "Algorithmic Trading", "Cryptocurrency"] }, { "name": "BioNanoAssembler", "description": "Assemble nanoscale structures with BioNanoAssembler - a bio-inspired nanotechnology toolkit.", "technologies": ["Python", "Nanotechnology", "Molecular Assembly"] }, { "name": "SkywardSimulator", "description": "Simulate the skyward journey with SkywardSimulator - an atmospheric simulation library.", "technologies": ["Java", "Simulation", "Atmospheric Science"] }, { "name": "RoboPetMaster", "description": "Master the art of training robotic pets with RoboPetMaster - an AI-driven pet training API.", "technologies": ["Python", "Robotics", "Pet Training Algorithms"] }, { "name": "QuantumMusicMixer", "description": "Mix music in the quantum realm with QuantumMusicMixer - a quantum-inspired music composition toolkit.", "technologies": ["C++", "Quantum Computing", "Music Production"] }, { "name": "AeroSpacePainter", "description": "Paint the aerospace landscape with AeroSpacePainter - a digital art creation toolkit for aviation enthusiasts.", "technologies": ["JavaScript", "Three.js", "Aviation Art"] }, { "name": "CryptoOracle", "description": "Seek guidance from the crypto oracle with CryptoOracle - a blockchain prediction and analysis API.", "technologies": ["Solidity", "Oracle Services", "Smart Contracts"] }, { "name": "NanoRoboticsCraft", "description": "Craft nanorobots for various applications with NanoRoboticsCraft - a nanotechnology robotics toolkit.", "technologies": ["Python", "Nanorobotics", "Mechatronics"] }, { "name": "QuantumChessMaster", "description": "Master the quantum chessboard with QuantumChessMaster - a quantum-inspired chess engine.", "technologies": ["C++", "Chess Algorithms", "Quantum Computing"] }, { "name": "VRUniverseExplorer", "description": "Explore virtual universes with VRUniverseExplorer - a virtual reality universe simulation API.", "technologies": ["Unity", "VR", "Universe Simulation"] }, { "name": "NeuralStyleCreator", "description": "Create unique art styles with NeuralStyleCreator - an AI-powered artistic style transfer toolkit.", "technologies": ["Python", "Deep Learning", "Artistic Style Transfer"] }, { "name": "QuantumMarketAnalyzer", "description": "Analyze quantum fluctuations in financial markets with QuantumMarketAnalyzer - a financial quantum analytics API.", "technologies": ["R", "Quantitative Finance", "Quantum Computing"] }, { "name": "BioMechanicalSim", "description": "Simulate biomechanics with BioMechanicalSim - a toolkit for realistic human and animal movement simulation.", "technologies": ["Python", "Biomechanics", "Physics Simulation"] }, { "name": "CryptoSpellcaster", "description": "Cast spells in the blockchain with CryptoSpellcaster - a decentralized magic-themed application toolkit.", "technologies": ["Solidity", "Smart Contracts", "Decentralized Magic"] }, { "name": "QuantumRealityEngine", "description": "Create alternate realities with QuantumRealityEngine - a quantum-inspired virtual reality development framework.", "technologies": ["Unity", "VR", "Quantum Computing"] }, { "name": "DeepSpaceCartographer", "description": "Chart the depths of deep space with DeepSpaceCartographer - a space mapping and exploration API.", "technologies": ["C#", "Unity", "Space Exploration"] }, { "name": "QuantumGameMaster", "description": "Master the quantum realm of gaming with QuantumGameMaster - a game development toolkit.", "technologies": ["C++", "Game Development", "Quantum Computing"] }, ]; const startIndex = (currentPage - 1) * itemsPerPage; const endIndex = startIndex + itemsPerPage; const displayedRepositories = repositories.slice(startIndex, endIndex); if (displayedRepositories && displayedRepositories.length) { document.querySelector("#container").innerHTML = ''; displayedRepositories.forEach((repo) => { let repoBox = document.createElement("div"); repoBox.setAttribute("class", "ApiBox"); let repoName = document.createElement("h2"); repoName.innerText = repo.name; let repoDescription = document.createElement("p"); repoDescription.innerText = repo.description; let techList = document.createElement("ul"); techList.setAttribute("class", "TechList"); repo.technologies.forEach((tech) => { let techItem = document.createElement("li"); techItem.setAttribute("class", "liBtn"); techItem.innerText = tech; techList.appendChild(techItem); }); repoBox.append(repoName, repoDescription, techList); document.querySelector("#container").append(repoBox); }); addPaginationControls(repositories.length); } else { console.error('Displayed repositories array is undefined or empty.'); } } catch (error) { console.error(error); } } function addPaginationControls(totalItems) { const totalPages = Math.ceil(totalItems / itemsPerPage); document.getElementById("currentPage").innerText = currentPage; document.getElementById("prevBtn").disabled = currentPage === 1; document.getElementById("nextBtn").disabled = currentPage === totalPages; } document.getElementById("prevBtn").addEventListener("click", () => { changePage(-1); }); document.getElementById("nextBtn").addEventListener("click", () => { changePage(1); }); function changePage(delta) { currentPage += delta; displayRepositories(currentPage); } displayRepositories(); });
import PropTypes from "prop-types"; import React, { useReducer } from "react"; import ArrowLeft from "@/assets/svg/ArrowLeft"; import Bookmark from "@/assets/svg/Bookmark"; import styles from "./index.module.scss"; interface Props { size: "XS" | "m" | "s"; icon: JSX.Element; stateProp: "hover-active" | "disable" | "default"; className?: any; } const Icon = ({ size, stateProp, className }: Props): JSX.Element => { const [state, dispatch] = useReducer(reducer, { size: size || "XS", state: stateProp || "default", }); return ( <div className={`${styles.icon} ${state.size} ${state.state} ${className}`} onMouseLeave={() => { dispatch("mouse_leave"); }} onMouseEnter={() => { dispatch("mouse_enter"); }} > {(state.size === "XS" || state.size === "s" || (state.size === "m" && state.state === "default")) && ( <Bookmark className={`${ state.size === "s" ? styles.class : state.size === "XS" ? styles.class2 : styles.arrowLeft }`} color={ state.state === "hover-active" ? "white" : state.state === "disable" ? "#929292" : "#242222" } /> )} {state.size === "m" && ["disable", "hover-active"].includes(state.state) && ( <ArrowLeft className={styles.arrowLeft} color={state.state === "disable" ? "#929292" : "white"} /> )} </div> ); }; function reducer(state: any, action: any) { switch (action) { case "mouse_enter": return { ...state, state: "hover-active", }; case "mouse_leave": return { ...state, state: "default", }; } return state; } Icon.propTypes = { size: PropTypes.oneOf(["XS", "m", "s"]), stateProp: PropTypes.oneOf(["hover-active", "disable", "default"]), }; export default Icon;
import { Meta, StoryObj } from "@storybook/react"; import LoginForm from "./LoginForm"; import { fn } from "@storybook/test"; const meta: Meta<typeof LoginForm> = { title: "Molecules/LoginForm", component: LoginForm, decorators: [ (Story) => ( <div className="flex justify-center items-center min-h-screen bg-gray-100 p-4"> <Story /> </div> ), ], args: { onForgotPassword: fn(), }, argTypes: { variant: { control: { type: "select" }, options: [ "default", "compact", "withImage", "withLogo", "floatingLabels", "edgeless", "inline", ], }, error: { control: { type: "text" }, }, imageUrl: { control: { type: "text" }, table: { category: "withImage Variant", }, }, logoUrl: { control: { type: "text" }, table: { category: "withLogo Variant", }, }, }, }; export default meta; export const Default: StoryObj<typeof LoginForm> = { args: { variant: "default", }, }; export const Compact: StoryObj<typeof LoginForm> = { args: { variant: "compact", }, }; export const WithImage: StoryObj<typeof LoginForm> = { args: { variant: "withImage", imageUrl: "https://via.placeholder.com/600x400", // Placeholder image URL }, }; export const WithLogo: StoryObj<typeof LoginForm> = { args: { variant: "withLogo", logoUrl: "https://via.placeholder.com/150", // Placeholder logo URL }, }; export const Edgeless: StoryObj<typeof LoginForm> = { args: { variant: "edgeless", }, }; export const Inline: StoryObj<typeof LoginForm> = { args: { variant: "inline", }, }; export const WithError: StoryObj<typeof LoginForm> = { args: { error: "Invalid username or password", }, };
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>About Me</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="assets/css/style.css"> </head> <body> <header> <nav class="navbar navbar-default"> <div class="container container-hdr"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">Elizabeth Tom</a> </div> <!-- end div class="navbar-header" --> <!-- Links to About, Portfolio, Contact --> <ul class="nav navbar-nav navbar-right navbar-text"> <li class="col-xs-4"><a href="index.html">About</a></li> <li class="col-xs-4"><a href="portfolio.html">Portfolio</a></li> <li class="col-xs-4"><a href="contact.html">Contact</a></li> </ul> </div> <!-- end div class="container container-main" --> </nav> </header> <div class="container-fluid container-main"> <div class="row"> <!-- About Me --> <div class="col-md-8 col-xs-12"> <section class="content"> <div class="panel panel-default"> <div class="panel-body"> <div class="hdr-row row"> <h2>About Me</h2> </div> <!-- end div class="row" --> <div class="row"> <div class="col-lg-5 col-md-12 col-sm-4 col-xs-12"> <div class="thumbnail"> <img src="assets/images/selfie.jpg" alt="Elizabeth Tom image"> </div> <!-- end div class="thumbnail" --> </div> <!-- end div class="col-lg-5 col-md-12 col-sm-4 col-xs-12" --> <p> Howdy ya'll! I'm a native Texan, born and raised in San Antonio. I'm currently working as a substitute teacher and pursuing a Bachelor's degree in Computer Science. In my free time, I enjoy coding, cooking, reading, and exploring with my puppy, Princess. </p> </div> <!-- end div class="row" --> </div> <!-- end div class="panel-body" --> </div> <!-- end div class="panel panel-default" --> </section> </div> <!-- end class="col-md-8 col-xs-12" --> <!-- Connect with Me --> <div class="col-md-4 col-xs-12"> <section class="connect"> <div class="panel panel-default"> <div class="panel-body"> <div class="hdr-row row"> <h3>Connect with Me</h3> </div> <!-- end div class="row" --> <!-- Links to Github, Linked In, and Stack Overflow --> <div class="row"> <div class="col-xs-2 col-md-3"> <a href="https://github.com/lizbeth523" target="_blank"> <img src="assets/images/gitHub48.png" alt="Github"> </a> </div> <!-- end div class="col-xs-2 col-md-3" --> <div class="col-xs-2 col-md-3"> <a href="https://www.linkedin.com/in/elizabeth-tom/" target="_blank"> <img src="assets/images/linkedIn48.png" alt="Linked In"> </a> </div> <!-- end div class="col-xs-2 col-md-3" --> <div class="col-xs-2 col-md-3"> <a href="https://stackexchange.com/users/11471754/liz?tab=accounts" target="_blank"> <img src="assets/images/stackOverflow48.png" alt="Stack Overlow"> </a> </div> <!-- end div class="col-xs-2 col-md-3" --> </div> <!-- end div class="row" --> </div> <!-- end div class="panel-body" --> </div> <!-- end div class="panel panel-default" --> </section> </div> <!-- end div class="col-md-4 col-xs-12" --> </div> <!-- end div class="row" --> </div> <!-- end div class="container-fluid" --> <footer> <nav class="navbar navbar-default navbar-fixed-bottom"> <div class="container-fluid"> <div class="row"> <div class="col-xs-8 col-xs-offset-2 col-sm-5 col-sm-offset-4 col-md-4 col-md-offset-4 col-lg-3 col-lg-offset-5"> <p class="navbar-text text-center">© Copyright 2017 Elizabeth Tom</p> </div> <!-- end div class="col-xs-8 col-xs-offset-2 col-sm-5 col-sm-offset-4 col-md-4 col-md-offset-4 col-lg-3 col-lg-offset-5" --> </div> <!-- end div class="row" --> </div> <!-- end div class="container-fluid" --> </nav> </footer> </body> </html>
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strdup.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yimizare <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/11/07 15:30:09 by abouramt #+# #+# */ /* Updated: 2024/06/12 18:13:27 by yimizare ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strdup(const char *s1) { int i; int j; char *tab; if (!s1) return (NULL); i = ft_strlen(s1); tab = (char *)malloc(sizeof(char) * (i + 1)); if (tab == NULL) return (NULL); j = 0; while (j < i) { tab[j] = s1[j]; j++; } tab[j] = '\0'; return (tab); }
from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import mixins, response from rest_framework.decorators import action from rest_framework.viewsets import GenericViewSet from rest_framework.pagination import PageNumberPagination from django_filters.rest_framework import DjangoFilterBackend from book.models import Book from favorite.models import Favorite from review.serializers import ReviewSerializer from . import serializers class StandartResultPagination(PageNumberPagination): page_size = 6 page_query_param = 'page' class BooksViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): queryset = Book.objects.all() pagination_class = StandartResultPagination filter_backends = (DjangoFilterBackend, ) filterset_fields = ('author', 'genre',) query_param_start_date = openapi.Parameter( 'start_date', openapi.IN_QUERY, description='Start date for filtering', type=openapi.TYPE_STRING, ) query_param_end_date = openapi.Parameter( 'end_date', openapi.IN_QUERY, description='End date for filtering', type=openapi.TYPE_STRING, ) @swagger_auto_schema(manual_parameters=[query_param_start_date, query_param_end_date, ]) def list(self, request, *args, **kwargs): return super().list(request, *args, *kwargs) def get_serializer_class(self): if self.action == 'list': return serializers.BookListSerializer elif self.action == 'retrieve': return serializers.BookDetailSerializer elif self.action == 'reviews': return ReviewSerializer def get_queryset(self): queryset = super().get_queryset() start_date = self.request.query_params.get('start_date', None) end_date = self.request.query_params.get('end_date', None) if start_date and end_date: queryset = queryset.filter(publish_date__range=[start_date, end_date]) return queryset # api/v1/books/<id>/reviews/ @action(['GET', 'POST', 'DELETE'], detail=True) def reviews(self, request, pk): book = self.get_object() user = request.user if request.method == 'GET': reviews = book.reviews.all() serializer = ReviewSerializer(reviews, many=True).data return response.Response(serializer, status=200) elif request.method == 'POST': if book.reviews.filter(owner=request.user).exists(): return response.Response({'msg': 'You already reviewed this book!'}, status=400) data = request.data serializer = ReviewSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save(owner=request.user, book=book) return response.Response(serializer.data, status=201) else: if not book.reviews.filter(owner=user).exists(): return response.Response({'msg': 'You didn\'t reviewed this book!'}, status=400) review = book.reviews.get(owner=user) review.delete() return response.Response({'msg': 'Successfully deleted'}, status=204) # api/v1/books/<id>/favorites/ @action(['POST', 'DELETE'], detail=True) def favorites(self, request, pk): book = self.get_object() # Book.objects.get(id=pk) user = request.user favorite = user.favorites.filter(book=book) if request.method == 'POST': if favorite.exists(): return response.Response({'msg': 'Already in Favorite'}, status=400) Favorite.objects.create(owner=user, book=book) return response.Response({'msg': 'Added to Favorite'}, status=201) if favorite.exists(): favorite.delete() return response.Response({'msg': 'Deleted from Favorite'}, status=204) return response.Response({'msg': 'Book Not Found in Favorite'}, status=404)
#include "../inc.h" class Solution { public: vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { unordered_map<string, unordered_map<string, double>> dict; int esize = equations.size(), qsize = queries.size(); for (int i = 0; i < esize; ++i) { const auto &a = equations[i][0], &b = equations[i][1]; dict[a][b] = values[i]; dict[b][a] = 1.0 / values[i]; } vector<double> ret(qsize, -1.0); for (int i = 0; i < qsize; ++i) { const auto &a = queries[i][0], &b = queries[i][1]; if (dict.count(a) == 0 || dict.count(b) == 0) continue; double curr = 1.0; unordered_set<string> vis; if (dfs(dict, a, b, curr, vis)) ret[i] = curr; } return ret; } bool dfs(unordered_map<string, unordered_map<string, double>>& dict, const string& a, const string& b, double& curr, unordered_set<string>& vis) { if (dict[a].count(b) > 0) { curr *= dict[a][b]; return true; } for (const auto& [c, ac] : dict[a]) { double ab = ac; if (vis.count(c) > 0) continue; vis.insert(c); if (dfs(dict, c, b, ab, vis)) { curr *= ab; return true; } } return false; } }; void test(vector<vector<string>>&& equations, vector<double>&& values, vector<vector<string>>&& queries, const vector<double>& expect) { save4print(equations, values, queries); assert_eq_ret(expect, Solution().calcEquation(equations, values, queries)); } int main() { test({{"x1", "x2"}, {"x2", "x3"}, {"x3", "x4"}, {"x4", "x5"}}, {3.0, 4.0, 5.0, 6.0}, {{"x1", "x5"}, {"x5", "x2"}, {"x2", "x4"}, {"x2", "x2"}, {"x2", "x9"}, {"x9", "x9"}}, {360, 0.00833333, 20, 1, -1, -1}); test({{"a", "c"}, {"b", "e"}, {"c", "d"}, {"e", "d"}}, {2.0, 3.0, 0.5, 5.0}, {{"a", "b"}}, {0.06667}); test({{"a", "b"}, {"b", "c"}}, {2.0, 3.0}, {{"a", "c"}, {"b", "a"}, {"a", "e"}, {"a", "a"}, {"x", "x"}}, {6.00000, 0.50000, -1.00000, 1.00000, -1.00000}); test({{"a", "b"}, {"b", "c"}, {"bc", "cd"}}, {1.5, 2.5, 5.0}, {{"a", "c"}, {"c", "b"}, {"bc", "cd"}, {"cd", "bc"}}, {3.75000, 0.40000, 5.00000, 0.20000}); test({{"a", "b"}}, {0.5}, {{"a", "b"}, {"b", "a"}, {"a", "c"}, {"x", "y"}}, {0.50000, 2.00000, -1.00000, -1.00000}); return 0; }
""" Nomear argumentos----------------------------- def cidade(parte1, parte2): print(parte1 + ' ' + parte2) cidade('São', "Paulo") cidade('Paulo', "São") cidade(parte1='São', parte2='Paulo') cidade(parte2='Paulo', parte1='São') #Parametro padrão #função que não exige parametros print() input() #função que exige parametro def soma(num1, num2): print(num1 + num2) soma(10,18) #função com parametro padrão (default) def medida(numero, referencia= 60): if numero > referencia: print(f'{numero} é maior que {referencia}') else: print(f"{numero} é menor que {referencia}") medida(70) medida(50) medida(100) medida(30) medida(200) medida(0) def medida(numero=76, referencia= 60): if numero > referencia: print(f'{numero} é maior que {referencia}') else: print(f"{numero} é menor que {referencia}") medida() medida(40,50) #se nao passar parametros ,vai valer isso medida(70) #se nao passar parametros ,vai valer isso # Comando global nome = 'arroz' #variavel global---------- def comida(): global nome #Comando global converte em varivel local nome = nome + " e miojo" print(nome) comida() """ def funFora(): #criar funcao total = 0 #criar variavel def funDentro(): #criar funcao dentro nonlocal total #faz variavel da funcao cima valer aqui total = total + 1 print(total) return funDentro() #pertence a funFora, retorna e fecha funFora()
import Link from "next/link" import styles from "./LatestNews.module.scss" import localFont from "next/font/local" import { convertTimeUTC } from "@/app/libs/date" import "../../styles/fontello/css/fontello.css" import { useAppContext } from "@/app/Hooks/Hook" const MontserratExtraBold = localFont({ src: '../../fonts/Montserrat-ExtraBold.woff2' }) const MontserratMedium = localFont({ src: '../../fonts/Montserrat-Medium.woff2' }) const LatestNews = ({ news }) => { const {dark} = useAppContext() return ( <div className={styles.wrapper}> <div className={`${styles.title} ${dark ? styles.active : ""} ${MontserratExtraBold.className}`}> <h2><Link href="/son-xeberler">Son xəbərlər</Link></h2> </div> <div className={`${styles.contentWrapper} ${MontserratMedium.className}`}> { news && news.slice(0, 20).map(item => { return ( <div key={item.id} className={`${styles.content} ${item.urgent && styles.urgent} ${item.important && styles.important}`}> <div className={styles.time}> <span>{convertTimeUTC(item.date)}</span> </div> <div className={styles.info}> <div className={styles.newsTitle}> <Link href={`/${item.subCatUrl !== "" ? item.subCatUrl : item.catUrl}/${item.id}`}>{item.photo && <span className="type">FOTO</span>}{item.video && <span className="type">VİDEO</span>}{item.title}{item.paid_info && <span className="iconLock"></span>}</Link> </div> <div className={styles.category}> <Link href={`/${item.subCatUrl !== "" ? item.subCatUrl : item.catUrl}`}>{item.sub_category !== "" ? item.sub_category : item.category}</Link> </div> </div> </div> ) }) } </div> <div className={styles.btnAllNews}> <Link href={`/son-xeberler`}>BÜTÜN XƏBƏR LENTİ</Link> </div> </div> ) } export default LatestNews
use std::collections::HashSet; use advent_of_code::{Compass, Grid}; use itertools::Itertools; use strum_macros::FromRepr; advent_of_code::solution!(16); #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] enum Mirror { None = b'.', Forward = b'/', Back = b'\\', Horizontal = b'-', Vertical = b'|', } impl From<char> for Mirror { fn from(value: char) -> Self { Mirror::from_repr(value as u8).unwrap() } } impl From<Mirror> for char { fn from(value: Mirror) -> Self { value as u8 as char } } fn trace_paths(start: (usize, Compass), grid: &Grid<Mirror>) -> HashSet<usize> { let mut search_heads = vec![start]; let mut seen_starts = HashSet::new(); let mut energized = HashSet::new(); while let Some((mut curr, mut dir)) = search_heads.pop() { let mut seen = HashSet::new(); if !seen_starts.insert((curr, dir)) { continue; } energized.insert(curr); loop { use Compass as D; use Mirror as M; if !seen.insert((curr, dir)) { break; } energized.insert(curr); let mirror = grid.at_index(curr).unwrap(); dir = match (dir, mirror) { (D::E, M::Forward) => D::N, (D::E, M::Back) => D::S, (D::E, M::Vertical) => { search_heads.push((curr, D::N)); D::S } (D::W, M::Forward) => D::S, (D::W, M::Back) => D::N, (D::W, M::Vertical) => { search_heads.push((curr, D::N)); D::S } (D::N, M::Forward) => D::E, (D::N, M::Back) => D::W, (D::N, M::Horizontal) => { search_heads.push((curr, D::E)); D::W } (D::S, M::Forward) => D::W, (D::S, M::Back) => D::E, (D::S, M::Horizontal) => { search_heads.push((curr, D::E)); D::W } _ => dir, }; match grid.step_from_index(curr, dir) { Some(next) => curr = next, _ => break, } } } energized } pub fn part_one(input: &str) -> Option<usize> { let grid = Grid::<Mirror>::parse_lines(input); Some(trace_paths((0, Compass::E), &grid).len()) } pub fn part_two(input: &str) -> Option<usize> { let grid = Grid::<Mirror>::parse_lines(input); let starts = Some(Compass::S) .iter() .cartesian_product(0..grid.width) .chain(Some(Compass::N).iter().cartesian_product( (grid.data.len() - grid.width)..grid.data.len(), )) .chain( Some(Compass::E).iter().cartesian_product( (0..grid.height).map(|x| x * grid.width), ), ) .chain(Some(Compass::W).iter().cartesian_product( (0..grid.height).map(|x| x * grid.width + (grid.width - 1)), )) .collect_vec(); let result = starts .into_iter() .map(|(d, s)| trace_paths((s, *d), &grid).len()) .max() .unwrap(); Some(result) } #[cfg(test)] mod tests { use super::*; #[test] fn test_part_one() { let result = part_one(&advent_of_code::template::read_file("examples", DAY)); assert_eq!(result, Some(46)); } #[test] fn test_part_two() { let result = part_two(&advent_of_code::template::read_file("examples", DAY)); assert_eq!(result, Some(51)); } }
/** * Copyright © 2017 Jan Schmidt * * 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/>. */ #pragma once #include "../math.hpp" #include "generic_landscape.hpp" #include <random> namespace intrep { /** House of Cards landscape * * The template parameter T is for the container and double must be * castable to T. */ template <std::size_t L, class T, template <std::size_t, class> class Container, class RandomDist> class GenericHouseOfCards : public GenericLandscape<L, T, Container> { private: std::mt19937_64 _rand_engine; RandomDist _dist; bool _escape; T _escape_value; public: GenericHouseOfCards() : _rand_engine(std::random_device{}()), _dist(), _escape(false) { createLandscape(); } GenericHouseOfCards(typename RandomDist::param_type p) : _rand_engine(std::random_device{}()), _dist(p), _escape(false) { createLandscape(); } GenericHouseOfCards(typename RandomDist::param_type p, T esc_value) : GenericHouseOfCards(p) { _escape_value = esc_value; _escape = true; createLandscape(); } void setParam(typename RandomDist::param_type p) { _escape = false; _dist.param(p); } void setParam(typename RandomDist::param_type p, T escape) { _escape = true; _escape_value = escape; _dist.param(p); } void createLandscape() { for (auto& f : this->_fitness) { f = static_cast<T>(_dist(_rand_engine)); } if (_escape) { this->_fitness.back() = _escape_value; } } void createLandscape(typename RandomDist::param_type p) { _dist.param(p); _escape = false; for(auto& f: this->_fitness) { f = static_cast<T>(_dist(_rand_engine)); } } void createLandscape(typename RandomDist::param_type p, double escape_value) { _escape_value = escape_value; _escape = true; _dist.param(p); // Unfortunately, the compiler does something stupid when using // optimizations. The value true for _escape is not set before // calculating the random parts. Hence, this has to be done here // manually... :`( for(auto& f: this->_fitness) { f = static_cast<T>(_dist(_rand_engine)); } this->_fitness.back() = _escape_value; } }; template <std::size_t L, class T = double, template <std::size_t, class> class Container = CubeValues> using UniHouseOfCards = GenericHouseOfCards<L, T, Container, std::uniform_real_distribution<>>; template <std::size_t L, class T = double, template <std::size_t, class> class Container = CubeValues> using ExpHouseOfCards = GenericHouseOfCards<L, T, Container, std::exponential_distribution<double>>; // Rough Mt Fuji landscape template <std::size_t L, template <std::size_t, class> class Container, class RandomDist> class GenericRMF : public GenericLandscape<L, double, Container> { private: std::mt19937_64 _rand_engine; RandomDist _dist; double _slope; public: GenericRMF(double slope) : _rand_engine(std::random_device{}()), _dist(), _slope(slope) { createLandscape(); } GenericRMF(typename RandomDist::param_type p, double slope = static_cast<double>(1)) : _rand_engine(std::random_device{}()), _dist(p), _slope(slope) { createLandscape(); } GenericRMF() : GenericRMF(static_cast<double>(1)) { createLandscape(); } void setParam(typename RandomDist::param_type p) { _dist.param(p); } void setParam(typename RandomDist::param_type p, double slope) { _slope = slope; _dist.param(p); } void createLandscape() { for (std::size_t vertex = 0; vertex != this->_fitness.size(); ++vertex) { this->_fitness[vertex] = _slope * hammingweight(vertex) + _dist(_rand_engine); } } void createLandscape(typename RandomDist::param_type p) { _dist.param(p); for (std::size_t vertex = 0; vertex != this->_fitness.size(); ++vertex) { this->_fitness[vertex] = _slope * hammingweight(vertex) + _dist(_rand_engine); } } void createLandscape(typename RandomDist::param_type p, double slope) { _slope = slope; _dist.param(p); for (std::size_t vertex = 0; vertex != this->_fitness.size(); ++vertex) { this->_fitness[vertex] = _slope * hammingweight(vertex) + _dist(_rand_engine); } } }; template <std::size_t L, template <std::size_t, class> class Container = CubeValues> using UniformRMF = GenericRMF<L, Container, std::uniform_real_distribution<>>; template <std::size_t L, template <std::size_t, class> class Container = CubeValues> using ExpRMF = GenericRMF<L, Container, std::exponential_distribution<>>; } // end namespace intrep template<std::size_t L, template<std::size_t, class> class Container, class RandomDist> std::ostream& operator<<(std::ostream& out, const intrep::GenericRMF<L, Container, RandomDist>& fitness) { for(std::size_t vertex = 0; vertex != fitness.size(); ++vertex) { out << vertex << ' ' << fitness[vertex] << '\n'; } return out; }
package com.yolt.creditscoring.usecase; import com.yolt.creditscoring.configuration.annotation.UseCase; import com.yolt.creditscoring.service.audit.UserAuditService; import com.yolt.creditscoring.service.client.ClientStorageService; import com.yolt.creditscoring.service.creditscore.storage.CreditScoreStorageService; import com.yolt.creditscoring.service.creditscore.storage.dto.response.user.UserReportDTO; import com.yolt.creditscoring.service.user.CreditScoreUserDTO; import com.yolt.creditscoring.service.user.UserStorageService; import com.yolt.creditscoring.service.user.model.InvitationStatus; import com.yolt.creditscoring.service.userjourney.UserJourneyService; import com.yolt.creditscoring.service.yoltapi.YoltProvider; import com.yolt.creditscoring.service.yoltapi.dto.CreditScoreAccountDTO; import com.yolt.creditscoring.usecase.dto.CreditScoreUserResponseDTO; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.Email; import java.time.Clock; import java.time.LocalDate; import java.util.NoSuchElementException; import java.util.UUID; @Slf4j @UseCase @Validated @RequiredArgsConstructor public class ConfirmCreditScoreReportUseCase { public static final int YOLT_DEFAULT_FETCH_WINDOW = 18; private final UserStorageService userStorageService; private final CreditScoreStorageService creditScoreStorageService; private final ClientStorageService clientService; private final UserJourneyService userJourneyService; private final UserAuditService userAuditService; private final YoltProvider yoltProvider; private final Clock clock = Clock.systemUTC(); public @Valid CreditScoreUserResponseDTO getReportForUser(UUID userId) { CreditScoreUserDTO user = userStorageService.findById(userId); InvitationStatus creditScoreUserInvitationStatus = userStorageService.getCreditScoreUserInvitationStatus(userId); if (!InvitationStatus.ACCOUNT_SELECTED.equals(creditScoreUserInvitationStatus)) { throw new IllegalStateException("Wrong user workflow state"); } String clientAdditionalReportText = clientService.getClientAdditionalReportTextBasedOnClientId(user.getClientId()); return yoltProvider.getAccounts(user.getYoltUserId()).stream() .filter(account -> account.getId().equals(user.getSelectedAccountId())) .findFirst() .map(account -> mapCreditScoreReportToCreditScoreResponseDTO(user.getId(), account, clientAdditionalReportText, user.getEmail())) .orElseThrow(() -> new NoSuchElementException("Previously selected account by user is missing in Yolt API")); } /** * User confirm to share already generated report. */ @Transactional public void confirmReportShare(UUID userId, UUID clientId) { userStorageService.reportShareConfirmed(userId); userJourneyService.registerReportSaved(clientId, userId); userAuditService.logConfirmReportShare(clientId, userId); log.info("Report share confirmed"); } /** * User reject to share already generated report. * * Report should not be stored if user didn't confirm to share. * If such situation happen we will remove such report. */ @Transactional public void refuseReportShare(@NonNull UUID userId) { CreditScoreUserDTO user = userStorageService.findById(userId); if (creditScoreStorageService.findCreditScoreReportIdByUserId(user.getId()).isPresent()) { log.error("The credit report should not be stored when user refuse"); creditScoreStorageService.deleteByCreditScoreUserId(user.getId()); } yoltProvider.removeUser(user.getYoltUserId()); userStorageService.refuse(user.getId()); userStorageService.removeYoltUser(userId); userJourneyService.registerReportRefused(user.getClientId(), user.getId()); log.info("Report share refused"); } public String getClientRedirectUrlIfPresent(@NonNull UUID userId, @NonNull UUID clientId, boolean wasReportShared) { String baseClientRedirectUrl = clientService.getClientRedirectUrl(clientId); String status = wasReportShared ? "confirm" : "refuse"; return StringUtils.isNotEmpty(baseClientRedirectUrl) ? baseClientRedirectUrl + "?userId=" + userId + "&status=" + status : StringUtils.EMPTY; } private @Valid CreditScoreUserResponseDTO mapCreditScoreReportToCreditScoreResponseDTO(@NonNull UUID userId, CreditScoreAccountDTO account, String clientAdditionalReportText, @Email String email) { final LocalDate newestTransactionDate = account.getLastDataFetchTime() != null ? account.getLastDataFetchTime().toLocalDate() : LocalDate.now(clock); return CreditScoreUserResponseDTO.builder() .report(UserReportDTO.builder() .userId(userId) .iban(account.getAccountReference().getIban()) .bban(account.getAccountReference().getBban()) .maskedPan(account.getAccountReference().getMaskedPan()) .sortCodeAccountNumber(account.getAccountReference().getSortCodeAccountNumber()) .initialBalance(account.getBalance()) .lastDataFetchTime(account.getLastDataFetchTime()) // Newest and oldest transactions date is important to user. // It was calculated based on date of each transaction. // Since we are not fetch transaction on for user overview CFA has to mimic this values. .newestTransactionDate(newestTransactionDate) .oldestTransactionDate(newestTransactionDate.minusMonths(YOLT_DEFAULT_FETCH_WINDOW)) .currency(account.getCurrency()) .creditLimit(account.getCreditLimit()) .accountHolder(account.getAccountHolder()) .build()) .userEmail(email) .additionalTextReport(clientAdditionalReportText) .build(); } }
import { Notice } from '../interfaces/Notice' import moment from 'moment' import { getShortedDescription } from './NewCard' import { Bookmark } from './shared/Bookmark' interface Props { notice:Notice onClick: () => void handleSaveNotice: () => void } export const TopNewCard = ({ notice, onClick, handleSaveNotice }:Props) => { const { Title, Author, PublicationDate, Media, Description } = notice const publicationDateFormatted = moment(PublicationDate).startOf('hour').fromNow() const descriptionFormatted = getShortedDescription(Description) return ( <article className="flex flex-1 rounded-md py-5 max-w-7xl sm:flex-row flex-col"> <img src={Media} alt={Title} width={500} height={500} className="rounded-md sm:max-w-sm w-full p-2 cursor-pointer" onClick={onClick}/> <div className="flex flex-1 flex-col ml-2 sm:ml-0 items-start"> <h3 className="text-3xl font-semibold cursor-pointer" onClick={onClick}>{Title}</h3> <div className='flex flex-row items-start mt-1'> <span>{Author}</span> <span className='mx-2'>·</span> <span>{publicationDateFormatted}</span> </div> <p className='mt-5'>{descriptionFormatted}</p> <Bookmark onClick={handleSaveNotice}/> </div> </article> ) }
#include <iostream> #include <map> #include <set> #include <utility> #include <string> using namespace std; struct Token{ string type; string val; int line; Token(string t,string v,int l=0){ type = t; val = v; line = l; } string toString(){ string s; s = "<"+type+"|"+val+">|"+to_string(line)+"\n"; return s; } }; set <char> alphabet = {'a','b','c','d','e','f','g','h','i','j', 'k','l','m','n','o','p','r','s','t','u', 'v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J', 'K','L','M','N','O','P','R','S','T','U', 'V','W','X','Y','Z' }; set <char> digits = {'0','1','2','3','4','5','6','7','8','9'}; set <char> num = {'0','1','2','3','4','5','6','7','8','9','.','+','-','e','E'}; map<string,string> words{ {"+","OP_SUM"}, {"-","OP_RES"}, {"*","OP_MULT"}, {"/","OP_DIVIS"}, {":=","OP_ASSG"}, {"=","OP_EQ"}, {"<>","OP_NOT_EQ"}, {"<","OP_LESS"}, {"<=","OP_LESS_EQ"}, {">=","OP_GRT_EQ"}, {">","OP_GRT"}, {"^","OP_POW"}, {".","OP_POINT"}, {"and","OP_AND"}, {"or","OP_OR"}, {"not","OP_NOT"}, {"div","OP_DIV"}, {"mod","OP_MOD"}, {"in","OP_IN"}, {",","DEL_COMMA"}, {";","DEL_SEMICOLON"}, {":","DEL_TWOPOINT"}, {"(","DEL_LT_PARNT"}, {")","DEL_RT_PARNT"}, {"[","DEL_LT_CORCH"}, {"]","DEL_RT_CORCH"}, {"..","DEL_DBL_POINT"}, {"array","ARRAY"}, {"begin","BEGIN"}, {"case","CASE"}, {"const","CONST"}, {"do","DO"}, {"downto","DOWNTO"}, {"else","ELSE"}, {"end","END"}, {"file","FILE"}, {"for","FOR"}, {"function","FUNCTION"}, {"goto","GOTO"}, {"if","IF"}, {"label","LABEL"}, {"nil","NIL"}, {"of","OF"}, {"packed","PACKED"}, {"procedure","PROCEDURE"}, {"program","PROGRAM"}, {"record","RECORD"}, {"repeat","REPEAT"}, {"set","SET"}, {"then","THEN"}, {"to","TO"}, {"type","TYPE"}, {"until","UNTIL"}, {"var","VAR"}, {"while","WHILE"}, {"with","WITH"}, {"write","WRITE"}, {"writeln","WRITELN"}, {"until","UNTIL"}, {"continue","CONTINUE"}, {"break","BREAK"} }; map<string,string> keyWords{ {"array","ARRAY"}, {"begin","BEGIN"}, {"case","CASE"}, {"const","CONST"}, {"do","DO"}, {"downto","DOWNTO"}, {"else","ELSE"}, {"end","END"}, {"file","FILE"}, {"for","FOR"}, {"function","FUNCTION"}, {"goto","GOTO"}, {"if","IF"}, {"label","LABEL"}, {"nil","NIL"}, {"of","OF"}, {"packed","PACKED"}, {"procedure","PROCEDURE"}, {"program","PROGRAM"}, {"record","RECORD"}, {"repeat","REPEAT"}, {"set","SET"}, {"then","THEN"}, {"to","TO"}, {"type","TYPE"}, {"until","UNTIL"}, {"var","VAR"}, {"while","WHILE"}, {"with","WITH"}, {"write","WRITE"}, {"writeln","WRITELN"}, {"until","UNTIL"}, {"continue","CONTINUE"}, {"break","BREAK"}, {"and","OP_AND"}, {"or","OP_OR"}, {"not","OP_NOT"}, {"div","OP_DIV"}, {"mod","OP_MOD"}, {"in","OP_IN"} }; map <string,string> operators{ {",","DEL_COMMA"}, {";","DEL_SEMICOLON"}, {":","DEL_TWOPOINT"}, {"(","DEL_LT_PARNT"}, {")","DEL_RT_PARNT"}, {"[","DEL_LT_CORCH"}, {"]","DEL_RT_CORCH"}, {"..","DEL_DBL_POINT"}, {"+","OP_SUM"}, {"-","OP_RES"}, {"*","OP_MULT"}, {"/","OP_DIVIS"}, {":=","OP_ASSG"}, {"=","OP_EQ"}, {"<>","OP_NOT_EQ"}, {"<","OP_LESS"}, {"<=","OP_LESS_EQ"}, {">=","OP_GRT_EQ"}, {">","OP_GRT"}, {"^","OP_POW"}, {".","OP_POINT"}, };
const mongoose = require("mongoose"); const slugify = require("slugify"); const books = require("../data/booksData"); const bookSchema = new mongoose.Schema( { title: { type: String, required: [true, "Book must have a title"], unique: true, validate: { validator: function (val) { return !val.includes("-"); }, message: "Title must not contain (-)", }, }, description: { type: String, required: [true, "Book must have a description"], }, price: { type: Number, required: [true, "Book must have a price"], min: [0, "Price must be positive"], }, copies: { type: Number, default: 1, }, author: String, cover: String, slug: String, }, { timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true }, } ); // Virtual Proprieties bookSchema.virtual("fullTitle").get(function () { return `${this.title} by ${this.author}`; }); bookSchema.virtual("published").get(function () { return this.createdAt.getFullYear(); }); // Doc Middleware: .save() & .create() bookSchema.pre("save", function (next) { this.slug = slugify(this.title, { lower: true }); next(); }); // Query Middleware bookSchema.pre(/^find/, function (next) { // console.log("pre findOne..."); this.find({ copies: { $gt: 0 } }); next(); }); const Book = mongoose.model("Book", bookSchema); // Book.findOne({ _id: "65f83b112e3b99b4a63072bc" }).then((book) => { // console.log(book.fullTitle); // console.log(book.published); // }); // Book.create(books).then((books) => console.log(`${books.length} books Added`)); module.exports = Book;
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <meta charset="utf-8"/> <title>BLOG | YOUR BEST CHOICE</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta content="" name="description"/> <meta content="" name="author"/> <%@ include file="./../common/base.jsp" %> <link rel="stylesheet" type="text/css" href="${basePath}/resources/plugins/metronic/css/bootstrap-markdown.min.css"> <script src="${basePath}/resources/plugins/metronic/script/markdown.js" type="text/javascript"></script> <script src="${basePath}/resources/plugins/metronic/script/bootstrap-markdown.js" type="text/javascript"></script> <script src="${basePath}/resources/scripts/blog/blogManage.js" type="text/javascript"></script> </head> <body class="page-md"> <%@ include file="./../common/header.jsp" %> <!-- BEGIN PAGE CONTAINER --> <div class="page-container"> <!-- BEGIN PAGE HEAD --> <div class="page-head"> <div class="container"> <!-- BEGIN PAGE TITLE --> <div class="page-title"> <h1>编辑博客 <small>正文请使用MarkDown语言</small> </h1> </div> <!-- END PAGE TITLE --> </div> </div> <!-- END PAGE HEAD --> <!-- BEGIN PAGE CONTENT --> <div class="page-content"> <%@ include file="./../common/modalDialog.jsp" %> <div class="container"> <!-- BEGIN PAGE BREADCRUMB --> <ul class="page-breadcrumb breadcrumb"> <li> <a href="/" style="color: #5b9bd1">Home</a><i class="fa fa-circle"></i> </li> <li class="active"> 编辑博客 </li> </ul> <!-- END PAGE BREADCRUMB --> <!-- BEGIN PAGE CONTENT INNER --> <div class="row"> <div class="col-md-12"> <!-- BEGIN EXTRAS PORTLET--> <div class="portlet light"> <div class="portlet-title"> <div class="caption"> <i class="fa fa-cogs font-green-sharp"></i> <span class="caption-subject font-green-sharp bold uppercase">编辑博客</span> </div> <div class="tools"> <a href="javascript:;" class="collapse"> </a> </div> </div> <div class="portlet-body form"> <form class="form-horizontal form-bordered"> <div class="form-body"> <input type="hidden" id="blogId" value="${blog.id}"> <div class="form-group"> <label class="control-label col-md-2">标题</label> <div class="col-md-10"> <input type="text" id="title" class="form-control maxlength-handler" name="product[meta_title]" maxlength="100" placeholder="" value="${blog.title}"> <span id="titleHelp" class="help-block">最多80字符</span> </div> </div> <div class="form-group"> <label class="control-label col-md-2">正文</label> <div class="col-md-10"> <textarea id="content" name="content" data-provide="markdown" rows="10">${blog.content}</textarea> <span id="contentHelp" class="help-block">最多48000字符</span> </div> </div> <div class="form-group"> <label class="control-label col-md-2">标签</label> <div class="col-md-10"> <div class="checkbox-list"> <c:forEach items="${tags}" var="tag"> <div class="col-md-3"> <label class="checkbox-inline"> <input type="checkbox" name="tagCheckbox" value="${tag.id}" <c:if test="${fn:contains(blogTags, tag.id)}"> checked="checked" </c:if> >${tag.name}</label> </div> </c:forEach> </div> </div> </div> <div class="form-actions"> <div class="row"> <div class="col-md-offset-4 col-md-8"> <button type="button" class="btn green" onclick="blogManager.edit();"> Submit </button> </div> </div> </div> </div> </form> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <!-- BEGIN EXTRAS PORTLET--> <div class="portlet light"> <div class="portlet-title"> <div class="caption"> <i class="fa fa-cogs font-green-sharp"></i> <span class="caption-subject font-green-sharp bold uppercase">正文预览</span> </div> <div class="tools"> <a href="javascript:;" class="collapse"> </a> </div> </div> <div class="portlet-body form"> <form class="form-horizontal form-bordered"> <div class="form-body"> <div class="form-group"> <div class="col-md-12"> <xmp theme="united" style="display:none;"> ${blog.content} </xmp> </div> </div> </div> </form> </div> </div> </div> </div> <!-- END PAGE CONTENT INNER --> </div> </div> <!-- END PAGE CONTENT --> </div> <!-- END PAGE CONTAINER --> <%@ include file="./../common/preFooter.jsp" %> <%@ include file="./../common/footer.jsp" %> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> <script src="${basePath}/resources/plugins/strapdown/strapdown.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //初始化页面相应元素绑定事件 blogManager.init(); }); </script> </body> </html>
-- Databricks notebook source -- MAGIC %md -- MAGIC ##Getting started with Azure Databricks -- COMMAND ---------- -- MAGIC %md -- MAGIC ### Ingest Data to the Notebook -- MAGIC -- MAGIC ##### • Ingest data from dbfs sources -- MAGIC ##### • Create Sources as tables -- COMMAND ---------- -- MAGIC %sql -- MAGIC SELECT * FROM employees_csv -- MAGIC LIMIT 5; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Let us change name of the table first (if by some reason we chose to leave _csv at the end of table name, we can simply rename it with following command): -- COMMAND ---------- -- MAGIC %sql -- MAGIC ALTER TABLE employees_csv -- MAGIC RENAME TO employees; -- COMMAND ---------- SELECT * FROM EMPLOYEES LIMIT 5; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### We can easily check the schema of created table with following command: -- COMMAND ---------- DESCRIBE TABLE EMPLOYEES; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### We can notice that HIRE_DATE column is of "string" format. Let's assume that we need to have it stored as "date" format for future reference: -- COMMAND ---------- ALTER TABLE employees ADD COLUMN HIRED_DATE DATE; -- COMMAND ---------- UPDATE EMPLOYEES SET HIRED_DATE = TO_DATE(HIRE_DATE, 'dd-MMM-yy'); -- COMMAND ---------- DESCRIBE EMPLOYEES; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### We can easily create new tables based on already existing table: -- COMMAND ---------- DROP TABLE IF EXISTS ANNUAL_SALARY; CREATE TABLE annual_salary AS ( SELECT EMPLOYEE_ID, CONCAT(FIRST_NAME, ' ', LAST_NAME) AS EMPLOYEE_NAME, (SALARY * 12) AS ANNUAL_SALARY, DEPARTMENT_ID AS DEPARTMENT FROM EMPLOYEES); -- COMMAND ---------- SELECT * FROM annual_salary -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Let's run some analysis on the annual_salary data - let's check who are the top 5 of employees annual salary-wise: -- COMMAND ---------- SELECT EMPLOYEE_ID, EMPLOYEE_NAME, ANNUAL_SALARY, DEPARTMENT FROM ANNUAL_SALARY ORDER BY ANNUAL_SALARY DESC LIMIT 5; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Databricks Notebook allows to display queried data as a charts: -- COMMAND ---------- SELECT EMPLOYEE_ID, EMPLOYEE_NAME, ANNUAL_SALARY, DEPARTMENT FROM ANNUAL_SALARY ORDER BY ANNUAL_SALARY DESC LIMIT 5; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Let's see what is the total salary for each department: -- COMMAND ---------- SELECT DEPARTMENT, SUM(ANNUAL_SALARY) AS DEPARTMENT_COST FROM ANNUAL_SALARY GROUP BY DEPARTMENT ORDER BY DEPARTMENT_COST DESC; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### If we want to save the results to CSV file (for future reference or to send it to other department), we can easily Export the file by pressing "download" button under query result -- COMMAND ---------- SELECT DEPARTMENT, SUM(ANNUAL_SALARY) AS DEPARTMENT_COST FROM ANNUAL_SALARY GROUP BY DEPARTMENT ORDER BY DEPARTMENT_COST DESC; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Let's say that company wants to introduce the commission system based on employees total experience - currently we would have to manually measure the time, so let SQL do this for us: -- COMMAND ---------- ALTER TABLE EMPLOYEES ADD COLUMN seniority FLOAT; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Calculate hire_date - current_date total elapsed time and insert the values to the column: -- COMMAND ---------- UPDATE EMPLOYEES SET seniority = ROUND(((BIGINT(TO_TIMESTAMP(NOW())) - (BIGINT(TO_TIMESTAMP(HIRED_DATE)))) / 86400) / 365, 1) -- COMMAND ---------- SELECT * FROM EMPLOYEES; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Now, let's add the commission values based on the total experience: -- COMMAND ---------- UPDATE EMPLOYEES SET COMMISSION_PCT = CASE WHEN SENIORITY BETWEEN 10 AND 15 THEN '3' WHEN SENIORITY BETWEEN 15.1 AND 17 THEN '5' WHEN SENIORITY BETWEEN 17.1 AND 20 THEN '10' WHEN SENIORITY > 20.1 THEN '15' END; -- COMMAND ---------- SELECT * FROM EMPLOYEES; -- COMMAND ---------- -- MAGIC %md -- MAGIC ##### Query result can also be displayed as a pivot table: -- COMMAND ---------- SELECT JOB_ID, AVG(SALARY) FROM EMPLOYEES GROUP BY JOB_ID;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.metadata.typesystem.types; import com.google.common.collect.ImmutableList; import org.apache.hadoop.metadata.typesystem.types.utils.TypesUtil; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import scala.actors.threadpool.Arrays; import java.util.Collections; import java.util.List; public class TypeSystemTest extends BaseTest { @BeforeClass public void setUp() throws Exception { super.setup(); } @AfterMethod public void tearDown() throws Exception { getTypeSystem().reset(); } @Test public void testGetTypeNames() throws Exception { getTypeSystem().defineEnumType("enum_test", new EnumValue("0", 0), new EnumValue("1", 1), new EnumValue("2", 2), new EnumValue("3", 3)); Assert.assertTrue(getTypeSystem().getTypeNames().contains("enum_test")); } @Test public void testIsRegistered() throws Exception { getTypeSystem().defineEnumType("enum_test", new EnumValue("0", 0), new EnumValue("1", 1), new EnumValue("2", 2), new EnumValue("3", 3)); Assert.assertTrue(getTypeSystem().isRegistered("enum_test")); } @Test public void testGetTraitsNames() throws Exception { HierarchicalTypeDefinition<TraitType> classificationTraitDefinition = TypesUtil.createTraitTypeDef("Classification", ImmutableList.<String>of(), TypesUtil.createRequiredAttrDef("tag", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<TraitType> piiTrait = TypesUtil.createTraitTypeDef("PII", ImmutableList.<String>of()); HierarchicalTypeDefinition<TraitType> phiTrait = TypesUtil.createTraitTypeDef("PHI", ImmutableList.<String>of()); HierarchicalTypeDefinition<TraitType> pciTrait = TypesUtil.createTraitTypeDef("PCI", ImmutableList.<String>of()); HierarchicalTypeDefinition<TraitType> soxTrait = TypesUtil.createTraitTypeDef("SOX", ImmutableList.<String>of()); HierarchicalTypeDefinition<TraitType> secTrait = TypesUtil.createTraitTypeDef("SEC", ImmutableList.<String>of()); HierarchicalTypeDefinition<TraitType> financeTrait = TypesUtil.createTraitTypeDef("Finance", ImmutableList.<String>of()); getTypeSystem().defineTypes( ImmutableList.<StructTypeDefinition>of(), ImmutableList.of(classificationTraitDefinition, piiTrait, phiTrait, pciTrait, soxTrait, secTrait, financeTrait), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); final ImmutableList<String> traitsNames = getTypeSystem().getTraitsNames(); Assert.assertEquals(traitsNames.size(), 7); List traits = Arrays.asList(new String[]{ "Classification", "PII", "PHI", "PCI", "SOX", "SEC", "Finance", }); Assert.assertFalse(Collections.disjoint(traitsNames, traits)); } }
<?php namespace TravelPSDK\Flight; use TravelPSDK\Traits\OptionsAware as OptionsAwareTrait; class SearchParameters extends \ArrayObject { use OptionsAwareTrait; /** * @param array $params */ public function __construct(array $params = null) { parent::__construct(); if ($params) { $this->setOptions($params); } } /** * @var string */ private $apiToken; /** * @param string $marker * @return $this */ public function setAffiliateMarker($marker) { $this['marker'] = $marker; return $this; } /** * @param string $token * @return $this */ public function setApiToken($token) { $this->apiToken = $token; return $this; } /** * @param string $host * @return $this */ public function setHost($host) { $this['host'] = $host; return $this; } /** * @param string $ip * @return $this */ public function setIp($ip) { $this['user_ip'] = $ip; return $this; } /** * @param string $locale */ public function setLocale($locale) { $this['locale'] = $locale; return $this; } /** * @param string $tripClass * @return $this */ public function setTripClass($tripClass) { if ($tripClass !== TripClass::ECONOMY && $tripClass !== TripClass::BUSINESS) { throw new \InvalidArgumentException("Invalid tripClass given: $tripClass"); } $this['trip_class'] = $tripClass; return $this; } /** * @param array $passengers * @return $this */ public function setPassengers(array $passengers) { $validKeys = ['adults', 'children', 'infants']; $this->validateArrayFormat($passengers, $validKeys, "Invalid passengers format given: %s"); $this['passengers'] = $passengers; return $this; } /** * @param array $segments * @return $this */ public function setSegments(array $segments) { $validKeys = ['origin', 'desgination', 'date']; $expectedDateFormat = "Y-m-d"; foreach ($segments as $segment) { $this->validateArrayFormat($segment, $validKeys, "Invliad segment format given: %s"); $date = \DateTime::createFromFormat($expectedDateFormat, $segment['date']); if (!$date) { throw new \InvalidArgumentException("Invalid date format given: {$segment['date']}. Expected format: $expectedDateFormat"); } } $this['segments'] = $segments; return $this; } /** * @param array $array * @param array $expectedKeys * @param string $errorMessage * @throws \InvalidArgumentException */ private function validateArrayFormat($array, $expectedKeys, $errorMessage) { $keys = array_keys($array); $intersection = array_intersect($keys, $expectedKeys); if (empty($intersection)) { $errorMessage = sprintf($errorMessage, serialize($array)); throw new \InvalidArgumentException($errorMessage); } } /** * @return string */ public function getSignature() { if (!isset($this['signature'])) { $this['signature'] = $this->makeSignature(); } return $this['signature']; } /** * @param array $array * @return array */ private function recursiveSort($array) { $clonedArray = (array) $array; ksort($clonedArray, SORT_NATURAL); foreach ($clonedArray as $key => $value) { if (is_array($clonedArray[$key])) { $clonedArray[$key] = $this->recursiveSort($clonedArray[$key]); } } return $clonedArray; } /** * @param array $array * @return array */ private function getFlatternedValues($array) { $return = []; foreach ($array as $key => $value) { if (is_array($value)) { $return = array_merge($return, $this->getFlatternedValues($value)); } else { $return[] = $value; } } return $return; } /** * @return string */ private function makeSignature() { $parameters = $this->recursiveSort($this); $values = $this->getFlatternedValues($parameters); $signatureString = implode(':', $values); $signatureString = $this->apiToken . ':' . $signatureString; $signature = md5($signatureString); return $signature; } /** * @return array */ public function getApiParams() { $clonedArray = $this->recursiveSort($this); $clonedArray['signature'] = $this->getSignature(); return $clonedArray; } }
// // MovieViewModel.swift // TheMovieApp // // Created by Berkay Sazak on 6.11.2023. // import Foundation class MovieViewModel { private let webService : MovieService? var movieOutput : MovieViewModelOutput? init(webService: MovieService) { self.webService = webService } func fetchMovieSearchs(movieName: String){ webService?.searchMovies(query: movieName, completion: { result in switch result { case .success(let movieResult): self.movieOutput?.setSearchMovie(movieList: movieResult, error: nil) case .failure(let customError): switch customError{ case .decodingError: self.movieOutput?.setSearchMovie(movieList: MovieSearchResponse(search: []), error: "Decoding error.") case .networkError: self.movieOutput?.setSearchMovie(movieList: MovieSearchResponse(search: []), error: "Network error.") case .serverError: self.movieOutput?.setSearchMovie(movieList: MovieSearchResponse(search: []), error: "Server error.") case .urlError: self.movieOutput?.setSearchMovie(movieList: MovieSearchResponse(search: []), error: "Url error.") } } }) } }
/// name : "Ahmed Abd Al-Muti" /// email : "[email protected]" /// phone : "01234567801" /// password : "$2a$12$Wp7A2bycw/orhD/vdlR9HeU3s0j7nNtdtidlLdOs4uRVwu5eDW3rm" /// role : "user" /// _id : "63cd78f9c57ec80280491b4d" /// createdAt : "2023-01-22T17:57:13.885Z" /// updatedAt : "2023-01-22T17:57:13.885Z" /// __v : 0 class User { User({ this.name, this.email, this.phone, this.password, this.role, this.id, this.createdAt, this.updatedAt, this.v,}); User.fromJson(dynamic json) { name = json['name']; email = json['email']; phone = json['phone']; password = json['password']; role = json['role']; id = json['_id']; createdAt = json['createdAt']; updatedAt = json['updatedAt']; v = json['__v']; } String? name; String? email; String? phone; String? password; String? role; String? id; String? createdAt; String? updatedAt; num? v; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['name'] = name; map['email'] = email; map['phone'] = phone; map['password'] = password; map['role'] = role; map['_id'] = id; map['createdAt'] = createdAt; map['updatedAt'] = updatedAt; map['__v'] = v; return map; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>AdminLTE 3 | Project Add</title> <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <!-- Font Awesome --> <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css"> <!-- Theme style --> <link rel="stylesheet" href="/dist/css/adminlte.min.css"> </head> <body class="hold-transition sidebar-mini"> <!-- Site wrapper --> <div class="wrapper"> <div th:replace="~{/nav :: navfrag}"/> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Regform</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Project Add</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-6"> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Board</h3> <div class="card-tools"> <button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse"> <i class="fas fa-minus"></i> </button> </div> </div> <form action="#" th:action="@{'/boards'}" th:object="${dto}" name="title" th:method="post" enctype="multipart/form-data"> <div class="card-body"> <div class="form-group"> <label for="inputName">Title</label> <input type="text" id="inputName" class="form-control" name="title" th:field="*{title}"> </div> <div class="form-group"> <label for="inputContent">Content</label> <textarea id="inputContent" class="form-control" rows="4" name="content" th:field="*{content}"></textarea> </div> <div class="form-group"> <label for="inputProjectLeader"></label> <input type="hidden" th:value="${session.login.seq}" th:name="writerSeq" readonly id="inputProjectLeader" class="form-control"> </div> <div class="form-group"> <label for="inputProjectLeader2"></label> <input type="hidden" th:value=0 th:name="views" readonly class="form-control"> </div> <div class="form-group"> <label for="inputProjectLeader2"></label> <input type="hidden" th:value="unblock" th:name="block" readonly id="inputProjectLeader2" class="form-control"> </div> <div class="form-group"> <label>이미지</label> <input type="file" multiple="multiple" name="file"> </div> </div> <div class="col-12"> <input type="submit" value="Register" class="btn btn-success"> <input type="reset" value="Cancel" class="btn btn-success float-right"> </div> <!-- /.card-body --> </form> </div> <!-- /.card --> </div> </div> <div class="row"> <div class="col-12"> </div> </div> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <div th:replace="~{/footer :: footerfrag}"/> <!-- ./wrapper --> <!-- jQuery --> <script src="/plugins/jquery/jquery.min.js"></script> <!-- Bootstrap 4 --> <script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- AdminLTE App --> <script src="/dist/js/adminlte.min.js"></script> <!-- AdminLTE for demo purposes --> <script src="/dist/js/demo.js"></script> </body> </html>
use std::io::{ Error, ErrorKind }; // async fn my_async_call(url: &str) -> Result<serde_json::Value, reqwest::Error> { // let response: serde_json::Value = reqwest::get(url).await?.json::<serde_json::Value>().await?; // Ok(response) // } async fn my_async_call(url: &str) -> Result<serde_json::Value, Error> { let response: reqwest::Response = reqwest::get(url) .await .map_err(|_| Error::new(ErrorKind::Other, "Could not retrieve response"))?; let json_response: serde_json::Value = response .json::<serde_json::Value>() .await .map_err(|_| Error::new(ErrorKind::Other, "Could not decode to JSON"))?; Ok(json_response) } #[cfg(test)] mod test { use super::*; #[tokio::test] async fn tests_calls_async_fn() { let api_url: &str = "https://cat-fact.herokuapp.com/facts"; let my_res: Result<serde_json::Value, Error> = my_async_call(api_url).await; match my_res { Ok(r) => { dbg!(r); }, Err(_) => { panic!("Failed to make a request"); } } } }
// { Driver Code Starts #include<iostream> #include<bits/stdc++.h> using namespace std; /* Link list Node */ struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } }; int intersectPoint(struct Node* head1, struct Node* head2); Node* inputList(int size) { if(size==0) return NULL; int val; cin>> val; Node *head = new Node(val); Node *tail = head; for(int i=0; i<size-1; i++) { cin>>val; tail->next = new Node(val); tail = tail->next; } return head; } /* Driver program to test above function*/ int main() { int T,n1,n2,n3; cin>>T; while(T--) { cin>>n1>>n2>>n3; Node* head1 = inputList(n1); Node* head2 = inputList(n2); Node* common = inputList(n3); Node* temp = head1; while(temp!=NULL && temp->next != NULL) temp = temp->next; if(temp!=NULL) temp->next = common; temp = head2; while(temp!=NULL && temp->next != NULL) temp = temp->next; if(temp!=NULL) temp->next = common; cout << intersectPoint(head1, head2) << endl; } return 0; } // } Driver Code Ends /* Linked List Node struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } }; */ Node* temp; Node* a; Node* b; //Function to find intersection point in Y shaped Linked Lists. int intersectPoint(Node* head1, Node* head2) { // Your Code Here if (head1 == nullptr || head2 == nullptr) { return -1; } int c1 = 0, c2 = 0; temp = head1; while (temp) { c1++; temp = temp->next; } temp = head2; while (temp) { c2++; temp = temp->next; } a = head1; b = head2; if (c1 > c2) { for (int i = 0; i < c1 - c2; i++) { a = a->next; } } else if (c2 > c1) { for (int i = 0; i < c2 - c1; i++) { b = b->next; } } while (a && b) { if (a == b) { return a->data; } a = a->next; b = b->next; } return -1; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>3D Transformation</title> <style> #header{ background-color: darkturquoise; text-align: center; border: 2px solid red; border-radius: 20px; } #cover{ border: 2px solid red; height: 200px; width: 200px; margin: 50px; } /*Rotate 3D*/ #content1{ height: 200px; width: 200px; background-color: darkturquoise; /* perspective: distance of watching (deep); */ /* totate: x-axis, y-axis, z-axis, angle */ transform: perspective(300px) rotate3d(0, 50, 50, 30deg); } /*translate 3D*/ #content2{ height: 200px; width: 200px; background-color: darkturquoise; transform: perspective(300px) translate3d(50px, 50px, -50px); } </style> </head> <body> <h1 id="header">3D Transformation</h1> <div id="cover"> <div id="content1">Rotate 3D</div> </div> <div id="cover"> <div id="content2">Translate 3D</div> </div> </body> </html>
package Java.lebin.Training.InterviewCases.SortArray; /* 367. 有效的完全平方数 给你一个正整数 num 。如果 num 是一个完全平方数,则返回 true ,否则返回 false 。 完全平方数 是一个可以写成某个整数的平方的整数。换句话说,它可以写成某个整数和自身的乘积。 不能使用任何内置的库函数,如 sqrt 。 示例 1: 输入:num = 16 输出:true 解释:返回 true ,因为 4 * 4 = 16 且 4 是一个整数。 示例 2: 输入:num = 14 输出:false 解释:返回 false ,因为 3.742 * 3.742 = 14 但 3.742 不是一个整数。 */ public class _367_有效的完全平方数 { //方法三:二分查找 // 时间复杂度:O(logn),其中 n 为正整数 num 的最大值。 // 空间复杂度:O(1) public boolean isPerfectSquare(int num) { int left = 0, right = num; while (left <= right) { int mid = (right - left) / 2 + left; long square = (long) mid * mid; if (square < num) { left = mid + 1; } else if (square > num) { right = mid - 1; } else { return true; } } return false; } //暴力 //时间复杂度:O(sqrt{n}),其中 n 为正整数 num 的最大值。我们最多需要遍历 sqrt{n} + 1 个正整数。 //空间复杂度:O(1) public boolean isPerfectSquare2(int num) { long x = 1, square = 1; while (square <= num) { if (square == num) { return true; } ++x; square = x * x; } return false; } }
(* An implementation of shift0 and shift. *) effect Ctrl O R = { shift0 : type A. ((A ->[|R] O) ->[|R] O) => A } let reset c = handle c () with | return v => v | shift0 v => v resume end let _ = printInt (100 + reset (fn () => 10 + shift0 (fn k => k (k 1)))) let _ = printInt (reset (fn () => 100 + (reset (fn () => 10 + shift0 (fn _ => shift0 (fn _ => 1)))))) (**********) let copy xs = let rec visit xs = match xs with | [] => [] | x :: xs => visit (shift0 (fn k => x :: (k xs))) end in reset (fn () => visit xs) let stringOfIntList xs = let rec loop xs = match xs with | [] => "" | x :: xs => ", " ++ stringOfInt x ++ loop xs end in match xs with | [] => "[]" | x :: xs => "[" ++ stringOfInt x ++ loop xs ++ "]" end let _ = printStr (stringOfIntList (copy [1,2,3]) ++ "\n") let rev xs = let rec visit (type R) xs : _ / [Ctrl _ R |R] = match xs with | [] => [] | x :: xs => shift0 (fn k => reset (fn () => x :: k (visit xs))) end in reset (fn () => visit xs) let _ = printStr (stringOfIntList (rev [1,2,3]) ++ "\n") (* The following two examples do not type check due to the lack of answer-type modification in the type system. *) (* let prefixes xs = let rec visit lst = match xs with | [] => shift0 (fn _ => []) | x :: xs => x :: shift0 (fn k => (k []) :: reset (fn () => k (visit xs))) end in reset (fn () => visit xs) *) (* let rec app xs = match xs with | [] => shift0 (fn k => k) | x :: xs => x :: app xs end *) (**********) let amb () = shift0 (fn k => k True; k False) let fail () = shift0 (fn _ => ()) let _ = reset (fn () => printInt (if amb () then 1 else 2)) data Triple = T of Int, Int, Int let stringOfTriple t = match t with | T i j k => "(" ++ stringOfInt i ++ ", " ++ stringOfInt j ++ ", " ++ stringOfInt k ++ ")" end let printTriple t = printStr (stringOfTriple t ++ "\n") let rec choice n = if n > 0 then if amb () then choice (n - 1) else n else fail () let triple n s = let i = choice n in let j = choice (i - 1) in let k = choice (j - 1) in if i + j + k = s then T i j k else fail () let triples_9_15 = reset (fn () => printTriple (triple 9 15)) (**********) let shift v = shift0 (fn k => reset (fn () => v k)) let _ = printInt (100 + reset (fn () => 10 + shift (fn k => k (k 1)))) let _ = printInt (reset (fn () => 100 + (reset (fn () => 10 + shift (fn _ => shift (fn _ => 1)))))) let copy' xs = let rec visit (type R) xs : _ / [Ctrl _ R |R] = match xs with | [] => [] | x :: xs => visit (shift (fn k => x :: (k xs))) end in reset (fn () => visit xs) let rev' xs = let rec visit (type R) xs : _ / [Ctrl _ R |R] = match xs with | [] => [] | x :: xs => shift (fn k => reset (fn () => x :: k (visit xs))) end in reset (fn () => visit xs) let amb' (type R) = fn () => shift (fn k => (k True) : _ / [Ctrl _ R |R]; k False) let fail' () = shift (fn _ => ()) let rec choice' n = if n > 0 then if amb' () then choice' (n - 1) else n else fail' () let triple' n s = let i = choice' n in let j = choice' (i - 1) in let k = choice' (j - 1) in if i + j + k = s then T i j k else fail' () let triples_9_15' = reset (fn () => printTriple (triple' 9 15)) (* EoF *)
import { ValueObject } from '../../../shared/domain/ValueObject'; import { Result } from '../../../shared/core/Result'; import { Guard } from '../../../shared/core/Guard'; import { AmountErrors } from './AmountErrors'; import { BaseError } from '../../../shared/core/AppError'; interface AmountProps { value: number; } enum Operation { SUM = 'SUM', SUBTRACT = 'SUBTRACT', } export class Amount extends ValueObject<AmountProps> { // The operations add and subtract first multiply numbers by 100 to work with integers instead of decimals, and as it has no sense to allow a value we won't be able to add or subtract we set a maximum value for the creation: public static MAX_ABS = 90071992547409; // JS Number.MAX_SAFE_INTEGER = 9007199254740991, Number.MIN_SAFE_INTEGER = -9007199254740991 get value(): number { return this.props.value; } private constructor(props: AmountProps) { super(props); } public static create(props: AmountProps): Result<Amount> { const guardNull = Guard.againstNullOrUndefined( props.value, new AmountErrors.NotDefined() ); const guardType = Guard.isType( props.value, 'number', new AmountErrors.NotNumber() ); const combined = Guard.combine([guardNull, guardType]); if (combined.isFailure) return Result.fail(combined.error as BaseError); // Unsigned integer part const integerAbsPart = Math.trunc(Math.abs(props.value)); if (integerAbsPart > Amount.MAX_ABS) return Result.fail(new AmountErrors.MaxBreached(props.value)); //#region round unsigned integer part to 2 decimal precision number // using "const rounded = Math.round(props.value * 100) / 100;" fails rounding 10.075 into 10.07 instead of 10.08, so do this: let rounded = integerAbsPart; const decimalStr = props.value.toString().split('.')[1]; if (decimalStr) { let str3 = decimalStr.substring(0, 3); // e.g. '10.0759' to '075' str3 = str3.padEnd(3, '0'); // e.g. '10.1' to '100'; '10.01' to '010' const XXO = str3.at(2); // e.g. '123' to '3' let num3 = Number(str3); if (Number(XXO) >= 5) { num3 += 10; } const num2 = Math.trunc(num3 / 10); if (num2 === 100) { rounded += 1; } else { const num2_str = num2.toString().padStart(2, '0'); rounded = Number(rounded + '.' + num2_str); } } //#endregion const sign = props.value < 0 ? -1 : 1; return Result.ok<Amount>(new Amount({ value: rounded * sign })); } private operation(amount: Amount, type: Operation): Result<Amount> { console.log(`operation: ${type}`); console.log('this.props.value', this.props.value); console.log('amount.value', amount.value); const thisx100 = Amount.multiplyBy100(this.props.value); const operandx100 = Amount.multiplyBy100(amount.value); let resultx100; switch (type) { case Operation.SUM: resultx100 = thisx100 + operandx100; break; case Operation.SUBTRACT: resultx100 = thisx100 - operandx100; break; default: throw Error(`Operation unknown: ${type}`); } const resultOrError = Amount.create({ value: Amount.divideBy100(resultx100) }); if (resultOrError.isFailure) return Result.fail( new AmountErrors.InvalidOperationResult(resultOrError.error as BaseError) ); const result = resultOrError.value; console.log('operation result', result); return Result.ok(result); } public subtract(amount: Amount): Result<Amount> { return this.operation(amount, Operation.SUBTRACT); } public add(amount: Amount): Result<Amount> { return this.operation(amount, Operation.SUM); } public negate(): Amount { return Amount.create({ value: -this.props.value }).value; } private static multiplyBy100(value: number): number { const arrayStr = value.toString().split(''); let integerPart, decimalPart; const dotIndex = arrayStr.indexOf('.'); if (dotIndex === -1) { integerPart = value; decimalPart = '00'; } else { decimalPart = arrayStr.slice(dotIndex + 1).join(''); decimalPart = decimalPart.padEnd(2, '0'); integerPart = arrayStr.slice(0, dotIndex).join(''); } return Number(integerPart + decimalPart); } private static divideBy100(value: number): number { const arrayStr = value.toString().split(''); if (arrayStr.includes('.')) throw Error(`divideBy100 only handles integer numbers`); const decimalPart = arrayStr.slice(-2).join(''); const integerPart = arrayStr.slice(0, -2).join(''); return Number(integerPart + '.' + decimalPart); } }
<template> <div class="register"> <!-- 头部 --> <AppHeader to=".app-header" title="注册" left-arrow back></AppHeader> <div class="container"> <van-form ref="regForm" @submit="onSubmit" validate-first validate-trigger="onChange"> <van-cell-group inset> <van-field v-model="tel" name="tel" label="手机号" placeholder="请填写手机号" :rules="[ { required: true, message: '请填写手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '请填写正确手机号' }, { validator: validateTel }]" /> <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" /> <van-field name="code" v-model="code" center clearable label="验证码" placeholder="请输入短信验证码" :rules="[{ validator: validateCode }]"> <template #button> <van-button class="sendBtn" :disabled="isSend" size="small" type="primary" @click="sendCode(tel)" round> {{ isSend ? countDown : '发送验证码' }} </van-button> </template> </van-field> </van-cell-group> <div style="margin: 16px;"> <van-button round block type="primary" native-type="submit"> 提交 </van-button> </div> </van-form> </div> </div> </template> <script lang="ts" setup> import AppHeader from "@/components/AppHeader/index.vue" import type { Ref } from 'vue' // 从声明文件中解构出来 import { ref } from 'vue'; import { doCheckPhoneAPI, doSendMsgCodeAPI, doCheckCodeAPI, doFinishRegisterAPI } from '@/api/user' import { showToast } from 'vant'; import type { FormInstance } from 'vant'; import { useRouter } from 'vue-router'; const router = useRouter() const countDown = ref<number>(30) const isSend = ref<boolean>(false) const timer = ref<number | null>(null) // 获取表单ref const regForm = ref<FormInstance>() const tel: Ref = ref<string>(''); const password: Ref = ref<string>(''); const code: Ref = ref<string>(''); // 验证函数,手机号失焦时判断是否可用 const validateTel = async (tel: number): Promise<any> => { // console.log('tel', tel); try { let res = await doCheckPhoneAPI({ tel }) // console.log('res', res); return true // 验证成功,返回true } catch (err: any) { showToast(err.message) return false // 验证失败 => 返回false ,或者错误 } } // 验证验证码的验证函数 const validateCode = async (code: string): Promise<any> => { // console.log('code', code); if (!code) return false try { var res = await doCheckCodeAPI({ tel: tel.value, telcode: code }) // console.log('验证码', res); return true // 验证成功,返回true } catch (err: any) { // showToast('验证码错误') return false // 验证失败 => 返回false ,或者错误 } } // 发送验证码 const sendCode = async (tel: number): Promise<any> => { // 发送验证码前,先判断手机号是否正确 // validate // regForm => ref对象 => 需要通过.value try { // 断言这个元素是ref对象 await (regForm as Ref).value.validate('tel') // 能进来说明手机号可用 let res = await doSendMsgCodeAPI({ tel: tel }) console.log('验证码是', res.data) // 禁用发送按钮 isSend.value = true // 设置计时器,30秒之内不能重复点击 timer.value = setInterval(() => { countDown.value-- // 如果倒计时归零,可以继续点击 if (countDown.value == 0) { clearInterval((timer as Ref).value) isSend.value = false countDown.value = 30 } }, 1000) } catch (err) { return false } } // 提交事件 const onSubmit = async (): Promise<any> => { // console.log(values); // console.log(tel.value); // console.log(password.value); try { let res = await doFinishRegisterAPI({ tel: tel.value, password: password.value }) router.push('/login') } catch (err) { return false } } </script> <style scoped lang="scss"> .register { width: 100%; height: 100%; background-color: rgb(247, 248, 250); overflow: hidden; } .container { width: 90%; height: 3rem; margin: 0 auto; margin-top: 1rem; } .van-form { height: 4rem; .van-cell-group { height: 4rem; display: flex; flex-direction: column; justify-content: space-evenly; .van-cell { height: 20%; align-items: center; font-size: 0.25rem; } } .van-button--round { height: 0.7rem; } } .sendBtn { width: 1.64rem; height: 0.4rem; }</style>
--- slug: setup-jenkins-ui append_help_link: true title: Jenkins UI hide_title: true description: Configure Jenkins to send the correct branch name to Semgrep Cloud Platform. tags: - Semgrep Supply Chain - Team & Enterprise Tier --- import MoreHelp from "/src/components/MoreHelp" <ul id="tag__badge-list"> { Object.entries(frontMatter).filter( frontmatter => frontmatter[0] === 'tags')[0].pop().map( (value) => <li class='tag__badge-item'>{value}</li> ) } </ul> # Setting up Semgrep Supply Chain with Jenkins UI When running a CI job, the Jenkins UI Git plugin creates a detached `HEAD` ref by default. This causes Semgrep Supply Chain (SSC) to send a repository's branch name as `HEAD` to Semgrep Cloud Platform (SCP), instead of using the actual branch name. As a result, the Supply Chain findings may not display by default. This document explains how to set up Jenkins to fix this behavior for users of the **Jenkins UI Git plugin**. :::info Prerequisites To receive Semgrep Supply Chain findings, you must [add or onboard a project](/semgrep-code/getting-started/) (repository) to Semgrep Cloud Platform for scanning. ::: ## Verifying that there are findings to send to SCP These steps are optional, but it is recommended to perform the following procedure to verify that there are findings that Semgrep Cloud Platform is not displaying from your Jenkins job. 1. Sign into Jenkins. 2. Select the project that runs Semgrep Supply Chain scans. 3. Click **Build Now**. A new job appears in your Project page. 4. Click the queue number of the new job. This takes you to the **Console Output** page, displaying a log of your job. 5. Take note of the total number of Supply Chain findings. Note that Supply Chain findings in the log are divided into Reachable and Unreachable findings. 5. In Semgrep Cloud Platform, click **Supply Chain**. 6. In the search bar, enter the name of the project or repository you scanned. This ensures that you see only findings for the scanned repository. 7. Ensure that you see the total number of findings by selecting all checkboxes for **Exposure** and **Transitivity**. Note any discrepancy in findings. Refer to the following section after verifying discrepancies between your CI job log and Semgrep Cloud Platform findings. ## Setting up SSC with Jenkins UI To set up SSC with Jenkins UI, perform the following steps: 1. Select the project that runs Semgrep Supply Chain scans. 1. Click **Configure**. 1. Under **Source Code Management**, ensure that **Git** is selected. 1. Under **Git > Additional behaviors** click **Add**. 1. From the drop-down box, click **Check out to specific local branch**. 1. Enter the name of repository's mainline or trunk branch, such as `master`. ![Location of specific local branch text box](/img/jenkins-specific-local-branch.png#bordered) 1. Click **Save**. 1. Optional: Click **Build Now** to test that your job can now send findings to Semgrep Cloud Platform. You have successfully set up your Jenkins UI job to send findings to Semgrep Cloud Platform. <MoreHelp />
/**************************************************************************//** \file misc_feat.cc \brief This source file implements the function of software system information display. \author Yanzhen Zhu \version V1.0.1 \date 21. November 2022 ******************************************************************************/ #include "misc_feat.h" #include <iostream> #include <sys/stat.h> #include "gitver.h" #include <sched.h> #include <pthread.h> #include <sys/resource.h> #include <sys/file.h> #include <csignal> #include <unistd.h> /*! \brief Show software system compilation time and version. */ void MiscFeat::display_software_info(const std::string &version) { std::cout << "Compiler version: " << CXX_COMPILER_VERSION << "\n"; std::cout << "GTK library version: " << GTK_LIBRARY_VERSION << "\n"; std::cout << "GTKMM library version: " << GTKMM_LIBRARY_VERSION << "\n"; std::cout << "Git version: " << GIT_VERSION_HASH << "\n"; std::cout << "Compile time: " << __TIMESTAMP__ << "\n"; std::cout << "Software version: " << version << "\n"; } /*! \brief Determine whether a file exists. \return Whether a file exists */ bool MiscFeat::file_exists(const std::string &filename) { struct stat buffer{}; return (stat(filename.c_str(), &buffer) == 0); } /*! \brief Append information to a file. \return Is the write file successful */ bool MiscFeat::write_all_bytes_(const char *path, const void *data) noexcept { FILE *f = fopen(path, "wb+"); if (nullptr == f) return false; fwrite((char *) data, 4, 1, f); fflush(f); fclose(f); return true; } /*! \brief Set the priority of the process to the highest. */ void MiscFeat::set_priority_to_max() noexcept { char path_[260]; snprintf(path_, sizeof(path_), "/proc/%d/oom_adj", getpid()); char level_[] = "-17"; write_all_bytes_(path_, level_); setpriority(PRIO_PROCESS, 0, -20); struct sched_param param_{}; param_.sched_priority = sched_get_priority_max(SCHED_FIFO); sched_setscheduler(getpid(), SCHED_RR, &param_); } /*! \brief Check if the time units are equal and calculate the corresponding timestamp range. \param[in] cli_parser: Command line parser structure pointer \param[in] vcd_parser: VCD parser structure pointer \param[out] begin: Converted starting timestamp \param[out] end: Converted ending timestamp */ void MiscFeat::check_time_range_exists(CLIParser *cli_parser, VCDParser *vcd_parser, uint64_t *begin, uint64_t *end) { if ((cli_parser->get_time_range()->end_time_unit != vcd_parser->get_vcd_header()->vcd_time_unit) || (cli_parser->get_time_range()->begin_time_unit != vcd_parser->get_vcd_header()->vcd_time_unit)) { std::cout << "The time units you entered do not match the vcd file.\n"; exit(8); } *begin = (cli_parser->get_time_range()->begin_time) / (vcd_parser->get_vcd_header()->vcd_time_scale); *end = (cli_parser->get_time_range()->end_time) / (vcd_parser->get_vcd_header()->vcd_time_scale); }
package com.crazyidea.alsalah.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.crazyidea.alsalah.data.room.entity.Ayat import com.crazyidea.alsalah.data.room.entity.Khatma import com.crazyidea.alsalah.data.room.entity.Surah import com.crazyidea.alsalah.databinding.ItemBookmarkBinding import com.crazyidea.alsalah.databinding.ItemKhatmaBinding class KhatmasAdapter( val clickListener: KhatmaClickListener ) : ListAdapter<Khatma, RecyclerView.ViewHolder>(KhatmaDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return ViewHolder.from(parent) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is ViewHolder -> { holder.bind(clickListener, getItem(position)) } } } class ViewHolder private constructor(val binding: ItemKhatmaBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(clickListener: KhatmaClickListener, item: Khatma) { binding.item = item binding.clickListener = clickListener binding.executePendingBindings() } companion object { fun from(parent: ViewGroup): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = ItemKhatmaBinding.inflate(layoutInflater, parent, false) return ViewHolder(binding) } } } } class KhatmaClickListener( val clickListener: (item: Khatma) -> Unit ) { fun onClick(item: Khatma) = clickListener(item) } class KhatmaDiffCallback : DiffUtil.ItemCallback<Khatma>() { override fun areItemsTheSame(oldItem: Khatma, newItem: Khatma): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Khatma, newItem: Khatma): Boolean { return oldItem == newItem } }