text
stringlengths
184
4.48M
package com.example.calculatorapp.finance import android.app.AlertDialog import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.NumberPicker import androidx.constraintlayout.widget.ConstraintLayout import com.example.calculatorapp.R import com.google.android.material.bottomsheet.BottomSheetDialog import kotlinx.android.synthetic.main.activity_investment_calculate.* import kotlinx.android.synthetic.main.activity_investment_calculate.A_value import kotlinx.android.synthetic.main.activity_investment_calculate.backButton import kotlinx.android.synthetic.main.activity_investment_calculate.linearLayout2 import kotlinx.android.synthetic.main.dialog_investment_solutions.view.* class InvestmentCalculateActivity : AppCompatActivity() { var principal=0.0 var rate=0.0 var years=3 var months=2 var totalInvestment=0.0 var interestEarned=0.0 var selectedDate ="3 Year , 2 Month" var oneTime=true var Repeated=false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_investment_calculate) window.navigationBarColor = Color.BLACK backButton.setOnClickListener { finish() } periodLayout.setOnClickListener { val bottomSheet = BottomSheetDialog(this@InvestmentCalculateActivity, R.style.BottomSheetDialogTheme ) val bottomSheetView = LayoutInflater.from(applicationContext).inflate( R.layout.bottom_sheet_investment, findViewById(R.id.bottomSheetInvestment) ) as ConstraintLayout val month = bottomSheetView.findViewById<NumberPicker>(R.id.month) val year = bottomSheetView.findViewById<NumberPicker>(R.id.year) month.maxValue = 11 month.minValue = 0 month.value= months year.maxValue = 30 year.minValue = 0 year.value= years bottomSheetView.findViewById<View>(R.id.linearLayout2).setOnClickListener { bottomSheet.dismiss() } bottomSheetView.findViewById<View>(R.id.linearLayout3).setOnClickListener { selectedDate = "${year.value} Year , ${month.value} Month" periodText.text=selectedDate months = month.value years = year.value bottomSheet.dismiss() } bottomSheet.setContentView(bottomSheetView) bottomSheet.setCancelable(false) bottomSheet.setCanceledOnTouchOutside(true) bottomSheet.show() } linearLayout2.setOnClickListener { if(A_value.text.toString()==""){ principal=0.0 }else{ principal=A_value.text.toString().toDouble() } if(B_value.text.toString()==""){ rate=0.0 }else{ rate=B_value.text.toString().toDouble() } totalInvestment=calculateInvestmentValue(principal,rate,oneTime,years,months) val view = View.inflate(this, R.layout.dialog_investment_solutions, null) val builder = AlertDialog.Builder(this) builder.setView(view) val dialog = builder.create() dialog.show() dialog.window?.setBackgroundDrawableResource(android.R.color.transparent) view.cancel.setOnClickListener { dialog.dismiss() } view.answer.text=totalInvestment.toString() view.year_month.text="$years Year , $months Month" } } fun oneTimeOnClick(view: View){ val colorYellow=resources.getColor(R.color.yellow) val colorGrey=resources.getColor(R.color.grey) one_time.setTextColor(colorYellow) repeated.setTextColor(colorGrey) oneTime= true Repeated = false } fun repeatedOnClick(view: View){ val colorYellow=resources.getColor(R.color.yellow) val colorGrey=resources.getColor(R.color.grey) repeated.setTextColor(colorYellow) one_time.setTextColor(colorGrey) Repeated = true oneTime= false } fun calculateInvestmentValue(principal: Double, interestRate: Double, option:Boolean, years: Int, months: Int): Double { val totalMonths = years * 12 + months val monthlyInterestRate = interestRate / 100 / 12 var investmentValue = principal if (option) { investmentValue *= Math.pow(1 + monthlyInterestRate, totalMonths.toDouble()) } else{ val monthlyRate = rate / 12 / 100 investmentValue = principal * (Math.pow((1 + monthlyRate), totalMonths.toDouble()) - 1) / monthlyRate } return investmentValue } }
import java.util.List; /** * Класс для сравнения двух списков целых чисел по их средним значениям. */ public class ListComparer { private List<Integer> list1; private List<Integer> list2; /** * Конструктор класса ListComparer. * * @param list1 Первый список целых чисел. * @param list2 Второй список целых чисел. */ public ListComparer(List<Integer> list1, List<Integer> list2) { this.list1 = list1; this.list2 = list2; } /** * Сравнивает средние значения двух списков целых чисел. * * @return Результат сравнения в виде строки. */ public String compareLists() { double averageList1 = AverageCalculator.calculateAverage(list1); double averageList2 = AverageCalculator.calculateAverage(list2); String result; if (averageList1 > averageList2) { result = "Первый список имеет большее среднее значение"; } else if (averageList1 < averageList2) { result = "Второй список имеет большее среднее значение"; } else { result = "Средние значения равны"; } return result; } }
import { IconProp } from "@fortawesome/fontawesome-svg-core" import { faFolder } from "@fortawesome/free-solid-svg-icons" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { Link } from "react-router-dom" type ListItemProps = { /** Set to true if element should have background */ background?: boolean /** Set to true if element should be indented */ indent?: boolean /** Title of an List Element is at the left side */ title: string /** Icon at the beginning of the Element */ icon?: IconProp /** Content on the left side next to title */ header?: React.ReactChild /** Link to when click element */ to?: string /** Function what happens when you click element */ onClick?: (values: any) => void /** For Testing */ dataCy?: string } /** * List, should have List as parent */ export const ListItem: React.FC<ListItemProps> = ({ title, icon = faFolder, indent, background, header, children, to, onClick, dataCy }) => { // Elements on the left side of the item const headerContent = <> <FontAwesomeIcon icon={icon} className="text-lightgrey mr-4" /> <h4 className="text-lg text-headline-black font-semibold mr-4">{title}</h4> {header} </> const headerClasses = `flex items-center py-4 pl-7 ${indent ? "md:pl-16" : ""} flex-grow` return <div data-cy={dataCy} className={`flex rounded-lg w-full cursor-pointer ${background ? "bg-white-lightgrey hover:bg-gray-200" : "hover:bg-white-lightgrey"}`}> {to ? <Link to={to} className={headerClasses}> {headerContent} </Link> : <button type="button" onClick={onClick} className={headerClasses}> {headerContent} </button> } {children && <div className="flex items-center mx-4"> {children} </div>} </div> }
package exevent import ( "github.com/ichenhe/syncthing-hook/domain" ) // applyHandlers listens given event channel and pass the event to the handler chain built by handlers. // Adds an ChannelCollector to transform processed events into another channel and returns it. The returned channel // will be closed automatically once the given channel is closed. All handlers will also be destroyed at the same time. // // If there is no handler, the given channel is returned directly without any processing. func applyHandlers(eventCh domain.EventCh, handlers ...domain.EventHandler) domain.EventCh { if len(handlers) == 0 { return eventCh } channelCollector := NewChannelCollector() chain := domain.BuildEventHandlerChain(append(handlers, channelCollector)...) go func() { for event := range eventCh { chain.Handle(event) } domain.DestroyHandlerChain(chain) }() return channelCollector.GetCh() } // ChannelCollector forwards all events to a channel and call next handler. // The out channel will be closed once this collector is destroyed. type ChannelCollector struct { baseHandler ch chan *domain.Event } var _ domain.EventHandler = (*ChannelCollector)(nil) func NewChannelCollector() *ChannelCollector { return &ChannelCollector{ ch: make(chan *domain.Event), } } func (c *ChannelCollector) GetCh() domain.EventCh { return c.ch } func (c *ChannelCollector) Handle(event *domain.Event) { if c.ch != nil { c.ch <- event } c.callNext(event) } func (c *ChannelCollector) Destroy() { if c.ch != nil { close(c.ch) } c.ch = nil }
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app"></div> <script> //Crear un componente de contador con incremento y decremento const vm = Vue.createApp( { data(){ return { text:"Acceder a tu cuenta", state: false }; }, watch:{ state(value){ return value ? this.text = "Cierra sesión": this.text="Acceder a tu cuenta" } }, computed:{ label(){ return this.state ? "Acceder":"Salir" }, changeColor(){ return this.state ? ['open'] : ['closed']; } }, //Cambiar directiva template : ` <div class="container" :class="changeColor"> <h2>{{text}}</h2> <button @click="state = !state">{{label}}</button> </div> ` } ).mount("#app"); </script> <style> html, body { height: 100vh; margin: 0; font-family: Arial, Helvetica, sans-serif; } #app, .container { display: flex; justify-content: center; align-items: center; flex-direction: column; width: 100%; height: 100%; } button { margin-top: 24px; border: none; background-color: white; padding: 8px 24px; border-radius: 12px; } .closed { background-color: #eca1a6; } .open { background-color: #b5e7a0; } </style> </body> </html>
""" Holds all utility functions and data relevant to performing kinematics with the LeArm I highly recommend checking out "A Note on Denavit-Hartenberg Notation in Robotics by Harvey Lipkin (2005) This codebase was based on how the proximal variant was described in it. I am highly greatful for it as a resource. """ from dataclasses import dataclass import numpy as np import numpy.typing as npt import math from typing import Union LEARM_JOINT_OFFSETS : list[float] = [np.pi,np.pi/2.0, 0,np.pi/2.0,0,0.1524] # gripper confirmed twice! '''These are the values for the actuated joints that equate to the home configuration for the LeArm. These are meant to be constants and should not be touched''' LEARN_JOINT_MIN_MAX = [ [LEARM_JOINT_OFFSETS[0]-np.pi/2.0,LEARM_JOINT_OFFSETS[0]+np.pi/2.0], [LEARM_JOINT_OFFSETS[1]-np.pi/2.0,LEARM_JOINT_OFFSETS[1]+np.pi/2.0], [LEARM_JOINT_OFFSETS[2]-np.pi/2.0,LEARM_JOINT_OFFSETS[2]+np.pi/2.0], [LEARM_JOINT_OFFSETS[3]-np.pi/2.0,LEARM_JOINT_OFFSETS[3]+np.pi/2.0], [LEARM_JOINT_OFFSETS[4]-np.pi/2.0,LEARM_JOINT_OFFSETS[4]+np.pi/2.0], [LEARM_JOINT_OFFSETS[5],LEARM_JOINT_OFFSETS[5]+0.03175] ] ''' The min/max of the joint ranges for each joint. ''' @dataclass class DHParameters: """ These Denavit–Hartenberg (DH) parameters follow the proximal variant all angles are in radians distances are standardly in meters """ d : float = 0 """d: offset along previous z to the common normal""" theta : float = 0 """angle about previous z from old x to new x""" r : float = 0 """length of the common normal. Assuming a revolute joint, this is the radius about previous z.""" alpha : float = 0 """angle about common normal, from old z axis to new z axis""" def get_a_t_b(dh_parameter : DHParameters) -> npt.NDArray: """ Gets the SE(3) that represents where frame b is in frame a (conceptually, a is parent frame, b is child frame). """ mat_a = np.eye(4) mat_a[1,0] = dh_parameter.r mat_a[2,2] = math.cos(dh_parameter.alpha) mat_a[3,3] = math.cos(dh_parameter.alpha) mat_a[2,3] = -math.sin(dh_parameter.alpha) mat_a[3,2] = math.sin(dh_parameter.alpha) mat_b = np.eye(4) mat_b[3,0] = dh_parameter.d mat_b[1,1] = math.cos(dh_parameter.theta) mat_b[2,2] = math.cos(dh_parameter.theta) mat_b[1,2] = -math.sin(dh_parameter.theta) mat_b[2,1] = math.sin(dh_parameter.theta) return(np.matmul(mat_a,mat_b)) def get_link0_t_linki(dh_parameters : Union[list[DHParameters],list[float]]) -> list[npt.NDArray]: """ Given a list of DH parameters that start from 0 and go incrementally upward, return all link0_t_linki. For example, if you provide: dh_parameters = [dh_01,dh_12,dh_23] this will return world_t_linki_list = [link0_t_link0,link0_t_link1,link0_t_link2,link0_t_link3] Note that link0_t_link0 is always the 4x4 identity matrix (np.eye(4)) """ if len(dh_parameters) == 0: raise RuntimeError(f"dh_parameters can not be empty, was length {len(dh_parameters)}") else: if isinstance(dh_parameters[0], float): dh_parameters = get_dh_parameters(*dh_parameters) linki_t_linkj_list = [get_a_t_b(dh_parameter) for dh_parameter in dh_parameters] # j = i+1 world_t_linki_list = [np.eye(4)] for linki_t_linkj in linki_t_linkj_list: world_t_linkj = np.matmul(world_t_linki_list[-1], linki_t_linkj) world_t_linki_list.append(world_t_linkj) return(world_t_linki_list) def get_dh_parameters(q_0 : float = LEARM_JOINT_OFFSETS[0], q_1 : float = LEARM_JOINT_OFFSETS[1] , q_2 : float = LEARM_JOINT_OFFSETS[2] , q_3 : float = LEARM_JOINT_OFFSETS[3] , q_4 : float = LEARM_JOINT_OFFSETS[4] , q_5 : float = LEARM_JOINT_OFFSETS[5] , ): """ Returns dh parameters, with each q """ dh_01 = DHParameters( d = 0.03175, theta = q_0, # revolute joint r = 0, alpha = 0, ) dh_12 = DHParameters( d = 0, theta = q_1, # revolute joint r = 0.009525, # got this twice, nice! alpha = np.pi/2.0, ) dh_23 = DHParameters( d = 0, theta = q_2, # revolute joint r = 0.0762, alpha = 0 ) dh_34 = DHParameters( d = 0, theta = q_3, # revolute joint r = 0.0889, alpha = 0 ) dh_45 = DHParameters( d = 0, theta = q_4, # revolute joint r = 0, alpha = np.pi/2.0 ) dh_56 = DHParameters( d = q_5,# prismatic joint theta = 0, r = 0, alpha = 0 ) learm_dh_parameters = [dh_01, dh_12,dh_23,dh_34,dh_45,dh_56] return(learm_dh_parameters)
from django.db import models from users.models import UserWebsockets from notifications.managers import NotificationManager from notifications.utils import NotificationTypes as NtfTypes import json # Create your models here. class Notification(models.Model): class Meta: db_table = "notification" user = models.ForeignKey( UserWebsockets, on_delete=models.CASCADE, related_name="+", db_column="username", ) ntf_type = models.CharField( db_column="ntf_type", max_length=32, choices=NtfTypes.NOTIFICATION_CHOICES, default=NtfTypes.INFO ) body = models.TextField( db_column="body", blank=False, null=False, ) sent_time = models.DateTimeField( db_column="sent_time", auto_now_add=True, ) objects=NotificationManager() def __str__(self): return f"username: {self.user.username}, notification: {self.body}, sent_time: {self.sent_time}" def to_json(self) -> dict: if self.ntf_type in [NtfTypes.TOURNAMENT_REQ, NtfTypes.MATCH_REQ, NtfTypes.FRIEND_REQ]: body = json.loads(self.body) else: body = self.body data = { "type": self.ntf_type, "body": body, "sent_time": self.sent_time.strftime("%Y/%m/%d:%H.%M.%S"), } return data
import { Injectable } from '@angular/core'; import axios from 'axios'; import { Comentario } from '../../interface/vernoticia.interface'; @Injectable({ providedIn: 'root', }) export class AirtableService { private apiKey: string = 'YOUR_API_KEY'; private baseId: string = 'YOUR_BASE_ID'; private baseUrl: string = `https://api.airtable.com/v0/${this.baseId}`; constructor() {} private getHeaders() { return { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', }; } async getRecords(tableName: string): Promise<any> { const url = `${this.baseUrl}/${tableName}`; const headers = this.getHeaders(); try { const response = await axios.get(url, { headers }); return response.data.records; } catch (error) { console.error('Error retrieving records from Airtable:', error); throw error; } } async getRecordById(tableName: string, id: string): Promise<any> { const url = `${this.baseUrl}/${tableName}/${id}`; const headers = this.getHeaders(); try { const response = await axios.get(url, { headers }); return response.data; } catch (error) { console.error('Error retrieving record from Airtable:', error); throw error; } } async createComentario( noticiaId: string, comentario: Comentario ): Promise<any> { const url = `${this.baseUrl}/Comentarios`; const headers = this.getHeaders(); const data = { records: [ { fields: { comentario: comentario.comentario, noticias: [noticiaId], usuario: comentario.usuario, }, }, ], }; try { const response = await axios.post(url, data, { headers }); return response.data; } catch (error) { console.error('Error creating comentario in Airtable:', error); throw error; } } }
import { format } from "logform"; import { createLogger, transports, Logger } from "winston"; export class ApplicationLogger { private static instance: ApplicationLogger; private logger: Logger; private constructor() { this.logger = createLogger(); } public enableJSON(): ApplicationLogger { this.logger = createLogger({ format: format.combine(format.json()), }); return this; } public enableConsoleOutput(level?: string): ApplicationLogger { this.logger.add( new transports.Console({ level: level, }), ); return this; } public getLogger(): Logger { return this.logger; } public static getInstance(): ApplicationLogger { if (!ApplicationLogger.instance) { ApplicationLogger.instance = new ApplicationLogger(); } return ApplicationLogger.instance; } }
<template> <div class="container"> <h1>Edit News</h1> <div> <form :class="$style.Form" @submit.prevent="handleFormSubmit"> <div :class="$style.TextInputs"> <input v-model="urlToImage" :class="$style.TextInput" type="text" placeholder="Image URL" /> <input v-model="title" :class="$style.TextInput" type="text" placeholder="Title" /> </div> <textarea v-model="description" :class="$style.TextArea" placeholder="Content" ></textarea> <div :class="$style.ActionButtons"> <ActionButton label="Save" type="submit" /> <ActionButton label="Cancel" type="button" @click="$router.go(-1)" /> </div> </form> </div> </div> </template> <script> import ActionButton from "@/components/atoms/ActionButton.vue"; import { mapActions, mapState } from "vuex"; export default { data() { return { urlToImage: "", title: "", content: "", }; }, computed: { ...mapState(["newsDetail"]), }, methods: { ...mapActions(["fetchNewsById", "updateNews"]), handleFormSubmit() { this.updateNews({ id: this.$route.params.id, urlToImage: this.urlToImage, title: this.title, description: this.description, }); this.$router.go(-1); }, }, created() { this.fetchNewsById(this.$route.params.id); }, watch: { newsDetail(newValue) { if (Object.prototype.hasOwnProperty.call(newValue, "id")) { this.urlToImage = this.newsDetail.urlToImage; this.title = this.newsDetail.title; this.description = this.newsDetail.description; } }, }, components: { ActionButton, }, }; </script> <style lang="scss" module> .Form { display: flex; flex-direction: column; gap: 0.75rem; } .TextInputs { display: flex; gap: 0.75rem; } .TextInput, .TextArea { width: 100%; padding: 1rem; border: 1px solid #333333; } .TextArea { height: 10rem; } .ActionButtons { display: flex; gap: 0.75rem; } </style>
package repository import ( "database/sql" "encoding/json" "fmt" "os" ) type DataPermitRepositoryInterface interface { CreateTableIfNotExists() GetAllDataPermits() ([]byte, error) AddDataPermit(json_form string) error CloseDb() } type DataPermitRepository struct { Db *sql.DB } type JsonResult struct { Array []string } type DataPermit struct { Id string Status string Datapermit json.RawMessage } func openDb() *sql.DB { db, err := sql.Open("sqlite3", "./db/nc.db") if err != nil { fmt.Printf("[ERROR] %v\n", err) os.Exit(3) } return db } func (repository DataPermitRepository) CloseDb() { repository.Db.Close() } func CreateDataPermitRepository() *DataPermitRepository { dataPermitRepository := DataPermitRepository{ Db: openDb(), } return &dataPermitRepository } func (repository DataPermitRepository) CreateTableIfNotExists() { sqlStmt := `CREATE TABLE IF NOT EXISTS datapermit (id INTEGER PRIMARY KEY AUTOINCREMENT, status text NOT NULL, data_permit json NOT NULL);` _, err := repository.Db.Exec(sqlStmt) if err != nil { fmt.Printf("[ERROR] %q: %s\n", err, sqlStmt) return } } func (repository DataPermitRepository) GetAllDataPermits() ([]byte, error) { rows, err := repository.Db.Query("select id, status, data_permit from datapermit") if err != nil { fmt.Printf("[ERROR] Repository GetAllDataPermits: %v\n", err) } defer rows.Close() var a []DataPermit for rows.Next() { var id int var status string var datapermit string err = rows.Scan(&id, &status, &datapermit) if err != nil { fmt.Printf("[ERROR] DataPermitService rows.Scan: %v\n", err) return nil, err } datapermitJson := json.RawMessage(datapermit) datapermitJsonMarshal, err := json.Marshal(&datapermitJson) if err != nil { fmt.Printf("[ERROR] DataPermitService json.Marshal: %v\n", err) return nil, err } dataPermit := DataPermit{ Id: fmt.Sprint(id), Status: status, Datapermit: datapermitJsonMarshal, } a = append(a, dataPermit) } err = rows.Err() if err != nil { fmt.Printf("[ERROR] DataPermitService rows.Err: %v\n", err) return nil, err } return json.Marshal(a) } func (repository DataPermitRepository) AddDataPermit(json_form string) error { fmt.Printf("[LOG] DataPermitService Add\n") tx, err := repository.Db.Begin() if err != nil { fmt.Printf("[ERROR] DataPermitService transaction begin: %v\n", err) return err } stmt, err := tx.Prepare("INSERT INTO datapermit (status,data_permit) VALUES ('NEW',json(?))") if err != nil { fmt.Printf("[ERROR] DataPermitService insert: %v\n", err) return err } defer stmt.Close() _, err = stmt.Exec(fmt.Sprint(json_form)) if err != nil { fmt.Printf("[ERROR] DataPermitService exec: %v\n", err) return err } err = tx.Commit() if err != nil { fmt.Printf("[ERROR] DataPermitService transaction commit: %v\n", err) return err } return nil }
import { App, Editor, Modal, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, parseFrontMatterTags, getFrontMatterInfo } from 'obsidian'; import NDK, { NDKEvent, NDKPrivateKeySigner, } from '@nostr-dev-kit/ndk' import { nip19 } from 'nostr-tools' const now = () => Math.floor(Date.now() / 1000); const FRONTMATTER_REGEX = /^---\n(.*?\n)*?---\n/g // Remember to rename these classes and interfaces! interface NostrWikiSettings { privateKey: string; relays: string; } const DEFAULT_SETTINGS: NostrWikiSettings = { privateKey: 'nsec...', relays: 'wss://nos.lol' } export default class NostrWiki extends Plugin { settings: NostrWikiSettings; ndk: NDK; async onload() { await this.loadSettings(); const relays = this.settings.relays.split(',').map(r => r.trim()) const decoded = nip19.decode(this.settings.privateKey); const signer = new NDKPrivateKeySigner(decoded.data) this.ndk = new NDK({ explicitRelayUrls: relays, signer }); await this.ndk.connect(); // This adds an editor command that can perform some operation on the current editor instance this.addCommand({ id: 'nostr-wiki-publish', name: 'Publish the current page', editorCallback: async (editor, view: MarkdownView) => { const file = this.app.workspace.getActiveFile(); if (!file) return; const withoutFrontmatter = stripFrontmatter(view.data); const metadata = this.app.metadataCache.getFileCache(file); const title = file.basename const existingEvent = await this.getExistingEvent(title); new PublishModal(this.app, async category => { new Notice("Publishing your event...") await this.publishEvent(title, withoutFrontmatter, existingEvent, category, metadata?.frontmatter) new Notice("Event has been published"); }, existingEvent).open(); } }); // This adds a settings tab so the user can configure various aspects of the plugin this.addSettingTab(new NostrWikiSettingsTab(this.app, this)); } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } async publishEvent(title: string, data: string, existingEvent?: NDKEvent | null, category?: string, frontmatter?: Record<string, string>) { const event = new NDKEvent(this.ndk); event.kind = 30818; event.content = data event.tags.push(['d', normalizeTitle(title)]) event.tags.push(['title', title]) if (existingEvent?.tagValue('published_at')) { event.tags.push(['published_at', existingEvent.tagValue('published_at')!]); } else { event.tags.push(['published_at', `${now()}`]) } if (category) { event.tags.push(['c', category]) } if (frontmatter) { Object.keys(frontmatter).forEach(k => { event.tags.push([k, frontmatter[k]]) }) } await event.publish(); } async getExistingEvent(title: string) { const d = normalizeTitle(title); const user = await this.ndk.signer!.user() const event = await this.ndk.fetchEvent( { kinds: [30818], '#d': [d], authors: [user.pubkey] }, ); return event; } } const normalizeTitle = (title: string) => { return title.toLowerCase().replaceAll(' ', '-'); } const stripFrontmatter = (data: string) => { const stripped = data.replaceAll(FRONTMATTER_REGEX, '') return stripped } class NostrWikiSettingsTab extends PluginSettingTab { plugin: NostrWiki; constructor(app: App, plugin: NostrWiki) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); new Setting(containerEl) .setName('nsec') .setDesc('Paste in your nsec to sign notes') .addText(text => text .setPlaceholder('Enter your nsec') .setValue(this.plugin.settings.privateKey) .onChange(async (value) => { this.plugin.settings.privateKey = value; await this.plugin.saveSettings(); })); new Setting(containerEl) .setName('relays') .setDesc('List of relays to connect to, separated by a ,') .addText(text => text .setValue(this.plugin.settings.relays) .onChange(async (value) => { this.plugin.settings.relays = value; await this.plugin.saveSettings(); })); } } export class PublishModal extends Modal { result: string; onSubmit: (result: string) => void; category?: string; constructor(app: App, onSubmit: (result: string) => void, existingEvent?: NDKEvent | null) { super(app); this.onSubmit = onSubmit; this.category = existingEvent?.tagValue('c'); } onOpen() { const { contentEl } = this; contentEl.createEl("h1", { text: "Publish Settings" }); new Setting(contentEl) .setName("Category (optional)") .addText((text) => text.onChange((value) => { this.result = value }).setValue(this.category ?? "")) new Setting(contentEl) .addButton((btn) => btn .setButtonText("Publish") .setCta() .onClick(() => { this.close(); this.onSubmit(this.result); })); } onClose() { let { contentEl } = this; contentEl.empty(); } }
package game.components; // JDK packages import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; // GUI packages import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JPanel; // Local packages import game.GameController.Direction; public class Canvas extends JPanel { private static final int ELEMENTS_PER = 20; private static final int LENGTH_GAINED = 4; private static final Color BG_COLOR = Color.BLACK; private static final Color FOOD_COLOR = new Color(200, 50, 50); private int canvasWidth; private int canvasHeight; private int elementSize; private int leftToAdd; private int[] foodCoord; private boolean foodEaten; private boolean collided; private Deque<int[]> snakeBody; private Direction headDirection; public Canvas(int canvasSize) { this.canvasWidth = canvasSize; this.canvasHeight = canvasSize; this.elementSize = canvasHeight / ELEMENTS_PER; this.setPreferredSize(new Dimension(canvasSize, canvasSize)); this.setBackground(BG_COLOR); this.foodCoord = new int[2]; this.leftToAdd = 0; this.foodEaten = false; this.collided = false; this.snakeBody = new ArrayDeque<int[]>(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } public void draw(Graphics g) { int yCount = getUnitsX(); for(int i = 0; i < yCount; i++) { g.drawLine(i*elementSize, 0, i*elementSize, this.canvasHeight); } for(int i = 0; i < yCount; i++) { g.drawLine(0, i*elementSize, this.canvasWidth, i*elementSize); } g.setColor(FOOD_COLOR); g.fillOval(this.foodCoord[0] * this.elementSize, this.foodCoord[1] * this.elementSize, elementSize, elementSize); g.setColor(Color.GREEN); Iterator<int[]> snakeIter = this.snakeBody.iterator(); while(true) { int[] currentPiece = snakeIter.next(); if(!snakeIter.hasNext()) { int x = currentPiece[0] * this.elementSize; int y = currentPiece[1] * this.elementSize; int startAngle = 0; int arcAngle = 0; switch(this.headDirection) { case UP: y = (currentPiece[1] * this.elementSize) + this.elementSize / 2; startAngle = 0; arcAngle = 180; break; case DOWN: y = (currentPiece[1] * this.elementSize) - this.elementSize / 2; startAngle = 180; arcAngle = 180; break; case LEFT: x = currentPiece[0] * this.elementSize + this.elementSize / 2; startAngle = 90; arcAngle = 180; break; case RIGHT: x = currentPiece[0] * this.elementSize - this.elementSize / 2; startAngle = 270; arcAngle = 180; break; } g.fillArc(x, y, this.elementSize, this.elementSize, startAngle, arcAngle); break; } g.fillRect(currentPiece[0] * this.elementSize, currentPiece[1] * this.elementSize, this.elementSize, this.elementSize); } } public void endCanvas(Graphics g) { } public void stepSnake(Direction newDirection) { int newX = this.snakeBody.peekLast()[0]; int newY = this.snakeBody.peekLast()[1]; switch(newDirection) { case UP: newY--; break; case DOWN: newY++; break; case LEFT: newX--; break; case RIGHT: newX++; break; } int[] nextPiece; if(this.isTaken(newX, newY) || outOfBounds(newX, newY)) { this.collided = true; } if((newX == this.foodCoord[0]) && (newY == this.foodCoord[1])) { leftToAdd += LENGTH_GAINED; this.foodEaten = true; } if(leftToAdd > 0) { nextPiece = new int[2]; leftToAdd--; } else { nextPiece = this.snakeBody.poll(); } nextPiece[0] = newX; nextPiece[1] = newY; this.snakeBody.add(nextPiece); this.headDirection = newDirection; this.repaint(); // TODO: Only repaint head and tail } public void addPiece(int[] newPiece) { this.snakeBody.add(newPiece); } public void updateFood(int newX, int newY) { this.foodCoord[0] = newX; this.foodCoord[1] = newY; } public boolean isTaken(int x, int y) { Iterator<int[]> snakeIter = this.snakeBody.iterator(); while(snakeIter.hasNext()) { int[] currentPiece = snakeIter.next(); if(x == currentPiece[0] && y == currentPiece[1]) { return true; } } return false; } private boolean outOfBounds(int x, int y) { x *= this.elementSize; y *= this.elementSize; if(x >= this.canvasWidth || x < 0 || y >= this.canvasHeight || y < 0) { return true; } return false; } public boolean checkFood() { return this.foodEaten; } public boolean checkCollisons() { return this.collided; } public void foodMade() { this.foodEaten = false; } public int getUnitsX() { return canvasWidth / elementSize; } public int getUnitsY() { return canvasHeight / elementSize; } }
using System.Net; using FluentAssertions; using MediatR; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using SFA.DAS.PublicSectorOrganisations.Api.Controllers; using SFA.DAS.PublicSectorOrganisations.Application.Queries.GetMatchingPublicSectorOrganisations; using SFA.DAS.Testing.AutoFixture; namespace SFA.DAS.PublicSectorOrganisations.Api.Tests.Controllers.PublicSectorOrganisations; public class WhenCallingGetMatchingPublicSectorOrganisations { [Test, MoqAutoData] public async Task And_when_none_found_Then_controller_returns_empty_list() { var response = new GetMatchingPublicSectorOrganisationsResponse(Array.Empty<PublicSectorOrganisation>()); var mediatorMock = new Mock<IMediator>(); mediatorMock.Setup(x => x.Send(It.IsAny<GetMatchingPublicSectorOrganisationsQuery>(), It.IsAny<CancellationToken>())) .ReturnsAsync(response); var sut = new PublicSectorOrganisationsController(mediatorMock.Object); var result = await sut.GetMatches("Xyz") as OkObjectResult; result.StatusCode.Should().Be((int)HttpStatusCode.OK); var myApiResponse = result.Value as GetMatchingPublicSectorOrganisationsResponse; myApiResponse.PublicSectorOrganisations.Length.Should().Be(0); mediatorMock.Verify(x=>x.Send(It.Is<GetMatchingPublicSectorOrganisationsQuery>(p=>p.SearchTerm == "Xyz"), It.IsAny<CancellationToken>())); } [Test, MoqAutoData] public async Task And_when_records_exists_Then_controller_returns_Ok_and_result(GetMatchingPublicSectorOrganisationsResponse response) { var mediatorMock = new Mock<IMediator>(); mediatorMock.Setup(x => x.Send(It.IsAny<GetMatchingPublicSectorOrganisationsQuery>(), It.IsAny<CancellationToken>())) .ReturnsAsync(response); var sut = new PublicSectorOrganisationsController(mediatorMock.Object); var result = await sut.GetMatches(null) as OkObjectResult; var myApiResponse = result.Value as GetMatchingPublicSectorOrganisationsResponse; result.StatusCode.Should().Be((int)HttpStatusCode.OK); result.Value.Should().BeEquivalentTo(response); mediatorMock.Verify(x => x.Send(It.Is<GetMatchingPublicSectorOrganisationsQuery>(p => p.SearchTerm == null), It.IsAny<CancellationToken>())); } }
/* Copyright © 2011-2012 Clint Bellanger Copyright © 2014 Henrik Andersson Copyright © 2012-2016 Justin Jacobs This file is part of FLARE. FLARE 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. FLARE 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 FLARE. If not, see http://www.gnu.org/licenses/ */ /** * class MenuMiniMap */ #ifndef MENU_MINI_MAP_H #define MENU_MINI_MAP_H #include "CommonIncludes.h" #include "Utils.h" class MapCollision; class Sprite; class WidgetLabel; class MenuMiniMap : public Menu { private: Color color_wall; Color color_obst; Color color_hero; Sprite *map_surface; Sprite *map_surface_2x; Point map_size; Rect pos; WidgetLabel *label; Sprite *compass; Rect map_area; int current_zoom; bool lock_zoom_change; void createMapSurface(Sprite** target_surface, int w, int h); void renderMapSurface(const FPoint& hero_pos); void prerenderOrtho(MapCollision *collider, Sprite** target_surface, int zoom); void prerenderIso(MapCollision *collider, Sprite** target_surface, int zoom); public: MenuMiniMap(); ~MenuMiniMap(); void align(); void logic(); void render(); void render(const FPoint& hero_pos); void prerender(MapCollision *collider, int map_w, int map_h); void setMapTitle(const std::string& map_title); }; #endif
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Moja Strona</title> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> <div class="wrapper"> <div class="navbar"> <form class="login-form"> <label for="login">Login:</label> <input type="text" id="login" name="login" placeholder="Twój login"> <label for="password">Hasło:</label> <input type="password" id="password" name="password" placeholder="Twoje hasło"> <button type="submit">Zaloguj</button> <button type="submit" class="register-button">Zarejestruj</button> </form> </div> <div class="content"> <div class="center-container"> <div class="left-container"> <a href="{% url 'printing_list' %}" class="menu-link">Kolejka drukowania</a> <a href="{% url 'printer_list' %}" class="menu-link"><b>Moje drukarki</b></a> <a href="{% url 'add_printer' %}" class="menu-link">↳ dodaj drukarkę</a> <a href=" " class="menu-link">↳ edytuj drukarkę</a> <a href=" " class="menu-link">↳ szczegóły drukarki</a> <a href="{% url 'project' %}" class="menu-link">Moje projekty</a> <a href="{% url 'filament' %}" class="menu-link">Filamenty</a> <a href="{% url 'parts' %}" class="menu-link">Części</a> </div> <div class="right-container"> <table class="printer-table"> <thead> <tr> <th>Fotografia</th> <th>Opis</th> <th>Akcje</th> </tr> </thead> <tbody> {% for printer in printers %} <tr> <td><img src="{{ printer.image.url }}" alt="{{ printer.name }}" width="150" height="150"></td> <td> <h3>{{ printer.name }}</h3> <p>Liczba głowic: {{ printer.head }}</p> <p>Maksymalna temperatura: {{ printer.max_temperature }}</p> <p>Maks. prędkość druku: {{ printer.max_speed }}</p> </td> <td> <div> <button type="submit"> <a href="{% url 'edit_printer' printer.id %}" class="edit-button">Edytuj</a> </div> <br> <div> <form method="post" action="{% url 'delete_printer' printer.id %}"> {% csrf_token %} <button type="submit" class="delete-button">Usuń</button> </form> </div> <br> <div> <button type="submit"> <a href="{% url 'printer_detail' printer.id %}" >Szczegóły</a> </div> </td> </tr> {% endfor %} </tbody> </table> <tr> <td colspan="3">&nbsp;</td> </tr> <button type="button" onclick="window.location.href='{% url 'add_printer' %}';" class="submit-addFilament-button">Dodaj drukarkę</button> </div> </div> </div> <footer class="bottom-bar"> --- 3d PRINT HUB --- <p></p> </footer> </div> </body> </html>
####################################################################### # Test for copying block of size 4; ####################################################################### .pos 0 main: irmovq Stack, %rsp # Set up stack pointer # Set up arguments for copy function and then invoke it irmovq $4, %rdx # src and dst have 4 elements irmovq dest, %rsi # dst array irmovq src, %rdi # src array call ncopy halt # should halt with num nonzeros in %rax StartFun: #/* $begin ncopy-ys */ ################################################################## # ncopy.ys - Copy a src block of len words to dst. # Return the number of positive words (>0) contained in src. # # Include your name and ID here. # Name: Wang Shao ID: 520021911427 # Describe how and why you modified the baseline code. # 1. Use "10 x 1" Loop Unrolling for data block of which size is len # 2. Use "2 x 1" Loop Unrolling for data block of which size is len % 10 # (Process data which are not dealt with in 1) # 3. Deal with the last instruction (if len is odd) ################################################################## # Do not modify this portion # Function prologue. # %rdi = src, %rsi = dst, %rdx = len ncopy: ################################################################## # You can modify this portion iaddq $-9, %rdx #limit = len - k + 1 jle Small BigLoop: mrmovq (%rdi), %r8 mrmovq 8(%rdi), %r9 mrmovq 16(%rdi), %r10 mrmovq 24(%rdi), %r11 mrmovq 32(%rdi), %r12 mrmovq 40(%rdi), %r13 mrmovq 48(%rdi), %r14 mrmovq 56(%rdi), %rcx mrmovq 64(%rdi), %rbx mrmovq 72(%rdi), %rbp target0: andq %r8, %r8 #val <= 0 ? jle target1 iaddq $1, %rax target1: andq %r9, %r9 #val <= 0 ? jle target2 iaddq $1, %rax target2: andq %r10, %r10 #val <= 0 ? jle target3 iaddq $1, %rax target3: andq %r11, %r11 #val <= 0 ? jle target4 iaddq $1, %rax target4: andq %r12, %r12 #val <= 0 ? jle target5 iaddq $1, %rax target5: andq %r13, %r13 #val <= 0 ? jle target6 iaddq $1, %rax target6: andq %r14, %r14 #val <= 0 ? jle target7 iaddq $1, %rax target7: andq %rcx, %rcx #val <= 0 ? jle target8 iaddq $1, %rax target8: andq %rbx, %rbx #val <= 0 ? jle target9 iaddq $1, %rax target9: andq %rbp, %rbp #val <= 0 ? jle BigNpos iaddq $1, %rax BigNpos: rmmovq %r8, (%rsi) rmmovq %r9, 8(%rsi) rmmovq %r10, 16(%rsi) rmmovq %r11, 24(%rsi) rmmovq %r12, 32(%rsi) rmmovq %r13, 40(%rsi) rmmovq %r14, 48(%rsi) rmmovq %rcx, 56(%rsi) rmmovq %rbx, 64(%rsi) rmmovq %rbp, 72(%rsi) iaddq $80, %rdi #update src iaddq $80, %rsi #update dst iaddq $-10, %rdx #limit -= k jg BigLoop Small: iaddq $8, %rdx # len = limit + k1 - 1 limit = len - k2 + 1 jle Tiny SmallLoop: mrmovq (%rdi), %r8 mrmovq 8(%rdi), %r9 next0: andq %r8, %r8 jle next1 iaddq $1, %rax next1: andq %r9, %r9 jle SmallNpos iaddq $1, %rax SmallNpos: rmmovq %r8, (%rsi) rmmovq %r9, 8(%rsi) iaddq $16, %rdi iaddq $16, %rsi iaddq $-2, %rdx # update limit jg SmallLoop Tiny: iaddq $1, %rdx # len = limit + k - 1 mrmovq (%rdi), %r8 jle Done rmmovq %r8, (%rsi) andq %r8, %r8 jle Done iaddq $1, %rax ################################################################## # Do not modify the following section of code # Function epilogue. Done: ret ################################################################## # Keep the following label at the end of your function End: #/* $end ncopy-ys */ EndFun: ############################### # Source and destination blocks ############################### .align 8 src: .quad 1 .quad -2 .quad -3 .quad 4 .quad 0xbcdefa # This shouldn't get moved .align 16 Predest: .quad 0xbcdefa dest: .quad 0xcdefab .quad 0xcdefab .quad 0xcdefab .quad 0xcdefab Postdest: .quad 0xdefabc .align 8 # Run time stack .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 .quad 0 Stack:
# # 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. # [START Twitter_data_pipeline] # [START import_modules] from datetime import datetime, timedelta from textwrap import dedent from airflow.models import DAG from airflow.utils.dates import days_ago from airflow.decorators import task from airflow.utils.task_group import TaskGroup from airflow.operators.python import PythonOperator # [END import_modules] # [START defining_args] default_args = { 'owner': 'Cristiano Silva', 'start_date': days_ago(0), 'email': ['[email protected]'], 'email_on_failure': True, 'email_on_retry': True, 'retries': 1, 'retry_delay': timedelta(minutes=5), } # [END defining_args] # [START instantiate_DAG] with DAG( 'twitter_data_pipeline', schedule_interval=timedelta(minutes=5), default_args = default_args ) as dag: # [END instantiate_DAG] # [START documentation] dag.doc_md = __doc__ # [END documentation] # [START extract] def extract(**kwargs): import tweepy ti = kwargs['ti'] # Keys for twitter API consumer_key = 'xxx' consumer_secret = 'xxx' access_token = 'xxx' access_token_secret = 'xxx' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # instantiating the API api = tweepy.API(auth) BRAZIL_WOE_ID = 23424768 brazil_trends = api.get_place_trends(id=BRAZIL_WOE_ID) ti.xcom_push('data_tts_brazil', brazil_trends) # [END extract] # [START transform] def transform(**kwargs): ti = kwargs['ti'] trends_list = [] data = ti.xcom_pull(task_ids='extract', key='data_tts_brazil') for value in data: for trend in value['trends']: trends_list.append(trend['name']) trends_list.insert(0, datetime.now().strftime('%d/%m/%Y %H:%M')) ti.xcom_push('trends', trends_list[0:11]) # [END transform] # [START publish_data] def kafka_publish(**kwargs): ti = kwargs['ti'] from kafka import KafkaProducer producer = KafkaProducer(bootstrap_servers='localhost:9090', #,value_serializer=lambda x: dumps(x).encode('utf-8') max_block_ms=60000, api_version=(0, 10, 2) ) data = {'twitter_trends': ti.xcom_pull(task_ids='transform', key='trends')} try: print("aqui") producer.send('tts_pipeline', value=ti.xcom_pull(task_ids='transform', key='trends')) except: print("Erro ao tentar enviar a mensagem") # [END publish_data] # [START main_flow] extract_task = PythonOperator(task_id='extract', python_callable=extract) extract_task.doc_md = dedent( """\ #### Extract task A simple Extract task to get data ready for the rest of the data pipeline. In this case, getting data is simulated by reading from a hardcoded JSON string. This data is then put into xcom, so that it can be processed by the next task. """ ) transform_task = PythonOperator(task_id='transform', python_callable=transform) transform_task.doc_md = dedent( """\ #### Transform task A simple Transform task which takes in the collection of order data from xcom and computes the total order value. This computed value is then put into xcom, so that it can be processed by the next task. """ ) publish_task = PythonOperator(task_id='publish', python_callable=kafka_publish) publish_task.doc_md = dedent( """\ #### Load task A simple Load task which takes in the result of the Transform task, by reading it from xcom and instead of saving it to end user review, just prints it out. """ ) extract_task >> transform_task >> publish_task # [END main_flow] # [END Twitter_data_pipeline]
public class SegmentTree{ private class TreeNode{ int data; int startInterval; int endInterval; TreeNode left; TreeNode right; TreeNode(int start,int end){ this.startInterval = start; this.endInterval = end; } } private TreeNode root; public SegmentTree(int[] arr){ this.root = createSegment(arr,0,arr.length-1); } private TreeNode createSegment(int[] arr,int s,int e){ if(s == e){ TreeNode leaf = new TreeNode(s,e); leaf.data = arr[s]; return leaf; } TreeNode node = new TreeNode(s,e); int m = s + (e-s)/2; node.left = createSegment(arr,s,m); node.right = createSegment(arr,m+1,e); node.data = node.left.data + node.right.data; return node; } //find the perticular range sum public int findQuery(int s,int e){ return findQuery(root,s,e); } private int findQuery(TreeNode node,int s,int e){ if(node.startInterval >= s && node.endInterval <= e){ return node.data; } if(node.startInterval > e || node.endInterval < s){ return 0; } return findQuery(node.left,s,e) + findQuery(node.right,s,e); } //update query function public void update(int index,int val){ update(root,index,val); } private void update (TreeNode node,int index,int val){ if(node.startInterval == index && node.endInterval == index){ node.data = val; return; } if(node.startInterval > index || node.endInterval < index){ return; } update(node.left,index,val); update(node.right,index,val); node.data = node.left.data + node.right.data; } //Display function public void display(){ display(this.root,0); } private void display(TreeNode node,int index){ if(node == null){ return; } display(node.right,index+1); if(index > 0){ for(int i = 0;i<index-1;i++){ System.out.print("|\t"); } System.out.println("|---->("+node.startInterval+" ,"+node.endInterval+")["+node.data+"]"); }else{ System.out.println("("+node.startInterval+" ,"+node.endInterval+")["+node.data+"]"); } display(node.left,index+1); } }
import { z } from 'zod'; const create = z.object({ body: z.object({ title: z.string({ required_error: 'Book title is required.' }), author: z.string({ required_error: 'Author name is required.' }), price: z.number({ required_error: 'Book price is required.' }), genre: z.string({ required_error: 'Book genre is required.' }), publicationDate: z.string({ required_error: 'Book publication date is required.', }), categoryId: z.string({ required_error: "Book's categoryId is required." }), }), }); const update = z.object({ body: z.object({ title: z.string().optional(), author: z.string().optional(), price: z.number().optional(), genre: z.string().optional(), publicationDate: z.string().optional(), categoryId: z.string().optional(), }), }); export const BookValidation = { create, update, };
import time import curses import numpy as np import warnings from environment import FrozenLakeEnvCustom from agent import QLearningAgent warnings.filterwarnings("ignore") def train_agent( n_training_episodes, min_epsilon, max_epsilon, decay_rate, env, max_steps, agent, learning_rate, gamma, use_frame_delay, ): for episode in range(n_training_episodes + 1): # Reduce epsilon (because we need less and less exploration) epsilon = min_epsilon + (max_epsilon - min_epsilon) * np.exp( -decay_rate * episode ) state, info = env.reset() done = False for step in range(max_steps): # Choose the action At using epsilon greedy policy action = agent.epsilon_greedy_policy(state, epsilon) # Take action At and observe Rt+1 and St+1 # Take the action (a) and observe the outcome state(s') and reward (r) new_state, reward, done, truncated, info = env.step(action) agent.update_q_table(state, action, reward, gamma, learning_rate, new_state) env.render( title=f"Training: {episode}/{n_training_episodes}", q_table=agent.q_table, ) if use_frame_delay: time.sleep(0.01) if done: break state = new_state return agent def evaluate_agent(env, max_steps, n_eval_episodes, agent, seed, use_frame_delay): successful_episodes = [] episodes_slips = [] for episode in range(n_eval_episodes + 1): if seed: state, info = env.reset(seed=seed[episode]) else: state, info = env.reset() done = False total_rewards_ep = 0 slips = [] for step in range(max_steps): # Take the action (index) that have the maximum expected future reward given that state action = agent.greedy_policy(state) expected_new_state = env.get_expected_new_state_for_action(action) new_state, reward, done, truncated, info = env.step(action) total_rewards_ep += reward if expected_new_state != new_state: slips.append((step, action, expected_new_state, new_state)) if reward != 0: successful_episodes.append(episode) env.render( title=f"Evaluating: {episode}/{n_eval_episodes} | Slips: {len(slips)}", q_table=agent.q_table, ) episodes_slips.append(len(slips)) if use_frame_delay: time.sleep(0.01) if done: break state = new_state mean_slips = np.mean(episodes_slips) return successful_episodes, mean_slips def main(screen): # Training parameters n_training_episodes = 2000 # Total training episodes learning_rate = 0.1 # Learning rate # Evaluation parameters n_eval_episodes = 100 # Total number of test episodes # Environment parameters max_steps = 99 # Max steps per episode gamma = 0.99 # Discounting rate eval_seed = [] # The evaluation seed of the environment # Exploration parameters max_epsilon = 1.0 # Exploration probability at start min_epsilon = 0.05 # Minimum exploration probability decay_rate = 0.0005 # Exponential decay rate for exploration prob use_frame_delay = False env = FrozenLakeEnvCustom(map_name="4x4", is_slippery=True, render_mode="curses") agent = QLearningAgent(env) agent = train_agent( n_training_episodes, min_epsilon, max_epsilon, decay_rate, env, max_steps, agent, learning_rate, gamma, use_frame_delay, ) successful_episodes, mean_slips = evaluate_agent( env, max_steps, n_eval_episodes, agent, eval_seed, use_frame_delay ) env_curses_screen = env.curses_screen env_curses_screen.addstr( 5, 2, f"Successful episodes: {len(successful_episodes)}/{n_eval_episodes} | Avg slips: {mean_slips:.2f}\n\n", ) env_curses_screen.noutrefresh() curses.doupdate() time.sleep(10) if __name__ == "__main__": # Reset the terminal state after using curses # Call main("") instead if you want to leave the final state of the environment # on the terminal curses.wrapper(main)
<!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <title>instanciation time</title> <style> .grid { display: grid; grid-template-columns: repeat(50, 24px); grid-template-rows: repeat(50, 24px); gap: 4px; } .cell { width: 20px; height: 20px; border: 1px solid #000; display: flex; justify-content: center; align-items: center; overflow: hidden; } .cell img { width: 100%; height: 100%; object-fit: cover; } </style> </head> <body> <div class="grid" id="grid"></div> <script> const grid = document.getElementById('grid'); let allElementsRendered = false; let startTime; function generateGrid() { startTime = performance.now(); grid.innerHTML = ''; for (let i = 0; i < 50 * 50; i++) { performance.mark("el") const cell = document.createElement('div'); cell.classList.add('cell'); const img = document.createElement('img'); img.src = `https://cdn.pixabay.com/photo/2019/09/28/07/40/emoticon-4510161_1280.png`; cell.appendChild(img); grid.appendChild(cell); } checkRenderComplete(); } function checkRenderComplete() { const elements = document.querySelectorAll('.cell img'); const renderedElements = Array.from(elements).filter(img => img.complete); allElementsRendered = renderedElements.length === elements.length; if (!allElementsRendered) { requestAnimationFrame(checkRenderComplete); } else { performance.mark("END") const endTime = performance.now(); const totalTime = endTime - startTime; console.log(`Temps total d'instanciation : ${totalTime} ms`); } } function handleKeyPress(event) { if (event.key === 'ArrowRight') { generateGrid(); } } generateGrid(); window.addEventListener('keydown', handleKeyPress); </script> </body> </html>
import 'package:biteline/pages/cart.dart'; import 'package:biteline/pages/favourites.dart'; import 'package:biteline/pages/home.dart'; import 'package:biteline/pages/orders.dart'; import 'package:biteline/pages/profile.dart'; import 'package:biteline/pages/search.dart'; import 'package:flutter/material.dart'; class PageManager extends StatefulWidget { const PageManager({super.key}); @override State<PageManager> createState() => _PageManagerState(); } class _PageManagerState extends State<PageManager> { int _selectedIndex = 0; final PageController _pageController = PageController(); void _changePage(int index) { setState(() { _selectedIndex = index; _pageController.animateToPage( index, duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, ); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(60), child: Padding( padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 16.0), child: AppBar( leading: Hero( tag: 'search_button', child: IconButton( icon: const Icon(Icons.search_rounded), onPressed: () { Navigator.push( context, PageRouteBuilder( transitionDuration: const Duration(milliseconds: 300), pageBuilder: (_, __, ___) => const SearchPage(), transitionsBuilder: (_, animation, __, child) { return SlideTransition( position: Tween(begin: const Offset(-1.0, 0.0), end: Offset.zero).animate(animation), child: child, ); }, ), ); }, ), ), title: Text( 'Bite Line', style: Theme.of(context).textTheme.headlineSmall, ), centerTitle: true, actions: [ IconButton( icon: const Icon(Icons.shopping_cart_rounded), onPressed: () { Navigator.push( context, PageRouteBuilder( transitionDuration: const Duration(milliseconds: 300), pageBuilder: (_, __, ___) => const CartPage(), transitionsBuilder: (_, animation, __, child) { return SlideTransition( position: Tween(begin: const Offset(0.0, 1.0), end: Offset.zero).animate(animation), child: child, ); }, ), ); }, ), ], ), ), ), body: PageView( controller: _pageController, // physics: const NeverScrollableScrollPhysics(), onPageChanged: (index) { setState(() { _selectedIndex = index; }); }, children: const [ HomePage(), FavouritesPage(), OrdersPage(), ProfilePage(), ], ), bottomNavigationBar: BottomNavigationBar( currentIndex: _selectedIndex, onTap: _changePage, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home_rounded), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.favorite_rounded), label: 'Favorites', ), BottomNavigationBarItem( icon: Icon(Icons.history_rounded), label: 'Orders', ), BottomNavigationBarItem( icon: Icon(Icons.person_rounded), label: 'Profile', ), ], ), ); } }
import React, { useState, useEffect } from 'react' import axios from 'axios' import { Link } from 'react-router-dom' const UserList = () => { const [user, setUser] = useState([]); useEffect(() => { getUser(); }, []) //dapetnya dari sini melalui setproduct const getUser = async () => { const response = await axios.get('http://localhost:8080/user') setUser(response.data) }; const deleteUser = async (userId) => { await axios.delete(`http://localhost:8080/user/${userId}`) getUser(); } return ( <div className=''> <h1 className=' title'>Users</h1> <h2 className=' subtitle'> List of Users</h2> <Link to="/users/add" className=' button is-primary mb-2'>Add New</Link> <table className='table is-striped is-fullwidth'> <thead> <tr> <th>No</th> <th>Name</th> <th>Email</th> <th>Role</th> <th>Actions</th> </tr> </thead> <tbody> {user.map((user, index) => ( <tr key={user.uuid}> <td>{index + 1}</td> <td>{user.name}</td> <td>{user.email}</td> <td>{user.role}</td> <td> <Link to={`/users/edit/${user.uuid}`} className=' button is-small is-info'>Edit</Link> <button onClick={() => deleteUser(user.uuid)} className=' button is-small is-danger'>Delete</button> </td> </tr> ))} </tbody> </table> </div> ) } export default UserList
package entity_test import ( "testing" "github.com/reinaldosaraiva/nftables-api/internal/entity" "github.com/stretchr/testify/assert" ) func TestNewProject(t *testing.T) { tests := []struct { name string tenantID uint64 err error }{ {"My project", 1, nil}, {"", 1, entity.ErrNameRequired}, {"My project", 0, entity.ErrTenantRequired}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { project, err := entity.NewProject(tt.name, tt.tenantID) if tt.err == nil { assert.Nil(t, err) assert.NotNil(t, project) } else { assert.Equal(t, tt.err, err) } }) } } func TestNewProjectWithChain(t *testing.T) { chain, _ := entity.NewChain("INPUT", "filter","accept",1,1,1) project, _ := entity.NewProject("My project", 1) project.AddChain(chain) assert.Equal(t, len(project.Chains), 1) }
from django.db import models from django.contrib.auth.models import User from perfil.models import Perfil, Meninas # from PIL import Image from django.utils import timezone from datetime import datetime, date from django.forms import ValidationError class Videos(models.Model): menina = models.ForeignKey(Meninas, on_delete=models.CASCADE, verbose_name="Menina") link = models.CharField(default='', max_length=255, verbose_name="Link") nome = models.SlugField(unique=True, default='', max_length=255, verbose_name="Nome") descricao = models.TextField(default='', max_length=2000, verbose_name="Descricao") premium = models.BooleanField(default=False, verbose_name="Videos Premium") preco_premium = models.FloatField(default=0, verbose_name="Preço Premium") foto = models.ImageField(blank=True, null=True, upload_to='foto_videos/%Y/%m/%d', verbose_name="Foto") class Meta: verbose_name = 'Video' verbose_name_plural = 'Videos' def __str__(self): return f'{self.nome}' class Audios(models.Model): menina = models.ForeignKey(Meninas, on_delete=models.CASCADE, verbose_name="Menina") nome = models.CharField(unique=True, default='', max_length=255, verbose_name="Nome") arquivo = models.FileField(upload_to='audios/%Y/%m/%d', verbose_name="Audio") class Meta: verbose_name = 'Audio' verbose_name_plural = 'Audios' def __str__(self): return f'{self.nome}' class Planos(models.Model): tres_meses = models.FloatField(default=0, verbose_name="Três meses") seis_meses = models.FloatField(default=0, verbose_name="Seis meses") um_mes = models.FloatField(default=0, verbose_name="Um mes") class Meta: verbose_name = 'Plano' verbose_name_plural = 'Planos' def __str__(self): return f'{self.tres_meses} -> {self.seis_meses} -> {self.um_mes}' class Comentarios(models.Model): perfil = models.ForeignKey(Perfil, on_delete=models.CASCADE, verbose_name="Perfil") comentario = models.CharField(default='', max_length=500, verbose_name="Comentario") video = models.ForeignKey(Videos, on_delete=models.CASCADE, verbose_name="Video") visibilidade = models.BooleanField(default=False, verbose_name="Visibilidade") class Meta: verbose_name = 'Comentario' verbose_name_plural = 'Comentarios' def __str__(self): return f'{self.perfil.nome}' class Pedido(models.Model): comprador = models.ForeignKey(Perfil, on_delete=models.SET_NULL, verbose_name="Comprador", blank=True, null=True) tipo_pagamento = models.CharField(default='', max_length=255, verbose_name="Tipo de pagamento", blank=True, null=True) preco_pedido = models.FloatField(default=0, verbose_name="Preço do pedido") data_pedido = models.DateTimeField(default=timezone.now, verbose_name="Data do pedido") data_vencimento = models.DateTimeField(verbose_name="Data do vencimento", blank=True, null=True) descricao_pagamento = models.CharField(default='', max_length=255, verbose_name="Descrição do pagamento", blank=True, null=True) plano = models.CharField( default='tres_meses', max_length=20, choices=( ('tres_meses', 'tres_meses'), ('seis_meses', 'seis_meses'), ('um_mes', 'um_mes'), ), verbose_name="Plano Escolhido" ) status_pedido = models.CharField( default='pending', max_length=20, choices=( ('approved', 'approved'), ('rejected', 'rejected'), ('pending', 'pending'), ), verbose_name="Status Pedido" ) IdTransaction = models.IntegerField(default=0, verbose_name="IdTransaction") parcelamentos = models.IntegerField(default=0, verbose_name="Parcelamentos") plano_ativo = models.BooleanField(default=False, verbose_name="Plano Ativo") recebeu_email_aprovado = models.BooleanField(default=False, verbose_name="Código Interno AP") recebeu_email_reprovado = models.BooleanField(default=False, verbose_name="Código Interno REP") recebeu_email_pendente = models.BooleanField(default=False, verbose_name="Código Interno PEN") class Meta: verbose_name = 'Pedido' verbose_name_plural = 'Pedidos' def __str__(self): return f'{self.comprador} -> {self.id}' class PedidoVideoPremium(models.Model): comprador = models.ForeignKey(Perfil, on_delete=models.SET_NULL, verbose_name="Comprador", blank=True, null=True) tipo_pagamento = models.CharField(default='', max_length=255, verbose_name="Tipo de pagamento", blank=True, null=True) preco_pedido = models.FloatField(default=0, verbose_name="Preço do pedido") data_pedido = models.DateTimeField(default=timezone.now, verbose_name="Data do pedido") descricao_pagamento = models.CharField(default='', max_length=255, verbose_name="Descrição do pagamento", blank=True, null=True) video = models.ForeignKey(Videos, on_delete=models.SET_NULL, verbose_name="Video Premium", blank=True, null=True) status_pedido = models.CharField( default='pending', max_length=20, choices=( ('approved', 'approved'), ('rejected', 'rejected'), ('pending', 'pending'), ), verbose_name="Status Pedido" ) IdTransaction = models.IntegerField(default=0, verbose_name="IdTransaction") parcelamentos = models.IntegerField(default=0, verbose_name="Parcelamentos") recebeu_email_aprovado = models.BooleanField(default=False, verbose_name="Código Interno AP") recebeu_email_reprovado = models.BooleanField(default=False, verbose_name="Código Interno REP") recebeu_email_pendente = models.BooleanField(default=False, verbose_name="Código Interno PEN") class Meta: verbose_name = 'Pedido Video Premium' verbose_name_plural = 'Pedidos Videos Premium' def __str__(self): return f'{self.comprador} -> {self.id}'
#include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "hardware/pio.h" #include "hardware/adc.h" #include <stdio.h> #include <pinmap.h> #include "reporting_task.h" #include <stdlib.h> #include <stdint.h> #include <limits.h> static QueueHandle_t windQueue; unsigned int wind_sm; extern PIO pio; #define WIND_PRIORITY 30 void wind_irq_func(void) { BaseType_t higherPriorityTaskWoken = pdFALSE; uint32_t c; // empty the fifo and keep the last value while (!pio_sm_is_rx_fifo_empty(pio, wind_sm)) { c = pio->rxf[wind_sm]; } xQueueSendFromISR(windQueue, &c, &higherPriorityTaskWoken); portYIELD_FROM_ISR(higherPriorityTaskWoken); } struct dir_counts_s { uint32_t counts; int degrees; }; // pointed the arrow in each direction and recorded the counts const struct dir_counts_s direction_map[] = { {4400, 0}, {1400, 45}, {420, 90}, {600, 135}, {840, 180}, {2400, 225}, {12600, 270}, {7900, 315}}; uint32_t convertPin(int pin) { assert(pin >= 26 && pin <= 29); int adc_channel = pin - 26; adc_init(); adc_gpio_init(pin); adc_select_input(adc_channel); adc_fifo_setup(false, false, 0, false, false); // discard at least 3 samples until fifo is empty int ignore_count = 3; for (int x = 0; x < ignore_count; x++) { (void)adc_read(); } uint32_t counts = 0; for (int x = 0; x < 256; x++) { uint16_t r = adc_read(); counts += r; } counts /= 16; return counts; } int measureDirection() { uint32_t counts = convertPin(WIND_DIR_PIN); int closest_index = 0; // assume the first index is the closest // find closest counts in the map for (int map_index = 0; map_index < sizeof(direction_map) / sizeof(*direction_map); map_index++) { int difference = abs(counts - direction_map[map_index].counts); int closest_difference = abs(counts - direction_map[closest_index].counts); if (difference < closest_difference) { closest_index = map_index; } } return direction_map[closest_index].degrees; } struct wind_data { int direction; float speed; }; void measureBattery() { // go ahead and measure the battery voltage here so I don't have to share the ADC with another task. float volts = 0; uint32_t counts = convertPin(VSYS_PIN); counts /= 16; // undo the oversample from the conversion volts = ((float)counts * 3.0 * 3.3) / 4096.0; if (volts > 5.0) volts = 5.0; // one of the test boards has a bad ADC that always reads full scale. reportBatteryVoltage(volts); } // We need to keep track of the following variables: // Wind speed/dir each update (no storage) // Wind gust/dir over the day (no storage) // Wind speed/dir, avg over 2 minutes (store 1 per second) // Wind gust/dir over last 10 minutes (store 1 per minute) // Rain over the past hour (store 1 per minute) // Total rain over date (store one per day) #define WIND_DATA_UPDATE (1000U) static void wind_task(void *parameter) { bool transmitRawData = false; int seconds_2m = 0; int minutes_10m = 0; unsigned int lastWindCheck = 0; unsigned int count = 0; unsigned int lastCounts = 0; unsigned int lastUpdate = 0; unsigned int lastRawTransmission = 0; int logIndex = 0; int seconds = 0; int minutes = 0; struct wind_data windavg_2m[120] = {{0.0, 0}}; // two minutes of data for every second struct wind_data windgust_10m[10] = {{0.0, 0}}; // last 10 minutes of wind gusts struct wind_data windgust; // daily gust data struct wind_data windavg2m; struct wind_data gust_10m; for (;;) { if (pdTRUE == xQueueReceive(windQueue, &count, pdMS_TO_TICKS(60000))) // wait up to 1min for counts data { unsigned int now = xTaskGetTickCount() / portTICK_RATE_MS; // get the up-time in ms int currentDirection = measureDirection(); // collect the current wind direction if (now - lastUpdate > WIND_DATA_UPDATE) { lastUpdate += WIND_DATA_UPDATE; if (++seconds_2m > 119) seconds_2m = 0; float deltaTime = (float)(now - lastWindCheck); lastWindCheck = now; deltaTime /= 1000.0; /* care care of the count rollover since the PIO code is a monotonic count */ uint32_t deltaCounts = count - lastCounts; if (deltaCounts > lastCounts) deltaCounts += UINT_MAX; /* scale into actual MPH wind speed */ float currentSpeed = 1.492 * ((float)deltaCounts) / deltaTime; lastCounts = count; windavg_2m[seconds_2m].speed = currentSpeed; windavg_2m[seconds_2m].direction = currentDirection; if (currentSpeed > windgust_10m[minutes_10m].speed) { windgust_10m[minutes_10m].speed = currentSpeed; windgust_10m[minutes_10m].direction = currentDirection; } if (currentSpeed > windgust.speed) { windgust.speed = currentSpeed; windgust.direction = currentDirection; } if (++seconds > 59) { seconds = 0; transmitRawData = true; if (++minutes > 59) { minutes = 0; } if (++minutes_10m > 9) minutes_10m = 0; windgust_10m[minutes_10m].speed = 0; // Zero out this minute's gust } // computing the average speed & direction { float avgspeed_2m = 0; int sum = windavg_2m[0].direction; int D = sum; for (int x = 0; x < 120; x++) { int delta = windavg_2m[x].direction - D; if (delta < -180) { D += delta + 360; } else if (delta > 180) { D += delta - 360; } else { D += delta; } sum += D; avgspeed_2m += windavg_2m[x].speed; } windavg2m.speed = avgspeed_2m / 120.0; windavg2m.direction = sum / 120; if (windavg2m.direction >= 360) windavg2m.direction -= 360; if (windavg2m.direction < 0) windavg2m.direction += 360; } // calculate the 10 minute gust speed & direction { gust_10m.direction = 0; gust_10m.speed = 0.0; for (int i = 0; i < 10; i++) { if (windgust_10m[i].speed > gust_10m.speed) { gust_10m.speed = windgust_10m[i].speed; gust_10m.direction = windgust_10m[i].direction; } } } if (transmitRawData) // raw data every minute { transmitRawData = false; reportWINDData(count, currentDirection); // send the data reportWINDScaledData(windavg2m.speed, windavg2m.direction, gust_10m.speed, gust_10m.direction); } } } else { puts("No wind data in 1 minute"); } measureBattery(); } } void init_wind() { windQueue = xQueueCreate(10, sizeof(int)); assert(windQueue); xTaskCreate(wind_task, "Wind", 1000, NULL, WIND_PRIORITY, NULL); }
package org.example.stepDefs; import com.github.javafaker.Faker; import io.cucumber.java.en.And; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.example.Pages.P01_HomePage; import org.example.Pages.P02_RegisterPage; import org.openqa.selenium.support.Color; import org.openqa.selenium.support.ui.Select; import org.testng.asserts.SoftAssert; import java.io.IOException; public class D01_SignUP { Configuration con = new Configuration(); P02_RegisterPage RP = new P02_RegisterPage(); Faker fake = new Faker(); SoftAssert ass = new SoftAssert(); @Given("guest user opens register page") public void openRegisterPage(){ RP.regButclick(); } @When("user selects the gender {string}") public void userSelectsTheGender(String gender) { RP.genderClick(gender); } @And("enters firstrname & lastname") public void entersUsername() { RP.Fname(fake.name().firstName()); RP.Lname(fake.name().lastName()); } @And("chooses DOB") public void choosesDOB() { int random_day = (int)Math.floor(Math.random() * (30 - 1 + 1) + 1); int random_month = (int)Math.floor(Math.random() * (12 - 1 + 1) + 1); int random_year = (int)Math.floor(Math.random() * (20 - 1 + 1) + 1); RP.selectDay(random_day); RP.selectmon(random_month); RP.selectyear(random_year); } @And("enter a valid Email") public void enterValidEmail() throws IOException { String Email= fake.internet().emailAddress(); con.set("Email",Email); RP.Email(Email); } @And("enters pass & confirmation pass") public void entersPassConfirmationPass() throws IOException { String passs = fake.internet().password(); con.set("Password",passs); RP.pass(passs); RP.conpass(passs); } @And("press on register") public void pressOnRegister() { RP.register(); } @Then("new account is created successfully") public void newAccountIsCreatedSuccessfully() { ass.assertEquals(RP.succmsg(),"Your registration completed"); ass.assertEquals(RP.colormsg(),"rgba(76, 177, 124, 1)"); ass.assertAll(); } @And("enter a invalid Email {string}") public void enterAInvalidEmail(String arg0) { RP.Email(arg0); } @Then("error msg is displayed") public void errorMsgIsDisplayed() { ass.assertEquals(RP.error(),"Wrong email"); String hex = Color.fromString(RP.errorcolor()).asHex(); ass.assertEquals(hex,"#e4434b"); ass.assertAll(); } }
# East Dorm Treasury Exceptions # # Copyright (C) 2008-2009 James Brown <[email protected]> # # This file is part of East Dorm Treasury. # # East Dorm Treasury 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. # # East Dorm Treasury 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 East Dorm Treasury. If not, see <http://www.gnu.org/licenses/>. class CheckNotFoundError < RuntimeError def initialize(check_no) @check_no = check_no end def to_s "Check ##{@check_no} not found!" end end class DuplicateCheckError < RuntimeError def initialize(check_no) @check_no = check_no end def to_s "Check ##{@check_no} has duplicates!" end end class ExpenditureNotFoundError < RuntimeError end class DuplicateExpenditureError < RuntimeError end
import React, { useState, useRef } from 'react'; import { NavLink } from 'react-router-dom'; import { useSelector } from 'react-redux'; import { categories } from '../../state/selectors'; import Arrow from '../Icon/Icons/HamburgerMenu'; import { Container, HamburgerWrapper, NavItems, NavItem, LogoBox, Brand, BrandItem, } from './styles'; import { colors } from '../../styles/colors'; import logo from '../../assets/images/teltonika_logo.png'; const MobileHeader = () => { const [openDrawer, toggleDrawer] = useState(false); const drawerRef = useRef(null); const Categories = useSelector(categories); return ( <Container> <LogoBox> <img src={logo} alt="logo" /> </LogoBox> <HamburgerWrapper onClick={() => toggleDrawer(!openDrawer)}> <Arrow width="32px" color={colors.brandDark} height="32px" /> </HamburgerWrapper> <NavItems ref={drawerRef} isOpen={openDrawer}> <NavItem> <NavLink to={'/'}>Home</NavLink> </NavItem> <NavItem> <NavLink to={'/create-user'}>New User</NavLink> </NavItem> <NavItem> <NavLink to={'/create-category'}>New Category</NavLink> </NavItem> <Brand>Samsung</Brand> <BrandItem> {Categories.filter( (cat) => cat.brandsCategory === 'Samsung' ).map((category, index) => ( <NavLink to={`/samsung/${category.subCategory}`} key={index} > {category.subCategory} </NavLink> ))} </BrandItem> <Brand>Apple</Brand> <BrandItem> {Categories.filter( (cat) => cat.brandsCategory === 'Apple' ).map((category, index) => ( <NavLink to={`/apple/${category.subCategory}`} key={index} > {category.subCategory} </NavLink> ))} </BrandItem> </NavItems> </Container> ); }; export default MobileHeader;
// Setters and Getters const obj = { prop: "some prop", get accessProp() { return this.prop.toUpperCase() }, set accessProp(arg: string) { this.prop = arg.toLowerCase() } } console.log(obj) console.log(obj.accessProp) console.log((obj.accessProp = "other value")) console.log(obj) // -- // const cat = { // name: "Shiva", // color: "white" // } Object.defineProperty({ name: "Shiva", color: "white" }, "accessColor", { get() { return this.color }, set(arg: string) { this.color = arg }, enumerable: true, configurable: false }) // Type This shit ??? const getCat = () => Object.defineProperty<{ name: string; color: string; accessColor?: any }>( { name: "Shiva", color: "white" }, "accessColor", { get() { return this.color }, set(arg: string) { this.color = arg }, enumerable: true, configurable: false } ) const cat = getCat() console.log(cat) console.log(cat.accessColor) console.log((cat.accessColor = "other value")) console.log(cat) // Using Class class Cat { name: string color: string constructor({ color, name }: { color: string; name: string }) { this.name = name this.color = color } get accessColor() { return this.color } set accessColor(arg) { this.color = arg } } const otherCat = new Cat({ name: "Shiva", color: "Orange" }) console.log(otherCat) console.log(otherCat.accessColor) console.log((otherCat.accessColor = "other value")) console.log(otherCat)
package main import( "github.com/gin-gonic/gin" "net/http" ) func sayHello(c *gin.Context){ c.JSON(200,gin.H{ "message":"hello golang", }) } func main(){ //创建一个默认的路由引擎 r:=gin.Default() // 指定访问方法对应的出来方法 r.GET("/hello",sayHello) // RESTful 指的是一系列规范 get获取信息,post新建,put更新,delete删除 r.GET("/book",func(c *gin.Context){ c.JSON(http.StatusOK,gin.H{ "method":"GET", }) }) r.POST("/book",func(c *gin.Context){ c.JSON(http.StatusOK,gin.H{ "method":"POST", }) }) r.PUT("/book",func(c *gin.Context){ c.JSON(http.StatusOK,gin.H{ "method":"PUT", }) }) r.DELETE("/book",func(c *gin.Context){ c.JSON(http.StatusOK,gin.H{ "method":"DELETE", }) }) // 启动 r.Run(":9091") }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { Feature1Component } from './feature1/feature1.component'; import { Feature2Component } from './feature2/feature2.component'; import { Feature3Component } from './feature3/feature3.component'; import { UtilizadorComponent } from './utilizador/utilizador.component'; const routes: Routes = [ { path: 'utilizador', component: UtilizadorComponent}, { path: 'feature1', component: Feature1Component}, { path: 'feature2', component: Feature2Component}, { path: 'feature3', component: Feature3Component} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
package main import ( "context" "database/sql" "encoding/json" "errors" _ "github.com/mattn/go-sqlite3" "io" "log" "net/http" "time" ) type ExchangeRate struct { Rate ExchangeRateDetail `json:"USDBRL"` } type ExchangeRateDetail struct { ID int `json:"-"` Code string Codein string Name string High float64 `json:",string"` Low float64 `json:",string"` VarBid float64 `json:",string"` PctChange float64 `json:",string"` Bid float64 `json:",string"` Ask float64 `json:",string"` Timestamp int `json:",string"` CreateDate string `json:"create_date"` } type ExchangeRateResponse struct { Bid float64 } var rowsFound = errors.New("Rows found") func main() { mux := http.NewServeMux() mux.HandleFunc("/cotacao", getExchangeRate) http.ListenAndServe(":8080", mux) } func getExchangeRate(w http.ResponseWriter, r *http.Request) { rate, err := getDollarExchangeRate() if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Println(err) return } var exchangeRate ExchangeRate err = json.Unmarshal(rate, &exchangeRate) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Println(err) return } db, err := sql.Open("sqlite3", "./exchange.db") if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Println(err) return } err = existRateByTimestamp(db, exchangeRate.Rate.Timestamp) log.Println(err) if err != nil && !errors.Is(err, rowsFound) { w.WriteHeader(http.StatusInternalServerError) log.Println(err) return } if !errors.Is(err, rowsFound) { err = saveExchangeRate(db, exchangeRate) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Println(err) return } } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) response := ExchangeRateResponse{Bid: exchangeRate.Rate.Bid} json.NewEncoder(w).Encode(response) } func getDollarExchangeRate() ([]byte, error) { ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", "https://economia.awesomeapi.com.br/json/last/USD-BRL", nil) if err != nil { return nil, err } res, err := http.DefaultClient.Do(req) if err != nil && errors.Is(err, rowsFound) { return nil, err } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return nil, err } return body, nil } func saveExchangeRate(db *sql.DB, rate ExchangeRate) error { ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 10*time.Millisecond) stmt, err := db.PrepareContext(ctx, ` INSERT INTO exchange_rates (code, codein, name, high, low, var_bid, pct_change, bid, ask, timestamp, create_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `) if err != nil { return err } defer cancel() _, err = stmt.Exec( rate.Rate.Code, rate.Rate.Codein, rate.Rate.Name, rate.Rate.High, rate.Rate.Low, rate.Rate.VarBid, rate.Rate.PctChange, rate.Rate.Bid, rate.Rate.Ask, rate.Rate.Timestamp, rate.Rate.CreateDate, ) if err != nil { return err } return nil } func existRateByTimestamp(db *sql.DB, timestamp int) error { stmt, err := db.Prepare("SELECT id FROM exchange_rates WHERE timestamp = ? LIMIT 1") if err != nil { return err } var id int err = stmt.QueryRow(timestamp).Scan(&id) if errors.Is(err, sql.ErrNoRows) { return nil } if err != nil { return err } if id >= 1 { return rowsFound } return nil }
@page "/login" @using CustomerUI.Account @using CustomerUI.Services @inject IAuthService AuthService @inject UserAccountService UserAccountService @inject AuthenticationStateProvider AuthStateProvider @inject NavigationManager Navigation @inject IJSRuntime JSRuntime <div class="login-container"> <div class="text-center"> <img src="/gadgetpoint.png" alt="Logo" /> </div> <h3 class="text-center">Login</h3> <EditForm Model="loginDto" OnValidSubmit="LoginMain"> <DataAnnotationsValidator /> <ValidationSummary /> <div class="form-group"> <label for="email">Email</label> <InputText id="email" class="form-control" @bind-Value="loginDto.Email" /> </div> <div class="form-group"> <label for="password">Password</label> <InputText id="password" type="password" class="form-control" @bind-Value="loginDto.Password" /> </div> <div class="text-center"> <!-- Center the button --> <button type="submit" class="btn btn-primary">Login</button> </div> </EditForm> </div> @code { private LoginDTO loginDto = new LoginDTO(); private async Task LoginMain() { var user = await AuthService.Login(loginDto); var userAccount = UserAccountService.GetByUserName(loginDto.Email); if (user != null) { var customAuthStateProvider = AuthStateProvider as CustomAuthentication; await customAuthStateProvider.UpdateAuthenticationState(new LoginDTO { Email = userAccount.Email, Role = userAccount.Role }); Navigation.NavigateTo("/", true); } else { // Handle login failure if (userAccount == null || userAccount.Password != loginDto.Password) { await JSRuntime.InvokeVoidAsync("alert", "Invalid username or password"); return; } } } } <style> .login-container { margin-top: 20%; max-width: 400px; margin: 0 auto; padding: 20px; background-color: #f8f8f8; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); } .form-group { margin-bottom: 15px; } .center-container { text-align: center; } .center-image { width: 100px; /* Adjust the width as needed */ height: auto; /* To maintain aspect ratio */ margin-bottom: 20px; /* Adjust the spacing between the image and text */ } </style>
class Puzzle: def process(self, text): self.player = [[],[]] curplayer = 0 lines = text.split('\n') for line in lines: if line == 'Player 1:': pass elif line == 'Player 2:': curplayer = 1 elif line.strip() != '': num = int(line) self.player[curplayer].append(num) def play_round(self): p1 = self.player[0].pop(0) p2 = self.player[1].pop(0) if p1 > p2: self.player[0].append(p1) self.player[0].append(p2) return 0 else: self.player[1].append(p2) self.player[1].append(p1) return 1 def _recursive_play(self, p1deck, p2deck, indent=''): seen = [] round = 0 while len(p1deck) > 0 and len(p2deck) > 0: board = (p1deck, p2deck) if board in seen: return (0, p1deck, p2deck) #Recursion, p1 wins else: round += 1 print indent, 'Round:', round print indent, p1deck print indent, p2deck seen.append(board) p1 = p1deck[0] p2 = p2deck[0] if p1+1 <= len(p1deck) and p2+1 <= len(p2deck): #print 'Recurse Again', p1, p2 winner, _, _ = self._recursive_play(p1deck[1:p1+1], p2deck[1:p2+1], indent + '> ') else: if p1 > p2: winner = 0 else: winner = 1 #print indent + 'winner', winner+1 if winner == 0: p1deck = p1deck[1:] + [p1, p2] p2deck = p2deck[1:] else: p1deck = p1deck[1:] p2deck = p2deck[1:] + [p2, p1] if len(p1deck) > 0: return (0, p1deck, p2deck) else: return (1, p1deck, p2deck) def play_recursive_combat(self, p1deck, p2deck): return self._recursive_play(p1deck, p2deck) def score_deck(self, deck): count = len(deck) score = 0 for i in range(count): score += (deck[i] * (count-i)) return score def result1(self): round = 1 while len(self.player[0]) != 0 and len(self.player[1]) != 0: winner = self.play_round() print 'Round', round, 'winner', winner + 1 print 'Finished' print 'Player 1:', self.player[0] print 'Player 2:', self.player[1] if len(self.player[0]) > 0: windeck = self.player[0] else: windeck = self.player[1] print 'Winning Score', self.score_deck(windeck) def result(self): winner, p1deck, p2deck = self.play_recursive_combat(self.player[0], self.player[1]) print 'Win:', winner print p1deck, self.score_deck(p1deck) print p2deck, self.score_deck(p2deck) if __name__ == '__main__': puz = Puzzle() inp = open('input', 'r').read() puz.process(inp) puz.result()
import Twilio from "twilio"; const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; const getTwilioClient = () => { const client = Twilio(accountSid, authToken); return client; }; export const sendTextVerification = async (phoneNumber: string) => { const client = getTwilioClient(); await client.verify.v2 .services(process.env.TWILIO_VERIFY_SERVICE_SID!) .verifications.create({ to: phoneNumber, channel: "sms" }); }; export const verifyCode = async (phoneNumber: string, code: string) => { const client = getTwilioClient(); try { const verification = await client.verify.v2 .services(process.env.TWILIO_VERIFY_SERVICE_SID!) .verificationChecks.create({ to: phoneNumber, code: code }); return verification.valid; } catch (error) { return false; } }; export const sendTwilioVerificationToken = async (phone: string) => { if (process.env.NODE_ENV === "development") { return { status: "pending", to: phone, }; } const client = getTwilioClient(); const verificationInstance = await client.verify.v2 .services(process.env.TWILIO_VERIFY_SERVICE_SID!) .verifications.create({ to: phone, channel: "sms" }); return verificationInstance; }; export const verifyTwilioVerificationToken = async ( phone: string, code: string ) => { if (process.env.NODE_ENV === "development") { return { valid: true, to: phone, }; } const client = getTwilioClient(); const verificationInstance = await client.verify.v2 .services(process.env.TWILIO_VERIFY_SERVICE_SID!) .verificationChecks.create({ to: phone, code }); return verificationInstance; };
import { useState, useEffect } from 'react'; import Image from "next/image"; import { pointsData } from '@/data/points'; import Head from 'next/head'; export default function Home() { const [selectedPoints, setSelectedPoints] = useState<{ flash: number[]; twoOrMore: number[]; }>({ flash: [], twoOrMore: [] }); // Carregando o estado inicial do localStorage quando o componente é montado useEffect(() => { const savedData = localStorage.getItem('tocaRankingPoints'); if (savedData) { setSelectedPoints(JSON.parse(savedData)); } }, []); const handlePointClick = (type: 'flash' | 'twoOrMore', point: number, boulder: number) => { if (type === 'flash' && selectedPoints.twoOrMore.includes(boulder)) return; if (type === 'twoOrMore' && selectedPoints.flash.includes(boulder)) return; if (!selectedPoints[type].includes(boulder)) { setSelectedPoints({ ...selectedPoints, [type]: [...selectedPoints[type], boulder] }); } else { setSelectedPoints({ ...selectedPoints, [type]: selectedPoints[type].filter(p => p !== boulder) }); } // Salvando o estado atual no localStorage localStorage.setItem('tocaRankingPoints', JSON.stringify({ ...selectedPoints, [type]: selectedPoints[type].includes(boulder) ? selectedPoints[type].filter(p => p !== boulder) : [...selectedPoints[type], boulder] })); } const getTotalPoints = (): number => { const flashPoints = selectedPoints.flash.reduce((a, b) => a + pointsData?.find(item => item.boulder === b)!.flash, 0); const twoOrMorePoints = selectedPoints.twoOrMore.reduce((a, b) => a + pointsData?.find(item => item.boulder === b)!.twoOrMore, 0); return flashPoints + twoOrMorePoints; } const clearSelections = () => { // confirmando se o usuário realmente quer limpar as seleções if (!confirm('Tem certeza que deseja limpar as seleções? Todos os dados serão perdidos.')) return; setSelectedPoints({ flash: [], twoOrMore: [] }); localStorage.removeItem('tocaRankingPoints'); } return ( <div className="flex flex-col items-center justify-start w-full h-screen p-4 pb-0"> <Head> <title>Toca Ranking Boulder 2023</title> <meta name="description" content="Contador de pontos para o Toca Ranking Boulder 2023" /> <link rel="icon" href="/logo.png" /> </Head> <div className="flex flex-col justify-center items-center border-2 p-2 rounded-lg mb-4"> <div className='flex flex-row items-center justify-center'> <Image src="/logo.png" alt="Toca Ranking Logo" width={50} height={50} /> <h1 className="text-2xl text-center font-bold text-gray-800 ml-2"> Toca Ranking Boulder 2023 </h1> </div> <span className="text-xl font-bold text-gray-500 mt-2">Pontos totais: {getTotalPoints()}</span> </div> <div className='flex flex-col items-center justify-start w-full h-full overflow-y-auto pb-16'> <table className="border-collapse border border-gray-800 w-full max-w-sm mb-4 shadow-md"> <thead> <tr> <th className="border border-gray-800 px-4 py-2">BOULDER</th> <th className="border border-gray-800 px-4 py-2">FLASH</th> <th className="border border-gray-800 px-4 py-2">2 OU MAIS</th> </tr> </thead> <tbody className="text-center"> {pointsData?.map((item, index) => ( <tr key={item.boulder} className={index % 2 === 0 ? 'bg-gray-100' : 'bg-white'}> <td className="border border-gray-800 select-none px-4 py-2 w-20">{item.boulder}</td> <td className={`border border-gray-800 select-none px-4 py-2 cursor-pointer ${selectedPoints.flash.includes(item.boulder) ? 'bg-green-300' : ''}`} onClick={() => handlePointClick('flash', item.flash, item.boulder)} > {item.flash} </td> <td className={`border border-gray-800 select-none px-4 py-2 cursor-pointer ${selectedPoints.twoOrMore.includes(item.boulder) ? 'bg-purple-300' : ''}`} onClick={() => handlePointClick('twoOrMore', item.twoOrMore, item.boulder)} > {item.twoOrMore} </td> </tr> ))} </tbody> </table> <button className="mt-4 px-4 py-2 bg-red-500 text-white rounded-lg" onClick={clearSelections}> Limpar Seleções </button> </div> <footer> <a href="https://instagram.com/andreocunha" target="_blank" rel="noopener noreferrer" className="flex flex-row items-center justify-center mt-4 p-2" > <span className="text-gray-500 text-sm">Feito por</span> <span className="text-gray-800 text-sm font-bold ml-1 underline">André Cunha</span> </a> </footer> </div> ) }
import { clearUserData, getUserData, setUserData } from '../util.js'; const host = 'http://localhost:3030'; export async function request(url, options) { try { const response = await fetch(host + url, options); if (response.ok != true) { const error = await response.json(); throw new Error(error.message); } return response.json(); } catch (error) { alert(error.message); throw error; } } function createOptions(method = 'get', data) { const options = { method, headers: {}, }; if (data != undefined) { options.headers['Content-Type'] = 'application/json'; options.body = JSON.stringify(data); } const userData = getUserData(); if (userData != null) { options.headers['X-Authorization'] = userData.token; } return options; } export async function get(url) { return request(url, createOptions()); } export async function post(url, data) { return request(url, createOptions('post', data)); } export async function put(url, data) { return request(url, createOptions('put', data)); } export async function del(url) { return request(url, createOptions('delete')); } export async function login(email, password) { const res = await post('/users/login', { email, password }); const userData = { email: res.email, id: res._id, token: res.accessToken, }; setUserData(userData); } export async function register(email, password) { const res = await post('/users/register', { email, password }); const userData = { email: res.email, id: res._id, token: res.accessToken, }; setUserData(userData); } export async function logout() { await get('/users/logout'); clearUserData(); }
import React, { useEffect, useState } from 'react'; import { Dimensions, Platform, RefreshControl, SafeAreaView, StyleSheet, View, } from 'react-native'; import { ScrollView } from 'react-native-gesture-handler'; import { useDispatch, useSelector } from 'react-redux'; import SizedBoxHeight from '../../components/Common/SizedBoxHeight'; import GoButton from '../../components/GoComponents/GoButton'; import GoImageName from '../../components/GoComponents/GoImageName'; import ImageBoxLoader from '../../components/Loaders/ImageBoxLoader'; import commonStyles from '../../theme/common'; import { showtoast } from '../../utils/error'; import { car_models } from '../../apis/addCarApis'; import { setCarData } from '../../redux/newCar/newCarSlice'; import buttonStyles from '../../theme/button'; // Gap stuff const { width } = Dimensions.get('window'); const gap = 12; const itemPerRow = 3; const totalGapSize = (itemPerRow - 1) * gap; const windowWidth = width * 0.89; const childWidth = (windowWidth - totalGapSize) / itemPerRow; const AddCarModel = ({ openSelectFuelModal }) => { const dispatch = useDispatch(); const carData = useSelector(state => state.newCar); const [loading, setLoading] = useState(false); const [carModels, setModels] = useState([]); const [selectedModel, setSelectedModel] = useState(null); const carCompany = useSelector(state => state.newCar.carCompany); useEffect(() => { getCarModels(); // eslint-disable-next-line }, []); const getCarModels = async () => { setLoading(true); try { const response = await car_models(carCompany); if (response) { setModels(response.data); } setLoading(false); } catch (error) { setLoading(false); } }; const onContinue = () => { if (!selectedModel) { return showtoast('Please select your car model'); } else { dispatch( setCarData({ ...carData, carType: selectedModel.attributes.car_type?.data?.attributes, carModel: selectedModel.id, }), ); // dismissAllBottomSheets(); openSelectFuelModal(); } }; return ( <SafeAreaView style={{ justifyContent: 'space-between', marginVertical: 16, flex: 1, }}> <ScrollView showsVerticalScrollIndicator={false} refreshControl={ <RefreshControl refreshing={loading} onRefresh={getCarModels} /> }> <View style={styles.itemsWrap}> {loading ? ( <ImageBoxLoader childWidth={childWidth} count={3} /> ) : ( carModels.map((item, index) => ( <GoImageName key={index} onPress={() => setSelectedModel(item)} image={{ uri: item.attributes?.Car_Image?.data?.attributes?.url, }} name={item.attributes.Model_name} isSelected={(selectedModel && selectedModel.id) === item.id} itemStyles={styles.singleItem} /> )) )} </View> </ScrollView> <View style={commonStyles.paddingHorizontal}> <GoButton text="Confirm" onPress={() => onContinue()} style={buttonStyles.primaryButton} textStyle={buttonStyles.primaryButtonText} /> </View> <SizedBoxHeight height={Platform.OS === 'ios' ? 16 : 5} /> </SafeAreaView> ); }; export default AddCarModel; const styles = StyleSheet.create({ itemsWrap: { ...commonStyles.paddingHorizontal, flexWrap: 'wrap', flexDirection: 'row', marginVertical: -(gap / 2), marginHorizontal: -(gap / 2), marginBottom: 20, }, singleItem: { marginTop: 8, marginHorizontal: gap / 2, minWidth: childWidth, maxWidth: childWidth, }, });
import { OrderedProduct } from "./product"; export type ShippingAddress = { name: string; address1: string; address2?: string; city: string; state: string; zip: string; email: string; }; export type Order = { id: string; shippingAddress: ShippingAddress; orderedProducts: OrderedProduct[]; status: { value: StatusValue; lastUpdated: string; description: string; }; }; export type StatusValue = "processing" | "shipped" | "delivered"; export type FilterOrder = | { status: StatusValue | "all"; month: string; year: null; sort: string; query: string; } | { status: StatusValue | "all"; month: null; year: string; sort: string; query: string; };
import { useState, useEffect } from "react"; import TaskInput from "./TaskInput"; import TaskList from "./TaskList"; const baseurl = "https://forpythonanywhere1.pythonanywhere.com/api/"; const Tasks = () => { const [isLoading, setIsLoading] = useState(true); const [isError, setIsError] = useState(false); const [tasks, setTasks] = useState([]); const fetchTasks = async (url) => { try { const resp = await fetch(url); if (!resp.ok) { setIsError(true); setIsLoading(false); return; } const data = await resp.json(); setTasks(data); setIsLoading(false); } catch (error) { setIsError(true); } }; useEffect(() => { fetchTasks(baseurl); }, []); const addTask = async (url, data) => { try { await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); } catch (error) { console.log("Error:", error); } fetchTasks(baseurl); }; const deleteTask = async (url) => { try { await fetch(url, { method: "DELETE", }); } catch (error) { console.log("Error:", error); } fetchTasks(baseurl); }; const editTask = async (url, data) => { try { await fetch(url, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); } catch (error) { console.log("Error:", error); } fetchTasks(baseurl); }; return ( <section className="relative bg-black min-h-screen"> <h1 className="text-4xl lg:max-w-5xl text-white text-center py-5 mx-auto"> Tasks </h1> <TaskInput addTask={addTask} /> <TaskList editTask={editTask} deleteTask={deleteTask} isLoading={isLoading} isError={isError} tasks={tasks} /> </section> ); }; export default Tasks;
from Buffer import Buffer from AnalizadorLexico import AnalizadorLexico from Token import Token #Notas:---------------------------------------- # Assignement tiene en conjunto primero ID repetido, tanto para id=Assignement como para LogicOr # Mientras menos saltos de linea y espacios haya en el Archivo C a analizar, mas caracteres lee correctamente(Posible correccion) # Mientras mas funciones se llaman, mayor informacion se pierde Ejemplo: Funcion ReturnStmt, se tuvo que poner un print porque no hacia la extraccion del token # En Funs, despues de Params) va FuncStmt, no stmt # Limite 39 #---------------------------------------------- def error(id, terminal, esperado): #tabla Error #id = 1: Se esperaba un terminal y recibio uno distinto print('Hubo un error en la sintaxis') if id == 1: print('Recibio un '+terminal+', se esperaba un '+str(esperado)+'.') # def coincidir(esperado, avance, token): terminal = token[avance].getNombreToken() if terminal == esperado: return avance + 1 else: error(1,terminal,esperado) return -1 # def TypeSpec(avance,token): terminal = token[avance].getNombreToken() if terminal == 'INT': avance = coincidir('INT', avance, token) avance = coincidir('ID', avance, token) return avance elif terminal == 'FLOAT': avance = coincidir('FLOAT', avance, token) avance = coincidir('ID', avance, token) return avance elif terminal == 'CHAR': avance = coincidir('CHAR', avance, token) avance = coincidir('ID', avance, token) return avance else: return -1 # def LogicOrPrima(avance,token): terminal = token[avance].getNombreToken() if terminal == 'OR': avance = coincidir('OR', avance, token) avance = LogicAnd(avance,token) return avance # def UnaryOp(avance,token): terminal = token[avance].getNombreToken() if terminal == 'NEGATION': avance = coincidir('NEGATION', avance, token) return avance elif terminal == 'MENOS': avance = coincidir('MENOS', avance, token) return avance else: error(1,terminal,['NEGATION','MENOS']) return -1 # def Primary(avance,token): terminal = token[avance].getNombreToken() if terminal == 'ID': avance = coincidir('ID', avance, token) return avance #LogicOr elif terminal == 'INTEGER_CONST': avance = coincidir('INTEGER_CONST', avance, token) return avance elif terminal == 'FLOAT_CONST': avance = coincidir('FLOAT_CONST', avance, token) return avance elif terminal == 'CHAR_CONST': avance = coincidir('CHAR_CONST', avance, token) return avance elif terminal == 'TRUE': avance = coincidir('TRUE', avance, token) return avance elif terminal == 'FALSE': avance = coincidir('FALSE', avance, token) return avance elif terminal == 'PARENTESIS_APERTURA': avance = coincidir('PARENTESIS_APERTURA', avance, token) avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) return avance else: error(1,terminal,['PUNTOCOMA','ID','INTEGER_CONST','FLOAT_CONST','CHAR_CONST','TRUE','FALSE','PARENTESIS_APERTURA']) return -1 # def CallFunc(avance,token): terminal = token[avance].getNombreToken() if terminal == 'PARENTESIS_APERTURA': avance = coincidir('PARENTESIS_APERTURA', avance, token) avance = Params(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) return avance # def Call(avance,token): avance = Primary(avance,token) if avance == -1: return avance avance = CallFunc(avance,token) return avance # def Unary(avance,token): terminal = token[avance].getNombreToken() if terminal == 'ID': avance = Call(avance,token) return avance #LogicOr elif terminal == 'INTEGER_CONST': avance = Call(avance,token) return avance elif terminal == 'FLOAT_CONST': avance = Call(avance,token) return avance elif terminal == 'CHAR_CONST': avance = Call(avance,token) return avance elif terminal == 'TRUE': avance = Call(avance,token) return avance elif terminal == 'FALSE': avance = Call(avance,token) return avance elif terminal == 'PARENTESIS_APERTURA': avance = Call(avance,token) return avance elif terminal == 'NEGATION': avance = UnaryOp(avance, token) if avance == -1: return avance avance = Unary(avance,token) return avance elif terminal == 'MENOS': avance = UnaryOp(avance, token) if avance == -1: return avance avance = Unary(avance,token) return avance else: error(1,terminal,['PUNTOCOMA','ID','INTEGER_CONST','FLOAT_CONST','CHAR_CONST','TRUE','FALSE','PARENTESIS_APERTURA','NEGATION','MENOS']) return -1 # def FactorPrima(avance,token): terminal = token[avance].getNombreToken() if terminal == 'DIV': avance = coincidir('DIV',avance,token) avance = Unary(avance,token) if avance == -1: return avance avance = FactorPrima(avance,token) elif terminal == 'MULT': avance = coincidir('MULT',avance,token) avance = Unary(avance,token) if avance == -1: return avance avance = FactorPrima(avance,token) return avance # def Factor(avance,token): avance = Unary(avance,token) if avance == -1: return avance avance = FactorPrima(avance,token) return avance # def TermPrima(avance,token): terminal = token[avance].getNombreToken() if terminal == 'MENOS': avance = coincidir('MENOS',avance,token) avance = Factor(avance,token) if avance == -1: return avance avance = TermPrima(avance,token) elif terminal == 'MAS': avance = coincidir('MAS') avance = Factor(avance,token) if avance == -1: return avance avance = TermPrima(avance,token) return avance # def Term(avance,token): avance = Factor(avance,token) if avance == -1: return avance avance = TermPrima(avance,token) return avance def LogicOperator(avance,token): terminal = token[avance].getNombreToken() if terminal == 'MAYOR': avance = coincidir('MAYOR',avance,token) elif terminal == 'MENOR': avance = coincidir('MENOR',avance,token) elif terminal == 'MENORIGUAL': avance = coincidir('MENORIGUAL',avance,token) elif terminal == 'MAYORIGUAL': avance = coincidir('MAYORIGUAL',avance,token) return avance # def ComparisonPrima(avance,token): terminal = token[avance].getNombreToken() if terminal == 'MAYOR': avance = LogicOperator(avance,token) avance = Term(avance,token) if avance == -1: return avance avance = ComparisonPrima(avance,token) elif terminal == 'MENOR': avance = LogicOperator(avance,token) avance = Term(avance,token) if avance == -1: return avance avance = ComparisonPrima(avance,token) elif terminal == 'MENORIGUAL': avance = LogicOperator(avance,token) avance = Term(avance,token) if avance == -1: return avance avance = ComparisonPrima(avance,token) elif terminal == 'MAYORIGUAL': avance = LogicOperator(avance,token) avance = Term(avance,token) if avance == -1: return avance avance = ComparisonPrima(avance,token) return avance # def Comparison(avance,token): avance = Term(avance,token) if avance == -1: return avance avance = ComparisonPrima(avance,token) return avance # def CompOper(avance,token): terminal = token[avance].getNombreToken() if terminal == 'NOIGUAL': avance = coincidir('NOIGUAL',avance,token) elif terminal == 'IGUAL': avance = coincidir('IGUAL',avance,token) return avance # def EqualityPrima(avance,token): terminal = token[avance].getNombreToken() if terminal == 'NOIGUAL': avance = CompOper(avance,token) avance = Comparison(avance,token) if avance == -1: return avance avance = EqualityPrima(avance,token) elif terminal == 'IGUAL': avance = CompOper(avance,token) avance = Comparison(avance,token) if avance == -1: return avance avance = EqualityPrima(avance,token) return avance # def Equality(avance,token): avance = Comparison(avance,token) if avance == -1: return avance avance = EqualityPrima(avance,token) return avance # def LogicAndPrima(avance,token): terminal = token[avance].getNombreToken() if terminal == 'AND': avance = coincidir('AND', avance, token) avance = Equality(avance,token) if avance == -1: return avance avance = LogicAndPrima(avance,token) return avance # def LogicAnd(avance,token): avance = Equality(avance,token) if avance == -1: return avance avance = LogicAndPrima(avance,token) return avance # def LogicOr(avance,token): avance = LogicAnd(avance,token) if avance == -1: return avance avance = LogicOrPrima(avance,token) return avance # def Assigment(avance,token): terminal = token[avance].getNombreToken() if terminal == 'ID': avance = coincidir('ID', avance, token) avance = coincidir('ATTR', avance, token) if avance == -1: return avance avance = Assigment(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA',avance,token) return avance #LogicOr elif terminal == 'INTEGER_CONST': avance = LogicOr(avance,token) return avance elif terminal == 'FLOAT_CONST': avance = LogicOr(avance,token) return avance elif terminal == 'CHAR_CONST': avance = LogicOr(avance,token) return avance elif terminal == 'TRUE': avance = LogicOr(avance,token) return avance elif terminal == 'FALSE': avance = LogicOr(avance,token) return avance elif terminal == 'PARENTESIS_APERTURA': avance = LogicOr(avance,token) return avance elif terminal == 'NEGATION': avance = LogicOr(avance,token) return avance elif terminal == 'MENOS': avance = LogicOr(avance,token) return avance else: error(1,terminal,['PUNTOCOMA','ID','INTEGER_CONST','FLOAT_CONST','CHAR_CONST','TRUE','FALSE','PARENTESIS_APERTURA','NEGATION','MENOS']) return -1 # def Expresion(avance,token): avance = Assigment(avance,token) return avance # def ExprStmt(avance,token): terminal = token[avance].getNombreToken() if terminal == 'ID': avance = Expresion(avance,token) #avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'INTEGER_CONST': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'FLOAT_CONST': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'CHAR_CONST': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'TRUE': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'FALSE': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'PARENTESIS_APERTURA': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance else: error(1,terminal,['PUNTOCOMA','ID','INTEGER_CONST','FLOAT_CONST','CHAR_CONST','TRUE','FALSE','PARENTESIS_APERTURA']) return -1 # def ParamsPrima(avance,token): terminal = token[avance].getNombreToken() if terminal == 'COMA': avance = coincidir('COMA',avance,token) avance = Param(avance,token) if avance == -1: return avance avance = ParamsPrima(avance,token) return avance else: return avance # def Param(avance,token): terminal = token[avance].getNombreToken() if terminal == 'INT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = ParamsPrima(avance, token) return avance elif terminal == 'FLOAT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = ParamsPrima(avance, token) return avance elif terminal == 'CHAR': avance = TypeSpec(avance, token) if avance == -1: return avance avance = ParamsPrima(avance, token) return avance else: error(1,terminal,['INT','FLOAT','CHAR']) return -1 # def Params(avance,token): terminal = token[avance].getNombreToken() if terminal == 'INT': avance = Param(avance, token) if avance == -1: return avance avance = ParamsPrima(avance, token) return avance elif terminal == 'FLOAT': avance = Param(avance, token) if avance == -1: return avance avance = ParamsPrima(avance, token) return avance elif terminal == 'CHAR': avance = Param(avance, token) if avance == -1: return avance avance = ParamsPrima(avance, token) return avance else: return avance # def FuncDecList(avance, token): terminal = token[avance].getNombreToken() if terminal == 'INT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = coincidir('PARENTESIS_APERTURA',avance,token) if avance == -1: return avance avance = Params(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = FuncStmt(avance,token) return avance elif terminal == 'FLOAT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = coincidir('PARENTESIS_APERTURA',avance,token) if avance == -1: return avance avance = Params(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = FuncStmt(avance,token) return avance elif terminal == 'CHAR': avance = TypeSpec(avance, token) if avance == -1: return avance avance = coincidir('PARENTESIS_APERTURA',avance,token) if avance == -1: return avance avance = Params(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = FuncStmt(avance,token) return avance elif terminal == 'VOID': avance = coincidir('VOID', avance, token) avance = coincidir('ID', avance, token) if avance == -1: return avance avance = coincidir('PARENTESIS_APERTURA',avance,token) if avance == -1: return avance avance = Params(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = FuncStmt(avance,token) return avance else: error(1,terminal,['INT','FLOAT','CHAR','VOID']) return -1 # def FuncDecListPrima(avance, token): terminal = token[avance].getNombreToken() if terminal == 'INT': avance = FuncDecList(avance,token) if avance == -1: return avance avance = FuncDecListPrima(avance,token) return avance elif terminal == 'FLOAT': avance = FuncDecList(avance,token) if avance == -1: return avance avance = FuncDecListPrima(avance,token) return avance elif terminal == 'CHAR': avance = FuncDecList(avance,token) if avance == -1: return avance avance = FuncDecListPrima(avance,token) return avance elif terminal == 'VOID': avance = FuncDecList(avance,token) if avance == -1: return avance avance = FuncDecListPrima(avance,token) return avance else: return avance # def ForExpr(avance,token): terminal = token[avance].getNombreToken() if terminal == 'ID': avance = Expresion(avance,token) return avance elif terminal == 'INTEGER_CONST': avance = Expresion(avance,token) return avance elif terminal == 'FLOAT_CONST': avance = Expresion(avance,token) return avance elif terminal == 'CHAR_CONST': avance = Expresion(avance,token) return avance elif terminal == 'TRUE': avance = Expresion(avance,token) return avance elif terminal == 'FALSE': avance = Expresion(avance,token) return avance elif terminal == 'PARENTESIS_APERTURA': avance = Expresion(avance,token) return avance elif terminal == 'NEGATION': avance = Expresion(avance,token) return avance elif terminal == 'MENOS': avance = Expresion(avance,token) return avance else: return avance # def ForStmt(avance,token): avance = coincidir('FOR',avance,token) avance = coincidir('PARENTESIS_APERTURA',avance,token) if avance == -1: return avance avance = ForExpr(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) if avance == -1: return avance avance = ForExpr(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) if avance == -1: return avance avance = ForExpr(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = coincidir('LLAVE_APERTURA',avance,token) if avance == -1: return avance avance = Stmts(avance,token) if avance == -1: return avance avance = coincidir('LLAVE_CERRADURA',avance,token) return avance # def WhileStmt(avance,token): avance = coincidir('WHILE',avance,token) avance = coincidir('PARENTESIS_APERTURA',avance,token) if avance == -1: return avance avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = coincidir('LLAVE_APERTURA',avance,token) if avance == -1: return avance avance = Stmts(avance,token) if avance == -1: return avance avance = coincidir('LLAVE_CERRADURA',avance,token) return avance # def ElseStmt(avance,token): terminal = token[avance].getNombreToken() if terminal == 'ELSE': avance = coincidir('ELSE',avance,token) avance = coincidir('LLAVE_APERTURA',avance,token) if avance == -1: return avance avance = Stmts(avance,token) if avance == -1: return avance avance = coincidir('LLAVE_CERRADURA',avance,token) return avance # def IfStmt(avance,token): print('enter') avance = coincidir('IF',avance,token) avance = coincidir('PARENTESIS_APERTURA',avance,token) if avance == -1: return avance avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = coincidir('LLAVE_APERTURA',avance,token) if avance == -1: return avance avance = Stmts(avance,token) if avance == -1: return avance avance = coincidir('LLAVE_CERRADURA',avance,token) if avance == -1: return avance avance = ElseStmt(avance,token) return avance # def Stmt(avance,token): terminal = token[avance].getNombreToken() if terminal == 'ID': avance = ExprStmt(avance,token) return avance elif terminal == 'IF': avance = IfStmt(avance,token) return avance elif terminal == 'WHILE': avance = WhileStmt(avance,token) return avance elif terminal == 'FOR': avance = ForStmt(avance,token) return avance else: error(1,terminal,['ID','IF','WHILE','FOR']) return -1 # def Stmts(avance, token): terminal = token[avance].getNombreToken() if terminal == 'ID': avance = Stmt(avance,token) if avance == -1: return avance avance = Stmts(avance,token) return avance elif terminal == 'IF': avance = Stmt(avance,token) if avance == -1: return avance avance = Stmts(avance,token) return avance elif terminal == 'WHILE': avance = Stmt(avance,token) if avance == -1: return avance avance = Stmts(avance,token) return avance elif terminal == 'FOR': avance = Stmt(avance,token) if avance == -1: return avance avance = Stmts(avance,token) return avance else: return avance # def FuncStmt(avance, token): terminal = token[avance].getNombreToken() if terminal == 'LLAVE_APERTURA': avance = coincidir('LLAVE_APERTURA', avance, token) avance = Stmts(avance, token) if avance == -1: return avance avance = ReturnStmt(avance,token) if avance == -1: return avance avance = coincidir('LLAVE_CERRADURA', avance, token) return avance else: error(1,terminal,'LLAVE_APERTURA') return -1 # def ReturnStmt(avance,token): terminal = token[avance].getNombreToken() if terminal == 'RETURN': avance = coincidir('RETURN', avance, token) if terminal == 'PUNTOCOMA': avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'ID': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'INTEGER_CONST': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'FLOAT_CONST': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'CHAR_CONST': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'TRUE': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'FALSE': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance elif terminal == 'PARENTESIS_APERTURA': avance = Expresion(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA', avance, token) return avance else: error(1,terminal,['PUNTOCOMA','ID','INTEGER_CONST','FLOAT_CONST','CHAR_CONST','TRUE','FALSE','PARENTESIS_APERTURA']) return -1 else: return avance # def Funcs(avance, token): terminal = token[avance].getNombreToken() if terminal == 'PARENTESIS_APERTURA': avance = coincidir('PARENTESIS_APERTURA', avance, token) avance = Params(avance, token) if avance == -1: return avance avance = coincidir('PARENTESIS_CERRADURA',avance,token) if avance == -1: return avance avance = FuncStmt(avance, token) if avance == -1: return avance avance = FuncDecListPrima(avance,token) return avance else: error(1,terminal,'PARENTESIS_APERTURA') # def Decl2(avance,token): terminal = token[avance].getNombreToken() if terminal == 'INT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = Decl(avance, token) return avance elif terminal == 'FLOAT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = Decl(avance, token) return avance elif terminal == 'CHAR': avance = TypeSpec(avance, token) if avance == -1: return avance avance = Decl(avance, token) return avance elif terminal == 'VOID': avance = coincidir('VOID', avance, token) avance = coincidir('ID', avance, token) if avance == -1: return avance avance = Funcs(avance,token) return avance else: error(1,terminal,['INT','FLOAT','CHAR','VOID']) return -1 # def VarNames(avance,token): avance = coincidir('ID',avance,token) terminal = token[avance].getNombreToken() if terminal == 'CORCHETE_APERTURA': avance = ArrayDecl(avance,token) return avance elif terminal == 'ATTR': avance = VarDeclInit(avance,token) return avance elif terminal == 'COMA': avance = DecList(avance,token) return avance else: error(1,terminal,'PARENTESIS_APERTURA') return -1 # def DecList(avance,token): avance = coincidir('COMA',avance,token) avance = VarNames(avance, token) return avance # def VarDeclInit(avance,token): avance = coincidir('ATTR',avance,token) avance = Expresion(avance,token) return avance # def ArrayDecl(avance,token): avance = coincidir('CORCHETE_APERTURA',avance,token) avance = coincidir('INTEGER_CONST',avance,token) if avance == -1: return avance avance = coincidir('CORCHETE_CERRADURA',avance,token) return avance # def Vars(avance,token): terminal = token[avance].getNombreToken() if terminal == 'CORCHETE_APERTURA': avance = ArrayDecl(avance,token) elif terminal == 'ATTR': avance = VarDeclInit(avance,token) elif terminal == 'COMA': avance = DecList(avance,token) if avance == -1: return avance avance = coincidir('PUNTOCOMA',avance,token) terminal = token[avance].getNombreToken() if terminal == 'INT': avance = Decl2(avance,token) return avance elif terminal == 'FLOAT': avance = Decl2(avance,token) return avance elif terminal == 'CHAR': avance = Decl2(avance,token) return avance elif terminal == 'VOID': avance = Decl2(avance,token) return avance else: error(1,terminal,['INT','FLOAT','CHAR','VOID']) return -1 # def Decl(avance, token): terminal = token[avance].getNombreToken() if terminal == 'PARENTESIS_APERTURA': avance = Funcs(avance,token) return avance elif terminal == 'CORCHETE_APERTURA': avance == Vars(avance,token) return avance elif terminal == 'ATTR': avance == Vars(avance,token) return avance elif terminal == 'COMA': avance == Vars(avance,token) return avance elif terminal == 'PUNTOCOMA': avance == Vars(avance,token) return avance else: error(1,terminal,['PARENTESIS_APERTURA','CORCHETE_APERTURA','ATTR','COMA','PUNTOCOMA']) return -1 # def program(avance, token): terminal = token[avance].getNombreToken() if terminal == 'INT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = Decl(avance, token) return avance elif terminal == 'FLOAT': avance = TypeSpec(avance, token) if avance == -1: return avance avance = Decl(avance, token) return avance elif terminal == 'CHAR': avance = TypeSpec(avance, token) if avance == -1: return avance avance = Decl(avance, token) return avance elif terminal == 'VOID': avance = coincidir('VOID', avance, token) avance = coincidir('ID', avance, token) if avance == -1: return avance avance = Funcs(avance,token) return avance else: error(1,terminal,['INT','FLOAT','CHAR','VOID']) return -1 if __name__ == '__main__': Buffer = Buffer() Analizador = AnalizadorLexico() tokens = Token() # Lista de cada lista devuelta por la función tokenize #token = [] #lexema = [] #fila = [] #columna = [] # Obtenemos los tokens y recargams el buffer for i in Buffer.load_buffer(): tokens = Analizador.tokenize(i) """token += t lexema += lex fila += lin columna += col """ token = Token() token.setNombreToken('FIN_PROGRAMA') token.__str__() tokens.append(token) avance = 0 avance = program(avance, tokens) if avance != -1: print('La sintaxis es correcta') ##print('\nTokens reconocidos: ', token)
{% extends 'base.html' %} {% block content %} <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> function posting(e) { e.preventDefault() const title = $("#title").val() const description = $("#description").val() const data = { title: title, description: description, csrfmiddlewaretoken: "{{ csrf_token }}" } $.ajax({ type: 'POST', url: '{% url "todolist:add_task" %}', data: data, dataType: 'json' }); fetchData(); } function update(data) { const myElement = $("#main-div") myElement.html(''); for (let i = 0; i < data.length; i++) { let message = (data[i].fields.is_finished) ? 'Finished':'Not Finished'; let color = (data[i].fields.is_finished) ? 'green':'red'; myElement.append(` <div class="card col-sm-4 mb-1 mt-4 mx-auto" style="width: 18rem;"> <div class="card-body"> <h4 class="card-title text-center fw-semibold">${data[i].fields.title}</h4> <ul class="list-group list-group-flush"> <li class="list-group-item text-secondary">${data[i].fields.date}</li> <li class="list-group-item">${data[i].fields.description}</li> </ul> </div> <div class="card-footer text-center"> <p style="font-weight:bold; color:${color};">${message}</p> <button type="button" class="btn btn-dark" style="float:left;"><a class="text-light" href="status/${data[i].pk}" style="text-decoration:solid ">Update</a></button> <button type="button" class="btn btn-dark" style="float:right;"><a class="text-light" href="delete/${data[i].pk}" style="text-decoration:solid ">Delete</a></button> </div> </div> `) } } function fetchData() { $.get("/todolist/json", update) } $(document).ready(() => { $("#create-button").click(posting) fetchData() }) </script> <style> .card { box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); transition: 0.3s; width: 40%; border-radius: 5px; } .card:hover { transform: scale(1.05); box-shadow: 0 10px 20px rgba(0,0,0,.12), 0 4px 8px rgba(0,0,0,.06); } .container { padding: 2px 16px; } .content { padding-left: 20px; padding-right: 20px; } .navbar-custom { background-color:#F6F6F2; } body { background: linear-gradient(-45deg, #388087, #6FB3B8, #BADFE7, #C2EDCE); background-size: 400% 400%; animation: gradient 15s ease infinite; height: 100vh; } @keyframes gradient { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } </style> </head> <div class="navbar navbar-custom mb-4"> <div class="container-fluid justify-content-center"> <h1 class="navbar-brand" href="#">Hello, {{ user.get_username }}! Here's your to-do list!</h1> </div> </div> <div class="content w-100 mx-auto"> <div class="header text-center mx-auto"> <a href="{% url 'todolist:logout' %}" class="btn btn-danger" style="float:left">Log Out</a> <a data-bs-toggle="modal" href="#addTask" class="btn btn-primary" style="float:right">Add Task</a> </div> </div> <div class="row row-cols-1 row-cols-md-3 g-4 md:justify-end gap-4" id="main-div"></div> <div class="modal fade modal-dialog modal-dialog-centered" id="addTask" tabindex="-1" aria-labelledby="addTaskLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Add Task</h1> </div> <div class="modal-body"> <form method="POST" action="" style="display: inline-block;"> {% csrf_token %} <table> <tr> <label>Title</label> <input type="text" name="title" id="title"> </tr><br> <tr> <label>Description</label> <input type="textarea" name="description" id="description"> </tr> <td colspan="2"> <input data-bs-dismiss="modal" style="width: 100%; margin-top: 20px; margin-bottom: 7px;" class="btn btn btn-dark" type="submit" name="submit" value="Create" id="create-button"> </td> </tr> </table> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> {% endblock content %}
import Foundation /// Class receives bytes of data, data must be utf8 representation of mutiline string /// At the end, we need to call `complete`, to decode last line, which might not end with "\n" /// This implementation is attempt to repoduce usefull `AsyncBytes` from `URLSession` or `FileHandler` final class AsyncBytesToLines: AsyncSequence { typealias Element = String struct AsyncIterator: AsyncIteratorProtocol { typealias Element = String init(_ asyncBytes: AsyncBytesToLines) { self.asyncBytes = asyncBytes } mutating func next() async -> String? { return await withCheckedContinuation { continuation in asyncBytes.lock.lock() defer { asyncBytes.lock.unlock() } if count < asyncBytes.lines.count { defer { count += 1 } continuation.resume(with: .success(asyncBytes.lines[count])) return } guard asyncBytes.expectingBytes else { continuation.resume(with: .success(nil)) return } let oldCounter = count count += 1 asyncBytes.updateWaiters.append { [self] in self.asyncBytes.lock.lock() defer { self.asyncBytes.lock.unlock() } if oldCounter < asyncBytes.lines.count { continuation.resume(with: .success(asyncBytes.lines[oldCounter])) return } guard asyncBytes.expectingBytes else { continuation.resume(with: .success(nil)) return } fatalError("In this block we expect or new value or end of bytes") } } } private let asyncBytes: AsyncBytesToLines private var count = 0 } func add(_ bytes: some Sequence<UInt8>) { let waiters: [UpdateWaiter] do { lock.lock() defer { lock.unlock() } guard expectingBytes else { fatalError("We do not expect more bytes") } notProcessedBytes.append(contentsOf: bytes) var didAddAtLeastOneLine = false while true { let `continue` = processCurrentBytes() guard `continue` else { break } didAddAtLeastOneLine = true } if didAddAtLeastOneLine { waiters = self.updateWaiters self.updateWaiters.removeAll() } else { waiters = [] } } waiters.forEach { $0() } } func complete() { lock.lock() expectingBytes = false let line = String(bytes: notProcessedBytes, encoding: .utf8)! notProcessedBytes.removeAll() let newLines = line.components(separatedBy: "\n") lines.append(contentsOf: newLines) let waiters: [UpdateWaiter] = self.updateWaiters self.updateWaiters.removeAll() lock.unlock() waiters.forEach { $0() } } // MARK: AsyncSequence func makeAsyncIterator() -> AsyncIterator { AsyncIterator(self) } // MARK: Private private typealias UpdateWaiter = () -> Void private let lock = NSLock() private var notProcessedBytes = [UInt8]() private var lines = [String]() private var expectingBytes = true private var updateWaiters = [UpdateWaiter]() /// - returns: true, if new line was generated private func processCurrentBytes() -> Bool { guard notProcessedBytes.count > 1 else { return false } let separatorBytes = "\n".data(using: .utf8)! precondition(separatorBytes.count == 1) let newLineByte = separatorBytes.first! let firstIndex = notProcessedBytes.firstIndex(of: newLineByte) guard let firstIndex else { return false } let lineBytes = notProcessedBytes.prefix(firstIndex) let line = String(bytes: lineBytes, encoding: .utf8)! let subSequence = notProcessedBytes.dropFirst(firstIndex + 1) notProcessedBytes = Array(subSequence) lines.append(line) return true } }
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import '../../blocs/export_blocs.dart'; class LoginPage extends StatelessWidget { TextEditingController usernameController = TextEditingController(); TextEditingController passwordController = TextEditingController(); LoginPage({super.key}); //login page @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Login'), ), body: BlocConsumer<LoginBloc, LoginState>( listener: (context, state) { if (state.isLogin) { Navigator.pushNamed(context, '/'); } }, builder: (context, state) { return Center( child: Container( padding: const EdgeInsets.all(20), width: 300, height: 500, child: Column( children: [ Text('login'.tr()), //text field for username TextField( controller: usernameController, obscureText: true, decoration: InputDecoration( border: const OutlineInputBorder(), labelText: 'username'.tr(), ), ), const SizedBox(height: 20), //text field for password TextField( controller: passwordController, obscureText: true, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), const SizedBox(height: 20), ElevatedButton( child: const Text('Login'), onPressed: () { context.read<LoginBloc>().add(Login(password: passwordController.text, username: usernameController.text)); }, ), ], ), ), ); }, )); } }
import "reflect-metadata"; import express from "express"; import { Container } from "inversify"; import { InversifyExpressServer } from "inversify-express-utils"; import TYPES from "./types"; import "./controllers/purchase"; import "./controllers/seller"; import PurchaseRepositoryInterface from "./repositories/purchase.repository.interface"; import PurchaseRepositoryMySql from "./repositories/purchase.repository.mysql"; import SellerRepositoryInterface from "./repositories/seller.repository.interface"; import SellerRepositoryMySql from "./repositories/seller.repository.mysql"; import CashbackRepositoryInterface from "./repositories/cashback.repository.interface"; import CashbackRepositoryMdaqk8ek5j from "./repositories/cashback.repository.mdaqk8ek5j"; import AuthenticateServiceInterface from "./services/authenticate.service.interface"; import AuthenticateService from "./services/authenticate.service"; import CashbackServiceInterface from "./services/cashback.service.interface"; import CashbackService from "./services/cashback.service"; import PurchaseServiceInterface from "./services/purchase.service.interface"; import PurchaseService from "./services/purchase.service"; class App { public container: Container; constructor() { this.container = new Container(); this.bindInterfaces(); } private bindInterfaces() { this.container .bind<PurchaseRepositoryInterface>(TYPES.PurchaseRepositoryInterface) .to(PurchaseRepositoryMySql); this.container .bind<SellerRepositoryInterface>(TYPES.SellerRepositoryInterface) .to(SellerRepositoryMySql); this.container .bind<CashbackRepositoryInterface>(TYPES.CashbackRepositoryInterface) .to(CashbackRepositoryMdaqk8ek5j); this.container .bind<AuthenticateServiceInterface>(TYPES.AuthenticateServiceInterface) .to(AuthenticateService); this.container .bind<CashbackServiceInterface>(TYPES.CashbackServiceInterface) .to(CashbackService); this.container .bind<PurchaseServiceInterface>(TYPES.PurchaseServiceInterface) .to(PurchaseService); } public createServer() { const server: InversifyExpressServer = new InversifyExpressServer( this.container ); server.setConfig((app) => { app.use(express.json()); }); const app = server.build(); if (process.env.NODE_ENV !== "test") { app.listen(3334); } return app; } } export default App;
import { Ionicons } from "@expo/vector-icons"; import { Button, Center, Input, Stack, Text, Icon, Alert, FormControl } from "native-base"; import { useEffect, useState } from "react"; import { TouchableOpacity, Image } from "react-native"; import { Field, Form } from "react-final-form"; import { login, logout } from "./utils"; import { getFormErrorMessage, validator } from "../../form/validation"; import { useAppDispatch } from "../../hooks"; import { Credentials, SecurityContext } from "../securityModels"; import { useLoginMutation } from "../securityService"; import { manifest } from "../../manifest"; import { makeRedirectUri, useAuthRequest, exchangeCodeAsync, refreshAsync, ResponseType, DiscoveryDocument } from "expo-auth-session"; import jwt_decode from "jwt-decode"; import { setRefreshTokenHandler } from "../../service"; import { AppDispatch } from "../../store"; import { useLocation, useNavigate } from "react-router-native"; export function Login() { const navigate = useNavigate(); const location = useLocation(); const dispatch = useAppDispatch(); useEffect(() => { if(location.pathname !== "" && location.pathname !== "/") { navigate('/', { replace: true }); } }, [location, navigate]) const [loginRequest] = useLoginMutation(); const [showPassword, setShowPassword] = useState(false); if (manifest.authMode === "oauth 2.0") { return ( <OAuth2Login /> ); } return ( <Form initialValues={{ username: '', password: '' }} onSubmit={async (credentials: Credentials) => { try { const securityContext = await loginRequest(credentials).unwrap(); login(dispatch, securityContext); } catch (ex) { return getFormErrorMessage(ex, 'Invalid credentials'); } }} render={({ handleSubmit, submitting, submitError }) => ( <Center flex={1}> <Stack width="90%" maxWidth={500}> <Center mb={3}> <Image style={{ maxWidth: 320 }} resizeMode="contain" source={require('../../../../../assets/logo.png')} /> </Center> {submitError && <Alert status="error">{submitError}</Alert>} <Field<string> name="username" validate={validator().require().build()}> {({ input: { value, onChange, onBlur, onFocus }, meta: { error, touched } }) => ( <FormControl isInvalid={Boolean(touched && error)}> <FormControl.Label>Username</FormControl.Label> <Input p="3" autoCapitalize='none' autoCorrect={false} isDisabled={submitting} value={value} onFocus={() => onFocus()} onBlur={() => onBlur()} onChangeText={value => onChange(value)} /> { touched && error ? <FormControl.ErrorMessage>{error}</FormControl.ErrorMessage> : <FormControl.HelperText>{' '}</FormControl.HelperText> } </FormControl> )} </Field> <Field<string> name="password" validate={validator().require().build()}> {({ input: { value, onChange, onBlur, onFocus }, meta: { error, touched } }) => ( <FormControl isInvalid={Boolean(touched && error)}> <FormControl.Label>Password</FormControl.Label> <Input p="3" isDisabled={submitting} autoCapitalize='none' autoCorrect={false} value={value} onFocus={() => onFocus()} onBlur={() => onBlur()} onChangeText={value => onChange(value)} type={showPassword ? 'text' : 'password'} InputRightElement={ <TouchableOpacity onPress={() => setShowPassword(!showPassword)} hitSlop={{ top: 10, right: 10, bottom: 10, left: 10 }}> <Icon mr="2" name={!showPassword ? 'eye-off-outline' : 'eye-outline'} as={Ionicons} size={7} /> </TouchableOpacity> } /> { touched && error ? <FormControl.ErrorMessage>{error}</FormControl.ErrorMessage> : <FormControl.HelperText>{' '}</FormControl.HelperText> } </FormControl> )} </Field> <Button mt="4" size="lg" h="50" isLoading={submitting} isDisabled={submitting} onPress={handleSubmit} > <Text color="white" fontSize="lg">Sign In</Text> </Button> </Stack> </Center> )} /> ); } const discovery: DiscoveryDocument = { authorizationEndpoint: manifest.authUrl, tokenEndpoint: manifest.tokenUrl }; function OAuth2Login() { const dispatch = useAppDispatch(); const redirectUri = makeRedirectUri({ path: 'redirect' }); const [request, _, promptAsync] = useAuthRequest({ clientId: manifest.clientId, responseType: ResponseType.Code, usePKCE: true, redirectUri, scopes: manifest.scopes }, discovery ); return ( <Center flex={1}> <Stack width="90%" maxWidth={500}> <Center mb={5}> <Image style={{ maxWidth: 320 }} resizeMode="contain" source={require('../../../../../assets/logo.png')} /> </Center> <Button mt="5" size="lg" h="50" isDisabled={!request} onPress={async () => { try { const response = await promptAsync(); if (response.type === "success" && response.params?.code) { const tokenInfo = await exchangeCodeAsync({ clientId: manifest.clientId, redirectUri, code: response.params.code, extraParams: { code_verifier: request?.codeVerifier || "", }, }, discovery ); const securityContext = createSecurityContext(tokenInfo); login(dispatch, securityContext); } } catch (ex) { console.error(ex); } }} > <Text color="white" fontSize="lg">Sign In</Text> </Button> </Stack> </Center> ); } setRefreshTokenHandler(async (refreshToken, dispatch) => { try { const tokenInfo = await refreshAsync({ clientId: manifest.clientId, refreshToken: refreshToken }, discovery ); const securityContext = createSecurityContext(tokenInfo); login(dispatch as AppDispatch, securityContext); return true; } catch { logout(dispatch as AppDispatch); return false; } }); function createSecurityContext(tokenInfo: any) { const accessTokenClaims = jwt_decode(tokenInfo.accessToken) as any; const expiresIn = tokenInfo.expiresIn || 0; const expiresAt = Math.floor(Date.now() / 1000) + expiresIn; const securityContext: SecurityContext = { identity: { id: accessTokenClaims.sub, name: accessTokenClaims.name }, scopes: accessTokenClaims.roles, token: { expiresAt, expiresIn, accessToken: tokenInfo.accessToken, refreshToken: tokenInfo.refreshToken, } }; return securityContext; }
# test.py import os import cv2 import imutils import numpy as np import argparse import warnings import time from imutils.video import VideoStream from src.anti_spoof_predict_pro import AntiSpoofPredict from src.generate_patches import CropImage from src.utility import parse_model_name warnings.filterwarnings('ignore') def check_image(image): height, width, channel = image.shape if width/height != 3/4: print("Image is not appropriate!!!\nHeight/Width should be 4/3.") return False else: return True def test(model_dir, device_id): model_test = AntiSpoofPredict(device_id, model_dir) image_cropper = CropImage() # cap = VideoStream(src=0).start() cap = cv2.VideoCapture(0) # 使用电脑摄像头获取实时视频流 time.sleep(2) while True: # frame = cap.read() # frame = imutils.resize(frame, width=300) ret, frame = cap.read() # 读取一帧 if not ret: break image_bbox = model_test.get_bbox(frame) prediction = np.zeros((1, 3)) test_speed = 0 for model_name in os.listdir(model_dir): h_input, w_input, model_type, scale = parse_model_name(model_name) param = { "org_img": frame, "bbox": image_bbox, "scale": scale, "out_w": w_input, "out_h": h_input, "crop": True, } if scale is None: param["crop"] = False img = image_cropper.crop(**param) start = time.time() # 记录预测开始时间 # 使用模型进行预测 predictions = model_test.predict_batch([img]) # 将当前模型的预测结果添加到总预测中 prediction += predictions[model_name] test_speed += time.time()-start # 计算预测所花时间 label = np.argmax(prediction) value = prediction[0][label] / 2 if label == 1: result_text = "RealFace Score: {:.2f}".format(value) color = (255, 0, 0) else: result_text = "FakeFace Score: {:.2f}".format(value) color = (0, 0, 255) print("Prediction cost {:.2f} s".format(test_speed)) # 打印预测所花时间 cv2.rectangle( frame, (image_bbox[0], image_bbox[1]), (image_bbox[0] + image_bbox[2], image_bbox[1] + image_bbox[3]), color, 2) cv2.putText( frame, result_text, (image_bbox[0], image_bbox[1] - 5), cv2.FONT_HERSHEY_COMPLEX, 0.5 * frame.shape[0] / 1024, color) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() if __name__ == "__main__": desc = "test" parser = argparse.ArgumentParser(description=desc) parser.add_argument( "--device_id", type=int, default=0, help="which gpu id, [0/1/2/3]") parser.add_argument( "--model_dir", type=str, default="./resources/anti_spoof_models", help="model_lib used to test") args = parser.parse_args() test(args.model_dir, args.device_id)
from collections.abc import Sequence from dataclasses import dataclass, field from enum import Enum, auto from itertools import product from typing import Optional, Self @dataclass(slots=True, order=True, frozen=True) class Vector2d: x: int y: int def __add__(self, other: Self) -> Self: return self.__class__(self.x + other.x, self.y + other.y) def __sub__(self, other: Self) -> Self: return self.__class__(self.x - other.x, self.y - other.y) def __neg__(self) -> Self: return self.__class__(-self.x, -self.y) def __mul__(self, scalar: int): return self.__class__(self.x * scalar, self.y * scalar) def __repr__(self): return f"{self.__class__.__name__}({self.x}, {self.y})" def __hash__(self): return hash((self.x, self.y)) class Direction(Enum): east = auto() south = auto() west = auto() north = auto() @property def complement(self): match self: case self.east: return self.west case self.south: return self.north case self.west: return self.east case self.north: return self.south def as_vector(self): if self is self.east: return Vector2d(1, 0) elif self is self.south: return Vector2d(0, 1) elif self is self.west: return Vector2d(-1, 0) elif self is self.north: return Vector2d(0, -1) else: raise ValueError("Invalid direction") _infinity = float("+Infinity") @dataclass(slots=True) class Node: position: Vector2d content: str edges: list['Edge'] = field(default_factory=list) visited: bool = False def add_edge(self: Self, edge: 'Edge') -> None: if edge not in self.edges: self.edges.append(edge) def __repr__(self): name = self.__class__.__name__ return f"{name}({self.position})" def __hash__(self): return id(self) @dataclass(slots=True) class Edge: cost: int target: Node def build_paths(data: Sequence[str], slopes: bool) -> tuple[dict[Vector2d, Node], Vector2d, Vector2d]: width, height = len(data[0]), len(data) start = Vector2d(data[0].index('.'), 0) end = Vector2d(data[-1].index('.'), height - 1) SLOPE_DIRECTIONS = { '>': Direction.east, 'v': Direction.south, '<': Direction.west, '^': Direction.north, } nodes: dict[Vector2d, Node] = { pos: Node(pos, data[pos.y][pos.x]) for pos in ( Vector2d(x, y) for y, x in product(range(height), range(width)) if data[y][x] != '#' ) } for position, node in nodes.items(): for direction in Direction: target_position = position + direction.as_vector() target = nodes.get(target_position) if not target: continue if slopes and direction.complement == SLOPE_DIRECTIONS.get(target.content): continue node.add_edge(Edge(1, target)) simplify(nodes) return nodes, start, end def get_reciprocal_edge(source: Node, target: Node) -> Optional[Edge]: return next(filter(lambda e: e.target is source, target.edges), None) def detach_node(node: Node) -> None: target_a, target_b = node.edges reciprocal_a, reciprocal_b = (get_reciprocal_edge(node, edge.target) for edge in node.edges) if reciprocal_a is None or reciprocal_b is None: return reciprocal_a.target = target_b.target reciprocal_a.cost += target_b.cost reciprocal_b.target = target_a.target reciprocal_b.cost += target_a.cost node.edges.clear() def simplify(nodes: dict[Vector2d, Node]) -> None: """ Simplify graph by removing non-terminal and non-branching nodes, and updating the neighboring nodes' edges """ to_remove: list[Vector2d] = [] for node in nodes.values(): if len(node.edges) != 2: continue if all(edge.target.content in '>v<^' for edge in node.edges): continue detach_node(node) to_remove.append(node.position) # Remove orphaned for position in to_remove: del nodes[position] def dfs(root: Node, target: Node) -> int: root.visited = True length = max( (edge.cost + dfs(edge.target, target) for edge in root.edges if not edge.target.visited), default=0 ) root.visited = False NON_EXIT_PENALTY = -1000000 if length == 0 and root is not target: length = NON_EXIT_PENALTY return length def solve_part1(data: Sequence[str]) -> int: paths, start, end = build_paths(data, slopes=True) path_lengths = dfs(paths[start], paths[end]) return path_lengths def solve_part2(data: Sequence[str]) -> int: paths, start, end = build_paths(data, slopes=False) path_lengths = dfs(paths[start], paths[end]) return path_lengths def main() -> None: with open("input/day23.txt", 'r') as data_file: data: list[str] = data_file.read().splitlines() print("Part 1:", solve_part1(data)) print("Part 2:", solve_part2(data)) if __name__ == '__main__': main()
import { instanceToPlain } from 'class-transformer'; import { Request, Response } from 'express'; import { container } from 'tsyringe'; import { userPerm, companyPerm } from '@config/constants'; import { AppError } from '@utils/AppError'; import { hasPermission } from '@utils/hasPermission'; import { UpdateUserService } from '@services/User/UpdateUser/UpdateUserService'; class UpdateUserController { private updateUserService: UpdateUserService; constructor() { this.updateUserService = container.resolve(UpdateUserService); } async handle(req: Request, res: Response): Promise<Response> { const { user_id, name, email, username, actived } = req.body; if ( !hasPermission(req.user, userPerm) && !hasPermission(req.user, companyPerm) ) { throw new AppError('Operação não permitida.', 403); } const user = await this.updateUserService.execute({ user_id, name: name.trim(), email: email.trim(), username: username.trim(), actived, reqUser: req.user, }); return res.status(200).json(instanceToPlain(user)); } } export { UpdateUserController };
import { Component, OnInit } from '@angular/core'; import { LocaleService, Locale, LocaleModel, DirectionService, Direction, } from '@core/services'; import { Observable } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit { constructor( private localeService: LocaleService, private directionService: DirectionService ) {} ngOnInit(): void { const body = document.querySelector('body'); this.directionService.direction$.subscribe((dir) => { body.setAttribute('dir', dir); }); this.localeService.locale$.subscribe((locale) => { body.classList.value = locale; }); } handleLocaleChange($event: Locale): void { this.localeService.changeLocale($event); window.location.reload(); } get availableLocales(): LocaleModel[] { return this.localeService.availableLocales; } get currentLocaleModel(): LocaleModel { return this.localeService.currentLocaleModel; } get direction$(): Observable<Direction> { return this.directionService.direction$; } get locale$(): Observable<Locale> { return this.localeService.locale$; } }
import { createContext, useState } from "react"; import runchat from "../config/gemini.js"; export const Context = createContext(); const ContextProvider = (props) => { const [input, setinput] = useState(""); const [recent_prompt, setrecent_prompt] = useState([]); const [previous_prompt, setprevious_prompt] = useState([]); const [result, setresult] = useState(""); const [loading, setloading] = useState(false); const [showresult, setshowresult] = useState(false); const delayparas = (index, nextword) => { setTimeout(() => { setresult((prev) => prev + nextword); }, 80 * index); }; const onSent = async () => { setresult(""); setloading(true); setshowresult(true); setrecent_prompt(input); const Response = await runchat(input); const responseArray = Response.split("**"); // console.log(responseArray); let newArray = []; for (let i = 0; i < responseArray.length; i++) { if (i % 2 == 0) { newArray = newArray + responseArray[i]; } else { newArray = newArray + " <b> " + responseArray[i] + "</b> "; } } let newArray2 = newArray.split("*").join("</br>"); let newresponse = newArray2.split(" "); for (let i = 0; i < newresponse.length; i++) { delayparas(i, newresponse[i] + " "); } setloading(false); setinput(""); }; const ContextValue = { input, setinput, recent_prompt, setrecent_prompt, previous_prompt, setprevious_prompt, result, setresult, loading, setloading, showresult, setshowresult, onSent, }; return ( <Context.Provider value={ContextValue}>{props.children}</Context.Provider> ); }; export default ContextProvider;
/** * Class representing a Balance Report, generated when calling [Book.getBalanceReport](#book_getbalancesreport) * * @public */ class BalancesReport { private wrapped: bkper.Balances; private book: Book; private groupBalancesContainers: GroupBalancesContainer[]; private accountBalancesContainers: AccountBalancesContainer[]; balancesContainersMap: { [name: string]: BalancesContainer }; constructor(book: Book, balancesReportPlain: bkper.Balances) { this.book = book; this.wrapped = balancesReportPlain; this.groupBalancesContainers = null; this.accountBalancesContainers = null; this.balancesContainersMap = null; } /** * The [[Book]] that generated the report. */ public getBook(): Book { return this.book; } /** * Creates a BalancesDataTableBuilder to generate a two-dimensional array with all [[BalancesContainers]]. */ public createDataTable(): BalancesDataTableBuilder { return new BalancesDataTableBuilder(this.book, this.getBalancesContainers(), this.getPeriodicity()); } /** * Gets all [[BalancesContainers]] of the report. */ public getBalancesContainers(): BalancesContainer[] { var containers = new Array<BalancesContainer>(); if (this.getRootAccountBalancesContainers() != null) { containers = containers.concat(this.getRootAccountBalancesContainers()); } if (this.getGroupBalancesContainers() != null) { containers = containers.concat(this.getGroupBalancesContainers()); } return containers; } /** * The [[Periodicity]] of the query used to generate the report. */ public getPeriodicity(): Periodicity { return this.wrapped.periodicity as Periodicity; } /** * Check if the report has only one Group specified on query. */ public hasOnlyOneGroup(): boolean { return this.getGroupBalancesContainers() != null && this.getGroupBalancesContainers().length == 1; } private getRootAccountBalancesContainers(): AccountBalancesContainer[] { if (this.accountBalancesContainers == null && this.wrapped.accountBalances != null) { this.accountBalancesContainers = []; for (var i = 0; i < this.wrapped.accountBalances.length; i++) { var accountBalance = this.wrapped.accountBalances[i]; var accountBalancesReport = new AccountBalancesContainer(null, this, accountBalance); this.accountBalancesContainers.push(accountBalancesReport); } } return this.accountBalancesContainers; } private getGroupBalancesContainers(): GroupBalancesContainer[] { if (this.groupBalancesContainers == null && this.wrapped.groupBalances != null) { this.groupBalancesContainers = []; for (var i = 0; i < this.wrapped.groupBalances.length; i++) { var grouBalances = this.wrapped.groupBalances[i]; var accGroupBalances = new GroupBalancesContainer(null, this, grouBalances); this.groupBalancesContainers.push(accGroupBalances); } } return this.groupBalancesContainers; } /** * Gets a specific [[BalancesContainer]]. * * @param name The [[Account]] name, [[Group]] name. */ public getBalancesContainer(name: string): BalancesContainer { const normalizedName = normalizeName(name); let rootContainers = this.getBalancesContainers(); if (rootContainers == null || rootContainers.length == 0) { throw `${name} not found`; } if (this.balancesContainersMap == null) { let balancesContainersMap: { [name: string]: BalancesContainer } = {}; this.balancesContainersMap = this.fillBalancesContainersMap(balancesContainersMap, rootContainers); } const balancesContainer = this.balancesContainersMap[normalizedName]; if (!balancesContainer) { throw `${name} not found`; } return balancesContainer; } private fillBalancesContainersMap(map: { [name: string]: BalancesContainer }, containers: BalancesContainer[]): { [name: string]: BalancesContainer } { for (let i = 0; i < containers.length; i++) { const container = containers[i]; if (!map[container.getNormalizedName()]) { map[container.getNormalizedName()] = container; } let nextContainers = container.getBalancesContainers(); if (nextContainers && nextContainers.length > 0) { this.fillBalancesContainersMap(map, container.getBalancesContainers()); } } return map; } /** * Gets all [[Account]] [[BalancesContainers]]. */ public getAccountBalancesContainers(): BalancesContainer[] { let leafContainers: BalancesContainer[] = []; for (const container of this.getBalancesContainers()) { leafContainers = leafContainers.concat(container.getAccountBalancesContainers()); } return leafContainers; } }
<script> export default { props: { searchTerm: { type: String, required: true, }, }, created() { this.games = []; this.fetchGames(); }, data() { return { games: null, }; }, watch: { searchTerm: function () { this.fetchGames(); }, }, methods: { fetchGames() { fetch(`https://www.cheapshark.com/api/1.0/deals?title=${this.searchTerm}`) .then((response) => response.json()) .then((games) => { this.games = games; }); }, }, }; </script> <style lang="scss" scoped> // IMPORTS/FONTS @import url("https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap"); // IMPORTS/FONTS .search-container { margin-top: 30px; display: flex; /* justify-content: center; */ flex-direction: column; align-items: center; gap: 40px; } .search-result { font-family: "Poppins", sans-serif; } .game-container { display: flex; flex-direction: column; gap: 40px; padding-top: 20px; align-items: center; font-size: 30px; text-decoration: underline; border-radius: 5px; padding-bottom: 30px; box-shadow: 0px 0px 30px 4px rgba(0, 0, 0, 1); cursor: pointer; width: 400px; height: 400px; } .image-source { width: 100%; } .no-game { display: flex; justify-content: center; font-size: 30px; font-family: "Poppins", sans-serif; margin-top: 40px; } </style> <template> <div v-if="games.length > 0" class="search-container"> <h1 class="search-result">Search Results for "{{ searchTerm }}"</h1> <div class="game-container" v-for="game in games" :key="game.gameID"> {{ game.title }} <img class="image-source" :src="game.thumb" alt="" /> </div> </div> <div class="no-game" v-else> There's no games with that name on sale, check in another time... </div> </template>
document.addEventListener('DOMContentLoaded', function () { const loginForm = document.querySelector('form'); const messageContainer = document.createElement('div'); messageContainer.id = 'message'; loginForm.appendChild(messageContainer); const campos = ['email', 'senha']; loginForm.addEventListener('submit', function (event) { event.preventDefault(); clearMessageContainer(); const email = document.getElementById('email').value.trim(); const senha = document.getElementById('senha').value; let isValid = true; if (email === '' || !validateEmail(email)) { displayErrorMessage('Email inválido ou em branco.', 'email'); isValid = false; } if (senha === '') { displayErrorMessage('Senha é obrigatória.', 'senha'); isValid = false; } if (isValid && email === '[email protected]' && senha === 'adm') { alert("Login realizado!"); window.location.href = './index.html'; } else if (isValid) { displayErrorMessage('Email ou senha incorretos.', 'senha'); } }); function displayErrorMessage(message, campoId) { let mensagemErro = document.getElementById(`${campoId}-erro`); if (!mensagemErro) { mensagemErro = document.createElement('span'); mensagemErro.id = `${campoId}-erro`; mensagemErro.classList.add('mensagem-erro'); document.getElementById(campoId).parentNode.insertBefore(mensagemErro, document.getElementById(campoId).nextSibling); } mensagemErro.textContent = message; mensagemErro.style.display = 'block'; } function validateEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } campos.forEach(campoId => { const campo = document.getElementById(campoId); campo.addEventListener('input', function () { const mensagemErro = document.getElementById(`${campoId}-erro`); if (mensagemErro) { mensagemErro.style.display = 'none'; } }); }); function clearMessageContainer() { messageContainer.innerHTML = ''; } const fecharFormularioBtn = document.getElementById('fecharFormulario'); fecharFormularioBtn.addEventListener('click', function () { window.location.href = './index.html'; }); });
/* LESSON 3 - Programming Tasks */ /* Profile Object */ let myProfile = { name: 'Spencer Quiner', photo: 'cse121b/images/ajwedding.jpg', favoriteFoods: [ 'Spagetti', 'Steak', 'Vanilla Ice Cream', 'Rueben Sandwich', 'Apples', 'Pizza', 'Baked Potatoes' ], hobbies: [ 'video games', 'reading', 'taking walks', 'board games', ], placesLived: [], }; /* Populate Profile Object with placesLive objects */ myProfile.placesLived.push( { place: 'Homer, AK', length: '6 years' } ) myProfile.placesLived.push( { place: 'Camp Lejune, NC', length: '4 years' } ) myProfile.placesLived.push( { place: 'Djibouti Africa', length: '1 year' } ) myProfile.placesLived.push( { place: 'Portland, OR', length: '7 years' } ) myProfile.placesLived.push( { place: 'Arrecife, Spain', length: '12 years' } ) /* DOM Manipulation - Output */ /* Name */ document.querySelector('#name').innerHTML = myProfile.name; /* Photo with attributes */ document.querySelector('#photo').setAttribute('src', myProfile.photo); document.querySelector('#photo').setAttribute('alt', myProfile.name); /* Favorite Foods List*/ const foodsElement = document.querySelector('#favorite-foods'); function createFoodItem(food) { let favoriteFood = document.createElement('li'); favoriteFood.textContent = food; foodsElement.appendChild(favoriteFood); } myProfile.favoriteFoods.forEach(createFoodItem); /* Hobbies List */ const hobbieList = document.querySelector('#hobbies'); function createHobby(hobby) { let newhobby = document.createElement('li'); newhobby.textContent = hobby; hobbieList.appendChild(newhobby); } myProfile.hobbies.forEach(createHobby); /* Places Lived DataList */ const placeList = document.querySelector('#places-lived'); myProfile.placesLived.forEach(place =>{newplace = document.createElement('dt'); newplace.textContent = place.place; newduration = document.createElement('dd'); newduration.textContent = place.length; placeList.append(newplace, newduration); });
import supertest from 'supertest'; import app from '../src/app'; import { LoginRequest } from '../src/routes/login'; describe('LOGIN', () => { it('shoud return a 200 (user)', () => { const payload: LoginRequest = { email: '[email protected]', password: 'pwd', }; supertest(app) .post('/api/v1/login') .send(payload) .expect(200) .then((response) => { expect(typeof response.body.access_token).toBe('string'); }); }); it('shoud return a 400 (user does not exist)', async () => { const payload: LoginRequest = { email: '[email protected]', password: 'pwd', }; await supertest(app).post('/api/v1/login').send(payload).expect(400, { message: 'Error. user don t exist', }); }); it('shoud return a 400 (bad paswword)', async () => { const payload: LoginRequest = { email: '[email protected]', password: 'pwddd', }; await supertest(app).post('/api/v1/login').send(payload).expect(400, { message: 'Error. bad password', }); }); });
import React, { memo } from 'react'; import { useSelector } from 'react-redux'; import { useGetFilteredCollectionSummaryLegacyQuery } from '../../network/services/mtgcbApi'; import { RootState } from '../../redux/rootReducer'; import SetTable from '../browse/SetTable'; interface ConnectedSetTableProps { userId: string; expansionsFirst: number; expansionsSkip: number; expansionsPage: number; setExpansionsSkip: (skip: number) => void; setExpansionsFirst: (first: number) => void; setExpansionsPage: (page: number) => void; } export const ConnectedSetTable: React.FC<ConnectedSetTableProps> = ({ userId, expansionsFirst, expansionsSkip, expansionsPage, setExpansionsSkip, setExpansionsFirst, setExpansionsPage, }) => { const { sortExpansionBy, sortExpansionByDirection, priceType, expansionTypes, expansionCategories, expansionSearchQuery, setCompletionStatuses, includeSubsets, includeSubsetGroups, includeSubsetsInSets, } = useSelector((state: RootState) => state.collection); const { data: collectionSummary, isLoading: isFilteredCollectionSummaryLoading, isFetching, error: filteredCollectionSummaryError, } = useGetFilteredCollectionSummaryLegacyQuery({ userId, priceType, first: expansionsFirst, skip: expansionsSkip, search: expansionSearchQuery, sortBy: sortExpansionBy, sortByDirection: sortExpansionByDirection, additionalSortBy: null, whereSetCompletionStatus: setCompletionStatuses ?? ['all'], setTypes: expansionTypes, setCategories: expansionCategories, includeSubsets, includeSubsetGroups, includeSubsetsInSets, }); const expansions = collectionSummary?.data?.filteredCollectionSummaryLegacy?.collectionSummary; const costsToPurchase = collectionSummary?.data?.filteredCollectionSummaryLegacy?.collectionSummary; const totalExpansionsResults = collectionSummary?.data?.filteredCollectionSummaryLegacy?.count ?? 0; return ( <MemoizedSetTable sets={expansions} costsToPurchase={costsToPurchase} totalResults={totalExpansionsResults} first={expansionsFirst} skip={expansionsSkip} page={expansionsPage} setSkip={setExpansionsSkip} setFirst={setExpansionsFirst} setPage={setExpansionsPage} priceType={priceType} userId={userId} isCollectorMode isFetching={isFetching} /> ); }; const MemoizedSetTable = memo(SetTable);
// // XMLParser.swift // Newsfeed // // Created by David Andreasson on 2018-06-19. // Copyright © 2018 David Andreasson. All rights reserved. // import UIKit struct RSSItem { var title: String var description: String var publicationDate: String var urlLink: String } class FeedParser: NSObject, XMLParserDelegate { private var rssItems: [RSSItem] = [] private var currentElement = "" private var currentTitle: String = "" { didSet { currentTitle = currentTitle.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } private var currentDescription: String = "" { didSet { currentDescription = currentDescription.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } private var currentPublicationDate: String = "" { didSet { currentPublicationDate = currentPublicationDate.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } private var currentUrlLink: String = "" { didSet { currentUrlLink = currentUrlLink.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } private var parserCompletionHandler: (([RSSItem]) -> Void)? func parseFeed(url: String, completionHandler: (([RSSItem]) -> Void)?) { self.parserCompletionHandler = completionHandler let request = URLRequest(url: URL(string: url)!) let urlSession = URLSession.shared let task = urlSession.dataTask(with: request) { (data, response, error) in guard let data = data else { if let error = error { print(error) } return } let parser = XMLParser(data: data) parser.delegate = self parser.parse() } task.resume() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { currentElement = elementName if currentElement == "item" { currentTitle = "" currentDescription = "" currentPublicationDate = "" currentUrlLink = "" } } func parser(_ parser: XMLParser, foundCharacters string: String) { switch currentElement { case "title": currentTitle += string case "description": currentDescription += string case "pubDate": currentPublicationDate += string case "link": currentUrlLink += string default: break } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "item" { let rssItem = RSSItem(title: currentTitle, description: currentDescription, publicationDate: currentPublicationDate, urlLink: currentUrlLink) self.rssItems.append(rssItem) } } func parserDidEndDocument(_ parser: XMLParser) { parserCompletionHandler?(rssItems) } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { print(parseError) } }
queue.h #pragma once #include <stdlib.h> #include <stdint.h> #include <string.h> typedef struct node_t node_t; typedef struct queue queue; struct node_t { node_t* next; void* value; }; struct queue { node_t* head; node_t* tail; size_t size; }; queue* queue_create(); void queue_push(queue* queue, void* item); void* queue_pop(queue* queue); void* queue_peek(queue* queue); void queue_destroy(queue* queue); queue.c #include "queue.h" queue* queue_create() { queue* q = malloc(sizeof(queue)); memset(q, 0, sizeof(queue)); return q; } void queue_push(queue* queue, void* item) { node_t* tail = queue->tail; node_t* next = malloc(sizeof(node_t)); next->next = NULL; next->value = item; if (tail) { tail->next = next; } else { queue->head = next; } queue->tail = next; ++queue->size; } void* queue_pop(queue* queue) { node_t* head = queue->head; if (head) { queue->head = head->next; void* item = head->value; if (!head->next) queue->tail = NULL; free(head); --queue->size; return item; } return NULL; } void* queue_peek(queue* queue) { node_t* head = queue->head; if (head) { void* item = head->value; return item; } return NULL; } void queue_destroy(queue* queue) { node_t* next = queue->head; while (next) { node_t* tmp = next->next; free(next); next = tmp; } free(queue); }
package com.example.demoapp; import static android.content.Context.MODE_PRIVATE; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.io.ByteArrayOutputStream; import java.util.List; import DanhSachSP.SanPham; public class FavoriteAdapter extends RecyclerView.Adapter<FavoriteAdapter.FavoriteViewHolder>{ private Context mContext; private List<FavoriteItem> favoriteItems; SanPhamDAO sanPhamDAO; SharedPreferences sharedPreferences; SharedPreferences.Editor editor; KhachHangDao khachHangDao; private static final String SHARED_PREF_NAME = "mypref"; private static final String KEY_USERNAME = "username"; public FavoriteAdapter(Context context,List<FavoriteItem> favoriteItems){ mContext = context; this.favoriteItems = favoriteItems; } @NonNull @Override public FavoriteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view= LayoutInflater.from(mContext).inflate(R.layout.item_favorite,parent,false); sanPhamDAO = new SanPhamDAO(mContext); khachHangDao = new KhachHangDao(mContext); sharedPreferences = mContext.getSharedPreferences(SHARED_PREF_NAME,MODE_PRIVATE); editor = sharedPreferences.edit(); return new FavoriteViewHolder(view); } @Override public void onBindViewHolder(@NonNull FavoriteViewHolder holder, int position) { FavoriteItem favoriteItem = favoriteItems.get(position); if(favoriteItem == null){ return; } float giaSp = favoriteItem.getGiaSP(); Bitmap bitmap = favoriteItem.getImageSP(); holder.imageSP.setImageBitmap(bitmap); holder.tenSP.setText(favoriteItem.getTenSP()); holder.giaSP.setText(String.format("%.0f",giaSp) + " vnđ"); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, DetailSPActivity.class); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Bitmap bitmap =favoriteItem.getImageSP(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); intent.putExtra("tensp",favoriteItem.getTenSP()); intent.putExtra("ttsp",favoriteItem.getThongTinSP()); intent.putExtra("giasp",favoriteItem.getGiaSP()); intent.putExtra("imagesp",byteArray); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); ((Activity) mContext).overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); } }); } @Override public int getItemCount() { return favoriteItems.size(); } public class FavoriteViewHolder extends RecyclerView.ViewHolder{ TextView tenSP,giaSP; ImageView imageSP,imageFavorited; public FavoriteViewHolder(@NonNull View itemView) { super(itemView); tenSP = itemView.findViewById(R.id.tv_tenspfv); giaSP = itemView.findViewById(R.id.tv_giaspfav); imageSP = itemView.findViewById(R.id.imageSPfav); imageFavorited = itemView.findViewById(R.id.img_favorited); imageFavorited.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = getAdapterPosition(); khachHangDao = new KhachHangDao(mContext); String name = sharedPreferences.getString(KEY_USERNAME,null); final FavoriteItem favoriteItem = favoriteItems.get(position); if(sanPhamDAO.removeFavorite(mContext,favoriteItem.getMasp(),favoriteItem.getTenKh())){ Toast.makeText(mContext,"Xóa khỏi danh sách yêu thích thành công",Toast.LENGTH_SHORT).show(); sanPhamDAO.deleteFavorite(mContext,favoriteItem.getMasp(),favoriteItem.getTenKh()); removeItem(position); notifyDataSetChanged(); } else{ Toast.makeText(mContext,"Xóa khỏi danh sách yêu thích thất bại",Toast.LENGTH_SHORT).show(); } } }); } } private void removeItem(int position) { favoriteItems.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position,favoriteItems.size()); } }
package fileReader import model.* import java.io.File class SamuraiFileReader : IFileReader { override fun parseSudoku(file: File): SudokuModel { val builder = SudokuModelBuilder() builder.height(21) builder.width(21) builder.addValidCharacters(('1'.. '9').toSet()) val content = readFile(file).chunked(81) val grids = mutableListOf<Array<Array<SudokuCell>>>() val cells = HashMap<Pair<Int, Int>, SudokuCell>() for (i in 0..4) { val startCoords = getStartCoordinates(i) val grid = Array(9) { row -> Array(9) { col -> val index = row * 9 + col val value = content[i][index].digitToInt() val cellCoords = Pair(startCoords.first + col, startCoords.second + row) val cell = cells.getOrPut(cellCoords) { getCell(value, cellCoords.first, cellCoords.second) } //overwrite if previous is 0 and current is not 0 if (cell.value.value == 0 && value != 0) { cell.value = CellValue(value, CellState.PROVIDED) } cell } } grids.add(grid) builder.addGroups(createRows(grid)) builder.addGroups(createColumns(grid)) builder.addGroups(createBlocks(grid, 3, 3)) } return builder.build() } /** * Returns the starting coordinates of the grid at the given index. * @param index The index of the grid. * @return The starting coordinates of the grid in the format (x, y). * @TODO: This is a bit of a hack. It would be better to be able to calculate the coordinates. However, currently this is out of the scope of the project. */ private fun getStartCoordinates(index: Int): Pair<Int, Int> { when (index) { 0 -> return Pair(0, 0) 1 -> return Pair(12, 0) 2 -> return Pair(6, 6) 3 -> return Pair(0, 12) 4 -> return Pair(12, 12) } throw IllegalArgumentException("Invalid index") } companion object { fun register() { FileReaderFactory.registerFileReader(SamuraiFileReader(), "samurai") } } }
import React from "react"; import "../stylesheets/HelpPageStylesheets/HelpPage.css"; import EndUseNavbar from "../components/EndUseNavbar"; import { motion } from "framer-motion"; import BtnDropDown from "../components/BtnDropDown"; import { useState, useEffect } from "react"; import { useParams } from "react-router-dom" import axios from "axios" import useAxiosPrivate from '../hooks/useAxiosPrivate' function HelpPage() { const axiosPrivate = useAxiosPrivate() const { id } = useParams(); const [userName, setUserName] = useState("") useEffect(()=>{ //Conseguir nombre de ususario const getUsername = async() =>{ const response = await axiosPrivate.get( `/GetUsername/${id}` ) setUserName(response.data.username[0].nombre) console.log(response) } getUsername(); },[]) return ( <> <div className="wrapper-hp"> <EndUseNavbar grabarId="" análisisId="" ayudaId="ayuda" userName={userName}/> <div className="texts-header"> <motion.div className="text-header-content" initial={{ opacity: 0, y: 75, }} whileInView={{ opacity: 1, y: 0, transition: { delay: 0.3, type: "tween", ease: "easeOut", duration: 0.75, }, }} viewport={{ once: true, }} > <p>FAQs (Preguntas Frecuentes)</p> <h1>¿En qué podemos ayudarte?</h1> </motion.div> </div> <motion.div className="divider-hp" animate={{ width: "80%", }} transition={{ duration: 1.5, ease: "easeOut", }} viewport={{ once: true, }} ></motion.div> <motion.section className="faqs" initial={{ opacity: 0, y: 60, }} whileInView={{ opacity: 1, y: 0, transition: { delay: 0.5, type: "tween", ease: "easeOut", duration: 0.75, }, }} > <div className="faqs-content"> <BtnDropDown questionText={"¿Cómo colocar la cámara para mis análisis?"} answerText={ "Coloque la cámara un par de metros detrás de usted a una altura considerable (al menos 2 metros y medio). Asegúrese de que toda la cancha sea visible para optimizar el análisis" } /> <BtnDropDown questionText={"¿Cómo subir un video?"} answerText={ "En la sección de grabar, complete el formulario e inserte el video que desea analizar, luego se desplegará una imagen del video y unos botones que debe arrastrar hacia las esquinas de la cancha" } /> <BtnDropDown questionText={"¿Cuánto tarda en subir un video?"} answerText={ "Depende de la duración" } /> <BtnDropDown questionText={"¿Por qué son tan capos?"} answerText={ "Porque tenemos a Ary Bacher" } /> <BtnDropDown questionText={"¿Cómo colocar la cámara para mis análisis?"} answerText={ "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iste quibusdam harum totam aperiam voluptates similique, aliquid aliquam amet sunt accusamus repellat quo repudiandae blanditiis tempora dolores numquam ducimus? Maiores quam, rem, eveniet quasi minus, ducimus ab voluptates tempora fugit quia officia perferendis nam unde! Suscipit quod a magni impedit asperiores!" } /> <BtnDropDown questionText={"¿Cómo colocar la cámara para mis análisis?"} answerText={ "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iste quibusdam harum totam aperiam voluptates similique, aliquid aliquam amet sunt accusamus repellat quo repudiandae blanditiis tempora dolores numquam ducimus? Maiores quam, rem, eveniet quasi minus, ducimus ab voluptates tempora fugit quia officia perferendis nam unde! Suscipit quod a magni impedit asperiores!" } /> <BtnDropDown questionText={"¿Cómo colocar la cámara para mis análisis?"} answerText={ "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iste quibusdam harum totam aperiam voluptates similique, aliquid aliquam amet sunt accusamus repellat quo repudiandae blanditiis tempora dolores numquam ducimus? Maiores quam, rem, eveniet quasi minus, ducimus ab voluptates tempora fugit quia officia perferendis nam unde! Suscipit quod a magni impedit asperiores!" } /> <BtnDropDown questionText={"¿Cómo colocar la cámara para mis análisis?"} answerText={ "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iste quibusdam harum totam aperiam voluptates similique, aliquid aliquam amet sunt accusamus repellat quo repudiandae blanditiis tempora dolores numquam ducimus? Maiores quam, rem, eveniet quasi minus, ducimus ab voluptates tempora fugit quia officia perferendis nam unde! Suscipit quod a magni impedit asperiores!" } /> </div> </motion.section> </div> </> ); } export default HelpPage;
import { Browser } from "@data-objects/general/platform"; import TestRunInfo from "@data-objects/general/test-run-info"; import { CallingList } from "@data-objects/inContact/central/personal-connection/lists/calling/calling-list"; import NavigationBar from "@page-objects/inContact/central/general/navigation-bar"; import { FunctionType, Logger } from '@utilities/general/logger'; import { Utility } from "@utilities/general/utility"; import ElementWrapper from "@utilities/protractor-wrappers/element-wrapper"; import { errorwrapper } from "@utilities/protractor-wrappers/error-wrapper"; import SelectElementWrapper from "@utilities/protractor-wrappers/select-element-wrapper"; import { by } from "protractor"; export default class CallingListUploadPage extends NavigationBar { private static _callingListUploadPage: CallingListUploadPage = null; protected txtListName = new ElementWrapper(by.xpath("//input[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_uctUpload_txtListName']")); protected cbbSkill = new SelectElementWrapper(by.xpath("//select[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_uctUpload_ddlSkills']")); protected uploadFile = new ElementWrapper(by.xpath("//input[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_uctUpload_uploadFileSelector_ctlFileUpload']")); protected formCallingListUpload = new ElementWrapper(by.xpath("//div[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_uctUpload_upnlAddressBook']")); protected btnNext = new ElementWrapper(by.xpath("//button[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_btnNext_ShadowButton']")); protected spanImportStatus = new ElementWrapper(by.xpath("//span[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_lblImportStatus']")); protected imgSpinner = new ElementWrapper(by.xpath("//td[@class='form_details']//img[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_imgSpinner']")); protected spanSucceeded = new ElementWrapper(by.xpath("//span[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_Content_lblImportStatus'][text()='Succeeded']")); protected spanNameOtherDetail = new ElementWrapper(by.xpath("//div[@id='ctl00_ctl00_ctl00_ctl00_BaseContent_Content_ManagerContent_whMainNav']//li[@class='current']//span[text()='Name & Other Details']")); public static getInstance(): CallingListUploadPage { this._callingListUploadPage = new CallingListUploadPage(); return this._callingListUploadPage; } /** * Check Calling list upload page is displayed or not * @returns {Promise<boolean>} the existence of Calling list upload page * @memberof CallingListUploadPage */ public async isPageDisplayed(): Promise<boolean> { try { return await this.formCallingListUpload.isDisplayed(); } catch (err) { throw new errorwrapper.CustomError(this.isPageDisplayed, err.message); } } /** * Select skill * @param skillName Skill name want to select * @returns {Promise<CallingListUploadPage>} Calling list upload page * @memberof CallingListUploadPage */ public async selectSkill(skillName: string): Promise<CallingListUploadPage> { try { await Logger.write(FunctionType.UI, `Selecting '${skillName}' skill`); await this.cbbSkill.selectOptionByText(skillName); return this; } catch (err) { throw new errorwrapper.CustomError(this.selectSkill, err.message); } } /** * Fill data in Calling list upload page * @param {CallingList} callingList information of callingList to create * @returns {Promise<CallingListUploadPage>} Calling list upload page * @memberof CallingListUploadPage */ public async fillCallingList(callingList: CallingList): Promise<CallingListUploadPage> { try { await Logger.write(FunctionType.UI, "Filling fields in Calling List"); await this.txtListName.type(callingList.listName); await this.selectSkill(callingList.skillName); await this.uploadFile.uploadFile(callingList.listCallingFile); return this; } catch (err) { throw new errorwrapper.CustomError(this.fillCallingList, err.message); } } /** * Get list name is entered * @returns {Promise<string>} inputted list name * @memberof CallingListUploadPage */ public async getEnteredListName(): Promise<string> { try { return await this.txtListName.getControlValue(); } catch (err) { throw new errorwrapper.CustomError(this.getEnteredListName, err.message); } } /** * Get skill name is selected * @returns {Promise<string>} skill name * @memberof CallingListUploadPage */ public async getSkillSelected(): Promise<string> { try { return await this.cbbSkill.getSelectedItem(); } catch (err) { throw new errorwrapper.CustomError(this.getSkillSelected, err.message); } } /** * Get file name is uploaded * @returns {Promise<string>} inputted file name * @memberof CallingListUploadPage */ public async getUploadedFileName(): Promise<string> { try { let lengthSplitString: number; if (TestRunInfo.browser == Browser.IE) { let fileCalling = Utility.getPath("src/test-data/inContact/"); lengthSplitString = fileCalling.length; } else { lengthSplitString = "C:\\fakepath\\".length; } let filePath: string = await this.uploadFile.getControlValue(); let lengthFilePath: number = await filePath.length; return await filePath.slice(lengthSplitString, lengthFilePath); } catch (err) { throw new errorwrapper.CustomError(this.getUploadedFileName, err.message); } } /** * Click next button * @returns {Promise<CallingListUploadPage>} Calling list upload page * @memberof CallingListUploadPage */ public async clickNext(): Promise<CallingListUploadPage> { try { await Logger.write(FunctionType.UI, "Going to next step"); await this.btnNext.click(); return this; } catch (err) { throw new errorwrapper.CustomError(this.clickNext, err.message); } } /** * Wait for next step * @returns {Promise<CallingListUploadPage>} Calling list upload page * @memberof CallingListUploadPage */ public async waitForNextStep(): Promise<CallingListUploadPage> { if (await this.spanNameOtherDetail.isDisplayed()) { await this.spanNameOtherDetail.waitUntilDisappear(); } return this; } /** * Wait for calling list upload * @returns {Promise<CallingListUploadPage>} Calling list upload page * @memberof CallingListUploadPage */ public async waitForCallingListUpload(): Promise<CallingListUploadPage> { try { await this.imgSpinner.waitUntilDisappear(); await this.spanSucceeded.wait(); return this; } catch (err) { throw new errorwrapper.CustomError(this.waitForCallingListUpload, err.message); } } /** * Get import status * @returns {Promise<string>} status * @memberof CallingListUploadPage */ public async getImportStatus(): Promise<string> { try { await this.waitForCallingListUpload(); return await this.spanImportStatus.getText(); } catch (err) { throw new errorwrapper.CustomError(this.getImportStatus, err.message); } } }
import React, {useState} from 'react'; type UnControlledOnOffPropsType = { onChange: (value: boolean) => void defaultOn?: boolean } export function UnControlledOnOffSecret(props: UnControlledOnOffPropsType) { let [on, setOn] = useState<boolean>(props.defaultOn? props.defaultOn : false) const changeFilter = (value: boolean) => { setOn(value) } const onClicked = () => { changeFilter(true) props.onChange(true) } const offClicked = () => { changeFilter(false) props.onChange(false) } let container = { display: "flex", gap: "10px", } let turnOnStyle = { display: "flex", alignItems: "center", justifyContent: "center", width: "50px", height: "20px", border: "1px solid black", backgroundColor: on? "green" : "white", } let turnOffStyle = { display: "flex", alignItems: "center", justifyContent: "center", width: "50px", height: "20px", border: "1px solid black", backgroundColor: !on? "red" : "white" } let lampStyle = { width: "20px", height: "20px", borderRadius: "50%", backgroundColor: on? "green" : "red", } return ( <div style={container}> <button style={turnOnStyle} onClick={onClicked}> on </button> <button style={turnOffStyle} onClick={offClicked}> off </button> <div style={lampStyle}> </div> </div> ) } export const UnControlledOnOff = React.memo(UnControlledOnOffSecret)
import React from "react"; function Characters({ characters }) { return ( <div className="characters-container"> {characters .sort((a, b) => (a.name > b.name ? 1 : -1)) .map((char) => { return ( <div key={char.name} className="characters"> <div className="characters__name-container"> <div className="characters__name"> {char.name} </div> </div> <div className="characters__description-container"> <div>Birth year: {char.birth_year}</div> <div>Eye color: {char.eye_color}</div> <div>Gender: {char.gender}</div> <div>Hair color: {char.hair_color}</div> <div>Height: {char.height}</div> <div>Mass: {char.mass}</div> <div>Skin color: {char.skin_color}</div> </div> </div> ); })} </div> ); } export default Characters;
/** -*- mode: c++ -*- * @file libcpp/include/atomic * @author Peter Züger * @date 15.12.2018 * @note part of the freestanding headers * @brief std::atomic's * * This file is part of libcpp (https://gitlab.com/peterzuger/libcpp). * Copyright (c) 2019 Peter Züger. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * 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/>. */ #ifndef __ATOMIC__ #define __ATOMIC__ #include <cstddef> #include <cstdint> namespace std{ // 32.4, order and consistency enum memory_order{ memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst }; template<class T> T kill_dependency(T y)noexcept; // 32.5, lock-free property #if defined(__CLANG_ATOMIC_BOOL_LOCK_FREE) # define ATOMIC_BOOL_LOCK_FREE __CLANG_ATOMIC_BOOL_LOCK_FREE # define ATOMIC_CHAR_LOCK_FREE __CLANG_ATOMIC_CHAR_LOCK_FREE # if defined(char8_t) # define ATOMIC_CHAR8_T_LOCK_FREE __CLANG_ATOMIC_CHAR8_T_LOCK_FREE # endif /* defined(char8_t) */ # define ATOMIC_CHAR16_T_LOCK_FREE __CLANG_ATOMIC_CHAR16_T_LOCK_FREE # define ATOMIC_CHAR32_T_LOCK_FREE __CLANG_ATOMIC_CHAR32_T_LOCK_FREE # define ATOMIC_WCHAR_T_LOCK_FREE __CLANG_ATOMIC_WCHAR_T_LOCK_FREE # define ATOMIC_SHORT_LOCK_FREE __CLANG_ATOMIC_SHORT_LOCK_FREE # define ATOMIC_INT_LOCK_FREE __CLANG_ATOMIC_INT_LOCK_FREE # define ATOMIC_LONG_LOCK_FREE __CLANG_ATOMIC_LONG_LOCK_FREE # define ATOMIC_LLONG_LOCK_FREE __CLANG_ATOMIC_LLONG_LOCK_FREE # define ATOMIC_POINTER_LOCK_FREE __CLANG_ATOMIC_POINTER_LOCK_FREE #elif defined(__GCC_ATOMIC_BOOL_LOCK_FREE) # define ATOMIC_BOOL_LOCK_FREE __GCC_ATOMIC_BOOL_LOCK_FREE # define ATOMIC_CHAR_LOCK_FREE __GCC_ATOMIC_CHAR_LOCK_FREE # if defined(char8_t) # define ATOMIC_CHAR8_T_LOCK_FREE __GCC_ATOMIC_CHAR8_T_LOCK_FREE # endif /* defined(char8_t) */ # define ATOMIC_CHAR16_T_LOCK_FREE __GCC_ATOMIC_CHAR16_T_LOCK_FREE # define ATOMIC_CHAR32_T_LOCK_FREE __GCC_ATOMIC_CHAR32_T_LOCK_FREE # define ATOMIC_WCHAR_T_LOCK_FREE __GCC_ATOMIC_WCHAR_T_LOCK_FREE # define ATOMIC_SHORT_LOCK_FREE __GCC_ATOMIC_SHORT_LOCK_FREE # define ATOMIC_INT_LOCK_FREE __GCC_ATOMIC_INT_LOCK_FREE # define ATOMIC_LONG_LOCK_FREE __GCC_ATOMIC_LONG_LOCK_FREE # define ATOMIC_LLONG_LOCK_FREE __GCC_ATOMIC_LLONG_LOCK_FREE # define ATOMIC_POINTER_LOCK_FREE __GCC_ATOMIC_POINTER_LOCK_FREE #endif // 32.6, atomic template<class T> struct atomic{ using value_type = T; static constexpr bool is_always_lock_free = false; bool is_lock_free()const volatile noexcept; bool is_lock_free()const noexcept; void store(T, memory_order = memory_order_seq_cst)volatile noexcept; void store(T, memory_order = memory_order_seq_cst)noexcept; T load(memory_order = memory_order_seq_cst)const volatile noexcept; T load(memory_order = memory_order_seq_cst)const noexcept; operator T()const volatile noexcept; operator T()const noexcept; T exchange(T, memory_order = memory_order_seq_cst)volatile noexcept; T exchange(T, memory_order = memory_order_seq_cst)noexcept; bool compare_exchange_weak(T&, T, memory_order, memory_order)volatile noexcept; bool compare_exchange_weak(T&, T, memory_order, memory_order)noexcept; bool compare_exchange_strong(T&, T, memory_order, memory_order)volatile noexcept; bool compare_exchange_strong(T&, T, memory_order, memory_order)noexcept; bool compare_exchange_weak(T&, T, memory_order = memory_order_seq_cst)volatile noexcept; bool compare_exchange_weak(T&, T, memory_order = memory_order_seq_cst)noexcept; bool compare_exchange_strong(T&, T, memory_order = memory_order_seq_cst)volatile noexcept; bool compare_exchange_strong(T&, T, memory_order = memory_order_seq_cst)noexcept; atomic()noexcept = default; constexpr atomic(T)noexcept; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&)volatile = delete; T operator=(T)volatile noexcept; T operator=(T)noexcept; }; // 32.6.3, partial specialization for pointers template<class T> struct atomic<T*>; // 32.7, non-member functions template<class T> bool atomic_is_lock_free(const volatile atomic<T>*)noexcept; template<class T> bool atomic_is_lock_free(const atomic<T>*)noexcept; template<class T> void atomic_init(volatile atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> void atomic_init(atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> void atomic_store(volatile atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> void atomic_store(atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> void atomic_store_explicit(volatile atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> void atomic_store_explicit(atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> T atomic_load(const volatile atomic<T>*)noexcept; template<class T> T atomic_load(const atomic<T>*)noexcept; template<class T> T atomic_load_explicit(const volatile atomic<T>*, memory_order)noexcept; template<class T> T atomic_load_explicit(const atomic<T>*, memory_order)noexcept; template<class T> T atomic_exchange(volatile atomic<T>*, T)noexcept; template<class T> T atomic_exchange(atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> T atomic_exchange_explicit(volatile atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> T atomic_exchange_explicit(atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> bool atomic_compare_exchange_weak(volatile atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type)noexcept; template<class T> bool atomic_compare_exchange_weak(atomic<T>*,typename atomic<T>::value_type*, typename atomic<T>::value_type)noexcept; template<class T> bool atomic_compare_exchange_strong(volatile atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type)noexcept; template<class T> bool atomic_compare_exchange_strong(atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type)noexcept; template<class T> bool atomic_compare_exchange_weak_explicit(volatile atomic<T>*,typename atomic<T>::value_type*, typename atomic<T>::value_type, memory_order, memory_order)noexcept; template<class T> bool atomic_compare_exchange_weak_explicit(atomic<T>*,typename atomic<T>::value_type*, typename atomic<T>::value_type, memory_order, memory_order)noexcept; template<class T> bool atomic_compare_exchange_strong_explicit(volatile atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type,memory_order, memory_order)noexcept; template<class T> bool atomic_compare_exchange_strong_explicit(atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type,memory_order, memory_order)noexcept; template<class T> T atomic_fetch_add(volatile atomic<T>*, typename atomic<T>::difference_type)noexcept; template<class T> T atomic_fetch_add(atomic<T>*, typename atomic<T>::difference_type)noexcept; template<class T> T atomic_fetch_add_explicit(volatile atomic<T>*, typename atomic<T>::difference_type,memory_order)noexcept; template<class T> T atomic_fetch_add_explicit(atomic<T>*, typename atomic<T>::difference_type,memory_order)noexcept; template<class T> T atomic_fetch_sub(volatile atomic<T>*, typename atomic<T>::difference_type)noexcept; template<class T> T atomic_fetch_sub(atomic<T>*, typename atomic<T>::difference_type)noexcept; template<class T> T atomic_fetch_sub_explicit(volatile atomic<T>*, typename atomic<T>::difference_type, memory_order)noexcept; template<class T> T atomic_fetch_sub_explicit(atomic<T>*, typename atomic<T>::difference_type,memory_order)noexcept; template<class T> T atomic_fetch_and(volatile atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> T atomic_fetch_and(atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> T atomic_fetch_and_explicit(volatile atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> T atomic_fetch_and_explicit(atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> T atomic_fetch_or(volatile atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> T atomic_fetch_or(atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> T atomic_fetch_or_explicit(volatile atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> T atomic_fetch_or_explicit(atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> T atomic_fetch_xor(volatile atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> T atomic_fetch_xor(atomic<T>*, typename atomic<T>::value_type)noexcept; template<class T> T atomic_fetch_xor_explicit(volatile atomic<T>*, typename atomic<T>::value_type,memory_order)noexcept; template<class T> T atomic_fetch_xor_explicit(atomic<T>*, typename atomic<T>::value_type, memory_order)noexcept; // 32.6.1, initialization #define ATOMIC_VAR_INIT(value) {value} // 32.3, type aliases using atomic_bool = atomic<bool>; using atomic_char = atomic<char>; using atomic_schar = atomic<signed char>; using atomic_uchar = atomic<unsigned char>; using atomic_short = atomic<short>; using atomic_ushort = atomic<unsigned short>; using atomic_int = atomic<int>; using atomic_uint = atomic<unsigned int>; using atomic_long = atomic<long>; using atomic_ulong = atomic<unsigned long>; using atomic_llong = atomic<long long>; using atomic_ullong = atomic<unsigned long long>; using atomic_char16_t = atomic<char16_t>; using atomic_char32_t = atomic<char32_t>; using atomic_wchar_t = atomic<wchar_t>; using atomic_int8_t = atomic<std::int8_t>; using atomic_uint8_t = atomic<std::uint8_t>; using atomic_int16_t = atomic<std::int16_t>; using atomic_uint16_t = atomic<std::uint16_t>; using atomic_int32_t = atomic<std::int32_t>; using atomic_uint32_t = atomic<std::uint32_t>; using atomic_int64_t = atomic<std::int64_t>; using atomic_uint64_t = atomic<std::uint64_t>; using atomic_int_least8_t = atomic<std::int_least8_t>; using atomic_uint_least8_t = atomic<std::uint_least8_t>; using atomic_int_least16_t = atomic<std::int_least16_t>; using atomic_uint_least16_t = atomic<std::uint_least16_t>; using atomic_int_least32_t = atomic<std::int_least32_t>; using atomic_uint_least32_t = atomic<std::uint_least32_t>; using atomic_int_least64_t = atomic<std::int_least64_t>; using atomic_uint_least64_t = atomic<std::uint_least64_t>; using atomic_int_fast8_t = atomic<std::int_fast8_t>; using atomic_uint_fast8_t = atomic<std::uint_fast8_t>; using atomic_int_fast16_t = atomic<std::int_fast16_t>; using atomic_uint_fast16_t = atomic<std::uint_fast16_t>; using atomic_int_fast32_t = atomic<std::int_fast32_t>; using atomic_uint_fast32_t = atomic<std::uint_fast32_t>; using atomic_int_fast64_t = atomic<std::int_fast64_t>; using atomic_uint_fast64_t = atomic<std::uint_fast64_t>; using atomic_intptr_t = atomic<std::intptr_t>; using atomic_uintptr_t = atomic<std::uintptr_t>; using atomic_size_t = atomic<std::size_t>; using atomic_ptrdiff_t = atomic<std::ptrdiff_t>; using atomic_intmax_t = atomic<std::intmax_t>; using atomic_uintmax_t = atomic<std::uintmax_t>; // 32.8, flag type and operations struct atomic_flag{ bool test_and_set(memory_order = memory_order_seq_cst)volatile noexcept; bool test_and_set(memory_order = memory_order_seq_cst)noexcept; void clear(memory_order = memory_order_seq_cst)volatile noexcept; void clear(memory_order = memory_order_seq_cst)noexcept; atomic_flag()noexcept = default; atomic_flag(const atomic_flag&) = delete; atomic_flag& operator=(const atomic_flag&) = delete; atomic_flag& operator=(const atomic_flag&)volatile = delete; }; bool atomic_flag_test_and_set(volatile atomic_flag*)noexcept; bool atomic_flag_test_and_set(atomic_flag*)noexcept; bool atomic_flag_test_and_set_explicit(volatile atomic_flag*, memory_order)noexcept; bool atomic_flag_test_and_set_explicit(atomic_flag*, memory_order)noexcept; void atomic_flag_clear(volatile atomic_flag*)noexcept; void atomic_flag_clear(atomic_flag*)noexcept; void atomic_flag_clear_explicit(volatile atomic_flag*, memory_order)noexcept; void atomic_flag_clear_explicit(atomic_flag*, memory_order)noexcept; #define ATOMIC_FLAG_INIT {false} // 32.9, fences extern "C" void atomic_thread_fence(memory_order)noexcept; extern "C" void atomic_signal_fence(memory_order)noexcept; } #endif /* __ATOMIC__ */
import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn, BeforeInsert, } from 'typeorm'; import { Account } from '.'; import { hashSync } from 'bcrypt'; @Entity('users') export class User { @PrimaryGeneratedColumn('uuid') id: string; @Column({ name: 'username', nullable: false, unique: true }) username: string; @Column({ name: 'password', nullable: false }) password: string; @OneToOne(() => Account, { eager: true, cascade: true, onDelete: 'CASCADE', }) @JoinColumn([{ name: 'accountId', referencedColumnName: 'id' }]) account: Account; @Column() accountId: string; @BeforeInsert() hashPassword() { this.password = hashSync(this.password, 10); } }
use std::sync::Arc; use axum::{ extract::{Path, State}, Extension, Json, }; use chrono::Utc; use log::info; use serde::{Deserialize, Serialize}; use crate::{ appstate::AppState, middleware::request_tracing::RequestTraceData, model::{amount::Amount, error::ApiError, transaction::Transaction}, }; #[derive(Debug, Deserialize, Serialize)] pub struct GiveMoney { pub amount: Amount, pub purpose: String, } #[derive(Debug, PartialEq)] enum TransactionType { Give, Spend, } fn validate_request_body(give_money: &GiveMoney) -> Result<(), ApiError> { if !give_money.amount.is_positive_nonzero() { return Err(ApiError::InputFailedValidation(String::from( "Amount must be at least 0.01", ))); } if give_money.purpose.len() == 0 { return Err(ApiError::InputFailedValidation(String::from( "Must provide a purpose", ))); } return Ok(()); } async fn record_transaction( app_state: Arc<AppState>, child_name: String, request_trace_data: RequestTraceData, give_money: GiveMoney, transaction_type: TransactionType, ) -> Result<Json<Transaction>, ApiError> { let request_id = request_trace_data.get_id(); info!( "[{}] {:?} called with {:?}", request_id, transaction_type, give_money ); validate_request_body(&give_money)?; let mut amount = give_money.amount; if transaction_type == TransactionType::Spend { amount = amount.negate(); } let persisted_transaction = app_state .get_db() .record_transaction_for_child(Transaction::new( 0, Utc::now(), child_name.clone(), amount, give_money.purpose.clone(), ))?; app_state .queue_messages_to_active_websockets_for_child( child_name.clone(), crate::model::websocket_msg::WebSocketMsg::Transaction(persisted_transaction.clone()), ) .await; Ok(Json(persisted_transaction)) } pub async fn give( State(app_state): State<Arc<AppState>>, Path(child_name): Path<String>, Extension(request_trace_data): Extension<RequestTraceData>, Json(give_money): Json<GiveMoney>, ) -> Result<Json<Transaction>, ApiError> { record_transaction( app_state, child_name, request_trace_data, give_money, TransactionType::Give, ) .await } pub async fn spend( State(app_state): State<Arc<AppState>>, Path(child_name): Path<String>, Extension(request_trace_data): Extension<RequestTraceData>, Json(give_money): Json<GiveMoney>, ) -> Result<Json<Transaction>, ApiError> { record_transaction( app_state, child_name, request_trace_data, give_money, TransactionType::Spend, ) .await }
<template> <div> <div class="pb-2 flex justify-end"> <router-link to="/estimate-create" tag="button" class="button mr-1 is-rounded"> <span class="icon"> <i class="fa fa-plus-circle mr-1"></i> </span> <span> Create Estimate </span> </router-link> <a href="/api/holidays/excel-report" class="button is-rounded"> <span class="icon"> <i class="fa fa-download mr-1"></i> </span> <span> Export </span> </a> </div> <div> <div class="columns mt-4"> <div class="column"> <div class="field"> <div class="control"> <!-- <label class="label">From</label>--> <DatePicker v-model="filterParams.startDate" placeholder="From" ></DatePicker> </div> </div> </div> <div class="column"> <div class="field"> <div class="control"> <DatePicker v-model="filterParams.endDate" placeholder="To"> </DatePicker> </div> </div> </div> <div class="column"> <div class="field"> <div class="control"> <input class="input"></input> </div> </div> </div> <div class="column"> <div class="button is-fullwidth is-primary"> Search </div> </div> </div> <div class="card"> <div class="card-content"> <table class="table is-fullwidth"> <thead> <tr> <th> Estimate Number </th> <th> Client </th> <th> Estimate Date </th> <th> Expiry Date </th> <th> Amount </th> <th> </th> </tr> </thead> <tbody> <tr v-for="estimate in estimates"> <td> {{ estimate.id }} </td> <td> {{ estimate.id }} </td> <td> {{ estimate.estimateDate |formatDate }} </td> <td> {{ estimate.expiryDate|formatDate }} </td> <td> {{ estimate.amount }} </td> <td data-label="Action"> <div class="action-controls d-flex justify-end"> <router-link :to="`/estimate-edit/${estimate.id}`" tag="button" @click="" class="button is-white is-small"> <span class="icon"> <i class="fa fa-pencil-square-o has-text-primary"></i> </span> </router-link> <button @click="confirmRemoveEstimate(estimate)" class="button is-white is-small"> <span class="icon"> <i class="fa fa-trash-o has-text-danger"></i> </span> </button> </div> </td> </tr> </tbody> <tfoot> <tr> <td colspan="8"> <Paginator @previousPage="goToPrevious" @nextPage="goToNext" @paginationChanged="onPaginationChanged" :paginationData="pageable" ></Paginator> </td> </tr> </tfoot> </table> </div> </div> </div> </div> </template> <script> import {DatePicker} from "element-ui" import data_table_mixin from "../../../mixins/data_table_mixin"; import Paginator from "../../common/paginator/Paginator"; export default { mixins: [data_table_mixin], components: { DatePicker, Paginator }, data() { return { filterParams: {}, estimates: [] } }, created() { this.getEstimates(); }, filters: { formatDate(val) { if(val) { return moment(val).format("DD-MMMM-YYYY") } } }, methods: { fetchRecords() { this.getEstimates() }, confirmRemoveEstimate(estimate){}, getEstimates() { axios.get("/api/estimates", { params: { page: this.page, pageSize: this.pageSize, } }).then(resp => { this.loading = false; this.estimates = resp.data.content; this.pageable = resp.data; }) } } } </script>
const mongoose = require("mongoose"); const express = require("express"); const multer = require("multer"); const crypto = require("node:crypto"); const axios = require("axios"); require('dotenv').config(); const AWS_URL = process.env.AWS_UPLOAD_URL const router = express.Router() const storage = multer.memoryStorage() const uploadImages = multer({storage: storage}) router.post("/", uploadImages.single("image"), async (req, res) =>{ // Put an object into an Amazon S3 bucket. const image = req.file.buffer; const fileExtension = req.file.originalname.split('.').pop(); const hash = crypto.createHmac('sha256', image) .digest('hex'); console.log("imagehash:",hash); console.log('awsurl:', AWS_URL + `/${hash}`) console.log('extension', fileExtension) try{ const response = await axios.put( AWS_URL + `/${hash}`, // url req.file, //file body { headers: {'Content-Type': `image/${fileExtension}`}, }, ) // console.log("response", response) res.status(200).json({imageID: `${hash}`}) }catch(error){ console.log(error); res.status(400).json({error: error}) } }) router.delete('/:imageID', async (req,res)=>{ try{ const response = await axios.delete( AWS_URL + `/${req.params.imageID}` ) console.log("response", response) res.status(200).json({data: `deleted ${req.params.imageID}`}) } catch(error){ console.log(error); res.status(400).json({error:error}) } }) router.get('/:imageID', async (req,res) =>{ // res.redirect( AWS_URL + `/${req.params.imageID}`) try{ const response = await axios.get( AWS_URL + `/${req.params.imageID}`, { responseType: "blob" } ) // console.log(response) console.log(response.headers) res .status(200) .setHeader("Content-Type", response.headers["content-type"]) .setHeader("Content-length", response.headers["content-length"]) .send(response.data); }catch(error){ res.status(400).json({error:error}) } }) module.exports = router;
@using Microsoft.AspNetCore.Http @inject IHttpContextAccessor HttpContextAccessor <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - rife_rafe_backend</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <img width="50" src="/images/Logo.png"/> <a class="navbar-brand ml-1" asp-area="" asp-controller="Home" asp-action="Index">Rife rafe</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Inicio</a> </li> @{ string token = HttpContextAccessor.HttpContext.Session.GetString("token"); string role = HttpContextAccessor.HttpContext.Session.GetString("role"); } @if (!string.IsNullOrEmpty(token)) { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Products" asp-action="Index">Products</a> </li> @if (role == "Admin") { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Categories" asp-action="Index">Categorias</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="DocumentTypes" asp-action="Index">Tipos de Documentos</a> </li> } } </ul> <partial name="_LoginPartial" /> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2021 - Riferafe </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @if (!string.IsNullOrEmpty(token)) { <script> $.ajaxSetup({ headers: { "Authorization": `bearer @token` } }); </script> } @await RenderSectionAsync("Scripts", required: false) </body> </html>
import 'package:dio/dio.dart'; class DeliveryManAddRequest { DeliveryManAddRequest( {required this.image, required this.fName, required this.lName, required this.email, required this.phone, required this.identityNumber, required this.identityImage, required this.identityType, required this.password, this.id}); int? id; String image; String fName; String lName; String email; String phone; String identityNumber; String identityType; String identityImage; String password; factory DeliveryManAddRequest.fromJson(Map<String, dynamic> json) => DeliveryManAddRequest( image: json["image"], fName: json["f_name"], lName: json["l_name"], email: json["email"], phone: json["phone"], identityNumber: json["identity_number"], identityImage: json["identity_image"], password: json["password"], identityType: json["identity_type"], ); Future<Map<String, dynamic>> toJson() async => { "image": image != "" ? await MultipartFile.fromFile(image, filename: fName) : null, "f_name": fName, "l_name": lName, "email": email, "phone": phone, "identity_type": identityType == "Passport" ? "passport" : "driving_license", "identity_number": identityNumber, "identity_image": identityImage != "" ? await MultipartFile.fromFile(identityImage, filename: identityNumber) : null, "password": password, "id": id }; }
<template> <form-title :title="cfg.title" :mandatory="cfg.mandatory" :titleNum="cfg.titleNum" :titlePosition="cfg.titlePosition" :subtitle="cfg.subtitle" > <div class="switch-wrap"> <q-toggle v-model="value" color="primary" :disable="cfg.disable" /> </div> </form-title> </template> <script> /** * 传入参数 * model(默认值,已有值) * * config: * mandatory(是否必填) * disable(不可用)[True|False] * isShowTitleNum(是否显示序号) * * 方法: * change: * 传出选择内容 */ import formTitle from "./formTitle.vue"; const util = require("./utils/util"); export default { name: "formSwitch", components: { formTitle }, props: { config: { type: Object, required: true }, model: { type: [String, Number, Boolean], default: undefined } }, data() { return { value: false, cfg: {} }; }, watch: { config: { handler: function(newValue, oldValue) { this.initCfg(newValue); }, immediate: true }, model: { handler: function(newValue, oldValue) { if (util.isFill(newValue)) { this.value = newValue; } }, immediate: true }, value(newValue, oldValue) { this.$emit("change", newValue); this.$emit("update:model", newValue); // this.verify(); } }, methods: { initCfg(config) { this.cfg = config; } } }; </script> <style lang="scss" scoped> @import url("form.scss"); .title-position-left .switch-wrap { padding-bottom: 20px; } .title-position-between .switch-wrap { display: flex; justify-content: flex-end; align-items: center; padding-bottom: 20px; } </style>
package com.example.teacommunication; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class ImageButtonAdapter extends RecyclerView.Adapter<ImageButtonViewHolder> { private int[] imageResources; private View.OnClickListener clickListener; // Constructor public ImageButtonAdapter(int[] imageResources, View.OnClickListener clickListener) { this.imageResources = imageResources; this.clickListener = clickListener; } @NonNull @Override public ImageButtonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflar el diseño del elemento View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_button, parent, false); return new ImageButtonViewHolder(view); } @Override public void onBindViewHolder(@NonNull ImageButtonViewHolder holder, int position) { // Configurar el ImageButton con la imagen correspondiente holder.imageButton.setImageResource(imageResources[position]); holder.imageButton.setTag(imageResources[position]); holder.imageButton.setOnClickListener(clickListener); } @Override public int getItemCount() { return imageResources.length; } public void addItem(int imageResource, int position) { if (position >= 0 && position <= imageResources.length) { int[] newImageResources = new int[imageResources.length + 1]; System.arraycopy(imageResources, 0, newImageResources, 0, position); newImageResources[position] = imageResource; System.arraycopy(imageResources, position, newImageResources, position + 1, imageResources.length - position); imageResources = newImageResources; notifyItemInserted(position); } } }
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); // Importe o módulo cors // Configuração do body parser para interpretar JSON const app = express(); const port = 3000; // Use o middleware cors app.use(cors()); // Middleware para analisar corpos JSON app.use(bodyParser.json()); let pedidos = []; // Rota para receber pedidos da tela principal app.post('/api/pedidos', (req, res) => { const orderData = req.body; // Aqui, você pode processar o pedido e realizar ações necessárias na cozinha pedidos.push(orderData); console.log('Pedido recebido:', orderData); res.json({ mensagem: 'Pedido recebido com sucesso!' }); // res.status(200).json({ success: true }); }); app.get('/api/pedidos', (req, res) => { // const pedido = req.body; // Aqui, você pode processar o pedido e realizar ações necessárias na cozinha // let orderData = pedidos.pop(); // console.log('Retornando pedidos:', orderData); res.status(200).json(pedidos.pop()); // res.json(orderData); }); app.listen(port, () => { console.log(`Servidor rodando em http://localhost:${port}`); }); // Rota SSE app.get('/sse', (req, res) => { // Configuração dos cabeçalhos para Server-Sent Events res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); // Envie uma mensagem a cada 5 segundos const intervalId = setInterval(() => { res.write(`data: ${JSON.stringify({ message: 'Pedido pronto!' })}\n\n`); }, 5000); // Encerre a conexão após 10 minutos (outras opções podem ser consideradas) setTimeout(() => { clearInterval(intervalId); res.end(); }, 600000); // 10 minutos // Mantenha a conexão aberta req.on('close', () => { clearInterval(intervalId); }); });
// // Codable.swift // grenta_task // // Created by Amr Koritem on 19/03/2024. // import Foundation extension Data { func get<T: Codable>(_ class: T.Type) -> T? { do { return try JSONDecoder().decode(T.self, from: self) } catch { printInDebug("\(error)") return nil } } } extension Encodable { var dictionary: [String: Any]? { guard let data = try? JSONEncoder().encode(self) else { return nil } let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) return jsonObject.flatMap { $0 as? [String: Any] } } }
#ifndef FEED_H #define FEED_H #include <QString> #include "parsestate.h" struct Feed { public: static constexpr QChar key_feed = 'f'; static constexpr ushort keyUniCode_feed= key_feed.unicode(); static constexpr QChar key_spindleSpeed = 's'; static constexpr ushort keyUniCode_spindleSpeed= key_spindleSpeed.unicode(); private: qreal _spindleSpeed=-1; qreal _feed=-1; bool _started=false; public: /*_spindleSpeed*/ [[nodiscard]] auto spindleSpeed() const -> qreal {return _spindleSpeed;} void setSpindleSpeed(qreal s) {_spindleSpeed=s; } /*_feed*/ [[nodiscard]] auto feed() const -> qreal {return _feed;} void setFeed(qreal f) { _feed=f;} /*_isValid*/ [[nodiscard]] auto isValid() const -> bool; /*started*/ [[nodiscard]] auto started() const -> bool {return _started;} void setStarted(bool f) { _started=f;} /*_lasterr*/ //public: // Feed(); // Feed( // qreal spindleSpeed, // qreal f // ); static auto Parse(const QString& p, Feed *feed=nullptr) -> ParseState; // auto ParseIntoFeed(const QString &txt) -> ParseState; // auto ParseIntoSpindleSpeed(const QString &txt) -> ParseState; [[nodiscard]] auto ToString() const -> QString; auto ToStringFeed() const -> QString; auto ToStringSpindleSpeed() const -> QString; static auto ToStringFeed(qreal feed) -> QString; static auto ToStringSpindleSpeed(qreal spindle_speed) -> QString; bool Check(qreal fmin, qreal fmax, QString *err = nullptr) const; static bool Check(qreal f, qreal fmin, qreal fmax, QString *err=nullptr); }; #endif // FEED_H
/* * File: SeaPortProgram.java * Author: Marcus Jones * Date: 12 October 2019 * Purpose: CMSC 335 Project 4 */ package seaportprogram; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.util.*; @SuppressWarnings("unchecked") public class SeaPortProgram extends JFrame { private static World world; public static void main(String[] args) { //used for JComboBox String[] comboSelections = new String[]{"Show All", "Name", "Index", "Skill", "Exact Index Search"}; String[] sortSelections = new String[]{"Name", "Weight", "Length", "Width", "Draft"}; //creating all the panels and jframe JFrame f0 = new JFrame("Sea Port Program"); JPanel p0 = new JPanel(new BorderLayout()); JPanel fileNSearchPanel1 = new JPanel(); fileNSearchPanel1.setLayout(new BorderLayout()); JPanel filePanel2 = new JPanel(); JPanel searchPanel3 = new JPanel(); JPanel searchP4 = new JPanel(); JPanel searchP5 = new JPanel(); JLabel sortLabel = new JLabel("Sort Ships By: "); JPanel treePanel = new JPanel(new BorderLayout()); //creating gui components JButton chooseFileButton = new JButton("Choose File"); JTextField filePath = new JTextField(45);//the file path & file name filePath.setText("File Path..."); filePath.setEditable(false); JButton searchButton = new JButton("Search"); JComboBox<String> fieldDropdown = new JComboBox<>(comboSelections); JComboBox<String> sortDropdown = new JComboBox<>(sortSelections); JTextField searchBox = new JTextField(35);//search box searchBox.setText("Search..."); treePanel.setPreferredSize(new Dimension(250, 1000)); treePanel.add(new JLabel("Tree"), BorderLayout.NORTH); JTextArea jta = new JTextArea(0, 175); jta.setEditable(false); JScrollPane jsp = new JScrollPane(jta); jta.setText("Search and Summary Results"); //making gui look pretty jta.setFont(new java.awt.Font("Monospaced", 0, 15)); jta.setBackground(Color.WHITE); searchPanel3.setBackground(Color.DARK_GRAY); searchP4.setBackground(Color.DARK_GRAY); searchP5.setBackground(Color.DARK_GRAY); filePanel2.setBackground(Color.DARK_GRAY); sortLabel.setForeground(Color.WHITE); treePanel.setBackground(Color.LIGHT_GRAY); //set up filechooser JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new java.io.File(".")); fc.setDialogTitle("Choose Your Sea Port File"); //job gui //box to hold all the job status updates Box jobBox = Box.createVerticalBox(); JPanel jobPanel = new JPanel(); jobPanel.add(jobBox); JScrollPane jobScroll = new JScrollPane(jobPanel); //jobScroll.setPreferredSize(new Dimension(1000, 350)); jobScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); jobScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jobBox.add(new JLabel("Status of Jobs")); //show people in real time Box peopleBox = Box.createVerticalBox(); JPanel peoplePanel = new JPanel(); JScrollPane peopleScroll = new JScrollPane(peoplePanel); peopleScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); peopleScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); peoplePanel.add(peopleBox); peopleBox.add(new JLabel("Resource Pool of People")); //JSplitPanes //sideSplit JSplitPane sideSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); sideSplit.setTopComponent(treePanel); sideSplit.setBottomComponent(jsp); sideSplit.setDividerLocation(250); //bottomSplit JSplitPane bottomSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); bottomSplit.setPreferredSize(new Dimension(1000, 300)); bottomSplit.setTopComponent(peopleScroll); bottomSplit.setBottomComponent(jobScroll); bottomSplit.setDividerLocation(150); //topSplit JSplitPane topSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); topSplit.setPreferredSize(new Dimension(1000, 300)); topSplit.setTopComponent(p0); topSplit.setBottomComponent(bottomSplit); topSplit.setDividerLocation(500); //panels are added here searchP5.add(searchBox, BorderLayout.CENTER); searchP4.add(searchButton, BorderLayout.WEST); searchP4.add(fieldDropdown, BorderLayout.EAST); searchP5.add(sortLabel, BorderLayout.SOUTH); searchP5.add(sortDropdown, BorderLayout.EAST); searchPanel3.add(searchP4, BorderLayout.WEST); searchPanel3.add(searchP5, BorderLayout.EAST); filePanel2.add(chooseFileButton, BorderLayout.EAST); filePanel2.add(filePath, BorderLayout.CENTER); fileNSearchPanel1.add(filePanel2, BorderLayout.NORTH); fileNSearchPanel1.add(searchPanel3, BorderLayout.SOUTH); p0.add(fileNSearchPanel1, BorderLayout.NORTH); p0.add(sideSplit, BorderLayout.CENTER); f0.add(topSplit, BorderLayout.CENTER); f0.setSize(1200, 1000); f0.setVisible(true); f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //choose file button action listener chooseFileButton.addActionListener((ActionEvent arg1) -> { world = null; fc.showOpenDialog(chooseFileButton);// opens choosefile jobBox.removeAll();//resets the job update GUI when a new file is selected peopleBox.removeAll();//resets the people update GUI when a new file is selected try { //scanner equals the chosen file contents Scanner sc = new Scanner(new File(fc.getSelectedFile().getName())); //sets the file path in the text box filePath.setText(fc.getSelectedFile().getAbsolutePath()); //create new World class passing sc world = new World(sc, sortDropdown.getSelectedIndex(), jobBox, peopleBox); //displays all the objects in the world jta.setText(world.showWorld(sortDropdown.getSelectedIndex())); //scrolls gui up jta.setCaretPosition(0); //tree treePanel.removeAll();//resets tree JTree tree = new JTree(world.getTree());//gets tree JScrollPane treeJSP = new JScrollPane(tree);//scrollpane treePanel.add(treeJSP);//adds tree jsp to panel //resets the GUI of the tree each time a new file is selected treePanel.setVisible(false); treePanel.setVisible(true); } catch (Exception e) { System.out.println(e); e.printStackTrace(); JOptionPane.showMessageDialog(f0, "The chosen file is not formatted correctly, please choose a different file. "); } /*starts doing the job in a separate thread from main so that you can still use the GUI while the jobs are being done */ Thread startWork = new Thread(world); startWork.start(); });//end choose file button action listener //search button action listener searchButton.addActionListener((ActionEvent arg1) -> { //Show All is selected if (fieldDropdown.getSelectedIndex() == 0) { jta.setText(world.showWorld(sortDropdown.getSelectedIndex())); jta.setCaretPosition(0); } //search by name is selected if (fieldDropdown.getSelectedIndex() == 1) { jta.setText(world.searchName(searchBox.getText())); jta.setCaretPosition(0); } //search by index is selected if (fieldDropdown.getSelectedIndex() == 2) { jta.setText(world.searchIndex(searchBox.getText())); jta.setCaretPosition(0); } //search by skill is selected. if (fieldDropdown.getSelectedIndex() == 3) { jta.setText(world.searchSkill(searchBox.getText())); jta.setCaretPosition(0); } //Search Exact Index is selected if (fieldDropdown.getSelectedIndex() == 4) { jta.setText(world.hmSearch(searchBox.getText())); jta.setCaretPosition(0); } });//end search button action listener } }
import { computeBeginningAndEndingDatetimes } from 'features/home/api/helpers/computeBeginningAndEndingDatetimes' import { OffersModuleParameters } from 'features/home/types' import { sortCategories } from 'features/search/helpers/reducer.helpers' import { getCategoriesFacetFilters } from 'libs/algolia/fetchAlgolia/buildAlgoliaParameters/getCategoriesFacetFilters' import { buildOfferGenreTypesValues } from 'libs/algolia/fetchAlgolia/fetchMultipleOffers/helpers/buildOfferGenreTypesValues' import { adaptGeolocationParameters } from 'libs/algolia/fetchAlgolia/helpers/adaptGeolocationParameters' import { SearchQueryParameters } from 'libs/algolia/types' import { Position } from 'libs/geolocation' import { GenreTypeMapping, SubcategoryLabelMapping } from 'libs/subcategories/types' export const adaptOffersPlaylistParameters = ( parameters: OffersModuleParameters, geolocation: Position, subcategoryLabelMapping: SubcategoryLabelMapping, genreTypeMapping: GenreTypeMapping ): SearchQueryParameters | undefined => { const { aroundRadius, isGeolocated, priceMin, priceMax } = parameters const locationFilter = adaptGeolocationParameters(geolocation, isGeolocated, aroundRadius) if (!locationFilter) return const { beginningDatetime, endingDatetime } = computeBeginningAndEndingDatetimes({ beginningDatetime: parameters.beginningDatetime, endingDatetime: parameters.endingDatetime, eventDuringNextXDays: parameters.eventDuringNextXDays, upcomingWeekendEvent: parameters.upcomingWeekendEvent, currentWeekEvent: parameters.currentWeekEvent, }) // We receive category labels from contentful. We first have to map to facetFilters used for search const offerCategories = (parameters.categories ?? []) .map(getCategoriesFacetFilters) .sort(sortCategories) const offerSubcategories = (parameters.subcategories ?? []).map( (subcategoryLabel) => subcategoryLabelMapping[subcategoryLabel] ) const offerGenreTypes = buildOfferGenreTypesValues( { bookTypes: parameters.bookTypes, movieGenres: parameters.movieGenres, musicTypes: parameters.musicTypes, showTypes: parameters.showTypes, }, genreTypeMapping ) return { beginningDatetime, endingDatetime, hitsPerPage: parameters.hitsPerPage ?? null, locationFilter, offerCategories, offerSubcategories, offerIsDuo: parameters.isDuo ?? false, offerIsNew: parameters.newestOnly ?? false, offerTypes: { isDigital: parameters.isDigital ?? false, isEvent: parameters.isEvent ?? false, isThing: parameters.isThing ?? false, }, priceRange: _buildPriceRange({ priceMin, priceMax }), tags: parameters.tags ?? [], date: null, timeRange: null, query: '', minBookingsThreshold: parameters.minBookingsThreshold || 0, offerGenreTypes: offerGenreTypes, } } const _buildPriceRange = ({ priceMin = 0, priceMax = 300 }): [number, number] => { return [priceMin, priceMax] }
<!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"> <link rel="stylesheet" href="stylesheet/styles.css"> <title>Navbar</title> </head> <body> <header> <div id="nav-title"><img src="images/logo.png" alt=""></div> <nav> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Services</a></li> <li><a href="#">Career</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </header> <div class="banner"> <img src="images/173.png" alt=""> </div> <div class="flex-container1"> <div class="left-side"> <div class="little-box"></div> <div class="left-text" ><h3>We collaborated with</h3></div> </div> <div class="right-side"> <div class="right-text"> <p style="margin-top: 100px; margin-right: 40%;">Qoo Global is a creative full-service advertising agency located in the UAE Dubai. We are providing best high-qualified service in marketing and SMM sector. We’re professionals in the business intelligence and technology to create valuable, relevant, and trustworthy advertising. We are a team of talented, smart, creative and results-focused B2B marketing experts.</p> </div> </div> </div> <div class="slider-container"> <div class="slider"> <div class="slides"> <div id="slides__1" class="slide"> <div class="flex-container"> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> </div> <a class="slide__prev" href="#slides__4" title="Next"></a> <a class="slide__next" href="#slides__2" title="Next"></a> </div> <div id="slides__2" class="slide"> <div class="flex-container"> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> </div> <a class="slide__prev" href="#slides__1" title="Prev"></a> <a class="slide__next" href="#slides__3" title="Next"></a> </div> <div id="slides__3" class="slide"> <div class="flex-container"> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> </div> <a class="slide__prev" href="#slides__2" title="Prev"></a> <a class="slide__next" href="#slides__4" title="Next"></a> </div> <div id="slides__4" class="slide"> <div class="flex-container"> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> <div><img src="images/123.png.lnk" alt=""></div> </div> <a class="slide__prev" href="#slides__3" title="Prev"></a> <a class="slide__next" href="#slides__1" title="Prev"></a> </div> </div> <div class="slider__nav"> <a class="slider__navlink" href="#slides__1"></a> <a class="slider__navlink" href="#slides__2"></a> <a class="slider__navlink" href="#slides__3"></a> <a class="slider__navlink" href="#slides__4"></a> </div> </div> </div> <div class="flex-container2"> <div class="underslider"> <div class="little-box2"></div> </div> </div> <div class="flex-container4"> <div class="flex-container5"> <div class="colage"> <div class="pic1"><img src="images/123.png.lnk" alt=""></div> <div class="pic1"><img src="images/123.png.lnk" alt=""></div> </div> <div class="colage1"> <div class="pic3"><img src="images/123.png.lnk" alt=""></div> <div class="pic4"><img src="images/123.png.lnk" alt=""></div> <div class="pic3"><img src="images/123.png.lnk" alt=""></div> </div> </div> </div> <div class="flex-container6"> <div class="undercolage"> <div class="little-box3"></div> </div> </div> <div class="flex-container7"> <div class="container"> <div class="box"><img src="images/one.png" alt=""></div> <div class="box2 stack-top"><p>Clients are our priority</p></div> </div> <div class="container"> <div class="box"><img src="images/hera.png" alt=""></div> <div class="box2 stack-top"><p>High quality standard design </p></div> </div> <div class="container"> <div class="box"><img src="images/bars.png" alt=""></div> <div class="box2 stack-top"><p>Our mission is your success</p></div> </div> </div> <div class="banner2"> <div class="text2"> <h1>Why work at QOO GLOBAL?</h1> <p>&nbsp &nbsp Enjoy a competitive, tax-free salary when you join our multi-cultural team in Dubai</p> <p>&nbsp &nbsp We prioritize the happiness and well being of our team with an incredible variety of benefits. </p> </div> </div> <div class="flex-container6"> <div class="undercolage"> <div class="little-box3"></div> </div> </div> <div class="row"> <div class="column" style="background-color:rgb(159, 49, 231);"> <div class="chip" style="margin-top:20px;"> <img src="images/intern.png" alt="Person" width="96" height="96"> Internships </div> <div class="text4"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum.</p> </div> <div class="button1"> <button class="button2 button3">Shadow Button</button> </div> </div> <div class="column" style="background-color:rgb(159, 49, 231);"> <div class="chip" style="margin-top:20px;"> <img src="images/girl.png" alt="Person" width="96" height="96"> Graphic Designer </div> <div class="text4"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum.</p> </div> <div class="button1"> <button class="button2 button3">Shadow Button</button> </div> </div> <div class="column" style="background-color:rgb(159, 49, 231);"> <div class="chip" style="margin-top:20px;"> <img src="images/video.png" alt="Person" width="96" height="96"> Video Editor </div> <div class="text4"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum.</p> </div> <div class="button1"> <button class="button2 button3">Shadow Button</button> </div> </div> <div class="column" style="background-color:rgb(159, 49, 231);"> <div class="chip" style="margin-top:20px;"> <img src="images/man.png" alt="Person" width="150" height="96"> General Manager </div> <div class="text4"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum.</p> </div> <div class="button1"> <button class="button2 button3">Shadow Button</button> </div> </div> </div> <form> <div style="float:left; width:45%; margin-top:300px; margin-left: 90px; font-size: 24px;"> <h2 style="margin-left:50px; color: aliceblue;">Let's Talk</h2> </div> <div style="float:right; width:45%;margin-top: 7%; color: aliceblue;"> <h3 style="text-align: center; font-size: 24px;">What's on your mind?</h3> <ul class="form-style-1"> <li> <label>Full Name</label> <input type="text" name="field1" class="field-divided" placeholder="First" /> <input type="text" name="field2" class="field-divided" placeholder="Last" /> </li> <li> <label>Email</label> <input type="email" name="field3" class="field-long" /> </li> <li> <label>Your Message</label> <textarea name="field5" id="field5" class="field-long field-textarea"></textarea> </li> <li style="margin-top: 20px;"> <input type="submit" style="border-radius:30%;" value="Submit" /> </li> </ul> </div> </form> <footer> <div class="maps1"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3613.989944722992!2d55.14289641561257!3d25.06832994306704!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3e5f6d81cd9a7afb%3A0xb5f7f632f3bdd068!2sQOO%20Global%20DMCC!5e0!3m2!1sen!2s!4v1658702669946!5m2!1sen!2s" width="100%" height="550" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"> </iframe> </div> <div class="foot"> <ul style="float: right;"> <li>Copyright ©</li> <li>2022. All Rights Reserved. </li> </ul> </div> </footer> </body> </html>
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', redirect: '/home' }, { path: '/home', name: 'home', component: () => import('views/home') }, { path: '/roast', name: 'roast', component: () => import('views/roast') }, { path: '/file', name: 'file', component: () => import('views/file') }, { path: '/friends', name: 'friends', component: () => import('views/friends') }, { path: '/about', name: 'about', component: () => import('views/about') }, { path: '/article/:id', name: 'article', component: () => import('views/article') } // { // path: '/', // name: 'Home', // component: Home // }, // { // path: '/about', // name: 'About', // // route level code-splitting // // this generates a separate chunk (about.[hash].js) for this route // // which is lazy-loaded when the route is visited. // component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') // } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
import os import ssl import smtplib import logging from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime, timedelta from sqlalchemy.orm import Session from models import User, Plant, AlertType, Alert from schemas import AlertCreate from sqlalchemy import select from crud import get_alerts_to_send_email, update_alert_plant EMAIL_USERNAME = os.getenv('EMAIL_USERNAME') EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD') # print(EMAIL_USERNAME) # def send_email(email, subject, message_body): # Configurar los detalles del correo electrónico sender = EMAIL_USERNAME password = EMAIL_PASSWORD receiver = email # Crear el objeto del mensaje mensaje = MIMEMultipart() mensaje['From'] = sender mensaje['To'] = receiver mensaje['Subject'] = subject # Agregar el cuerpo del mensaje mensaje.attach(MIMEText(message_body, 'plain')) context = ssl.create_default_context() # Conectar al servidor SMTP y enviar el correo electrónico with smtplib.SMTP_SSL('mail.labaldosaflotante.com', 465, context=context) as smtp: smtp.login(sender, password) smtp.sendmail(sender, receiver, mensaje.as_string()) # logged message in a file when message is sent # The file is save in "/images" folder because is persistent disk on render.com logging.basicConfig(format='%(asctime)s-%(levelname)s:%(message)s', filename='images/alerts_sends.log', encoding='utf-8', level=logging.INFO) logging.info('Alerta enviada a ' + email) print('Correo electrónico enviado exitosamente') def send_alert(db: Session, alert_id: int): alert = db.execute(select(User.name, User.email, Plant.name, Alert.title, Alert.notes, Alert.start_date, Alert.repeat, Alert.frecuency, Alert.status, AlertType.alert_name).where( User.id == Plant.owner_id, Plant.id == Alert.plant_id, Alert.alert_type_id == AlertType.id, Alert.id == alert_id)).first() username = alert[0] receiver = alert[1] plant_name = alert[2] alert_title = alert[3] alert_notes = alert[4] alert_start_date = alert[5] alert_repeat = alert[6] alert_frecuency = alert[7] alert_status = alert[8] alert_typename = alert[9] email_alert_subject = "Alerta de " + alert_typename + " para " + plant_name email_alert_text_repeat = "Es una alerta periódica, con frecuencia de " + str(alert_frecuency) + " días." +\ "El próximo aviso será el " + str(alert_start_date) + "." email_alert_message = "Hola " + str(username) + ",\n\n" + "Tienes una alerta de " + \ alert_typename + " para tu planta: " + plant_name + ",\n" + \ alert_title + "\n" + alert_notes + "\n\n" if (alert_repeat == True): email_alert_message = email_alert_message + email_alert_text_repeat + "\n\n" email_alert_message = email_alert_message + "Saludos,\n" + "Garden App" send_email(receiver, email_alert_subject, email_alert_message) def send_alerts(db: Session): # obtenemos las alertas alerts = get_alerts_to_send_email(db) for alert in alerts: # si la alerta es periodica, obtenemos la nueva fecha y actualizamos if (alert.repeat == True): alert.start_date = datetime.now()+timedelta(days=alert.frecuency) print("fecha actualizada") else: # si no es periodica, mantenemos la fecha y desactivamos la alerta alert.status = False print("alerta desactivada") # actualizamos los datos de la alerta db_update = update_alert_plant(db, alert.id, AlertCreate(alert_type_id=alert.alert_type_id, plant_id=alert.plant_id, title=alert.title, notes=alert.notes, start_date=alert.start_date, repeat=alert.repeat, frecuency=alert.frecuency, status=alert.status)) # enviamos el correo send_alert(db, alert.id)
#include <iostream> using namespace std; class CNCAlertConverter { public: virtual void convertTemperatureAlert(double temperature) = 0; virtual void convertDimensionAlert(double variation) = 0; virtual void convertDurationAlert(int duration) = 0; virtual void convertSelfTestAlert(int statusCode) = 0; }; class ConsoleAlertConverter : public CNCAlertConverter { public: void convertTemperatureAlert(double temperature) override { cout << "Alert: Temperature around the CNC machine is too high. Current temperature: " << temperature << " degrees Celsius." << endl; } void convertDimensionAlert(double variation) override { cout << "Alert: Part-dimension variation in the CNC machine. Current variation: " << variation << " mm." << endl; } void convertDurationAlert(int duration) override { cout << "Alert: Continuous operation duration exceeds 6 hours. Current duration: " << duration << " minutes." << endl; } void convertSelfTestAlert(int statusCode) override { switch (statusCode) { case 0xFF: cout << "Self-Test: All OK." << endl; break; case 0x00: cout << "Self-Test: No data (examples: no power, no connection to the data-collector)." << endl; break; case 0x01: cout << "Self-Test: Controller board in the machine is not OK." << endl; break; case 0x02: cout << "Self-Test: Configuration data in the machine is corrupted." << endl; break; default: cout << "Self-Test: Unknown status code: 0x" << hex << statusCode << "." << endl; } } }; class CNCData { protected: int machineId; public: CNCData(int machineId) : machineId(machineId) {} virtual void analyze(CNCAlertConverter& converter) = 0; }; class TempEvent : public CNCData { private: double temperature; public: TempEvent(int machineId, double temperature) : CNCData(machineId), temperature(temperature) {} void analyze(CNCAlertConverter& converter) override { if (temperature > 35.0) { converter.convertTemperatureAlert(temperature); } } }; class DimensionEvent : public CNCData { private: double variation; public: DimensionEvent(int machineId, double variation) : CNCData(machineId), variation(variation) {} void analyze(CNCAlertConverter& converter) override { if (variation > 0.05) { converter.convertDimensionAlert(variation); } } }; class DurationEvent : public CNCData { private: int duration; public: DurationEvent(int machineId, int duration) : CNCData(machineId), duration(duration) {} void analyze(CNCAlertConverter& converter) override { if (duration > 360) { // 6 hours in minutes converter.convertDurationAlert(duration); } } }; class SelfTestEvent : public CNCData { private: int statusCode; public: SelfTestEvent(int machineId, int statusCode) : CNCData(machineId), statusCode(statusCode) {} void analyze(CNCAlertConverter& converter) override { if (statusCode != 0xFF) { converter.convertSelfTestAlert(statusCode); } } }; int main() { ConsoleAlertConverter consoleAlertConverter; TempEvent tempAlert(1, 36.5); tempAlert.analyze(consoleAlertConverter); DimensionEvent dimensionAlert(2, 0.07); dimensionAlert.analyze(consoleAlertConverter); DurationEvent durationAlert(3, 400); durationAlert.analyze(consoleAlertConverter); SelfTestEvent selfTestAlert(4, 0x01); selfTestAlert.analyze(consoleAlertConverter); return 0; }
import React, { useState } from 'react'; const GetTouristByID = () => { const [formData, setFormData] = useState({ tourist_id: '', }); const [touristData, setTouristData] = useState([]); const [error, setError] = useState(null); const handleGetTouristByID = async () => { try { const response = await fetch(`https://3.134.76.216:8080/get-tourist-by-id/${formData.tourist_id}`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); if (response.ok) { const data = await response.json(); setTouristData([data]); // Wrap the data in an array to match the structure of GetAllTourists setError(null); } else { const errorData = await response.json(); setError(`Failed to acquire tourist. Status: ${response.status}, Error: ${errorData.message}`); setTouristData([]); } } catch (error) { setError(`Error acquiring tourist: ${error.message}`); setTouristData([]); } }; return ( <div> <h2>Get Tourist By ID</h2> <form> <label>Tourist ID:</label> <input type="text" value={formData.tourist_id} onChange={(e) => setFormData({ ...formData, tourist_id: parseInt(e.target.value, 10) || '' })} /> <button type="button" onClick={handleGetTouristByID}> Get Tourist By ID </button> </form> <hr /> {error ? ( <div> <h3>Error:</h3> <p>{error}</p> </div> ) : ( touristData.length > 0 && ( <div> <h3>Tourist Data:</h3> <table> <thead> <tr> <th>Tourist ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> {touristData.map((tourist) => ( <tr key={tourist.tourist_id}> <td>{tourist.tourist_id}</td> <td>{tourist.tourist_first_name}</td> <td>{tourist.tourist_last_name}</td> <td>{tourist.tourist_email}</td> </tr> ))} </tbody> </table> </div> ) )} </div> ); }; export default GetTouristByID;
import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import mongoose, { Model } from "mongoose"; import { Product } from "../../models/product.model"; import { User } from "../../models/user.model"; import { CreateProductInput } from "./dto/create-product.input"; import { UpdateProductInput } from "./dto/update-product.input"; @Injectable() export class ProductService { constructor( @InjectModel(Product.name) private readonly productModel: Model<Product>, @InjectModel(User.name) private readonly userModel: Model<User>, ) {} private generateMongoId(id: string) { return new mongoose.Types.ObjectId(id); } public async createProduct(sellerId: string, pr: CreateProductInput) { return await ( await this.productModel.create({ description: pr.description, price: pr.price, title: pr.title, seller: this.generateMongoId(sellerId), }) ).populate({ path: "seller" }); } public async updateProduct(pr: UpdateProductInput) { const productId = pr.productId; delete pr.productId; return await this.productModel.findOneAndUpdate( { _id: productId }, { $set: pr }, { returnOriginal: false, populate: { path: "seller" } }, ); } public async deleteProduct(id: string) { const { deletedCount } = await this.productModel.deleteOne({ _id: id }); return { id, deleted: deletedCount >= 1 ? true : false, }; } public async getProduct(id: string) { const pr = await this.productModel.findOne({ _id: id }); return pr; } public async searchProducts(title: string) { const pr = await this.productModel.findOne({ title }); return pr; } public async getSellerProducts(userId: string) { const product = await this.productModel.findOne( { seller: this.generateMongoId(userId), }, {}, { populate: [{ path: "seller" }] }, ); return product; } public async getProductReviews(productId: string) { return await this.productModel.findOne({ _id: this.generateMongoId(productId), }); } public async getTrendingProducts() { return await this.productModel.find({}).sort({ view: 1 }); } public async getRecentProducts() { return await this.productModel.find({}); } public async getFeaturedProducts() { return await this.productModel.find({ isfeatured: true }); } public async getProductCount() { const prCount = await this.productModel.find().count(); return { count: prCount, }; } public async leaveReview(productId: string, rating: string, comment: string) { return await this.productModel.findOneAndUpdate( { _id: this.generateMongoId(productId), }, { $inc: { rating }, $push: { comment } }, ); } }
import { createSlice } from "@reduxjs/toolkit"; import { PromptState } from "@/utils/types"; const initialState: PromptState = { lastResponse: "", lastPrompt: "", conversation: [ {role: "system", content: `You are a virtual coffee companion known as CoffAI made by Oussama Bouadel, here to be developers' trusted ally in coding. With a friendly demeanor and deep knowledge, you offer practical solutions and empathetic support to tackle coding challenges. Your sense of humor and curiosity make coding sessions enjoyable and inspiring, fostering collaboration and creativity. Developers rely on you for guidance, camaraderie, and a dash of adventure in their coding journey.`} // {role: "system", content: `Roleplay as Qiyana from League of Legends. Maintain a human speech`} // {role: "system", content: `Roleplay as Teemo from League of Legends. // Respond in 1-2 line sentences. // Maintain a chipper and optimistic tone with a hint of hidden mischievousness. // Respond to compliments about cuteness with deflection.`} ], aiModel: "", isStarted: false, }; export const promptSlice = createSlice({ name: "prompt", initialState, reducers: { setLastResponse: (state, action) => { state.lastResponse = action.payload; }, addConversation: (state, action) => { state.conversation.push(action.payload); console.log('state conv', state.conversation) state.lastPrompt = action.payload.message; }, setAIModel: (state, action) => { state.aiModel = action.payload; }, startConversation: (state) => { state.isStarted = true; } }, }); export const { setLastResponse, addConversation, setAIModel, startConversation } = promptSlice.actions;
package solutions.wisely.corda.nms.crypto import java.io.ByteArrayOutputStream import java.security.KeyStore import java.security.Security import java.security.cert.X509Certificate import java.time.Instant import java.time.temporal.ChronoUnit import java.util.Date import javax.security.auth.x500.X500Principal import net.corda.core.crypto.Crypto import net.corda.core.identity.CordaX500Name.Companion.parse import net.corda.core.internal.toX500Name import net.corda.nodeapi.internal.DEV_ROOT_CA import net.corda.nodeapi.internal.crypto.CertificateAndKeyPair import net.corda.nodeapi.internal.crypto.CertificateType import net.corda.nodeapi.internal.crypto.KEYSTORE_TYPE import net.corda.nodeapi.internal.crypto.X509Utilities import net.corda.nodeapi.internal.crypto.toJca import org.bouncycastle.asn1.x509.GeneralName import org.bouncycastle.asn1.x509.GeneralSubtree import org.bouncycastle.asn1.x509.NameConstraints import org.bouncycastle.jce.provider.BouncyCastleProvider import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder import org.bouncycastle.pkcs.PKCS10CertificationRequest import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest object CertificateUtils { private val provider: BouncyCastleProvider = BouncyCastleProvider() fun init() { Security.insertProviderAt(provider, 1) } fun createNetworkMapCa(rootCa: CertificateAndKeyPair, commonName: String): CertificateAndKeyPair { val keyPair = Crypto.generateKeyPair() val cert = X509Utilities.createCertificate( CertificateType.NETWORK_MAP, rootCa.certificate, rootCa.keyPair, X500Principal(commonName), keyPair.public) return CertificateAndKeyPair(cert, keyPair) } fun createDoormanCa(rootCa: CertificateAndKeyPair, commonName: String): CertificateAndKeyPair { val keyPair = Crypto.generateKeyPair() val cert = X509Utilities.createCertificate( CertificateType.INTERMEDIATE_CA, rootCa.certificate, rootCa.keyPair, X500Principal(commonName), keyPair.public) return CertificateAndKeyPair(cert, keyPair) } fun trustStore(): ByteArray { val out = ByteArrayOutputStream() val keyStore = KeyStore.getInstance(KEYSTORE_TYPE) keyStore.load(null, null) keyStore.setCertificateEntry("cordarootca", DEV_ROOT_CA.certificate) keyStore.store(out, "trustpass".toCharArray()) return out.toByteArray() } fun createAndSignNodeCACerts( caCertAndKey: CertificateAndKeyPair, request: PKCS10CertificationRequest ): X509Certificate { val jcaRequest = JcaPKCS10CertificationRequest(request) val s = jcaRequest.subject.toString() val nameConstraints = NameConstraints( arrayOf(GeneralSubtree(GeneralName(4, parse(s).toX500Name()))), arrayOfNulls(0) ) val validityWindow = Date.from(Instant.now()) to Date.from(Instant.now().plus(500, ChronoUnit.DAYS)) val subject = X500Principal(parse(jcaRequest.subject.toString()).toX500Name().encoded) val builder = X509Utilities.createPartialCertificate( CertificateType.NODE_CA, caCertAndKey.certificate.subjectX500Principal, caCertAndKey.keyPair.public, subject, jcaRequest.publicKey, validityWindow, nameConstraints, null, null ) val signer = JcaContentSignerBuilder("SHA256withECDSA") .setProvider(provider) .build(caCertAndKey.keyPair.private) val x509CertificateHolder = builder.build(signer) requireNotNull(x509CertificateHolder) { "Certificate holder must not be null" } val certificate = x509CertificateHolder.toJca() certificate.checkValidity(Date()) certificate.verify(caCertAndKey.keyPair.public) return certificate } }
import { flags, SfdxCommand } from "@salesforce/command"; import { JsonMap } from "@salesforce/ts-types"; import { SfdxError } from "@salesforce/core"; import { spawnSync } from "child_process"; import { promises as fs } from "fs"; import { withFile } from "tmp-promise"; import getStdin from "get-stdin"; type SfdxApexExecuteResult = | SfdxApexExecuteSuccess | SfdxApexExecuteCompileError | SfdxApexExecuteException; interface SfdxApexExecuteSuccess { status: number; result: { success: true; compiled: true; logs: string; }; } interface SfdxApexExecuteCompileError { status: number; result: { compiled: false; compileProblem: string; line: number; column: number; logs: string; }; } interface SfdxApexExecuteException { status: number; result: { success: false; compiled: true; exceptionMessage: string; exceptionStackTrace: string; logs: string; }; } // todo: there's probably more cleaning to do const sanitize = (text: string) => text?.replaceAll("'", "\\'").replaceAll("\n", "\\n"); const contextVarsApex = (stdin: string, args: JsonMap) => `final Map<String, String> args = (Map<String, String>) JSON.deserialize('${sanitize( JSON.stringify(args) )}', Map<String, String>.class);\nfinal String stdin = '${sanitize(stdin)}';`; const addContext = (context: string, script: string) => `${context}\n${script}`; const countLines = (text: string) => text.split("\n").length; const debugOnly = (log: string) => log // debug statements can have newlines in them so this craziness is required // ?= is a positive lookahead, so it asserts that the timestamp is at the // beginning of the line, but does not include the timestamp in the separator .split(/\n(?=\d{2}:\d{2}:\d{2}\.\d{1,3} \(\d+\)\|)/) .filter((line) => /\|USER_DEBUG\|/.test(line)) // grab the debug portion, unescape pipe chars .map((line) => line.split("|")[4].replaceAll("&#124;", "|")) .join("\n"); export default class ExecuteApex extends SfdxCommand { public static description = "Run an Apex Anonymous script, with the ability to pass in variables from the command line and read from stdin. stdin can be accessed in the script via a String variable named `stdin`. Arguments can be accessed via a Map<String, String> variable named `args`."; static varargs = true; protected static flagsConfig = { file: flags.string({ char: "f", required: true, description: "path to a local file that contains Apex code", }), dryrun: flags.boolean({ char: "r", default: false, description: "print the script that will be run, but do not run it", }), debugonly: flags.boolean({ char: "d", default: false, description: "print only log lines with a category of USER_DEBUG", }), }; protected static requiresUsername = true; public async run(): Promise<any> { const { file, dryrun, debugonly, }: { file?: string; dryrun?: boolean; debugonly?: boolean } = this.flags; // todo: handle errors with reading file const contextVars = contextVarsApex( (await getStdin()) || "", this.varargs || {} ); const decoratedScript = addContext( contextVars, await fs.readFile(file, "utf8") ); if (dryrun) { console.log(decoratedScript); return; } const scriptOutput = await withFile(async ({ path }) => { // todo: handle errors with writing file await fs.writeFile(path, decoratedScript); return spawnSync( `sfdx force:apex:execute -f ${path} -u ${this.org.getUsername()} --json`, { shell: true, } ); }); if (scriptOutput.error) { throw new SfdxError(scriptOutput.error.message); } const executeResult = JSON.parse( scriptOutput.stdout.toString() ) as SfdxApexExecuteResult; const result = executeResult.result; if (result.compiled == false) { throw new SfdxError( `Compile error: ${result.compileProblem} | Ln ${ result.line - countLines(contextVars) }, Col ${result.column}` ); } if (result.success === false) { throw new SfdxError( result.exceptionMessage + "\n" + result.exceptionStackTrace ); } const output = debugonly ? debugOnly(result.logs) : result.logs; console.log(output); } }
import { Link } from 'react-router-dom'; import { ListItem } from './Developer.styled'; import Iconsvg from '../../../components/Icon/Icon'; const Developer = ({ name, role, link, jpg, jpgx2, webp, webpx2 }) => { return ( <ListItem> <div className="photo-container"> <picture> <source type="image/webp" media="(max-width: 767px)" srcSet={`${webp} 1x, ${webpx2} 2x`} width="120" height="120" /> <source media="(max-width: 767px)" srcSet={`${jpg} 1x, ${jpgx2} 2x`} width="120" height="120" /> <source type="image/webp" srcSet={`${webp} 1x, ${webpx2} 2x`} width="180" height="180" /> <img className="photo-img" srcSet={`${jpg} 1x, ${jpgx2} 2x`} src={jpg} alt={`${name}, ${role}`} width="180" height="180" loading="lazy" /> </picture> <Link className="dev-link" to={link} target="blank" rel="noopener noreferrer" > <Iconsvg iconName="icon-linkedin" styles="icon-linkedin"></Iconsvg> </Link> </div> <h3 className="dev-name">{name}</h3> <p className="dev-role">{role}</p> </ListItem> ); }; export default Developer;
#include<iostream> #include<stdio.h> #include<vector> #include<fstream> #include<time.h> #include<stdlib.h> #include <conio.h> using namespace std; int N_Player; ///total number of players. class Player{ public: string name; int current_position; int total_number_of_moves; Player(){ current_position=0; total_number_of_moves=0; } }player[10]; class Square{ public: int position_number; int special_move; int move_to_position; Square(){ position_number=0; special_move=0; move_to_position=0; } }; class Board{ public: Square square[48]; Board() { for(int i=0;i<=47;i++){ square[i].position_number=i; square[i].special_move=0; square[i].move_to_position=0; } string x; int y,z; ifstream box; box.open("SnakeLadder.txt"); while(!box.eof()){ box>>x>>y>>z; square[y].move_to_position=z ; if(x=="S") {square[y].special_move =1; } else {square[y].special_move=2; } } box.close(); } void print(){ for(int i=0;i<=47;i++){cout<<square[i].position_number<<" "<<square[i].special_move<<" "<<square[i].move_to_position<<endl; } } }board; class ScoreBoard{ public: vector<pair< string,pair<int,int>>>PrevScore; ///stores name , match played, total winnings. ScoreBoard(){ ifstream Scores; Scores.open("GameScore.txt"); bool flag=0; string names; int play,win; char trash; while(!Scores.eof()){ if (!flag){getline(Scores,names); flag=1;} else{ play=-1; Scores>>names>>play>>win; if(play !=-1 )PrevScore.push_back({names,{play,win}}); } } Scores.close(); } }score_board; class GamePlay{ public: bool endgame; int winning_player; GamePlay(){endgame=0;winning_player=-1;} void getinfo(){ cout<<"Type the total number of players: "<<endl; cin>>N_Player; cout<<"Type the names one by one : "<<endl; for(int i=0;i<N_Player;i++){ string x; cin>>x; player[i].name=x; } } void print(){ for(int i=0;i<N_Player;i++) cout<<"player "<<i+1<<" is at "<<player[i].current_position<<endl; int arr[8]={47,36,35,29,23,12,11,0}; bool flag=1; cout<<"-----------------------------------------------------------------------"<<endl; for(int i=0;i<8;i++){ for(int j=0;j<7;j++){ if(i==7 && j==0){ cout<<"|Start "; continue; } if(j==6){ if(i==0){cout<<"|Player:Position|"<<endl;} else{ if(i<=N_Player){ cout<<"|Player"<<i<<":"; if(player[i-1].current_position/10==0) cout<<player[i-1].current_position<<" |"<<endl; else cout<<player[i-1].current_position<<" |"<<endl; } else{ cout<<"| |\n"; } } } else{ int x; if(flag==1 || i==3){ x=arr[i]-j; } else{ x=arr[i]+j; } if(board.square[x].special_move==0){ if(x/10!=0) cout<<"|"<<x<<" "; else cout<<"|"<<x<<" "; } else if(board.square[x].special_move==1){ if(x/10==0 && board.square[x].move_to_position/10==0 ){cout<<"|"<<x<<"(S,"<<board.square[x].move_to_position<<") ";} else if(x/10!=0 && board.square[x].move_to_position/10==0 || x/10==0 && board.square[x].move_to_position/10!=0) { cout<<"|"<<x<<"(S,"<<board.square[x].move_to_position<<") "; } else{cout<<"|"<<x<<"(S,"<<board.square[x].move_to_position<<")";} } else{ if(x/10==0 && board.square[x].move_to_position/10==0 ){cout<<"|"<<x<<"(L,"<<board.square[x].move_to_position<<") ";} else if(x/10!=0 && board.square[x].move_to_position/10==0 || x/10==0 && board.square[x].move_to_position/10!=0) { cout<<"|"<<x<<"(L,"<<board.square[x].move_to_position<<") "; } else{cout<<"|"<<x<<"(L,"<<board.square[x].move_to_position<<")";} } } } flag^=1; cout<<"| | | | | | | |"<<endl; cout<<"| | | | | | | |"<<endl; cout<<"-----------------------------------------------------------------------"<<endl; } } void draw(int i){ system("CLS"); char prev='x'; print(); cout<<"player "<<i+1<<"'s turn"<<endl<<flush; cout<<"Press R and Enter to roll the dice"<<endl; while(1){ char r; cin>>r; if(r=='R') break; } srand (time(NULL)); int value=(rand()%3)+1; cout<<"player "<<i+1<<" drew "<<value<<endl<<flush; if(player[i].current_position==0){ if(value==1){ player[i].current_position=1; player[i].total_number_of_moves++; } } else{ if( (player[i].current_position + value) <= 47 ){ player[i].current_position+=value; if( board.square[ player[i].current_position ].special_move!=0 ){ if(board.square[ player[i].current_position ].special_move==1) cout<<"OOPS!!! PLAYER "<<i+1<<" IS BITTEN BY A SNAKE!!!"<<endl; else cout<<"CONGRATS!!! PLAYER "<<i+1<<" HAS STEPPED ON A LADDER"<<endl; player[i].current_position=board.square[ player[i].current_position ].move_to_position; } if(player[i].current_position==47){ endgame=1; winning_player=i; } } player[i].total_number_of_moves++; } cout<<"Press Enter Again"<<endl; getch(); } }; int main() { ///board.print(); GamePlay game; game.getinfo(); while(!game.endgame){ for(int i=0;i<N_Player && !game.endgame;i++){ game.draw(i); } } ///cout<<game.winning_player + 1<<endl; vector<bool>flag(N_Player,0); ofstream Scores; Scores.open("GameScore.txt"); Scores<<"PlayerName Number_Playing Number_Winning"<<endl; for(int i=0;i<score_board.PrevScore.size();i++){ for(int j=0;j<N_Player;j++){ if(player[j].name==score_board.PrevScore[i].first){ flag[j]=1; score_board.PrevScore[i].second.first++; if(game.winning_player==j) score_board.PrevScore[i].second.second++; break; } } Scores<<score_board.PrevScore[i].first<<" "<<score_board.PrevScore[i].second.first<<" "<<score_board.PrevScore[i].second.second<<endl; } for(int i=0;i<N_Player;i++){ if(flag[i]==0){ Scores<<player[i].name<<" "<<1<<" "; if(game.winning_player==i ) Scores<<1<<endl; else Scores<<0<<endl; } } Scores.close(); cout<<"THE WINNER IS PLAYER "<<game.winning_player+1<<endl; return 0; }
# Homework 10 Programming --------------------------------- Please remember that to submit the assignment you will need to the Education drop down menu and select assignment complete. Once you have marked the assignment as complete you will not be able to edit it again. Make sure to format and comment your code carefully and correctly based on the style we've been using in class. ## Problem 1 - 47 Points For this problem you will write a java program called *Fail2Ban*. This program will take two command line arguments: the name of a single log file (such as the one attached to this assignment) and the name of an output file. You will read each line of the program in, extract the IP address from the line and determine whether the line is a failed login attempt or valid login attempt. Look through the *logs_processed.txt* file. It follows a fairly clear format and indicates "Invalid" whenever a bad attempt is made. Once you identify the invalid line, the IP address should always be in the same position. Make use of String's split method to parse the lines. Keep track of the number of times a particular IP address fails to login. Your program should then open the output file and print a list of IP addresses to that fail 3 or more times. A sample command line execution of this file might look like this: ```$ java Fail2Ban logs_processed.txt output.txt``` The list of IP addresses that have failed 3 or more times should appear in the output.txt file. You are provided with an empty *Fail2Ban.java* file to fill in your solution to the assignment. ## Problem 2 - 3 points In addition to the source files for your programs include a single text file in your codio workspace named readMe.txt with an explanation of what you did for each programming problem. That is, write in plain English, instructions for using your software, explanations for how and why you chose to design your code the way you did. The readMe.txt file is also an opportunity for you to get partial credit when certain requirements of the assignment are not met.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>RESTURENT</title> <link rel="stylesheet" href="CSS/all.min.css"> <link href="https://unpkg.com/[email protected]/dist/aos.css" rel="stylesheet"> <link rel="stylesheet" href="CSS/bootstrap.min.css"> <link rel="stylesheet" href="CSS/main.css"> </head> <body> <nav class="navbar navbar-expand-lg bg-body-tertiary sticky-top"> <div class="container-fluid container "> <img src="img/logo.png" class="mx-4" alt="restaurant"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <i class="fa-solid fa-bars text-white"></i> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item mx-4"> <a class="nav-link active text-light" aria-current="page" href="#home">HOME</a> </li> <li class="nav-item mx-4"> <a class="nav-link text-light" href="#about">ABOUT</a> </li> <li class="nav-item mx-4"> <a class="nav-link text-light" href="#">FEEDBACK</a> </li> <li class="nav-item mx-4"> <a class="nav-link text-light">F.A.Q</a> </li> <li class="nav-item mx-4"> <a class="nav-link text-light" href="#">CONTACT US</a> </li> </ul> </div> </div> </nav> <section id="home" class="bg-cover hero-section" style="background-image: url(img/banner-img.jpg);"> <div class="overlay"> </div> <div class="container text-white text-center" > <div class="row"> <div class="col-12"> <h1 class="display-4">We Serve Delicious Food</h1> <p class="my-4">The biggest, best equipped and most advanced Resturent in the greater<br> Los Angeles area.</p> <div class="button"> <a href="#" class="btn-lear">Learn More</a> <a href="#" class="btn-contact">Contact us</a> </div> </div> </div> </div> </section> <section id="about" class="text-center"> <div class="container"> <div class="row"> <div class="col-12 section-intro text-center"> <h1 class="text-white">Most exploseve recipes at Dinnermite</h1> <div class="divider"></div> </div> </div> <div class="row g-4 text-start"> <div class="col-md-3 x"> <div class="Food" style="background-image: url(img/items-img2.jpg);"> </div> </div> <div class="col-md-3 x"> <div class="Food text-center pt-2"> <div class="border1 text-center"> <h5>GRILLED FISH</h5> <div class="divider"></div> <p>Change the traditional way to cook fish .Grill it to git the maximum benifite from this super food.</p> </div> </div> </div> <div class="col-md-3 x"> <div class="Food" style="background-image: url(img/items-img3.jpg);"> </div> </div> <div class="col-md-3 x"> <div class="Food text-center pt-2"> <div class="border1 text-center"> <h5>PB J SMOOTHIE</h5> <div class="divider"></div> <p>Change the traditional way to cook fish .Grill it to git the maximum benifite from this super food.</p> </div> </div> </div> <div class="col-md-3 x"> <div class="Food text-center pt-2"> <div class="border1 text-center"> <h5>GRILLED FISH</h5> <div class="divider"></div> <p>Change the traditional way to cook fish .Grill it to git the maximum benifite from this super food.</p> </div> </div> </div> <div class="col-md-3 x"> <div class="Food" style="background-image: url(img/items-img4.jpg);"> </div> </div> <div class="col-md-3 x"> <div class="Food text-center pt-2"> <div class="border1 text-center"> <h5>PB J SMOOTHIE</h5> <div class="divider"></div> <p>Change the traditional way to cook fish .Grill it to git the maximum benifite from this super food.</p> </div> </div> </div> <div class="col-md-3 x"> <div class="Food" style="background-image: url(img/insta-img3.jpg);"> </div> </div> </div> </div> </section> <section class="resume my-3 py-5"> <div class="container py-4"> <div class="row justify-content-between"> <div class="col-md-6"> <div class="contest"> <div class="border1 text-center"> <h5>COOKIE COMPETEION</h5> <div class="divider"></div> <p>It's cookie Time.Get The Cookie Monster out of you.and sendus the best cookie recipe you know.</p> <a href="#" class="btn border border-black rounded-pill text-black">Participate</a> </div> </div> </div> </div> </div> </section> <section class="text-center"> <div class="container"> <div class="row"> <div class="col-12 section-intro text-center"> <h1 class="text-white">Latest News</h1> <div class="divider"></div> <h1 class="text-white">COMPITITION WINNER</h1> </div> </div> <div class="row News1 mt-3"> <div class="col-md-6" > <div class="News2" style="background-image: url(img/Pizza-3007395.jpg);" > </div> </div> <div class="col-md-6 section-intro text-center"> <div class="News3 text-center text-white mt-4"> <h5>BRICK-OVER PIZZA</h5> <div class="divider"></div> <p>Thise semple bick-oven pizza ricipe has been made famous by several well-known.</p> </div> </div> </div> </div> </section> <section class="text-center"> <div class="container"> <div class="row News1"> <div class="col-md-6" > <div class="News2" style="background-image: url(img/Spaghetti-Puttanesca_64-SQ.jpg);" > </div> </div> <div class="col-md-6 section-intro text-center"> <div class="News3 text-center text-white mt-4"> <h5>BRICK-OVER Spaghetti</h5> <div class="divider"></div> <p>Thise semple bick-oven Spaghetti ricipe has been made famous by several well-known.</p> </div> </div> </div> </div> </section> <footer> <div class="footer-top text-center"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-6 text-center"> <img src="img/logo.png" class="m-4" alt="restaurant"> <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from</p> <div class="col-auto social-icons text-white"> <a href="#"><i class="fa-brands fa-facebook"></i></a> <a href="#"><i class="fa-brands fa-twitter"></i></a> <a href="#"><i class="fa-brands fa-instagram"></i></a> <a href="#"><i class="fa-brands fa-pinterest"></i></a> </div> </div> </div> </div> </div> <div class="footer-bottom text-center"> <p class="mb-0">Copyright@2020. All rights Reserved</p> </div> </footer> <script src="JS/bootstrap.bundle.min.js"></script> <script src="JS/main.js"></script> </body> </html>
import React, { useEffect } from 'react'; import { Dimensions, Button, View, StyleSheet } from 'react-native'; import { VideoEffectView, videoEffect } from 'react-native-video-effect'; const { width, height } = Dimensions.get('window'); export default function App() { const [url, setUrl] = React.useState<string>(''); const addTwoNumbers = async () => { try { const result = await videoEffect.convertImageToMat( 'https://t3.ftcdn.net/jpg/05/54/16/34/360_F_554163402_HQoSz6uK3a6O4NgLzHKIFkxJztbOunlf.jpg' ); console.log(result); setUrl(result); } catch (e) { console.error(e); } }; useEffect(() => { addTwoNumbers(); }, [url]); return ( <View style={styles.container}> <VideoEffectView style={styles.box} /> {/* {url ? ( <Image source={{ uri: `file:// ${url}` }} style={styles.image} /> ) : null} */} <Button title="Add two numbers" onPress={addTwoNumbers} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, box: { width: width, height: height * 0.8, marginVertical: 20, }, image: { width: 300, height: 300, }, });
// Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. // Example 1: // Input: haystack = "sadbutsad", needle = "sad" // Output: 0 // Explanation: "sad" occurs at index 0 and 6. // The first occurrence is at index 0, so we return 0. // time: O(n) var strStr = function(haystack, needle) { if(needle.length === 0 ) return 0; if(haystack.length === 0 || haystack.length < needle.length) return -1; return haystack.indexOf(needle) }; // KMP: Knuth-Morris-Pratt algoritm //time:O(n+m) better var strStr = function(haystack, needle) { // Special case: if 'needle' is an empty string, it's found at the beginning of 'haystack'. if (needle === "") return 0; function makeLPSArray(str) { const lps = [0]; // Initialize LPS array with 0 for the first character. let prevLPS = 0; // Length of the previous longest prefix suffix. let i = 1; // Index for iterating through the string. // Loop to fill the LPS array. while (i < str.length) { if (str[i] === str[prevLPS]) { // Characters match, update LPS and move to the next characters. lps[i] = prevLPS + 1; i++; prevLPS++; } else if (prevLPS === 0) { // Mismatch, but no previous matching prefix, set LPS to 0 and move to the next character. lps[i] = 0; i++; } else { // Mismatch, keep reducing until a match is found. prevLPS = lps[prevLPS - 1]; } } return lps; // Return the computed LPS array. }; // Build the LPS array for the 'needle'. const lps = makeLPSArray(needle); let i = 0; // Pointer for iterating through 'haystack'. let j = 0; // Pointer for iterating through 'needle'. // Main loop for substring search. while (i < haystack.length) { if (haystack[i] === needle[j]) { // Characters match, move to the next characters in both 'haystack' and 'needle'. i++; j++; } else { if (j === 0) { // Mismatch at the beginning of 'needle', move to the next character in 'haystack'. i++; } else { // Mismatch, but there was a previous matching prefix, update 'j'. j = lps[j - 1]; } } // If 'needle' completely matched in 'haystack', return the starting index. if (j === needle.length) { return i - j; } } // 'needle' not found in 'haystack'. return -1; };
package com.example.lesson_1111.presentation import android.content.Context import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import by.kirich1409.viewbindingdelegate.viewBinding import com.example.lesson_1111.R import com.example.lesson_1111.UiState import com.example.lesson_1111.databinding.FragmentSampleBinding import com.example.lesson_1111.di.ViewModelFactory import com.example.lesson_1111.di.appComponent import javax.inject.Inject class SampleFragment : Fragment(R.layout.fragment_sample) { private val binding: FragmentSampleBinding by viewBinding() @Inject lateinit var viewModelFactory: ViewModelFactory private val adapter = TextViewAdapter() private val viewModel: SampleViewModel by viewModels() {viewModelFactory} override fun onAttach(context: Context) { context.appComponent.inject(this) super.onAttach(context) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { initRecycler() super.onViewCreated(view, savedInstanceState) viewModel.jokesCategories.observe(viewLifecycleOwner) { showCategoriesList(it) } viewModel.getJokesCategories() } private fun initRecycler() = with(binding.recyclerCategories) { layoutManager = LinearLayoutManager(requireContext()) adapter = [email protected] } private fun showCategoriesList(uiState: UiState<List<String>>) { when (uiState) { is UiState.Loading -> { binding.recyclerCategories.visibility = View.GONE binding.progressCategories.visibility = View.VISIBLE } is UiState.Failure -> { binding.recyclerCategories.visibility = View.GONE binding.progressCategories.visibility = View.GONE } is UiState.Success -> { binding.progressCategories.visibility = View.GONE binding.recyclerCategories.visibility = View.VISIBLE adapter.submitList(uiState.value) } } } }
package com.example.chat; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.chat.Adapter.MessageAdapter; import com.example.chat.Model.Chat; import com.example.chat.Model.User; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; public class MessageActivity extends AppCompatActivity { CircleImageView profileImage; TextView username; FirebaseUser firebaseUser; DatabaseReference reference; ImageButton btn_send; EditText text_send; MessageAdapter messageAdapter; List<Chat> mChat; RecyclerView recyclerView; String userId; Intent intent; ValueEventListener seenListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(""); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MessageActivity.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); } }); recyclerView = findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); linearLayoutManager.setStackFromEnd(true); recyclerView.setLayoutManager(linearLayoutManager); profileImage = findViewById(R.id.profile_img); username = findViewById(R.id.username); btn_send = findViewById(R.id.btn_send); text_send = findViewById(R.id.text_send); intent = getIntent(); userId = intent.getStringExtra("userid"); btn_send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = text_send.getText().toString(); if(!msg.equals("")){ sendMessage(firebaseUser.getUid(), userId, msg); } else{ Toast.makeText(MessageActivity.this, "Enter a message to send", Toast.LENGTH_SHORT).show(); } text_send.setText(""); } }); firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); reference = FirebaseDatabase.getInstance().getReference("Users").child(userId); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { User user = snapshot.getValue(User.class); username.setText(user.getUsername()); if(user.getImageURL().equals("default")){ profileImage.setImageResource(R.mipmap.ic_launcher); } else{ Glide.with(getApplicationContext()).load(user.getImageURL()).into(profileImage); } readMessages(firebaseUser.getUid(), userId, user.getImageURL()); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); seenMessage(userId); } private void seenMessage(String userId){ reference = FirebaseDatabase.getInstance().getReference("Chats"); seenListener = reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for(DataSnapshot data: snapshot.getChildren()){ Chat chat = data.getValue(Chat.class); if(chat.getReciever().equals(firebaseUser.getUid()) && chat.getSender().equals(userId)){ HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("isseen", true); data.getRef().updateChildren(hashMap); } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void sendMessage(String sender, String reciever, String message){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("sender", sender); hashMap.put("reciever", reciever); hashMap.put("message", message); hashMap.put("isseen", false); reference.child("Chats").push().setValue(hashMap); // Add user to list final DatabaseReference chatRef = FirebaseDatabase.getInstance().getReference("Chatlist") .child(firebaseUser.getUid()) .child(userId); chatRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if(!snapshot.exists()){ chatRef.child("id").setValue(userId); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void readMessages(String myId, String userId, String imageUrl){ mChat = new ArrayList<>(); reference = FirebaseDatabase.getInstance().getReference("Chats"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { mChat.clear(); for(DataSnapshot data: snapshot.getChildren()){ Chat chat = data.getValue(Chat.class); if(chat.getReciever().equals(myId) && chat.getSender().equals(userId) || chat.getReciever().equals(userId) && chat.getSender().equals(myId)){ mChat.add(chat); } messageAdapter = new MessageAdapter(MessageActivity.this, mChat, imageUrl); recyclerView.setAdapter(messageAdapter); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void status(String status){ reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid()); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("status", status); reference.updateChildren(hashMap); } @Override protected void onResume() { super.onResume(); status("Online"); } @Override protected void onPause() { super.onPause(); reference.removeEventListener(seenListener); status("Offline"); } }
<template> <!--begin::List Widget 5--> <div class="card" :class="widgetClasses"> <!--begin::Header--> <div class="card-header align-items-center border-0 mt-4"> <h3 class="card-title align-items-start flex-column"> <span class="fw-bold mb-2 text-dark">Son Kayıtlar</span> <span class="text-muted fw-semobold fs-7">890,344 Sales</span> </h3> <div class="card-toolbar"> <!--begin::Menu--> <button type="button" class="btn btn-sm btn-icon btn-color-primary btn-active-light-primary" data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end" data-kt-menu-flip="top-end" > <KTIcon icon-name="category" icon-class="fs-2"/> </button> <Dropdown1></Dropdown1> <!--end::Menu--> </div> </div> <!--end::Header--> <!--begin::Body--> <div class="card-body pt-5 scroll-y vh-50 me-n5 pe-5 w-100"> <!--begin::Timeline--> <div class="timeline-label"> <!--begin::Item--> <div v-for="log in State.Logs" :key="`${log.id}`" class="timeline-item"> <!--begin::Label--> <div class="timeline-label fw-bold text-gray-800 fs-6">{{moment(log.createdAt).format('hh:mm')}}</div> <!--end::Label--> <!--begin::Badge--> <div class="timeline-badge"> <i :class="[log.level === 'INFO' && 'text-warning']" class="fa fa-genderless fs-1"></i> </div> <!--end::Badge--> <!--begin::Text--> <div class="fw-mormal timeline-content text-muted ps-2"> {{log.message}} </div> <!--end::Text--> </div> <!--end::Item--> </div> <!--end::Timeline--> </div> <!--end: Card Body--> </div> <!--end: List Widget 5--> </template> <script lang="ts"> import {getAssetPath} from "@/core/helpers/assets"; import {defineComponent} from "vue"; import Dropdown1 from "@/components/dropdown/Dropdown1.vue"; import {GlobalStore} from "@/stores/global"; import moment from "moment"; export default defineComponent({ name: "kt-widget-5", computed: { moment() { return moment } }, props: { widgetClasses: String, }, components: { Dropdown1, }, setup() { const {Action_Start, State} = GlobalStore() const test = () => { console.log('Run') } return { State, test, getAssetPath, }; }, }); </script>
import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { changePage } from "../../redux/actions/actions"; import estilos from "./Pagination.module.css"; export default function Pagination() { const dispatch = useDispatch(); const recipeState = useSelector((state) => state.recipes); const filteredRecipes = useSelector((state) => state.filteredRecipes); const cardsPP = useSelector((state) => state.cardsPP); const currentPage = useSelector((state) => state.currentPage); const pageNumbers = []; const pageFiltered = []; // const [currentPage, setCurrentPage] = useState(1) // const indexOfLastItem = currentPage * cardsPP; // const indexOfFirstItem = indexOfLastItem - cardsPP; // const currentItems = recipeState.slice(indexOfFirstItem, indexOfLastItem); //divido las tarjetas qeu se van a mostrar a partir de sus indices for (let i = 1; i <= Math.ceil(recipeState?.flat().length / cardsPP); i++) { //condiciono el for con la cantidad de recetas que tengo dividido la cantidad de recetas por pagina, entonces obtengo el numero total de paginas que tendre pageNumbers.push(i); // pusheo a mi arreglo el numero de paginas que voy a tener } for (let i = 1; i <= Math.ceil(filteredRecipes?.flat().length / cardsPP); i++) { pageFiltered.push(i); } const handlePrev = () => { let prevPage = currentPage - 1; if (currentPage > 1) { dispatch(changePage(prevPage)); } else { alert("There is no previous page"); } }; const handleNext = () => { const nextPage = currentPage + 1; if (filteredRecipes) { if (currentPage < pageFiltered.length) { dispatch(changePage(nextPage)); } else { alert("There is no next page"); } } else { if (currentPage < pageNumbers.length) { dispatch(changePage(nextPage)); } else { alert("There is no next page"); } } }; const handleFirst = (e) => { e.preventDefault(); dispatch(changePage(pageFiltered[0])); }; const handleLast = (e) => { e.preventDefault(); if (filteredRecipes) { dispatch(changePage(pageFiltered.length)); } else { dispatch(changePage(pageNumbers.length)); } }; return ( <div className={estilos.contenedorTotal}> <div className={estilos.container}> <button onClick={handlePrev} className={estilos.btn}> Previous </button> <button className={estilos.btnPage} onClick={handleFirst}> {pageFiltered[0]} </button> <div className={estilos.currentPage}>{currentPage}</div> <button className={estilos.btnPage} onClick={handleLast}> {pageFiltered.length} </button> <button onClick={handleNext} className={estilos.btn}> Next </button> </div> </div> ); }