text
stringlengths
184
4.48M
/* * SPDX-FileCopyrightText: 2013 (c) Business Operation Systems GmbH <info@top-logic.com> * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-BOS-TopLogic-1.0 */ package com.top_logic.layout.table.control; import com.top_logic.basic.StringServices; import com.top_logic.layout.LabelProvider; import com.top_logic.layout.table.model.Column; /** * {@link LabelProvider} for {@link Column}s that produces a structured label including all parent * column group names. * * @author <a href="mailto:bhu@top-logic.com">Bernhard Haumacher</a> */ public class StructuredColumnLabels implements LabelProvider { private final LabelProvider _directLabels; /** * Creates a {@link StructuredColumnLabels}. * * @param directLabels * {@link LabelProvider} that produce user-readable column names for technical column * names. */ public StructuredColumnLabels(LabelProvider directLabels) { _directLabels = directLabels; } @Override public String getLabel(Object object) { Column column = (Column) object; if (column.getParent() == null) { return directLabel(column); } StringBuilder buffer = new StringBuilder(); printComposedLabel(buffer, column); return buffer.toString(); } private boolean printComposedLabel(StringBuilder buffer, Column column) { Column parent = column.getParent(); if (parent != null) { boolean parentHasLabel = printComposedLabel(buffer, parent); if (parentHasLabel) { buffer.append(": "); } } String label = directLabel(column); boolean hasLabel = !StringServices.isEmpty(label); if (hasLabel) { buffer.append(label); } return hasLabel; } private String directLabel(Column column) { return _directLabels.getLabel(column.getName()); } }
(ns context.entity (:require [clj-commons.pretty.repl :as p] [x.x :refer [defsystem doseq-entity]] [gdl.context :refer [draw-text]] [utils.core :refer [define-order sort-by-order]] [game.context :refer [get-entity]])) ; doseq-entity - what if key is not available anymore ? check :when (k @entity) ? (defrecord Entity [id position]) (defsystem create [_]) (defsystem create! [_ entity context]) (defsystem destroy! [_ entity context]) ; only used twice position/body (defsystem tick! [_ entity context delta]) (defsystem moved! [_ entity context direction-vector]) ; body/position (defsystem render-below [_ entity* context]) (defsystem render-default [_ entity* context]) (defsystem render-above [_ entity* context]) (defsystem render-info [_ entity* context]) (defsystem render-debug [_ entity* context]) (defn- render-entity* [system entity* {:keys [context.entity/thrown-error] :as context}] (doseq [component entity*] (try (system component entity* context) (catch Throwable t (when-not @thrown-error (println "Render error for: entity :id " (:id entity*) " \n component " component "\n system" system) (p/pretty-pst t) (reset! thrown-error t)) (let [[x y] (:position entity*)] (draw-text context {:text (str "Render error entity :id " (:id entity*) "\n" (component 0) "\n"system "\n" @thrown-error) :x x :y y :up? true})))))) (let [cnt (atom 0)] (defn- unique-number! [] (swap! cnt inc))) ; using this because x.x/update-map with transients is destroying defrecords and ; turning them into normal maps. ; check (keys (methods multimethod)) ; remove 'tick' / counters then this doesnt hurt so much anymore performance wise (defn- update-map "Updates every map-entry with (apply f [k v] args)." [m f & args] (loop [ks (keys m) m m] (if (seq ks) (recur (rest ks) (let [k (first ks)] (assoc m k (apply f [k (k m)] args)))) m))) (extend-type gdl.context.Context game.context/EntityComponentSystem (get-entity [{:keys [context.entity/ids->entities]} id] (get @ids->entities id)) (create-entity! [{:keys [context.entity/ids->entities] :as context} components-map] {:pre [(not (contains? components-map :id)) (:position components-map)]} (let [id (unique-number!) entity (-> (assoc components-map :id id) (update-map create) map->Entity atom (doseq-entity create! context))] (swap! ids->entities assoc id entity) entity)) (tick-entity [{:keys [context.entity/thrown-error] :as context} entity delta] (try (doseq-entity entity tick! context delta) (catch Throwable t (p/pretty-pst t) (println "Entity id: " (:id @entity)) (reset! thrown-error t)))) (render-entities* [{:keys [context.entity/render-on-map-order] :as context} entities*] (doseq [entities* (map second (sort-by-order (group-by :z-order entities*) first render-on-map-order)) ; vars so I can see the function name @ error (can I do this with x.x? give multimethods names?) system [#'render-below #'render-default #'render-above #'render-info] entity* entities*] (render-entity* system entity* context)) (doseq [entity* entities*] (render-entity* #'render-debug entity* context))) (remove-destroyed-entities [{:keys [context.entity/ids->entities] :as context}] (doseq [e (filter (comp :destroyed? deref) (vals @ids->entities))] (doseq-entity e destroy! context) (swap! ids->entities dissoc (:id @e))))) (defn ->context [& {:keys [z-orders]}] {:context.entity/ids->entities (atom {}) :context.entity/thrown-error (atom nil) :context.entity/render-on-map-order (define-order z-orders)})
// // agendaYoberBlockDate.swift // Yobli // // Created by Brounie on 16/10/20. // Copyright © 2020 Brounie. All rights reserved. // import Foundation import UIKit import Parse import FSCalendar class agendaYoberBlockDate: UIViewController{ // MARK: OUTLETS @IBOutlet weak var agendaYober: FSCalendar! // MARK: VARs/LETs var datesBlocked = [Date]() let currenDateTime = Date() var daysAvailable = [String]() var daysAvailableInt = [Int]() var frequency = "" override func viewDidLoad() { super.viewDidLoad() agendaYober.delegate = self agendaYober.dataSource = self agendaYober.allowsMultipleSelection = true agendaYober.locale = NSLocale.init(localeIdentifier: "es_MX") as Locale self.updateView() self.dismissWithSwipe() } override func viewWillAppear(_ animated: Bool) { if PFUser.current() == nil { self.sendAlert() } } // MARK: BUTTON FUNCTIONS @IBAction func goBack(_ sender: Any) { _ = navigationController?.popViewController(animated: true) } @IBAction func saveChanges(_ sender: Any) { let user = PFUser.current()! user["blockedDates"] = datesBlocked user.saveInBackground { (success: Bool?, error: Error?) in if let error = error { self.sendErrorType(error: error) }else if success != nil{ let alert = UIAlertController(title: "ÉXITO", message: "Cambios guardados", preferredStyle: .alert) //This action is to goBack to the agendaYober after creating the user let action = UIAlertAction(title: "Continuar", style: .default){ (_) in let goTo = UIStoryboard(name: "TabProfile", bundle: nil).instantiateViewController(withIdentifier: "tabBarYober") as! UITabBarController goTo.selectedIndex = 0 let nav = UINavigationController(rootViewController: goTo ) nav.isNavigationBarHidden = true let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = nav } alert.addAction(action) self.present(alert, animated: true, completion: nil) } } } // MARK: OTHER FUNCTIONS func updateView(){ let user = PFUser.current()! if let newDates = user["blockedDates"] as? [Date]{ datesBlocked = newDates } if let newTsAvailable = user["availableDays"] as? [String]{ daysAvailable = newTsAvailable daysAvailableInt = [] for myTime in daysAvailable{ if(myTime == "LUN"){ daysAvailableInt.append(2) }else if(myTime == "MAR"){ daysAvailableInt.append(3) }else if(myTime == "MIE"){ daysAvailableInt.append(4) }else if(myTime == "JUE"){ daysAvailableInt.append(5) }else if(myTime == "VIE"){ daysAvailableInt.append(6) }else if(myTime == "SAB"){ daysAvailableInt.append(7) }else if(myTime == "DOM"){ daysAvailableInt.append(1) } } } if let newFrequency = user["availableFrequency"] as? String{ frequency = newFrequency } for myDate in datesBlocked{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd" let labelDate1 = dateFormatter.string(from: currenDateTime) let labelDate2 = dateFormatter.string(from: myDate) if(labelDate1 == labelDate2){ agendaYober.select(myDate) } if( myDate > currenDateTime ){ agendaYober.select(myDate) } } agendaYober.reloadData() } } //MARK: FSCALENDAR EXTENSION extension agendaYoberBlockDate: FSCalendarDelegate, FSCalendarDelegateAppearance, FSCalendarDataSource{ func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool { let result = comparisonOfDate(date: date, calendar) return result } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillSelectionColorFor date: Date) -> UIColor? { return UIColor.lightGray } func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) { datesBlocked.append(date) } func calendar(_ calendar: FSCalendar, didDeselect date: Date, at monthPosition: FSCalendarMonthPosition) { if let index = datesBlocked.index(of: date) { datesBlocked.remove(at: index) } } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd" let labelDate1 = dateFormatter.string(from: currenDateTime) let labelDate2 = dateFormatter.string(from: date) if(labelDate1 == labelDate2){ if ( datesBlocked.contains(date) ){ return UIColor.lightGray } return UIColor.black } if( date > currenDateTime ){ let result = comparisonOfDate(date: date, calendar) if( result == true ){ let color = returnBlackColor(date: date, calendar) return color }else{ return UIColor.lightGray } }else{ return UIColor.lightGray } } func minimumDate(for calendar: FSCalendar) -> Date { return currenDateTime } func comparisonOfDate(date: Date, _ calendar: FSCalendar) -> Bool{ if( daysAvailableInt.contains( calendar.gregorian.component(.weekday, from: date) ) ){ if( frequency == "Semanal" ){ if( calendar.gregorian.component(.year, from: currenDateTime) == calendar.gregorian.component(.year, from: date) ){ if( calendar.gregorian.component(.weekOfYear, from: currenDateTime) == calendar.gregorian.component(.weekOfYear, from: date) ){ return true }else{ return false } } }else if( frequency == "Mensual" ){ if( calendar.gregorian.component(.year, from: currenDateTime) == calendar.gregorian.component(.year, from: date) ){ if( calendar.gregorian.component(.month, from: currenDateTime) == calendar.gregorian.component(.month, from: date) ){ return true }else{ return false } } }else if( frequency == "Anual" ){ if( calendar.gregorian.component(.year, from: currenDateTime) == calendar.gregorian.component(.year, from: date) ){ return true } }else{ return false } } return false } func returnBlackColor(date: Date, _ calendar: FSCalendar) -> UIColor{ switch calendar.gregorian.component(.weekday, from: date) { case 1: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } case 2: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } case 3: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } case 4: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } case 5: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } case 6: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } case 7: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } default: if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.white } else { // User Interface is Light return UIColor.black } } } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, borderDefaultColorFor date: Date) -> UIColor? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd" let labelDate1 = dateFormatter.string(from: currenDateTime) let labelDate2 = dateFormatter.string(from: date) if(labelDate1 == labelDate2){ if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark return UIColor.black } else { // User Interface is Light return UIColor.white } }else{ return nil } } }
[**Volume I: Motion**](./volume-I.md) [**Previous: 1.1. Mathematics and science in ancient Greece.**](./vol-I-chap-1-sect-1.md) *** ## 1.2. Conceptualizations of spaces and quantum statistics. !!! info "Conceptual developments in ancient Greece." The first part of this section is based on the conference *Géométrie et astronomie sphérique dans la première cosmologie grecque* by Vernant (1963). He considered how the evolution of ancient Greek society generated two kinds of conceptual developments, all of them before the Christian era: (1) the building of circular spaces in family life and community (the reference is made to the philosopher Pherecydes, the poet Homer, the historian and geographer Herodotus and the architect Hippodamus), and (2) the concept of circularity in the definition of astronomical spaces (reference is made to the poet and philosopher Hesiod and to the philosopher, geographer and physicist Anaximander). !!! info "Building circular spaces according to political organizations." Before political institutions were established in Greece, the highest level in the social organization was occupied by the king-priest. The entire population was always under conditions of domination and submission. There were no spaces for communications. Public affairs were not discussed, they were imposed. However, laws and rules were promulgated and made public in written. ### Pherecydes of Syros (580 BC – 520 BC). <figure markdown> ![Pherecydes of Syros](https://upload.wikimedia.org/wikipedia/commons/3/33/Pherecydes_of_Syros_recent_bust_Syro208.jpg){ width="240" } <figcaption>(Image credit: CC Wikimedia Commons)</figcaption> </figure> When Greek cities were built (_the polis_) writing was used as a transforming instrument that made public private issues. Probably it was Pherecydes of Syros (580 BC – 520 BC) the first writer to publish a philosophical work in prose. He wrote books for transforming private knowledges into public possibilities for discussion. ### Herodotus of Halicarnassus (484 BC- 425 BC). <figure markdown> ![Herodotus of Halicarnassus](https://upload.wikimedia.org/wikipedia/commons/6/6d/Marble_bust_of_Herodotos_MET_DT11742_%28cropped%29.jpg){ width="240" } <figcaption>(Image credit: CC Wikimedia Commons)</figcaption> </figure> Herodotus of Halicarnassus (484 BC- 425 BC) mentioned that when the dictator Polycrates of Samos died, his successor asked all the citizens to meet in an assembly and informed them that he will behave in a democratic way in total disagreement with his predecessor. ### Homer (VIII century). <figure markdown> ![Homer](https://upload.wikimedia.org/wikipedia/commons/5/57/Homeros_MFA_Munich_51.jpg){ width="240" } <figcaption>(Image credit: CC Wikimedia Commons)</figcaption> </figure> Homer (VIII century) wrote in Odyssey (chant II) that Telemachus, son of Ulysses and Penelope, was worried because many pretenders to the throne were harassing his mother. He asked soldiers to protect her by forming an agora (Greek word for an assembly). It is attributed to the same writer the use of the word _ageirien laon_, that means to congregate the army. ### Hippodamus of Miletus (498 BC- 408 BC). <figure markdown> ![Hippodamus of Miletus](figs/vol-I-Chap-1-sect-2-Hippodamus.png){ width="240" } <figcaption>(Image credit: Geogebra.org)</figcaption> </figure> One of the first urban architects Hippodamus of Miletus (498 BC- 408 BC) rebuild Miletus around 479 BC. The city was sacked and destroyed by Persians in 490 BC. The map made by Hippodamus shows an ordered reticular structure having an agora as its center with broader and straight streets (Figure 1.4a). For comparison, plans of other old sites are shown in Figure 1.4, b, c and d. !!! question "The agora." As a part of a demystification and rationalization process of the social life, the agora was a center for political actions and decisions with social, urban and cultural implications for the community. In that place democracy and law application were expressions of equality, equilibrium, symmetry and reciprocity. This was an indication of the appearance of new politically centralized institutions. See Figure 1.4. <!-- HTML Table 1.1.1--> <table width="100%"> <tr> <th width="50%"> <img src="https://upload.wikimedia.org/wikipedia/commons/f/ff/Miletos_stadsplan_400.jpg" width=300 align=center> </th> <th width="50%"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/Teotihuacan_completo.jpg/280px-Teotihuacan_completo.jpg" width=200 align=center> </th> </tr> <tr> <td> <img src="https://upload.wikimedia.org/wikipedia/commons/4/49/Karta_MachuPicchu.PNG" width=350 align=center> </td> <td> <img src="https://upload.wikimedia.org/wikipedia/commons/b/b0/Map_of_Masada.svg" width=450 align=center> </td> </tr> </table> (Images credit: CC Wikimedia Commons) **Figure 1.4.** Plans of different archeological sites: a) Mileto in Asia Minor, nearby 490 BC.; b) Sun pyramid in Teotihuacan, Mexico, nearby 450 AC; c) residential palace in Machu Pichu, Peru, nearby 1500 AC, and d) Massada in Israel, nearby 20 BC. !!! info "Astronomical and geometrical spaces." According to Vernant, the new image of the democratic Greek society went in parallel with a new image of the astronomical and geometrical spaces. This conceptual change implied overcoming astronomical Babylonian ideas as well as eliminating myths about the form of the Earth. Astronomy in Babylon characterized a religion believing that stars were divinities whose intentions might be perceived if their positions in the sky were carefully observed and registered. Scribes serving the king were in charge for registering the economic activity of the kingdom and for accounting all celestial and terrestrial events. Their knowledge was arithmetic without connections to any geometrical system of spatial representations of positions and movements. However, Greek ancient astronomy was looking for explanations about the structure of the world without appeal to divinities nor ritual ceremonies, although it was full of myths. ### Hesiod of Askra, Thebes (nearby 800 BC). <figure markdown> ![Hesiod of Askra](https://upload.wikimedia.org/wikipedia/commons/2/2c/Bust_of_Hesiod_%28%3F%29-Ancient_Roman_busts_in_the_Neues_Museum.jpg){ width="240" } <figcaption>(Image credit: CC Wikimedia Commons)</figcaption> </figure> Hesiod of Askra, Thebes (nearby 800 BC) wrote a Theogony, a mythological treatise describing the origin of gods. According to him the Earth was a vessel whose interior contained a structured world enclosed by Zeus to avoid the perception of light in the disordered world: at the upper level lived Zeus and immortal gods, then the human beings and downward death and underground gods. ### Anaximander of Miletus, Ionia, (619 – 546). <figure markdown> ![Anaximander of Miletus](https://upload.wikimedia.org/wikipedia/commons/3/38/Anaximander.jpg){ width="240" } <figcaption>(Image credit: CC Wikimedia Commons)</figcaption> </figure> Anaximander of Miletus, Ionia, (619 – 546) had a spherical notion of the universe whose center contained the Earth as a cylindrical column at equilibrium, stagnant and without falling. This was a democratic conceptualization of space were all positions and distances were mathematically defined. !!! info "Cognitive spaces in quantum statistics: fermions or bosons." The notion of quantum statistics is now analyzed by looking at two Physics Nobel Prizes: the 1945 Prize to Wolfgang Pauli “for the discovery of the Exclusion Principle, also called the Pauli Principle”, and the 1954 Prize to Max Born “for his fundamental research in quantum mechanics, especially for his statistical interpretation of the wavefunction”. The 1945 Prize was also awarded to Walther Bothe "for the coincidence method and his discoveries made therewith". Next, for each Nobel Laureate we include a brief description of his work as presented in the document called *Works* published in the Nobel wave page and indicate the titles of heir Nobel Lectures. References for both documents are mentioned in MLA format (MLA means Modern Language Association). Furthermore, each Nobel Lecture is described in two boxes: one for *Accepted knowledge or questions under discussion in Laureate´s time* and another for *Laureat´s contributions or explanations*. Complete quoted paragraphs are indicated in in between quotation marks. !!! tip "Wolfgang Pauli (1900 -1958)." WORK: "In Niels Bohr’s model of the atom, electrons move in fixed orbits around a nucleus. As this model developed, electrons were assigned certain quantum numbers corresponding to distinct states of energy and movement. In 1925, Wolfgang Pauli introduced two new numbers and formulated the Pauli principle, which proposed that no two electrons in an atom could have identical sets of quantum numbers. It was later discovered that protons and neutrons in nuclei could also be assigned quantum numbers and that Pauli’s principle applied here too." MLA style: Wolfgang Pauli – Facts. NobelPrize.org. Nobel Prize Outreach AB 2023. Sat. 25 Feb 2023. <https://www.nobelprize.org/prizes/physics/1945/pauli/facts/> NOBEL LECTURE: *Exclusion Principle and Quantum Mechanic.* MLA style: Wolfgang Pauli – Nobel Lecture. NobelPrize.org. Nobel Prize Outreach AB 2023. Sat. 25 Feb 2023. <https://www.nobelprize.org/prizes/physics/1945/pauli/lecture/> !!! bug "BOX 1.1: Accepted knowledge or questions under discussion in Pauli´s times." - Einstein relativity theories were not well understood. - The complete description of the quantum state of an electron in an atom required four quantum numbers: the principal quantum number $n$, the azimuthal quantum number $l$, the magnetic quantum number $m$, and the spin quantum number $m_s$. Uhlenbeck and Goudsmit introduced the idea of electron spin (intrinsic angular momentum). - Uhlenbeck and Goudsmit introduced the idea of electron spin (intrinsic angular momentum). - Three crucial contributions to quantum mechanics have been made: 1. Matter waves by De Broglie: To each quantum particle a wave function is associated in such a way that the square of the amplitude of the function describes the probability of occupation in space. 2. Wave mechanics equation by Schrödinger: This equation corresponds to the quantum counterpart of Newton´s second law in classical mechanics. 3. Matrix formulation by Heisenberg: The formulation of quantum mechanics serves to interpret the physical properties of particles as matrices that evolve in time. !!! quote "BOX 1.2: Pauli´s contributions or explanations." - "As soon as the symmetry classes for electrons were cleared, the question arose which are the symmetry classes for other particles with symmetrical wave functions like photons. We note that the symmetrical class for photons occurs together with the integer value 1 for their spin, while the antisymmetrical class for the electron occurs together with the half-integer value ½ for the spin." - "In order to prepare for the discussion of more fundamental questions, we want to stress here a law of Nature which is generally valid, namely, the connection between spin and symmetry class. A half-integer value of the spin quantum number is always connected with antisymmetric states (exclusion principle), an integer spin with symmetrical states. This law holds not only for protons and neutrons but also for protons and electrons. Moreover, it can easily be seen that it holds for compound systems, if it holds for all of its constituents. If we search for a theoretical explanation of this law, we must pass to the discussion of relativistic wave mechanics, since we saw that it can certainly not be explained by non-relativistic wave mechanics." - "In his lecture delivered here in Stockholm (*) he himself explained his proposal of a new interpretation of his theory, according to which in the actual vacuum all the states of negative energy should be occupied and only deviations of this state of smallest energy, namely holes in the sea of these occupied states are assumed to be observable. It is the exclusion principle which guarantees the stability of the vacuum, in which all states of negative energy are occupied. Furthermore, the holes have all properties of particles with positive energy and positive electric charge, which in external electromagnetic fields can be produced and annihilated in pairs. These predicted positrons, the exact mirror images of the electrons, have been actually discovered experimentally." (*) Pauli refers to a lecture delivered by Dirac. !!! tip "Max Born (1882-1970)." WORK: "In Niels Bohr’s theory of the atom, electrons absorb and emit radiation of fixed wavelengths when jumping between orbits around a nucleus. The theory provided a good description of the spectrum created by the hydrogen atom, but needed to be developed to suit more complicated atoms and molecules. Following Werner Heisenberg’s initial work around 1925, Max Born contributed to the further development of quantum mechanics. He also proved that Schrödinger’s wave equation could be interpreted as giving statistical (rather than exact) predictions of variables." MLA style: Max Born – Facts. NobelPrize.org. Nobel Prize Outreach AB 2023. Sat. 25 Feb 2023. <https://www.nobelprize.org/prizes/physics/1954/born/facts/> NOBEL LECTURE: *The Statistical Interpretations of Quantum Mechanics.* MLA style: Max Born – Nobel Lecture. NobelPrize.org. Nobel Prize Outreach AB 2023. Sat. 25 Feb 2023. <https://www.nobelprize.org/prizes/physics/1954/born/lecture/> !!! bug "BOX 1.3: Accepted knowledge or questions under discussion in Born´s times." * Niels Bohr introduced the idea that electronic energy levels were discrete stationary states. This assumption explained the stability of the atoms, the structure of their electronic shells, and the Periodic System of the elements. Transition between these discrete levels corresponded to quantized emissions or absorptions. * Bohr also formulated his principle of correspondence which requires that for transitions in between energy levels with very high quantum numbers the changes in energy are so small that practically coincide with the continuum of values predicted by classical mechanics. * Einstein proposed that the concept of intensity of radiation must be replaced by the statistical concept of transition probability. For each transition there must be a corresponding intensity. However, the idea of an amplitude of oscillation associated with each transition was indispensable. * Heisenberg disregarded the picture of electron orbits with definite radii and periods of rotation because these quantities were not observable. Instead of describing the motion by giving a coordinate as a function of time, $x(t)$, an array of transition amplitudes $x_{nm}$ should be determined. * By solving his equation, Schrödinger obtained the stationary states of the hydrogen atom and demonstrated the complete equivalence of the two systems of explanation: matrix mechanics and wave mechanics. Instead of speaking of electrons as particles, he considered them as continuous density distributions $‖ψ‖^2$. !!! quote "BOX 1.4: Born´s contributions or explanations." - By following Einstein’s idea that for photons the square of the optical wave amplitude represents the probability density for their occurrence, $‖ψ‖^2$ could represent the probability density for electrons (or other particles). - Introduction of the square arrays of quantities called matrices and applied to Heisenberg’s quantum condition requiring that coordinates $q$ and momenta $p$ cannot be represented by figure values but by symbols, and that their product depends upon the order of multiplication - they are “non-commuting”. - The statistical interpretation of quantum mechanics indicates that transition probabilities can be calculated if the wave function is time and space dependent as well as a function of the discrete index $n$ which enumerates the electronic stationary states. - Discussion of the essentially indeterministic statistical interpretation of quantum mechanics and the questions of reality, indeterminacy, and complementarity. *** [**Next: 1.3. Contexts learning for conceptualizing cognitive spaces.**](./vol-I-chap-1-sect-3.md)
""" Functions for reading and writing to deb_example encoded TensorFlow datasets """ from typing import Dict, List, Tuple, Callable, Iterable, Union from pathlib import Path import numpy as np import tensorflow as tf # We can store multiple configuration of the mags feature but we can publish only one. stored_mags_features = { "mags_1024_0.75": (1024, 0.75), "mags_1024_1.0": (1024, 1.0), # "mags_2048_0.75": (2048, 0.75), # "mags_2048_1.0": (2048, 1.0), "mags_4096_0.75": (4096, 0.75), "mags_4096_1.0": (4096, 1.0), } default_mags_key = "mags_1024_0.75" # pylint: disable=invalid-name (default_mags_bins, default_mags_wrap_phase) = stored_mags_features[default_mags_key] # pylint: disable=invalid-name # Python 3.7+ language spec ensures dictionary order is preserved # The full set of stored labels and any scaling applied to them when read labels_and_scales = { "rA_plus_rB": 1., "k": 1., "J": 1., "ecosw": 1., "esinw": 1., "inc": 0.01, "bP": 1., "L3": 1., "cosi": 1., "sini": 1. } # Extra features other than the light-curve used for predictions extra_features_and_defaults = { "phiS": 0.5, # Phase of secondary eclipse; correlated with ecosw "dS_over_dP": 1.0, # Ratio of eclipse durations; correlated with esinw } # The deb Example protobuf description used by tf.Datasets description = { # General purpose identifier "id": tf.io.FixedLenFeature([], tf.string, default_value=""), # Every label is expected to have a single float value **{ k: tf.io.FixedLenFeature([], tf.float32, default_value=0.) for k in labels_and_scales }, # Complex features: multiple configs of the phase folded light-curve mags **{ k: tf.io.FixedLenFeature((bins,), tf.float32, [0.] * bins) for (k, (bins, _)) in stored_mags_features.items() }, # Extra features are expected to have a single float value each **{ k: tf.io.FixedLenFeature([], tf.float32, default_value=v) for k, v in extra_features_and_defaults.items() }, } # Common options used when reading or writing a deb Example dataset file ds_options = tf.io.TFRecordOptions(compression_type=None) def create_mags_key(mags_bins: int, mags_wrap_phase: float) -> str: """ Helper function to format a key to the stored_mags_features dict """ return f"mags_{int(mags_bins)}_{float(mags_wrap_phase)}" def serialize(identifier: str, labels: Dict[str, float], mags_features: Dict[str, List[float]], extra_features: Dict[str, float]) -> bytearray: """ Encode the requested test instance data to a TF Example protobuf. :identifier: unique id of the instance :labels: the training labels :mags_features: the various configurations of phase folded time series magnitude data :extra_features: single value features associated with the light-curve :returns: a bytearray containing the serialized data """ if default_mags_key not in mags_features: raise ValueError(f"The published {default_mags_key} not found in mags_features.") features = { "id": _to_bytes_feature(identifier), # Labels - will raise KeyError if an expected label is not given **{ k: _to_float_feature(labels[k]) for k in labels_and_scales }, # Various supported configurations of the magnitudes feature. Will error if bins wrong? ** { k: _to_float_feature(v) for (k, v) in mags_features.items() if k in stored_mags_features }, # Extra features, will fall back on default value where not given **{ k: _to_float_feature(extra_features.get(k, d)) for k, d in extra_features_and_defaults.items()}, } example = tf.train.Example(features=tf.train.Features(feature=features)) return example.SerializeToString() def create_map_func(mags_bins: int = default_mags_bins, mags_wrap_phase: float = default_mags_wrap_phase, ext_features: List[str] = None, labels: List[str] = None, noise_stddev: Callable[[], float] = None, roll_steps: Callable[[], int] = None) -> Callable: """ Configures and returns a dataset map function for deb_examples. The map function is used by TFRecordDataset().map() to deserialize each raw tfrecord row into the corresponding features and labels required for model training or testing. In addition to deserializing the rows, the map function supports the option of perturbing the output magnitudes feature by adding Gaussian noise and/or rolling the bins left or right. These options are configured by supplying functions which set their stddev or roll values respectively (otherwise they do nothing). Note, these will be running within the context of a graph so you should use tf.functions if you want to do anything beyond setting a fixed value. For example: roll_steps = lambda: tf.random.uniform([], -3, 4, tf.int32) :mags_bins: the width of the mags to publish :mags_wrap_phase: the wrap phase of the mags to publish :ext_features: a chosen subset of the available ext_features, in the requested order, or all if None :labels: a chosen subset of the available labels, in requested order, or all if None :noise_stddev: a function which returns the stddev of the Gaussian noise to add :roll_steps: a function which returns the number of steps to roll the mag data, negative values roll to the left and positive values to the right :returns: the configured map function """ mags_key = create_mags_key(mags_bins, mags_wrap_phase) if ext_features is not None: chosen_ext_feat_and_defs = { ef: extra_features_and_defaults[ef] for ef in ext_features} else: chosen_ext_feat_and_defs = extra_features_and_defaults if labels is not None: chosen_lab_and_scl = { l: labels_and_scales[l] for l in labels } else: chosen_lab_and_scl = labels_and_scales # Define the map function with the two, optional perturbing actions on the mags feature def map_func(record_bytes): example = tf.io.parse_single_example(record_bytes, description) # Need to adjust the model mags slightly to get it into a shape for the model # so basically a change from (#bins,) to (#bins, 1) mags_feature = tf.reshape(example[mags_key], shape=(mags_bins, 1)) # Apply any perturbations to the model mags if noise_stddev: stddev = noise_stddev() if stddev != 0.: mags_feature += tf.random.normal(mags_feature.shape, stddev=stddev) if roll_steps: roll_by = roll_steps() if roll_by != 0: mags_feature = tf.roll(mags_feature, [roll_by], axis=[0]) # The Extra features: ignore unknown fields and use default if not found ext_features = [example.get(k, d) for (k, d) in chosen_ext_feat_and_defs.items()] ext_features = tf.reshape(ext_features, shape=(len(ext_features), 1)) # Copy labels in the expected order & apply any scaling labels = [example[k] * s for k, s in chosen_lab_and_scl.items()] return ((mags_feature, ext_features), labels) return map_func def create_dataset_pipeline(dataset_files: Iterable[str], batch_size: float=100, map_func: Callable=create_map_func(), filter_func: Callable=None, shuffle: bool=False, reshuffle_each_iteration: bool=False, max_buffer_size: int=1000000, prefetch: int=0, seed: int=42) -> Tuple[tf.data.TFRecordDataset, int]: """ Creates the requested TFRecordDataset pipeline. :dataset_files: the source tfrecord dataset files. :batch_size: the relative size of each batch. May be set to 0 (no batch, effectively all rows), <1 (this fraction of all rows) or >=1 this size (will be rounded) :map_func: the map function to use to deserialize each row :filter_func: an optional func to filter the results (must be a tf.function) :shuffle: whether to include a shuffle step in the pipeline :reshuffle_each_iteration: whether the shuffle step suffles on each epoch :max_buffer_size: the maximum size of the shuffle buffer :prefetch: the number of prefetch operations to perform :seed: seed for any random behaviour :returns: a tuple of (dataset pipeline, row count). The row count is the total rows without any optional filtering applied. """ # Read through once to get the total number of records ds = tf.data.TFRecordDataset(list(dataset_files), num_parallel_reads=100, compression_type=ds_options.compression_type) row_count = ds.reduce(0, lambda count, _: count+1).numpy() # Now build the full pipeline if shuffle or reshuffle_each_iteration: buffer_size = min(row_count, max_buffer_size) ds = ds.shuffle(buffer_size, seed, reshuffle_each_iteration=reshuffle_each_iteration) ds = ds.map(map_func) if filter_func: ds = ds.filter(filter_func) if batch_size: if batch_size < 1: batch_size = int(np.ceil(row_count * batch_size)) else: batch_size = min(row_count, int(batch_size)) if batch_size: ds = ds.batch(batch_size, drop_remainder=True) if prefetch: ds = ds.prefetch(prefetch) return (ds, row_count) def iterate_dataset(dataset_files: Iterable[str], mags_bins: int = default_mags_bins, mags_wrap_phase: float = default_mags_wrap_phase, ext_features: List[str] = None, labels: List[str]=None, identifiers: List[str]=None, scale_labels: bool=False, noise_stddev: float = 0., roll_max: int = 0): """ Utility/diagnostics function which will parse a saved dataset yielding rows, and within the rows labels and features, which match the requested criteria. The rows are yielded in the order in which they appear in the supplied dataset files. The extra_features and labels are listed in the order they have been specified or in the order of extra_features_and_defaults and labels_and_scales if not specified. This function is not for use when training a model; for that, requirement use create_dataset_pipeline() directly. Instead this gives easy access to the contents of a dataset for diagnostics lookup, testing or plotting. :dataset_files: the set of dataset files to parse :mags_bins: the width of the mags to publish :mags_wrap_phase: the wrap phase of the mags to publish :ext_features: a chosen subset of the available features, in this order, or all if None :labels: a chosen subset of the available labels, in this order, or all if None :identifiers: optional list of ids to yield, or all ids if None :scale_values: if True values will be scaled :noise_stddev: the standard deviation of Gaussian Noise to add to the mags feature :roll_max: the maximum random roll to apply to the mags feature :returns: for each matching row yields a tuple of (id, mags vals, ext feature vals, label vals) """ # pylint: disable=too-many-arguments, too-many-locals mags_key = create_mags_key(mags_bins, mags_wrap_phase) if ext_features is not None: chosen_ext_feats = { f: extra_features_and_defaults[f] for f in ext_features if f != "mags" } else: chosen_ext_feats = extra_features_and_defaults if labels is not None: chosen_labels = { l: labels_and_scales[l] for l in labels } else: chosen_labels = labels_and_scales def map_func(record_bytes): example = tf.io.parse_single_example(record_bytes, description) mags_feature = example[mags_key] # Apply any required random augmentations to the model mags if noise_stddev: mags_feature += tf.random.normal(mags_feature.shape, stddev=noise_stddev) if roll_max: roll_by = tf.random.uniform([], -roll_max, roll_max+1, tf.int32) if roll_by != 0: mags_feature = tf.roll(mags_feature, [roll_by], axis=[0]) ext_features = [example.get(k, d) for (k, d) in chosen_ext_feats.items()] if scale_labels: labels = [example[k] * s for k, s in chosen_labels.items()] else: labels = [example[k] for k in chosen_labels] return example["id"], mags_feature, ext_features, labels # Create a custom pipeline for this dataset, with the above map function (ds, count) = create_dataset_pipeline(dataset_files, 0, map_func) for id_val, mags_val, feat_vals, lab_vals in ds.take(count).as_numpy_iterator(): id_val = id_val.decode(encoding="utf8") if identifiers is None or id_val in identifiers: yield id_val, mags_val, feat_vals, lab_vals def read_dataset(dataset_files: Iterable[str], mags_bins: int = default_mags_bins, mags_wrap_phase: float = default_mags_wrap_phase, ext_features: List[str] = None, labels: List[str]=None, identifiers: List[str]=None, scale_labels: bool=False, noise_stddev: float = 0., roll_max: int = 0): """ Wrapper around iterate_dataset() which handles the iteration and returns separate np ndarrays for the dataset ids, mags values, feature values and label values. This may not be hugely performant, especially with large datasets, but it's for convenience. :dataset_files: the set of dataset files to parse :mags_bins: the width of the mags to publish :mags_wrap_phase: the wrap phase of the mags to publish :ext_features: a chosen subset of the available features, in this order, or all if None :labels: a chosen subset of the available labels, in this order, or all if None :identifiers: optional list of ids to yield, or all ids if None :scale_values: if True values will be scaled :noise_stddev: the standard deviation of Gaussian Noise to add to the mags feature :roll_max: the maximum random roll to apply to the mags feature :returns: Tuple[ NDArray[#insts, 1], NDArray[#insts, #bins], NDArray[#insts, #feats], NDArray[#insts, #labels]] """ # pylint: disable=too-many-arguments, too-many-locals ids, mags_vals, feature_vals, label_vals = [], [], [], [] for row in iterate_dataset(dataset_files, mags_bins, mags_wrap_phase, ext_features, labels, identifiers, scale_labels, noise_stddev, roll_max): ids += [row[0]] mags_vals += [row[1]] feature_vals += [row[2]] label_vals += [row[3]] # Need to sort the data in the order of the requested ids (if given). # Not hugely performant, but we only ever expect short lists of indices. if identifiers is not None and len(identifiers) > 0: indices = [ids.index(i) for i in identifiers if i in ids] ids = [ids[ix] for ix in indices] mags_vals = [mags_vals[ix] for ix in indices] feature_vals = [feature_vals[ix] for ix in indices] label_vals = [label_vals[ix] for ix in indices] return np.array(ids), np.array(mags_vals), np.array(feature_vals), np.array(label_vals) # # Helpers based on https://www.tensorflow.org/tutorials/load_data/tfrecord # def _to_bytes_feature(value) -> tf.train.Feature: """ Encodes the passed value to a BytesList in a TensorFlow feature. :value: the value to encode :returns: the resulting Feature """ if isinstance(value, type(tf.constant(0))): # BytesList won't unpack a string from an EagerTensor. value = value.numpy() elif isinstance(value, str): value = bytes(value, encoding="utf8") return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _to_float_feature(value) -> tf.train.Feature: """ Encodes the passed value to a FloatList in a TensorFlow feature. :value: the value to encode :returns: the resulting Feature """ if isinstance(value, np.ndarray): value = value.tolist() elif isinstance(value, list): pass else: value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value))
import databaseFunctions from "./databaseFunctions"; interface DataItem { field: string; name: string; type: string; value?: string | number | null; // Optional value based on type pk?: string; // Optional primary key constraint fk: string; default?: string | number | null; // Optional default value } async function generateInsertSQL( db: any, tableName: string, data: DataItem[] ): Promise<string> { // Extract field names and escape values (optional for TEXT and BLOB) const columns: string[] = []; const values: string[] = []; await Promise.all( data.map(async (item) => { const hasDefault = await databaseFunctions.checkColumnHasDefault( db, tableName, item.type.toUpperCase(), item.field ); if (item.value === "") { if (!hasDefault.bool) { // doesn't have default value columns.push(item.field); if ( item.type.toUpperCase() === "TEXT" || item.type.toUpperCase() === "BLOB" ) { values.push( item.value !== "" ? `'${String(item.value).replace(/'/g, "''")}'` : "NULL" // Escape single quotes or use NULL ); } else { values.push( String(item.value) !== "" ? String(item.value) : "NULL" ); // Include NULL for empty values } } } else { // doesn't have default value columns.push(item.field); if ( item.type.toUpperCase() === "TEXT" || item.type.toUpperCase() === "BLOB" ) { values.push( item.value !== "" ? `'${String(item.value).replace(/'/g, "''")}'` : "NULL" // Escape single quotes or use NULL ); } else { values.push(String(item.value) !== "" ? String(item.value) : "NULL"); // Include NULL for empty values } } }) ); // Form the SQL statement const sql = `INSERT INTO ${tableName} (${columns.join( ", " )}) VALUES (${values.join(", ")});`; return sql; } function generateUpdateSQL( tableName: string, data: DataItem[], id: number, id_label: string ): string { // Extract field names and values with proper handling const setClauses = data .map((item) => { let value: string; if ( item.value === null || item.value === "" || item.value === undefined ) { value = "NULL"; } else if (item.type === "TEXT") { value = `'${String(item.value).replace(/'/g, "''")}'`; // Escape single quotes } else { value = item.value.toString(); // Ensure string representation for database } return `${item.field} = ${value}`; }) .join(", "); // Form the SQL statement const sql = `UPDATE ${tableName} SET ${setClauses} WHERE ${id_label} = ${id};`; return sql; } function generateCreateTableSQL(tableName: string, data: DataItem[]): string { // Map through data to generate column definitions const fk_array: string[] = []; const columnDefinitions = data .map((item) => { let columnType: string; if (item.fk !== "No") { fk_array.push(item.fk); } switch (item.type) { case "TEXT": columnType = "TEXT"; break; case "INTEGER": columnType = "INTEGER"; break; case "REAL": columnType = "REAL"; break; case "DATE": columnType = "DATETIME DEFAULT CURRENT_TIMESTAMP"; break; default: throw new Error(`Unknown type: ${item.type}`); } let columnDefinition = `${item.name} ${columnType}`; if (item.pk) { columnDefinition += ` ${item.pk}`; // Include primary key constraint } if (item.default !== null && item.default !== undefined) { columnDefinition += ` DEFAULT ${item.default}`; // Include default value } return columnDefinition; }) .join(", "); // Form the SQL statement let sql; if (fk_array.length !== 0) { sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columnDefinitions} ${ "," + fk_array.join(",") });`; } else { sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columnDefinitions});`; } return sql; } export default { generateInsertSQL, generateUpdateSQL, generateCreateTableSQL, };
import DashboardPage from '@/pages/dashboard'; import { renderWithRouter } from '@/test_utils/createMockRouter'; import { Provider } from 'react-redux'; import { store } from '@/app/store'; import { fireEvent, screen } from '@testing-library/react'; describe('dashboard page test', function () { it('checks if the page is rendered with exact components', function () { renderWithRouter( <Provider store={store()}> <DashboardPage /> </Provider>, { query: { dev: 'true' } } ); const searchBar = screen.getByRole('textbox'); expect(searchBar).toBeInTheDocument(); const searchBtn = screen.getByRole('button', { name: 'Search', }) as HTMLButtonElement; expect(searchBtn).toBeInTheDocument(); }); it('renders 404 without passing the feature flag', function () { renderWithRouter( <Provider store={store()}> <DashboardPage /> </Provider> ); const headings = screen.getAllByRole('heading'); expect(headings).toHaveLength(1); expect(headings[0].innerHTML).toBe('404 - Page Not Found'); }); it('console logs the value', function () { console.log = jest.fn(); renderWithRouter( <Provider store={store()}> <DashboardPage /> </Provider>, { query: { dev: 'true' } } ); const input = screen.getByRole('textbox') as HTMLInputElement; fireEvent.change(input, { target: { value: 'jhon, doe' } }); const searchBtn = screen.getByRole('button', { name: 'Search', }) as HTMLButtonElement; fireEvent.click(searchBtn); const value = input.value.split(','); expect(console.log).toBeCalledWith('Searching', value); }); });
"use client" import { ChangeEvent, FormEvent, useState, useEffect } from "react"; import { useRouter, useParams } from "next/navigation"; import styles from "./new.module.css"; function FormPage() { const [newTask, setNewTask] = useState({ title: "", body: "" }) const router = useRouter() const params = useParams() const getTask = async () => { const res = await fetch(`/api/task/${params.id}`, { method: "GET" }) const data = await res.json() setNewTask({ title: data.taskFound.title, body: data.taskFound.body }) } const creatTask = async (task: object) => { try { const res = await fetch('/api/task', { method: "POST", body: JSON.stringify(task), headers: { "Content-Type": "application/json" } }) const data = await res.json() if (res.status === 200) { router.push('/') router.refresh() } } catch (error) { console.log(error); } } const handleSubmit = async (e: FormEvent) => { e.preventDefault() if (!params.id) { creatTask(newTask) } else { updateTask() } // Si no se actualizara el layout al redireccionar // router.refresh() } const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { setNewTask({ ...newTask, [e.target.name]: e.target.value }) } const updateTask = async () => { try { const res = await fetch(`/api/task/${params.id}`, { method: "PUT", body: JSON.stringify(newTask), headers: { "Content-Type": "application/json" } }) const data = await res.json() if (res.status === 200) { router.push('/') router.refresh() } } catch (error) { console.log(error); } } const handleDelete = async () => { try { if (window.confirm("Are u sure?")) { const res = await fetch(`/api/task/${params.id}`, { method: "DELETE" }) router.push('/') router.refresh() } } catch (error) { console.log(error); } } useEffect(() => { if (params.id) { getTask() } }, []) return ( <div className={styles.sub_form}> <form onSubmit={handleSubmit}> <header className={styles.sub_header}> <h1 className={styles.sub_title}> {!params.id ? "Create Task" : "Update Task"} </h1> <div> <button className={styles.sub_delete} onClick={handleDelete} type="button">Delete</button> </div> </header> <input className={styles.sub_input} onChange={handleChange} value={newTask.title} type="text" name="title" placeholder="Title" /> <textarea className={styles.sub_input} onChange={handleChange} value={newTask.body} name="body" id="bodyReq" placeholder="Description" rows={3}></textarea> <button className={styles.sub_btn} type="submit"> {!params.id ? "Create" : "Update"} </button> </form> </div> ) } export default FormPage
// Import Swiper React components import { Swiper, SwiperSlide } from "swiper/react"; import "./CarouselCastContainer.scss"; import { Lazy, Mousewheel } from "swiper"; // Import Swiper styles import "swiper/css"; import "swiper/css/mousewheel"; import { FC, useEffect, useState } from "react"; import { Box } from "@mui/system"; import { Fade, Typography } from "@mui/material"; import { useNavigate } from "react-router-dom"; interface CarouselProps { cast: Array<any>; } const CarouselCastContainer: FC<CarouselProps> = ({ cast }) => { const [loadCast, setloadCast] = useState(true); const [imgIsLoad, setImgIsLoad] = useState(true); const navigate = useNavigate(); useEffect(() => { setTimeout(() => { setloadCast(false); }, 1500); }); return ( <Swiper modules={[Lazy, Mousewheel]} lazy={true} spaceBetween={20} slidesPerView={2} mousewheel={true} className='swiper-wrapper' style={{ opacity: loadCast ? 0 : 1, marginLeft: 0, transition: "1s opacity", }} breakpoints={{ 1200: { slidesPerView: 5, spaceBetween: 65, }, 1000: { slidesPerView: 4, spaceBetween: 65, }, 700: { slidesPerView: 5, spaceBetween: 90, }, 300: { slidesPerView: 3, spaceBetween: 50, }, }}> {!loadCast && cast .filter((item: any) => item.profile_path !== null && item.gender !== 0) .map((actor: any, i: number) => { return ( <SwiperSlide key={actor.id} style={{ width: "90%" }}> <Box sx={{ width: "90%", cursor: "pointer" }} onClick={() => navigate(`/person/${actor.id}`)}> <img style={{ height: "25vh", border: "none", borderRadius: "5px" }} className='swiper-lazy' data-src={`https://image.tmdb.org/t/p/w300${actor.profile_path}`} /> <Typography sx={{ opacity: 0 }} className='swiper-lazy' data-src={null}> {actor.original_name} </Typography> </Box> </SwiperSlide> ); })} </Swiper> ); }; export default CarouselCastContainer;
import { Component, Input, OnInit } from '@angular/core'; import { Collection } from 'src/app/models/Collection'; import { Link } from 'src/app/models/Link'; import { faLink, faPencil } from '@fortawesome/free-solid-svg-icons'; import { LinksService } from '../../services/links.service'; import { FormControl } from '@angular/forms'; import { CollectionsService } from '../../services/collections.service'; import { MatDialog } from '@angular/material/dialog'; import { CollectionFormUpdateComponent } from '../collection-form-update/collection-form-update.component'; import { LinksComponent } from '../links/links.component'; import { LinkFormUpdateComponent } from '../link-form-update/link-form-update.component'; import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { ToastrService } from 'ngx-toastr'; import { RssFeed } from '../../models/RssFeed'; import { ConfirmDeleteModalComponent } from '../modals/confirm-delete-modal/confirm-delete-modal.component'; @Component({ selector: 'app-collection', templateUrl: './collection.component.html', styleUrls: ['./collection.component.scss'], }) export class CollectionComponent implements OnInit { faPencil = faPencil; faLink = faLink; public color = '#FFFFFF'; @Input() isFavCollection = false; constructor( private linksService: LinksService, private collectionService: CollectionsService, public dialog: MatDialog, private toastr: ToastrService ) {} links: Link[] = []; link!: Link; id = new FormControl(); url = new FormControl(''); title = new FormControl(''); collectionId = new FormControl(); @Input() collection!: Collection; ngOnInit() { this.collection.links?.sort((a, b) => a.position - b.position); } getLinkComment(link: Link) { return link.title ? link.title : link.url; } openConfirmationModal(): void { const dialogRef = this.dialog.open(ConfirmDeleteModalComponent, { width: '400px', data: { message: `Etes-vous sûr de vouloir supprimer la collection ${this.collection.title} ?`, }, }); dialogRef.afterClosed().subscribe((result) => { if (result) { this.deleteCollection(); } }); } deleteCollection() { this.collectionService.deleteCollection(this.collection.id).subscribe((data) => { this.collectionService.updateCollectionData(this.collection); this.toastr.success(`La collection ${this.collection.title} a été supprimée !`); }); } openDialogUpdate(enterAnimationDuration: string, exitAnimationDuration: string): void { this.dialog.open(CollectionFormUpdateComponent, { width: '280px', enterAnimationDuration, exitAnimationDuration, data: { collection: this.collection, }, }); } openDialogCreateLink(enterAnimationDuration: string, exitAnimationDuration: string): void { this.dialog.open(LinksComponent, { width: '280px', enterAnimationDuration, exitAnimationDuration, data: { collection: this.collection, }, }); } openDialogUpdateLink(link: Link, enterAnimationDuration: string, exitAnimationDuration: string): void { this.dialog.open(LinkFormUpdateComponent, { width: '280px', enterAnimationDuration, exitAnimationDuration, data: { link: link, }, }); } patchFavorite() { this.collectionService.patchFavorite(this.collection.id, !this.collection.favorite).subscribe(() => { this.collection.favorite = !this.collection.favorite; if (this.collection.favorite) { this.toastr.success(`La collection ${this.collection.title} a été ajoutée aux favoris !`); } else { this.toastr.info(`La collection ${this.collection.title} a été retirée des favoris !`); } }); } openConfirmationLinkModal(link: Link): void { const dialogRef = this.dialog.open(ConfirmDeleteModalComponent, { width: '400px', data: { link: link, message: `Etes-vous sûr de vouloir supprimer le lien ${link.title} ?`, }, }); dialogRef.afterClosed().subscribe((result) => { if (result) { this.deleteLink(link.id); } }); } deleteLink(id: number) { this.linksService.deleteLink(id).subscribe(() => { return this.collectionService.updateCollectionData(this.collection); }); } drop(event: CdkDragDrop<string[]>) { if (this.collection.links) { moveItemInArray(this.collection.links, event.previousIndex, event.currentIndex); this.collection.links?.forEach((link, index) => { link.position = index; }); const links = this.collection.links; if (links) { links.sort((a, b) => a.position - b.position); this.collectionService.updateLinksPosition(this.collection.id, links).subscribe(() => { return this.collectionService.updateCollectionData(this.collection); }); } } } }
(ns north.test.result) (use 'clojure.pprint) (def run-specs #()) (def ^:dynamic test-list {}) (defn run-specs [] (binding [test-list (assoc test-list "Feature name" {})] (println test-list))) (defstruct suite-struct :name :context-list :before-all :before-each :after-all :after-each) (defstruct context-struct :name :test-list :before-all :before-each :after-all :after-each) (defstruct test-struct :name :fun) (def tests (struct-map suite-struct :name "Feature name" :context-list [(struct-map context-struct :name "In some strange context" :test-list [(struct-map test-struct :name "it should do this" :fun #(println "--> Uhu!")) (struct-map test-struct :name "and it should do that" :fun #(println "--> Another test"))])])) (def test-count (let [count (ref 0)] #(dosync (alter count inc)))) (def ok-count (let [count (ref 0)] #(dosync (alter count inc)))) (def fail-count (let [count (ref 0)] #(dosync (alter count inc)))) (pprint tests) (println "Running tests") (dorun (map (fn [x] (dorun (map (fn [y] (println (str (:name tests) ": " (:name x) " " (:name y))) (test-count) (try (do ((:fun y)) (println "OK\n") (ok-count)) (catch Exception e (println "Error") (fail-count) (.printStackTrace e)))) (:test-list x)))) (:context-list tests))) (println (str "Ran " (dec (test-count)) " tests with 0 assertions")) (println (str (dec (ok-count)) " passed and " (dec (fail-count)) " failed."))
<?php namespace App\Controller\Api; use App\Repository\CategoryRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; #[Route('/api')] class CategoryController extends AbstractController { #[Route('/category', name: 'app_api_category', methods: ['GET'])] public function index(CategoryRepository $category): JsonResponse { $categories = $category->findAll(); return $this->json($categories, Response::HTTP_OK, [], ['groups' => 'categories']); } #[Route('/category/{id}', name: 'app_api_category_show' , methods: ['GET'])] public function show(CategoryRepository $category, int $id): JsonResponse { $category = $category->find($id); return $this->json($category, Response::HTTP_OK, [], ['groups' => 'categories']); } }
// Name: Transition // Description: Utilities for transitions // // Component: `bdt-transition-*` // // Modifiers: `bdt-transition-fade` // `bdt-transition-scale-up` // `bdt-transition-scale-down` // `bdt-transition-slide-top-*` // `bdt-transition-slide-bottom-*` // `bdt-transition-slide-left-*` // `bdt-transition-slide-right-*` // `bdt-transition-opaque` // `bdt-transition-slow` // // Sub-objects: `bdt-transition-toggle`, // `bdt-transition-active` // // States: `bdt-active` // // Variables @transition-duration: 0.3s; @transition-scale: 1.03; @transition-slide-small-translate: 10px; @transition-slide-medium-translate: 50px; @transition-slow-duration: 0.7s; Component: Transition /* Transitions /* * The toggle is triggered on touch devices by two methods: * 1. Using `:focus` and tabindex * 2. Using `:hover` and a `touchstart` event listener registered on the document * (Doesn't work on Surface touch devices) */ :where(.bdt-transition-fade), :where([class*='bdt-transition-scale']), :where([class*='bdt-transition-slide']) { --bdt-position-translate-x: 0; --bdt-position-translate-y: 0; } .bdt-transition-fade, [class*='bdt-transition-scale'], [class*='bdt-transition-slide'] { --bdt-translate-x: 0; --bdt-translate-y: 0; --bdt-scale-x: 1; --bdt-scale-y: 1; transform: translate(var(--bdt-position-translate-x), var(--bdt-position-translate-y)) translate(var(--bdt-translate-x), var(--bdt-translate-y)) scale(var(--bdt-scale-x), var(--bdt-scale-y)); transition: @transition-duration ease-out; transition-property: opacity, transform, filter; opacity: 0; } /* * Fade */ .bdt-transition-toggle:hover .bdt-transition-fade, .bdt-transition-toggle:focus .bdt-transition-fade, .bdt-transition-toggle .bdt-transition-fade:focus-within, .bdt-transition-active.bdt-active .bdt-transition-fade { opacity: 1; } /* * Scale * 1. Make image rendering the same during the transition as before and after. Prefixed because of Safari. */ /* 1 */ [class*='bdt-transition-scale'] { -webkit-backface-visibility: hidden; } .bdt-transition-scale-up { --bdt-scale-x: 1; --bdt-scale-y: 1; } .bdt-transition-scale-down { --bdt-scale-x: @transition-scale; --bdt-scale-y: @transition-scale; } /* Show */ .bdt-transition-toggle:hover .bdt-transition-scale-up, .bdt-transition-toggle:focus .bdt-transition-scale-up, .bdt-transition-toggle .bdt-transition-scale-up:focus-within, .bdt-transition-active.bdt-active .bdt-transition-scale-up { --bdt-scale-x: @transition-scale; --bdt-scale-y: @transition-scale; opacity: 1; } .bdt-transition-toggle:hover .bdt-transition-scale-down, .bdt-transition-toggle:focus .bdt-transition-scale-down, .bdt-transition-toggle .bdt-transition-scale-down:focus-within, .bdt-transition-active.bdt-active .bdt-transition-scale-down { --bdt-scale-x: 1; --bdt-scale-y: 1; opacity: 1; } /* * Slide */ .bdt-transition-slide-top { --bdt-translate-y: -100%; } .bdt-transition-slide-bottom { --bdt-translate-y: 100%; } .bdt-transition-slide-left { --bdt-translate-x: -100%; } .bdt-transition-slide-right { --bdt-translate-x: 100%; } .bdt-transition-slide-top-small { --bdt-translate-y: ~'calc(-1 * @{transition-slide-small-translate})'; } .bdt-transition-slide-bottom-small { --bdt-translate-y: @transition-slide-small-translate; } .bdt-transition-slide-left-small { --bdt-translate-x: ~'calc(-1 * @{transition-slide-small-translate})'; } .bdt-transition-slide-right-small { --bdt-translate-x: @transition-slide-small-translate; } .bdt-transition-slide-top-medium { --bdt-translate-y: ~'calc(-1 * @{transition-slide-medium-translate})'; } .bdt-transition-slide-bottom-medium { --bdt-translate-y: @transition-slide-medium-translate; } .bdt-transition-slide-left-medium { --bdt-translate-x: ~'calc(-1 * @{transition-slide-medium-translate})'; } .bdt-transition-slide-right-medium { --bdt-translate-x: @transition-slide-medium-translate; } /* Show */ .bdt-transition-toggle:hover [class*='bdt-transition-slide'], .bdt-transition-toggle:focus [class*='bdt-transition-slide'], .bdt-transition-toggle [class*='bdt-transition-slide']:focus-within, .bdt-transition-active.bdt-active [class*='bdt-transition-slide'] { --bdt-translate-x: 0; --bdt-translate-y: 0; opacity: 1; } /* Opacity modifier .bdt-transition-opaque { opacity: 1; } /* Duration modifiers .bdt-transition-slow { transition-duration: @transition-slow-duration; } // Hooks .hook-transition-misc(); .hook-transition-misc() {}
package com.cream.helper.core.net.msg.base; import com.cream.helper.core.net.common.constant.MsgMeta; import com.cream.helper.core.net.common.constant.MsgType; import com.cream.helper.utils.Times; import com.cream.helper.utils.Util; import com.google.protobuf.GeneratedMessageV3; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Parser; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Constructor; import java.util.function.Supplier; @Slf4j @Getter public abstract class Message<T extends GeneratedMessageV3> { private int msgId; private MsgType type; /** * 消息体(内容) */ private T data; private final long sendTime = Times.now(); @Setter private long receiveTime; @Setter private int serialNum; public Message(Supplier<T> dataBuilder) { this.data = dataBuilder == null ? null : dataBuilder.get(); init(); } public void setDataFromGV3(GeneratedMessageV3 protoObj) { this.data = getDataClass().cast(protoObj); } public void setDataFromBytes(byte[] data) { try { this.data = parseData(data); } catch (Exception e) { throw new RuntimeException(e); } } /** * 即使通过元信息已经能够获取msgId和type了,也仍然需要保留这两个字段; * 否则预计序列化、反序列化会出问题 */ public final void init() { MsgMeta msgMeta = getMsgMeta(); if (msgMeta == null) { log.error("消息元信息未定义 class:{}", this.getClass()); Util.errExit(); } this.msgId = msgMeta.msgId; this.type = msgMeta.msgType; } public abstract MsgMeta getMsgMeta(); public abstract Class<T> getDataClass(); public String getName() { return getClass().getSimpleName(); } @SuppressWarnings("unchecked") private T parseData(byte[] dataBytes) { if (dataBytes == null) { return null; } Class<T> dataClass = getDataClass(); T dataDefaultInstance; try { Constructor<T> constructor = dataClass.getDeclaredConstructor(); constructor.setAccessible(true); dataDefaultInstance = constructor.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } Parser<? extends GeneratedMessageV3> parserForType = dataDefaultInstance.getParserForType(); try { GeneratedMessageV3 protoInstance = parserForType.parseFrom(dataBytes); return (T) protoInstance; } catch (InvalidProtocolBufferException e) { log.error("解析proto字节出错 {}", Util.getSimpleStackTrace(), e); } return null; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="Description" content="Enter your description here" /> <title>Snacks and Bites</title> <!-- bootstrap CDN --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"> <!-- OWN CSS --> <link rel="stylesheet" href="css/style.css"> </head> <body> <!-- header design --> <header> <nav class="navbar navbar-expand-lg navigation-wrap"> <div class="container"> <a class="navbar-brand" href="#"><img class="logo-img" src="images/logo.png"></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <i class="fas fa-stream navbar-toggler-icon"></i> </button> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#home">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#about">About Us</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact Us</a> </li> <li><a href="tel:+91 9004947716"><button class="main-btn">9004947716</button></a></li> </ul> </div> </div> </nav> </header> <!-- section-1 top-banner --> <section id="home"> <div class="container-fluid px-0 top-banner"> <div class="container"> <div class="row"> <div class="col-lg-5 col-md-6"> <h1>Good food choices are good investments.</h1> <p>Savour the wholesomeness of Food with Foodies. Order the happiness home. </p> <div class="mt-4"> <button class="main-btn">Order now <i class="fas fa-shopping-basket ps-3"></i></button> </div> </div> </div> </div> </div> </section> <!-- section-2 counter --> <section id="counter"> <section class="counter-section"> <div class="container"> <div class="row text-center"> <div class="col-md-3 mb-lg-0 mb-md-0 mb-5"> <h2> <span id="count1"></span>+ </h2> <p>DELICACIES</p> </div> <div class="col-md-3 mb-lg-0 mb-md-0 mb-5"> <h2> <span id="count2"></span>+ </h2> <p>CUSTOMERS</p> </div> <div class="col-md-3 mb-lg-0 mb-md-0 mb-5"> <h2> <span id="count3"></span>+ </h2> <p>REVIEWS</p> </div> <div class="col-md-3 mb-lg-0 mb-md-0 mb-5"> <h2> <span id="count4"></span>+ </h2> <p>SAVINGS</p> </div> </div> </div> </section> </section> <!-- section-3 about--> <section id="about"> <div class="about-section wrapper"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-7 col-md-12 mb-lg-0 mb-5"> <div class="card border-0"> <img src="images/img/img-1.png" class="img-fluid"> </div> </div> <div class="col-lg-5 col-md-12 text-sec"> <h2>We pride ourselves on making real food from the best ingredients.</h2> <p>Hurry Up, we are at best home made meals provider at your door.Try us now and get best taste at best price..</p> <button class="main-btn mt-4">Learn More</button> </div> </div> </div> <div class="container food-type"> <div class="row align-items-center"> <div class="col-lg-5 col-md-12 text-sec mb-lg-0 mb-5"> <h2>We make everything by hand with the best possible ingredients.</h2> <p>We at snacks and bites mostly try to solve your budget problem on food. Get in touch and get special tiffin service at low cost.</p> <ul class="list-unstyled py-3"> <li>We deliver all orders on time.</li> <li>We provide proper packaging of every dish.</li> <li>In case of any inconvenience, you can contact us.</li> </ul> <button class="main-btn mt-4">Learn More</button> </div> <div class="col-lg-7 col-md-12"> <div class="card border-0"> <img src="images/img/img-2.png" class="img-2 img-fluid"> </div> </div> </div> </div> </div> </section> <!-- section-3 story--> <section id="story"> <div class="story-section"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="text-content"> <h2>When a man's stomach is full it makes no difference whether he is rich or poor.</h2> <p></p> <button class="main-btn mt-3">Read More</button> </div> </div> </div> </div> </div> </section> <section id="explore-food"> <div class="explore-food wrapper"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="text-content text-center"> <h2>Explore Our Foods</h2> <p>We provide a wide range of desi and authentic food with the feel of homeliness. The taste of our dishes will make you feel like it's straight from a home kitchen. We make use of authentic ingredients and no other chemicals which makes our dishes highly preferrable.</p> </div> </div> </div> <div class="row pt-5"> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-3.jpg" class="img-fluid"> <div class="pt-3"> <h4>Mattar Paneer</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-4.jpg" class="img-fluid"> <div class="pt-3"> <h4>Chana Masala</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-5.jpg" class="img-fluid"> <div class="pt-3"> <h4>Alloo Paratha</h4> <p>Fresh and Hot</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-6.jpg" class="img-fluid"> <div class="pt-3"> <h4>Mix Veg</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-7.jpg" class="img-fluid"> <div class="pt-3"> <h4>Aloo Mattar</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-8.jpg" class="img-fluid"> <div class="pt-3"> <h4>Palak Paneer</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-9.jpg" class="img-fluid"> <div class="pt-3"> <h4>Rajma Masala</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-3.jpg" class="img-fluid"> <div class="pt-3"> <h4>Matar Paneer</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-lg-0 mb-5"> <div class="card"> <img src="images/img/img-11.jpg" class="img-fluid"> <div class="pt-3"> <h4>Raita Boondi</h4> <p>Available in 3 Sizes</p> <button class="mt-4 main-btn">Order Now</button> </div> </div> </div> </div> </div> </div> </section> <!-- explore menu ---> <section id="menu"> <div class="menu-section"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="text-content"> <h2>Explore Our Menu</h2> <img class="menu-img img-fluid" src="../images/img/menu-card.jpeg"> </div> </div> </div> </div> </div> </section> <!-- section-4 explore food--> <!-- Section-5 testimonial--> <!-- <section id="testimonial"> <div class="wrapper testimonial-section"> <div class="container text-center"> <div class="text-center pb-4"> <h2>Testimonial</h2> </div> <div class="row"> <div class="col-sm-12 col-lg-10 offset-lg-1"> <div id="carouselExampleDark" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleDark" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleDark" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleDark" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <div class="carousel-caption"> <img src="images/review/review-1.jpg"> <p>"The food is extremely delicious and finger-licking and the service provided by the Restaurant is superb, highly recommended."</p> <h5>Bob Fernandes - Mumbai</h5> </div> </div> <div class="carousel-item"> <div class="carousel-caption"> <img src="images/review/review-2.jpg"> <p>"The food is extremely delicious and finger-licking and the service provided by the Restaurant is superb, highly recommended."</p> <h5>Mahima Chaudhary - Thane</h5> </div> </div> <div class="carousel-item"> <div class="carousel-caption"> <img src="images/review/review-1.jpg"> <p>"The food is extremely delicious and finger-licking and the service provided by the Restaurant is superb, highly recommended."</p> <h5>Gaurav Sinha - Mumbai</h5> </div> </div> </div> </div> </div> </div> </div> </div> </section> --> <!-- section-6 faq--> <section id="faq"> <div class="faq wrapper"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="text-center pb-4"> <h2>Frequently Asked Questions</h2> </div> </div> </div> <div class="row pt-5"> <div class="col-sm-6 mb-4"> <h4><span>~</span>Do you deliver at Home ?</h4> <p>Yes, we deliver at your door with proper safety and hygeine. </p> </div> <div class="col-sm-6 mb-4"> <h4><span>~</span>Do you provide cutlery ?</h4> <p>Yes, we provide cutlery and proper packing of all food items. We ensure evry safety for the food. </p> </div> <div class="col-sm-6 mb-4"> <h4><span>~</span>Can I order your products online?</h4> <p>Yes, we are available on zomAto and swiggy both. We are coming with our application as well. </p> </div> <div class="col-sm-6 mb-4"> <h4><span>~</span>When are you opening a shop near me?</h4> <p>Very soon, Please support us to grow and serve your better. </p> </div> </div> </div> </div> </section> <!-- section-7 book-food--> <section id="book-food"> <div class="book-food"> <div class="container book-food-text"> <div class="row text-center"> <div class="col-lg-9 col-md-12"> <h2>Cooked fresh daily by Chefs with passion.</h2> </div> <div class="col-lg-3 col-md-12 mt-lg-0 mt-4"> <button class="main-btn">Learn more</button> </div> </div> </div> </div> </section> <!-- section-8 newslettar--> <section id="newslettar"> <div class="newslettar wrapper"> <div class="container"> <div class="row"> <div class="sol-sm-12"> <div class="text-content text-center pb-4"> <h2>Hurry up!</h2> <p>Limited time offer for this month.</p> </div> <form class="newsletter"> <div class="row"> <div class="col-md-8 col-12"> <input class="form-control" placeholder="Email Address here" name="email" type="email"> </div> <div class="col-md-4 col-12"> <button class="main-btn" type="submit">Send Mail</button> </div> </div> </form> </div> </div> </div> </div> </section> <!-- section-9 footer--> <footer id="footer"> <div class="footer py-5"> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <a class="footer-link" href="#">Home</a> <a class="footer-link" href="#">About</a> <a class="footer-link" href="#">Explore our Menu</a> <a class="footer-link" href="#">Contact Us</a> <div class="footer-social pt-4 text-center"> <a href="#"><i class="fab fa-facebook-f"></i></a> <a href="#"><i class="fab fa-twitter"></i></a> <a href="#"><i class="fab fa-youtube"></i></a> <a href="#"><i class="fab fa-dribbble"></i></a> <a href="#"><i class="fab fa-linkedin"></i></a> <a href="#"><i class="fab fa-instagram"></i></a> </div> </div> <div class="col-sm-12"> <div class="footer-play"> <div class="play-link text-center pt-4"> </div> </div> </div> <div class="col-sm-12"> <div class="footer-copy"> <div class="copy-right text-center pt-4"> <p class="text-light">© 2022. Snacks and Bites. All rights reserved.</p> </div> </div> </div> </div> </div> </div> </footer> <!-- Scroll Reveal --> <script src="https://unpkg.com/scrollreveal"></script> <!-- JS Libraries --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js"></script> <!-- Custom js --> <script src="js/main.js"></script> </body> </html>
<template> <form @submit.prevent="handleSubmit"> <label for="default-search" class="mb-2 text-sm font-medium text-gray-900 sr-only dark:text-white">Search</label> <div class="relative"> <div class="absolute inset-y-0 start-0 flex items-center ps-3 pointer-events-none"> <svg class="w-4 h-4 text-gray-500 dark:text-gray-400" aria-hidden="true" fill="none" viewBox="0 0 20 20"> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"/> </svg> </div> <input type="search" v-model="redditUrl" id="default-search" class="block w-full p-4 ps-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Download Reddit URL..." required> <button type="submit" class="text-white absolute end-2.5 bottom-2.5 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Enter</button> </div> </form> </template> <script> import {router} from "@inertiajs/vue3"; export default { data() { return { redditUrl: '', }; }, methods: { handleSubmit() { let inputUrl = this.redditUrl; // Check if the URL starts with http:// or https://, if not, prepend it if (!inputUrl.match(/^[a-zA-Z]+:\/\//)) { inputUrl = 'https://' + inputUrl; } try { const url = new URL(inputUrl); const path = url.pathname; if (path) { console.log(path); this.$inertia.visit(path); } else { alert('Invalid Reddit URL'); } } catch (e) { alert('Invalid URL format'); } }, }, }; </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ejercicio 1-2</title> </head> <body> <!-- 1. Crear un archivo HTML, que contenga un encabezado <h1> seguido de un párrafo y un encabezado <h2> seguido de otro párrafo. Después, hacer que un párrafo se muestre en negrita y el otro en itálica. Utilizar saltos de línea si los consideran necesarios. 2. Ahora vamos a tener que centrar nuestros encabezados y nuestros párrafos alinearlos a la izquierda. A continuación, después del último párrafo vamos a tener que crear una lista ordenada de lo que queramos. Tendremos que mostrar la lista donde la enumeración sean letras del alfabeto. Sin usar CSS --> <div> <h1 style="text-align: center;"> Eduardo Manuel Moreno </h1> <h2 style="text-align: right;"> Soy un programador junior recién iniciado en el campo de la tecnología. Desde mi infancia, siempre he sentido una gran fascinación por la tecnología y la informática, y por ello decidí estudiar programación. Me gradué recientemente y ahora estoy ansioso por poner mis habilidades en práctica y continuar creciendo como profesional en el campo de la programación. <br> Una de mis principales fortalezas es mi capacidad para aprender y mejorar constantemente. Soy un apasionado de la programación y siempre estoy buscando nuevas formas de desarrollar mis habilidades. Actualmente estoy trabajando en proyectos personales para expandir mi conocimiento en diferentes áreas de la programación. </h2> <h2><i> Además, soy un colaborador comprometido y un solucionador de problemas apasionado. Me encanta trabajar en equipo y colaborar con otros profesionales para crear soluciones innovadoras y de alta calidad. Estoy convencido de que la programación es una disciplina en constante evolución, y por ello estoy siempre en busca de nuevas oportunidades para aprender y crecer profesionalmente. <br> Si buscas un programador junior talentoso y motivado, por favor no dudes en contactarme a través de LinkedIn. Me encantaría unirme a un equipo de trabajo que comparta mi visión y mis valores, y que esté comprometido con el desarrollo de soluciones innovadoras y de alta calidad. ¡Será un placer trabajar contigo y ayudar a llevar tus proyectos al siguiente nivel!</i> </h2> </div> <div> <ul> <li type="A"> Programacion</li> <li type="A"> Estudios</li> <li type="A"> Constancia</li> <li type="A"> Ezfuerzo</li> <li type="A"> Dedicacion</li> <li type="A"> Manejo del Stress</li> </ul> </div> </body> </html>
import { navLinks } from "../constants/index"; import { logo } from "../assets/index"; import { useEffect, useRef, useState } from "react"; import { FaBarsStaggered } from "react-icons/fa6"; const Navbar = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const linksContainerRef = useRef(null); const linksRef = useRef(null); useEffect(() => { const linksHeight = linksRef.current.getBoundingClientRect().height; console.log(linksHeight); isMenuOpen ? (linksContainerRef.current.style.height = `${linksHeight + 8}px`) : (linksContainerRef.current.style.height = "0px"); }, [isMenuOpen]); return ( <header className="fixed left-0 right-0 top-0 backdrop-blur-md z-50 px-4 mb-8 max-w-[1536px] mx-auto md:px-16 lg:px-20"> <nav className="flex justify-between py-4"> {/* <!-- logo --> */} <a href="#"> <img src={logo} alt="logo" className="w-28" /> </a> {/* <!-- items --> */} <div className="hidden lg:flex"> <ul className="capitalize space-x-11 text-lg text-[#BFBEC4] flex"> {navLinks.map(item => ( <li key={item.id} className="hover:text-white transition"> <a href={`#${item.id}`}> {item.title} </a> </li> ))} </ul> </div> {/* <!-- toggle-btn --> */} <div className="block lg:hidden cursor-pointer text-2xl" onClick={() => setIsMenuOpen(prev => !prev)} > <FaBarsStaggered /> </div> </nav> {/* <!-- mobile-menu --> */} <div ref={linksContainerRef} className="backdrop-blur-md transition-[height] duration-300 h-0 overflow-hidden" > <ul ref={linksRef} className="flex flex-col items-center gap-3"> {navLinks.map(item => ( <li key={item.id} className="hover:text-white transition"> <a href={`#${item.id}`}>{item.title}</a> </li> ))} </ul> </div> {/* <!-- mobile-menu end --> */} </header> ); }; export default Navbar;
import { useContext, useState } from "react"; import { CartContext } from "../../context/CartContext"; import { Container, Stack, Title, Flex, Button, Text } from "@mantine/core"; import caixaMedicamento from "../../assets/caixa-remedio.png"; import Checkout from "./Checkout"; function Cart() { const { cartItems, addToCart, removeFromCart, clearCart, getCartTotal } = useContext(CartContext); const [showAddresses, setShowAddresses] = useState(false); function isImage(url) { return /\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url); } return ( <Container> <Title order={1} mt="lg" ta="center"> Carrinho </Title> <Stack bg="#DCE4F5" mt="md" mb="md" p="sm"> {cartItems.map((item) => ( <Flex direction="col" justify="space-between" key={item.id}> <Flex> <img src={ isImage(item.imageLink) ? item.imageLink : caixaMedicamento } alt={item.title} className="rounded-md h-24" height={100} /> <div className="flex flex-col"> <h2 className="text-lg font-bold"> {item.name} {item.dosage} {item.unitDosage} </h2> <p className="text-gray-600">R$ {item.unitPrice}</p> </div> </Flex> <Flex align="center"> <Button onClick={() => { addToCart(item, 1); }} > <Text ta="center">+</Text> </Button> <Text size="xl" m="sm"> {item.quantity_cart} </Text> <Button onClick={() => { if (item.quantity_cart == 1) removeFromCart(item); else addToCart(item, -1); }} > <b>-</b> </Button> </Flex> </Flex> ))} </Stack> {cartItems.length > 0 ? ( <Container> <Flex bg="#DCE4F5" mt="md" mb="md" p="sm" justify="space-between"> <h2 className="text-lg font-bold">Total: R$ {getCartTotal()}</h2> <Button onClick={() => { clearCart(); }} > Limpar carrinho </Button> </Flex> <Button size="xl" onClick={() => setShowAddresses(true)}> Finalizar compra </Button> </Container> ) : ( <h1 className="text-lg font-bold">Seu carrinho está vazio</h1> )} {showAddresses ? <Checkout></Checkout> : null} </Container> ); } export default Cart;
import { CreateProjectDto, ProjectForm, UpdateProjectDto, } from '../interfaces/project.interface' import { translate } from './language.utils' export const getProjectResponseTranslation = ( isSuccess: boolean, isUpdate: boolean ) => { if (isSuccess) { return { title: translate(isUpdate ? 'PROJECT_UPDATED' : 'PROJECT_CREATED'), description: translate( isUpdate ? 'PROJECT_UPDATED_DESCRIPTION' : 'PROJECT_CREATED_DESCRIPTION' ), } } return { title: translate( isUpdate ? 'PROJECT_UPDATED_ERROR' : 'PROJECT_CREATED_ERROR' ), description: translate( isUpdate ? 'PROJECT_UPDATED_ERROR_DESCRIPTION' : 'PROJECT_CREATED_ERROR_DESCRIPTION' ), } } export const projectFormToProjectDTO = ( project: ProjectForm, userEmail: string ): CreateProjectDto | UpdateProjectDto => ({ ...project, listing: project.listing.map((item) => item.name), co2EstimateReduction: [ project.co2EstimateReduction.min, project.co2EstimateReduction.max, ], owner: userEmail, }) export const deleteProjectResponseTranslation = ( isSuccess: boolean, isDelete: boolean ) => { if (isSuccess) { return { title: translate(isDelete ? 'PROJECT_RESTORED' : 'PROJECT_DELETED'), description: translate( isDelete ? 'PROJECT_RESTORED_DESCRIPTION' : 'PROJECT_DELETED_DESCRIPTION' ), } } return { title: translate( isDelete ? 'PROJECTED_RESTORED_ERROR' : 'PROJECTED_DELETE_ERROR' ), description: translate( isDelete ? 'PROJECT_RESTORED_ERROR_DESCRIPTION' : 'PROJECT_DELETE_ERROR_DESCRIPTION' ), } }
<template> <view> <!-- scroll-view --> <scroll-view scroll-x class="scroll"> <view class="group"> <view class="item" v-for=" item in imgs" :key="item.id"> <image :src="item.src" :alt="item.src"> </view> </view> </scroll-view> <view class="form box"> <form @submit="formSubmit" @reset="formReset"> <view class="row"> <view class="title">邮箱</view> <input class="uni-input" name="email" placeholder="请输入邮箱" :value="formData.email" /> </view> <view class="row"> <view class="title">密码</view> <input class="uni-input" name="psw" placeholder="请输入密码" password maxlength="16" :value="formData.psw" /> </view> <view class="btns"> <button form-type="submit">登录</button> <button form-type="reset">重置</button> </view> </form> </view> </view> </template> <script> import graceChecker from "../../common/graceChecker.js" export default { data() { return { formData: {}, rule: [{ name: "email", checkType: "email", checkRule: "", errorMsg: "邮箱格式错误" }, { name: "psw", checkType: "string", checkRule: "6,16", errorMsg: "请输入6~16位密码" }, ], imgs: [{ id: 2, src: '/static/2.jpg' }, { id: 3, src: '/static/3.jpg' }, { id: 4, src: '/static/4.jpg', }, { id: 5, src: '/static/5.jpg' }, { id: 6, src: '/static/6.jpg', }, ], } }, onLoad(e) { this.formData = { email: e.email, psw: e.psw } console.log(this.formData); this.formReset() }, methods: { formSubmit: function(e) { this.formData = e.detail.value const checkRes = graceChecker.check(this.formData, this.rule) if (checkRes) { uni.showToast({ title: "验证通过!", icon: "none" }); this.submit() } else { uni.showToast({ title: graceChecker.error, icon: "none" }); } }, formReset: function(e) { console.log('清空数据') this.formData = {} }, submit() { uni.showLoading({ title: '加载中' }); setTimeout(function () { uni.hideLoading(); // 登录接口 uni.navigateTo({ url: "/pages/list/list", }) }, 1000); }, } } </script> <style lang="scss"> .scroll { height: 400rpx; width: 200px; margin: 100rpx auto 50rpx auto; padding: 5rpx; border: 15rpx solid $purple-three; border-radius: 20rpx; .group { white-space: nowrap; .item { display: inline-block } } image { height: 400rpx; width: 400rpx; } } .box { width: 600rpx; margin: 50rpx auto; padding: 25rpx 15rpx; } .form { // border: 15rpx solid deeppink; border-radius: 20rpx; button { margin: 30rpx auto; background-color: $purple-three; color: white; font-weight: 700; } button:hover{ background-color: $purple-four; } label { margin: 0 15rpx } .row { padding: 15rpx; } .agree { font-size: 14rpx; text-align: center; } .title { padding: 15rpx 0; } .btns { width: 600rpx } .hover_btn { background-color: deeppink; } } </style>
/** * Copyright (c) 2013 Oculus Info Inc. * http://www.oculusinfo.com/ * * Released under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package spimedb.cluster.tracks; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spimedb.cluster.DataSet; import spimedb.cluster.Instance; import spimedb.cluster.feature.spatial.TrackFeature; import spimedb.cluster.feature.spatial.centroid.TrackCentroid; import spimedb.cluster.feature.spatial.distance.TrackDistance; import spimedb.cluster.unsupervised.cluster.Cluster; import spimedb.cluster.unsupervised.cluster.ClusterResult; import spimedb.cluster.unsupervised.cluster.kmeans.KMeans; import spimedb.cluster.validation.unsupervised.external.BCubed; import spimedb.util.geom.cartesian.CubicBSpline; import spimedb.util.geom.geodesic.Position; import spimedb.util.geom.geodesic.PositionCalculationParameters; import spimedb.util.geom.geodesic.PositionCalculationType; import spimedb.util.geom.geodesic.Track; import spimedb.util.geom.geodesic.tracks.GeodeticTrack; import spimedb.util.math.linearalgebra.Vector; import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import java.util.Random; public class TestTrackCluster { protected static final Logger log = LoggerFactory.getLogger("TestTrackCluster.class"); private static final PositionCalculationParameters GEODETIC_PARAMETERS = new PositionCalculationParameters(PositionCalculationType.Geodetic, 0.0001, 1E-8, false); public void clusterRandomTracks (int N, int T, int P, boolean visible) { TrackFrame frame = new TrackFrame(); DataSet ds = new DataSet(); log.info("Creating {} track splines as bases", N); // Create N track bases Rectangle2D bounds = new Rectangle2D.Double(12.5, 6.172, 1.521, 2.5); frame.setDrawingBounds(bounds); CubicBSpline[] trackBases = new CubicBSpline[N]; for (int i=0; i<N; ++i) { trackBases[i] = randomBoundedSpline(bounds); frame.addSpline(trackBases[i]); } log.info("Creating {} track per track bases", T); // Now create a hundred random tracks from each List<Track> tracks = new ArrayList<>(); for (int j=0; j<T; ++j) { for (int i=0; i<N; ++i) { Track track = new GeodeticTrack(GEODETIC_PARAMETERS, randomPoints(trackBases[i], P)); // add the track as an instance to the dataset Instance inst = new Instance(); TrackFeature feature = new TrackFeature("track"); feature.setValue(track); inst.addFeature(feature); inst.setClassLabel( Integer.toString(i)); // set the generating spline as the class label for verification ds.add(inst); tracks.add(track); } } log.info("Clustering {} tracks", ds.size()); // Cluster the tracks in N clusters. KMeans clusterer = new KMeans(N, 10, false); clusterer.registerFeatureType( "track", TrackCentroid.class, new TrackDistance(1.0)); ClusterResult clusterResults = clusterer.doCluster(ds); frame.addClusters(clusterResults); log.info("Validating track clusters"); // validate the clustering BCubed validator = new BCubed(); validator.validate(frame.getClusters()); log.info("Precision: {} ", validator.getPrecision()); log.info("Recall: {} ", validator.getRecall()); log.info("BCubed: {} ", validator.getBCubed()); if (visible) frame.showAndWait(); } private CubicBSpline randomBoundedSpline (Rectangle2D bounds) { double width = bounds.getWidth(); double height = bounds.getHeight(); double minX = bounds.getMinX(); double minY = bounds.getMinY(); int N = (int) Math.round(3 + Math.random() * 3); // Get our times double[] times = new double[N]; for (int i=0; i<N; ++i) { if (0 == i) times[i] = 0.0; else times[i] = times[i-1] + Math.random(); } double totalTime = times[N-1]; List<Vector> points = new ArrayList<>(); for (int i = 0; i < N; ++i) { times[i] = times[i] / totalTime; points.add(new Vector(minX + Math.random() * width, minY + Math.random() * height)); } return CubicBSpline.fit(times, points); } private List<Position> randomPoints (CubicBSpline basis, int N) { N = (int) Math.round(N + N*(Math.random()-Math.random())/2.0); double[] times = new double[N]; for (int i=0; i<N; ++i) { if (0 == i) times[i] = 0; else times[i] = times[i-1]+Math.random(); } double totalTime = times[N-1]; List<Position> points = new ArrayList<>(N); for (int i=1; i<N-1; ++i) { double t = times[i]/totalTime; Vector point = basis.getPoint(t); points.add(new Position(point.coord(0), point.coord(1))); } return points; } private static class TrackFrame extends TestFrame { private static final long serialVersionUID = 1L; private final List<CubicBSpline> _splines; private final List<Cluster> _clusters; private Rectangle2D _drawingBounds; public TrackFrame () { _splines = new ArrayList<>(); _clusters = new ArrayList<>(); _drawingBounds = null; } public void setDrawingBounds (Rectangle2D bounds) { _drawingBounds = bounds; } public void addSpline (CubicBSpline spline) { _splines.add(spline); } public void addClusters (Iterable<Cluster> clusters) { for (Cluster cluster: clusters) { _clusters.add(cluster); } } public List<Cluster> getClusters () { return _clusters; } private Rectangle2D getDrawingBounds () { if (null != _drawingBounds) return _drawingBounds; double minX = Double.MAX_VALUE; double maxX = -Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxY = -Double.MAX_VALUE; // For now, brute-force it; we'll put in max/min functions later. for (CubicBSpline s: _splines) { for (double t=0; t<=1.0; t += 0.01) { Vector v = s.getPoint(t); if (v.coord(0) < minX) minX = v.coord(0); if (v.coord(0) > maxX) maxX = v.coord(0); if (v.coord(1) < minY) minY = v.coord(1); if (v.coord(1) > maxY) maxY = v.coord(1); } } return new Rectangle2D.Double(minX, minY, maxX-minX, maxY-minY); } @Override public void paint (Graphics g) { Color[] colors = new Color[_splines.size()]; Random rnd = new Random(); // randomly associate a color with each spline for (int i = 0; i < colors.length; i++) { colors[i] = new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)); } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Rectangle2D bounds = getDrawingBounds(); bounds = new Rectangle2D.Double(bounds.getMinX()-bounds.getWidth()/10.0, bounds.getMinY()-bounds.getHeight()/10.0, bounds.getWidth()*1.2, bounds.getHeight()*1.2); double pixelsPerUnit = Math.min(size.width/bounds.getWidth(), size.height/bounds.getHeight()); double zeroX = bounds.getMinX(); double zeroY = bounds.getMaxY(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, size.width, size.height); // draw the ground truth splines for reference for (int i=0; i<_splines.size(); ++i) { g2.setColor( colors[i] ); g2.setStroke(new BasicStroke(4.0f)); CubicBSpline spline = _splines.get(i); spline.draw(g2, zeroX, zeroY, pixelsPerUnit, 100); } int i = 0; // draw the actual tracks - color by cluster they are assigned to for (Cluster cluster : _clusters) { Color color = colors[i]; i++; for (Instance inst: cluster.getMembers()) { Track track = ((TrackFeature)inst.getFeature("track")).getValue(); g2.setColor(color.darker()); g2.setStroke(new BasicStroke(1.0f)); Point ptLast = null; for (Position p: track.getPoints()) { Point pt = new Point((int) Math.round((p.getLongitude()-zeroX)*pixelsPerUnit), (int) Math.round((zeroY-p.getLatitude())*pixelsPerUnit)); if (null != ptLast) g.drawLine(ptLast.x, ptLast.y, pt.x, pt.y); ptLast = pt; } } } } } public static void main(String[] args) { TestTrackCluster test = new TestTrackCluster(); test.clusterRandomTracks(5, 10, 30, true); } }
import 'package:flutter/cupertino.dart'; import 'package:texnomart/data/models/catalog_page_model.dart'; import 'package:texnomart/data/models/detail_model.dart'; import 'package:texnomart/ui/pages/brands_page/brands_child_widget.dart'; import 'package:texnomart/ui/pages/brands_page/brands_page.dart'; import 'package:texnomart/ui/pages/catalog_categories_page/catalog_categories_page.dart'; import 'package:texnomart/ui/pages/catalog_categories_page/widgets/categories_child_widget.dart'; import 'package:texnomart/ui/pages/catalog_page/catalog_page.dart'; import 'package:texnomart/ui/pages/childs_product_page/childs_product_page.dart'; import 'package:texnomart/ui/pages/cities_page/cities_page.dart'; import 'package:texnomart/ui/pages/detail_page/detail_page.dart'; import 'package:texnomart/ui/pages/detail_page/widgets/detail_characterics_widget.dart'; import 'package:texnomart/ui/pages/detail_page/widgets/detail_documentaion_widget.dart'; import 'package:texnomart/ui/pages/detail_page/widgets/detail_market_widget.dart'; import 'package:texnomart/ui/pages/language_page/language_page.dart'; import 'package:texnomart/ui/pages/logIn_page/logIn_page.dart'; import 'package:texnomart/ui/pages/main_page/main_page.dart'; import 'package:texnomart/ui/pages/map_page/map_page.dart'; import 'package:texnomart/ui/pages/splash_page/splash_page.dart'; class AppRoutes { static const splashPage = '/splashPage'; static const languagePage = '/languagePage'; static const mainPage = '/mainPage'; static const detailPage = '/detailPage'; static const shopsPage = '/shopsPage'; static const documentationPage = '/documentationPage'; static const charactericsPage = '/charactericsPage'; static const brandsPage = '/brandsPage'; static const catalogCategoriesPage = '/catalogCategoriesPage'; static const catalogChildsPage = '/catalogChildsPage'; static const childsProductPage = '/childsProductsPage'; static const catalogPage = '/catalogPage'; static const citiesPage = '/citiesPage'; static const logInPage = '/logInPage'; static const brandsChildPage = '/brandsChildPage'; static const mapPage='/mapPage'; static Route<dynamic>? onGenerateRoute(RouteSettings routeSettings) { switch (routeSettings.name) { case AppRoutes.splashPage: return CupertinoPageRoute( builder: (context) => SplashPage(), ); case AppRoutes.languagePage: return CupertinoPageRoute( builder: (context) => LanguagePage(), ); case AppRoutes.mainPage: return CupertinoPageRoute( builder: (context) => MainPage(), ); case AppRoutes.detailPage: return CupertinoPageRoute( builder: (context) => DetailPage( id: routeSettings.arguments as int, ), ); case AppRoutes.shopsPage: return CupertinoPageRoute( builder: (context) => DetailShopsPage( shopsModel: routeSettings.arguments as List<AvailableStores>, ), ); case AppRoutes.documentationPage: return CupertinoPageRoute( builder: (context) => DetailDocumentationPage( text: routeSettings.arguments as String, ), ); case AppRoutes.charactericsPage: return CupertinoPageRoute( builder: (context) => DetailCharactericsPage( list: routeSettings.arguments as List<CharactericsModel>, ), ); case AppRoutes.brandsPage: return CupertinoPageRoute( builder: (context) => BrandsPage( brand: routeSettings.arguments as String, ), ); case AppRoutes.catalogCategoriesPage: return CupertinoPageRoute( builder: (context) => CategoriesCatalogPage( data: routeSettings.arguments as DataCatalog, ), ); case AppRoutes.catalogChildsPage: return CupertinoPageRoute( builder: (context) => CatalogChilds( childs: routeSettings.arguments as Childs, ), ); case AppRoutes.childsProductPage: return CupertinoPageRoute( builder: (context) => ChildsProducts( childsModel: routeSettings.arguments as Childs, ), ); case AppRoutes.catalogPage: return CupertinoPageRoute( builder: (context) => CatalogPage(), ); case AppRoutes.citiesPage: return CupertinoPageRoute( builder: (context) => CitiesPage(), ); case AppRoutes.logInPage: return CupertinoPageRoute( builder: (context) => LogInPage(), ); case AppRoutes.brandsChildPage: return CupertinoPageRoute( builder: (context) => BrandsChildPage(text: routeSettings.arguments as String), ); case AppRoutes.mapPage: return CupertinoPageRoute( builder: (context) => MapPage( stores: routeSettings.arguments as List<AvailableStores>, ), ); } return null; } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostSubCategoriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('post_sub_categories', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('post_category_id'); $table->text('name'); $table->char('slug', 200)->unique(); $table->longText('description'); $table->timestamps(); $table->softDeletes(); $table->index(['user_id', 'post_category_id']); $table->foreign('user_id')->references('id')->on('users'); $table->foreign('post_category_id')->references('id')->on('post_categories'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('post_sub_categories'); } }
<!--LINK TO DOWNLOAD ALL EXAMPLES--> <table width="650"> <tr> <td> <p class="license"> If you see any errors in this tutorial or have comments, please <a href="https://github.com/processing/processing-docs/issues?state=open">let us know</a>. This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>. </p> <h1 style="line-height: 0.7em;">Anatomy of a Program</h1> <h3 style="line-height: 0.7em;"><em>J David Eisenberg</em></h3> <p class="txt">&nbsp;</p> <p class="txt"> Many of the tutorials for Processing concentrate on what the language can do (change colors, draw shapes, create arrays of objects) and which function calls will let you accomplish these tasks. These are things you need to know in order to write a program in Processing. </p> <p class="txt"> There&rsquo;s one piece of the puzzle that these tutorials don&rsquo;t address: how do you analyze a problem and break it down into steps that the computer can do? In this tutorial, I&rsquo;m going to show you what went through my head as I took on the task of writing functions to draw regular polygons and star-shaped figures in Processing. This is a good choice because the task is not too big to get your mind around, but it&rsquo;s not an entirely trivial problem, either. </p> <p class="txt"> Remember that what you are seeing here is my particular thought process and programming style. There are many different approaches and styles. As you continue programming, you will find your own. You can also see other people&rsquo;s programming stye (though not their thought process!) by looking at the source code for the programs at <a href="http://openprocessing.org/">openProcessing.org</a>. </p> <h3>Drawing Regular Polygons</h3> <p class="txt"> You wouldn&rsquo;t think of building a house without a blueprint, and you shouldn&rsquo;t think of writing a program without a plan of some sort. Since Processing is such a visual language, I always have to sketch out what I want as a result before I approach the keyboard. So that&rsquo;s where I started. </p> <h3>Step 1: Planning on paper</h3> <p class="txt"> The first step was to draw a crude diagram to dredge up old memories of how regular polygons work. The hexagon was the first one I drew. As you can see from the little loop I drew inside the hexagon, the center angles of all the slices add up to a complete circle, or 360&deg;, and the &ldquo;radius&rdquo; of the polygon is a line from the center to each vertex. The angle between each of the radius lines is thus 360&deg; divided by the number of sides. </p> <img src="imgs/sketch1.jpg" alt="Crude diagram of regular polygons with 3-6 sides" width="400" height="120" class="tut" /> <p class="txt"> I just needed to get an idea of what the task was, and a hand-drawn diagram did the job. I didn&rsquo;t need to generate the diagram in a drawing program. </p> <blockquote> <p class="txt">Programming Hint: When you do your planning, do it away from the computer. If you are sitting in front of the computer, the screen will whisper, &ldquo;Look at me! Look at me!&rdquo; and the keyboard will whisper &ldquo;Type something! Type something!&rdquo; Go to your kitchen table instead. </p> </blockquote> <h3>Step 2: Some basic trigonometry</h3> <p class="txt"> So, if you have a line of length <em>r</em> starting at (0,0) at an angle theta (&theta;), what are its coordinates in terms of <em>x</em> and <em>y</em>? If you know a little bit of trigonometry, the answer is that the endpoint of the line is at (<em>r</em>&nbsp;cos&nbsp;&theta;,&nbsp;<em>r</em>&nbsp;sin&nbsp;&theta;). If you don&rsquo;t know trigonometry, take a look at <a href="http://catcode.com/trig/">this tutorial</a> (a general and very light introduction to trigonometry), <a href="http://processing.org/learning/trig/">this tutorial</a> (oriented towards Processing), and <a href="http://learningprocessing.com/examples/chp13/example-13-05-polar-cartesian">this example from chapter 13 of <em>Learning Processing</em></a>. In the following diagram, angles are drawn clockwise, which is how they are measured in Processing. </p> <img src="imgs/sketch2.jpg" alt="Diagram of angle showing relationship of cosine and sine" width="250" height="164" class="tut" /> <h3>Step 3: Design Decisions</h3> <p class="txt"> It looks like this is a job for a <code>for</code> loop that runs from 0 to <em>n</em> (the number of sides), calculating the points for each vertex and drawing lines connecting them. At each step, the angle at which we draw is increased by 360&deg;/<em>n</em>. </p> <p class="txt"> The problem with drawing a group of lines is that they are just lines&mdash;you don&rsquo;t get a true shape that you can fill, like <code>rect()</code> or <code>triangle()</code>. Luckily, Processing lets you create your own shapes with the <a href="http://processing.org/reference/beginShape_.html"><code>beginShape()</code></a>, <a href="file:///home/david/processing-1.0.9/reference/vertex_.html"><code>vertex()</code></a>, and <a href="http://processing.org/reference/endShape_.html"><code>endShape()</code></a> functions. The first example on the reference page for <code>beginShape()</code> is the model to follow. So the next design decision is to make polygons as true shapes.</p> <p class="txt"> Since you probably want to draw many polygons during a program, it makes sense to have a <code>polygon()</code> function. What parameters does it need? Four come to mind: the number of sides, the center <em>x</em> and <em>y</em> coordinate, and the radius. Here&rsquo;s the code. I wrote several different calls to <code>polygon()</code> in the <code>setup()</code> function. Although I calculated <code>angle</code> in degrees, sine and cosine measure angles in radians, so I had to use the <code>radians()</code> function to do a conversion. </p> <img src="imgs/polytest1.jpg" alt="polygon tests"width="200" height="200" class="tut" /> <pre> <span style="color: #33997E;">void</span> <span style="color: #006699;"><b>setup</b></span>() { &nbsp;&nbsp;<span style="color: #006699;">size</span>(300, 300); &nbsp;&nbsp;<span style="color: #006699;">background</span>(255); &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;polygon(3,&nbsp;50,&nbsp;75,&nbsp;50); &nbsp;&nbsp;polygon(4,&nbsp;170,&nbsp;75,&nbsp;50); &nbsp;&nbsp;<span style="color: #006699;">fill</span>(255, 204, 255); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128, 0, 128); &nbsp;&nbsp;polygon(5,&nbsp;50,&nbsp;180,&nbsp;50); &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(0); &nbsp;&nbsp;polygon(6,&nbsp;170,&nbsp;180,&nbsp;50); } <span style="color: #33997E;">void</span> polygon(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> r) { &nbsp;&nbsp;<span style="color: #E2661A;">float</span> angle = 360.0 / n; &nbsp;&nbsp;<span style="color: #006699;">beginShape</span>(); &nbsp;&nbsp;<span style="color: #669900;">for</span> (<span style="color: #E2661A;">int</span> i = 0; i &lt; n; i++) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">vertex</span>(cx + r * <span style="color: #006699;">cos</span>(<span style="color: #006699;">radians</span>(angle * i)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cy&nbsp;+&nbsp;r&nbsp;*&nbsp;<span style="color: #006699;">sin</span>(<span style="color: #006699;">radians</span>(angle * i))); &nbsp;&nbsp;} &nbsp;&nbsp;<span style="color: #006699;">endShape</span>(<span style="color: #718A62;">CLOSE</span>); } </pre> <h3>Two Steps Forward, One Step Back</h3> <p class="txt"> The program works, so it&rsquo;s time to see if there are things that could be added or changed. First, the triangle and pentagon seem somehow wrong; they are usually drawn pointing upwards instead of to the side. The reason they look odd is that the first vertex (at 0&deg;) points to the right instead of straight up. It would be nice to have an extra parameter that gives the starting angle for the first vertex. (Another solution is to leave things as they are and let programmers use <code>rotate()</code> [<a href="http://processing.org/learning/transform2d">see this tutorial</a>], but I made the design decision to use an extra parameter.) Should the angle be given in degrees or in radians? The answer: radians, in order to be consistent with everything else that Processing does. </p> <p class="txt"> My next thought was that it would be nice to be able to specify a width and height for the polygon, much as you do with an <code>ellipse()</code> or <code>rectangle()</code>. I already knew what the formula would be, but I wanted to make a drawing to check it out. As a preliminary experiment, I tried drawing a pentagon into a square using a protractor and straightedge, and ended up with the awful drawing at the left. How come the sides weren&rsquo;t equal length? I realized that I was trying to make the drawing fit my preconceptions, rather than making an accurate drawing and seeing where that led me. The drawing on the right was done much more carefully. After a little thinking, I realized that the pentagon wouldn&rsquo;t fit the square exactly, because the angles weren&rsquo;t multiples of 90 degrees. The regular polygon fits in a <em>circle</em>, not in a square! </p> <div style="text-align:center;"> <img src="imgs/bad_pentagon.jpg" alt="pentagon with unequal sides" width="200" height="200" style="display: inline;" class="tut" /> <img src="imgs/accurate_pentagon.jpg" alt="pentagon with equal sides" width="210" height="200" style="display: inline;" class="tut" /> </div> <p class="txt"> Well, that was a dead end. That sort of thing happens in programming all the time, so I didn&rsquo;t spend too much time worrying about it. It was time for another approach. Since I didn't have an accurate way of drawing ellipses, I had to think about the problem a different way. Presume you have a circle drawn on a square sheet of rubber, and you stretch it out so that it&rsquo;s twice as wide but the same height. The vertical position of the points on the circle does not change, but the horizontal positions are now twice as far away from the center as they used to be. The same idea applies if you stretch the sheet vertically. The following crude drawings seemed to bear this out, so it was time to rewrite the <code>polygon()</code> function. </p> <p style="text-align:center;"> <img src="imgs/stretchy.jpg" alt="diagrams showing stretched circle" width="600" height="194" class="tut" /> </p> <img src="imgs/poly2.png" alt="more complex polygon tests" width="200" height="229" class="tut" /> <pre> <span style="color: #33997E;">void</span> <span style="color: #006699;"><b>setup</b></span>() { &nbsp;&nbsp;<span style="color: #006699;">size</span>(300, 300); &nbsp;&nbsp;<span style="color: #006699;">background</span>(255); &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;polygon(3,&nbsp;50,&nbsp;75,&nbsp;100,&nbsp;100,&nbsp;-<span style="color: #718A62;">PI</span> / 2.0); <span style="color: #666666;">// -90 degrees</span> &nbsp;&nbsp;polygon(4,&nbsp;170,&nbsp;75,&nbsp;50,&nbsp;125,&nbsp;-<span style="color: #718A62;">PI</span> / 4.0); <span style="color: #666666;">// -45 degrees</span> &nbsp;&nbsp;<span style="color: #006699;">fill</span>(255, 204, 255); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128, 0, 128); &nbsp;&nbsp;polygon(5,&nbsp;50,&nbsp;200,&nbsp;75,&nbsp;50,&nbsp;-<span style="color: #718A62;">PI</span> / 2.0); <span style="color: #666666;">// -90 degrees</span> &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(0); &nbsp;&nbsp;polygon(6,&nbsp;170,&nbsp;200,&nbsp;50,&nbsp;100,&nbsp;0); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128); &nbsp;&nbsp;<span style="color: #666666;">// Draw enclosing ellipses to make sure we did it right</span> &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(50, 75, 100, 100); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(170, 75, 50, 125); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(50, 200, 75, 50); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(170, 200, 50, 100); } <span style="color: #33997E;">void</span> polygon(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> w, <span style="color: #E2661A;">float</span> h, <span style="color: #E2661A;">float</span> startAngle) { &nbsp;&nbsp;<span style="color: #E2661A;">float</span> angle = <span style="color: #718A62;">TWO_PI</span>/ n; &nbsp;&nbsp;<span style="color: #666666;">// The horizontal &quot;radius&quot; is one half the width,</span> &nbsp;&nbsp;<span style="color: #666666;">// the vertical &quot;radius&quot; is one half the height</span> &nbsp;&nbsp;w&nbsp;=&nbsp;w&nbsp;/&nbsp;2.0; &nbsp;&nbsp;h&nbsp;=&nbsp;h&nbsp;/&nbsp;2.0; &nbsp;&nbsp;<span style="color: #006699;">beginShape</span>(); &nbsp;&nbsp;<span style="color: #669900;">for</span> (<span style="color: #E2661A;">int</span> i = 0; i &lt; n; i++) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">vertex</span>(cx + w * <span style="color: #006699;">cos</span>(startAngle + angle * i), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cy&nbsp;+&nbsp;h&nbsp;*&nbsp;<span style="color: #006699;">sin</span>(startAngle + angle * i)); &nbsp;&nbsp;} &nbsp;&nbsp;<span style="color: #006699;">endShape</span>(<span style="color: #718A62;">CLOSE</span>); } </pre> <p class="txt"> Since everything was in radians, I now described angles in terms of <code>PI</code> and <code>TWO_PI</code> (2&pi;), since 2&pi; radians equals 360&deg;. In addition to the code in <code>setup()</code> to test the new features, I drew ellipses with the same center and width and height as the polygons to make sure that the vertices were within the proper area. </p> <h3>Too Many Parameters</h3> <p class="txt"> I now had a much more flexible function for drawing polygons, but it came at the expense of more parameters. It would be nice to be able to draw the ordinary case (equal width and height, start angle of zero) without having to specify all those parameters. The solution is to <dfn>overload</dfn> the function. In Processing, you can have two functions with the same name, as long as they have different numbers of parameters and/or types of parameters. An example of this is Processing&rsquo;s <code>stroke()</code> function, which is overloaded so that you can call it with one number for grayscale, three numbers for color, or four numbers for color with opacity. Processing looks at the number of arguments you provide and figures out which version of <code>stroke()</code> to call. </p> <p class="txt"> Here is the code to add to the previous example. When you give <code>polygon()</code> only four numbers, it will call the following function, which calls the &ldquo;big&rdquo; version of the function with width and height equal to twice your desired radius, and a start angle of zero. </p> <pre> <span style="color: #33997E;">void</span> polygon(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> r) { &nbsp;&nbsp;polygon(n,&nbsp;cx,&nbsp;cy,&nbsp;r&nbsp;*&nbsp;2.0,&nbsp;r&nbsp;*&nbsp;2.0,&nbsp;0.0); } </pre> <p class="txt"> And here is some code to test the overloaded function. </p> <img src="imgs/poly3.png" alt="regular triangle and diamond using overloaded functions" width="214" height="169" class="tut" /> <pre> <span style="color: #33997E;">void</span> <span style="color: #006699;"><b>setup</b></span>() { &nbsp;&nbsp;<span style="color: #006699;">size</span>(300, 300); &nbsp;&nbsp;<span style="color: #006699;">background</span>(255); &nbsp;&nbsp;<span style="color: #006699;">smooth</span>(); &nbsp;&nbsp; &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;polygon(3,&nbsp;70,&nbsp;75,&nbsp;50);&nbsp;<span style="color: #666666;">// use the defaults</span> &nbsp;&nbsp;polygon(4,&nbsp;170,&nbsp;75,&nbsp;25); &nbsp;&nbsp; &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128); &nbsp;&nbsp;<span style="color: #666666;">// draw enclosing ellipses to make sure we did it right</span> &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(70, 75, 100, 100); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(170, 75, 50, 50); } </pre> <h3>Safe Computing</h3> <p class="txt"> What happens if someone tries to draw a polygon with 2 sides, 1 side, or worse, 0 sides? The first two will generate a line and a point, but the third one will cause a division by zero error when trying to figure out the angle. And what would happen with negative numbers? Since polygons with fewer than three sides don&rsquo;t make a lot of sense, I wrapped the body of the <code>polygon()</code> function inside of an <code>if</code> statement. Now, when someone specifies two or fewer sides, the function just won&rsquo;t draw anything. </p> <pre> void polygon(int n, float cx, float cy, float w, float h, float startAngle) { if (n &gt; 2) { float angle = TWO_PI/ n; . . beginShape() . . endShape(CLOSE); } } </pre> <h3>Drawing Stars</h3> <p class="txt"> Now that I was satisfied with the <code>polygon()</code> function, it was time to move on to drawing stars. From some playing around with a crude sketch, I figured that it would be possible to draw a star by figuring out where all the diagonals of a polygon intersect. </p> <div class="text-align:center;"> <img src="imgs/bad_stars.jpg" width="450" height="204" alt="Stars drawn by intersections of diagonals" class="tut" /> </div> <p class="txt"> I saw two problems here. First, finding the intersection point of two lines is a lot of calculation. Not particularly hard calculation, but a lot of it, and it gets tricky when you have vertical lines. Second, I couldn't have a four-sided or three-sided arrow shape; there weren&rsquo;t enough diagonals. </p> <p class="txt"> Then, I had another idea. I can&rsquo;t tell you where the idea came from or how I arrived at it; it just hit me. That&rsquo;s a part of the process that I don&rsquo;t think can be taught. Here was the idea: What if you had a polygon cut out of cookie dough and you sort of pushed in the sides to make a star shape? That is a method that works for squares and triangles. </p> <div class="text-align:center;"> <img src="imgs/cookie_stars.jpg" width="450" height="128" alt="Stars drawn by pushing in the sides" class="tut" /> </div> <p class="txt"> When you push in the sides, you push them in at the midpoint so that you get a nice symmetric cookie. From there, it wasn&rsquo;t a big leap to figure out: &ldquo;what if I had a shorter radius at half of every slice of the polygon?&rdquo; </p> <div class="text-align:center;"> <img src="imgs/good_stars.jpg" width="450" height="114" alt="Stars drawn by pushing in the sides" class="tut" /> </div> <p class="txt"> This code would be fairly easy to write. I would need one extra parameter: the proportion of the small radius to the big radius. In the following code, an <code>if</code> statement controls whether to use the short radius or the long radius. I also put in an overloaded version that draws a star with equal width and height and a start angle of zero. For the test, I made the short radius one half the long radius. </p> <img src="imgs/surprise.png" width="200" height="226" alt="3, 4, 5, and 6-sided stars" class="tut" /> <pre> <span style="color: #33997E;">void</span> <span style="color: #006699;"><b>setup</b></span>() { &nbsp;&nbsp;<span style="color: #006699;">size</span>(300, 300); &nbsp;&nbsp;<span style="color: #006699;">background</span>(255); &nbsp;&nbsp;<span style="color: #006699;">smooth</span>(); &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;star(3,&nbsp;60,&nbsp;75,&nbsp;100,&nbsp;100,&nbsp;-<span style="color: #718A62;">PI</span> / 2.0, 0.50); <span style="color: #666666;">// -90 degrees</span> &nbsp;&nbsp;star(4,&nbsp;170,&nbsp;75,&nbsp;25,&nbsp;0.50);&nbsp;&nbsp;<span style="color: #666666;">// use simpler call</span> &nbsp;&nbsp;<span style="color: #006699;">fill</span>(255, 204, 255); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128, 0, 128); &nbsp;&nbsp;star(5,&nbsp;60,&nbsp;200,&nbsp;75,&nbsp;50,&nbsp;-<span style="color: #718A62;">PI</span> / 2.0, 0.50); <span style="color: #666666;">// -90 degrees</span> &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(0); &nbsp;&nbsp;star(6,&nbsp;170,&nbsp;200,&nbsp;50,&nbsp;100,&nbsp;0,&nbsp;0.50); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128); &nbsp;&nbsp; &nbsp;&nbsp;<span style="color: #666666;">// draw enclosing ellipses to make sure we did it right</span> &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(60, 75, 100, 100); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(170, 75, 50, 50); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(60, 200, 75, 50); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(170, 200, 50, 100); } <span style="color: #33997E;">void</span> star(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> r, <span style="color: #E2661A;">float</span> proportion) { &nbsp;&nbsp;star(n,&nbsp;cx,&nbsp;cy,&nbsp;2.0&nbsp;*&nbsp;r,&nbsp;2.0&nbsp;*&nbsp;r,&nbsp;0.0,&nbsp;proportion); } <span style="color: #33997E;">void</span> star(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> w, <span style="color: #E2661A;">float</span> h, &nbsp;&nbsp;<span style="color: #E2661A;">float</span> startAngle, <span style="color: #E2661A;">float</span> proportion) { &nbsp;&nbsp;<span style="color: #669900;">if</span> (n &gt; 2) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> angle = <span style="color: #718A62;">TWO_PI</span>/ (2 *n); <span style="color: #666666;">// twice as many sides</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> dw; <span style="color: #666666;">// draw width</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> dh; <span style="color: #666666;">// draw height</span> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;w&nbsp;=&nbsp;w&nbsp;/&nbsp;2.0; &nbsp;&nbsp;&nbsp;&nbsp;h&nbsp;=&nbsp;h&nbsp;/&nbsp;2.0; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">beginShape</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #669900;">for</span> (<span style="color: #E2661A;">int</span> i = 0; i &lt; 2 * n; i++) { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dw&nbsp;=&nbsp;w; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dh&nbsp;=&nbsp;h; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #669900;">if</span> (i % 2 == 1) { <span style="color: #666666;">// for odd vertices, use short radius</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dw&nbsp;=&nbsp;w&nbsp;*&nbsp;proportion; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dh&nbsp;=&nbsp;h&nbsp;*&nbsp;proportion; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">vertex</span>(cx + dw * <span style="color: #006699;">cos</span>(startAngle + angle * i), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cy&nbsp;+&nbsp;dh&nbsp;*&nbsp;<span style="color: #006699;">sin</span>(startAngle + angle * i)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">endShape</span>(<span style="color: #718A62;">CLOSE</span>); &nbsp;&nbsp;} } </pre> <h3>What Went Wrong?</h3> <p class="txt"> When I ran this program, I just freaked out. Everything looked great, except for the three-sided star. How come I didn&rsquo;t get a star from it? The code sure looks correct, so I decided to see what would happen if I drew the diagram by hand. I measured the angles with my protractor, and I drew the long radius lines with a length of two inches in black and the short radius lines with a length of one inch in red. Sure enough, it just so happens that the endpoints of the short radius lines are right on the lines of the main triangle. The program <em>is</em> drawing a star, with the sides pushed in by zero. </p> <div style="text-align:center;"> <img src="imgs/triangle_star.jpg" width="200" height="178" alt="triangular star drawn by hand" class="tut" /> </div> <p class="txt"> While wondering why this happened, I remembered that the cosine of the angle between the lines, 60&deg; (&pi;/3) comes out to 0.5, and I strongly suspected that this had something to do with it. To test my hypothesis, I changed the square to use a proportion of cosine of 45&deg; (&pi;/4), the pentagon to cosine of 36&deg; (&pi;/5), and the hexagon to cosine of 30&deg; (&pi;/6). Sure enough, they all came out with no push-in. </p> <p class="txt"> So, if you are drawing a star with <i>n</i> sides and you set the proportion for the short radius to long radius to the cos(&pi;/<i>n</i>), you get a non-star star! I still can&rsquo;t write a mathematical proof of it, but it is an interesting result. I don&rsquo;t consider that side trip of writing the test program to be wasted time; I did learn something new and mildly interesting, and it may turn out to be useful in the future. </p> <blockquote> <p class="txt"> <b>Programming Challenge:</b> What happens if you set the proportion to something <em>greater</em> than the &ldquo;non-star&rdquo; ratio? Try it and find out. </p> </blockquote> <p class="txt"> Of course, the way to get a three-sided star is to set the proportion to an amount less than 0.5, which I did in the following setup code, with much better results. I also changed the proportions for the other stars just to see what they would look like. </p> <img src="imgs/better_stars.png" width="200" height="228" alt="3, 4, 5, and 6-sided stars" class="tut"/> <pre> <span style="color: #33997E;">void</span> <span style="color: #006699;"><b>setup</b></span>(){ &nbsp;&nbsp;<span style="color: #006699;">size</span>(300, 300); &nbsp;&nbsp;<span style="color: #006699;">background</span>(255); &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;star(3,&nbsp;60,&nbsp;75,&nbsp;100,&nbsp;100,&nbsp;-<span style="color: #718A62;">PI</span> / 2.0, 0.3); <span style="color: #666666;">// -90 degrees</span> &nbsp;&nbsp;star(4,&nbsp;170,&nbsp;75,&nbsp;25,&nbsp;0.5);&nbsp;&nbsp;<span style="color: #666666;">// use simpler call</span> &nbsp;&nbsp;<span style="color: #006699;">fill</span>(255, 204, 255); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128, 0, 128); &nbsp;&nbsp;star(5,&nbsp;60,&nbsp;200,&nbsp;75,&nbsp;50,&nbsp;-<span style="color: #718A62;">PI</span> / 2.0, 0.75); <span style="color: #666666;">// -90 degrees</span> &nbsp;&nbsp;<span style="color: #006699;">noFill</span>(); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(0); &nbsp;&nbsp;star(6,&nbsp;170,&nbsp;200,&nbsp;50,&nbsp;100,&nbsp;0,&nbsp;0.4); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(128); &nbsp;&nbsp; &nbsp;&nbsp;<span style="color: #666666;">// Draw enclosing ellipses to make sure we did it right</span> &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(60, 75, 100, 100); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(170, 75, 50, 50); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(60, 200, 75, 50); &nbsp;&nbsp;<span style="color: #006699;">ellipse</span>(170, 200, 50, 100); } <span style="color: #33997E;">void</span> star(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> r, <span style="color: #E2661A;">float</span> proportion) { &nbsp;&nbsp;star(n,&nbsp;cx,&nbsp;cy,&nbsp;2.0&nbsp;*&nbsp;r,&nbsp;2.0&nbsp;*&nbsp;r,&nbsp;0.0,&nbsp;proportion); } <span style="color: #33997E;">void</span> star(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> w, <span style="color: #E2661A;">float</span> h, &nbsp;&nbsp;<span style="color: #E2661A;">float</span> startAngle, <span style="color: #E2661A;">float</span> proportion) { &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;<span style="color: #669900;">if</span> (n &gt; 2) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> angle = <span style="color: #718A62;">TWO_PI</span>/ (2 *n); <span style="color: #666666;">// twice as many sides</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> dw; <span style="color: #666666;">// draw width</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> dh; <span style="color: #666666;">// draw height</span> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;w&nbsp;=&nbsp;w&nbsp;/&nbsp;2.0; &nbsp;&nbsp;&nbsp;&nbsp;h&nbsp;=&nbsp;h&nbsp;/&nbsp;2.0; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">beginShape</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #669900;">for</span> (<span style="color: #E2661A;">int</span> i = 0; i &lt; 2 * n; i++) { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dw&nbsp;=&nbsp;w; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dh&nbsp;=&nbsp;h; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #669900;">if</span> (i % 2 == 1) { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dw&nbsp;=&nbsp;w&nbsp;*&nbsp;proportion; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dh&nbsp;=&nbsp;h&nbsp;*&nbsp;proportion; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">vertex</span>(cx + dw * <span style="color: #006699;">cos</span>(startAngle + angle * i), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cy&nbsp;+&nbsp;dh&nbsp;*&nbsp;<span style="color: #006699;">sin</span>(startAngle + angle * i)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">endShape</span>(<span style="color: #718A62;">CLOSE</span>); &nbsp;&nbsp;} } </pre> <h3>Using the Functions</h3> <p class="txt"> Finally, in order to use the functions in something other than a test, I decided to write a program that would randomly generate polygons and stars. The window is 300 by 300, and the stars or polygons have a radius of 24 dots, so I have six rows and five columns (the extra dot is for spacing). Remember how I said that knowing the proportions that would create a star &ldquo;may turn out to be useful in the future&rdquo;? Well, they aren&rsquo;t just useful for this program&mdash;they&rsquo;re vital. When I generate a star, I need to make sure it really has a star shape, so I have to keep the proportion of short to long radius less than the cosine of &pi; divided by the number of sides. </p> <p class="txt"> Here is the code for <code>setup()</code> and <code>draw()</code>: </p> <img src="imgs/randomness.png" alt="random polygons and stars" width="200" height="213" class="tut" /> <pre> <span style="color: #33997E;">void</span> <span style="color: #006699;"><b>setup</b></span>() { &nbsp;&nbsp;<span style="color: #006699;">size</span>(300, 300); &nbsp;&nbsp;<span style="color: #006699;">background</span>(255); &nbsp;&nbsp;<span style="color: #006699;">frameRate</span>(6); &nbsp;&nbsp;<span style="color: #006699;">rectMode</span>(<span style="color: #718A62;">CENTER</span>); } <span style="color: #33997E;">void</span> <span style="color: #006699;"><b>draw</b></span>() { &nbsp;&nbsp;<span style="color: #666666;">// Choose a random stroke color</span> &nbsp;&nbsp;<span style="color: #E2661A;">int</span> r = <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(0, 255)); &nbsp;&nbsp;<span style="color: #E2661A;">int</span> g = <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(0, 255)); &nbsp;&nbsp;<span style="color: #E2661A;">int</span> b = <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(0, 255)); &nbsp;&nbsp;<span style="color: #666666;">// Fill opacity</span> &nbsp;&nbsp;<span style="color: #E2661A;">int</span> opacity = <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(100, 255)); &nbsp;&nbsp;<span style="color: #E2661A;">int</span> nSides = <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(3, 9)); &nbsp;&nbsp;<span style="color: #666666;">// Determine the center x and y coordinates</span> &nbsp;&nbsp;<span style="color: #E2661A;">int</span> cx = 25 + 50 * <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(0, 6)); &nbsp;&nbsp;<span style="color: #E2661A;">int</span> cy = 25 + 50 * <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(0, 6)); &nbsp;&nbsp;<span style="color: #666666;">// If a random number (0 or 1) is 0, draw a polygon;</span> &nbsp;&nbsp;<span style="color: #666666;">// otherwise, draw a star</span> &nbsp;&nbsp;<span style="color: #E2661A;">boolean</span> isPolygon = <span style="color: #006699;">int</span>(<span style="color: #006699;">random</span>(2)) == 0; &nbsp;&nbsp;<span style="color: #666666;">// For stars, you need the proportion of short to long radius</span> &nbsp;&nbsp;<span style="color: #E2661A;">float</span> proportion; &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(255); <span style="color: #666666;">// erase any previous drawing in this area</span> &nbsp;&nbsp;<span style="color: #006699;">fill</span>(255); &nbsp;&nbsp;<span style="color: #006699;">rect</span>(cx, cy, 50, 50); &nbsp;&nbsp;<span style="color: #006699;">stroke</span>(r, g, b); &nbsp;&nbsp;<span style="color: #006699;">fill</span>(r, g, b, opacity); &nbsp;&nbsp;<span style="color: #669900;">if</span> (isPolygon) { &nbsp;&nbsp;&nbsp;&nbsp;polygon(nSides,&nbsp;cx,&nbsp;cy,&nbsp;24); &nbsp;&nbsp;}&nbsp;<span style="color: #669900;">else</span> { &nbsp;&nbsp;&nbsp;&nbsp;proportion&nbsp;=&nbsp;<span style="color: #006699;">random</span>(0.2, 0.8) * <span style="color: #006699;">cos</span>(<span style="color: #718A62;">PI</span> / nSides); &nbsp;&nbsp;&nbsp;&nbsp;star(nSides,&nbsp;cx,&nbsp;cy,&nbsp;24,&nbsp;proportion); &nbsp;&nbsp;} } <span style="color: #33997E;">void</span> polygon(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> r) { &nbsp;&nbsp;<span style="color: #E2661A;">float</span> angle = 360.0 / n; &nbsp;&nbsp;<span style="color: #006699;">beginShape</span>(); &nbsp;&nbsp;<span style="color: #669900;">for</span> (<span style="color: #E2661A;">int</span> i = 0; i &lt; n; i++) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">vertex</span>(cx + r * <span style="color: #006699;">cos</span>(<span style="color: #006699;">radians</span>(angle * i)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cy&nbsp;+&nbsp;r&nbsp;*&nbsp;<span style="color: #006699;">sin</span>(<span style="color: #006699;">radians</span>(angle * i))); &nbsp;&nbsp;} &nbsp;&nbsp;<span style="color: #006699;">endShape</span>(<span style="color: #718A62;">CLOSE</span>); } <span style="color: #33997E;">void</span> star(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> r, <span style="color: #E2661A;">float</span> proportion) { &nbsp;&nbsp;star(n,&nbsp;cx,&nbsp;cy,&nbsp;2.0&nbsp;*&nbsp;r,&nbsp;2.0&nbsp;*&nbsp;r,&nbsp;0.0,&nbsp;proportion); } <span style="color: #33997E;">void</span> star(<span style="color: #E2661A;">int</span> n, <span style="color: #E2661A;">float</span> cx, <span style="color: #E2661A;">float</span> cy, <span style="color: #E2661A;">float</span> w, <span style="color: #E2661A;">float</span> h, &nbsp;&nbsp;<span style="color: #E2661A;">float</span> startAngle, <span style="color: #E2661A;">float</span> proportion) { &nbsp;&nbsp;<span style="color: #669900;">if</span> (n &gt; 2) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> angle = <span style="color: #718A62;">TWO_PI</span>/ (2 *n); <span style="color: #666666;">// twice as many sides</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> dw; <span style="color: #666666;">// draw width</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #E2661A;">float</span> dh; <span style="color: #666666;">// draw height</span> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;w&nbsp;=&nbsp;w&nbsp;/&nbsp;2.0; &nbsp;&nbsp;&nbsp;&nbsp;h&nbsp;=&nbsp;h&nbsp;/&nbsp;2.0; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">beginShape</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #669900;">for</span> (<span style="color: #E2661A;">int</span> i = 0; i &lt; 2 * n; i++) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dw&nbsp;=&nbsp;w; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dh&nbsp;=&nbsp;h; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #669900;">if</span> (i % 2 == 1) <span style="color: #666666;">// for odd vertices, use short radius</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dw&nbsp;=&nbsp;w&nbsp;*&nbsp;proportion; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dh&nbsp;=&nbsp;h&nbsp;*&nbsp;proportion; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">vertex</span>(cx + dw * <span style="color: #006699;">cos</span>(startAngle + angle * i), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cy&nbsp;+&nbsp;dh&nbsp;*&nbsp;<span style="color: #006699;">sin</span>(startAngle + angle * i)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #006699;">endShape</span>(<span style="color: #718A62;">CLOSE</span>); &nbsp;&nbsp;} } </pre> <h3>Polygons and Stars as Objects</h3> <p class="txt"> Now that I have working functions for polygons and stars, it might be useful to make a <code>Polygon</code> and <code>Star</code> class so that I can treat them as objects. The method I would use is much the same; I would start with simple test cases, build up the classes step by step, and finally use them in a full-blown program. <a href="http://processing.org/learning/objects">Here is a tutorial about objects in Processing.</a> </p> <h3>Summing Up</h3> <p class="txt"> This tutorial has shown you the things you never see in books. In a book, all the diagrams are picture perfect. You see a sample program, and it just works, and it produces gorgeous results. To be fair, the authors <em>can&rsquo;t</em> show you their thought process; otherwise, their books would be ten times as large. In fact, I did not include all the versions where a misplaced parenthesis or a forgotten call to <code>radians()</code> made my sketch explode into a mass of incomprehensible lines. But all of us, the big name authors, the people who write these tutorials, and the beginning programmers, go through this same tawdry process of design, trial and error, and development. I wanted you to see that process at least once, because we are all in this together. </p> <p class="txt"> You can <a href="code/polystar.zip">download the files from this tutorial</a>. </p> </td> </tr> </table>
import { renderHook } from '@testing-library/react-hooks'; import { useAuthenticationApi } from '../AuthApi'; import MockAdapter from 'axios-mock-adapter'; import axios from 'axios'; describe('useAuthenticationApi', () => { it('is able to authenticate user', async () => { const baseUrl = `${process.env.REACT_APP_API_URL}`; const getRequestData: AuthenticationRequest = { user: { email: 'testEmail@email.com', password: 'TestPassword' }, }; const url = `${baseUrl}/login`; const successfulUseAuthResponse = { verified: true }; const mock = new MockAdapter(axios); mock.onAny(url, getRequestData).reply(200, successfulUseAuthResponse); const { result, waitForNextUpdate } = renderHook(() => useAuthenticationApi( getRequestData.user.email, getRequestData.user.password ) ); await waitForNextUpdate(); expect(result.current.response).toStrictEqual(successfulUseAuthResponse); expect(result.current.isLoading).toEqual(false); expect(result.current.isSuccessful).toEqual(true); }); it('is able to return an unsuccessful authentication', async () => { const baseUrl = `${process.env.REACT_APP_API_URL}`; const getRequestData: AuthenticationRequest = { user: { email: 'testEmail@email.com', password: 'TestPassword' }, }; const url = `${baseUrl}/login`; const failedUseAuthResponse = { verified: false }; const mock = new MockAdapter(axios); mock.onAny(url, getRequestData).reply(400, failedUseAuthResponse); const { result, waitForNextUpdate } = renderHook(() => useAuthenticationApi( getRequestData.user.email, getRequestData.user.password ) ); await waitForNextUpdate(); expect(result.current.response).toStrictEqual(failedUseAuthResponse); expect(result.current.isLoading).toEqual(false); expect(result.current.isSuccessful).toEqual(false); }); it('is able to indicate it is loading while waiting for a response', async () => { const baseUrl = `${process.env.REACT_APP_API_URL}`; const getRequestData: AuthenticationRequest = { user: { email: 'testEmail@email.com', password: 'TestPassword' }, }; const url = `${baseUrl}/login`; const successfulUseAuthResponse = { verified: true }; const mock = new MockAdapter(axios); mock.onAny(url, getRequestData).reply(200, successfulUseAuthResponse); const { result, waitForNextUpdate } = renderHook(() => useAuthenticationApi( getRequestData.user.email, getRequestData.user.password ) ); expect(result.current.isLoading).toEqual(true); expect(result.current.isSuccessful).toEqual(false); await waitForNextUpdate(); // Wait for axios to recieve a reply. }); });
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package servidor; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import modelo.Administrador; import modelo.Empleado; import modelo.Televisor; import modelo.Totem; import patronStateServidor.IState; import patronStateServidor.PrimarioState; import patronStateServidor.SecundarioState; /** * * @author ignacio */ public class Servidor extends Thread implements Serializable{ private static final long serialVersionUID = 4209360273818925922L; private ColasManager manager; private PrintWriter out; private ServerSocket serverSocket; private int puerto; private IState estado = new SecundarioState(this); public Servidor() throws IOException{ this.manager = ColasManager.getInstancia(); try { this.setPuerto(5555); this.serverSocket = new ServerSocket(this.puerto); this.estado = new PrimarioState(this); System.out.println("Servidor TCP iniciado. Esperando conexiones…"); } catch (IOException e) { this.setPuerto(7777); this.serverSocket = new ServerSocket(this.puerto); this.estado = new SecundarioState(this); System.out.println("Servidor TCP secundario iniciado. Esperando conexiones…"); } } public Servidor(ColasManager manager) throws IOException{ this.manager = manager; try { this.setPuerto(5555); this.serverSocket = new ServerSocket(this.puerto); this.estado = new PrimarioState(this); System.out.println("Servidor TCP iniciado. Esperando conexiones…"); } catch (IOException e) { this.setPuerto(7777); this.serverSocket = new ServerSocket(this.puerto); this.estado = new SecundarioState(this); System.out.println("Servidor TCP secundario iniciado. Esperando conexiones…"); } } /*public Servidor(String ip, int puerto) throws IOException { this.manager = ColasManager.getInstancia(); this.serverSocket = new ServerSocket(puerto); switch (puerto) { case 5555: System.out.println("Servidor TCP iniciado. Esperando conexiones…"); break; case 7777: System.out.println("Servidor TCP secundario iniciado. Esperando conexiones…"); break; default: System.out.println("Puerto incorrecto."); break; } }*/ //para test /*public Servidor(String mensaje) { try { this.serverSocket = new ServerSocket(5555); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Servidor ALTER TCP iniciado. Esperando conexiones..."); }*/ public void startServer() { System.out.println("Puerto: " + this.getServerSocket().getLocalPort() + "\nServidor: " + this.getEstado()); try { while(true) { Socket clientSocket = this.serverSocket.accept(); Thread thread = new Thread(new ClientHandler(clientSocket,manager, "localhost", this.getServerSocket().getLocalPort())); System.out.println(thread); thread.start(); /*try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static class ClientHandler implements Runnable { private Socket clientSocket; private ColasManager manager; private String ip; private int puerto; public ClientHandler(Socket clientSocket,ColasManager manager, String ip, int puerto) { this.clientSocket = clientSocket; this.manager = manager; this.ip = ip; this.puerto = puerto; } @Override public void run() { try { DatosConexion datos = new DatosConexion(this.clientSocket); //ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); Object obj = datos.ois.readObject(); if(obj instanceof Totem){ System.out.println("entra totem"); Totem totem=(Totem)obj; System.out.println("dni que entra: " + totem.getDni()); manager.newCliente(totem.getDni()); System.out.println("documentos: " + manager.getDnis().toString()); mandar_int("agregar index dnis",manager.obtener_index_dnis(), ip, puerto); //manager.obtener_index_dnis() //mandar_objeto("agregar dnis",manager.obtener_dnis().getLast()); }else if(obj instanceof Televisor){ System.out.println("entra televisor"); System.out.println("datos: " + datos); manager.creaTele(datos); //zona de pruebas mandar_objeto("televisor",manager.obtener_teles(), ip, puerto); //mandar_objeto("televisor",manager.obtener_teles().getLast()); }else if(obj instanceof Empleado){ System.out.println("entra empleado"); Empleado empleado = (Empleado) obj; String msg=datos.in.readLine(); if(msg.equalsIgnoreCase("nuevo")) { manager.newBox(datos); //boxes.add(indexBox,String.valueOf(indexBox)); //indexBox++; mandar_int("agregar index box",manager.obtener_index_box(), ip, puerto); mandar_objeto("nuevo boxes",manager.obtener_boxes(), ip, puerto); }else { manager.llamaCliente(String.valueOf(empleado.getPuesto())); //atendidos.add(dnis.get(0)); //dnis.remove(0); mandar_objeto("agregar dnis",manager.obtener_dnis(), ip, puerto); mandar_objeto("agregar atendidos",manager.obtener_atendidos(), ip, puerto); } }else if(obj instanceof Administrador){ System.out.println("entra administrador"); this.manager.nuevoAdministrador(datos); } else if (obj==null){ System.out.println("entra ping al servidor"); MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); MemoryUsage cantMemoriaUsada = mbean.getHeapMemoryUsage(); datos.out.flush(); datos.out.println(cantMemoriaUsada.toString()); datos.out.flush(); } } catch (IOException e) { System.err.println("Error al manejar la conexión con el cliente: " + e.getMessage()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void mandar_int(String mensaje,int numero_enviar, String ip, int puerto) { try { Socket socket = new Socket(ip, puerto); //inicializo BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); PrintWriter out = new PrintWriter(socket.getOutputStream(),true); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.flush(); dos.writeUTF(mensaje); dos.flush(); System.out.println("se mando el mensaje"); dos.flush(); dos.writeInt(numero_enviar); dos.flush(); System.out.println("se mando el integer"); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void mandar_objeto(String mensaje,Object objeto, String ip, int puerto) { try { Socket socket = new Socket(ip, puerto); //inicializo ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); PrintWriter out = new PrintWriter(socket.getOutputStream(),true); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); dos.flush(); dos.writeUTF(mensaje); dos.flush(); System.out.println("se mando el mensaje"); oos.flush(); System.out.println(objeto); oos.writeObject(objeto); oos.flush(); System.out.println("se mando el objeto"); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void cerrarsocket(){ } public static long getSerialversionuid() { return serialVersionUID; } public IState getEstado() { return estado; } public void setEstado(IState estado) { this.estado = estado; } public ServerSocket getServerSocket() { return serverSocket; } public void setServerSocket(ServerSocket serverSocket) { this.serverSocket = serverSocket; } public int getPuerto() { return puerto; } public void setPuerto(int puerto) { this.puerto = puerto; } }
import { useContext } from 'react'; import { Link } from 'react-router-dom'; import { UserContext } from '../../Context'; import { NavItemLogin } from './components'; export default function Menu() { const { logged, resetUser } = useContext(UserContext); const logout = () => { if (resetUser) resetUser(); }; return ( <nav className='navbar navbar-expand-lg navbar-dark bg-dark'> <div className='container-fluid'> <Link className='navbar-brand' to='/'> <img src='images/icon.png' alt='X' width='30' height='30' style={{ borderRadius: '5px' }} /> </Link> <Link className='navbar-brand' to='/' title='To Home' > To do List </Link> <button className='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#navbarSupportedContent' aria-controls='navbarSupportedContent' aria-expanded='false' aria-label='Toggle navigation' > <span className='navbar-toggler-icon'></span> </button> <div className='collapse navbar-collapse' id='navbarSupportedContent'> <ul className='navbar-nav me-auto mb-2 mb-lg-0'> { logged && ( <li className='nav-item'> <Link className='nav-link active' aria-current='page' to='/dashboard' title='To Dashboard' > Dashboard </Link> </li> ) } </ul> <ul className='navbar-nav mb-2 mb-lg-0' style={{ cursor: 'pointer' }}> { logged ? <NavItemLogin text='Sair' clickFunction={() => logout()} /> : <NavItemLogin text='Login' /> } </ul> </div> </div> </nav> ); }
package realpage.catalogbackend.serviceimpl; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import realpage.catalogbackend.dto.AuthenticationDto; import realpage.catalogbackend.dto.AuthenticationResponseDto; import realpage.catalogbackend.dto.UserDto; import realpage.catalogbackend.entity.User; import realpage.catalogbackend.mapper.UserMapper; import realpage.catalogbackend.repository.IUserRepository; import realpage.catalogbackend.service.IAuthenticationService; import realpage.catalogbackend.util.EObjectResponseCode; import realpage.catalogbackend.util.ObjectResponse; import realpage.catalogbackend.util.FunctionUtils; import realpage.catalogbackend.util.TokenUtils; /** * Class used to manage the authentication feature. * @author Carlos Torres * */ @Service @Transactional(readOnly=true) public class AuthenticationServiceImpl implements IAuthenticationService { private static final Logger logger = LogManager.getLogger(AuthenticationServiceImpl.class); private final IUserRepository userRepository; private final TokenUtils tokenUtils; @Autowired public AuthenticationServiceImpl(IUserRepository userRepository,TokenUtils tokenUtils) { this.userRepository = userRepository; this.tokenUtils = tokenUtils; } @Override public ObjectResponse<AuthenticationResponseDto> validateAuthorization(AuthenticationDto auth) { try { User user = userRepository.findByUsername(auth.getUsername()); if(user==null) { return new ObjectResponse<>(EObjectResponseCode.WARNING,"The user does not exist", null); } final String password = FunctionUtils.generateHashWithApacheCommons().apply(auth.getPassword()); if(!user.getPassword().equals(password)) { return new ObjectResponse<>(EObjectResponseCode.WARNING,"Password incorrect", null); } AuthenticationResponseDto response = new AuthenticationResponseDto(user.getUsername(), tokenUtils.generateToken(user.getUsername()),user.getRole().getId()); return new ObjectResponse<>(EObjectResponseCode.CORRECT, "status ok",response); } catch (Exception e) { String message =AuthenticationServiceImpl.class.getName()+"-validateAuthorization "; logger.error(message, e); return new ObjectResponse<>(EObjectResponseCode.ERROR,message+e.getMessage(), null); } } }
package com.darxign.codeware.display.text.raster { import flash.display.BitmapData; import flash.geom.Point; import flash.geom.Rectangle; /** * Raster font. * @author darxign */ public class RasterFont { static public const SMALL_LETTERS_SET:String = "abcdefghijklmnopqrstuvwxyz"; static public const BIG_LETTERS_SET:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; protected var interval:int; protected var chars:Array; protected var charHeight:int; protected var _rect:Rectangle = new Rectangle(); protected var _point:Point = new Point(); /* * fontImage - image with symbols * symbolSet - array of correspondance between fontImage and real symbols * interval - pixel count between two symbols when typing. WARNING: in the font file must always be 1 pixel between 2 symbols. * charHeight - default height of every char * ...rest - set of [s, x] arrays where s:String - a symbol string from symbolSet, x:int - their custom width */ public function RasterFont(fontData:BitmapData, symbolSet:String, interval:int, ...charWidths) { // validation... if (fontData == null) throw new Error("fontData mustn't be null"); if (symbolSet == null) throw new Error("symbolSet mustn't be null"); if (interval < 0) throw new Error("interval must be 0 or more"); this.charHeight = fontData.height var checkSymbols:String = ""; for (var i:int = 0; i < charWidths.length; i++) { if (charWidths[i] is Array) { var cw:Array = charWidths[i]; // cw - chars and width, for example: ['abc',13] var seq:String = cw[0] as String; if (seq) { if (seq.length != 0) { for (var n:int = 0; n < seq.length; n++) { if (symbolSet.indexOf(seq.charAt(n)) == -1) { throw new Error("charWidths[" + i + "][0]: no such symbol in symbolSet: " + seq.charAt(n)); } if (checkSymbols.indexOf(seq.charAt(n)) != -1) { throw new Error("charWidths[" + i + "][0]: symbol already exists in charWidths: " + seq.charAt(n)); } checkSymbols = checkSymbols.concat(seq.charAt(n)); } } else { throw new Error("charWidths[" + i + "][0]: must be at least 1 symbol"); } } else { throw new Error("charWidths[" + i + "][0]: must be a String"); } if (cw[1] is int) { if (cw[1] < 1) { throw new Error("charWidths[" + i + "][1]: must be more than 0"); } } else { throw new Error("charWidths[" + i + "][1]: must be an int"); } } else { throw new Error("charWidths[" + i + "]: must be an array"); } } var checkSymbolSet:String = ""; for (i = 0; i < symbolSet.length; i++) { if (checkSymbolSet.indexOf(symbolSet.charAt(i)) != -1) { throw new Error("symbolSet[" + i + "]: symbol '" + symbolSet.charAt(i) + "' already exists in symbolSet"); } if (checkSymbols.indexOf(symbolSet.charAt(i)) == -1) { throw new Error("symbolSet[" + i + "]: symbol '" + symbolSet.charAt(i) + "' has no width"); } checkSymbolSet = checkSymbolSet.concat(symbolSet.charAt(i)); } // prepare widths... this.chars = new Array(); for (i = 0; i < symbolSet.length; i++) { this.chars[symbolSet.charCodeAt(i)] = null; } for (i = 0; i < charWidths.length; i++) { cw = charWidths[i]; seq = cw[0]; for (var j:int = 0; j < seq.length; j++) { this.chars[seq.charCodeAt(j)] = cw[1]; } } // ...done var summaryWidth:int = -1; for (i = 0; i < symbolSet.length; i++) { summaryWidth += this.chars[symbolSet.charCodeAt(i)] + 1; } if (fontData.width < summaryWidth) { throw new Error("fontImage hasn't necessary width"); } // ...done // create bitmap datas... //var fontData:BitmapData = new BitmapData(fontImage.width, fontImage.height, true, 0); //fontData.draw(fontImage); _rect.x = -1; _rect.y = 0; _rect.height = charHeight; _rect.width = 0; _point.x = 0; _point.y = 0; for (i = 0; i < symbolSet.length; i++) { _rect.x = _rect.x + _rect.width + 1; _rect.width = int(this.chars[symbolSet.charCodeAt(i)]); var char:BitmapData = new BitmapData(_rect.width, _rect.height, true, 0); char.copyPixels(fontData, _rect, _point); this.chars[symbolSet.charCodeAt(i)] = char; } // ...done this.interval = interval; this.charHeight = charHeight; } /* * Draws the string of the text object as a set of images */ public final function draw(text:RasterText):void { var txtString:String = text.getString(); var txtLength:int if (txtString == null || (txtLength = txtString.length) == 0) { text.getContent().bitmapData = null return }; var w:int = (txtString.length - 1) * this.interval; var h:int = this.charHeight; for (var i:int = 0; i < txtLength; i++) { if (this.chars[txtString.charCodeAt(i)] == null) { this.chars[txtString.charCodeAt(i)] = new BitmapData(this.charHeight, this.charHeight) } w += (this.chars[txtString.charCodeAt(i)] as BitmapData).width; } _rect.x = 0; _rect.y = 0; _rect.width = w; _rect.height = h; var txtData:BitmapData = text.getContent().bitmapData; if (txtData && txtData.width == w && txtData.height == h) { txtData.fillRect(_rect, 0); } else { if (txtData) { txtData.dispose() } txtData = new BitmapData(w, h, true, 0); } _point.x = 0; _point.y = 0; for (i = 0; i < txtLength; i++) { var data:BitmapData = this.chars[txtString.charCodeAt(i)]; _rect.width = data.width; _rect.height = data.height; txtData.copyPixels(data, _rect, _point); _point.x += _rect.width + this.interval; } text.getContent().bitmapData = txtData; } public final function getCharHeight():int { return this.charHeight; } public final function getCharWidth(charCode:Number):int { return this.getChar(charCode).width; } public final function getTextWidth(txtString:String):int { var txtLength:int = txtString.length; var w:int = (txtLength - 1) * this.interval; for (var i:int = 0; i < txtLength; i++) { w += this.getChar(txtString.charCodeAt(i)).width; } return w; } private final function getChar(charCode:Number):BitmapData { var char:BitmapData = this.chars[charCode]; if (!char) { // chars that don't exist must all be just a square char = new BitmapData(this.charHeight, this.charHeight); this.chars[charCode] = char; } return char; } public final function getInterval():int { return this.interval; } } }
package com.nw.dressmart.service; import com.nw.dressmart.dto.LoginRequestDto; import com.nw.dressmart.dto.LoginResponseDto; import com.nw.dressmart.dto.RegisterRequestDto; import com.nw.dressmart.dto.UserDto; import com.nw.dressmart.entity.Role; import com.nw.dressmart.entity.User; import com.nw.dressmart.mappers.UserMapper; import com.nw.dressmart.repository.UserRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.Optional; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; class AuthenticationServiceImplTest { @Mock private UserRepository userRepository; @Mock private UserMapper userMapper; @Mock private PasswordEncoder passwordEncoder; @Mock AuthenticationManager authenticationManager; @Mock JwtService jwtService; @Mock VerificationService verificationService; @InjectMocks private AuthenticationServiceImpl authenticationService; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } @Test void saveUser_ShouldSaveUser() { //given RegisterRequestDto dto=new RegisterRequestDto("john","doe","mkmk@example.com","password"); User user=new User(); user.setFirstName(dto.getFirstName()); user.setLastName(dto.getLastName()); user.setEmail(dto.getEmail()); user.setPassword("encodedPw"); user.setRole(Role.CUSTOMER); User savedUser=new User(); savedUser.setFirstName(user.getFirstName()); savedUser.setLastName(user.getLastName()); savedUser.setEmail(user.getEmail()); savedUser.setPassword("encodedPw"); savedUser.setRole(user.getRole()); savedUser.setId(1L); when(userRepository.findByEmail(dto.getEmail())).thenReturn(Optional.empty()); when(userMapper.registerRequestDtoToUser(dto)).thenReturn(user); when(passwordEncoder.encode(dto.getPassword())).thenReturn("encodedPw"); when(userRepository.save(user)).thenReturn(savedUser); UserDto userDto = new UserDto(1L, "test", "sata", "asda"); when(userMapper.UserToUserDto(savedUser)).thenReturn(userDto); //when UserDto result=authenticationService.saveUser(dto); //then assertThat(userDto.getEmail()).isEqualTo(result.getEmail()); assertThat(userDto.getFirstName()).isEqualTo(result.getFirstName()); assertThat(userDto.getLastName()).isEqualTo(result.getLastName()); verify(userRepository,times(1)).save(any(User.class)); } @Test void saveUser_ShouldFailWhenEmailAlreadyExists(){ RegisterRequestDto dto=new RegisterRequestDto("john","doe","mkmk@example.com","password"); User user=new User(); user.setFirstName(dto.getFirstName()); user.setLastName(dto.getLastName()); user.setEmail(dto.getEmail()); user.setPassword("encodedPw"); user.setRole(Role.CUSTOMER); when(userRepository.findByEmail(dto.getEmail())).thenReturn(Optional.of(user)); assertThrows(IllegalStateException.class,()-> authenticationService.saveUser(dto), "user with email " + dto.getEmail() +" already exists"); } @Test void authenticate_ShouldAuthenticateUser() { //given LoginRequestDto request=new LoginRequestDto("nilu@gmail.com","password"); User user=new User(); user.setFirstName("nilupulee"); user.setLastName("wathsala"); user.setEmail("nilu@gmail.com"); user.setPassword("encodedPw"); user.setRole(Role.CUSTOMER); String token="token"; LoginResponseDto response=new LoginResponseDto(token); when(authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(request.getEmail(),request.getPassword()))).thenReturn(null); when(userRepository.findByEmail(request.getEmail())).thenReturn(Optional.of(user)); when(jwtService.generateToken(user)).thenReturn(token); //when LoginResponseDto result=authenticationService.authenticate(request); //then assertThat(response.getToken()).isEqualTo(result.getToken()); } @Test void authenticate_ShouldFailWhenEmailNotFound(){ LoginRequestDto request=new LoginRequestDto("nilu@gmail.com","password"); when(userRepository.findByEmail(request.getEmail())).thenReturn(Optional.empty()); assertThrows(IllegalStateException.class,()-> authenticationService.authenticate(request), "user with email " + request.getEmail() +" not found"); } }
/* * @lc app=leetcode.cn id=23 lang=typescript * * [23] 合并K个升序链表 */ // @lc code=start /** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function mergeKLists(lists: Array<ListNode | null>): ListNode | null { if (!lists.length) return null; const n = lists.length; if (n === 1) return lists[0]; const pre = lists.splice(0, Math.floor(n / 2)); let first = mergeKLists(pre); let second = mergeKLists(lists); let protect = new ListNode(0); let head = protect; while (first && second) { if (first.val <= second.val) { head.next = first; first = first.next; } else { head.next = second; second = second.next; } head = head.next; } head.next = first || second; return protect.next; }; // @lc code=end
<template> <div> <el-row class="main-top"> <el-form :inline="true" class="btn-main"> <el-form-item label=""> <el-button type="primary" icon="plus" @click="created_course" v-if="prm.isCreate">创建课程</el-button> </el-form-item> </el-form> <el-form :inline="true"> <el-form-item label=""> <el-input style="display:none"></el-input> <el-input placeholder="课程标题" v-model="params.query" class='w230' @keyup.13.native="searchKey" clearable> <el-button @click="searchKey" slot="append" icon="el-icon-search"></el-button> </el-input> </el-form-item> <el-form-item> <el-cascader filterable :options="courseClassify" :props="keyName" v-model="categoryId" @change="ClassifyId" change-on-select clearable placeholder="课程分类"></el-cascader> </el-form-item> <el-form-item> <el-select placeholder="课程状态" class='w150' v-model="params.state" @change="getList" clearable @clear="params.state = ''"> <el-option v-for="(i) in stateArr" :key="i.text" :label="i.text" :value="i.id"></el-option> </el-select> </el-form-item> <el-form-item> <el-date-picker v-model="time" start-placeholder="开始日期" end-placeholder="结束日期" type="daterange" placeholder="选择时间" @change='handleChangeTime' value-format='yyyy-MM-dd' > </el-date-picker> </el-form-item> </el-form> </el-row> <el-row class="main-body"> <el-table ref="mainTable" @selection-change="handleSelectionChange" @sort-change='sortFunc' header-row-class-name="thead" :data="tableData" stripe v-loading="loading" element-loading-text="加载中..."> <el-table-column type="selection" align="center" min-width='55' v-if="prm.isDelete" :selectable='selectInit'></el-table-column> <el-table-column prop="courseImg" label="课程封面" width='100' align='center'> <template slot-scope="scope"> <img class='img-bor' :src="scope.row.courseImg ? ($store.state.configData.imgDomain + scope.row.courseImg+$imgSize['30x30']) : ($store.state.configData.imgDomain + '/default/cdwork/course.jpg' + $imgSize['30x30'])" /> </template> </el-table-column> <el-table-column prop="courseTitle" label="课程标题" min-width="140"></el-table-column> <el-table-column prop="categoryTitle" label="课程分类" min-width='100'></el-table-column> <el-table-column prop="stateStr" label="状态" min-width='80'> <template slot-scope="scope"> {{scope.row.stateStr}} <el-tooltip effect="dark" placement="top" v-show="scope.row.state == 2"> <div slot="content">{{scope.row.reason}}</div> <img :src="require('@/img/common/tips.png')" class="reason-tooltip"/> </el-tooltip> </template> </el-table-column> <el-table-column prop="createUserName" label="创建人" min-width='100'></el-table-column> <el-table-column prop="createTimeStr" label="创建时间" width='170'></el-table-column> <el-table-column prop="" label="操作" width="470"> <template slot-scope='scope'> <el-button v-if="prm.isUpdate" type="text" @click.native="edit(scope.row)">编辑</el-button> <el-button type="text" @click.native="addClass(scope.row)">章节</el-button> <el-button type="text" @click.native="choiceUser(scope.row)">报名</el-button> <el-button v-if="prm.isAudit && scope.row.state != 5" type="text" @click.native="audit(scope.row)">审核</el-button> <el-button v-if="prm.isRecommend && scope.row.state == 4" type="text" @click.native="recommend(scope.row)">{{scope.row.isRecommend ? "取消推荐" : "推荐"}}</el-button> <el-button v-if="prm.isOnline && scope.row.state != 3" type="text" @click.native="on_off(scope.row)">{{scope.row.state == 4 ? "关闭" : "发布" }}</el-button> <el-button v-if="prm.isStatistics" type="text" @click.native="statistics(scope.row)">统计</el-button> <el-button v-if="prm.isDelete && scope.row.state != 4" type="text" @click.native="showDelDialog(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <el-row v-if="prm.isDelete"> <span class="mag-top20"> <el-checkbox class="mag-left20" v-model="toggleCheckbox" :indeterminate="isIndeterminate" @change="handleCheckAllChange" :disabled="tableData.length === 0">{{!toggleCheckbox ? '全选' : '取消全选'}}</el-checkbox> <el-button class="mag-left20" @click="delCheck">删除</el-button> </span> </el-row> <div class="page-num"> <el-form :inline="true"> <el-form-item> 共有 <span class="fc303e">{{total}}</span>条数据,每页显示 <el-select placeholder="" v-model="params.pageSize" class='w65' @change='params.pageNum = 1;getList()'> <el-option label="10" value="10"></el-option> <el-option label="20" value="20"></el-option> <el-option label="50" value="50"></el-option> </el-select> 条 </el-form-item> </el-form> <el-pagination :current-page.sync="params.pageNum" background @current-change="getList('type')" :page-size="parseInt(params.pageSize)" layout="prev, pager, next, jumper" :total="total"> </el-pagination> </div> </el-row> <el-dialog :close-on-click-modal="false" width="30%" title="审核" :visible.sync="showAudit" :before-close="closeAudit"> <div> <el-radio v-model="state" :label="4">通过</el-radio> <el-radio v-model="state" :label="2">不通过</el-radio> <br /> <br /> <el-input v-show="state ==2" tyle="text" placeholder="请输入审核不通过的原因" v-model="reason"></el-input> <el-row style="margin-top:10px"> <el-button type="primary" class="fr" :loading="isPending" @click="saveBtn">确定</el-button> </el-row> </div> </el-dialog> <el-dialog width="70%" v-if="createEditOne" :title="title" :visible.sync="createEditOne" :close-on-click-modal="false" :before-close="closeOne"> <create-edit-one @createEditOneOver="createEditOneOver" :queryData="queryCourseData" :title="{'title':title}"></create-edit-one> </el-dialog> <el-dialog width="70%" v-if="createEditTwo" :title="title" :visible.sync="createEditTwo" :close-on-click-modal="false" :before-close="closeTwo"> <create-edit-two @createEditTwoOver='createEditTwoOver' @createEditTwoOverUp='createEditTwoOverUp' @createEditTwoOverDown='createEditTwoOverDown' :queryData="queryCourseData" :title="{'title':title}" :isShow='isShow'></create-edit-two> </el-dialog> <el-dialog width="70%" v-if="createEditThree" :title="title" :visible.sync="createEditThree" :close-on-click-modal="false" :before-close="closeThree"> <create-edit-three :options='courseData' @createEditThreeOverUp="createEditThreeOverUp" @createEditThreeOver="createEditThreeOver" :isShow='isShow'></create-edit-three> </el-dialog> <el-dialog width="70%" v-if="statisticsUser" title="课程用户报表" :visible.sync="statisticsUser" :close-on-click-modal="false" :before-close="closeUser"> <statistics-user @statisticsUserOver="statisticsUserOver" from="course"></statistics-user> </el-dialog> <el-dialog width="50%" v-if="statisticsState" title="统计" :visible.sync="statisticsState" :close-on-click-modal="false"> <el-table header-row-class-name="thead" :data="statisticsData" border v-loading="loading" header-align="center" element-loading-text="加载中..."> <el-table-column prop="chapterNumber" label="章节数" align="center" min-width="80"></el-table-column> <el-table-column prop="browseNumber" label="浏览量" align="center" min-width="80"></el-table-column> <el-table-column prop="complimentNumber" label="点赞数" align="center" min-width="80"></el-table-column> <el-table-column prop="commentNumber" label="评论数" align="center" min-width="80"></el-table-column> <el-table-column label="学习人数" align="center" min-width="80"> <template slot-scope='scope'> <a style="cursor: pointer" @click="studyNumberFun(scope.row)">{{scope.row.studyNumber}}</a> </template> </el-table-column> <el-table-column label="平均进度" align="center" min-width="80"> <template slot-scope="scope"> {{scope.row.progress ? Math.round(scope.row.progress * 100) + "%" : "-"}} </template> </el-table-column> <el-table-column prop="length" label="学习总时长" align="center" min-width="80"> <template slot-scope="scope"> {{scope.row.length ? $formatSeconds(scope.row.length) : "-"}} </template> </el-table-column> <el-table-column prop="score" label="平均成绩" align="center" min-width="80"> <template slot-scope="scope"> {{scope.row.score ? scope.row.score : "-"}} </template> </el-table-column> </el-table> </el-dialog> <el-dialog width="30%" v-if="isDelShow" title="删除" :visible.sync="isDelShow" :close-on-click-modal="false"> <el-form> <el-form-item label="请填写删除原因:"> <el-input rows="3" type="textarea" placeholder="原因不能为空" v-model="delCause"></el-input> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="isDelShow = false">取 消</el-button> <el-button type="primary" @click="del">确 定</el-button> </span> </el-dialog> </div> </template> <script lang="ts"> import { Component, Vue, Watch } from "vue-property-decorator"; import { debounce } from "typescript-debounce-decorator"; import Course from "@api/train"; import Category from "@api/category"; import Org from "@api/org"; import { emptyLast } from "@utils/index"; //https://github.com/ktsn/vuex-class @Component({ components: { "create-edit-one": () => import("./createAndEdit_one.vue"), "create-edit-two": () => import("./createAndEdit_two.vue"), "create-edit-three": () => import("@c/ChoiceUser.vue"), "statistics-user": () => import("@c/StatisticsUser.vue") } }) export default class Companyreg extends Vue { isDelShow: boolean = false; createEditOne: boolean = false; createEditTwo: boolean = false; createEditThree: boolean = false; statisticsState: boolean = false; statisticsUser: boolean = false; statisticsData: any = []; forms: any = null; title: any = "创建课程"; keyName: object = { label: "categoryTitle", value: "categoryId" }; params: any = { pageSize: 10, pageNum: 1, venueId: "", sortBy: false, sortField: "createTime", query: "", startTime: "", endTime: "" }; prm = { isDelete: false, isCreate: false, isAudit: false, isUpdate: false, isOnline: false, isRecommend: false, isStatistics: false }; state: number = 4; reason: string = ""; courseId: string | number = ""; courseClassify: any[] = []; ArticSrc: string = ""; isShowArtic: boolean = false; isShow: object = { user: false, class: false } stateArr: object[] = [ { id: 1, text: "草稿" }, { id: 2, text: "未通过" }, { id: 3, text: "审核中" }, { id: 4, text: "发布中" }, { id: 5, text: "已关闭" } ]; tableData: any[] = []; loading: boolean = false; showAudit: boolean = false; isPending: boolean = false; time: string[] = []; total: number = 0; categoryId: any = []; queryCourseData: any = {}; delCourseId: string = ""; delCause: string = ""; isIndeterminate: boolean = false; toggleCheckbox: boolean = false; selectData: any[] = []; courseData: any = { params: { courseId: '', sortBy: false, sortField: "userId", pageSize: 10, pageNum: 1 }, arrs: 'userIds', arr: 'userId' } created() { this.getCategory(); this.getList(); Object.keys(this.prm).forEach((i, index) => { //@ts-ignore this.prm[i] = this.$store.state.activeMenu[this.$route.path][i]; }); } handleCheckAllChange() { if (this.toggleCheckbox) { this.$refs.mainTable.toggleAllSelection(); } else { this.$refs.mainTable.clearSelection(); } this.handleSelectionChange; } handleSelectionChange(e: any) { this.selectData = e; let checkedCount = e.length; this.toggleCheckbox = checkedCount === this.tableData.length && this.tableData.length != 0; this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableData.length; } selectInit(row: any, index: any) { if(row.state != 4){ return true } else{       return false   }   } courseOnlineOffline() { let data = { state: 4, courseId: this.$store.state.courseData.id } Course.online_offline_course({ data }) .then(res => { if (res.code === 0) { this.createEditThree = this.createEditTwo = this.createEditOne = false } }) } delCheck(e: any){ if (this.selectData.length === 0 && !e) { this.$notify({ title: "错误", message: `请至少选择一个课程!`, type: "error" }); return; } let id = e && e.courseId ? JSON.stringify(e.courseId) : JSON.stringify(this.selectData.map(i => i.courseId)); this.delCourseId = id.replace(/"|\[|\]/g,''); this.isDelShow = true; } ClassifyId(e: any) { if (e.length) { this.params.categoryIds = "" + e; } else { delete this.params.categoryIds; } this.getList(); } // 推荐 recommend(e: any): void { let data = { courseId: e.courseId, isRecommend: !e.isRecommend ? 1 : 0 }; Course.is_recommend_course({ data }).then(res => { if (res.code === 0) { this.getList(); } }); } // 上下线 on_off(e: any): void { if(e.state == 2){ this.$notify({ title: "警告", message: `未通过审核不能发布`, type: "warning" }); return; } if(e.state == 3){ this.$notify({ title: "警告", message: `审核中不能发布`, type: "warning" }); return; } let data = { courseId: e.courseId, state: e.state == 4 ? 5 : 4 }; Course.online_offline_course({ data }).then(res => { if (res.code === 0) { this.$notify({ title: "提示", message: `${e.state == 4 ? "关闭" : "发布"}成功!`, type: "success" }); this.getList(); } }); } // 审核_弹框 audit(e: any) { this.showAudit = true; this.courseId = e.courseId; } // 审核 saveBtn() { if (this.state === 2 && !this.reason || this.reason.includes(" ")){ this.$notify.error({ title: "错误", message: "原因填写不合法!" }); return; } let data = { courseId: this.courseId, state: this.state, reason: this.reason }; this.isPending = true; Course.audit_course_admin({ data }) .then(res => { if (res.code === 0) { this.$notify({ title: "提示", message: "审核成功!", type: "success" }); this.closeAudit(); this.getList(); } }) .finally(() => { this.isPending = false; }); } // 展示删除细节 showDelDialog(e: any): void { this.isDelShow = true; this.delCourseId = e.courseId; } // 执行逻辑删除 del(): void { if (!this.delCause || this.delCause.includes(" ")) { this.$notify.error({ title: "错误", message: "删除原因必填,并且不能含有空格!" }); return; } let data = { courseIds: this.delCourseId, reason: this.delCause }; Course.del_course_admin({ data }).then(res => { if (res.code === 0) { this.$notify({ title: "提示", message: "删除成功!", type: "success" }); this.isDelShow = false; this.delCause = ""; if ((this.selectData.length === this.tableData.length || this.tableData.length === 1 ) && this.params.pageNum > 1) { this.params.pageNum --; } this.getList(); } }); } // 报名用户 apply(e: any) { this.$router.push({ path: "/course/reglist", query: { courseId: e.courseId } }); } // 统计 statistics(e: any) { if(e){ let arr = this.$store.state.courseData; arr.id = e.courseId; arr.title = e.courseTitle; this.$store.commit('setCourseData', arr) } let data = { courseId: this.$store.state.courseData.id }; Course.query_course_statistics_admin({ data }).then(res => { if (res.code === 0) { let arr = []; arr.push(res.data); this.statisticsData = arr; this.statisticsState = true; } }); } // 关闭第一步回调 closeOne() { this.createEditOne = false; this.getList(); } closeTwo() { this.createEditTwo = false; this.getList(); } closeThree() { this.createEditThree = false; this.getList(); } // 编辑 edit(e: any): void { this.loading = true; let arr = this.$store.state.courseData; arr.id = e.courseId; this.$store.commit('setCourseData', arr) let data = { courseId: e.courseId }; Course.query_course_admin({ data }) .then(res => { if (res.code === 0) { this.queryCourseData = res.data; this.createEditOne = true; this.title = "编辑课程"; } }) .finally(() => { this.loading = false; }); } // 创建课程 created_course(): void { this.$store.state.courseData.id = ''; this.createEditOne = true; this.title = "创建课程"; } createEditOneOver() { this.isShow.class = false; this.createEditOne = false; this.createEditTwo = true; } createEditTwoOver() { this.createEditTwo = false; } createEditTwoOverUp() { this.createEditOne = true; this.createEditTwo = false; } createEditTwoOverDown() { this.isShow.user = false; this.createEditTwo = false; this.createEditThree = true; } createEditThreeOverUp() { this.isShow.class = false; this.createEditTwo = true; this.createEditThree = false; } createEditThreeOver() { this.createEditThree = false; this.getList(); } closeAudit() { this.showAudit = false; this.state = 4; this.reason = ""; } getCategory() { let data = {}; Category.category_list_course({ data }).then(res => { if (res.code === 0) { emptyLast(res.data); let arr = this.$store.state.courseData; arr.classify = res.data; this.$store.commit('setCourseData', arr) this.courseClassify = res.data; } }); } getList(type: any) { if (type !== 'type') { if ( this.params.query || this.params.categoryIds || this.params.state || this.params.startTime || this.params.endTime ) { this.params.pageNum = 1; } } let data = { ...this.params }; this.loading = true; Course.course_list_admin({ data }) .then(res => { if (res.code === 0) { this.total = res.data.total; res.data.result.forEach((i: any) => { i.createTimeStr = this.$formatDate(i.createTime); i.stateStr = this.$mapTypeStr(i.state, this.stateArr); }); this.tableData = res.data.result; } }) .finally(() => { this.loading = false; }); } handleChangeTime() { if (this.time) { let time = this.$getApiTime(this.time); this.params.startTime = time[0]; this.params.endTime = time[1]; } else { this.params.startTime = ""; this.params.endTime = ""; } this.getList(); } addClass(e: any) { this.$store.commit('setCourseData', { id: e.courseId }); this.isShow.class = true; e.state == 4 ? this.isShow.delete = false : this.isShow.delete = true; this.createEditTwo = true; this.title = "章节"; } choiceUser(e: any) { this.$store.commit('setCourseData', { id: e.courseId }); this.isShow.user = true; this.createEditThree = true; this.title = "用户"; } studyNumberFun() { this.isShow.study = true; this.statisticsUser = true; } statisticsUserOver() { this.statisticsUser = false; } closeUser() { this.statistics(); this.statisticsUser = false; } @debounce(200, { leading: false }) searchKey() { this.getList(); } sortFunc() { this.params.sortBy = !this.params.sortBy; this.getList(); } } </script> <style lang="scss" scope> .mag-top20 { float: left; margin-top: 15px; } .mag-left20 { margin-left: 15px; } </style> <style lang="scss"> .artic-dlog { text-align: center; height: 750px; .el-dialog__body { padding: 0 !important; padding-bottom: 5px; } } </style>
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace RepairDesk.Api.Data { public class Order : BaseEntity { [Required] public string OrderNumber { get; set; } [Required] public DateTime OrderDate { get; set; } [ForeignKey(nameof(OrderStatus))] public int OrderStatusId { get; set; } public virtual OrderStatus OrderStatus { get; set; } [Required] public decimal TotalAmount { get; set; } public ICollection<OrderItem> OrderItems { get; set; } [ForeignKey(nameof(User))] public int UserId { get; set; } public virtual User User { get; set; } [ForeignKey(nameof(POS))] public int POSId { get; set; } public virtual POS POS { get; set; } public string PaymentMethod { get; set; } } }
import ProductItem from "./ProductItem"; import classes from "./Products.module.css"; const DUMMY_PRODUCTS = [ { id: "p1", price: 6, title: "Book", description: "First book I wrote", }, { id: "p2", price: 10, title: "Book2", description: "Second book I wrote", }, { id: "p3", price: 8, title: "Book3", description: "Third book I wrote", }, ]; const Products = (props) => { return ( <section className={classes.products}> <h2>Buy your favorite products</h2> <ul> {DUMMY_PRODUCTS.map((product) => { return ( <ProductItem key={product.id} id={product.id} title={product.title} price={product.price} description={product.description} /> ); })} </ul> </section> ); }; export default Products;
import React, { useEffect } from 'react' import Navbar from "react-bootstrap/Navbar"; import {Link} from "react-router-dom"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import { useForm } from "react-hook-form"; import { InputGroup } from "react-bootstrap"; import { useState } from 'react'; import { Navigate, useNavigate, useParams } from 'react-router'; import { instance } from '../../../axioConfig'; const ResetPassword = () => { const { register, handleSubmit,watch,formState: { errors } } = useForm({ mode:"all" }); const [passwordtype,setPasswordType]=useState("password"); const [cnfpPasswordType,setCnfpPasswordType]=useState("password"); const [responseType,setResponseType]=useState(null) const [responseError,setResponseError]=useState(null) const [responseMessage, setResponseMessage] = useState(null) const [count, setCount] = useState(null); const [disable,setDisable]=useState(false) const navigate = useNavigate(); useEffect(() => { if(count!=null){ const interval = setInterval(() => { // update the state after 1000ms setCount((currentCount) => currentCount - 1); }, 1000); count === 0 && navigate("/"); // clean up the interval return () => clearInterval(interval); } }, [count, navigate]); let params = useParams(); const onSubmit = (data) => { setDisable(true) setResponseMessage(null) setResponseError(null) Object.assign(data, params); instance.post('resetpassword', data ).then(function (response) { if (response.status == 200 && response.data?.type == "success") { setResponseType(true) setResponseMessage(response.data.message) setResponseError(null) setCount(10); }else { setResponseMessage(null) setResponseError(response.data?.error) setDisable(false) } }) .catch(function (error) { }); } function set_PasswordType(passwordtype,type){ switch(type) { case "password": if(passwordtype=="password") { setPasswordType("text") }else { setPasswordType("password") } break; case "confirm": if(passwordtype=="password") { setCnfpPasswordType("text") }else { setCnfpPasswordType("password") } break; default: } } return ( <div className="container-fluid otp-verification"> <div className="row"> <div className="col-lg-8 offset-lg-2 mt-5 mt-lg-0 right d-flex justify-content-center align-items-center"> <Link to="/"> <Navbar.Brand> <img src="/logo.png" className="img-fluid site-logo" /> </Navbar.Brand> </Link> <h2 className="mb-4 mt-4 red-text">Password reset</h2> <Form onSubmit={handleSubmit(onSubmit)}> <h4 className="text-center mb-3">Set a new password</h4> <Form.Group className="form-group width_100" controlId=""> <Form.Label>Password</Form.Label> <InputGroup> <Form.Control type={passwordtype} className={errors?.password ? "border border-danger " : null } {...register("password",{ required: true, minLength:8, maxLength:15, validate: { lower: value => /[a-z]/.test(value), upper: value=> /[A-Z]/.test(value), number: value=> /[0-9]/.test(value), special: value=> /[^a-zA-Z0-9]/.test(value), } })} /> <Button variant="outline-primary" onClick={()=>set_PasswordType(passwordtype,"password")}> { passwordtype==="password"? <i className="bi bi-eye-slash mb-3"></i> :<i className="bi bi-eye mb-3"></i> } </Button> </InputGroup> {errors.password && errors.password?.type ==="required" && <span className="error_p mt-1">Please Enter Password</span>} {errors.password && errors.password?.type ==="minLength" && <span className="error_p mt-1">Password Should be of minimum 8 character </span> } {errors.password && errors.password?.type ==="maxLength"&& <span className="error_p mt-1">Password cannot be more than 15 charcter </span> } {errors.password && errors.password?.type ==="lower" && <span className="error_p mt-1">Password must include a lowercase character</span>} {errors.password && errors.password?.type ==="upper" && <span className="error_p mt-1">Password must include a uppercase character</span> } {errors.password && errors.password?.type ==="number"&& <span className="error_p mt-1">Password must include a number character</span> } {errors.password && errors.password?.type ==="special"&& <span className="error_p mt-1">Password must include a special character</span> } </Form.Group> <Form.Group className="form-group width_100" controlId=""> <Form.Label>Confirm Password</Form.Label> <InputGroup> <Form.Control type={cnfpPasswordType} name="password_confirmation" {...register("password_confirmation",{ required: true, validate: { notconfirmed: (val) => (watch('password') == val ) } })} /> <Button variant="outline-primary" onClick={()=>set_PasswordType(cnfpPasswordType,"confirm")}> { cnfpPasswordType==="password"? <i className="bi bi-eye-slash"></i> :<i className="bi bi-eye"></i> } </Button> </InputGroup> {errors.password_confirmation && errors.password_confirmation?.type ==="notconfirmed"&& <span className="error_p mt-1">Password and Confirmed password do not match</span> } {errors.password_confirmation && errors.password_confirmation?.type ==="required"&& <span className="error_p mt-1">Please enter confirm password value</span> } <div className="d-flex justify-content-center error_p server_error mt-1 "> {responseMessage ? responseMessage : null} {responseError ? responseError : null}<br/> {responseError?.email? responseError.email[0]:null}<br/> {responseError?.password? responseError.password[0]:null}<br/> {count ? <>Redirecting to Login in {count} sec</>:null } </div> </Form.Group> <div style={{clear: "both"}}></div> <button type="submit" disabled={disable} className="d-block mx-auto btn dark-btn btn-lg mt-3 mb-3" id=""> Set password </button> </Form> </div> </div> </div> ) } export default ResetPassword
<?php namespace App\Livewire; use App\Models\State; use Livewire\Component; use App\Models\Category; use App\Models\Volunteer; class Home extends Component { public $search; public $category; public $state; public function render() { $query = Volunteer::query(); // Apply search filter if ($this->search) { $query->where('post_title', 'like', '%' . $this->search . '%'); } // Apply category filter if ($this->category) { $query->where('category_id', $this->category); } // Apply state filter if ($this->state) { $query->where('state_id', $this->state); } // Fetch latest volunteers with applied filters $latest_volunteers = $query->search($this->search)->latest()->take(10)->get(); $categories = Category::all(); $states = State::all(); // Pass data to the view return view('livewire.home', compact('latest_volunteers', 'states', 'categories')); } }
# func.sh # This function defines a 'cd' replacement function capable of keeping, # displaying and accessing history of visited directories, up to 10 entries. # To use it, uncomment it, source this file and try 'cd --'. # acd_func 1.0.5, 10-nov-2004 # Petar Marinov, http:/geocities.com/h2428, this is public domain cd_func () { local depth=${CD_DEPTH:=20} local x2 the_new_dir adir index local -i cnt if [[ $1 = "--" ]]; then dirs -v return 0 fi if [[ -n $ZSH_NAME ]]; then # assumes that the following zsh options are set # AUTO_PUSHD # PUSHD_IGNORE_DUPS # PUSHD_MINUS # PUSHD_SILENT cd $1 # Trim down everything beyond 11th entry popd -$depth 2>/dev/null 1>/dev/null else the_new_dir=$1 [[ -z $1 ]] && the_new_dir=$HOME if [[ ${the_new_dir:0:1} = '-' ]]; then # # Extract dir N from dirs index=${the_new_dir:1} [[ -z $index ]] && index=1 adir=$(dirs +$index) [[ -z $adir ]] && return 1 the_new_dir=$adir fi # '~' has to be substituted by ${HOME} [[ ${the_new_dir:0:2} = '~' ]] && the_new_dir="${HOME}" [[ ${the_new_dir:0:2} = '~ ' ]] && the_new_dir="${HOME}" [[ ${the_new_dir:0:2} = '~/' ]] && the_new_dir="${HOME}${the_new_dir:1}" # Now change to the new dir and add to the top of the stack pushd "${the_new_dir}" > /dev/null [[ $? -ne 0 ]] && return 1 the_new_dir=$(pwd) # Remove any other occurence of this dir, skipping the top of the stack for ((cnt=1; cnt <= $depth-1; cnt++)); do x2=$(dirs +${cnt} 2>/dev/null) [[ $? -ne 0 ]] && return 0 [[ ${x2:0:1} = '~' ]] && x2="${HOME}${x2:1}" if [[ "${x2}" = "${the_new_dir}" ]]; then popd +$cnt -n 2>/dev/null 1>/dev/null cnt=cnt-1 fi done # Trim down everything beyond Nth entry popd +$depth -n 2>/dev/null 1>/dev/null fi return 0 } alias cd=cd_func alias home='cd ~'
package com.kei037.file_stream_ex01 import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.core.app.ActivityCompat import java.io.File import java.io.FileInputStream import java.io.IOException import java.lang.Exception class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) /* Part 1 setContentView(R.layout.activity_main) val btnWrite = findViewById<Button>(R.id.btnWrite) val btnRead = findViewById<Button>(R.id.btnRead) btnWrite.setOnClickListener { // openFileOutput 객체 생성, file.txt파일 생성, MODE_PRIVATE: 생성한 앱에서만 사용가능 val outputStream = openFileOutput("file.txt", Context.MODE_PRIVATE) val string = "파일 처리 테스트" outputStream.write(string.toByteArray()) // file.txt파일에 string 문자열 입력 outputStream.close() // 닫기 Toast.makeText(applicationContext, "file.txt가 생성됨.", Toast.LENGTH_SHORT).show() } btnRead.setOnClickListener { try { // openFileInput로 file.txt 불러옴 val inputStream = openFileInput("file.txt") val txt = ByteArray(30) inputStream.read(txt) // 읽기 val string = txt.toString(Charsets.UTF_8) Toast.makeText(applicationContext, string, Toast.LENGTH_SHORT).show() } catch (e : Exception) { Toast.makeText(applicationContext, "파일 없음", Toast.LENGTH_SHORT).show() } } */ /* // Part 2 raw폴더의 txt파일 읽기 setContentView(R.layout.layout01) val btnRead = findViewById<Button>(R.id.btnRead) val editRaw = findViewById<EditText>(R.id.editRaw) btnRead.setOnClickListener { // res > raw > text.txt 파일 불러와 내용을 editText에 넣음 val inputStream = resources.openRawResource(R.raw.text) val txt = ByteArray(inputStream.available()) inputStream.read(txt) editRaw.setText(txt.toString(Charsets.UTF_8)) inputStream.close() } */ /* // Part 3 SD카드 파일 setContentView(R.layout.layout02) ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), Context.MODE_PRIVATE ) val btnRead = findViewById<Button>(R.id.btnRead) val editSD = findViewById<EditText>(R.id.editSD) btnRead.setOnClickListener { try { // 경로 지정 val inputStream = FileInputStream("/storage/emulated/0/DownLoad/test.txt") val txt = ByteArray(inputStream.available()) // 글자 길이만큼 불러옴 inputStream.read(txt) editSD.setText(txt.toString(Charsets.UTF_8)) inputStream.close() } catch (e: IOException) { println(e.printStackTrace()) Toast.makeText(applicationContext, "에러", Toast.LENGTH_SHORT).show() } } */ /* // Part 4 SD카드 저장소에 디렉토리 생성, 삭제 setContentView(R.layout.layout03) ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), Context.MODE_PRIVATE ) val btnMkdir = findViewById<Button>(R.id.btnMkDir) val btnRmdir = findViewById<Button>(R.id.btnRmDir) // SD카드의 절대경로를 돌려줌, 환경변수 밑에 /MyDir 생성하도록 경로 지정 val strSDpath = Environment.getExternalStorageDirectory().absolutePath val myDir = File("${strSDpath}/MyDir") // 버튼을 누르면 경로에 디렉토리 생성, 삭제 btnMkdir.setOnClickListener { myDir.mkdir() } btnRmdir.setOnClickListener { myDir.delete() } */ // Part 5 시스템 폴더의 폴더.파일 목록 출력 setContentView(R.layout.layout04) val btnFileList = findViewById<Button>(R.id.btnFileList) val editFileList = findViewById<EditText>(R.id.editFileList) btnFileList.setOnClickListener { val sysDir = Environment.getRootDirectory().absolutePath val sysFiles = File(sysDir).listFiles() var strFname: String for (i in sysFiles.indices) { if (sysFiles[i].isDirectory == true) { strFname = "<폴더> " + sysFiles[i].toString() } else { strFname = "<파일> " + sysFiles[i].toString() } editFileList.setText(editFileList.text.toString() + "\n" + strFname) } } } }
import { ChangeDetectionStrategy, Component, ElementRef, OnInit, ViewChild, ViewContainerRef, ViewRef } from '@angular/core'; import {FormControl, FormGroup, Validators} from '@angular/forms'; import { defaultEditorExtensions, tiptapEditorStyles, TUI_EDITOR_CONTENT_PROCESSOR, TUI_EDITOR_EXTENSIONS, TUI_EDITOR_STYLES, TuiEditorNewComponent, TuiEditorTool, tuiLegacyEditorConverter, } from '@taiga-ui/addon-editor'; import {toolbarEditor} from "../../utils/toolbar-editor"; import {TuiToolbarNewComponent} from "@taiga-ui/addon-editor/components/toolbar-new/toolbar-new.component"; import {CheckColumnsService} from "../../services/check-columns.service"; import {HttpChatService} from "../../services/http-chat.service"; import {ChatService} from "../../services/chat.service"; @Component({ selector: 'app-dialog-user', templateUrl: './dialog-user.component.html', styleUrls: ['./dialog-user.component.scss'], providers: [ { provide: TUI_EDITOR_EXTENSIONS, useValue: defaultEditorExtensions, }, { provide: TUI_EDITOR_STYLES, useValue: tiptapEditorStyles, }, { provide: TUI_EDITOR_CONTENT_PROCESSOR, useValue: tuiLegacyEditorConverter, }, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DialogUserComponent implements OnInit { @ViewChild('editorNewComponent') editorNewComponent: TuiEditorNewComponent; public form: FormGroup; public tools: TuiEditorTool[]; constructor( private checkColumnsService: CheckColumnsService, private chatService: ChatService, private httpService: HttpChatService, ) {} ngOnInit() { this.tools = toolbarEditor; } placeholder: any; control = new FormControl('', [ Validators.required, this.checkColumnsService.checkColumns ] ); public submit(): void { if (this.control.value) { console.log(this.control.value) this.httpService.postMessage(this.control.value, this.chatService.getCurrentChat()).subscribe( () => { this.httpService.getMessageByRoomId(this.chatService.getCurrentChat()).subscribe(); }, () => {} ); this.control.reset(); } } }
package com.tobeto.rentalcardemo.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; import java.util.List; @Table(name = "cars") @Entity @Getter @Setter public class Car { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "brand") private String brandName; @Column(name = "model") private String modelName; @Column(name = "year") private Integer modelYear; @Column(name = "fuel_type") private String fuelType; @Column(name = "gear_type") private String gearType; @Column(name = "price") private double dailyPrice; @JsonIgnoreProperties("car") @OneToMany(mappedBy = "car") private List<Reservation> reservations; @JsonIgnoreProperties("car") @OneToOne @JoinColumn(name = "address_id") private Address address; }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { SuppliermaterialdetailsComponent } from './components/suppliermaterialdetails/suppliermaterialdetails.component'; import { AddrawmaterialComponent } from './components/addrawmaterial/addrawmaterial.component'; import { AddsupplierComponent } from './components/addsupplier/addsupplier.component'; import { RawmateriallistComponent } from './components/rawmateriallist/rawmateriallist.component'; import { SupplierlistComponent } from './components/supplierlist/supplierlist.component'; import { CompanymateriallistComponent } from './components/companymateriallist/companymateriallist.component'; import { UpdateplayerComponent } from './components/updateplayer/updateplayer.component'; import { HomeComponent } from './components/home/home.component'; import { AboutComponent } from './components/about/about.component'; import { ContactComponent } from './components/contact/contact.component'; import { FeedbackComponent } from './components/feedback/feedback.component'; import { ServiceComponent } from './components/service/service.component'; import { RegistrationComponent } from './components/registration/registration.component'; import { LoginComponent } from './components/login/login.component'; import { AddDistributorComponent } from './components/add-distributor/add-distributor.component'; import { AddProductComponent } from './components/add-product/add-product.component'; import { DistributorProductDetailsComponent } from './components/distributor-product-details/distributor-product-details.component'; import { ProductListComponent } from './components/product-list/product-list.component'; import { DistributorListComponent } from './components/distributor-list/distributor-list.component'; import { UpdateProductComponent } from './components/update-product/update-product.component'; const routes: Routes = [ {path:'add', component:AddrawmaterialComponent}, {path:'addSupplier', component:AddsupplierComponent}, {path:'details/:supplierId', component:SuppliermaterialdetailsComponent}, {path:'raw', component:RawmateriallistComponent}, {path:'supplierlist', component:SupplierlistComponent}, {path:'companyrawlist', component:CompanymateriallistComponent}, {path:'update/:rawMaterialId', component:UpdateplayerComponent}, {path:'addd', component:AddProductComponent}, {path:'addDistributor', component:AddDistributorComponent}, {path:'details/:distributorId', component:DistributorProductDetailsComponent}, {path:'product', component:ProductListComponent}, {path:'distributorList', component:DistributorListComponent }, // {path:'companyrawlist', component:CompanymateriallistComponent}, {path:'update/:productId', component:UpdateProductComponent}, { path:'', component:HomeComponent }, { path:'about', component:AboutComponent }, { path:'contact', component:ContactComponent }, { path:'feedback', component:FeedbackComponent }, { path:'service', component:ServiceComponent }, {path:'login', component:LoginComponent}, {path:'registration', component:RegistrationComponent}, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
/** * Copyright Quadrivium LLC * All Rights Reserved * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include "application/app_state_manager.hpp" #include <condition_variable> #include <csignal> #include <mutex> #include <queue> #include "log/logger.hpp" namespace kagome::application { class AppStateManagerImpl : public AppStateManager, public std::enable_shared_from_this<AppStateManagerImpl> { public: AppStateManagerImpl(); AppStateManagerImpl(const AppStateManagerImpl &) = delete; AppStateManagerImpl(AppStateManagerImpl &&) noexcept = delete; ~AppStateManagerImpl() override; AppStateManagerImpl &operator=(const AppStateManagerImpl &) = delete; AppStateManagerImpl &operator=(AppStateManagerImpl &&) noexcept = delete; void atPrepare(OnPrepare &&cb) override; void atLaunch(OnLaunch &&cb) override; void atShutdown(OnShutdown &&cb) override; void run() override; void shutdown() override; State state() const override { return state_; } protected: void reset(); void doPrepare() override; void doLaunch() override; void doShutdown() override; private: static std::weak_ptr<AppStateManagerImpl> wp_to_myself; static void shuttingDownSignalsHandler(int); void shutdownRequestWaiting(); log::Logger logger_; std::atomic<State> state_ = State::Init; std::recursive_mutex mutex_; std::mutex cv_mutex_; std::condition_variable cv_; std::queue<OnPrepare> prepare_; std::queue<OnLaunch> launch_; std::queue<OnShutdown> shutdown_; }; } // namespace kagome::application
import { useEffect, useState } from "react"; import NewsItem from "./NewsItem"; const NewsBoard = ({category}) => { const [articles, setArticles] = useState([]); useEffect(() => { let url = `https://newsapi.org/v2/top-headlines?country=us&category=${category}&apiKey=${import.meta.env.VITE_API_KEY}`; // let url = `https://newsapi.org/v2/top-headlines?country=us&apiKey=563415aa95ca48cb99bfaf83f77b31ed`; fetch(url) .then(response => { if (!response.ok) { throw new Error('Failed to fetch data'); } return response.json(); }) .then(data => setArticles(data.articles)) .catch(error => console.error('Error fetching data:', error)); }, [category]); return ( <div> <h2 className="text-center"> Latest <span className="badge bg-danger">News</span> </h2> { articles.map((news, index) => { return <NewsItem key={index} title={news.title} description={news.description} src={news.urlToImage} url={news.url} /> }) } </div> ); }; export default NewsBoard;
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using UnityEngine.UI; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; public class UserManager : MonoBehaviour { string fileName = ""; public string currentUserName; public Text usernameTxt; public List<UserDetails> userDetails = new List<UserDetails>(); public UserWrapperData userWrapperData; public GameObject gameSceneUI; [Header("Sign Up")] public GameObject signUpUI; public InputField usernameSignUpField; public InputField passwordSignUpField; public InputField confirmPasswordSignUpField; public Toggle confirmPasswordSignUpToggle; public Toggle passwordSignUpToggle; [Header("Login")] public GameObject loginUI; public InputField usernameLogInField; public InputField passwordLogInField; public Toggle passwordLoginToggle; private Dictionary<Toggle, InputField> toggleToInputFieldMap; DbManager dbManager; GameManager gameManager; MarkerHandler markerHandler; TimeManager timeManager; LoadImages loadImages; ScreenShotManager screenShotManager; private void Start() { dbManager = FindObjectOfType<DbManager>(); gameManager = FindObjectOfType<GameManager>(); markerHandler = FindObjectOfType<MarkerHandler>(); timeManager = FindObjectOfType<TimeManager>(); loadImages = FindObjectOfType<LoadImages>(); screenShotManager = FindObjectOfType<ScreenShotManager>(); loginUI.SetActive(true); fileName = Application.dataPath + "/userdata.csv"; toggleToInputFieldMap = new Dictionary<Toggle, InputField> { { confirmPasswordSignUpToggle, confirmPasswordSignUpField }, { passwordLoginToggle, passwordLogInField }, { passwordSignUpToggle, passwordSignUpField } }; // Subscribe to the onValueChanged events of the toggles foreach (var toggle in toggleToInputFieldMap.Keys) { toggle.onValueChanged.AddListener((isOn) => ShowPassword(toggle, isOn)); } } // Login & Sign Up public void SignUp() { var username = usernameSignUpField.text; var password = passwordSignUpField.text; var confirmPassword = confirmPasswordSignUpField.text; // Check if username or password is null or empty if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { gameManager.Notification("Username or Password cannot be empty", Color.red); return; // Exit the method if username or password is empty } // Check if passwords match if (confirmPassword == password) { // Check if the user already exists if (!UserExists(username)) { User newUser = new User(username, password); userWrapperData.users.Add(newUser); dbManager.CreateUser(newUser); currentUserName = username; SuccessfulLogin(); gameManager.Notification("Sign up successful!", Color.green); } else { gameManager.Notification("User already exists. Try another username!", Color.red); } } else { gameManager.Notification("Passwords do not match!", Color.red); } } public void LogIn() { var username = usernameLogInField.text; var password = passwordLogInField.text; // Check if username or password is null or empty if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { gameManager.Notification("Username and password cannot be empty", Color.red); return; // Exit the method if username or password is empty } bool loginSuccessful = false; foreach (User user in userWrapperData.users) { if (user.userName == username && user.password == password) { gameManager.Notification("Login successful!", Color.green); SuccessfulLogin(); currentUserName = user.userName; usernameTxt.text = "Username: " + currentUserName; loginSuccessful = true; break; // Exit the loop since login is successful } } if (!loginSuccessful) { gameManager.Notification("Login unsuccessful! Incorrect password or username", Color.red); } } public void SignOut() { gameManager.ReloadScene(); } private bool UserExists(string username) { return userWrapperData.users.Exists(user => user.userName == username); } private void ShowPassword(Toggle toggle, bool isOn) { if (toggleToInputFieldMap.TryGetValue(toggle, out InputField inputField)) { inputField.contentType = isOn ? InputField.ContentType.Standard : InputField.ContentType.Password; string currentText = inputField.text; inputField.text = ""; inputField.text = currentText; } else { Debug.LogError("Toggle not found in the map!"); } } void SuccessfulLogin() { loadImages.PopulateDropdown(); loginUI.SetActive(false); signUpUI.SetActive(false); gameSceneUI.SetActive(true); loadImages.chooseImageUI.SetActive(true); } // Submit Button public void SubmitUserDetails() { timeManager.SaveTime(); var dist = markerHandler.distanceTxt.text.ToString(); var time = timeManager.timeTaken; var difficulty = gameManager.currentDifficulty.ToString(); UserDetails newUserDetails = new UserDetails(currentUserName, dist, time, difficulty); userDetails.Add(newUserDetails); dbManager.CreateUserData(newUserDetails); WriteCSV(); screenShotManager.TakeScreenShot(); // Uncomment below to Reset Game to Choose Image Page UI //gameManager.ResetToChooseImage(); } // Local Data Access: Ensure you can access the gameplay data of the current user locally (Csv) public void WriteCSV() { if(userDetails.Count > 0) { TextWriter tw = new StreamWriter(fileName, false); tw.WriteLine("Username, DistanceMeasured, TimeTaken, DifficultyLevel"); tw.Close(); tw = new StreamWriter(fileName, true); for (int i = 0; i < userDetails.Count; i++) { tw.WriteLine(userDetails[i].userName + "," + userDetails[i].distanceMeasured + "," + userDetails[i].timeTaken + "," + userDetails[i].difficultyLevel); } tw.Close(); } } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ゲームプログラミング2 第九章</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <link rel="stylesheet" href="css/template.css"> <script src="template.js"></script> </head> <body> <div id="box"> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script> <script> jQuery(function(){ $('#box').load('header.html') // #headerにheader.htmlを読み込む }); </script> <div class="title"> <h1>第九章 Enemyの実装(前編)</h1> </div> <div class="letter-body"> <ul id="list1"> <div> <h3>この章で学ぶこと</h3> <h5> <ul><li><span class="strong-letter">ベクトルは大事です。</span></li> <li><span class="strong-letter">早期リターン</span></li> </ul> </h5> </div> <li id="1"><h2 class="margin-letter2">9.1 Enemy側の行動</h2></li> <div class="letter"> <div> 最後に、第九章・第十章で「Enemy」の実装をしていきましょう。数学の話が出てきますが、ゲーム制作と数学は切り離せないので、頑張ってください。 <br>まず、実装したい「Enemy」の行動は、以下の通りです。 <div> <img src="sprite/action9/1_1.png" class="margin-letter"> <br><img src="sprite/action9/2_1.png" class="margin-letter"> </div> <div class="margin-letter"> 実装したい「Enemy」の行動を紹介したところで、「Enemy」のステートについても紹介します。 例にもれず、「Enemy」もステートを遷移させることにより、行動を制御していきます。 </div> <div> <img src="sprite/action9/5.png" class="margin-letter"> </div> </div> </div> <li id="2"><h2 class="margin-letter2">9.2 ステート遷移</h2></li> <div class="letter"> <div> では早速ステートを遷移させるプログラムを書いていきましょう。まずは、「Player」を発見したら、魔法攻撃or追尾ステートに遷移するようにしてみましょう。 <br>Enemy.cppのProcessCommonStateTransition関数に下記のコードを追加してください。 <div class="margin-letter"> <code> <ol class="code-region row col-11"> <li><font style="color:lightgreen;font-style:italic;">//Enemy.cpp/Enemy::ProcessCommonStateTransition()</font></li> <li></li> <li>void Enemy::ProcessCommonStateTransition()</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//各タイマーを初期化。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//待機時間と追跡時間を制限するため。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_idleTimer = 0.0f;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_chaseTimer = 0.0f;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//プレイヤーを見つけたら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (SearchPlayer() == true)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//通常攻撃できない距離なら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (IsCanAttack() == false)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//乱数によって、追跡させるか魔法攻撃をするか決定する。&nbsp;&nbsp;&nbsp;&nbsp;</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">int ram = rand() % 100;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//乱数が40以上なら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (ram &gt; 40)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//追跡ステートに遷移する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_enemyState = enEnemyState_Chase;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//乱数が40未満なら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//魔法攻撃ステートに遷移する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_enemyState = enEnemyState_MagicAttack;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//プレイヤーを見つけられなければ。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//待機ステートに遷移する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_enemyState = enEnemyState_Idle;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return;</span></li> <li>}</li> </ol></code> </div> <div class="margin-letter"> 続いて、「Player」に接近した際の処理を追加しましょう。 </div> <div class="margin-letter"> <code> <ol class="code-region row col-11"> <li><font style="color:lightgreen;font-style:italic;">//Enemy.cpp/Enemy::ProcessCommonStateTransition()/Enemy::IsCanAttack()</font></li> <li></li> <li>const bool Enemy::IsCanAttack() const</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">Vector3 diff = m_player-&gt;GetPosition() - m_position;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//エネミーとプレイヤーの距離が近かったら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (diff.LengthSq() &lt;= 100.0f * 100.0f)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//攻撃できる!</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return true;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//攻撃できない。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return false;</span></li> <li>}</li> <li></li> <li>void Enemy::ProcessCommonStateTransition()</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//各タイマーを初期化。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//待機時間と追跡時間を制限するため。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;m_idleTimer = 0.0f;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;m_chaseTimer = 0.0f;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//プレイヤーを見つけたら。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;if (SearchPlayer() == true)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//通常攻撃できない距離なら。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (IsCanAttack() == false)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//乱数によって、追跡させるか魔法攻撃をするか決定する。&nbsp;&nbsp;&nbsp;&nbsp;</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int ram = rand() % 100;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//乱数が40以上なら。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (ram &gt; 40)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//追跡ステートに遷移する。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;m_enemyState = enEnemyState_Chase;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//乱数が40未満なら。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//魔法攻撃ステートに遷移する。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;m_enemyState = enEnemyState_MagicAttack;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//通常攻撃ができない範囲なら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//乱数によって、待機させるか通常攻撃をするか決定する。&nbsp;&nbsp;&nbsp;&nbsp;</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">int ram = rand() % 100;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//乱数が30より上なら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (ram &gt; 30)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//攻撃ステートに遷移する。</font></li> <li></span> <span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_enemyState = enEnemyState_Attack;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//乱数が30未満なら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//待機ステートに遷移する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_enemyState = enEnemyState_Idle;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return;</span> </li> <li>&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//プレイヤーを見つけられなければ。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//待機ステートに遷移する。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;m_enemyState = enEnemyState_Idle;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;return;</li> <li>}</li> </ol></code> </div> <div class="margin-letter"> これで、ステート遷移の処理は以上です。 </div> </div> </div> <li id="3"><h2 class="margin-letter2">9.3 Playerの発見</h2></li> <div class="letter"> <div> 先ほどのプログラムで、「SearchPlayer」という関数が出てきました。この関数で「Player」が発見できたかどうかを判断するのですが、まだこの関数は未実装です。 なので、次はSearchPlayer関数の処理を追加していきます。 <div class="margin-letter"> 処理を追加する前に、問題です。<span class="strong-letter">「Player」を発見している、とはどういう状況でしょうか。</span> プログラムに落とし込むには、具体的な数値や計算が必要になってきます。少し考えてみてください。 </div> <div class="margin-letter3"> 今回の実装では、 <ul> <li><span class="strong-letter">PlayerとEnemyの距離が一定以内。</span></li> <li><span class="strong-letter">PlayerがEnemyの視野角内にいる。</span></li> </ul> の2つを満たせば、「Player」を発見しているという風にしたいと思います。 では、SearchPlayer関数に下記のコードを追加してください。 </div> <div class="margin-letter"> <code> <ol class="code-region row col-11"> <li><font style="color:lightgreen;font-style:italic;">//Enemy.cpp/Enemy::SearchPlayer()</font></li> <li></li> <li>const bool Enemy::SearchPlayer() const</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//エネミーからプレイヤーに向かうベクトルを求める。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">Vector3 diff = m_player-&gt;GetPosition() - m_position;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//プレイヤーにある程度近かったら。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (diff.LengthSq() &lt;= 700.0 * 700.0f)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//エネミーからプレイヤーに向かうベクトルを正規化(大きさを1)する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">diff.Normalize();</span> </li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//エネミーの正面のベクトルと、エネミーからプレイヤーに向かうベクトルの。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//内積(cosθ)を求める。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">float cos = m_forward.Dot(diff);</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//内積(cosθ)から角度(θ)を求める。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">float angle = acosf(cos);</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//角度(θ)が120°(視野角)より小さければ。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (angle &lt;= (Math::PI / 180.0f) * 120.0f)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//プレイヤーを見つけた!</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return true;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//プレイヤーを見つけられなかった。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">return false;</span></li> <li>}</li> </ol></code> </div> <div class="margin-letter"> できたら、実行してください。「Player」が「Enemy」の視界に入ると、何らかの挙動をするようになったと思います。 <br>先ほどの視野角判定処理は、以下のようになっています。 </div> <div class="margin-letter"> <img src="sprite/action9/8_1.png" class="margin-letter"> </div> <div class="margin-letter"> <br><span class="strong-letter">2つのベクトルの内積を計算すると、cosθを求める</span>ことができます。さらに、<span class="strong-letter">arcos(cosθ)を計算すれば、θを求める</span>ことができます。 このように2つのベクトルのなす角を求めます。 <br><a href="https://w3e.kanazawa-it.ac.jp/math/category/vector/henkan-tex.cgi?target=/math/category/vector/naiseki-wo-fukumu-kihonsiki.html">2つのベクトルのなす角</a> </div> </div> </div> <li id="4"><h2 class="margin-letter2">9.4 追跡</h2></li> <div class="letter"> <div> 最後に、「Player」を追跡する処理を追加しましょう。Enemy.cppのProcessCommonStateTransition関数とChase関数に下記のコードを追加してください。 <div class="margin-letter"> <code> <ol class="code-region row col-11"> <li><font style="color:lightgreen;font-style:italic;">//Enemy.cpp/Enemy::SearchPlayer()</font></li> <li></li> <li>void Enemy::Chase()</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//追跡ステートでないなら、追跡処理はしない。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;if (m_enemyState != enEnemyState_Chase)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//エネミーを移動させる。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_position = m_charaCon.Execute(m_moveSpeed, g_gameTime-&gt;GetFrameDeltaTime());</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">if (m_charaCon.IsOnGround()) {</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//地面についた。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//重力を0にする。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_moveSpeed.y = 0.0f;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">}</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">Vector3 modelPosition = m_position;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//ちょっとだけモデルの座標を挙げる。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">modelPosition.y += 2.5f;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//座標を設定する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_modelRender.SetPosition(modelPosition);</span></li> <li>}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.</li> <li>void Enemy::ProcessCommonStateTransition()</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//各タイマーを初期化。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//待機時間と追跡時間を制限するため。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;m_idleTimer = 0.0f;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;m_chaseTimer = 0.0f;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//エネミーからプレイヤーに向かうベクトルを計算する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">Vector3 diff = m_player-&gt;GetPosition() - m_position;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//プレイヤーを見つけたら。</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;if (SearchPlayer() == true)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//ベクトルを正規化する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">diff.Normalize();</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;"><font style="color:lightgreen;font-style:italic;">//移動速度を設定する。</span></font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(210,255,61);border-bottom:solid 1px rgb(210,255,61);font-weight:bold;">m_moveSpeed = diff * 250.0f;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//乱数によって、追跡させるか魔法攻撃をするか決定する。&nbsp;&nbsp;&nbsp;&nbsp;</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int ram = rand() % 100;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.</li> </ol></code> </div> <div class="margin-letter"> 出来たら、実行してみてください。追跡するようになっているでしょうか。 </div> <div class="margin-letter"> 追跡する際の移動速度の計算は以下の通りです。 <ol> <li>「Enemy」から「Player」に向かうベクトルと求める。</li> <li>前述のベクトルを正規化する。</li> <li>正規化したベクトルに定数を乗算する。</li> </ol> </div> <div class="margin-letter"> この章では、ベクトルの話が出てきました。今回のようなオブジェクト制御だけでなく、グラフィックスな話にもベクトルは大いに関わってくるので、<span class="strong-letter">不安な学生はベクトルの復習をしておくとよいでしょう。</span> </div> </div> </div> <li id="5"><h2 class="margin-letter2">9.5 まとめ</h2></li> <div class="letter"> <div> <ul> <li>ベクトルは大事です。</li> </ul> </div> </div> <li id="6"><h2 class="margin-letter2">9.6 Tips 早期リターン</h2></li> <div class="letter"> <div> プログラムを書く際に、if-else文が出てきた時は<span class="strong-letter">「早期リターン」</span>を活用しては如何でしょうか。 早期リターンとは、<span class="strong-letter">関数の処理の途中で値が確定した時点でreturnを使用することで、if分のネストを減らすテクニック</span>です。 ネストを減らすということは、簡単にいうとif文の中にif文を書くことを減らすということです。 <div class="margin-letter"> まずは、早期リターンを使用せずに書いたプログラムを見てみましょう。 </div> <div class="margin-letter"> <code> <ol class="code-region row col-11"> <li><font style="color:lightgreen;font-style:italic;">//エアコンを付けるかどうかの判断をする。</font></li> <li>function test(temp,humidity)</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//温度が25度より上なら</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;if (temp &gt; 25)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:lightgreen;font-style:italic;">//湿度が60より上なら</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(humidity&gt;60)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"冷房を付ける"</font>;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"何もしない"</font>;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;else if (temp &lt; 10)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"暖房を付ける"</font>;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;else</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"何もしない"</font>;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>}</li> </ol></code> </div> <div class="margin-letter"> 次に、早期リターンを使用したプログラムを見てみましょう。 </div> <div class="margin-letter"> <code> <ol class="code-region row col-11"> <li><font style="color:lightgreen;font-style:italic;">//エアコンを付けるかどうかの判断をする。</font></li> <li>function test(temp,humidity)</li> <li>{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;if(temp &lt;=25 &amp;&amp; temp &gt;= 10)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"なにもしない"</font>;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;if(temp &lt; 10)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"暖房を付ける"</font></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;if(humidity&gt;60)</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;{</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"冷房を付ける"</font>;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;}</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;return <font style="color:lightcoral;">"何もしない"</font>;</li> <li>}</li> </ol></code> </div> <div class="margin-letter"> 下のプログラムでは、早期リターンを使用することでかなりスッキリしたものになっているのではないでしょうか。 今回の「Enemy」のプログラムでも、早期リターンを使用することで、else文を使用せずネストを減らしています。 </div> </div> </div> </ul> </div> </body>
import java.util.concurrent.Semaphore; import java.util.function.IntBinaryOperator; public class MatrixRowSums { private static final int ROWS = 10; private static final int COLUMNS = 100; private static class Matrix { private final int rows; private final int columns; private final IntBinaryOperator definition; public Matrix(int rows, int columns, IntBinaryOperator definition) { this.rows = rows; this.columns = columns; this.definition = definition; } public int[] rowSums() { int[] rowSums = new int[rows]; for (int row = 0; row < rows; ++row) { int sum = 0; for (int column = 0; column < columns; ++column) { sum += definition.applyAsInt(row, column); } rowSums[row] = sum; } return rowSums; } private volatile int [] done; private Semaphore[] s = new Semaphore[COLUMNS]; private static int [] rowSums; private static Thread[] threads; private class Helper implements Runnable { private int row; public Helper(int row) { this.row = row; } private void freeSem(int col) { for (int i = 0; i < ROWS; i++) { s[col].release(); } } @Override public void run() { for (int col = 0; col < COLUMNS; ++col) { if (done[col] < ROWS) { try { s[col].acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } } rowSums[row] += definition.applyAsInt(row, col); // System.out.println(row + " " + col); done[col + 1]++; if (done[col + 1] == ROWS && col < COLUMNS - 1) freeSem(col + 1); } } } public int[] rowSumsConcurrent() { done = new int[COLUMNS + 1]; done[0] = ROWS; rowSums = new int[ROWS]; threads = new Thread[ROWS]; for (int i = 0; i < COLUMNS; i++) { s[i] = new Semaphore(0); } for (int i = 0; i < ROWS; i++) { threads[i] = new Thread(new Helper(i)); threads[i].start(); } for (int i = 0; i < ROWS; i++) { try { threads[i].join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } return rowSums; } } public static void main(String[] args) { Matrix matrix = new Matrix(ROWS, COLUMNS, (row, column) -> { int a = 2 * column + 1; return (row + 1) * (a % 4 - 2) * a; }); int[] rowSums = matrix.rowSumsConcurrent(); for (int i = 0; i < rowSums.length; i++) { System.out.println(i + " -> " + rowSums[i]); } } }
import { Card, Col, Container, Image, Row, Spinner } from "react-bootstrap"; import Main from "../../../layouts/Main"; import { useEffect, useState } from "react"; import api from "../../api/config/api"; import { Loading } from "@nextui-org/react"; export default function Dashboard() { const [count, setCount] = useState({ count_karya_tulis: 0, count_karya_citra: 0, count_akun_siswa: 0, count_akun_guru: 0, count_akun_tim: 0, }); const [isLoading, setIsLoading] = useState(false); const jumlahAkun = [ { total: count.count_akun_siswa, title: "akun siswa" }, { total: count.count_akun_guru, title: "akun guru" }, { total: count.count_akun_tim, title: "akun tim ppdb" }, ]; const jumlahKarya = [ { total: count.count_karya_citra, title: "karya citra" }, { total: count.count_karya_tulis, title: "karya tulis" }, ]; const fetchData = async () => { setIsLoading(true); await api .get("count") .then((response) => { setCount({ count_karya_tulis: response.data.count_karya_tulis, count_karya_citra: response.data.count_karya_citra, count_akun_tim: response.data.akun_tim, count_akun_siswa: response.data.akun_siswa, count_akun_guru: response.data.akun_guru, }); setIsLoading(false); }) .catch(() => { setIsLoading(false); }); }; useEffect(() => { fetchData(); }, []); return ( <> <Main> <Container> <header> <h1>Halo, Selamat datang di halaman dashboard admin</h1> <p className="lead">SMK Pariwisata Islam Terpadu Nurul Imam</p> </header> <main> <Row> <Col md={6}> <Card className="rounded p-5 mt-5"> <h5>Jumlah akun</h5> <Row> {jumlahAkun.map((item, i) => ( <Col md={4} key={i}> {isLoading ? ( <Loading type="spinner" size="lg" /> ) : ( <h2 className="fw-bold">{item.total}</h2> )} <p>{item.title}</p> </Col> ))} </Row> <h5 className="mt-5">Jumlah karya</h5> <Row> {jumlahKarya.map((item, i) => ( <Col md={4} key={i}> {isLoading ? ( <Loading type="spinner" size="lg" /> ) : ( <h2 className="fw-bold">{item.total}</h2> )} <p>{item.title}</p> </Col> ))} </Row> </Card> </Col> <Col md={6}> <Image src="/img/dashboard.jpg" className="img-fluid" alt="dashboard" /> </Col> </Row> </main> </Container> </Main> </> ); }
package rooms; import static rooms.Properties.REFRIGERATOR; import static rooms.Properties.TV; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.apache.log4j.Logger; /** * Class that extends {@link rooms.Room} abstract class and adds fields * that are specific to this type of room. */ @Getter @Setter @NoArgsConstructor public class Standard extends Room { private static Logger logger = Logger.getLogger(Standard.class); private boolean withTV; private boolean withRefrigerator; /** * Constructor that accepts room number and floor number and sets * the room status as not booked. It sets the price and the total size * of this kind of room. It also adds room properties * 'TV' and 'Refrigerator' to the list of properties. * * @param number sets a number of the room. {@link hotel.HotelBuilder} * methods automatically assign a consecutive value on given floor. * @param floor sets a number of the floor on which the room is being set. */ public Standard(int number, int floor) { super(number, floor); this.price = 280; this.totalSize = 20; this.withTV = true; this.withRefrigerator = true; roomProperties.add(TV); roomProperties.add(REFRIGERATOR); } @Override public String toString() { return "Standard {" + "number: " + number + ", floor: " + floor + '}'; } }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:ruletafirebase/src/screens/ruletaPersonalizada.dart'; import 'package:ruletafirebase/src/screens/ruletaView.dart'; class EditarActividad extends StatefulWidget { EditarActividad({Key key}) : super(key: key); @override _EditarActividadState createState() => _EditarActividadState(); } class _EditarActividadState extends State<EditarActividad> { @override Widget build(BuildContext context) { TextEditingController textDescripcionCtrl = TextEditingController(); final actividad = ModalRoute.of(context).settings.arguments as Map<String, dynamic>; textDescripcionCtrl.text = actividad['descripcion']; final textDescripcion = TextFormField( maxLines: 10, controller: textDescripcionCtrl, decoration: InputDecoration( filled: true, fillColor: Colors.white24, prefixIcon: Icon(Icons.description), labelText: 'Descripcion', labelStyle: TextStyle(color: Colors.white54), border: OutlineInputBorder(borderRadius: BorderRadius.circular(30)), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(30), ), ), style: TextStyle(color: Colors.white, fontSize: 15), ); final btnAgregar = ElevatedButton( onPressed: () { FirebaseFirestore.instance .collection('actividades') .doc(actividad['id']) .update( { 'descripcion': textDescripcionCtrl.text, }, ); Navigator.pop(context); Navigator.pop(context); if (actividad['tipo'] == "Casa") { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => RuletaView( tipoRuleta: "Casa", ), ), ); } else { if (actividad['tipo'] == "Salidas") { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => RuletaView( tipoRuleta: "Salidas", ), ), ); } else { Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => RuletaPersonalizada()), ); } } }, style: ElevatedButton.styleFrom( textStyle: TextStyle(color: Colors.white), padding: EdgeInsets.all(0), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), ), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), gradient: LinearGradient( colors: <Color>[ Color(0xFFFF4F2C), Color(0xFFEF2295), ], )), padding: EdgeInsets.all(15.0), width: 10000, child: Text( 'Guardar', style: TextStyle(fontSize: 20), textAlign: TextAlign.center, ), ), ); return Scaffold( appBar: AppBar( title: Text("Editar actividad"), backgroundColor: Color(0xFF102E89), ), body: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Color(0xFF102E89), Color(0xFF020818), ], ), ), child: Center( child: Padding( padding: const EdgeInsets.all(10.0), child: ListView( children: [ SizedBox(height: 20), Center( child: Text( "Editar actividad número " + actividad['numero'].toString() + " de " + actividad['tipo'], style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), ), SizedBox(height: 20), textDescripcion, SizedBox(height: 20), btnAgregar, ], ), ), ), ), ); } }
// // PhotoListViewModelTests.swift // PhotoListViewModelTests // // Created by Hemg on 2/10/24. // import XCTest @testable import ios_unsplash import Combine class MockUnsplashRepository: UnsplashRepository { var fetchPhotosResult: Result<[Photo], Error>? func fetchPhotos(page: Int) -> AnyPublisher<[Photo], Error> { return fetchPhotosResult!.publisher.eraseToAnyPublisher() } } final class PhotoListViewModelTests: XCTestCase { var viewModel: PhotoListViewModel! var mockRepository: MockUnsplashRepository! override func setUpWithError() throws { mockRepository = MockUnsplashRepository() viewModel = PhotoListViewModel(repository: mockRepository) } override func tearDownWithError() throws { viewModel = nil mockRepository = nil } func test_통신실패시에배열이_비어있는지_확인() { // Given let expectedError = NSError(domain: "test", code: 0, userInfo: nil) mockRepository.fetchPhotosResult = .failure(expectedError) // When viewModel.loadPhotos(isRefresh: true) // Then XCTAssertTrue(viewModel.photos.isEmpty) } func test_로딩중확인하기() { // Given mockRepository.fetchPhotosResult = .success([]) // When viewModel.loadPhotos(isRefresh: false) // Then XCTAssertTrue(viewModel.isLoading) XCTAssertEqual(viewModel.isLoading, true) } }
'use strict'; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator['throw'](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, '__esModule', { value: true }); exports.getUserRole = exports.getCurrentUser = void 0; const jsonwebtoken_1 = __importDefault(require('jsonwebtoken')); const UserStore_1 = require('../../stores/UserStore/UserStore'); const userStore = new UserStore_1.UserStore(); function getCurrentUser(req, res) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { const authorizationHeader = req.headers.authorization; if (!authorizationHeader) res.status(401).send('You must provide token'); else { const token = authorizationHeader.split(' ')[1]; jsonwebtoken_1.default.verify( token, process.env.TOKEN_SECRET, (err, result) => __awaiter(this, void 0, void 0, function* () { if (err) reject(res.status(400).send(`Invalid token: ${err.message}`)); else { let tokenObj = JSON.parse(JSON.stringify(result)); const user = yield userStore.getUser(tokenObj.user.id); console.log(user); resolve(user); } }) ); } }); }); } exports.getCurrentUser = getCurrentUser; function getUserRole(req) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { const authorizationHeader = req.headers.authorization; if (!authorizationHeader) reject('You must provide token'); else { const token = authorizationHeader.split(' ')[1]; jsonwebtoken_1.default.verify( token, process.env.TOKEN_SECRET, (err, result) => __awaiter(this, void 0, void 0, function* () { if (err) reject(`Invalid token: ${err.message}`); else { let tokenObj = JSON.parse(JSON.stringify(result)); const user = yield userStore.getUser(tokenObj.user.id); if (user) resolve(user.role || 'No role found'); else reject('User must be logged in'); } }) ); } }); }); } exports.getUserRole = getUserRole;
import RecordInfos from "./RecordInfos"; import { _data } from "@/Context/Context"; import { useEffect, useState, useContext } from "react"; import PlayButton from "./PlayButton"; import XSign from "./XSign"; export default function PlayARecord({ record, onDelete, edits }) { const { sourceAudio, setSourceAudio } = useContext(_data) const [isPlaying, setIsPlaying] = useState(false); const stream = `${process.env.NEXT_PUBLIC_API_URL}/api/stream?id=${record._id}`; const audioTag = document.getElementById("audioSource"); const equal = () => ( audioTag.src === stream ) useEffect(() => { let audio = document.getElementById("audioSource"); equal() && audio.play ? setIsPlaying(true) : setIsPlaying(false); function handlePlay() { equal() ? setIsPlaying(true) : null; } function handlePause() { equal() ? setIsPlaying(false) : null; }; audio.addEventListener("play", handlePlay); audio.addEventListener("pause", handlePause); equal() ? audio.addEventListener("ended", () => setIsPlaying(false)) : null; return () => { audio.removeEventListener("play", handlePlay); audio.removeEventListener("pause", handlePause); equal() ? audio.removeEventListener("ended", () => setIsPlaying(false)) : null; }; }, []); return ( <> <PlayButton record={record} isPlaying={isPlaying} setSourceAudio={setSourceAudio} equal={equal} /> <RecordInfos record={record} equal={equal} /> {edits && <XSign mixId={record._id} onDelete={() => onDelete(record._id)} /> } </> ); }
# Installing HemaScopeR: ## Quick Installation ### 1. Install R, python and optionally RStudio **HemaScopeR** is a package written in R and Python. It can also be utilized within the interactive environment of RStudio. R can be obtained and installed from [https://cran.rstudio.com](https://cran.rstudio.com). Python can be obtained and installed from [https://www.python.org](https://www.python.org). Please install R version 4.2 and python version 3.11.4 or higher. Following installation of R, Rstudio can be obtained and installed from [https://www.rstudio.com/products/rstudio/download/](https://www.rstudio.com/products/rstudio/download/). The free version of RStudio Desktop is sufficient. ### 2. Install required R-packages, Python-packages and HemaScopeR #### A. Install required R-packages and HemaScopeR automatically We wrote a script that will attempt to install all required R-packages for HemaScopeR and then HemaScopeR itself. Start RStudio and then run the installation script from the console: ```R source("https://github.com/ZhenyiWangTHU/HemaScopeR/blob/master/HemaScopeR-install.R") ``` #### If something went wrong previously, you may need to try manually installing some of HemaScopeR's dependent R-packages, as well as HemaScopeR itself, following steps B, C and E: #### B. Install and attach the *devtools* package *devtools* is required to compile and install HemaScopeR, since it's distributed through GitHub. ```R install.packages("devtools") ``` #### C. Install required R-packages Installation of these R-packages is necessary prior to HemaScopeR installation. ```R shiny 1.7.5 textshaping 0.3.6 shinyjs 2.1.0 Seurat 4.3.0.1 phateR 1.0.7 DoubletFinder 2.0.3 monocle 2.28.0 slingshot 2.8.0 GSVA 1.48.3 limma 3.56.2 plyr 1.8.8 dplyr 1.1.2 org.Mm.eg.db 3.17.0 org.Hs.eg.db 3.17.0 CellChat 1.6.1 velocyto.R 0.6 SeuratWrappers 0.3.1 stringr 1.5.0 scran 1.28.2 ggpubr 0.6.0 viridis 0.6.4 pheatmap 1.0.12 parallel 4.3.1 reticulate 1.31 SCENIC 1.1.2.1 feather 0.3.5 AUCell 1.22.0 RcisTarget 1.20.0 Matrix 1.6.1 foreach 1.5.2 doParallel 1.0.17 clusterProfiler 4.8.3 OpenXGR 1.0.0 RColorBrewer 1.1.3 Rfast2 0.1.5.1 SeuratDisk 0.0.0.9020 abcCellmap 0.1.0 biomaRt 2.56.1 copykat 1.1.0 gelnet 1.2.1 ggplot2 3.4.4 parallelDist 0.2.6 patchwork 1.1.3 markdown 1.10 ``` #### D. Install required Python-packages These Python-packages must be installed for Python-based steps in HemaScopeR. ```Python numpy 1.23.5 pandas 1.3.5 scvelo 0.2.5 arboreto 0.1.6 pot 0.9.1 anndata 0.9.2 scanpy 1.9.4 scipy 1.11.2 seaborn 0.12.2 commot 0.0.3 matplotlib 3.7.2 cell2location 0.1.3 scvi-tools 1.0.3 phate 1.0.11 ``` #### E. Install HemaScopeR *HemaScopeR* can be installed directly from the GitHub repository ```R library(devtools) ``` ```R install_github(repo="ZhenyiWangTHU/HemaScopeR") ``` If you do not want to update the installed dependencies, you could run this command ```R install_github(repo="ZhenyiWangTHU/HemaScopeR", dep = FALSE) ``` Or download HemaScopeR_1.0.0.tar.gz and install in R ```R install.packages('HemaScopeR_1.0.0.tar.gz') ``` #### F. Download databases In addition to the R-packages and Python-packages, you will also need to download the databases for HemaScopeR. The databases are available in our Cloud Drive via this link [https://cloud.tsinghua.edu.cn/d/759fd04333274d3f9946/](https://cloud.tsinghua.edu.cn/d/759fd04333274d3f9946/). #### G. Configure HemaScopeR Please note the installation path of Python and the storage path of databases. When running HemaScopeR, assign these two paths respectively to 'pythonPath' and 'databasePath' parameters. ### 3. Pull Docker image 'hemascoper' from Docker Hub *HemaScopeR* can be accessed via Docker Hub at [https://hub.docker.com/r/l1hj/hemascoper](https://hub.docker.com/r/l1hj/hemascoper) or through Docker pull command ```shell docker pull l1hj/hemascoper ```
/* eslint-disable @typescript-eslint/no-unused-vars */ import {AminoMsg} from "@cosmjs/amino"; import {AminoConverter} from "../../amino/types"; import {MsgBurn, MsgBuyShr, MsgLoad, MsgSend, MsgSetExchange, MsgLoadFee} from "../../codec/shareledger/gentlemint/tx"; import {EncodeObject, GeneratedType} from "../../signing"; import {DecCoin} from "../../codec/cosmos/base/v1beta1/coin"; export interface AminoMsgBurn extends AminoMsg { // NOTE: Type string and names diverge here! readonly type: "gentlemint/Burn"; readonly value: { readonly coins: DecCoin[]; readonly creator: string; }; } export function isAminoMsgBurn(msg: AminoMsg): msg is AminoMsgBurn { // NOTE: Type string and names diverge here! return msg.type === "gentlemint/Burn"; } export interface MsgBurnEncodeObject extends EncodeObject { readonly typeUrl: "/shareledger.gentlemint.MsgBurn"; readonly value: Partial<MsgBurn>; } export function isMsgBurnEncodeObject(encodeObject: EncodeObject): encodeObject is MsgBurnEncodeObject { return (encodeObject as MsgBurnEncodeObject).typeUrl === "/shareledger.gentlemint.MsgBurn"; } export interface AminoMsgLoad extends AminoMsg { // NOTE: Type string and names diverge here! readonly type: "gentlemint/Load"; readonly value: { readonly address: string; readonly coins: DecCoin[]; readonly creator: string; }; } export function isAminoMsgLoad(msg: AminoMsg): msg is AminoMsgLoad { // NOTE: Type string and names diverge here! return msg.type === "gentlemint/Load"; } export interface MsgLoadEncodeObject extends EncodeObject { readonly typeUrl: "/shareledger.gentlemint.MsgLoad"; readonly value: Partial<MsgLoad>; } export function isMsgLoadEncodeObject(encodeObject: EncodeObject): encodeObject is MsgLoadEncodeObject { return (encodeObject as MsgLoadEncodeObject).typeUrl === "/shareledger.gentlemint.MsgLoad"; } export interface AminoMsgSend extends AminoMsg { // NOTE: Type string and names diverge here! readonly type: "gentlemint/Send"; readonly value: { readonly address: string; readonly coins: DecCoin[]; readonly creator: string; }; } export function isAminoMsgSend(msg: AminoMsg): msg is AminoMsgSend { // NOTE: Type string and names diverge here! return msg.type === "gentlemint/Send"; } export interface MsgSendEncodeObject extends EncodeObject { readonly typeUrl: "/shareledger.gentlemint.MsgSend"; readonly value: Partial<MsgSend>; } export function isMsgSendEncodeObject(encodeObject: EncodeObject): encodeObject is MsgSendEncodeObject { return (encodeObject as MsgSendEncodeObject).typeUrl === "/shareledger.gentlemint.MsgSend"; } export interface AminoMsgBuyShr extends AminoMsg { // NOTE: Type string and names diverge here! readonly type: "gentlemint/BuyShr"; readonly value: { readonly amount: string; readonly creator: string; }; } export function isAminoMsgBuyShr(msg: AminoMsg): msg is AminoMsgBuyShr { // NOTE: Type string and names diverge here! return msg.type === "gentlemint/BuyShr"; } export interface MsgBuyShrEncodeObject extends EncodeObject { readonly typeUrl: "/shareledger.gentlemint.MsgBuyShr"; readonly value: Partial<MsgBuyShr>; } export function isMsgBuyShrEncodeObject(encodeObject: EncodeObject): encodeObject is MsgBuyShrEncodeObject { return (encodeObject as MsgBuyShrEncodeObject).typeUrl === "/shareledger.gentlemint.MsgBuyShr"; } export interface AminoMsgSetExchange extends AminoMsg { // NOTE: Type string and names diverge here! readonly type: "gentlemint/SetExchange"; readonly value: { readonly creator: string; readonly rate: string; }; } export function isAminoMsgSetExchange(msg: AminoMsg): msg is AminoMsgSetExchange { // NOTE: Type string and names diverge here! return msg.type === "gentlemint/SetExchange"; } export interface MsgSetExchangeEncodeObject extends EncodeObject { readonly typeUrl: "/shareledger.gentlemint.MsgSetExchange"; readonly value: Partial<MsgSetExchange>; } export function isMsgSetExchangeEncodeObject(encodeObject: EncodeObject): encodeObject is MsgSetExchangeEncodeObject { return (encodeObject as MsgSetExchangeEncodeObject).typeUrl === "/shareledger.gentlemint.MsgSetExchange"; } export interface AminoMsgLoadFee extends AminoMsg { // NOTE: Type string and names diverge here! readonly type: "gentlemint/LoadFee"; readonly value: { readonly creator: string; readonly shrp?: DecCoin; }; } export function isAminoMsgLoadFee(msg: AminoMsg): msg is AminoMsgLoadFee { // NOTE: Type string and names diverge here! return msg.type === "gentlemint/LoadFee"; } export interface MsgLoadFeeEncodeObject extends EncodeObject { readonly typeUrl: "/shareledger.gentlemint.MsgLoadFee"; readonly value: Partial<MsgLoadFee>; } export function isMsgLoadFeeEncodeObject(encodeObject: EncodeObject): encodeObject is MsgLoadFeeEncodeObject { return (encodeObject as MsgLoadFeeEncodeObject).typeUrl === "/shareledger.gentlemint.MsgLoadFee"; } export function createAminoTypes(prefix: string): Record<string, AminoConverter> { return { "/shareledger.gentlemint.MsgBurn": { aminoType: "gentlemint/Burn", toAmino: ({coins, creator}: MsgBurn): AminoMsgBurn["value"] => ({ coins: [...coins], creator }), fromAmino: ({coins, creator}: AminoMsgBurn["value"]): MsgBurn => ({ coins: [...coins], creator }) }, "/shareledger.gentlemint.MsgLoad": { aminoType: "gentlemint/Load", toAmino: ({address, coins, creator}: MsgLoad): AminoMsgLoad["value"] => ({ address, coins: [...coins], creator }), fromAmino: ({address, coins, creator}: AminoMsgLoad["value"]): MsgLoad => ({ address, coins: [...coins], creator }) }, "/shareledger.gentlemint.MsgSend": { aminoType: "gentlemint/Send", toAmino: ({address, coins, creator}: MsgSend): AminoMsgSend["value"] => ({ address, coins: [...coins], creator }), fromAmino: ({address, coins, creator}: AminoMsgSend["value"]): MsgSend => ({ address, coins: [...coins], creator }) }, "/shareledger.gentlemint.MsgBuyShr": { aminoType: "gentlemint/BuyShr", toAmino: ({amount, creator}: MsgBuyShr): AminoMsgBuyShr["value"] => ({ amount, creator }), fromAmino: ({amount, creator}: AminoMsgBuyShr["value"]): MsgBuyShr => ({ amount, creator }) }, "/shareledger.gentlemint.MsgSetExchange": { aminoType: "gentlemint/SetExchange", toAmino: ({creator, rate}: MsgSetExchange): AminoMsgSetExchange["value"] => ({ creator, rate }), fromAmino: ({creator, rate}: AminoMsgSetExchange["value"]): MsgSetExchange => ({ creator, rate }) }, "/shareledger.gentlemint.MsgLoadFee": { aminoType: "gentlemint/LoadFee", toAmino: ({creator, shrp}: MsgLoadFee): AminoMsgLoadFee["value"] => ({ creator, shrp }), fromAmino: ({creator, shrp}: AminoMsgLoadFee["value"]): MsgLoadFee => ({ creator, shrp }) } }; } export function createRegistryTypes(): ReadonlyArray<[string, GeneratedType]> { return [ ["/shareledger.gentlemint.MsgBurn", MsgBurn], ["/shareledger.gentlemint.MsgLoad", MsgLoad], ["/shareledger.gentlemint.MsgSend", MsgSend], ["/shareledger.gentlemint.MsgBuyShr", MsgBuyShr], ["/shareledger.gentlemint.MsgSetExchange", MsgSetExchange], ["/shareledger.gentlemint.MsgLoadFee", MsgLoadFee] ]; }
// Get user input for focus and break times and font color const focusTime = prompt("Enter focus time (in minutes):"); const breakTime = prompt("Enter break time (in minutes):"); const fontColor = prompt("Enter font color for the Pomodoro timer:"); // Update the Pomodoro timer's font color document.getElementById("pomodoro-timer").style.color = fontColor; let sessionNumber = 1; function updateSessionNumber() { document.getElementById("session-number").textContent = sessionNumber; } function startPomodoroTimer() { const pomodoroTimer = document.getElementById("pomodoro-timer"); let totalTime = focusTime * 60; // Convert focus time to seconds let minutes, seconds; const interval = setInterval(function () { minutes = Math.floor(totalTime / 60); seconds = totalTime % 60; pomodoroTimer.textContent = `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`; if (totalTime <= 0) { clearInterval(interval); sessionNumber++; updateSessionNumber(); if (sessionNumber <= 7) { setTimeout(startBreakTimer, 1000); } } else { totalTime--; } }, 1000); } function startBreakTimer() { const pomodoroTimer = document.getElementById("pomodoro-timer"); let totalTime = breakTime * 60; // Convert break time to seconds let minutes, seconds; const interval = setInterval(function () { minutes = Math.floor(totalTime / 60); seconds = totalTime % 60; pomodoroTimer.textContent = `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`; if (totalTime <= 0) { clearInterval(interval); if (sessionNumber <= 7) { setTimeout(startPomodoroTimer, 1000); } } else { totalTime--; } }, 1000); } // Initialize the Pomodoro timer updateSessionNumber(); startPomodoroTimer(); // Function to update the Indian time function updateIndianTime() { const indianTime = document.getElementById("indian-time"); const now = new Date(); const options = { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", timeZoneName: "short", timeZone: "Asia/Kolkata" }; indianTime.textContent = now.toLocaleDateString("en-IN", options); } // Update Indian time every second setInterval(updateIndianTime, 1000);
// // Created by Honza Fojtík on 15.11.2022. // #include "TextReader.h" /// @brief Constructor for my TextReader class /// @param source is the name of the file thats being loaded TextReader::TextReader(string source) { this->source = source; loadFile(); } /// @brief loadFile is a function that scans the contents of a txt file void TextReader::loadFile() { ifstream file; int counter = 0; file.open(this->source, ios::in); if (file.is_open()) { string line; while (getline(file, line, '\n')) { this->lines += line + " "; } } file.close(); split(); } /// @brief split is a function that splits the numbers into 3 vectors, a - for the first dimension, b - for the second dimension, c - for the expected result void TextReader::split() { stringstream ss(lines); string s; int counter = 0; while (std::getline(ss, s, ' ')) { switch (counter % 3) { case 0: this->a.push_back(s); break; case 1: this->b.push_back(s); break; case 2: this->c.push_back(s); break; } counter++; } } /// @brief printFile is a function that prints the contents of the vectors a, b, c. It shows the layout of the txt file void TextReader::printFile() { for (int i = 0; i < this->a.size(); i++) { cout << a[i] << " " << b[i] << " " << c[i] << endl; } } /// @brief getA is a getter for vector a vector<string> TextReader::getA() { return this->a; } /// @brief getB is a getter for vector b vector<string> TextReader::getB() { return this->b; } /// @brief getCis a getter for vector c vector<string> TextReader::getC() { return this->c; }
const express = require('express'); const { check } = require('express-validator'); const { auth, checkOwnership } = require('../middleware'); const { postsController } = require('../controllers'); const router = express.Router(); /** @route GET /api/posts * @desc fetch all posts */ router.route('/') .get(postsController.getPosts); /** @route GET /api/posts/tag/:tagname * @desc fetch all posts of a specific tag */ // router.route('/tag/:tagname') // .get(postsController.getTagPosts); /** @route GET /api/posts/:id * @desc fetch a single post */ router.route('/:id') .get(postsController.getSinglePost); /** @route POST /api/posts/ * @desc add a post */ router.route('/') .post( // auth, // check('title', 'Enter a title with minimum 15 characters').isLength({ min: 15 }), // check('body', 'Enter a body with minimum 30 characters').isLength({ min: 30 }), postsController.addPost, ); /** @route DELETE /api/posts/:id * @desc delete a post */ // router.route('/:id') // .delete( // auth, // checkOwnership, // postsController.deletePost, // ); module.exports = router;
""" This file should be used to describe the whole evaluation procedure, during and after the training. Todo: We should implement a function full_evaluation() that takes data_in a generator and a config file, so we do not need to load the trainer everytime. Todo: Also, we need to factorize the set of test metric from the evaluation module """ from statistics import mean import torch import numpy as np from src.model.Generator import PairNetGenerator, Generator from torch.autograd import grad as torch_grad from src.aux_functions import * import matplotlib.pyplot as plt from timeit import default_timer from os import listdir from os.path import isfile, join from scipy.stats import logistic from sklearn.manifold import TSNE def compute_grad_norm(generator, discriminator, sample_data, config, device): """ This function computes the gradient norm of the discriminator and the penalty coefficient :param generator: :param sample_data: :param config: :return: """ unfixed_test_bsz = config['unfixed_test_bsz'] unfixed_data = sample_data[:unfixed_test_bsz] actual_bsz = unfixed_data.shape[0] bm = unfixed_data[:, :config['bm_dim']] fake_data = generator(bm).detach() gradient_penalty, gradient_norm = _gradient_penalty(unfixed_data, fake_data, gp_weight=0, discriminator=discriminator, device=device) return gradient_norm, gradient_penalty def _gradient_penalty(real_data, generated_data, gp_weight, discriminator, device): """ Computes the gradient penalty coefficients used during the training of discriminator :param real_data: :param generated_data: :param gp_weight: :param discriminator: :param device: :return: """ b_size_gp = real_data.shape[0] # Calculate interpolation alpha = torch.rand(b_size_gp, 1, device=device) alpha = alpha.expand_as(real_data) interpolated = (alpha * real_data + (1 - alpha) * generated_data).requires_grad_(True) interpolated = interpolated.to(device) # Calculate probability of interpolated examples prob_interpolated = discriminator(interpolated) # Calculate gradients of probabilities with respect to examples gradients = torch_grad(outputs=prob_interpolated, inputs=interpolated, grad_outputs=torch.ones(prob_interpolated.size(), device=device), create_graph=True, retain_graph=True)[0] # Gradients have shape (b_size, num_channels, img_width, img_height), # so flatten to easily take norm per example in batch gradients = gradients.view(b_size_gp, -1) # grad_norm = gradients.norm(2, dim=1).mean().item() # Derivatives of the gradient close to 0 can cause problems because of # the square root, so manually calculate norm and add epsilon gradients_norm = torch.sqrt(torch.sum(gradients ** 2, dim=1) + 1e-12) avg_grad_norm = gradients_norm.mean().item() # Return gradient penalty return gp_weight * ((gradients_norm - 1) ** 2).mean(), avg_grad_norm def compute_fixed_losses(generator, config, input_true_data: torch.Tensor, input_true_bm: torch.Tensor, true_fourth_moments = None, comp_joint_error=False): """ Compute various losses for model evaluation: 1) avg_st_dev_error: the second moment difference between real and fake Levy terms 2) joint_w2_loss: Wasserstein loss of the joint process (L_ij) 3) marginal_w2_loss: Wassertein loss computed at each coordinate :param generator: :param config: :param input_true_data: :param device: :param comp_joint_error: :return: """ # prepare data_ins test_bsz = input_true_data.shape[0] bm_dim = input_true_bm.shape[0] levy_dim = int((bm_dim * (bm_dim - 1)) // 2) if input_true_data.shape[1] != levy_dim: print(f"Warning in compute_fixed_losses: input_true_bm.shape={input_true_bm.shape}, but " f"input_true_data.shape={input_true_data.shape}") if len(input_true_bm.shape) == 1: bm = input_true_bm.expand(test_bsz, bm_dim) else: bm = input_true_bm levy_true = input_true_data[:test_bsz] # compute correct st_dev st_dev_fixed_increment = np.diag(levy_conditional_st_dev(bm[1, :].to('cpu').tolist())) # run generator fake_data = generator.sample_fake_data(bm) levy_fake = fake_data[:, bm_dim: (bm_dim + levy_dim)] marginal_w2_loss = [sqrt(ot.wasserstein_1d(levy_true[:, i], levy_fake[:, i], p=2).item()) for i in range(levy_dim)] if bm_dim >= 3: levy_fake_np = levy_fake.to('cpu').numpy() st_dev_err = avg_st_dev_error(st_dev_fixed_increment, levy_fake_np) # self.test_results['st dev error'] = st_dev_err else: st_dev_err = float('inf') if comp_joint_error and (bm_dim >= 3): joint_wass_dist_bsz = config['joint_wass_dist_bsz'] joint_w2_loss = joint_wass_dist(levy_true[:joint_wass_dist_bsz], levy_fake[:joint_wass_dist_bsz]) else: joint_w2_loss = float('inf') if true_fourth_moments is not None: mom4_errs = fourth_moment_errors(input_samples=levy_fake, true_moments=true_fourth_moments).item() return marginal_w2_loss, joint_w2_loss, st_dev_err, mom4_errs def compute_joint_losses(generator, config, input_true_data, device, bm_dim=None): """ Computes the joint law of joint Brownian Motion and Levy area :param generator: :param config: :param input_true_data: :param device: :return: """ bm_dim = generator.bm_dim if bm_dim is None else bm_dim bm_dim = generator.bm_dim levy_dim = int((bm_dim * (bm_dim - 1)) // 2) joint_wass_dist_bsz = config['joint_wass_dist_bsz'] # Randomly choose samples from real data indices = torch.randperm(input_true_data.shape[0])[:joint_wass_dist_bsz] true_data = input_true_data[indices] true_data_np = true_data.to('cpu').numpy() bm_torch = true_data[:, :bm_dim] levy_true = true_data[:, bm_dim: (bm_dim + levy_dim)] # run generator fake_data = sample_fake_data(generator, bm_torch) levy_fake = fake_data[:, bm_dim: (bm_dim + levy_dim)] joint_w2_loss = joint_wass_dist(levy_true, levy_fake) return joint_w2_loss def avg_st_dev_error(st_dev_fixed_increment, _levy_generated): difference = np.abs(st_dev_fixed_increment - np.sqrt(np.abs(empirical_second_moments(_levy_generated)))) return difference.mean() def make_report(tester, epoch: int = None, iters: int = None, add_line_break=True, short=False): """ Generate a string that contains all the test metrics :param tester: The trainer object :param epoch: :param iters: :param chen_iters: :param add_line_break: :param short: :return: """ test_results = tester.test_results report = "" if add_line_break: line_break = "\n" else: line_break = ", " if not (iters is None): report += f"itr: {iters}, " score = test_results['best score'] best_4mom = test_results['best_max_4mom_errors'] report += f"best_scr: {score:.3f}, 100best_4mom: {best_4mom*100:.3f} " # grad_norm = test_results['gradient norm'] # report += f"discr grad norm: {grad_norm:.5f}, " if len(test_results['loss d']) > 0: if short: avg_loss_d = mean(test_results['loss d']) report += f"discr loss: {make_pretty(avg_loss_d)}" else: report += f"discr loss: {make_pretty(test_results['loss d'])}" joint_wass_errors = test_results['joint wass errors'] if len(joint_wass_errors) > 0: if short: avg_joint = mean(joint_wass_errors) report += f", averaged joint w1 loss: {make_pretty(avg_joint)}" else: report += f", joint w1 loss: {make_pretty(joint_wass_errors)}" st_dev_error = test_results['st dev error'] if st_dev_error < 100 and not short: report += f", st dev loss: {st_dev_error:.5f}" if len(test_results['marginal w2 loss']) > 0: if short: avg_err = mean(test_results['marginal w2 loss']) report += f" avg margW2 loss: {make_pretty(avg_err)}" else: report += f"{line_break}marginal w2 loss: {make_pretty(test_results['marginal w2 loss'])}" if len(test_results['fourth_mom_errors']) > 0: if short: avg_err = mean(test_results['fourth_mom_errors']) report += f" 4mom loss: {make_pretty(avg_err)}" else: report += f"{line_break} max 4th mom errors: {make_pretty(test_results['fourth_mom_errors'])}" return report def draw_error_graphs(graph_filename, marginal_w2_losses_through_training, single_coord_labels, discriminative_losses_through_training, fourth_moments_through_training=None, joint_labels=None, descriptor: str = '', iters=None): """ Plot the losses with respect to training iterations :param graph_filename: :param marginal_w2_losses_through_training: :param single_coord_labels: :param discriminative_losses_through_training: :param fourth_moments_through_training: :param joint_labels: :param descriptor: :return: """ plt.rcParams.update({'font.size': 15}) if (fourth_moments_through_training is not None) and len(fourth_moments_through_training) > 0: fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(28, 7)) ax3.set_title("Maximal error in 4th moments") ax3.plot(iters, fourth_moments_through_training, label=joint_labels) ax3.set_ylim([0, 0.1]) ax3.set_xlabel("iterations") ax3.legend(prop={'size': 10}) ax2.set_xlabel("iterations") ax2.set_title("Discriminator losses") ax2.plot(iters, discriminative_losses_through_training) ax2.set_ylim([0, 0.3]) ax2.legend(prop={'size': 7}) elif (discriminative_losses_through_training is not None) and len(discriminative_losses_through_training) > 0: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 7)) ax2.set_xlabel("iterations") ax2.set_title("Discriminator losses") ax2.plot(iters, discriminative_losses_through_training) ax2.set_ylim([-0.01, 0.1]) ax2.legend(prop={'size': 7}) else: fig, ax1 = plt.subplots(1, 1, figsize=(10, 7)) ax1.set_xlabel("iterations") ax1.set_title("Marginal 2-Wasserstein errors") ax1.plot(iters, marginal_w2_losses_through_training, label=single_coord_labels) ax1.set_ylim([0, 0.03]) ax1.legend(prop={'size': 7}) # Add the descriptor graph_filename = graph_filename + "_{}.png".format(descriptor) # graph_filename = f"model_saves/{self.dict_saves_folder}/graph_{self.dict_saves_folder}_num{self.serial_number}_{descriptor}.png" fig.savefig(graph_filename) def sample_fake_data(generator, bm_in): """ Takes in w and prints out levy area. :param generator: :param bm_in: :return: """ actual_bsz = bm_in.shape[0] generator.eval() # self.start_time = timeit.default_timer() fake_data = generator(bm_in).detach() generator.train() return fake_data def check_perm_inv_densities(gen: Generator, h_in: list[float] = None, only_draw_first_dim = False): if h_in is None: h_in = [1.0, -2.0, 3.0, -0.5] assert len(h_in) == 4 bsz = 65536 bm_dim = 4 levy_dim = int((bm_dim * (bm_dim - 1)) // 2) h_in2 = [h_in[1], h_in[0], h_in[2], h_in[3]] h1_row = torch.tensor([h_in], dtype=torch.float, device=gen.device) h2_row = torch.tensor([h_in2], dtype=torch.float, device=gen.device) h1 = h1_row.expand(bsz, -1) h2 = h2_row.expand(bsz, -1) bb1 = gen.generate_bb(h_in=h1)[:, bm_dim:] bb2 = gen.generate_bb(h_in=h2)[:, bm_dim:] bb2_prime = torch.clone(bb2) # triu_indices = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] bb2_prime[:, 0] = - bb2[:, 0] bb2_prime[:, 1] = bb2[:, 3] bb2_prime[:, 3] = bb2[:, 1] bb2_prime[:, 2] = bb2[:, 4] bb2_prime[:, 4] = bb2[:, 2] errors = [sqrt(ot.wasserstein_1d(bb1[:, i], bb2_prime[:, i], p=2)) for i in range(levy_dim)] print(make_pretty(errors)) distns1 = [bb1[:, i].detach().to('cpu').numpy() for i in range(6)] distns2 = [bb2_prime[:, i].detach().to('cpu').numpy() for i in range(6)] if only_draw_first_dim: fig, ax = plt.subplots(nrows=1, ncols=1, sharex='all', sharey='all', figsize=(5, 3)) ax.set_title("b(0,1)") labels = ['original', '1st and 2nd dim swapped'] ax.hist((distns1[0], distns2[0]), bins=400, density=True, histtype='step', stacked=False, label=labels) ax.set_xlim(-1.5, 1.5) ax.legend(prop={'size': 6}) fig.show() return fig, axs = plt.subplots(nrows=2, ncols=3, sharex='all', sharey='all', figsize=(16, 5)) def axx(i): return axs[i // 3, i % 3] triu_indices = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] for i in range(6): ax: plt.Axes = axx(i) ax.set_title(f"b({triu_indices[i][0] + 1}, {triu_indices[i][1] + 1})") labels = ['original', '1st and 2nd dim swapped'] ax.hist((distns1[i], distns2[i]), bins=400, density=True, histtype='step', stacked=False, label=labels) ax.set_xlim(-1.5, 1.5) ax.legend(prop={'size': 6}) fig.show() def draw_density_graphs(data_in: np.ndarray, use_levy_dim_titles=False, xlim: float = 1.5): """ Draws histograms of data_in Args: data_in (np.ndarray): use_levy_dim_titles: Just to ensure proper titling of graphs when graphing levy data Returns: """ num_features = data_in.shape[1] graph_arrangement = { 1: (1, 1), 2: (1, 2), 3: (1, 3), 4: (2, 2), 5: (1, 5), 6: (2, 3), 7: (2, 4), 10: (2, 5), 15: (3, 5), 21: (5, 7) } nrows, ncols = graph_arrangement[num_features] print(ncols) fig, axs = plt.subplots(nrows=nrows, ncols=ncols, sharex='all', sharey='all', figsize=(5 * ncols, 3 * nrows)) def axx(i): return axs[i // ncols, i % ncols] for i in range(num_features): ax: plt.Axes = axx(i) if use_levy_dim_titles: bm_dim = int((1 + sqrt(1 + 8 * num_features)) / 2) ax.set_title(f"dim {bm_indices(i, bm_dim)}") else: ax.set_title(f"dim {i}") ax.hist(data_in[:, i], bins=400, density=True, histtype='step', stacked=False) ax.set_xlim(-xlim, xlim) fig.show() def draw_generator_densities(gen: Generator, generate_bb=False, data_in: torch.Tensor = None, data_in_row: list[float] = None, bsz: int = 65536, xlim: float = 1.5): """ Draws density graphs of the generator's outputs. Args: bsz: gen: the generator generate_bb: If False will generate Levy area given W=data_in, if True will generate bb given H=data_in data_in: either W increment or H increment (as a tensor) data_in_row: """ if data_in is not None: bsz = data_in.shape[0] bm_dim = gen.bm_dim data = data_in if data_in_row is not None and data is None: data: torch.Tensor = torch.tensor([data_in_row], dtype=torch.float, device=gen.device) data = data.expand(bsz, -1) if data is None: data = torch.randn((bsz, bm_dim), dtype=torch.float, device=gen.device) assert bm_dim == data.shape[1] if generate_bb: out = gen.generate_bb(h_in=data)[:, bm_dim:] else: out = gen.forward(data)[:, bm_dim:] out_numpy = out.detach().to('cpu').numpy() draw_density_graphs(out_numpy, use_levy_dim_titles=True, xlim=xlim) def compute_objectives(levG, gen_conf: dict, tr_conf: dict, num_trials: int = 5, use_saves = False): files = ['']*num_trials if use_saves: levG.init_generator(gen_conf) levG.generator.init_dict_saves_folder() path = f"model_saves/{levG.generator.dict_saves_folder}/" files = [path+f for f in listdir(path) if isfile(join(path, f)) and ('best__scr' in f or 'best_4mom' in f)] print(len(files)) min_marginal_loss = 100.0 min_eval_time = 100.0 min_mom4_loss = 100.0 avg_marginal_loss = 0 avg_eval_time = 0 avg_mom4_loss = 0 for trial in range(len(files)): levG.reset_test_results() if use_saves: levG.generator.load_dict(filename=files[trial]) else: levG.init_generator(gen_conf) levG.cf_train(tr_conf) results = levG.tester.test_results err = 0.01 * results['best score'] mom4_loss = results['best_max_4mom_errors'] z = torch.randn((65536, levG.bm_dim), dtype=torch.float, device=levG.device) start_time = default_timer() levG.generator.sample_fake_data(z) elapsed = default_timer() - start_time min_marginal_loss = err if err < min_marginal_loss else min_marginal_loss avg_marginal_loss += err / num_trials min_mom4_loss = mom4_loss if mom4_loss < min_mom4_loss else min_mom4_loss avg_mom4_loss += mom4_loss / num_trials min_eval_time = elapsed if elapsed < min_eval_time else min_eval_time avg_eval_time += elapsed/num_trials print(f"trial: {trial}, elapsed: {make_pretty(elapsed)}, marginal_err: {make_pretty(err)}," f" 4mom_err: {make_pretty(mom4_loss)}") marginal_err = avg_marginal_loss - min_marginal_loss mom4_err = avg_mom4_loss - min_mom4_loss time_err = avg_eval_time - min_eval_time return min_marginal_loss, marginal_err, min_mom4_loss, mom4_err, min_eval_time, time_err def full_evaluation(x_real, generator, conf, device, foster=False, gamma=0.5, num_iter=5, real_fourth_moments = None): """ Generate unconditional Levy process, compute the test metrics and :param x_real: real levy area and increment generated by Julia package :param generator: trained LevyGAN :param conf: generator configuration file :param device: cuda or cpu :return: loss_dict: dictionary with test metrics """ bm_dim = conf['bm_dim'] levy_dim = int(bm_dim * (bm_dim - 1) / 2) bm_real = x_real[:, :bm_dim] levy_real = x_real[:, bm_dim:] if not real_fourth_moments: real_fourth_moments = fourth_moments(levy_real) # Initialize the kernel kernel = RBFKernel(gamma=gamma) mmd = MMD(kernel, sub_matrix_dim=2 ** 10) loss_dict = { 'marginal_w2_losses': [], 'fourth_moment_losses': [], 'MMD': [], 'unconditional_loc': [], 'unconditional_scale': [] } with torch.no_grad(): # Repeat the generation for 5 times for seed in range(num_iter): torch.manual_seed(seed) mmd = MMD(kernel, sub_matrix_dim=2 ** 10) if not foster: x_fake = generator(bm_real) else: x_fake = mom4_gpu(bm_dim, x_real.shape[0], bm_in=bm_real) levy_fake = x_fake[:, bm_dim:] marginal_w2_loss = np.mean( np.array([100 * sqrt(ot.wasserstein_1d(levy_real[:, i], levy_fake[:, i], p=2)) for i in range(levy_dim)])) fourth_moment_loss = fourth_moment_errors(levy_fake, real_fourth_moments).item() loss_dict['marginal_w2_losses'].append(marginal_w2_loss) loss_dict['fourth_moment_losses'].append(fourth_moment_loss) mmd_value = mmd(x_real, x_fake) loss_dict['MMD'].append(mmd_value) del x_fake, mmd, levy_fake # if not foster: # _, levy_bb = generator.generate_bb(10 ** 5, concat_hb = False) # # def fit_logistic(data): # loc, scale = logistic.fit(data) # return loc, scale # # fitted_loc, fitted_scale = fit_logistic(levy_bb[:, 0].detach().cpu()) # loss_dict['unconditional_loc'].append(fitted_loc) # loss_dict['unconditional_scale'].append(fitted_scale) return loss_dict """ MMD computation through Kernel """ class Kernel: """ Base class """ def __call__(self, x, y): raise NotImplementedError class LinearKernel(Kernel): """ Linear Kernel """ def __call__(self, x, y): return torch.matmul(x, y.t()) class PolynomialKernel(Kernel): """ Polynomial Kernel """ def __init__(self, degree=3, c=1): self.degree = degree self.c = c def __call__(self, x, y): return (torch.matmul(x, y.t()) + self.c) ** self.degree class RBFKernel(Kernel): """ Radial basis function kernel """ def __init__(self, gamma=1.): self.gamma = gamma def __call__(self, x, y): xx = torch.sum(x**2, dim=1).view(-1, 1) yy = torch.sum(y**2, dim=1).view(1, -1) distance = xx + yy - 2.0 * torch.matmul(x, y.t()) return torch.exp(-self.gamma * distance) class MMD: def __init__(self, kernel, sub_matrix_dim=None): self.kernel = kernel self.sub_matrix_dim = sub_matrix_dim def mmd(self, X, Y): """ Computes E(K(X,Y)), batchwise if needed :param X: :param Y: :return: """ m = X.size(0) n = Y.size(0) if self.sub_matrix_dim is None: XY = self.kernel(X, Y).sum().item() / (m * n) else: row_iters = m // self.sub_matrix_dim + 1 col_iters = n // self.sub_matrix_dim + 1 XY = 0. for row_num in range(row_iters): for col_num in range(col_iters): X1 = X[row_num * self.sub_matrix_dim: (row_num + 1) * self.sub_matrix_dim] Y1 = Y[col_num * self.sub_matrix_dim: (col_num + 1) * self.sub_matrix_dim] XY += self.kernel(X1, Y1).sum().item() XY /= (m * n) return XY def __call__(self, X, Y): return self.mmd(X,X) + self.mmd(Y,Y) - 2*self.mmd(X,Y)
import torch import torch.nn as nn import torch.optim as optim from torch.distributions import Normal import torch.nn.functional as F import numpy as np import random from ..model_trainer.model_network import * from tool.utils_model import * # from environment.models import Generator # import torchvision.transforms as transforms class SAC_Trainer(): def __init__(self, env, replay_buffer, args, action_range): self.replay_buffer = replay_buffer self.transition_model_type = args.transition_type self.discount = args.gamma self.env = env self.lambda_t = args.lambda_t self.lambda_s = args.lambda_s self.eps_p = args.eps_p device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") action_dim = env.action_dim state_dim = env.state_dim * args.n_history hidden_dim = args.hidden_dim self.worker_step = torch.zeros(1, dtype=torch.int32, requires_grad=False, device='cpu') self.update_step = torch.zeros(1, dtype=torch.int32, requires_grad=False, device='cpu') self.eps = torch.zeros(1, dtype=torch.int32, requires_grad=False, device='cpu') self.soft_q_net1 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device) self.soft_q_net2 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device) self.target_soft_q_net1 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device) self.target_soft_q_net2 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device) self.policy_net = PolicyNetwork(state_dim, action_dim, hidden_dim, action_range).to(device) self.log_alpha = torch.zeros(1, dtype=torch.float32, requires_grad=True, device=device) print('Soft Q Network (1,2): ', self.soft_q_net1) print('Policy Network: ', self.policy_net) for target_param, param in zip(self.target_soft_q_net1.parameters(), self.soft_q_net1.parameters()): target_param.data.copy_(param.data) for target_param, param in zip(self.target_soft_q_net2.parameters(), self.soft_q_net2.parameters()): target_param.data.copy_(param.data) self.soft_q_criterion1 = nn.MSELoss() self.soft_q_criterion2 = nn.MSELoss() soft_q_lr = args.val_lr policy_lr = args.pol_lr alpha_lr = args.alpha_lr self.soft_q_optimizer = optim.Adam(list(self.soft_q_net1.parameters()) + list(self.soft_q_net2.parameters()), lr=soft_q_lr) self.policy_optimizer = optim.Adam(self.policy_net.parameters(), lr=policy_lr) self.alpha_optimizer = optim.Adam([self.log_alpha], lr=alpha_lr) self.train() self.target_soft_q_net1.train() self.target_soft_q_net2.train() ## For training model network if args.develop_mode == "mrrl": self.model_net = ModelNetwork(state_dim, action_dim, hidden_dim, args).to(device) self.pid_net = PidNetwork(state_dim, action_dim, hidden_dim, args).to(device) self.mn_optimizer = optim.Adam( list(self.model_net.parameters()) + list(self.pid_net.parameters()), lr=args.model_lr) self.model_net.trains() self.pid_net.trains() if args.develop_mode == "imn": if args.train is True: self.inv_model_net = InverseModelNetwork(env, hidden_dim, args).to(device) else: self.inv_model_net = InverseModelNetwork(env, hidden_dim, args, net_type="dnn").to(device) self.imn_optimizer = optim.Adam(self.inv_model_net.parameters(), lr=args.inv_model_lr) self.inv_model_net.trains() self.imn_criterion = nn_ard.ELBOLoss(self.inv_model_net, F.smooth_l1_loss).to(device) def train(self, training=True): self.training = training self.policy_net.train(training) self.soft_q_net1.train(training) self.soft_q_net2.train(training) def eval(self): self.policy_net.eval() self.soft_q_net1.eval() self.soft_q_net2.eval() @property def alpha(self): return self.log_alpha.exp() def update(self, args, worker_step, target_entropy=-2): batch_size = args.batch_size reward_scale = args.reward_scale auto_entropy = args.AUTO_ENTROPY gamma = args.gamma soft_tau = args.soft_tau device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") if worker_step < args.model_train_start_step and args.use_prev_policy is False: transition = self.replay_buffer.get_batch(batch_size) network_state = np.concatenate([transition["position_error_obs"], transition["velocity_error_obs"], transition["rotation_obs"], transition["angular_velocity_error_obs"]], axis=1) next_network_state = np.concatenate([transition["position_error_next_obs"], transition["velocity_error_next_obs"], transition["rotation_next_obs"], transition["angular_velocity_error_next_obs"]], axis=1) random_network_state = np.random.normal(network_state, self.eps_p) reward = transition["reward"] done = transition["done"] action = transition["action"] network_state = torch.FloatTensor(network_state).to(device) next_network_state = torch.FloatTensor(next_network_state).to(device) random_network_state = torch.FloatTensor(random_network_state).to(device) action = torch.FloatTensor(action).to(device) reward = torch.FloatTensor(reward).to(device) done = torch.FloatTensor(np.float32(done)).to(device) predicted_q_value1 = self.soft_q_net1(network_state, action) predicted_q_value2 = self.soft_q_net2(network_state, action) new_action, log_prob, z, mean, log_std = self.policy_net.evaluate(network_state) new_next_action, next_log_prob, _, _, _ = self.policy_net.evaluate(next_network_state) new_random_action, _, _, _, _ = self.policy_net.evaluate(random_network_state) # reward = reward_scale * (reward - reward.mean(dim=0)) / (reward.std(dim=0) + 1e-6) # normalize with batch mean and std; plus a small number to prevent numerical problem # Training Q Function target_q_min = torch.min(self.target_soft_q_net1(next_network_state, new_next_action), self.target_soft_q_net2(next_network_state, new_next_action)) - self.alpha.detach() * next_log_prob target_q_value = reward + (1 - done) * gamma * target_q_min # if done==1, only reward q_value_loss1 = self.soft_q_criterion1(predicted_q_value1, target_q_value.detach()) # detach: no gradients for the variable q_value_loss2 = self.soft_q_criterion2(predicted_q_value2, target_q_value.detach()) q_loss = 0.5 * q_value_loss1 + 0.5 * q_value_loss2 self.soft_q_optimizer.zero_grad() q_loss.backward() self.soft_q_optimizer.step() # Training Policy Function predicted_new_q_value = torch.min(self.soft_q_net1(network_state, new_action, detach_encoder=True), self.soft_q_net2(network_state, new_action, detach_encoder=True)) policy_loss = (self.alpha.detach() * log_prob - predicted_new_q_value).mean() policy_loss_t = torch.norm(new_action - new_next_action, dim=1).mean() policy_loss_s = torch.norm(new_action - new_random_action, dim=1).mean() policy_loss += self.lambda_t * policy_loss_t policy_loss += self.lambda_s * policy_loss_s self.policy_optimizer.zero_grad() policy_loss.backward() self.policy_optimizer.step() # print('q loss: ', q_value_loss1, q_value_loss2) # print('policy loss: ', policy_loss ) # Training alpha wrt entropy # alpha = 0.0 # trade-off between exploration (max entropy) and exploitation (max Q) if auto_entropy is True: alpha_loss = (-self.alpha * (log_prob + target_entropy).detach()).mean() # print('alpha loss: ',alpha_loss) self.alpha_optimizer.zero_grad() alpha_loss.backward() self.alpha_optimizer.step() # Soft update the target value net for target_param, param in zip(self.target_soft_q_net1.parameters(), self.soft_q_net1.parameters()): target_param.data.copy_( # copy data value into target parameters target_param.data * (1.0 - soft_tau) + param.data * soft_tau ) for target_param, param in zip(self.target_soft_q_net2.parameters(), self.soft_q_net2.parameters()): target_param.data.copy_( # copy data value into target parameters target_param.data * (1.0 - soft_tau) + param.data * soft_tau ) return predicted_new_q_value.mean() # Training model network else: if args.develop_mode == "imn": transition = self.replay_buffer.get_batch(64) self.inv_model_net.trains() network_state, prev_network_action, next_network_state = get_model_net_input(self.env, transition, ver=args.develop_version) action = transition["action"] network_state = torch.FloatTensor(network_state).to(device) prev_network_action = torch.FloatTensor(prev_network_action).to(device) next_network_state = torch.FloatTensor(next_network_state).to(device) action = torch.FloatTensor(action).to(device) action_hat = self.inv_model_net(network_state, prev_network_action, next_network_state) def get_kl_weight(epoch): if args.use_prev_policy is True: return min(1, args.reg_weight * epoch / args.model_train_start_step) else: return min(1, args.reg_weight * (epoch - args.model_train_start_step) / args.model_train_start_step) if args.use_prev_policy is True or (args.net_type == "bnn" and worker_step > args.model_train_start_step): model_loss = self.imn_criterion(action_hat, action, 1, get_kl_weight(worker_step)).mean() else: model_loss = F.smooth_l1_loss(action, action_hat).mean() self.imn_optimizer.zero_grad() model_loss.backward() self.imn_optimizer.step() else: return class ValueNetwork(nn.Module): def __init__(self, state_dim, hidden_dim, encoder_feature_dim=50, init_w=3e-3): super(ValueNetwork, self).__init__() self.linear1 = nn.Linear(state_dim, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, 1) # weights initialization # self.linear3.weight.data.uniform_(-init_w, init_w) # self.linear3.bias.data.uniform_(-init_w, init_w) # torch.nn.init.xavier_uniform(self.linear1.weight) # torch.nn.init.xavier_uniform(self.linear2.weight) # torch.nn.init.xavier_uniform(self.linear3.weight) torch.nn.init.kaiming_uniform_(self.linear1.weight, nonlinearity='relu') torch.nn.init.kaiming_uniform_(self.linear2.weight, nonlinearity='relu') torch.nn.init.kaiming_uniform_(self.linear3.weight, nonlinearity='relu') def forward(self, state, detach_encoder=False): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x class SoftQNetwork(nn.Module): def __init__(self, num_inputs, num_actions, hidden_size, encoder_feature_dim=50, init_w=3e-3): super(SoftQNetwork, self).__init__() self.linear1 = nn.Linear(num_inputs+num_actions, hidden_size) self.linear2 = nn.Linear(hidden_size, hidden_size) self.linear3 = nn.Linear(hidden_size, 1) # self.linear3.weight.data.uniform_(-init_w, init_w) # self.linear3.bias.data.uniform_(-init_w, init_w) # torch.nn.init.xavier_uniform(self.linear1.weight) # torch.nn.init.xavier_uniform(self.linear2.weight) # torch.nn.init.xavier_uniform(self.linear3.weight) torch.nn.init.kaiming_uniform_(self.linear1.weight, nonlinearity='relu') torch.nn.init.kaiming_uniform_(self.linear2.weight, nonlinearity='relu') torch.nn.init.kaiming_uniform_(self.linear3.weight, nonlinearity='relu') def forward(self, state, action, detach_encoder=False): x = torch.cat([state, action], 1) # the dim 0 is number of samples x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x class PolicyNetwork(nn.Module): def __init__(self, num_inputs, num_actions, hidden_size, action_range=1., encoder_feature_dim=50, init_w=3e-3, log_std_min=-20, log_std_max=2): super(PolicyNetwork, self).__init__() self.log_std_min = log_std_min self.log_std_max = log_std_max self.linear1 = nn.Linear(num_inputs, hidden_size) self.linear2 = nn.Linear(hidden_size, hidden_size) self.linear1.bias.data.zero_() self.linear2.bias.data.zero_() self.mean_linear = nn.Linear(hidden_size, num_actions) # self.mean_linear.weight.data.uniform_(-init_w, init_w) # self.mean_linear.bias.data.uniform_(-init_w, init_w) # self.mean_linear.bias.data.zero_() self.log_std_linear = nn.Linear(hidden_size, num_actions) # self.log_std_linear.weight.data.uniform_(-init_w, init_w) # self.log_std_linear.bias.data.uniform_(-init_w, init_w) # self.log_std_linear.bias.data.zero_() # torch.nn.init.xavier_uniform(self.linear1.weight) # torch.nn.init.xavier_uniform(self.linear2.weight) # torch.nn.init.xavier_uniform(self.mean_linear.weight) # torch.nn.init.xavier_uniform(self.log_std_linear.weight) torch.nn.init.kaiming_uniform_(self.linear1.weight, nonlinearity='relu') torch.nn.init.kaiming_uniform_(self.linear2.weight, nonlinearity='relu') torch.nn.init.kaiming_uniform_(self.mean_linear.weight, nonlinearity='relu') torch.nn.init.kaiming_uniform_(self.log_std_linear.weight, nonlinearity='relu') self.action_range = action_range self.num_actions = num_actions def forward(self, state, detach_encoder=False): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) mean = (self.mean_linear(x)) # mean = F.leaky_relu(self.mean_linear(x)) log_std = self.log_std_linear(x) log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max) return mean, log_std def evaluate(self, state, epsilon=1e-6): ''' generate sampled action with state as input wrt the policy network; ''' device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") mean, log_std = self.forward(state, detach_encoder=True) std = log_std.exp() # no clip in evaluation, clip affects gradients flow normal = Normal(0, 1) z = normal.sample(mean.shape) action_0 = torch.tanh(mean + std * z.to(device)) # TanhNormal distribution as actions; reparameterization trick action = self.action_range * action_0 log_prob = Normal(mean, std).log_prob(mean + std * z.to(device)) - torch.log( 1. - action_0.pow(2) + epsilon) - np.log(self.action_range) # both dims of normal.log_prob and -log(1-a**2) are (N,dim_of_action); # the Normal.log_prob outputs the same dim of input features instead of 1 dim probability, # needs sum up across the features dim to get 1 dim prob; or else use Multivariate Normal. log_prob = log_prob.sum(dim=1, keepdim=True) return action, log_prob, z, mean, log_std def get_action(self, state, deterministic): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") state = torch.FloatTensor(state).unsqueeze(0).to(device) mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(0, 1) z = normal.sample(mean.shape).to(device) action = self.action_range * torch.tanh(mean + std * z) action = self.action_range * torch.tanh(mean).detach().cpu().numpy()[0] if deterministic else \ action.detach().cpu().numpy()[0] return action def random_action(self, ): a = torch.FloatTensor(self.num_actions).uniform_(-1, 1) return self.action_range * a.numpy()
import setupEncryptionKey = require("viewmodels/resources/setupEncryptionKey"); import jsonUtil = require("common/jsonUtil"); class encryptionSettings { private encryptedDatabase = ko.observable<boolean>(); private backupType: KnockoutObservable<Raven.Client.Documents.Operations.Backups.BackupType>; encryptionSection: setupEncryptionKey; enabled = ko.observable<boolean>(false); mode = ko.observable<Raven.Client.Documents.Operations.Backups.EncryptionMode>(); originalKey = ko.observable<string>(); // current key of an existing encrypted backup key = ko.observable<string>(); // the new key that is selected in UI changeKeyRequest = ko.observable<boolean>(false); keyConfirmation = ko.observable<boolean>(false); allowUnencryptedBackupForEncryptedDatabase = ko.observable<boolean>(false); canProvideOwnKey: KnockoutComputed<boolean>; canUseDatabaseKey: KnockoutComputed<boolean>; showKeySourceDropdown: KnockoutComputed<boolean>; enableKeySourceDropdown: KnockoutComputed<boolean>; keySourceDropdownTitle: KnockoutComputed<string>; showOriginalKeySection: KnockoutComputed<boolean>; showProvidedKeySection: KnockoutComputed<boolean>; needExplicitConsent = ko.pureComputed(() => !this.enabled() && this.encryptedDatabase()); dirtyFlag: () => DirtyFlag; encryptionModes: Array<valueAndLabelItem<Raven.Client.Documents.Operations.Backups.EncryptionMode, string>> = [ { label: "Encrypt using Database Encryption Key", value: "UseDatabaseKey" }, { label: "Provide your own Encryption Key", value: "UseProvidedKey" } ]; validationGroup: KnockoutComputed<KnockoutValidationGroup>; validationGroupWithKey: KnockoutValidationGroup; validationGroupWithoutKey: KnockoutValidationGroup; constructor(private databaseName: KnockoutObservable<string>, encryptedDatabase: boolean, backupType: KnockoutObservable<Raven.Client.Documents.Operations.Backups.BackupType>, dto: Raven.Client.Documents.Operations.Backups.BackupEncryptionSettings, private isServerWideBackupTask: boolean = false) { this.encryptedDatabase(encryptedDatabase); this.backupType = backupType; // 'originalKey' will hold current key used by the backup (if exists) // 'key' will hold a new key when generated from the UI this.originalKey(dto && dto.EncryptionMode !== 'None' ? dto.Key : undefined); if (!dto) { if (encryptedDatabase) { // new one or wasn't set in the client API this.enabled(encryptedDatabase); this.mode("UseDatabaseKey"); } } else if (dto.EncryptionMode) { this.mode(dto.EncryptionMode); if (dto.EncryptionMode === "None") { // it was already confirmed this.allowUnencryptedBackupForEncryptedDatabase(true); } else { this.enabled(true); } } else { this.mode(backupType() === "Backup" ? "UseProvidedKey": "UseDatabaseKey"); } this.initObservables(); this.dirtyFlag = new ko.DirtyFlag([ this.enabled, this.mode, this.allowUnencryptedBackupForEncryptedDatabase, this.changeKeyRequest ], false, jsonUtil.newLineNormalizingHashFunction); _.bindAll(this, "setEncryptionType"); } private initObservables() { this.validationGroup = ko.pureComputed(() => { if (this.enabled() && this.mode() === 'UseDatabaseKey') { return this.validationGroupWithoutKey; } return this.enabled() ? this.validationGroupWithKey : this.validationGroupWithoutKey; }); setupEncryptionKey.setupKeyValidation(this.key); this.backupType.subscribe(() => { const dbIsEncrypted = this.encryptedDatabase(); if (dbIsEncrypted) { if (this.backupType() === "Snapshot") { this.mode("UseDatabaseKey"); } } else { // db not encrypted if (this.backupType() === "Backup" && this.enabled()) { this.mode("UseProvidedKey"); if (!this.originalKey()) { return this.encryptionSection.generateEncryptionKey(); } } } }); this.mode.subscribe(mode => { if (this.encryptedDatabase() && mode === 'UseDatabaseKey') { this.changeKeyRequest(false); // imho - better to clear this checkbox } if (this.encryptedDatabase() && mode === 'UseProvidedKey' && !this.key()) { return this.encryptionSection.generateEncryptionKey(); } }); this.key.subscribe(() => { this.encryptionSection.syncQrCode(); this.keyConfirmation(false); }); this.encryptionSection = setupEncryptionKey.forBackup(this.key, this.keyConfirmation, this.databaseName); this.canProvideOwnKey = ko.pureComputed(() => { const type = this.backupType(); const encryptBackup = this.enabled(); return encryptBackup && type === "Backup"; }); this.canUseDatabaseKey = ko.pureComputed(() => { const isDbEncrypted = this.encryptedDatabase(); const encryptBackup = this.enabled(); return isDbEncrypted && encryptBackup; }); this.showKeySourceDropdown = ko.pureComputed(() => { const encryptBackup = this.enabled() && this.enabled.isValid(); const canProvideKey = this.canProvideOwnKey(); const canUseDbKey = this.canUseDatabaseKey(); return encryptBackup && (canProvideKey || canUseDbKey); }); this.keySourceDropdownTitle = ko.pureComputed(() => { if (this.encryptedDatabase()) { return this.enableKeySourceDropdown() ? 'Select Encryption Key mode' : 'The Database Encryption Key will be used when selecting Snapshot type'; } // db is not encrypted and the dropdown is disabled... return 'The database is not encrypted. Provide your own Encryption Key for the Backup task.'; }); this.enableKeySourceDropdown = ko.pureComputed(() => { const canProvideKey = this.canProvideOwnKey(); const canUseDbKey = this.canUseDatabaseKey(); return canProvideKey && canUseDbKey; }); this.showProvidedKeySection = ko.pureComputed(() => { const encryptBackup = this.enabled() && this.enabled.isValid(); const type = this.backupType(); const mode = this.mode(); return encryptBackup && type === "Backup" && mode === "UseProvidedKey" && (!this.originalKey() || (this.originalKey() && this.changeKeyRequest())); }); this.showOriginalKeySection = ko.pureComputed(() => { const canShowOriginalKey = this.enabled() && this.enabled.isValid() && !!this.originalKey() && this.mode() !== 'UseDatabaseKey'; if (this.isServerWideBackupTask) { return canShowOriginalKey && this.backupType() !== "Snapshot"; } return canShowOriginalKey; }); this.allowUnencryptedBackupForEncryptedDatabase.extend({ validation: [{ validator: (v: boolean) => this.needExplicitConsent() ? v : true, message: "Please confirm you want to perform unencrypted backup of encrypted database" }] }); // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; this.enabled.extend({ validation: [{ validator: function() { if (self.enabled() && !self.backupType()) { this.message = "Backup Type was not selected. Select Backup Type to continue."; return false; } const dbIsEncrypted = self.encryptedDatabase(); if (dbIsEncrypted) { if (!self.enabled()) { switch (self.backupType()) { case "Snapshot": this.message = "A 'Snapshot' backup-type was selected. An Unencrypted backup can only be defined for Encrypted databases when a 'Backup' backup-type is selected."; return false; case "Backup": return true; } } } else { if (self.enabled() && self.backupType() === "Snapshot" && !self.isServerWideBackupTask) { this.message = "A 'Snapshot' backup-type was selected. Creating an Encrypted backup for Unencrypted databases is only supported when selecting the 'Backup' backup-type."; return false; } } return true; } }] }); this.enabled.subscribe(enabled => { if (enabled && this.enabled.isValid()) { this.mode("UseProvidedKey"); if (!this.originalKey()) { return this.encryptionSection.generateEncryptionKey(); } } if (!this.enabled()) { this.changeKeyRequest(false); } }); this.changeKeyRequest.subscribe(changeKeyRequest => { if (changeKeyRequest) { return this.encryptionSection.generateEncryptionKey(); } }); const keyConfirmationNeeded = ko.pureComputed(() => this.canProvideOwnKey() && (!this.originalKey() || this.changeKeyRequest()) ); this.key.extend({ required: { onlyIf: () => keyConfirmationNeeded() } }); this.keyConfirmation.extend({ required: { onlyIf: () => keyConfirmationNeeded() } }); setupEncryptionKey.setupConfirmationValidation(this.keyConfirmation, keyConfirmationNeeded); this.validationGroupWithKey = ko.validatedObservable({ enabled: this.enabled, key: this.key, keyConfirmation: this.keyConfirmation, allowUnencryptedBackupForEncryptedDatabase: this.allowUnencryptedBackupForEncryptedDatabase }); this.validationGroupWithoutKey = ko.validatedObservable({ enabled: this.enabled, allowUnencryptedBackupForEncryptedDatabase: this.allowUnencryptedBackupForEncryptedDatabase }); } labelFor(mode: Raven.Client.Documents.Operations.Backups.EncryptionMode) { const matched = this.encryptionModes.find(x => x.value === mode); return matched ? matched.label : null; } setEncryptionType(mode: Raven.Client.Documents.Operations.Backups.EncryptionMode) { this.mode(mode); } setKeyUsedBeforeSave() { // Use 'original key' for 'save' when: // opened existing encrypted backup and didn't request to change key // or if 'key' does exist but asked to change // remember - 'key' has no value if wasn't generated from UI... if (this.originalKey() && (!this.key() || !this.changeKeyRequest())) { this.key(this.originalKey()); // using original this.keyConfirmation(true); // needed for validation } } toDto(): Raven.Client.Documents.Operations.Backups.BackupEncryptionSettings { return { EncryptionMode: this.enabled() ? this.mode() : "None", Key: this.mode() === "UseProvidedKey" ? this.key() : undefined } } } export = encryptionSettings;
 <form id="formCadastro" method="post"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="Nome">Nome:</label> <input required="required" type="text" class="form-control" id="Nome" name="Nome" placeholder="Ex.: João" maxlength="50"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Sobrenome">Sobrenome:</label> <input required="required" type="text" class="form-control" id="Sobrenome" name="Sobrenome" placeholder="Ex.: da Silva" maxlength="255"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="CPF">CPF:</label> <input required="required" type="text" class="form-control" id="CPF" name="CPF" placeholder="Ex.: 010.011.111-00" maxlength="14"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Nacionalidade">Nacionalidade:</label> <input required="required" type="text" class="form-control" id="Nacionalidade" name="Nacionalidade" placeholder="Ex.: brasileira" maxlength="50"> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="CEP">CEP:</label> <input required="required" type="text" class="form-control" id="CEP" name="CEP" placeholder="Ex.: 01011-100" maxlength="9"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="Estado">Estado:</label> <select required="required" id="Estado" class="form-control" name="Estado"> <option value="">Selecione</option> <option value="SP">São Paulo</option> <option value="PE">Pernambuco</option> </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="Cidade">Cidade:</label> <input required="required" type="text" class="form-control" id="Cidade" name="Cidade" maxlength="50" placeholder="Ex.: São Paulo"> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="Logradouro">Logradouro:</label> <input required="required" type="text" class="form-control" id="Logradouro" name="Logradouro" placeholder="Ex.: Rua Boa Vista 253" maxlength="500"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="Email">E-mail:</label> <input required="required" type="text" class="form-control" id="Email" name="Email" placeholder="Ex.: email@email.com" maxlength="2079"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Telefone">Telefone:</label> <input required="required" type="tel" class="form-control" id="Telefone" name="Telefone" placeholder="Ex.: (11) 2020-3030" maxlength="15"> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="pull-right"> <button type="submit" class="btn btn-sm btn-success">Salvar</button> @Html.ActionLink("Voltar", "Index", "Cliente", new { }, new { @class = "btn btn-sm btn-danger" }) </div> <div class="pull-left"> <button type="button" class="btn btn-sm btn-default" data-toggle="modal" data-target="#modalBeneficiario">Beneficiários</button> </div> </div> </div> </form> @if (Model != null) { <div id="data-container" data-items='@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Beneficiarios))'></div> } <!--Modal do beneficiário--> <div class="modal fade" id="modalBeneficiario" tabindex="-1" role="dialog" aria-labelledby="beneficiarioModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header" style="display: flex; justify-content: space-between; align-items: center;"> <h4 class="modal-title" id="titleBenefModalLabel" style="margin: 0;">Beneficiários</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Fechar"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="formBeneficiario"> <div class="row"> <input type="hidden" id="benefId" name="benefId" /> <div class="col-md-5"> <div class="form-group"> <label for="CPF">CPF:</label> <input required="required" type="text" class="form-control" id="benefCPF" name="CPF" placeholder="Ex.: 010.011.111-00" maxlength="14"> </div> </div> <div class="col-md-5"> <div class="form-group"> <label for="Nome">Nome:</label> <input required="required" type="text" class="form-control" id="benefNome" name="Nome" placeholder="Ex.: João" maxlength="50"> </div> </div> <div class="col-md-2"> <div class="form-group"> <button type="submit" class="btn btn-sm btn-success" style="margin-top:24px;">Salvar</button> </div> </div> </div> </form> <div class="row"> <div class="col-md-12"> <div class="form-group"> <table class="table" id="tabelaBeneficiarios"> <thead> <tr> <th>CPF</th> <th>Nome</th> <th></th> </tr> </thead> <tbody> @if (Model != null) { foreach (var beneficiario in Model.Beneficiarios) { <tr id="@beneficiario.Id"> <td>@beneficiario.CPF</td> <td>@beneficiario.Nome</td> <td> <button type="button" class="btn btn-sm btn-primary btn-alterar" value="@beneficiario.Id">Alterar</button> <button type="button" class="btn btn-sm btn-primary btn-excluir" value="@beneficiario.Id">Excluir</button> </td> </tr> } } </tbody> </table> </div> </div> </div> </div> <div class="modal-footer"> <div class="pull-right"> <button type="button" class="btn btn-close" data-dismiss="modal">Fechar</button> </div> </div> </div> </div> </div>
import { zodResolver } from '@hookform/resolvers/zod' import { InputContent } from './styles' import * as z from 'zod' import { useForm } from 'react-hook-form' const searchFormSchemas = z.object({ query: z.string(), }) type SearchFormInput = z.infer<typeof searchFormSchemas> interface InputProps { getPost: (query?: string) => Promise<void> postLength: number } export function Input({ getPost, postLength }: InputProps) { const { register, handleSubmit } = useForm<SearchFormInput>({ resolver: zodResolver(searchFormSchemas), }) async function handleOnSubmit(data: SearchFormInput) { await getPost(data.query) } return ( <InputContent onSubmit={handleSubmit(handleOnSubmit)}> <div> <h2>Publicações</h2> <span>{postLength} publicações</span> </div> <input type="text" placeholder="Buscar conteúdo" {...register('query')} /> </InputContent> ) }
# Datasheet Format ```{note} Prior to June 2024 CACE used the datasheet version 4.0 text format. This format is now deprecated, please export your datasheet in the new YAML format. ``` The CACE datasheet contains the specification of your design and other important information. It acts as both documentation for the specifiaction but also as input for CACE. The following sections describe the structure of the datasheet. ## Metadata Example entry: ```yaml name: ota-5t description: A simple 5 transistor OTA commit: n/a PDK: sky130A cace_format: 5.0 ``` - `name: <string>` > Name of the design (cell name) - `description: <string>` > Description of the design - `commit: <hash-value>` > Commit hash of the repository of this IP - `PDK: <string>` > Name of the PDK (no spaces) - `cace_format: <string>` > Format version of the datasheet. Current version: `5.0`. ## Authorship Example entry: ```yaml authorship: designer: Leo Moser company: Efabless creation_date: May 27, 2024 license: Apache 2.0 ``` - `designer: <name>` > The person to whom the design is attributed. - `company: <name>` > The name of a company, if applicable. This is generally for reference and may be replaced by "institution" or other key. - `creation_date: <datestamp>` > Date that the CACE setup was made, or any meaningful date for the creation of the design. - `modification_date: <datestamp>` > Generally handled by the tools to specify when the characterization file was last updated. - `license: <string>` > A known license type, such as "Apache 2.0". ## Paths The paths section is used to tell CACE where to find certain files of your design or where to generate files for simulation. Example entry: ```yaml paths: root: .. documentation: doc schematic: xschem layout: gds netlist: netlist testbench: cace simulation: ngspice plots: plots logs: ngspice/log reports: reports ``` - `documentation: <path>` > Location of any documentation for the design. - `schematic: <path>` > Location of any schematics (xschem) and symbols for the design. - `verilog: <path>` > Location of any structural verilog used in the design. - `magic: <path>` > Location of any layout in magic (.mag) format. - `layout: <path>` > Location of any layout in GDS (.gds or .gds.gz) format. - `netlist: <path>` > Location of all SPICE netlists. This netlist is usually automatically generated by cace_regenerate.py, with subdirectories for each netlist type according to the netlist source (see "-source" option): "schematic", "layout" (for LVS), "pex" (C-parasitic extracted layout), and "rcx" (R-C-parasitic extracted layout). - `testbench: <path>` > Location of schematics and/or netlists used by the CACE system for running characterization simulations. - `simulation: <path>` > Location of files used for simulation (e.g., netlists created by CACE through variable substitution into the testbench templates) and simulation results. - `reports: <path>` > Reports and log files generated by CACE. - `root: <path>` > This is the location of the project and the root of all the other paths in this dictionary. It is automatically inserted by CACE. ## Dependencies Each entry is a project on which the design under test is dependent. Example entry: ```yaml dependencies: sky130_ef_ip__samplehold: path: .. repository: https://github.com/RTimothyEdwards/sky130_ef_ip__samplehold commit: N/A ... ``` - `key: <string>` > Name of the dependency - `path: <path>` > Path to the dependency (may be relative or absolute, but preferably relative for portability). - `repository: <url>` > Location of the project repository of the dependency, so that if the dependency does not exist, it can be cloned into the target path on demand. - `commit: <hash>` > Commit hash of the repository of the dependency to use in this project. TBD: Various values that define actions such as updating the repository. ## Pins The pins of the design, mainly used for documentation purposes. The names of the pins are checked against the schematic. Example entry: ```yaml pins: VDD: description: Power supply direction: inout type: power Vmin: 1.7 Vmax: 1.9 ... ``` - `name: <string>` > The pin name. Must match the name on the schematic or netlist. Vectors should be indexed with ":" and will be expanded when needed. "b7:0" expands to "b7, b6, b5, ..." while "b[7:0]" expands to "b[7], b[6], b[5], ..." (Note that this is more flexible than the convention for condition names described below.) - `description: <string>` > Text description of the pin. May contain spaces. - `type: <string>` > The type may be one of "digital", "signal", "power", or "ground". - `direction: <string>` > The direction may be one of "input", "output", or "inout". - `Vmin: <number>|<expression>` > The pin minimum voltage may be a value or may be referenced to another pin; and may be referenced to another pin with an offset (e.g., "vss - 0.3"). - `Vmax: <number>|<expression>` > The pin minimum voltage may be a value or may be referenced to another pin; and may be referenced to another pin with an offset (e.g., "vdd + 0.3"). ## Default Conditions The default conditions under which to evaluate the parameters. Example entry: ```yaml default_conditions: corner: display: Corner description: The corner of the wafer typical: tt unit: V ... ``` - `name: <string>` > The name of the condition; this name is meaningful because it will match a variable name used in a schematic or netlist. The representation in the netlist is always ${<string>} to prevent accidental substitutions of matching strings. Any set of signals can be bundled, but the delimiters for the bundle must be brackets; e.g., b[7:0], with single bits called out as, e.g., b[0]. - `description: <string>` > A description of the condition. - `display: <string>` > A short, typically one-word value to display for the condition in a datasheet or GUI. - `unit: <string>` > The unit of measure used to display the condition value. - `typical: <value>` > If present, the default typical value of the condition. - `maximum: <value>` > If present, the default maximum value of the condition. - `minimum: <value>` > If present, the default minimum value of the condition. - `enumerate: <values>` > If present, instead of min/typ/max values, the values are enumerated from a space-separated list supplied in <values> (see above; long lists may be backslash-newline terminated). - `step: linear|logarithmic` > If not present, then only values min/typ/max are evaluated. If present, then values are automatically enumerated from min to max inclusive either in linear (default) or logarithmic progression. If typ exists and is not in the enumeration, then it is evaluated in addition. - `stepsize: <value>` > If not present, then a stepsize of 1 is assumed for linear enumeration or 2 for logarithmic enumeration. Otherwise, the enumeration steps by <value> additive values for linear enumeration or <value> multiplicative values for logarithmic enumeration. ## Electrical Parameters Example entry: ```yaml electrical_parameters: A0: description: DC gain display: A0 unit: V/V spec: minimum: value: '3' fail: true typical: value: any maximum: value: any simulate: ngspice: template: ota-5t_tb.spice format: ascii suffix: .data variables: [result, 'null', 'null'] conditions: vdd: typical: '1.8' vcm: typical: '0.9' corner: enumerate: [tt, ff, ss] ``` - `name: <string>` > A name for the electrical parameter (used only for bookkeeping purposes). - `description: <string>` > A description of the electrical parameter (may contain spaces) - `display: <string>` > A short description to display for the electrical parameter on a datasheet or GUI. - `unit: <string>` > The unit measurement of the electrical parameter result value. Same format as "unit" for conditions. - `spec: <dictionary>` > The target specification for the electrical parameter (see below). - `results: <list>` > The results corresponding to the spec, with dictionary entries similar to "spec". It is a list because specs may be measured at the schematic stage of design, layout for LVS, or layout with parasitics (see "results" dictionary definition, below). - `simulate: <list>` > How to collect data for measurement. Normally this list is a single item, as there is only one way to simulate a parameter. However, cosimulations or other complex setups may require additional entries. Each entry in the list is a tool or script to be run to produce simulation results. - `measure: <list>` > How to measure the electrical parameter or collect data for measurement. Each entry in the list is a tool or script to be run in sequence (see "measure" dictionary definiton, below). - `conditions: <dictionary>` > All the conditions to be applied to the measurement of the electrical parameter that are considered to be fixed with respect to the electrical parameter result (see "variables" below). - `variables: <list>` > Enumerates the variables that are enumerated within the simulation and output but which are not conditions (e.g., time). The 'result' variable (the one representing the electrical parameter) is already specified in the parameter and does not need to be in the 'variables' list. - `plot: <dictionary>` > Describes how to make a data plot for the electrical parameter (where result is plotted rather than generating a single set of min/typ/max values). Requires a corresponding "variables" list. ### Conditions Example entry: ```yaml conditions: vdd: typical: '1.8' vcm: typical: '0.9' corner: enumerate: [tt, ff, ss] ``` The "conditions" dictionary entries are the same as the "default_conditions" dictionary, above. The "default_conditions" dictionary is applied to every condition before adding or overwriting with the specific conditions listed for the electrical parameter. Conditions are only meaningful when the condition name exists in the netlist to be simulated or the file to be evaluated (see "simulate" and "measure" entries). ### Specification Example entry: ```yaml spec: minimum: value: '3' fail: true typical: value: any maximum: value: any ``` - ```yaml minimum: value: <value>|any fail: <bool> measurement: [<calculation>-<limit>] ``` > Specifies the target value for the electrical parameter minimum value. If not specified, then no minimum is measured. If "any" is given as the value, then the minimum is measured but there is no target value. By default, the electrical parameter is marked as failing if the measured value is out of spec. By setting `fail: false`, it is not checked agains the limit. If <calculation>-<limit> is specified, then it overrides the default calculation of "minimum-above" - ```yaml typical: value: <value>|any fail: <bool> measurement: [<calculation>-<limit>] ``` > Specifies the target value for the electrical parameter typical value. If not specified, then no typical is measured. If "any" is given as the value, then the typical is measured but there is no target value. If "fail" is also specified as "true", then electrical parameter is marked as failing if the measured value is out of spec (failing on a typical value is rarely if ever used). If <calculation>-<limit> is specified, then it overrides the default calculation of "average-exact" - ```yaml maximum: value: <value>|any fail: <bool> measurement: [<calculation>-<limit>] ``` > Specifies the target value for the electrical parameter maximum value. If not specified, then no maximum is measured. If "any" is given as the value, then the maximum is measured but there is no target value. If "fail" is also specified as "true", then electrical parameter is marked as failing if the measured value is out of spec. If <calculation>-<limit> is specified, then it overrides the default calculation of "maximum-below" ### Simulate Currently, only ngspice is supported as simulator, therefore the dictionary key has to be ngspice. Example entry: ```yaml simulate: ngspice: template: ota-5t_tb.spice format: ascii suffix: .data variables: [result, 'null', 'null'] ``` - `template: <string>` > This specifies the name of the file that is used as the template for simulation. The conditions for the specific measurement are determined, and the condition values are variable-substituted in the template, and then the resulting set of files is passed to the tool. - `format: <string>` > This specifies the format of the simulation output. Currently, only "ascii" is supported (however, "raw" for SPICE raw files will be supported in the future, and "vcd" files that may be produced from verilog cosimulation). - `suffix: <string>` > suffix is the filename suffix of the output file, which must have the same root name as the file passed to the tool. (For example if template is "ota-5t\_tb.spice" and suffix ".data", then CACE expects "ota-5t\_tb.data" to be created during simulation.) The format line informs CACE how to merge results from multiple simulation runs for the same electrical parameter by describing the format of the tool's output file and its contents. - `variables: <list>` > variables is a list consisting of one of "result", "time" or "null". "result" is the value that will be used for comparison against the spec. "time" is a time value that may be used for plotting. "null" for any value that is not evaluated, or any condition or variable name. If any condition name appears in the format string, then there must be enough lines of output in the file to match the number of conditions simulated. This is used for sweeps and plots. - `collate: <condition>` > This specifies that the simulation output should be collated from runs over all the specified conditions before passing the result to the first "measure" handler. ### Variables Example entry: ```yaml variables: time: display: Time unit: ms Vinp: display: Vinp unit: V result: display: Vout unit: V ``` A variable is any property that affects the electrical parameter result but which is not a condition. A variable may be used in a plot to graph the result vs. something that is not a condition. Otherwise, all variables must be eliminated during the course of evaluation. Note: Use of "collate" in a "simulate" dictionary will force any condition in the collated list to become a variable, as if it were produced by the simulation instead of being passed to it. - `name: <string>` > The name is a placeholder for bookkeeping, except for string "result" which indicates that the condition in this dictionary is the result vector to be plotted. - `display: <string>` > This value is text to display on the graph, which may appear in a key if the value is not for data corresponding to the graph X or Y axis. - `unit: <value>` > This is the unit that will be displayed after the display string. ### Plots Example entry: ```yaml plot: filename: transient.png xaxis: time yaxis: result ``` - `filename: <string>` Name of a graphic format and filename to use for graph output. Plots are done with python matplotlib, so it must be a format known to matplotlib. - `type: <string>` The type of plot to make. If this record is missing from the dictionary, then plot type "xyplot" is assumed by default. Otherwise, the value should be one of "xyplot", "histogram", "semilogx", "semilogy", or "loglog". - `xaxis: <name>` Condition to be plotted on the graph X axis, as determined from the condition related to <name> in the "variables" section. The X-axis label is taken from the variable entry as well. - `yaxis: <name>` Condition to be plotted on the graph Y axis, as determined from the condition related to <name> in the "variables" section. The Y-axis label is taken from the variable entry as well. - `title: <string>` A title for the graph. Plots are made from measured columnar data which may be from a "wrdata" command in ngspice, an "echo" statement directed to a file, or a raw file; regardless, each column will be either a condition or a result. Conditions produced by plot-generating tools may contain vectors not in the listed conditions for the electrical parameter, such as TIME for time or TRACE for the result. ### Measure "measure" dictionary: ```yaml measure: - tool: octave filename: dnl.m ``` Additional entries are tools that operate on the output of the simulator to produce the final results for the datasheet. They may be number-crunching tools like "octave" for compute- intensive evaluations, or they may be a script like python (using numpy or scipy) or bash. The purpose of "measure" is to modify the result produced by the simulation, including removing variables from the result list. - `calc: <string>` > This specifies an internal calculation understood by CACE to apply to the testbench result (see "caculations", below). - `tool: <string>` > This specifies an external tool to use to make the measurement, typically octave. It must also specify a filename of a script to run (see below). - `filename: <string>` > The filename is the name of a script to pass to the tool given as the value to the "tool" keyword (e.g., a ".m" script to pass to octave). The script must accept one argument, which is a filename consisting of the parameter name followed by ".dat". It is a list of all results and the set of conditions for each. Currently, ".dat" is in octave format, but should support JSON format for python scripts. The output of the "evaluate" tool is a single list of results that replaces (in order) the result list passed to the tool. Currently, the output is passed in stdout, and is a list of "result" values that replaces the existing "result" values in the testbench. Internal calculation (measurement) methods: > time: remove: rebase: abs: negate: add: subtract: multiply: clip: mean: risingedge: fallingedge: stabletime: inside: ## Physical Parameters Example entry: ```yaml physical_parameters: area: description: Total circuit layout area display: Area unit: µm² spec: maximum: value: '100' fail: true evaluate: cace_area ``` The physical parameters list has the same keywords as the electrical parameters, except that the parameters are physical measurements of the layout such as area, width, height, max metal layer, and may include number of DRC or LVS errors. Dictionary keys that are shared with "electrical_parameters" are: name, status, description, display, unit, and spec. The "evaluate" dictionary is unique to physical parameters and takes the place of "simulate" and "measure" for electrical parameters (see below). Internal physical parameter (evaluation) tools: - `cace_drc`: > Returns the number of DRC errors found in the design. The result is generally useful only as being zero or non-zero. - `cace_lvs`: > Returns the number of LVS errors found in the design. The result is generally useful only as being zero or non-zero. - `cace_area`: > Returns the area of the layout. - `cace_width`: > Returns the width of the layout. - `cace_length`: >Returns the length of the layout. ### Evaluate Example entry: ```yaml evaluate: cace_area ``` The "evaluate" dictionary is unique to the physical_parameters dictionaries. It describes how to obtain a specific physical or other non-electrical parameter, such as cell size or number of DRC or LVS errors. Running the tool must produce a single value as output, which is then checked against the spec to provide a pass/fail result. - `tool: <string>` > The name of a tool to use for the evaluation. This may be an internal procedure known to CACE (see list below). If not, then it must be a standard application or interpreter (such as python). The filename (see below) is passed to the tool as the argument. Any options to pass to the tool should be included in the string. - `filename: <name>` > The name of a script or filename to pass to the tool specified by "tool", if the tool is not an internal procedure. The file <name> should exist in the testbench directory.
package org.example; public class PilhaObj<T> { private int topo; private T[] itens; public PilhaObj(int tamanho) { topo = -1; itens = (T[]) new Object[tamanho]; } public void push(T elemento) { if(topo == itens.length - 1) { throw new RuntimeException("Pilha cheia"); } topo++; itens[topo] = elemento; } public T pop() { if(topo == -1) { throw new RuntimeException("Pilha vazia"); } T elemento = itens[topo]; topo--; return elemento; } public boolean isEmpty() { return (topo == -1); } public boolean isFull() { return (topo == itens.length - 1); } public int size() { return (topo + 1); } public void inverterFrase(String frase){ PilhaObj<Character> pilha = new PilhaObj<>(frase.length()); for(int i = 0; i < frase.length(); i++) { char c = frase.charAt(i); pilha.push(c); } System.out.print("\nFrase invertida: "); while(!pilha.isEmpty()) { System.out.print(pilha.pop()); } } public void analisaCaractere(String frase){ PilhaObj<Character> pilha = new PilhaObj<>(frase.length()); for(int i = 0; i < frase.length(); i++) { char c = frase.charAt(i); if(Character.isLetterOrDigit(c)) { pilha.push(Character.toLowerCase(c)); } } boolean palindromo = true; int i = 0; while(palindromo && !pilha.isEmpty()) { char c = pilha.pop(); char c2 = Character.toLowerCase(frase.charAt(i)); if(Character.isLetterOrDigit(c2)) { palindromo = (c == c2); } i++; } if(palindromo) { System.out.println("\nÉ palíndroma"); } else { System.out.println("\nNão é palíndroma"); } } }
import 'package:effective_mobile_test/core/resources/app_colors.dart'; import 'package:effective_mobile_test/core/resources/app_fonts.dart'; import 'package:flutter/material.dart'; class MainButton extends StatelessWidget { final Function()? onPressed; final String title; final Color color; const MainButton({ super.key, this.onPressed, required this.title, required this.color, }); @override Widget build(BuildContext context) { return SizedBox( height: 42, width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), backgroundColor: color, ), onPressed: onPressed, child: Text( title, style: AppFonts.s16w600.copyWith( color: AppColors.white, ), ), ), ); } }
import { AbuseIPDBClient } from 'abuseipdb-client'; import type { CheckBlockOptions } from 'abuseipdb-client'; const client = new AbuseIPDBClient('API_KEY'); // AbuseIPDB Docs: https://docs.abuseipdb.com/#check-block-endpoint try { // Options can be omitted, as the API has default values for every field. const options: CheckBlockOptions = { maxAgeInDays: 1, }; // Must be an IPv4/IPv6 CIDR. const network = '192.168.0.0/24'; const { headers, error, result } = await client.checkBlock(network, options); console.log(headers); if (error) { console.log(error); } if (result) { console.log(result); } } catch (err) { console.log(err); }
<script setup lang="ts"> import { ref } from 'vue'; import axios from 'axios'; const emit = defineEmits(['close-usersign', 'open-otpverify', 'open-otprecover']); const usernameEmail = ref(''); const passwordLogin = ref(''); const username = ref(''); const email = ref(''); const passwordSignUp = ref(''); const rePasswordSignUp = ref(''); const emailRegex = /^[^\s@]+@(?:collegeofidaho\.edu|[a-z]+\.collegeofidaho\.edu)$/i; const loginUser = async () => { if (!usernameEmail.value || !passwordLogin.value) { alert('Please fill in all fields'); return; } const formData = new FormData(); const { value: usernameEmailValue } = usernameEmail; if (emailRegex.test(usernameEmailValue)) { formData.append('email', usernameEmailValue); } else { formData.append('username', usernameEmailValue); } formData.append('password', passwordLogin.value); try { const response = await axios.post('/api/login', formData, { headers: { 'Content-Type': 'application/json', }, withCredentials: true, }); if (response.status === 200) { localStorage.setItem('username', response.data.user.username); localStorage.setItem('userImg', response.data.user.img); localStorage.setItem('userId', response.data.user.id); localStorage.setItem('userEmail', response.data.user.email); localStorage.setItem('lastActive', Date.now().toString()); location.reload(); } else { alert(response.data.message); } } catch (error) { if ((error as any).response.status === 400) { alert((error as any).response.data.message); } else { alert('Login failed'); //console.error('Login failed:', error); } } }; const requestOTP = async () => { if (!username.value || !email.value || !passwordSignUp.value || !rePasswordSignUp.value) { alert('Please fill in all fields'); return; } if (username.value.length < 6 || username.value.length > 12) { alert('Username must be at least 6 characters and a maximum of 12 characters'); return; } if (username.value.includes('admin') || username.value.includes('anonymous')) { alert('Username cannot contain "admin" or "anonymous"'); return; } const letters = username.value.match(/[a-zA-Z]/g); if (!letters || letters.length < 4) { alert('Username must contain at least 4 letters'); return; } if (!emailRegex.test(email.value)) { alert('You must use a College of Idaho email address to sign up.'); return; } const formData = new FormData(); formData.append('username', username.value); formData.append('email', email.value); if (passwordSignUp.value !== rePasswordSignUp.value) { alert('Passwords do not match'); return; } if (rePasswordSignUp.value.length < 6) { alert('Password must be at least 6 characters'); return; } formData.append('password', rePasswordSignUp.value); try { const response = await axios.post('/api/signup', formData, { headers: { 'Content-Type': 'application/json', }, withCredentials: true, }); if (response.status === 200) { emit('open-otpverify', { username: response.data.newUserInfo.username, email: response.data.newUserInfo.email, password: response.data.newUserInfo.password }); } else { alert(response.data.message); } } catch (error) { if ((error as any).response.status === 400) { alert((error as any).response.data.message); } else { alert('OTP request failed'); //console.error('OTP request failed:', error); } } }; </script> <template> <div class="sign-backdrop"> <div class="user-sign-container"> <div class="main"> <input type="checkbox" id="chk" aria-hidden="true"> <div class="login"> <button class="close-btn" @click="$emit('close-usersign')">&#10006;</button> <div class="form-temp"> <label for="chk" aria-hidden="true">Login</label> <input type="text" name="usernameemail" placeholder="Username/Email" autocomplete="off" role="presentation" v-model="usernameEmail" required> <input type="password" name="pswd" placeholder="Password" v-model="passwordLogin" required> <button @click="loginUser">Login</button> <button class="fgpass-btn" @click="$emit('open-otprecover')">Forgot Password?</button> </div> </div> <div class="signup"> <div class="form-temp"> <label for="chk" aria-hidden="true">Sign up</label> <input type="text" name="txt" placeholder="Username" autocomplete="off" role="presentation" v-model="username" required> <input type="email" name="email" placeholder="Email" autocomplete="off" role="presentation" v-model="email" required> <input type="password" name="pswd" placeholder="Password" v-model="passwordSignUp" required> <input type="password" name="re-pswd" placeholder="Re-enter Password" v-model="rePasswordSignUp" required> <button @click="requestOTP">Sign Up</button> </div> </div> </div> </div> </div> </template> <style scoped> @import url('https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,100..900;1,100..900&display=swap'); * { font-family: 'Jost', sans-serif; box-sizing: border-box; } .user-sign-container { margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; } .main{ width: 350px; height: 500px; overflow: hidden; background: rgb(65,4,103); background: radial-gradient(circle, rgba(65,4,103,1) 0%, rgba(101,51,209,1) 0%, rgba(65,4,103,1) 100%); border-radius: 10px; box-shadow: 5px 20px 50px #000; } #chk{ display: none; } .login{ position: relative; width:100%; height: 100%; } label{ color: #fff; font-size: 2.3em; justify-content: center; display: flex; margin: 60px; font-weight: bold; cursor: pointer; transition: .5s ease-in-out; } input{ width: 70%; height: 30px; background: #e0dede; justify-content: center; display: flex; margin: 15px auto; padding: 10px; border: none; outline: none; border-radius: 5px; font-size: 16px; } button{ width: 60%; height: 40px; margin: 10px auto; justify-content: center; display: block; color: #fff; background: #7a4dc7; font-size: 20px; font-weight: bold; margin-top: 20px; outline: none; border: none; border-radius: 5px; transition: .2s ease-in; cursor: pointer; border: 2px solid #ffffff; } button:hover{ background: #54348f; } .fgpass-btn { display: flex; justify-content: center; color: #fff; font-size: 16px; text-align: center; background-color: transparent; border: none; } .fgpass-btn:hover { font-size: 18px; background-color: transparent; } .signup{ height: 460px; background: #eee; border-radius: 60% / 10%; transform: translateY(-180px); transition: .8s ease-in-out; } .signup label{ color: #573b8a; transform: scale(.6); } #chk:checked ~ .signup{ transform: translateY(-500px); } #chk:checked ~ .signup label{ transform: scale(1); } #chk:checked ~ .login label{ transform: scale(.6); } .close-btn { position: absolute; top: -60px; right: 20px; border: none; color: white; cursor: pointer; padding: 5px; font-size: 20px; background-color: rgba(148, 148, 148, 0.5); border-radius: 50%; transition: background-color 0.2s ease-in-out; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; } .close-btn:hover { background-color: rgba(113, 113, 113, 0.5); } @media screen and (max-width: 650px) { .sign-backdrop { width: 20rem; } } </style>
<div class="checkinslist"> <h1>Check-ins</h1> <p>Here's a list of your lastest check-ins</p> <div class="search cf"> <h2>Search Check-ins</h2> <input type="text" ng-model="query" placeholder="Search for users"> <div class="formgroup cf"> <span class="label">by:</span> <select ng-model="order"> <option value="firstname">Firstname</option> <option value="lastname">Lastname</option> <option value="date">Date</option> </select> </div> <div class="formgroup cf"> <input id="dirascending" type="radio" ng-model="direction" name="direction" value=""> <label for="dirascending">asc</label> <input id="dirdescending" type="radio" ng-model="direction" name="direction" value="reverse"> <label for="dirdescending">desc</label> </div> </div> <div class="buttons cf" ng-show="signedIn()"> <button ng-hide="recordId" class="btn btn-pick" ng-click="pickRandom()">Pick Random</button> <button ng-show="recordId" class="btn btn-reset" ng-click="recordId=''">Reset</button> </div> <ul class="userlist cf"> <li ng-class="checkin.userState" ng-repeat="checkin in checkins | orderBy: order: direction | filter: {$id: recordId, $: query}"> <div class="checkin"> <div class="buttons" ng-show="signedIn()"> <button class="btn btn-love tooltip" ng-click="showLove(checkin)"> <span>Show the love</span> </button> </div> <div class="buttons" ng-show="signedIn()"> <button class="btn btn-delete tooltip" ng-click="deleteCheckin(checkin.$id)" confirmation-needed="Sure you want to delete the Checkin?"> <span>Delete this checkin</span> </button> </div> <div class="info"> <h2>{{checkin.firstname}} {{checkin.lastname}}</h2> <div class="date"> {{checkin.date | date: "MMM d, yy h:mm a"}} </div> </div> <div class="showcheckins" ng-show="checkin.show"> <form name="myform" class="cf" ng-submit="giveLove(checkin, checkin.giftText)" novalidate> <input type="text" name="giftText" ng-required="true" ng-model="checkin.giftText" placeholder="What are you giving them ?"> <button type="submit" class="btn" ng-disabled="myform.$invalid">+</button> </form> <ul class="awardslist cf"> <li class="cf" ng-repeat="(key, award) in checkin.awards"> <div clsas="award"> {{award.name}} <div class="buttons" ng-show="signedIn()"> <button class="btn btn-delete tooltip" ng-click="deleteLove(checkin.$id, key)" confirmation-needed="Sure you want to delete the Award?"> <span>Delete this award</span> </button> </div> </div> </li> </ul> </div> </div> </li> </ul> </div>
const { Client, LocalAuth } = require("whatsapp-web.js"); const express = require("express"); const app = express(); const QRCode = require("qrcode"); const qrcode = require("qrcode-terminal"); const { createServer } = require("http"); const { Server } = require("socket.io"); // const makeWitAiRequest = require('./botLogic'); require("dotenv").config(); const httpServer = createServer(app); const io = new Server(httpServer, { cors: { origin: "", methods: ["GET", "POST"], }, }); app.use(express.static("public")); const client = new Client({ authStrategy: new LocalAuth(), executablePath: "/usr/bin/chromium-browser", puppeteer: { args: ["--no-sandbox"], }, webVersionCache: { type: "remote", remotePath: "https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.2412.54.html", }, }); const queryAi = async (message) => { try { const response = await fetch( "http://localhost:50000/api/ai/prompt?prompt=" + message ); const data = await response.json(); return data.message; } catch (error) { console.log(error); } }; client.on("qr", (qr) => { console.log("QR RECEIVED", qr); // Emit the QR code data to the frontend io.emit("qrcode", qr); // Convert QR code to base64 image and emit to the frontend QRCode.toDataURL(qr, (err, url) => { io.emit("qrcode-image", url); }); QRCode.toString(qr, { type: "terminal" }, (err, terminalUrl) => { // console.log(terminalUrl); }); qrcode.generate(qr, { small: true }, (url) => { console.log(url); }); }); client.on("ready", () => { console.log("Client is ready!"); }); client.on("message", async (message) => { let chat = await message.getChat(); const messageBody = message.body; // const sender = message.author.split("@")[0]; const os = message.deviceType; const fromMe = message.fromMe; const quoted = message.hasQuotedMsg; const quotedContent = await message.getQuotedMessage(); // console.log(messageBody, os, fromMe, quoted, quotedContent); if (chat.isGroup) { const messageIsAboutMe = messageBody.startsWith("@[MY_NUMBER]"); // [MY_NUMBER] is an actual number but i dont want to be spamed so i am removing it if (messageIsAboutMe) { chat.sendSeen(); await chat.sendStateTyping(); const response = await queryAi(messageBody); return client.sendMessage(message.from, response); } else { return false; } } chat.sendSeen(); await chat.sendStateTyping(); const response = `You said: ${messageBody}`; setTimeout(() => { client.sendMessage(message.from, response); }, 1000); }); client.initialize(); httpServer.listen(3000, () => { console.log("Server Started"); });
// https://leetcode.com/problems/rotate-array/ // O(n) function rotateArray(nums, k) { const rotatedArray = new Array(nums.length); for(let i=0; i < nums.length; i++) { const newIndex = (i+k) % nums.length; rotatedArray[newIndex] = nums[i]; } for(let i=0; i<nums.length; i++) { nums[i] = rotatedArray[i]; } } const test1 = getTestData(); testResults(rotateArray, test1.test1, test1.test1k, test1.test1Res); testResults(rotateArray, test1.test2, test1.test2k, test1.test2Res); function rotateArrayByReversing(nums, k) { const reverseArray = (start, end) => { while (start < end) { const temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } }; const numberOfRotations = k % nums.length; reverseArray(0, nums.length - 1); reverseArray(0, numberOfRotations - 1); reverseArray(numberOfRotations, nums.length - 1); } const test2 = getTestData(); testResults(rotateArrayByReversing, test2.test1, test2.test1k, test2.test1Res); testResults(rotateArrayByReversing, test2.test2, test2.test2k, test2.test2Res); // Tests function testResults(func, nums, k, expected) { func(nums, k); for(i=0; i<nums.length; i++) { console.log(nums[i] === expected[i]); } } function getTestData() { const test1 = [1,2,3,4,5,6,7] const test1k = 3; const test1Res = [5,6,7,1,2,3,4]; const test2 = [-1,-100,3,99]; const test2k = 2; const test2Res = [3,99,-1,-100]; return { test1, test1k, test1Res, test2, test2k, test2Res, }; }
# HNSCC GSE195832 library(GEOquery) library(readr) library(data.table) library(readxl) library(dplyr) library(IOBR) setwd("/Users/daisys/Library/CloudStorage/OneDrive-MoffittCancerCenter/Moffitt_DaisyS/Data/8_HNSCC/GSE195832") #download the data myGSE<-"GSE195832" #gpl <- getGEO("GPL24676") #head(Table(gpl)) gset <- getGEO(myGSE, GSEMatrix =TRUE, getGPL=FALSE) if (length(gset) > 1) idx <- grep("GPL24676", attr(gset, "names")) else idx <- 1 gset <- gset[[idx]] cli<- pData(gset) write.csv(cli, "GSE195832_pheno.csv") ## counts to TPM expr <- read_tsv("GSE195832_TJU_featurecounts_symbol.tsv.gz") head(expr) expr <- expr[!is.na(expr$symbol),] expr <- expr %>% group_by(symbol) %>% summarise_if(is.numeric, mean) rownames(expr) <- expr$symbol rownames <- row.names(expr) expr <- expr[, -1] rownames(expr) <- rownames expr<-count2tpm(countMat = expr, idType = "symbol", org="hsa", source = "local" ) dim(expr) expr[1:5,1:5] # [1] 49434 56 # add rowname expr<-data.frame(GeneSymbol = rownames(expr), expr, check.names = FALSE) expr[1:5,1:5] ## convert expr_t<-t(expr) expr_t[1:5,1:5] write.table(expr_t, "GSE195832_temp.tsv", sep = "\t", quote = FALSE, row.names = TRUE, col.names = FALSE) expr_tpm <- read_tsv("GSE195832_temp.tsv") expr_tpm[1:3,1:3] cli<-read.csv("metadata_TJcohort.csv") head(cli) colnames(expr_tpm)[1] <- "Sample" # merge merged_data <- merge(cli,expr_tpm,by = "Sample") merged_data[1:3,1:3] dim(merged_data) # [1] 56 49443 write.csv(merged_data, "HNSCC_GSE195832.csv")
<!-- <script setup> import SavePosting from "../components/SavePosting.vue"; import ApplicationDetails from "../components/ApplicationDetails.vue"; const props = defineProps(["localStorageArr"]); </script> <template> <main class="max-w-7xl flex flex-col mx-auto"> <button class="border w-fit mx-auto" @click="showModal = true"> Save Job Posting </button> <SavePosting v-show="showModal" @close-modal="showModal = false" @addJob="addJob" /> <h2>Saved Postings</h2> <div class="border"> <ul> <template v-for="job in localStorageArr" :key="job.id"> <li v-if="job.status === `Saved`" @click="setSelectedJob(job) + setDetailsModalBool()" class="cursor-pointer hover:text-blue-500" > {{ job.company }} {{ job.status }} </li> </template> </ul> </div> <div v-if="showDetailsModal === true"> <ApplicationDetails v-show="showDetailsModal" @close-modal="closeModal" v-bind:job="selectedJob" /> </div> </main> </template> <script> export default { components: { SavePosting, ApplicationDetails }, data() { return { showModal: false, showDetailsModal: false, selectedJob: {}, }; }, methods: { setSelectedJob(job) { this.selectedJob = job; }, setDetailsModalBool() { this.showDetailsModal = true; }, closeModal(updates) { this.showDetailsModal = false; this.$emit("updateJob", updates); }, addJob(job) { this.$emit("addJob", job); }, }, }; </script> --> <template> <div class="px-4 sm:px-6 lg:px-8 mt-8"> <div class="sm:flex sm:items-center"> <div class="sm:flex-auto"> <h1 class="font-semibold text-lg leading-6 text-gray-900"></h1> </div> <div class="sm:ml-16 sm:mt-0 sm:flex-none"> <button type="button" @click="showModal = true" class="block rounded-md bg-indigo-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" > Save Job </button> <div v-if="showModal === true"> <SavePosting v-show="showModal" @close-modal="showModal = false" @addJob="addJob" /> </div> </div> </div> <div class="mt-8 flow-root"> <div class="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div class="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8"> <div v-if=" localStorageArr.filter((job) => job.status === `Saved`).length === 0 " > No saved jobs at this time </div> <table class="min-w-full divide-y divide-gray-300" v-if=" localStorageArr.filter((job) => job.status === `Saved`).length !== 0 " > <thead> <tr> <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-0" > Company </th> <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900" > Job title </th> <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900" > URL </th> <th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-0"> <span class="sr-only">Edit</span> </th> </tr> </thead> <tbody class="divide-y divide-gray-200"> <template v-for="job in localStorageArr" :key="job.id"> <tr v-if="job.status === `Saved`"> <td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-0" > {{ job.company }} </td> <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> {{ job.title }} </td> <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> {{ job.url }} </td> <td class="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-0" > <button class="text-indigo-600 hover:text-indigo-900" @click="setSelectedJob(job) + setDetailsModalBool()" > Edit </button> </td> </tr> </template> </tbody> </table> <div v-if="showDetailsModal === true"> <ApplicationDetails v-show="showDetailsModal" @close-modal="closeModal" v-bind:job="selectedJob" /> </div> </div> </div> </div> </div> </template> <script> import SavePosting from "../components/SavePosting.vue"; import ApplicationDetails from "../components/ApplicationDetails.vue"; export default { props: ["localStorageArr"], components: { SavePosting, ApplicationDetails }, data() { return { showModal: false, showDetailsModal: false, selectedJob: {} }; }, methods: { setSelectedJob(job) { this.selectedJob = job; }, setDetailsModalBool() { this.showDetailsModal = true; }, closeModal(updates) { this.showDetailsModal = false; this.$emit("updateJob", updates); }, addJob(job) { this.$emit("addJob", job); } } }; </script>
//! Module of a unique NFT `Unique` data type. //! //! It acts as a standard domain-specific implementation of an NFT type, //! fitting use cases such as Art and PFP NFT Collections. It uses the main //! NFT module to mint embedded NFTs. module nft_protocol::unique_nft { use sui::event; use sui::object::{Self, UID, ID}; use std::string::{Self, String}; use std::option; use sui::transfer; use sui::tx_context::{TxContext}; use sui::url::{Self, Url}; use nft_protocol::err; use nft_protocol::collection::{Self, MintAuthority}; use nft_protocol::utils::{to_string_vector}; use nft_protocol::supply_policy; use nft_protocol::slingshot::{Self, Slingshot}; use nft_protocol::sale; use nft_protocol::nft::{Self, Nft}; /// An NFT `Unique` data object with standard fields. struct Unique has key, store { id: UID, name: String, description: String, collection_id: ID, url: Url, attributes: Attributes, } struct Attributes has store, drop, copy { keys: vector<String>, values: vector<String>, } struct MintArgs has drop { name: String, description: String, url: Url, attributes: Attributes, } struct MintDataEvent has copy, drop { object_id: ID, collection_id: ID, } struct BurnDataEvent has copy, drop { object_id: ID, collection_id: ID, } // === Functions exposed to Witness Module === /// Mint one embedded `Nft` with `Unique` data and send it to `Launchpad`. /// Invokes `mint_to_launchpad()`. /// Mints an NFT from a `Collection` with unregulated supply. /// The only way to mint the NFT for a collection is to give a reference to /// [`UID`]. One is only allowed to mint `Nft`s for a given collection /// if one is the `MintAuthority` owner. /// /// To be called by the Witness Module deployed by NFT creator. public fun mint_unregulated_nft<T, Market: store>( name: vector<u8>, description: vector<u8>, url: vector<u8>, attribute_keys: vector<vector<u8>>, attribute_values: vector<vector<u8>>, mint: &MintAuthority<T>, sale_index: u64, // TODO: Ideally we do not take a mutable reference such that // no lock is needed launchpad: &mut Slingshot<T, Market>, ctx: &mut TxContext, ) { // Assert that it has an unregulated supply policy assert!( !supply_policy::regulated(collection::supply_policy(mint)), err::supply_policy_mismatch(), ); let args = mint_args( name, description, url, to_string_vector(&mut attribute_keys), to_string_vector(&mut attribute_values), ); mint_to_launchpad( args, collection::mint_collection_id(mint), sale_index, launchpad, ctx, ); } /// Mint one embedded `Nft` with `Unique` data and send it to `Launchpad`. /// Invokes `mint_to_launchpad()`. /// Mints an NFT from a `Collection` with regulated supply. /// The only way to mint the NFT for a collection is to give a reference to /// [`UID`]. One is only allowed to mint `Nft`s for a given collection /// if one is the `MintAuthority` owner. /// /// To be called by the Witness Module deployed by NFT creator. public fun mint_regulated_nft<T, Market: store>( name: vector<u8>, description: vector<u8>, url: vector<u8>, attribute_keys: vector<vector<u8>>, attribute_values: vector<vector<u8>>, mint: &mut MintAuthority<T>, sale_index: u64, launchpad: &mut Slingshot<T, Market>, ctx: &mut TxContext, ) { // Assert that it has regulated supply policy assert!( supply_policy::regulated(collection::supply_policy(mint)), err::supply_policy_mismatch(), ); let args = mint_args( name, description, url, to_string_vector(&mut attribute_keys), to_string_vector(&mut attribute_values), ); collection::increment_supply(mint, 1); mint_to_launchpad( args, collection::mint_collection_id(mint), sale_index, launchpad, ctx, ); } /// Mint one embedded `Nft` with `Unique` data and send it to `recipient`. /// Invokes `mint_and_transfer()`. /// Mints an NFT from a `Collection` with unregulated supply. /// The only way to mint the NFT for a collection is to give a reference to /// [`UID`]. One is only allowed to mint `Nft`s for a given collection /// if one is the `MintAuthority` owner. /// /// To be called by the Witness Module deployed by NFT creator. public fun direct_mint_unregulated_nft<T>( name: vector<u8>, description: vector<u8>, url: vector<u8>, attribute_keys: vector<vector<u8>>, attribute_values: vector<vector<u8>>, mint: &MintAuthority<T>, recipient: address, ctx: &mut TxContext, ) { // Assert that it has an unregulated supply policy assert!( !supply_policy::regulated(collection::supply_policy(mint)), err::supply_policy_mismatch() ); let args = mint_args( name, description, url, to_string_vector(&mut attribute_keys), to_string_vector(&mut attribute_values), ); mint_and_transfer<T>( args, collection::mint_collection_id(mint), recipient, ctx, ); } /// Mint one embedded `Nft` with `Unique` data and send it to `recipient`. /// Invokes `mint_and_transfer()`. /// Mints an NFT from a `Collection` with regulated supply. /// The only way to mint the NFT for a collection is to give a reference to /// [`UID`]. One is only allowed to mint `Nft`s for a given collection /// if one is the `MintAuthority` owner. /// /// To be called by the Witness Module deployed by NFT creator. public fun direct_mint_regulated_nft<T>( name: vector<u8>, description: vector<u8>, url: vector<u8>, attribute_keys: vector<vector<u8>>, attribute_values: vector<vector<u8>>, mint: &mut MintAuthority<T>, recipient: address, ctx: &mut TxContext, ) { // Assert that it has a regulated supply policy assert!( supply_policy::regulated(collection::supply_policy(mint)), err::supply_policy_mismatch(), ); let args = mint_args( name, description, url, to_string_vector(&mut attribute_keys), to_string_vector(&mut attribute_values), ); collection::increment_supply(mint, 1); mint_and_transfer<T>( args, collection::mint_collection_id(mint), recipient, ctx, ); } // === Entrypoints === /// Burns embedded `Nft` along with its `Unique`. It invokes `burn_nft()` public entry fun burn_nft<T>( nft: Nft<T, Unique>, ) { burn_nft_(nft); } // === Getter Functions === /// Get the Nft Unique's `id` public fun id( nft_data: &Unique, ): ID { *object::uid_as_inner(&nft_data.id) } /// Get the Nft Unique's `id` as reference public fun id_ref( nft_data: &Unique, ): &ID { object::uid_as_inner(&nft_data.id) } /// Get the Nft Unique's `name` public fun name( nft_data: &Unique, ): String { nft_data.name } /// Get the Nft Unique's `description` public fun description( nft_data: &Unique, ): String { nft_data.name } /// Get the Nft Unique's `collection_id` public fun collection_id( nft_data: &Unique, ): &ID { &nft_data.collection_id } /// Get the Nft Unique's `url` public fun url( nft_data: &Unique, ): Url { nft_data.url } /// Get the Nft Unique's `attributes` public fun attributes( nft_data: &Unique, ): &Attributes { &nft_data.attributes } /// Get the Nft Collectible's `attributes.keys` public fun attribute_keys( nft_data: &Unique, ): &vector<String> { &nft_data.attributes.keys } /// Get the Nft Collectible's `attributes.values` public fun attribute_values( nft_data: &Unique, ): &vector<String> { &nft_data.attributes.values } // === Private Functions === fun nft_data_id(nft_data: &Unique): ID { object::uid_to_inner(&nft_data.id) } fun mint_and_transfer<T>( args: MintArgs, collection_id: ID, recipient: address, ctx: &mut TxContext, ) { let data_id = object::new(ctx); event::emit( MintDataEvent { object_id: object::uid_to_inner(&data_id), collection_id: collection_id, } ); let nft_data = Unique { id: data_id, name: args.name, description: args.description, collection_id: collection_id, url: args.url, attributes: args.attributes, }; let nft = nft::mint_nft_embedded<T, Unique>( nft_data_id(&nft_data), nft_data, ctx ); transfer::transfer( nft, recipient, ); } fun mint_to_launchpad<T, M: store>( args: MintArgs, collection_id: ID, sale_index: u64, launchpad: &mut Slingshot<T, M>, ctx: &mut TxContext, ) { let data_id = object::new(ctx); event::emit( MintDataEvent { object_id: object::uid_to_inner(&data_id), collection_id: collection_id, } ); let nft_data = Unique { id: data_id, name: args.name, description: args.description, collection_id: collection_id, url: args.url, attributes: args.attributes, }; let nft = nft::mint_nft_embedded<T, Unique>( nft_data_id(&nft_data), nft_data, ctx ); let sale = slingshot::sale_mut(launchpad, sale_index); sale::add_nft<T, M>(sale, nft::id(&nft)); slingshot::mint_nft_to(launchpad, nft); } fun burn_nft_<T>( nft: Nft<T, Unique>, ) { let data_option = nft::burn_embedded_nft(nft); // TODO: Consider the best way to handle the data object: // Send it to the sender? // Make it shared? // Delete it? let data = option::extract(&mut data_option); option::destroy_none(data_option); event::emit( BurnDataEvent { object_id: id(&data), collection_id: *collection_id(&data), } ); let Unique { id, name: _, description: _, collection_id: _, url: _, attributes: _, } = data; object::delete(id); } fun mint_args( name: vector<u8>, description: vector<u8>, url: vector<u8>, attribute_keys: vector<String>, attribute_values: vector<String>, ): MintArgs { let attributes = Attributes { keys: attribute_keys, values: attribute_values, }; MintArgs { name: string::utf8(name), description: string::utf8(description), url: url::new_unsafe_from_bytes(url), attributes, } } }
import { Component, OnInit, ViewEncapsulation, } from '@angular/core'; import { HttpClient } from '@angular/common/http'; // import Swiper core and required modules import SwiperCore, { Navigation, Pagination, Scrollbar, A11y } from 'swiper'; // install Swiper modules SwiperCore.use([Navigation, Pagination, Scrollbar, A11y]); @Component({ selector: 'app-portfolio', templateUrl: './portfolio.component.html', styleUrls: ['./portfolio.component.scss'], encapsulation: ViewEncapsulation.None, }) export class PortfolioComponent implements OnInit { repositories: any[] = []; webRepositories: any[] = [ { title: 'Peluquería Lilian', description: 'HTML5 | CSS3', imgPath: '../../../assets/portfolio/img/lilian-web.png', webLink: 'https://lilian.ar/', repoLink: 'https://github.com/EmmaVZ89/Peluqueria-Lilian-Proyecto', }, { title: 'Peluquería Lilian Clientes', description: 'HTML5 | CSS3 | JavaScript | MySql | Node.js', imgPath: '../../../assets/portfolio/img/lilian-gestor.png', webLink: 'https://lilian-clientes.onrender.com/', repoLink: 'https://github.com/EmmaVZ89/Peluqueria-Lilian-Gestor', }, { title: 'Sala de Juegos', description: ' Angular | TypeScript | Firebase', imgPath: '../../../assets/portfolio/img/sj.png', webLink: 'https://fir-userauth-fe03f.web.app/', repoLink: 'https://github.com/EmmaVZ89/Sala-de-Juegos-TP-Laboratorio-IV', }, { title: 'Clínica Online', description: 'Angular | TypeScript | Firebase | Chartjs', imgPath: '../../../assets/portfolio/img/co.png', webLink: 'https://clinica-online-tp2-labo-iv.firebaseapp.com/', repoLink: 'https://github.com/EmmaVZ89/Clinica-Online-TP2-Laboratorio-IV', }, { title: 'Rick And Morty API', description: 'PHP | TypeScript | CSS3 | MySql', imgPath: '../../../assets/portfolio/img/ram.png', webLink: 'https://rickandmortycardgame.000webhostapp.com/index.php', repoLink: 'https://github.com/EmmaVZ89/Rick-and-Morty-Card-Game', }, { title: 'Easy To Git', description: 'JavaScript | HTML5 | CSS3', imgPath: '../../../assets/portfolio/img/etg.png', webLink: 'http://easytogit.com/', repoLink: 'https://github.com/EmmaVZ89/easy-to-git', }, { title: 'Documentación Técnica', description: 'HTML5 y CSS3', imgPath: '../../../assets/portfolio/img/td.png', webLink: 'https://emmavz89.github.io/Technical-Documentation/', repoLink: 'https://github.com/EmmaVZ89/Technical-Documentation', }, { title: 'Landing Page', description: 'HTML5 y CSS3', imgPath: '../../../assets/portfolio/img/lp.png', webLink: 'https://emmavz89.github.io/Landing-Page/', repoLink: 'https://github.com/EmmaVZ89/Landing-Page', }, ]; mobileRepositories: any[] = [ { title: 'Relevamiento Visual', description: 'Ionic Framework | Angular | Firebase | Chartjs', imgPath: '../../../assets/portfolio/img/rv.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Relevamiento-Visual-PPS', }, { title: 'Tabla Didáctica de Idiomas', description: 'Ionic Framework | Angular | Firebase', imgPath: '../../../assets/portfolio/img/tdi.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Tabla-Didactica-PPS', }, { title: 'Alarma de Robo', description: 'Ionic Framework | Angular | Firebase', imgPath: '../../../assets/portfolio/img/ar.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Alarma-de-Robo-PPS', }, { title: 'Carga de Crédito', description: 'Ionic Framework | Angular | Firebase', imgPath: '../../../assets/portfolio/img/cc.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Carga-de-Credito-PPS', }, { title: 'Conversando en el Aula', description: 'Ionic Framework | Angular | Firebase', imgPath: '../../../assets/portfolio/img/ca.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Conversando-en-el-Aula-PPS', }, { title: 'Administración de Usuarios', description: 'Ionic Framework | Angular | Firebase', imgPath: '../../../assets/portfolio/img/au.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Administracion-de-Usuarios-PPS', }, { title: 'Despertador por GPS', description: 'Ionic Framework | Angular | Firebase', imgPath: '../../../assets/portfolio/img/dgps.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Despertador-por-GPS-PPS', }, { title: 'Visualizador Kinético', description: 'Ionic Framework | Angular | Firebase | Chartjs', imgPath: '../../../assets/portfolio/img/vk.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Visualizador-Kinetico-PPS', }, { title: 'Juego Kinético', description: 'Ionic Framework | Angular | Firebase', imgPath: '../../../assets/portfolio/img/jk.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Juego-de-Movimiento-Kinetico-PPS', }, { title: 'Control de Gastos', description: 'Ionic Framework | Angular | Firebase | Chartjs', imgPath: '../../../assets/portfolio/img/cg.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Control-de-Gastos-PPS', }, ]; desktopRespositories: any[] = [ { title: 'Punto de Venta', description: 'NET Framework | C# | WPF | Sql Server', imgPath: '../../../assets/portfolio/img/pos.png', webLink: '', repoLink: 'https://github.com/EmmaVZ89/Punto-de-Venta-.NET', }, ]; spinner: boolean = false; repoQuantity: number = 0; constructor(private http: HttpClient) {} ngOnInit(): void { this.spinner = true; this.http .get('https://api.github.com/users/EmmaVZ89/repos?per_page=100') .subscribe((repos: any) => { this.repositories = repos; this.repositories.sort(function (a: any, b: any) { return <any>new Date(b.pushed_at) - <any>new Date(a.pushed_at); }); this.repoQuantity = this.repositories.length; this.spinner = false; }); } ngAfterViewInit(): void { } // INFO REPOS /* clone_url = link al repositorio description = descripción de repo language = lenguaje mas usado languages_url = JSON con lenguajes name = nombre del proyecto topics = array con las etiquetas del proyecto (angular, firebase-auth, etc) created_at = fecha de creación del repositorio "2021-05-19T11:46:15Z" pushed_at = ultimo push "2021-05-19T14:53:10Z" updated_at = ultima actualización "2022-12-22T23:08:28Z" */ }
import { combineReducers, configureStore } from "@reduxjs/toolkit"; import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux"; import { authReducer } from "./reducers/auth"; const store = configureStore({ reducer: combineReducers({ auth: authReducer, }), }); type RootState = ReturnType<typeof store.getState>; type AppDispatch = typeof store.dispatch; const useAppDispatch = (): AppDispatch => useDispatch<AppDispatch>(); const useAppSelector: TypedUseSelectorHook<RootState> = useSelector; export { useAppDispatch as useDispatch, useAppSelector as useSelector, store, };
package com.example.appPerm import android.R.id import android.content.pm.PackageManager import android.content.pm.PermissionGroupInfo import android.content.pm.PermissionInfo import android.os.Environment import android.util.Log import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import java.io.BufferedWriter import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.OutputStreamWriter import java.nio.charset.Charset class PresenterGruposNoSys constructor() { private lateinit var view: AppCompatActivity private lateinit var grupos: List<PermissionGroupInfo> constructor(activity: AppCompatActivity) : this() { this.view = activity // Obtenemos una lista con todos los grupos que existen en la app grupos = view.packageManager.getAllPermissionGroups(PackageManager.GET_META_DATA) } //Metodo para volver al menu principal de la app fun toMenu(item: MenuItem): Boolean { when (item.itemId) { id.home -> { view.finish() return true } } return view.onOptionsItemSelected(item) } //Obtenemos todos los grupos que no son del sistema fun getGrupos(): MutableList<String> { // Obtenemos solo el nombre de los grupos val nombreGrupos: MutableList<String> = mutableListOf() for (grupo in grupos) { nombreGrupos.add(grupo.name) } return nombreGrupos } // Obtenemos informacion de los permisos del grupo si la hubiera fun infoGrupo(grupo: String): MutableList<String> { val info: MutableList<String> = mutableListOf() info.add("Permisos en el grupo $grupo:\n") val permisos = view.packageManager.queryPermissionsByGroup(grupo, 0) if (permisos.isEmpty()) { info.add("Este grupo no contiene permisos") } else { for (permiso in permisos) { //Miramos el protection level del permiso val protection = when (permiso.protection) { PermissionInfo.PROTECTION_NORMAL -> "Normal" PermissionInfo.PROTECTION_DANGEROUS -> "Dangerous" PermissionInfo.PROTECTION_SIGNATURE -> "Signature" PermissionInfo.PROTECTION_INTERNAL -> "Internal" else -> "Desconocido" } info.add("${permiso.name}\n$protection\n") } } return info } //Muestra información de todos los permisos de todos los grupos. fun getPermissionsInGroups() { if (!compruebaCarpeta()) return val packageManager = view.packageManager compruebaCarpeta() val carpetaTFG = File(Environment.getExternalStorageDirectory(), "TFG") val rutaCompleta = File(carpetaTFG, "GruposNoSys.csv") try { val fileOutputStream = FileOutputStream(rutaCompleta) val outputStreamWriter = OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")) val bufferedWriter = BufferedWriter(outputStreamWriter) // Escribir una línea de cabecera en el archivo CSV bufferedWriter.write("Grupo;Permisos") bufferedWriter.newLine() grupos = packageManager.getAllPermissionGroups(PackageManager.GET_META_DATA) for (grupo in grupos) { val listaPermisos = packageManager.queryPermissionsByGroup(grupo.name, 0) var permisos = "" for (permiso in listaPermisos) { permisos += "${permiso.name}," } permisos = permisos.dropLast(1) bufferedWriter.write("${grupo.name};$permisos") bufferedWriter.newLine() } bufferedWriter.close() outputStreamWriter.close() fileOutputStream.close() Log.d("CSV", "Archivo CSV creado exitosamente en: ${rutaCompleta.absolutePath}") } catch (e: IOException) { e.printStackTrace() Log.e("CSV", "Error al crear el archivo CSV.") } } private fun compruebaCarpeta(): Boolean { // Comprobar si el almacenamiento externo está montado y listo para escribir if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) { val rutaCompleta = File(Environment.getExternalStorageDirectory(), "TFG") // Crea la carpeta return if (!rutaCompleta.exists()) { val exito = rutaCompleta.mkdir() if (exito) { Log.i("Carpeta", "Carpeta creada, creando archivos") true } else { Log.e("Carpeta", "No se ha podido crea la carpeta") false } } else { Log.i("Carpeta", "La carpeta ya existe en el almacenamiento externo.") true } } else { Log.e("Carpeta", "El almacenamiento externo no está disponible.") return false } } }
# Cloud Computing ## Foro temático del curso - FR1 ### 1.¿Cuáles serán las fortalezas que considera de Azure? Los servicios de computación en la nube de Microsoft, conocido como Azure, están compuestos por más de 200 productos y servicios cloud. Se trata de una solución segura, que permite trabajar en un entorno híbrido, donde se pueden ejecutar y administrar las aplicaciones empresariales en la nube, por eso, las ventajas de migrar a Azure son muchas. 🔥 Entre sus principales fortalezas tenemos: - **Nube híbrida:** Una de las grandes fortalezas de Azure es la nube híbrida. Muchas empresas cuentan con su propio centro de datos y cuando deciden dar el salto a la nube no quieren perder algunos beneficios que les otorga el entorno local. - **La recuperación de desastres se resuelve con Azure:** Azure dispone de grandes capacidades de recuperación de desastres. Esto incluye temas como ubicaciones de conmutación por error y objetivos de puntos de recuperación. - **Gran nivel de integración:** Los servicios y aplicaciones de Microsoft se integran de forma perfecta, ofreciendo una solución ideal para el trabajo en la nube de las empresas. - **Máquinas virtuales:** El uso de máquinas virtuales es fundamental a la hora de trabajar en la nube, ya que permiten un mayor grado de flexibilidad y escalado, así como una mejor utilización de los recursos disponibles. - **Facilidad y rapidez de uso:** Azure es una solución muy rápida y sencilla de utilizar para crear entornos de trabajo en la nube. Su alta velocidad de despliegue permite tener listas aplicaciones y otros servicios cloud en muy poco tiempo y sin la necesidad de realizar un gran esfuerzo. - **Azure ofrece cobertura global:** Azure tiene la ventaja de adaptarse de forma sencilla a los requisitos de rendimiento y utilización de cada empresa, bien sea una empresa local o una que tenga localizaciones en diferentes países. - **Entorno de desarrollo integrado de Azure:** Azure tiene el beneficio de tener el entorno de desarrollo líder en el mundo: Visual Studio . Como resultado, la curva de aprendizaje habitual asociado con una nueva plataforma se reduce drásticamente - **Azure se puede implementar en cualquier lugar:** Microsoft ha desarrollado Azure Stack, una extensión de Azure para ejecutar aplicaciones híbridas de forma coherente en el entorno local ❄ Información obtenida de los siguientes sitios web: [ILIMIT, (2021)](https://www.ilimit.com/blog/ventajas-migrar-azure/#:~:text=Una%20de%20las%20grandes%20fortalezas%20de%20Azure%20es,algunos%20beneficios%20que%20les%20otorga%20el%20entorno%20local) [Ibermática,(2021)](https://www.ibermatica365.com/10-beneficios-de-microsoft-azure/) ### 2.¿Qué diferencia encuentra entre Api y ApiRest? - ¿Qué es API? API significa “interfaz de programación de aplicaciones”. En el contexto de las API, la palabra aplicación se refiere a cualquier software con una función distinta. La interfaz puede considerarse como un contrato de servicio entre dos aplicaciones. Este contrato define cómo se comunican entre sí mediante solicitudes y respuestas. La documentación de su API contiene información sobre cómo los desarrolladores deben estructurar esas solicitudes y respuestas. - ¿Qué es la API REST? Transferencia de estado representacional abreviado a REST. Las API REST funcionan respondiendo solicitudes de un recurso y devolviendo toda la información relevante sobre el recurso, traducida a un formato que los clientes pueden interpretar fácilmente (este formato lo determina la API que recibe las solicitudes). Los clientes también pueden modificar elementos en el servidor e incluso agregar nuevos elementos al servidor a través de una API REST. 🔥 Las diferencias entre las API y las API REST No todas las API son REST, pero todos los servicios REST son API. Desafortunadamente el enfoque REST, aún siendo uno de los más famosos y usados en época moderna, sigue siendo uno de los más incomprendidos. REST, que significa Representational State Transfer o sea transferencia del estado, no tiene relación con las operaciones que usan métodos HTTP para efectuar CRUD en la base de datos. Solo hace falta leer con atención los principios descritos y notaréis que no han sido citados en el uso de los métodos HTTP como ocurre con clientes que se consideran RESTful. Los servicios HTTP que nosotros creemos o a los que accedemos en nuestras aplicaciones se denomina WEB API o también WEB SERVICES API. El punto sobre el que se concentran no es la transferencia del estado, como señala el enfoque REST, si no la gestión remota de los recursos a visualizar, modificar o crear. Entonces incluso si se ha convertido de uso común definir nuestras WEB API como servicios REST, en realidad es equivocado, ya que la implementación de un correcto enfoque REST requiere que el client no conozca desde el principio todos los recursos, si no que conozca solo el entry point de las API, o sea los URL o LINK iniciales y que sucesivamente sea el server el que gestione las transiciones de estado, enviando al client los hipervínculos entre un recurso y otro. Este dato puede pasar también a través de un archivo normal JSON que contenga en su interior los LINK que el cliente podrá seguir. ❄ Información obtenida de los siguiente sitios web: [Andrés C.,(2022)](https://www.desarrollolibre.net/blog/programacion-basica/api-api-rest-y-api-restful) AulaB, (2022) API y API RESTful qué son y las principales diferencias | Aulab Hackademy ### 3.¿Qué servicio(s) le parece más interesantes de aplicar, sustente su respuesta? Para mí un servicio interesante de aplicar sería el Language Studio, el cual se define como: es un conjunto de herramientas basadas en interfaz de usuario que le permiten explorar, compilar e integrar características de Azure Cognitive Service for Language en las aplicaciones. Me parece interesante porque unifica el QnA Maker con LUIS, además de otros servicios como lectura y traducción de textos, etc. Cosa que además de que nos sirve bastante en nuestro PIM, evita el estar conectando un servicio con el otro como era el caso con QnA Maker y LUIS. ❄ Información obtenida de: [Microsoft, (2022)](https://learn.microsoft.com/es-es/azure/cognitive-services/language-service/language-studio) ### 4.¿Que diferencias existirán entre Azure y Amazon? - AWS está enfocado más en modelos server-less proporcionando herramientas completas para dejar aún lado el hardware, licenciamiento y administración costosa. - Azure está enfocado en modelos de nubes híbridas con la ventaja de que los modelos on-premise conviven mejor por tener ya licenciamiento Microsoft. - AWS cuenta con escalabilidad y flexibilidad natural sin mínimos de consumo. - Azure otorga paquetes de almacenamiento predeterminados. - AWS cuenta ya con productos para soluciones de machine learning altamente automatizados sugiriendo el comportamiento de los algoritmos. - Azure cuenta con también con productos para ML solo que menos automatizados, es necesario más desarrollo y con ciertas limitantes para la operación y adaptabilidad. ❄ Información obtenida de los siguiente sitios web: [Helen F.,(2022)](https://www.inbest.cloud/comunidad/aws-vs.-azure-comparativo-general) ### 5.¿Cuál de los servicios implementados le pareció un reto? explique por qué. Podría decirse que al crear la máquina virtual, porque me demoré bastante y tuve algunas trabas, además, también implementamos un api que conectamos con la nube. Pero en sí diría que el reto lo tenemos en el PIM, ya que estamos usando diversos servicios tales como Language Studio, MySQL, conectado a python, sistema que sirve middleware para insertar datos en el GLPI.
# Purpose Deep learning project for music separation into source instruments. The final goal is to separate a given piece of music by instrument, then give the listener control over the volume of each instrument. One potential use is to isolate the drum part of a complex metal song (hence the name) for learning or general appreciation. # Components The project consists of four parts: 1. Data Handling for managing training data and preprocessing 2. Machine Learning for the separation algorithm (implements only a simple feed-forward neural network at this time) 3. Spectrogram for generating spectrograms from audio 4. Music Separation for applying separation techniques to multi-instrument spectrograms # How it Works 1. Training data is generated by mixing audio of two different instruments and dividing into small time segments 2. For each training example, an ideal binary mask is generated for each instrument such that when applied to the combined spectrogram, it returns the spectrum of only one instrument 3. A neural network is trained to predict a separation mask using the ideal mask from #2 as the truth data 4. The mask can be applied to mixed audio to recover the audio of specific instruments # Implementation The project is written in Python with numpy. The ML components are coded with numpy as well to gain an understanding of common deep learning algorithms.
import React, { useEffect, useRef } from 'react'; import { Animated, Easing } from 'react-native'; import { AnimatedContainer } from '../Animated'; import { ContainerProps } from '../Container'; const INITIAL_OPACITY = 0.25; const INITIAL_OPACITY_LIGHT = 1; const FINAL_OPACITY = 0.15; const FINAL_OPACITY_LIGHT = 0.5; const ANIMATION_DURATION = 1000; export const Skeleton = (props: ContainerProps & { light?: boolean }) => { const { light } = props; const opacity = useRef( new Animated.Value(light ? INITIAL_OPACITY_LIGHT : INITIAL_OPACITY) ); useEffect(() => { const config = { duration: ANIMATION_DURATION, easing: Easing.inOut(Easing.ease), useNativeDriver: true, }; Animated.loop( Animated.sequence([ Animated.timing(opacity.current, { ...config, toValue: light ? FINAL_OPACITY_LIGHT : FINAL_OPACITY, }), Animated.timing(opacity.current, { ...config, toValue: light ? INITIAL_OPACITY_LIGHT : INITIAL_OPACITY, }), ]) ).start(); }, [light]); return ( <AnimatedContainer backgroundColor={light ? 'lightSkeleton' : 'white'} height={25} borderRadius={10} width="100%" opacity={opacity.current} {...props} /> ); };
<template> <div class="cards-list" style="display: block;"> <div> <h2><i class="el-icon-tickets"></i> Logs </h2> <el-divider></el-divider> </div> <el-row> <el-col :span="12"> <el-form ref="form" label-position="left" :gutter="4"> <el-form-item label="Periodo"> <el-col :span="6"> <el-date-picker v-model="date_start" type="date" format= "dd/MM/yyyy" value-format="dd/MM/yyyy" placeholder="Data dal" > </el-date-picker> </el-col> <el-col :span="6"> <el-date-picker v-model="date_end" type="date" format= "dd/MM/yyyy" value-format="dd/MM/yyyy" placeholder="Data al"> </el-date-picker> </el-col> </el-form-item> <el-form-item label="Ricerca"> <el-col :span="12"> <el-input v-model="search_text" placeholder="Utente, POD o PDR" /> </el-col> </el-form-item> </el-form> </el-col> </el-row> <el-row> <el-col :span="6"> <el-button @click="resetForm" type="tertiary" > resetta filtri </el-button> </el-col> <el-col :span="6"> <el-button @click="doSubmit" type="primary" > filtra risultati </el-button> </el-col> </el-row> <div style="margin-top: 30px"> <el-divider></el-divider> <el-table :data="results" :default-sort="{ prop: 'data', order: 'descending' }" stripe style="width: 100%" > <el-table-column prop="data" label="Data" align="left" sortable width="200" /> <el-table-column label="Utente" align="left" > <template #default="scope"> <span> {{ getParametro(scope.row.parametri, 'username') }} ({{ scope.row.username }}) </span> </template> </el-table-column> <el-table-column prop="operazione" label="Operazione" align="left" /> <el-table-column label="POD/PRD" align="left" > <template #default="scope"> <span> {{ getParametro(scope.row.parametri, 'pdp') }} </span> </template> </el-table-column> <el-table-column label="Commodity" align="left" > <template #default="scope"> <span> {{ getParametro(scope.row.parametri, 'commodity') }} </span> </template> </el-table-column> <el-table-column label="Distributore" align="left" > <template #default="scope"> <span> {{ getParametro(scope.row.parametri, 'distributore') }} </span> </template> </el-table-column> <el-table-column label="Sorgente" align="left" > <template #default="scope"> <span> {{ getParametro(scope.row.parametri, 'source') || 'dashboard agente' }} </span> </template> </el-table-column> </el-table> </div> </div> </template> <script> export default { //layout: 'centered', data: () => { return { date_start: '', date_end: '', search_text: '', results: [], pagination: {}, requestSent: false } }, methods: { doSubmit() { this.requestSent = false this.search({ date_start: this.date_start.length ? this.date_start : null, date_end: this.date_end.length ? this.date_end : null, search_text: this.search_text }) }, search(fields) { this.$axios.get('/api/contendibilita/logs', { params: { ...fields }, headers:{ 'Secret-Key' : this.$store.getters['authToken']} } ).then( ({ data: result }) => { const { data, ...pagination } = result this.results = data this.pagination = pagination }, () => { this.results = [] } ).finally(() => { this.requestSent = true }) }, getParametro(paramsString, paramName) { const params = JSON.parse(paramsString) return params[paramName] || '' }, resetForm() { this.date_end = '' this.date_start = '' this.date_search = '' this.search({}) } }, mounted() { this.search({}) } } </script>
import { AudioVideoFacade, AudioVideoObserver, ConsoleLogger, DefaultDeviceController, DefaultMeetingSession, LogLevel, MeetingSessionConfiguration, } from "amazon-chime-sdk-js"; const BASE_URL = [ location.protocol, "//", location.host, location.pathname.replace(/\/*$/, "/"), ].join(""); class MeetingManager { private meetingSession: DefaultMeetingSession; private audioVideo: AudioVideoFacade; private title: string; async initializeMeetingSession( configuration: MeetingSessionConfiguration ): Promise<any> { const logger = new ConsoleLogger("DEV-SDK", LogLevel.INFO); const deviceController = new DefaultDeviceController(logger); this.meetingSession = new DefaultMeetingSession( configuration, logger, deviceController ); this.audioVideo = this.meetingSession.audioVideo; await this.setupAudioDevices(); } async setupAudioDevices(): Promise<void> { const audioOutput = await this.audioVideo.listAudioOutputDevices(); const defaultOutput = audioOutput[0] && audioOutput[0].deviceId; await this.audioVideo.chooseAudioOutput(defaultOutput); const audioInput = await this.audioVideo.listAudioInputDevices(); const defaultInput = audioInput[0] && audioInput[0].deviceId; await this.audioVideo.startAudioInput(defaultInput); } addAudioVideoObserver(observer: AudioVideoObserver): void { this.ensureAudioVideo(); this.audioVideo.addObserver(observer); } removeMediaObserver(observer: AudioVideoObserver): void { this.ensureAudioVideo(); this.audioVideo.removeObserver(observer); } bindVideoTile(id: number, videoEl: HTMLVideoElement): void { this.audioVideo.bindVideoElement(id, videoEl); } async startLocalVideo(): Promise<void> { const videoInput = await this.audioVideo.listVideoInputDevices(); const defaultVideo = videoInput[0]; await this.audioVideo.startVideoInput(defaultVideo); this.audioVideo.startLocalVideoTile(); } async stopLocalVideo(): Promise<void> { this.audioVideo.stopLocalVideoTile(); await this.audioVideo.stopVideoInput(); } async joinMeeting(meetingId: string, name: string): Promise<any> { const url = `${BASE_URL}join?title=${encodeURIComponent( meetingId )}&name=${encodeURIComponent(name)}`; const res = await fetch(url, { method: "POST" }); const data = await res.json(); this.title = meetingId; await this.initializeMeetingSession( new MeetingSessionConfiguration( data.JoinInfo.Meeting, data.JoinInfo.Attendee ) ); this.audioVideo.start(); } async endMeeting(): Promise<any> { await fetch(`${BASE_URL}end?title=${encodeURIComponent(this.title)}`, { method: "POST", }); await this.leaveMeeting(); } async leaveMeeting(): Promise<void> { this.meetingSession.deviceController.destroy(); this.audioVideo.stop(); } async getAttendee(attendeeId: string): Promise<string> { const response = await fetch( `${BASE_URL}attendee?title=${encodeURIComponent( this.title )}&attendee=${encodeURIComponent(attendeeId)}` ); const json = await response.json(); return json.AttendeeInfo.Name; } bindAudioElement(ref: HTMLAudioElement) { this.audioVideo.bindAudioElement(ref); } unbindAudioElement(): void { this.audioVideo.stopAudioInput(); this.audioVideo.unbindAudioElement(); } private ensureAudioVideo() { if (!this.audioVideo) { console.error("AudioVideo not initialized. Cannot add observer"); return; } } } export default new MeetingManager();
using Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Persistence.Data.Configuration; public class ProductConfiguration : IEntityTypeConfiguration<Product> { public void Configure(EntityTypeBuilder<Product> builder) { builder.ToTable("Product"); builder.Property(p => p.ProductName) .HasColumnType("varchar(255) COLLATE utf8mb4_unicode_ci") .HasMaxLength(70) .IsRequired(); builder.HasIndex(p => p.ProductName) .IsUnique(); builder.Property(p => p.Price) .IsRequired(); builder.Property(p => p.CreatedDate) .IsRequired(); builder.HasOne(b => b.Brand) .WithMany(b => b.Products) .HasForeignKey(b => b.IdBrand) .IsRequired(); builder.HasOne(c => c.Category) .WithMany(c => c.Products) .HasForeignKey(c => c.IdCategory) .IsRequired(); } }
package basic.core; import basic.core.member.Grade; import basic.core.member.Member; import basic.core.member.MemberService; import basic.core.member.MemberServiceImpl; import basic.core.order.Order; import basic.core.order.OrderService; import basic.core.order.OrderServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class OrderApp { public static void main(String[] args) { // AppConfig appConfig = new AppConfig(); // MemberService memberService = appConfig.memberService(); // OrderService orderService = appConfig.orderService(); ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); MemberService memberService = applicationContext.getBean("memberService", MemberService.class); OrderService orderService = applicationContext.getBean("orderService", OrderService.class); //회원생성 Long memberId = 1L; Member member = new Member(memberId, "memberA", Grade.VIP); memberService.join(member); //주문 Order order = orderService.createOrder(memberId, "itemA", 10000); System.out.println("order = " + order); } }
import React, { useState, useEffect } from 'react'; import { Container } from 'react-bootstrap'; import { fetchWeather } from '../redux/weatherSlice'; import { setGeo } from '../redux/userSlice'; import * as hooks from '../redux/hooks'; import Weather from './Weather'; function Home(props) { const dispatch = hooks.useAppDispatch(); const userReducer = hooks.useAppSelector(state => state.userReducer); const weatherReducer = hooks.useAppSelector(state => state.weatherReducer); useEffect(() => { if (!userReducer.lat || !userReducer.long) { navigator.geolocation.getCurrentPosition((position) => { dispatch(setGeo({ lat: position.coords.latitude, long: position.coords.longitude })); }); } }, [userReducer.lat, userReducer.long]); useEffect(() => { if (!userReducer.lat && !userReducer.lat) return; dispatch(fetchWeather()); }, [userReducer.lat, userReducer.long]); return ( <Container> {weatherReducer.isLoading ? <div>Loading</div> : (<div> <div> weather </div> <div> <div>lat: {userReducer.lat}</div> <div>long: {userReducer.long}</div> </div> <div> <button onClick={() => dispatch(fetchWeather())} >Reload</button> </div> {weatherReducer.weather && ( <Weather weather={weatherReducer.weather} /> )} </div>) } </Container> ) } export default Home;
import { EntityPosition, Search2D, SearchableEntity } from "../src"; // if you installed with npm, import "search2d" instead type ExampleEntityObject = { name: string; // Additional field } & SearchableEntity; // If you want to use a class, write the following class ExampleEntityClass implements SearchableEntity { constructor( readonly id: string, // Required readonly position: EntityPosition, // Required readonly name: string, // Additional field ) {} } // Specify field height and width // Entity's position range: 0 <= y <= height, 0 <= x <= width const search = new Search2D<ExampleEntityObject>({ height: 100, width: 100 }); const entity: ExampleEntityObject = { id: "001", // id must be unique position: new EntityPosition({ x: 10, y: 20 }), name: "buri", }; // Register entity to search search.register(entity); // Search by query const result = search.search({ position: { xFrom: 10, yFrom: 10, xTo: 20, yTo: 20, }, }); console.log(result); // { // entities: [ { id: '001', position: [EntityPosition], name: 'buri' } ] // } // Move entity position (Change x, y at the same time, it is faster) entity.position.set({ x: 15, y: 15 }); // x, y can also be set individually entity.position.x = 15; entity.position.y = 15; // You can deregister entity search.deregister(entity); // Deregister all entities before disposing search2D instance to prevent memory leak. search.deregisterAll();
const { Survey, Response } = require("../../models/surveySchema"); const { BadRequestError } = require("../../errors/bad-request-error"); const { NotFoundError } = require("../../errors/not-found-error"); function capitalize(text) { return text ?.split(" ") .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(" "); } const mongoose = require("mongoose"); const getResponseDataByDate = async (req, res) => { const { slug } = req.params; const createdBy = req.currentUser.id; try { // First, find the survey to ensure it exists and to get its ID const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { return res.status(404).send("Survey not found"); } // Fetch the responses for this survey const data = await Response.aggregate([ { $match: { surveyId: survey._id } }, { $project: { date: { $dateToString: { format: "%Y-%m-%d", date: "$respondedAt" } }, }, }, { $group: { _id: "$date", value: { $sum: 1 }, }, }, { $sort: { _id: 1 }, // sort by date in ascending order }, ]); const formattedData = data.map((item) => ({ date: item._id, value: item.value })); res.json(formattedData); } catch (error) { res.status(500).send("Server error"); } }; const getSurveyFieldStats = async (req, res) => { const { slug } = req.params; const createdBy = req.currentUser.id; try { const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { return res.status(404).send("Survey not found"); } const stats = { requiredFields: 0, totalFields: 0, radioFields: 0, checkboxFields: 0, dropdownFields: 0, rateFields: 0, dateFields: 0, rangeFields: 0, }; survey.fields.forEach((field) => { stats.totalFields += 1; if (field.required) stats.requiredFields += 1; if (field.type === "radio") stats.radioFields += 1; if (field.type === "checkbox") stats.checkboxFields += 1; if (field.type === "dropdown") stats.dropdownFields += 1; if (field.type === "rate") stats.rateFields += 1; if (field.type === "date") stats.dateFields += 1; if (field.type === "range") stats.rangeFields += 1; }); const formattedData = [ { name: "Total Fields", count: stats.totalFields }, { name: "Required Fields", count: stats.requiredFields }, { name: "Radio Fields", count: stats.radioFields }, { name: "Checkbox Fields", count: stats.checkboxFields }, { name: "Dropdown Fields", count: stats.dropdownFields }, { name: "Rate Fields", count: stats.rateFields }, { name: "Date Fields", count: stats.dateFields }, { name: "Range Fields", count: stats.rangeFields }, ]; res.json(formattedData); } catch (error) { res.status(500).send("Server error"); } }; const getAllFields = async (req, res) => { const { slug } = req.params; const createdBy = req.currentUser.id; try { const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { return res.status(404).send("Survey not found"); } // Extract radio fields const radioFields = survey.fields .filter((field) => field.type === "radio") .map((field) => ({ fieldId: field._id, fieldLabel: field.label, })); const dropdownFields = survey.fields .filter((field) => field.type === "dropdown") .map((field) => ({ fieldId: field._id, fieldLabel: field.label, })); const checkboxFields = survey.fields .filter((field) => field.type === "checkbox") .map((field) => ({ fieldId: field._id, fieldLabel: field.label, })); const rangeFields = survey.fields .filter((field) => field.type === "range") .map((field) => ({ fieldId: field._id, fieldLabel: field.label, })); const dateFields = survey.fields .filter((field) => field.type === "date") .map((field) => ({ fieldId: field._id, fieldLabel: field.label, })); const rateFields = survey.fields .filter((field) => field.type === "rate") .map((field) => ({ fieldId: field._id, fieldLabel: field.label, })); res.json({ rateFields, radioFields, checkboxFields, dateFields, rangeFields, dropdownFields, }); } catch (error) { res.status(500).send("Server error"); } }; const getRadioFieldData = async (req, res) => { const { fieldIds } = req.body; const { slug } = req.params; const createdBy = req.currentUser.id; // Validate that no more than three field IDs are sent if (!fieldIds || fieldIds.length > 3) { throw new BadRequestError("You can select up to three radio fields only."); } const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { throw new NotFoundError("Survey not found"); } const fieldsData = await Promise.all( fieldIds.map(async (fieldId) => { // Aggregate to get the count of each response option for the field const responseData = await Response.aggregate([ { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $unwind: "$responses" }, { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $group: { _id: "$responses.value", count: { $sum: 1 } } }, ]); const field = survey.fields.id(fieldId); return { fieldLabel: field.label, count: responseData.map((item) => ({ name: item._id, value: item.count })), }; }) ); res.json(fieldsData); }; const getCheckboxFieldData = async (req, res) => { const { fieldIds } = req.body; const { slug } = req.params; const createdBy = req.currentUser.id; // Validate that no more than three field IDs are sent if (!fieldIds || fieldIds.length > 3) { throw new BadRequestError("You can select up to three checkbox fields only."); } const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { throw new NotFoundError("Survey not found"); } const fieldsData = await Promise.all( fieldIds.map(async (fieldId) => { // Aggregate to get the count of each response option for the field const responseData = await Response.aggregate([ { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $unwind: "$responses" }, { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $unwind: "$responses.value" }, // Unwind the array of selected checkbox values { $group: { _id: "$responses.value", count: { $sum: 1 } } }, ]); const field = survey.fields.id(fieldId); return { fieldLabel: field.label, count: responseData.map((item) => ({ name: capitalize(item._id), value: item.count })), }; }) ); res.json(fieldsData); }; const getRateFieldData = async (req, res) => { const { fieldIds } = req.body; const { slug } = req.params; const createdBy = req.currentUser.id; // Validate that no more than three field IDs are sent if (!fieldIds || fieldIds.length > 3) { throw new BadRequestError("You can select up to three rate fields only."); } const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { throw new NotFoundError("Survey not found"); } const fieldsData = await Promise.all( fieldIds.map(async (fieldId) => { // Aggregate to get the average, count of each response, and detailed counts const responseData = await Response.aggregate([ { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $unwind: "$responses" }, { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $group: { _id: "$responses.value", count: { $sum: 1 }, }, }, { $sort: { _id: 1 } }, // Sort by rate value if needed ]); const field = survey.fields.id(fieldId); const totalResponses = responseData.reduce((acc, cur) => acc + cur.count, 0); const averageRating = responseData.reduce((acc, cur) => acc + cur._id * cur.count, 0) / totalResponses; return { fieldLabel: field.label, averageRating: averageRating.toFixed(2), totalCount: totalResponses, count: responseData.map((item) => ({ name: item._id, value: item.count })), }; }) ); res.json(fieldsData); }; const getDropdownFieldData = async (req, res) => { const { fieldIds } = req.body; const { slug } = req.params; const createdBy = req.currentUser.id; // Validate that no more than three field IDs are sent if (!fieldIds || fieldIds.length > 3) { throw new BadRequestError("You can select up to three dropdown fields only."); } const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { throw new NotFoundError("Survey not found"); } const fieldsData = await Promise.all( fieldIds.map(async (fieldId) => { // Aggregate to get the count of each response option for the field const responseData = await Response.aggregate([ { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $unwind: "$responses" }, { $match: { "responses.fieldId": new mongoose.Types.ObjectId(fieldId) } }, { $group: { _id: "$responses.value", count: { $sum: 1 }, }, }, { $sort: { _id: 1 } }, // Sort by option value if needed ]); const field = survey.fields.id(fieldId); return { fieldLabel: field.label, count: responseData.map((item) => ({ name: capitalize(item._id), value: item.count })), }; }) ); res.json(fieldsData); }; const getSurveyResponses = async (req, res) => { const { slug } = req.params; const { page = 1, pageSize = 10, search = "" } = req.query; const createdBy = req.currentUser.id; // Assuming this is set from the authenticated user session const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { throw new NotFoundError("Survey not found"); } // Find email and name field IDs for filtering and searching const emailField = survey.fields.find((field) => field.label.toLowerCase() === "email" && field.required); const nameField = survey.fields.find((field) => field.label.toLowerCase() === "name" && field.required); // Constructing the match condition based on search input let matchCondition = { surveyId: survey._id }; if (search && (emailField || nameField)) { matchCondition["$or"] = [ { responses: { $elemMatch: { fieldId: emailField?._id, value: new RegExp(search, "i") } } }, { responses: { $elemMatch: { fieldId: nameField?._id, value: new RegExp(search, "i") } } }, ]; } const total = await Response.countDocuments(matchCondition); const responses = await Response.find(matchCondition) .skip((page - 1) * pageSize) .limit(pageSize) .lean(); // Format responses to only include email, name, and respondedAt const formattedResponses = responses.map((response) => { return { email: response.responses.find((r) => r.fieldId.equals(emailField?._id))?.value, name: response.responses.find((r) => r.fieldId.equals(nameField?._id))?.value, respondedAt: response.respondedAt, _id: response._id, }; }); res.json({ data: formattedResponses, total, page, totalPages: Math.ceil(total / pageSize), }); }; const getSingleResponse = async (req, res) => { const { responseId } = req.params; const createdBy = req.currentUser.id; // Find the response by ID and ensure it belongs to a survey created by the current user const response = await Response.findOne({ _id: responseId }).populate({ path: "surveyId", match: { createdBy: createdBy }, }); // If the response does not exist or does not belong to a survey by the current user if (!response || !response.surveyId) { throw new NotFoundError("Not Found"); } // Optionally, include more details from the survey fields in the response data const survey = await Survey.findById(response.surveyId._id); const detailedResponses = response.responses.map((r) => { const field = survey.fields?.id(r.fieldId); return { fieldLabel: field ? field.label : "Field not found", responseValue: r.value, respondedAt: response.respondedAt, }; }); res.json(detailedResponses); }; const getFieldOverview = async (req, res) => { const { slug } = req.params; const createdBy = req.currentUser.id; // Assuming this is set from the authenticated user session const survey = await Survey.findOne({ slug, createdBy }); if (!survey) { throw new NotFoundError("Not Found"); } const fieldOverviews = await Promise.all( survey.fields.map(async (field) => { const fieldData = { fieldId: field._id, fieldLabel: field.label, }; switch (field.type) { case "rate": const rateData = await Response.aggregate([ { $unwind: "$responses" }, { $match: { "responses.fieldId": field._id } }, { $group: { _id: null, averageRate: { $avg: "$responses.value" } } }, ]); fieldData.averageRate = rateData[0] ? rateData[0].averageRate.toFixed(2) : "No data"; break; case "checkbox": case "radio": case "dropdown": const responseData = await Response.aggregate([ { $unwind: "$responses" }, { $match: { "responses.fieldId": field._id } }, { $group: { _id: "$responses.value", count: { $sum: 1 } } }, { $sort: { count: -1 } }, { $limit: 1 }, ]); fieldData.mostSelected = responseData[0] ? { option: responseData[0]._id, count: responseData[0].count } : { option: "No data", count: 0 }; break; default: break; } return fieldData; }) ); res.json(fieldOverviews); }; // OVERALL const reportForAllSurveys = async (req, res) => { const { from } = req.query; const creatorId = new mongoose.Types.ObjectId(req.currentUser.id); if (from === "summary") { const totalSurveys = await Survey.countDocuments({ createdBy: creatorId }); const totalResponses = await Response.aggregate([ { $lookup: { from: "surveys", // Ensure this is the correct collection name localField: "surveyId", foreignField: "_id", as: "surveyDetails", }, }, { $match: { "surveyDetails.createdBy": creatorId, }, }, { $count: "totalResponses", }, ]); res.status(200).json({ success: true, totalSurveys: totalSurveys, totalResponses: totalResponses.length > 0 ? totalResponses[0].totalResponses : 0, }); } else if (from === "graph") { const surveyResponses = await Survey.aggregate([ { $match: { createdBy: creatorId, }, }, { $lookup: { from: "responses", // Make sure this is your collection name for responses localField: "_id", foreignField: "surveyId", as: "responses", }, }, { $project: { _id: 1, title: 1, attemptsCount: { $size: "$responses" }, }, }, ]); res.json({ surveyResponses }); } }; module.exports = { getResponseDataByDate, getSurveyFieldStats, getAllFields, getRadioFieldData, getCheckboxFieldData, getRateFieldData, getDropdownFieldData, getSurveyResponses, getSingleResponse, getFieldOverview, reportForAllSurveys, };
import React, { useEffect, useState } from "react"; import hljs from "highlight.js" import "highlight.js/styles/vs2015.css"; import "./CodeEditor.scss" type FileDisplay = { fileName: string; codePreview: string; language: string; }; type PageDisplay = { page: number; code: string; language: string; }; interface Props { files: FileDisplay[]; onPageChange?: (page: number) => void } export default function CodeEditor({ files, onPageChange }: Props) { const [currentFile, setCurrentFile] = useState(0); const pagesToDisplay: PageDisplay[] = []; useEffect(() => { hljs.highlightAll(); }, [currentFile]); return ( <div className="w-11/12 lg:w-156 h-100 rounded-md border styled-border styled-background flex flex-col justify-end items-center material-shadow"> <div className="w-95p h-fit flex items-center"> <div className="gap-px h-9 flex items-end border-background px-px rounded-t-md"> {files?.map((value, index) => { let fileImage = ""; pagesToDisplay.push({ page: index, code: value.codePreview, language: value.language }); switch(value.language) { case "csharp": fileImage = `images/logos/file_csharp.svg` break; } return ( <div key={index} className={`w-fit px-4 h-9 ${ index == 0 && index == files.length - 1 ? "rounded-t-md" : index == 0 ? "rounded-tl-md" : index == files.length - 1 ? "rounded-tr-md" : " " } ${ currentFile == index ? "code-background selected-tab" : "styled-background nonselected-tab" } relative top-px ${currentFile == index ? "z-20" : " "} flex justify-center items-center cursor-pointer select-none`} onClick={() => { setCurrentFile(index); if(onPageChange) { onPageChange(index) } }} > {fileImage.length > 0 && ( <img src={`${window.location.origin}/${fileImage}`} className="w-4 h-4 mr-2" /> )} <p className="text-sm text-ellipsis whitespace-nowrap">{value.fileName}</p> </div> ); })} </div> </div> <pre className="w-95p h-80 overflow-hidden border styled-border mb-5 z-10"> <code className={`language-${pagesToDisplay[currentFile].language} overflow-scroll code-display h-full`}> {pagesToDisplay[currentFile].code} </code> </pre> </div> ); }
define(function(require, exports, module) { var View = require('famous/core/View'); var Surface = require('famous/core/Surface'); var Transform = require('famous/core/Transform'); var StateModifier = require('famous/modifiers/StateModifier'); var ImageSurface = require('famous/surfaces/ImageSurface'); var Transitionable = require('famous/transitions/Transitionable'); function Polaroid() { View.apply(this, arguments); this.rootModifier = new StateModifier({ size: this.options.size }); this.mainNode = this.add(this.rootModifier); _createPolaroid.call(this); } Polaroid.prototype = Object.create(View.prototype); Polaroid.prototype.constructor = Polaroid; Polaroid.DEFAULT_OPTIONS = { size: [400, 450], filmBorder: 15, photoBorder: 3, photoUrl: undefined, angle: -0.5, zIndex: 0 }; function _createPolaroid() { _createBackground.call(this); _createFilm.call(this); _createPhoto.call(this); } function _createBackground() { var background = new Surface({ properties: { backgroundColor: '#FFFFF5', boxShadow: '0 10px 20px -5px rgba(0, 0, 0, 0.5)', cursor: 'pointer', zIndex: this.options.zIndex } }); this.mainNode.add(background); background.on('click', function() { this._eventOutput.emit('click'); }.bind(this)); } function _createFilm() { this.options.filmSize = this.options.size[0] - 2 * this.options.filmBorder; var film = new Surface({ size: [this.options.filmSize, this.options.filmSize], properties: { backgroundColor: '#222', zIndex: this.options.zIndex+1, pointerEvents: 'none' } }); var filmModifier = new StateModifier({ origin: [0.5, 0], align: [0.5, 0], transform: Transform.translate(0, this.options.filmBorder, 0.05) }); this.mainNode.add(filmModifier).add(film); } function _createPhoto() { var size = this.options.filmSize - 2 * this.options.photoBorder; var photo = new ImageSurface({ size: [size, size], content: this.options.photoUrl, properties: { zIndex: this.options.zIndex+2, pointerEvents: 'none' } }); this.photoModifier = new StateModifier({ origin: [0.5, 0], align: [0.5, 0], transform: Transform.translate(0, this.options.filmBorder + this.options.photoBorder, 0.1), opacity: 0.01 }); this.mainNode.add(this.photoModifier).add(photo); } Polaroid.prototype.fadeIn = function() { this.photoModifier.setOpacity(1, { duration: 1500, curve: 'easeIn' }); // this.shake(); }; Polaroid.prototype.shake = function() { // this.rootModifier.halt(); // this.rootModifier.setTransform(Transform.rotateX(this.options.angle), { duration: 200, curve: 'easeOut' }); // this.rootModifier.setTransform(Transform.identity, { curve: 'spring', period: 600, dampingRatio: 0.15 }); }; module.exports = Polaroid; });
# INF601 - Advanced Programming in Python # Brayan Gomez # Mini Project 2 import matplotlib.pyplot as plt import pandas as pd from pathlib import Path import sys def files_found(): # Create charts directory try: Path("charts").mkdir() except FileExistsError: pass # Check csv file is found try: data = pd.read_csv("school_scores.csv") except FileNotFoundError: print("school_scores.csv not found, check file is inside folder running main.py") sys.exit() return data def get_states(dataframe): states = [] # get 5 states for i in range(1, 6): # verify the states while True: print(f"Enter state(format:\"Kansas\"): ") state_input = input(">") try: print("Verifying...") if len(dataframe.loc[dataframe["State.Name"] == state_input]) == 0: raise NameError print("Valid") states.append(state_input) break except NameError: print("Invalid state name") return states def get_states_math_gpa(dataframe, state): state_gpa = (dataframe.loc[dataframe["State.Name"] == state]) state_gpa = state_gpa.reset_index(drop=True) return state_gpa def graph_math_gpa(state): y_axis = [gpa for gpa in state["Academic Subjects.Mathematics.Average GPA"]] x_axis = [year for year in state["Year"]] # plot the graph plt.plot(x_axis, y_axis) # get min,max of gpa(y-axis) for nicer graph gpa_range = y_axis gpa_range.sort() plt.axis([x_axis[0], x_axis[-1], gpa_range[0] - .05, gpa_range[-1] + .05]) # show every year plt.xticks(x_axis) # labels for the graph plt.title(f"Average GPA for Math in a Year for {state['State.Name'][0]}") plt.xlabel("Year") plt.ylabel("GPA") # Save files to charts directory save_file = f"charts/{state['State.Name'][0]}.png" plt.savefig(save_file) # Render the graph plt.show() # CSV is found and saved to a panda dataframe df = pd.DataFrame(files_found()) # Filter appropriate Data df_math_gpa = df[["Year", "State.Name", "Academic Subjects.Mathematics.Average GPA"]] # Graph each state for state in get_states(df): graph_math_gpa(get_states_math_gpa(df_math_gpa, state))
// // ViewController.m // DoctorDemo // // Created by ChenQing on 17/9/7. // Copyright © 2017年 ChenQing. All rights reserved. // #import "ViewController.h" #import <StoreKit/StoreKit.h> @interface ViewController ()<SKProductsRequestDelegate,SKPaymentTransactionObserver>{ NSString *productId; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(100, 100, 100, 100); button.backgroundColor = [UIColor greenColor]; [button setTitle:@"6元" forState:UIControlStateNormal]; [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown]; [self.view addSubview:button]; } - (void)btnClick:(UIButton *)button{ productId=@"dabaiyisheng"; //开启内购监测 [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; if ([SKPaymentQueue canMakePayments]) { [self requestProductData:@"dabaiyisheng"]; }else{ NSLog(@"不允许程序内付费"); } } //沙盒测试环境验证 #define SANDBOX @"https://sandbox.itunes.apple.com/verifyReceipt" /** * 验证购买,避免越狱软件模拟苹果请求达到非法购买问题 * */ -(void)verifyPurchaseWithPaymentTransaction{ //从沙盒中获取交易凭证并且拼接成请求体数据 NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL]; NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl]; NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串 NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据 NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; //创建请求到苹果官方进行购买验证 NSURL *url=[NSURL URLWithString:SANDBOX]; NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url]; requestM.HTTPBody=bodyData; requestM.HTTPMethod=@"POST"; //创建连接并发送同步请求 NSError *error=nil; NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error]; if (error) { NSLog(@"验证购买过程中发生错误,错误信息:%@",error.localizedDescription); return; } NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@",dic); if([dic[@"status"] intValue]==0){ NSLog(@"购买成功!"); NSDictionary *dicReceipt= dic[@"receipt"]; NSDictionary *dicInApp=[dicReceipt[@"in_app"] firstObject]; NSString *productIdentifier= dicInApp[@"product_id"];//读取产品标识 //如果是消耗品则记录购买数量,非消耗品则记录是否购买过 NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults]; if ([productIdentifier isEqualToString:productId]) { int purchasedCount=[defaults integerForKey:productIdentifier];//已购买数量 [[NSUserDefaults standardUserDefaults] setInteger:(purchasedCount+1) forKey:productIdentifier]; }else{ [defaults setBool:YES forKey:productIdentifier]; } //在此处对购买记录进行存储,可以存储到开发商的服务器端 }else{ NSLog(@"购买失败,未通过验证!"); } } #pragma mark - 去苹果服务器请求商品 -(void)requestProductData:(NSString *)type{ NSSet *nsset=[NSSet setWithObjects:type, nil]; SKProductsRequest *request=[[SKProductsRequest alloc]initWithProductIdentifiers:nsset]; request.delegate=self; [request start]; } #pragma mark - 收到产品返回信息 -(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{ NSLog(@"收到产品反馈信息"); NSArray *product=response.products; if ([product count]==0) { NSLog(@"没有商品"); return; } NSLog(@"productID:%@", response.invalidProductIdentifiers); NSLog(@"产品付费数量:%lu",(unsigned long)[product count]); SKProduct *p = nil; for (SKProduct *pro in product) { NSLog(@"%@", [pro description]); NSLog(@"%@", [pro localizedTitle]); NSLog(@"%@", [pro localizedDescription]); NSLog(@"%@", [pro price]); NSLog(@"%@", [pro productIdentifier]); if([pro.productIdentifier isEqualToString:productId]){ p = pro; } } SKPayment *payment = [SKPayment paymentWithProduct:p]; NSLog(@"发送购买请求"); [[SKPaymentQueue defaultQueue] addPayment:payment]; } //请求失败 - (void)request:(SKRequest *)request didFailWithError:(NSError *)error{ NSLog(@"------------------错误-----------------:%@", error); } - (void)requestDidFinish:(SKRequest *)request{ NSLog(@"------------反馈信息结束-----------------"); } //监听购买结果 - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{ for(SKPaymentTransaction *tran in transaction){ switch (tran.transactionState) { case SKPaymentTransactionStatePurchased:{ NSLog(@"交易完成"); // 发送到苹果服务器验证凭证 [self verifyPurchaseWithPaymentTransaction]; [[SKPaymentQueue defaultQueue] finishTransaction:tran]; } break; case SKPaymentTransactionStatePurchasing: NSLog(@"商品添加进列表"); break; case SKPaymentTransactionStateRestored:{ NSLog(@"已经购买过商品"); [[SKPaymentQueue defaultQueue] finishTransaction:tran]; } break; case SKPaymentTransactionStateFailed:{ NSLog(@"交易失败"); [[SKPaymentQueue defaultQueue] finishTransaction:tran]; } break; default: break; } } } //交易结束 - (void)completeTransaction:(SKPaymentTransaction *)transaction{ NSLog(@"交易结束"); [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
<template> <div> <div class="relative overflow-x-auto"> <div class="p-6 bg-white border border-gray-200 rounded-lg shadow dark:bg-gray-800 dark:border-gray-700" > <form> <div class="mb-6"> <label for="user" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" >Agregar el Abono </label> <input type="text" id="abonoMaker" v-model="abono" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required /> </div> </form> <button @click="makeAbono()" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" > Crear Abono </button> </div> <br /> <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400"> <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400" > <tr> <th scope="col" class="px-6 py-3">id</th> <th scope="col" class="px-6 py-3">Id Del Viaje</th> <th scope="col" class="px-6 py-3">fecha</th> <th scope="col" class="px-6 py-3">description</th> <th scope="col" class="px-6 py-3">valor</th> <th scope="col" class="px-6 py-3">abono</th> <th scope="col" class="px-6 py-3">Viaje del abono</th> </tr> </thead> <tbody> <tr v-for="(object, index) in info" v-bind:key="index" class="bg-white border-b dark:bg-gray-800 dark:border-gray-700" > <td class="px-6 py-4">{{ object.id }}</td> <td class="px-6 py-4">{{ object.idViaje }}</td> <td class="px-6 py-4">{{ object.fecha }}</td> <td class="px-6 py-4">{{ object.description }}</td> <td class="px-6 py-4"> <div v-if="object.valor"> <label for="username-error" class="block mb-2 text-sm font-medium text-red-700 dark:text-red-500" >Your name</label > <input type="text" id="username-error" :value="object.valor" class="bg-red-50 border border-red-500 text-red-900 placeholder-red-700 text-sm rounded-lg focus:ring-red-500 focus:border-red-500 block w-full p-2.5 dark:bg-red-100 dark:border-red-400" disabled /> <p class="mt-2 text-sm text-red-600 dark:text-red-500"> <span class="font-medium">Oops!</span> Username already taken! </p> </div> </td> <td class="px-6 py-4"> <div v-if="object.abono"> <label for="username-success" class="block mb-2 text-sm font-medium text-green-700 dark:text-green-500" >Your name</label > <input type="text" id="username-success" :value="object.abono" class="bg-green-50 border border-green-500 text-green-900 placeholder-green-700 text-sm rounded-lg focus:ring-green-500 focus:border-green-500 block w-full p-2.5 dark:bg-green-100 dark:border-green-400" disabled /> <p class="mt-2 text-sm text-green-600 dark:text-green-500"> <span class="font-medium">Alright!</span> Username available! </p> </div> </td> <td class="px-6 py-4">{{ object.viajeDelAbono }}</td> </tr> </tbody> </table> </div> </div> </template> <script> import SimpleMaskMoney from "simple-mask-money"; export default { data() { return { info: [], idUser: this.$route.query.id, abono: "", access_token: "", user: "", }; }, async mounted() { SimpleMaskMoney.setMask("#abonoMaker"); const accessToken = this.$route.hash; this.linkForredirect = accessToken; const toke1Spilt = accessToken.split("&"); const found = toke1Spilt.find((element) => element.includes("access_token=") ); const toke2Spilt = found.split("="); this.access_token = toke2Spilt[1]; const response = await this.$sheets( toke2Spilt[1], `Clientes!B${Number(this.$route.query.id) + 1}`, "get" ); const KnowUser = await this.$sheets( toke2Spilt[1], `cliente_${response.values[0][0]}`, "get" ); this.user = response.values[0][0]; KnowUser.values.map((x, y) => { if (y > 0) { let salida = x[4] == undefined || x[4] == null || x[4] == "" ? 0 : SimpleMaskMoney.formatToCurrency(Number(x[4])); let entrada = x[5] == undefined || x[5] == null || x[5] == "" ? 0 : SimpleMaskMoney.formatToCurrency(Number(x[5])); console.log(entrada); this.info.push({ id: x[0], idViaje: x[1], fecha: x[2], description: x[3], valor: salida, abono: entrada, viajeDelAbono: x[6], }); } }); }, methods: { async makeAbono() { let abonoIsValid = SimpleMaskMoney.formatToNumber(this.abono) <= 0 ? false : true; if (abonoIsValid) { const response = await this.$makeAbono( this.access_token, `cliente_${this.user}`, [new Date().toISOString().slice(0, 10),"","",SimpleMaskMoney.formatToNumber(this.abono)] ); window.location.reload(); } else { alert("No se Agrego el valor del abono"); } }, }, }; </script>
import {State} from '../state/state.model'; import {ObjField, ResultType} from '../../modules/rest/decorators'; import {examples} from '../../modules/engine/rest/example.consts'; @ResultType() export class Base { @ObjField({description: 'ID', isID: true}) id!: string; @ObjField({description: 'Name', example: 'Awesome'}) name!: string; @ObjField({nullable: true, description: 'User State Info'}) state?: State; @ObjField({description: 'Created Timestamp', min: 0, example: examples.timestamp}) created!: number; } @ResultType() export class Page { @ObjField({nullable: true, description: 'Items starting from offset position', min: 0, example: 0}) skip?: number; @ObjField({nullable: true, description: 'Amount of returned items', min: 0, example: 25}) take?: number; @ObjField({nullable: true, description: 'Total amount of available items', min: 0, example: 123}) total?: number; }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { FourOfourComponent } from './four-ofour/four-ofour.component'; import { HomeComponent } from './home/home.component'; const routes: Routes = [ { path : "admin", loadChildren : () => import('./admin/admin.module').then(m => m.AdminModule) }, { path : "auth", loadChildren : () => import('./auth/auth.module').then(m => m.AuthModule) }, { path : "", component : HomeComponent}, { path : "**", component : FourOfourComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import React, { useEffect } from "react"; import { Provider, useSelector } from "react-redux"; import "./App.css"; import LoginPage from "./components/LoginPage/LoginPage"; import MainPage from "./components/MainPage/MainPage"; import { Route, Routes } from "react-router-dom"; import Protected from "./wrappers/Protected.jsx"; import { selectIsLoggedIn } from "./slices/authSlice"; import { useNavigate } from "react-router-dom"; function App() { let isLoggedIn = useSelector(selectIsLoggedIn); let navigate = useNavigate(); useEffect(() => { if (!isLoggedIn) return; navigate("/main"); }, [isLoggedIn]); return ( <Routes> <Route path="/main" element={ <Protected> <MainPage /> </Protected> } /> <Route path="/login" element={<LoginPage />} /> <Route path="/" element={<LoginPage />} /> </Routes> ); } export default App;
\qns{Introduction to Second Order Differential Equations} \qcontributor{Jessica Fan, Olivia Huang} Take a RLC circuit in series. We will examine the behavior of this circuit with different R, L, and C values. \input{\bank/ode/figures/second_order_rlc} \begin{enumerate} \qitem Using your knowledge of I-V relationships of inductors and capacitors, write out a KVL equation that represents the behavior of this circuit. \meta{ Current is consistent in the circuit as all components are in series. } \ws{\vspace{125px}} \sol{ $$-V_{dd} + V_L + V_R + V_C = 0$$ $$V_L = L\frac{dI}{dt} = LC \frac{d^2V_C}{dt^2}$$ $$C\frac{dV_C}{dt}$$ $$V_R = RI = RC \frac{dV_C}{dt}$$ $$LC \frac{d^2V_C}{dt^2} + RC \frac{dV_C}{dt} + V_C = V_{dd}$$ } \qitem What is the steady state solution of $V_C(t)$? \sol{ At steady state, $\frac{dV_C}{dt} = 0$, so we can set $V_{dd} = V_C(\infty)$. } \qitem Solve for the solution of the homogenous differential equation. \meta{ See https://www.youtube.com/watch?v=NW9JfMvIsxw for explanation of the general form of the solution. Also shown in Fa23 Lecture slides. } \ws{\vspace{125px}} \sol{ We can guess an exponential solution using the characteristic polynomial. We replace $\frac{dV_C}{dt}$ as r: $$LCr^2 + RCr + 1 = 0$$ Dividing the equation by $\frac{1}{LC}$, we get $$r^2 + \frac{R}{L}r + \frac{1}{LC} = 0$$ Solving for r, $$r = \frac{-\frac{R}{L} \pm \sqrt{\frac{R}{L}^2 - \frac{4}{LC}}}{2}$$ $$V_C(t) = C_0 e^{\frac{-\frac{R}{L} + \sqrt{\frac{R}{L}^2 - \frac{4}{LC}}}{2}t} + C_1 e^{\frac{-\frac{R}{L} - \sqrt{\frac{R}{L}^2 - \frac{4}{LC}}}{2}t}$$ Where $C_0$ and $C_1$ are determined by the initial conditions of $V_C$. } \qitem Let's analyze our solution. Under what conditions will we \begin{enumerate} \qitem Have two real exponent terms? \sol{ $$\sqrt{\frac{R}{L}^2 - \frac{4}{LC}} > 0$$ Under these conditions, our circuit will experience \textbf{overdamping}, better written as $\sqrt{\frac{R}{2L}^2 - \frac{1}{LC}} > 0$. } \qitem Have only one exponent term? \sol{ $$\sqrt{\frac{R}{L}^2 - \frac{4}{LC}} = 0$$ Under these conditions, our circuit will experience \textbf{critical damping}. } \qitem Have two complex exponent terms? \sol{ $$\sqrt{\frac{R}{L}^2 - \frac{4}{LC}} < 0$$ Under these conditions, our circuit will experience \textbf{underdamping}. } \end{enumerate} \end{enumerate}
import React, { useEffect, useRef, useState } from "react"; import { motion } from "framer-motion"; export default function ValesSlider({ claveAcceso, dbVales, dbConsumidos }) { const [desbloqueado, setDesbloqueado] = useState(false); const [clave, setClave] = useState(""); const [vales, setVales] = useState([]); const sliderRef = useRef(null); const comprobar = () => { return clave === claveAcceso; }; const handleSubmit = (e) => { e.preventDefault(); const desbloquear = comprobar(clave); setDesbloqueado(desbloquear); }; useEffect(() => { desbloqueado && setVales(dbVales); }, [desbloqueado]); if (desbloqueado) { return ( <div className="w-fit max-w-full overflow-hidden flex flex-col gap-10" ref={sliderRef}> <h1 class="text-2xl text-blue-950 font-semibold w-full text-center">V A L E S * E N * P A R E J A</h1> <motion.ul drag="x" dragConstraints={sliderRef} className="flex gap-2 w-fit h-auto px-4" > {vales.map((v) => ( <li key={v.id} className={`${v.consumido&&"opacity-40 pointer-events-none"} w-80 md:w-96 flex flex-col items-center justify-between bg-gradient-to-r from-black/50 to-blue-500/80 border-[1px] shadow-lg aspect-video rounded-xl p-4`} > <header className="w-full"> <h2 className="text-white text-center text-2xl font-bold text-wrap"> {v.titulo} </h2> </header> <main className="w-full"> <p className="text-white text-wrap text-center"> {v.descripcion} </p> </main> <footer className="w-full flex items-center justify-between"> <span className="text-white">{v.cantidad} &#x2764;</span> <form action="api/consumir" method="POST"> <input type="hidden" name="id" value={v.id} /> <button type="submit" className="px-2 py-1 border-blue-950 border-2 rounded-full text-blue-950 font-semibold hover:scale-95" > Consumir </button> </form> </footer> </li> ))} </motion.ul> <motion.ul drag="x" dragConstraints={sliderRef} className="flex gap-2 w-fit h-auto px-4" > {dbConsumidos.map((c) => ( <li key={c.id} className="pointer-events-none w-80 md:w-96 flex flex-col items-center justify-between bg-black/80 border-[1px] shadow-lg aspect-video rounded-xl p-4" > <header className="w-full"> <h1 className="text-red-300 text-center text-2xl font-bold text-wrap">CONSUMIDO</h1> <h2 className="text-white text-center text-xl font-bold text-wrap"> {c.titulo} </h2> </header> <main className="w-full"> <p className="text-white text-wrap text-center"> {c.descripcion} </p> </main> <small>{c.id}</small> </li> ))} </motion.ul> </div> ); } else { return ( <form onSubmit={handleSubmit} className="flex flex-col gap-2"> <fieldset> <label htmlFor="clave" className="flex flex-col items-center justify-center gap-2" > <span className="text-slate-600">CLAVE DE ACCESO</span> <input type="password" name="clave" id="clave" onChange={(e) => setClave(e.target.value)} className="outline-none px-2 py-1" /> </label> </fieldset> <button type="submit" className="px-2 py-1 bg-slate-800 text-slate-100 hover:bg-slate-700 cursor-pointer w-full" > Check </button> </form> ); } }
/* * Copyright (c) 2017 Lucas Satabin * * Licensed under the Apache License Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package toolxit package font package tfm import java.nio.file.{ Path, Files } import java.io.FileInputStream import scodec._ import bits._ class TfmFinder(dir: Path) extends FontFinder { def find(name: String): Option[FontMetrics] = { val path = dir.resolve(f"$name.tfm") if (Files.exists(path)) { val stream = new FileInputStream(path.toFile) try { val bv = BitVector.fromInputStream(stream) TfmCodec.file.decodeValue(bv) match { case Attempt.Successful(tfm) => Some(tfm) case Attempt.Failure(err) => throw new Exception(err.messageWithContext) } } finally { if (stream != null) stream.close() } } else { None } } }
import { useFetcher } from '@remix-run/react'; import { useEffect } from 'react'; import { QUERY_DOOH_BY_ID } from '~/routes/get-dooh-by-id'; import type { Marker } from 'app/types'; export interface DoohDetailsProps { selectedId: number; } export const DoohDetails = ({ selectedId }: DoohDetailsProps) => { const fetcher = useFetcher<Marker>(); const { data } = fetcher; // Fetch dooh details by given ID useEffect(() => { const formData = new FormData(); formData.append('id', selectedId.toString()); if (fetcher.state === 'idle' && !fetcher.data) { fetcher.submit(formData, { method: 'GET', action: QUERY_DOOH_BY_ID, }); } }, [selectedId, fetcher]); if (!data || fetcher.state === 'loading') { return <div>loading</div>; } return ( <div> <div className='text-xl font-semibold text-black'> {data.media_owner} </div> <div className='text-sm text-gray-600'>{data.site_name}</div> <div className='mt-8'> <div className='text-sm text-gray-600'>{`Display resolution: ${formatResolution( data.resolution )}`}</div> <div className='text-sm text-gray-600'>{`Recommended resolution: ${formatResolution( data.creative_dimension )}`}</div> </div> <div className='mt-8'> <button className='bg-blue-500 hover:bg-blue-700 text-white py-2 px-4 rounded-full'> Book now </button> </div> </div> ); }; // Utility function to format resolution const formatResolution = (resolution: string | null) => { if (!resolution) return ''; const [width, height] = resolution.split('x'); return `${width}px by ${height}px`; };
import { addDoc, collection, doc, updateDoc, deleteDoc } from "@firebase/firestore"; import { types } from '../types/types'; import { db } from "../firebase/firebase-config"; import { loadNotes } from "../helpers/loadNote"; import { toast } from "../helpers/sweetAlert2"; import { fileUpload } from "../helpers/fileUpload"; export const startNewNote = () => { return async ( dispatch, getState ) => { const { uid } = getState().auth; const newNode = { title: '', body: '', date: new Date().getTime() } const doc = await addDoc(collection(db, `${uid}`, "journal/notes"), newNode); dispatch(activeNote(doc.id, newNode)); } } export const activeNote = ( id, note ) => ({ type: types.notesActive, payload: { id, ...note } }) export const startLoadingNotes = ( uid ) => { return async ( dispatch ) => { const notes = await loadNotes(uid); dispatch(setNotes(notes)); } } export const setNotes = ( notes ) => ({ type: types.notesLoad, payload: notes }); export const startSaveNote = ( note ) => { return async ( dispatch, getState) => { const { uid } = getState().auth; const { id, url = null, ...noteToFirestore } = note; delete noteToFirestore.id; const dbRef = doc(db, `${uid}/journal/notes/${id}`); await updateDoc(dbRef, { url, ...noteToFirestore }); dispatch( startLoadingNotes( uid ) ); dispatch(refreshNote( id, note )); toast('success', 'Saved correctly'); } } export const refreshNote = ( id, note ) => ({ type: types.notesUpdated, payload: { id, note: { id, ...note } } }) export const startUpdloading = ( file ) => { return async ( dispatch, getState ) => { const { active:activeNote } = getState().notes; toast('info', 'Uploading...'); const fileUrl = await fileUpload( file ); activeNote.url = fileUrl; dispatch( startSaveNote(activeNote) ); } } export const startDeleting = ( id ) => { return async ( dispatch, getState ) => { const { uid } = getState().auth; const dbRef = doc(db, `${uid}/journal/notes/${id}`); await deleteDoc(dbRef); toast('success', 'Deleted correctly!'); dispatch( deleteNote(id) ); } } export const deleteNote = ( id ) => ({ type: types.notesDelete, payload: id }); export const noteLogout = () => ({ type: types.notesLogoutCleaning })