text
stringlengths 184
4.48M
|
---|
<?php
declare(strict_types=1);
namespace Junges\Kafka\Facades;
use Illuminate\Support\Facades\Facade;
use Junges\Kafka\Contracts\ProducerMessage;
use Junges\Kafka\Support\Testing\Fakes\KafkaFake;
/**
* @method static \Junges\Kafka\Contracts\MessageProducer publish(string $broker = null)
* @method static \Junges\Kafka\Consumers\Builder consumer(array $topics = [], string $groupId = null, string $brokers = null)
* @method static void assertPublished(ProducerMessage $expectedMessage = null, callable $callback = null)
* @method static void assertPublishedTimes(int $times = 1, ProducerMessage $expectedMessage = null, callable $callback = null)
* @method static void assertPublishedOn(string $topic, ProducerMessage $expectedMessage = null, callable $callback = null)
* @method static void assertPublishedOnTimes(string $topic, int $times = 1, ProducerMessage $expectedMessage = null, callable $callback = null)
* @method static void assertNothingPublished()
* @method static void shouldReceiveMessages(\Junges\Kafka\Contracts\ConsumerMessage|\Junges\Kafka\Contracts\ConsumerMessage[] $messages)
*
* @mixin \Junges\Kafka\Factory
*
* @see \Junges\Kafka\Factory
*/
class Kafka extends Facade
{
/** Replace the bound instance with a fake. */
public static function fake(): KafkaFake
{
static::swap($fake = new KafkaFake(
(static::getFacadeRoot())->shouldFake()
));
return $fake;
}
public static function getFacadeAccessor(): string
{
return \Junges\Kafka\Factory::class;
}
} |
---
title: "Regierende Populisten und ideologische Heterogenität anhand des Beispiels Griechenland"
subtitle: "Zusammenarbeit trotz oder Spaltung wegen politischer Differenzen?"
author: "Florian Wisniewski"
date: "`r Sys.Date()`"
output:
prettydoc::html_pretty:
theme: leonids
highlight: github
toc: TRUE
number_sections: TRUE
---
```{r loading libraries, message=FALSE, warning=FALSE, include=FALSE, paged.print=FALSE}
# libraries general
library(tidymodels)
library(tidyverse)
library(rms)
library(MASS)
library(corrplot)
library(lubridate)
library(Amelia)
library(xtable)
library(haven)
library(foreign)
library(broom)
library(psych)
library(Hmisc)
library(expss)
library(rockchalk)
library(effects)
library(modeldata)
library(randomForest)
library(compare)
library(psych)
library(desc)
library(PerformanceAnalytics)
library(reshape2)
library(d3heatmap)
library(kableExtra)
library(gtools)
library(gmodels)
library(summarytools)
library(data.table)
library(ggpubr)
```
```{r loading dfs, message=FALSE, warning=FALSE, include=FALSE, paged.print=FALSE}
# ches 19
ches19 <- read_dta(file = "/Users/flo/Desktop/data/ches/19/CHES2019V3.dta")
# ches 19 filtered (2 in 1 and separately)
ches19_f <- ches19 %>% filter(country == 4 | country == 8)
ches19_GRC <- ches19 %>% filter(country == 4)
ches19_ITA <- ches19 %>% filter(country == 8)
# ches 19 ITA, only M5S and LN
ches19_M5S_LN <- ches19_ITA[c(1, 8),]
# ches 14
ches14 <- read_dta(file = "/Users/flo/Desktop/data/ches/14/2014_CHES_dataset_means-2.dta")
# ches 14 filtered (2 in 1 and separately)
ches14_f <- ches14 %>% filter(country == 4 | country == 8)
ches14_GRC <- ches14 %>% filter(country == 4)
ches14_ITA <- ches14 %>% filter(country == 8)
# ches 14 GRC, only SYRIZA and ANEL
ches14_SYRIZA_ANEL <- ches14_GRC[c(3, 6),]
# poppa expert survey
poppa <- read_dta(file = "/Users/flo/Desktop/data/poppa/party_means.dta")
# poppa filtered (2 in 1 and separately)
poppa_f <- poppa %>% filter(country_id == 13 | country_id == 16)
poppa_GRC <- poppa %>% filter(country_id == 13)
poppa_ITA <- poppa %>% filter(country_id == 16)
# poppa filtered: ITA = M5S and LN | GRC = SYRIZA and ANEL
poppa_SYRIZA_ANEL <- poppa_GRC[c(1, 7),]
poppa_M5S_LN <- poppa_ITA[c(2, 4),]
# elnes (should it be required, it can be loaded here)
# elnes <- read_sav(file = "/Users/flo/Desktop/data/elnes/ELNES-2015b-clean-weights.sav")
```
# Einleitung
Am 13. Februar 2021 wurde Mateo Draghi, ehemaliger Präsident der Europäischen Zentralbank, nach einer erneuten Regierungskrise zum neuen Premierminister Italiens vereidigt. Um diese Handlung genauer zu verstehen, kann bis ins Jahr 2018 und der damals stattgefundenen Wahl zurückgegangen werden. Nach dieser wurde zunächst eine von manchen Medien erste populistische Koalition Westeuropas (vgl. NBC News 2018, CBC 2018, The Economist 2018, New York Times 2018) formiert - bestehend aus der Fünf-Sterne-Bewegung (M5S), welche starke Anti-Establishment-Positionen bezieht und der rechtspopulistischen Lega Nord (Lega). Premierminister und Kopf dieses Gebildes sollte der parteilose Giuseppe Conti werden, ein Jurist ohne vorherige Erfahrung. Doch nach etwas mehr als einem Jahr zerbrach diese Koalition bereits wieder durch ein Misstrauensvotum - vorrangig, so wurde dies von den beteiligten Akteuren gedeutet (vgl. Guardian 2019), aufgrund der persönlichen Ambitionen Matteo Salvinis, Innenminister und Vorsitzender der Lega.
Doch auch die in der Folge darauf neu eingesetzte Regierung, der wieder Conte vorstand, bestehend aus M5S und der Partito Democratico (PD), war nicht von großer Konstanz gekennzeichnet. Nachdem es bereits zu Beginn die Abspaltung der Partei Italia Vivo (IV) von der PD gab, führte sich das Motiv der Spaltung fort: letztlich zerbrach auch diese Folgeregierung im Januar/Februar 2021.
Doch nicht nur in Italien kam es dazu, dass sich populistische Parteien für die Regierung eines europäischen Staates verantwortlich zeichneten. Ein prominentes Beispiel hierfür ließ sich bis vor Kurzem auch noch in Griechenland wiederfinden. Als Folge der Finanzkrise konnte sich die dem linken, populistischen Parteienspektrum angehörende Partei von Alexis Tsipras, SYRIZA, profilieren und die Regierungsverantwortung übernehmen. Als es in den beiden Wahlen von 2015 nicht für eine absolute Mehrheit reichte, wurde als Koalitionspartner - und das auf den ersten Blick sehr überraschend - die rechtspopulistische und nationalkonservativ eingestellte Partei ANEL auserkoren. Diese Koalition regierte bis zu ihrem Zerfall aufgrund ideologischer Differenzen im Jahr 2019 gemeinsam.
Anhand dieser beiden Beispiele wird deutlich, dass es durchaus möglich ist, dass sich populistische Parteien nach einer Wahl in Regierungsverantwortung wiederfinden können. Doch oft kommt es bei derartigen Regierungsformen zu Schwierigkeiten, sie scheinen nicht sehr lange zu halten, gerade aufgrund dessen, da oft Koalitionen eingegangen werden müssen - und diese natürlich mit einem gewissen "tradeoff" verbunden sind, welcher der eigenen Partei im Hinblick auf nächste Wahlen durchaus zu schaden vermag. Für vorliegende Arbeit stellt sich aus diesen empirischen Beispielen und gerade diesen Überlegungen heraus die Frage: welche gemeinsamen Muster, aber auch Unterschiede lassen sich zwischen dem italienischen und dem griechischen Fall von populistischen Regierungen finden, die erklären könnten, wie die Zusammenarbeit zwischen populistischen Parteien in Regierungsverantwortung geregelt ist? Oder, anders formuliert: Was ist der *Kleber, der populistische Regierungen zusammenhält* und *welche Faktoren wirken eher spaltend*? Diese Frage ist besonders interessant, gerade wenn es um ideologisch heterogene Koalitionen geht, wie in den angesprochenen Praxisbeispielen. Dafür soll sich auch mit eben dieser Zusammenarbeit genauer auseinandergesetzt werden.
Einer möglichen Antwort auf diese Frage soll sich jedoch auch empirisch genähert werden. So sollen Daten aus der Chapel Hill Expert Survey und der Populist and Political Parties Expert Survey untersucht werden, um Themenbereiche herauszuarbeiten, in denen sich die Parteipositionen der jeweiligen Koalitionspartner in Italien und Griechenland zu verschiedenen Thematiken überschnitten oder auch diametral gegenüberstanden. Anhand dieser empirischen Gegenüberstellung sollen abschließend, sofern vorhanden, Muster aufgezeigt werden, welche dieser Positionen verbindend oder auch spaltend wirken können.
# Theorieteil, theoretische Annahmen
Zunächst soll jedoch näher auf die theoretischen Vorüberlegungen eingeganen werden, welche für diese Arbeit grundlegend sein werden. Dabei ist zunächst wichtig, zu klären, welche Definition des Begriffes oder Konstruktes *Populismus* in dieser Arbeit verwendet werden wird.
Diesbezüglich soll zunächst auf die gängige Definition von Populismus als "dünne Ideologie" hingewiesen werden, wonach der Populismus an sich keine eigenständige Ideologie ausmacht, hierfür zu unterkomplex konstruiert ist. Wodurch er vielmehr besticht, ist die gute Anschlussfähigkeit an andere Theorien und Ideologien, egal ob größer oder kleiner als er selbst, wie beispielsweise Kommunismus, Sozialismus oder auch Nationalismus (vgl. Mudde 2004, S. 544).
Doch für vorliegende Arbeit fällt dieser Ansatz in der Frage der Klassifizierung von populistischen Parteien oder Bewegungen nicht weit genug aus. So hätte man beispielsweise eventuell Probleme, einen Populismus der Mitte, wie er von Parteien wie der M5S in Italien betrieben wird, auf einer klassischen Links-Rechts-Skala zu verorten oder einer solchen Bewegung einen ideologisch klaren "Partner" für den Populismus zur Seite zu stellen.
Aus diesem Grund greift auch vorliegende Arbeit den ideellen Ansatz zur Definition und Beschreibung von Populismus auf. Hier wird dieser eher als Ausdruck eines manichäischen Weltbildes gesehen, welche zwar, ähnlich wie Mudde schon 2004 anmerkte, auf den Kampf zwischen dem Willen des Volkes einerseits gegen die korrupte Elite andererseits hinweisen. Dabei ist es jedoch weniger eine lose Ideologie, bei der manche Behauptungen zutreffen, andere wiederum nicht. Der ideelle Ansatz definiert sich nach Hawkins und Rovira-Kaltwasser in drei Teilen:
+ das *manichäische Weltbild* und stark in schwarz und weiß denkende Moralvorstellungen,
+ die *Erhebung "des Volkes"* zu einer homogenen und inhärent moralisch guten Instanz,
+ die *Konstruktion einer "Elite"* als Gruppe, die nur sich selbst dient, korrupt und moralisch verwerflich ist.
Die Autoren weisen diesbezüglich darauf hin, dass eine Bewegung oder Partei, bzw. allgemeiner ein Untersuchungsgegenstand als populistisch im Sinne des ideellen Ansatzes bezeichnet werden kann, sofern alle drei Punkte als erfüllt erachtet werden können (vgl. Hawkins/Rovira-Kaltwasser 2019, S. 3). Die Betonung liegt hierbei also darauf, dass nicht nur *entweder* ein solcher Volksgedanke *oder* eine derartige Elitendarstellung vorliegen sollten, sondern dass diese in Kombination über die manichäische Weltanschauung und Moralvorstellung vorliegen müssen.
# Kontext und Vorgeschichte zu Regierungen in ITA und GRC
+ Wie sind die jeweiligen Regierungen ideologisch aufgebaut?
+ Was bringt das mit sich, was ist erwartbar?
+ Wie lief das in der Wirklichkeit?
# Griechenland 2015
## Ausgangslage
Zunächst in gebotener Kürze zur Analyse der Ausgangslage in Griechenland vor dem und im Jahr 2015. Griechenland wurde von der Finanzkrise in der EU wohl zweifelsohne mit am stärksten getroffen. Viele Teile der Bevölkerungen litten stark unter den durchgesetzten Sparmaßnahmen. Dies schlug sich jedoch auch in den Wahlen nieder: die bisher größten Parteien PASOK und ND erlebten in der Zeit nach der Finanzkrise bis zum Januar 2015 zahlreiche Niederlagen an der Wahlurne und büßten viel von ihrer Vormachtstellung ein. Gerade die Wahlen von 2012 verdeutlichten hier bereits einen Trend für diese Parteien und wurden als "earthquake elections" bezeichnet - also das Aufbrechen von bisheriger Stabilität bei Wahlen in einem Staat (vgl. Tsatsanis/Teperoglou 2016, S. 429). In Zahlen äußerte sich dies wie folgt: konnte PASOK 2009 noch mit 44% der Stimmen die Wahl gewinnen und ND mit 33% zweitstärkste Kraft werden, so fielen diese Werte 2012 mit 19 (ND) und 13 (PASOK) extrem in den Keller - profitieren konnte jedoch auch schon bei dieser Wahl die linkspopulistische Partei SYRIZA - sie sprang von 5% in 2009 auf 17% in 2012. Als nach diesen Wahlen sich keine stabile Koalition formen ließ, wurden Neuwahlen nötig und ND und PASOK mussten mit der neu ins Parlament gekommenen linken Partei DIMAR eine Koalition eingehen, um weiter regieren zu können. Ebenso fällt in diese Zeit das starke Aufkommen von neuen Parteien im Parteiensystem, beispielsweise DIMAR (demokratische Linke), aber auch ANEL (rechtspopulistische Partei) (vgl. Tsatsanis et al. 2014, S. 524).
Diese Entwicklung hatte sich verstetigt, begünstigt durch die Finanzkrise und verbunden mit einer starken Abnahme des Vertrauens der Bevölkerung in das bestehende Parteiensystem (vgl. Verney 2014, S. 20 nach Tsatsanis et al. 2014, S. 524). Es taten sich gesellschaftlich mehrere, auch neue, Gräben auf, worauf auch Yanis Tsirbas hinwies: bezüglich des *Alters der Wählerschaft* (wobei SYRIZA unter jüngeren Wählern dominerte, ND unter den älteren), der *geographischen Herkunft* dieser (hier konnte SYRIZA die Stimmen v. a. der Stadtbevölkerung erringen, während ländliche Bereiche eher ND stimmten) und deren *sozialem Hintergrund* (mit mehr Stimmen für SYRIZA in ärmeren Bevölkerungsschichten) (vgl. Tsirbas 2016, S. 408; nach: Nikolakopoulos 2015 und Voulgaris und Nikolakopoulos 2014). Von den vielen neu ins System gekommenen Parteien zeichnete sich SYRIZA beginnend mit diesen Wahlen als neuer zentraler Spieler im griechischen Parteiensystem ab.
Weiterhin wurde in der Forschung konstatiert, dass diese Entwicklung sich auch im Zuge der Europawahl von 2014 weiter etablieren konnte. Zwar wurde ebenfalls angemerkt, dass auch zu diesem Zeitpunkt noch eine große Fluktuation von Wählern zwischen den Parteien stattfand, jedoch schon merklich weniger, als noch bei den Wahlgängen in Griechenland 2012. Dennoch befand sich das System auch hiernach noch nicht in einem kompletten Equilibrium (vgl. Teperoglou et al. 2015, S. 351). Die Spannungen der "Altparteien" PASOK und ND mit SYRIZA nahmen im Verlauf bis 2015 nur noch zu: Massenentlassungen und ein starker wirtschaftlicher Abschwung, sowie zunehmende Schulden bei der Europäischen Union, verbunden mit den dort geforderten Austeritätsmaßnahmen ließen die Spannungen wachsen, welche sich dann schließlich in der Europawahl von 2014 entluden (vgl. Rori 2016, S. 1324f.). Es wurde dabei aber in der Forschung festgehalten, dass zumindest der Dualismus von PASOK und ND, welche zuvor jahrzehntelang immer wieder in Ein-Parteien-Regierungen regieren konnten, aufgebrochen sei (vgl. Teperoglou et al. 2015, S. 351f.).
## Wahljahr 2015 und Populistenwahlen
Nun genauer zum Wahljahr 2015 in Griechenland, in dem es zu zwei Wahlen kam (im Januar und September des Jahres), aus denen in beiden Fällen SYRIZA als Sieger hervorgehen konnte. Regulär wäre es erst 2016 zu diesen Parlamentswahlen gekommen, jedoch wurden diese aufgrund der nicht geglückten Wahl eines ND-Ministers zum neuen Präsidenten vorgezogen. Sowohl SYRIZA als auch der spätere Koalitionspartner ANEL hatten sich geweigert, diesen gegenüber der amtierenden ND-PASOK-Regierung zu bestätigen, um ihrerseits von vorgezogenen Wahlen zu profitieren und gegen ein neues Memorandum der Troika vorzugehen. Vor dem Hintergrund der Europawahl 2014 und der stetig guten Umfrageergebnisse konnte davon ausgegangen werden, dass die linkspopulistische SYRIZA stärkste Kraft werden würde - mit 36,3% (149 von 300 Sitzen) konnte diese dann am Ende auch tatsächlich triumphieren, brauchte jedoch einen Koalitionspartner, um eine feste Mehrheit zu erreichen. Diesen fand sie in der rechtspopulistischen ANEL (2015 mit einem Ergebnis von 4,8% und 13 Sitzen) (vgl. Tsirbas 2016, S. 409).
Das Regierungsprogramm, welches von SYRIZA in der Koalition verfolgt werden sollte und mit welchem die Partei sich die Unterstützung der Bevölkerung in der Januar-Wahl sichern konnte, hatte sich, wie bereits erwähnt, zum Ziel gesetzt, ein neues Memorandum der Troika (bestehend aus IWF, EZB und EU-Kommission) und damit auch weitreichende Austeritäts- und Sparmaßnahmen, zu verhindern. Im von der ersten SYRIZA-ANEL-Koalition im Juli 2015 anberaumten Referendum über weitere EU-Hilfen empfahlen dann die beiden Regierungsparteien sowie die rechtsextreme Goldene Morgenröte der Bevölkerung, mit "Nein" zu stimmen - dagegen plädierten ND, PASOK und To Potami für die zusätzlichen Finanzhilfen. Das Ergebnis von 61% der Stimmen gegen die Finanzhilfen überraschte, jedoch entschloss sich das Kabinett Alexis Tsipras' dazu, dieses zu ignorieren, was zu einem parteiinternen Bruch führte - 43 SYRIZA-Abgeordnete entzogen der Regierung die Zustimmung zu diesen Zahlungen, was zu deren Handlungsunfähigkeit und damit zu Neuwahlen führen sollte (vgl. Markou 2017, S. 60f.).
## Regierungszeit der SYRIZA-ANEL-Koalition
## Ende der Koalition: Streit um Nordmazedonien
# Datengrundlage
<!-- Als grundlegende Daten für diese Untersuchung standen jene der Chapel Hill Expert Survey (CHES) zur Verfügung. Im Fall der Untersuchung zu Griechenland wurde hierfür auf die Daten aus dem Jahr 2014 zurückgegriffen, also im Jahr vor den beiden angesprochenen Wahlen. Für Italien wurde die aktuellste Untersuchung der CHES von 2019 verwendet. -->
<!-- Dass zwei zeitlich verschiedene Datensätze verwendet wurden hat den Grund, da die Partei ANEL im Datensatz 2019 nicht mehr enthalten war, weil sie nach den zweiten Neuwahlen nicht genug Stimmen erhielt und daher nicht mehr Teil des griechischen Parlamentes war. Diese Unterscheidung bringt jedoch auch die Problematik mit sich, dass nicht in jedem Fall auf die exakt gleichen Variablen zu den Parteipositionen kontrolliert werden konnte. -->
Die in vorliegender Arbeit genutzten Daten kommen aus der Populist and Political Parties Expert Survey (POPPA), einer Expertenumfrage, welche von Maurits Meijers und Andrej Zaslove im Rahmen der Populismusforschung der Radboud University durchgeführt wurde.
Innerhalb dieser Umfrage wurden Daten zu 250 Parteien aus 28 europäischen Staaten in den Themenbereichen Populismus, politischer Stil, Parteienideologie und Parteienorganisation gesammelt. Um diese zu erhalten, wurden zwischen April und Juli 2018 294 Experten aus den Ländern befragt. Die Studie eignet sich in vorliegendem Fall vor allem auch deswegen sehr gut als Datengrundlage zur Untersuchung, da es als Ziel weniger im Vordergrund stand, bestimmte Parteien als populistisch oder nicht populistisch zu klassifizieren, sondern es sollten bewusst die Einschätzungen von Experten zu den jeweiligen Parteien eingeholt werden. Aus diesen wurde dann unter anderem auch ein Datensatz mit den Mittelwerten der Einschätzungen aller Experten gebildet, welcher hier auch verwendet wird (vgl. Meijers/Zaslove 2020, S. 2).
Durch diese Daten ist eine einfache Vergleichbarkeit der untersuchten Parteien gegeben, um Aussagen über Unterschiede und Gemeinsamkeiten in den ideologisch und politisch bezogenen Positionen treffen zu können. Da hier der griechische Fall analysiert werden soll, wurden die Daten daraufhin noch gefiltert, damit auch nur dieser Fall behandelt werden kann.
In der POPPA Expert Survey wurde außerdem Wert der Variable *populism* betrachtet. Dabei handelt es sich um eine Operationalisierung des ideellen Ansatzes, basierend auf den folgenden fünf Ebenen (ausführlicher dazu vgl. Meijers/Zaslove 2020, S. 383-385):
+ Manichäische/s Weltbild bzw. Moralvorstellungen (*manichean*)
+ Homogenität des Volkes (*indivisible*)
+ Singulärer Wille des Volkes bzw. volonté générale (*general will*)
+ Souveränität sollte allein beim Volk liegen (*peoplecentrism*)
+ Anti-Elitismus (*antielitism*)
# SYRIZA-ANEL: Näheres zu den Parteien selbst und zur Regierungszusammenarbeit: Wie läuft diese ab?
+ Lassen sich die beobachteten Positionen in der realen Regierungsarbeit beobachten?
+ Wenn Unterschiede: kommt es deswegen zu Reibungen?
+ Wenn Gemeinsamkeiten: wie werden hier Sachen umgesetzt?
+ Allgemeine Bewertungen zur Regierungsarbeit?
+ Sind hier Werte zur Zufriedenheit der Bevölkerung vorhanden?
+ War die Arbeit erfolgreich oder erfolglos? Warum? Können solche heterogenen Koalitionen funktionieren?
-----------------------------
GRC
+ Wie kann man jeweils SYRIZA und ANEL charakterisieren?
+ SYRIZA = linkspopulistische Partei, die den Platz von PASOK als stärkste linke Kraft einnimmt
+ Erklären, warum die populistisch sind (anhand Positionen aus CHES oder auch POPPA-Umfrage)
+ ANEL = rechstpopulistische Partei, die ihre Argumentation schon aus der populistischen Ecke aufbaut (ethnische Volksabgrenzungen), aber nicht so rechtsextrem ist, wie die Goldene Morgenröte
+ Welche Motive der Zusammenarbeit gibt es?
+ einigendes Motiv: Krisennarrativ, Finanzkrise, Bailouts (vgl. Tsirbas 2016, S. 409)
+ unterschiedliche Interpretation von "wir" gg. "die" (Markou 2017, 63)
+ gemeinsamer Kampf gegen Memoranden und die Troika (Ebd.)
+ Woran scheitert das alles letztendlich?
+ Probleme sind ethnischer Natur: Mazedonien-Streitfrage
------------------------------
Nachdem nun in beiden Fällen auf den situativen Kontext eingegangen wurde, soll nun im Folgenden der bereits in der Einleitung aufgestellten Frage nachgegangen werden: Wie ist die Zusammenarbeit dieser heterogenen Regierungskoalitionen populistischer Parteien?
Dafür ist zunächst ein Blick auf die einzelnen Parteien nötig: inwiefern und auf welcher Grundlage können diese als populistisch bezeichnet werden und wie lassen sie sich politisch verorten? Außerdem werden hier die Standpunkte dieser Parteien zu bestimmten Themen anhand der Daten der POPPA Expert Survey miteinander abgeglichen, um eventuelle Gemeinsamkeiten und Unterschiede zu entdecken und anhand dessen Rückschlüsse über das jeweilige Ende der Koalitionen ziehen zu können.
Hierfür soll sich zunächst der Fall der griechischen Parteien SYRIZA und ANEL genauer betrachtet werden. Um deren Bewertungen auf der Populismus-Skala der POPPA-Expertenumfrage leicht überblicken zu können, wurde im Folgenden eine Graphik erstellt (Abbildung 1). Auf der Y-Achse wurde eben dieser Wert abgetragen, während auf der x-Achse zusätzlich der Wert auf einer Links-Rechts-Skala dargestellt wird, um diese in einem in der Forschung oft genutzten und bekannten Spektrum zu verorten.
```{r POPPA GRC: matrix of populism values and left right spectrum of parties, echo=FALSE, message=FALSE, warning=FALSE, paged.print=FALSE}
ggplot(data = poppa_GRC, aes(x = lroverall, y = populism)) +
geom_point() +
theme_minimal() +
geom_text(aes(label = party), hjust = 0.5, vjust = 1.5) +
geom_point(data = poppa_SYRIZA_ANEL, aes(x = lroverall, y = populism), colour = "red", size = 5) +
labs(title = "SYRIZA und ANEL im Raum zwischen Populismus und Links-Rechts-Verortung",
tag = "Abbildung 1",
caption = "Nach POPPA 2019",
x = "Links-Rechts-Verortung",
y = "Populismus (ideeller Ansatz)")
```
Dabei ist zunächst ersichtlich, dass die Annahme, es handele sich sowohl bei SYRIZA als auch bei ANEL um populistische Parteien, anhand der Daten aus der POPPA Expert Survey als bestätigt betrachtet werden kann: Sowohl SYRIZA (7,6) als auch ANEL (8,4) weisen bezüglich der Populismus-Skala einen hohen Wert auf. Allgemein wird auch ersichtlich: in Griechenland liegen sowohl auf der politisch linken als auch auf der politisch rechten Seite mehrere populistische Wahlalternativen vor. Die bereits im Abschnitt zur Ausgangslage in Griechenland angesprochenen Parteien ND, PASOK und To Potami, welche als pro-europäische Parteien beschrieben wurden, die anlässlich des Referendums über das dritte EU-Memorandum im Juli 2015 für "Ja" stimmen wollten, weisen allesamt niedrige Populismus-Werte auf und befinden sich im politischen Spektrum eher mittig.
Weiterhin geht auch aus der Graphik hervor, dass zwischen SYRIZA und ANEL im politischen Links-Rechts-Spektrum eine gewisse Distanz vorherrscht. Somit kann diese Regierung auch empirisch mit Hilfe der POPPA-Daten durchaus als populistisch und ideologisch heterogen gesehen werden.
### SYRIZA und ANEL: Was wirkte verbindend?
-----------------------------
+ *Politischer Stil*
+ hohe Werte beider Parteien was Populismus angeht - sowohl auf einzelnen Ebenen des ideellen Ansatzes, als auch insgesamt
+ beide mit emotionalisiertem Politikstil
+ Komplexität politischer Entscheidungen: typisch populistisch mit einfachen Lösungen für Probleme
+ *EU-Position*
+ beide sind nicht gerade EU-Enthusiasten
+ *Ökonomische Positionen?*
+ auffällig, dass zwar links und rechts angesiedelt, aber hier doch einige Überschneidungen
-----------------------------
Nachdem diese grundlegende Frage zur Einordnung der SYRIZA-ANEL-Koalitionen von 2015 als ideologisch heterogene zweier populistischer Parteien geklärt wurde, soll sich nun zunächst mit der Frage nach verbindenden Faktoren auseinandergesetzt werden.
```{r people centrism, echo=FALSE, message=FALSE, warning=FALSE, paged.print=FALSE}
### people centrism
ggplot(data = poppa_GRC, aes(x = peoplecentrism, y = party)) +
geom_point() +
theme_minimal() +
geom_text(aes(label = party), hjust = 0.5, vjust = 1.5) +
geom_point(data = poppa_SYRIZA_ANEL, aes(x = peoplecentrism, y = party), colour = "red", size = 5) +
labs(title = "SYRIZA und ANEL: Volk = alleiniger Souverän",
caption = "Nach POPPA 2019",
tag = "Abbildung 2",
x = "Volk = alleiniger Souverän",
y = "Partei")
```
# Fazit und Schlussbemerkungen
+ Zusammenfassend: Was trennt - was eint populistische Parteien an der Regierung?
+ Was kann noch gemacht werden in dem Bereich?
+ Konzept des inklusiven Populismus - gibt es "guten" Populismus?
# Literaturverzeichnis
+ Aslanidis, Paris; Rovira-Kaltwasser, Cristóbal (2016): *Dealing with populists in government: The SYRIZA-ANEL coalition in Greece*, Democratization, 23:6, S. 1077-1091.
+ Tsatsanis, Emmanouil; Teperoglou, Eftichia (2016): *Realignment under Stress: The July 2015 Referendum and the September Parliamentary Election in Greece*, South European Society and Politics, 21:4, S. 427-450.
+ Pappas, Takis; Aslanidis, Paris (2015): *Greek Populism: A Political Drama in Five Acts*, in: Kriesi, Hanspeter; Pappas, Takis (Hrsg.): *European Populism in the Shadow of the Great Recession*, ECPR Press, Colchester.
+ Tsatsanis, Emmanouil; Freire, André; Tsirbas, Yannis (2014): *The Impact of the Economic Crisis on the Ideological Space in Portugal and Greece: A Comparison of Elites and Voters*, South European Society and Politics, 19:4, S. 519-540.
+ Tsirbas, Yannis (2016): *The January 2015 Parliamentary Election in Greece: Government Change, Partial Punishment and Hesitant Stabilisation*, South European Society and Politics, 21:4, S. 407-426.
+ Mudde, Cas (2004): *The populist zeitgeist*, Government and Opposition, 39:4, S. 541-563.
+ Markou, Grigoris (2017): *The Rise of Inclusionary Populism in Europe: The Case of SYRIZA*, Contemporary Southeastern Europe, 4:1, S. 54-71.
+ Meijers, Maurits; Zaslove, Andrej (2020): *"Populism and Political Parties Expert Survey 2018 (POPPA)"*, https://doi.org/10.7910/DVN/8NEL7B, Harvard Dataverse, V1.
+ Meijers, Maurits; Zaslove, A. (2020): *Measuring Populism in Political Parties: Appraisal of a New Approach*, Comparative Political Studies, 54:2, S. 372-407.
# Abbildungsverzeichnis (wenn nötig)
# Eigenständigkeitserklärung
Ich erkläre hiermit, dass ich die Hausarbeit mit dem Titel *"Regierende Populisten und ideologische Heterogenität anhand der Beispiele Griechenland und Italien. Zusammenarbeit trotz oder Spaltung wegen politischer Differenzen?"* im Rahmen der Lehrveranstaltung "Politische Soziologie II: Soziokulturelle und ökonomische Ursachen des Populismus" unter der Leitung von Prof. Dr. Nils Steiner im Wintersemester 2020/2021 selbständig angefertigt, keine anderen Hilfsmittel als die im Quellen- und Literaturverzeichnis genannten benutzt und alle aus den Quellen und der Literatur wörtlich oder sinngemäß übernommenen Stellen als solche gekennzeichnet habe.
Bamberg, den 12.04.2021
Unterschrift Florian Wisniewski |
import { EffectsModule } from '@ngrx/effects';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { ReactiveFormsModule } from '@angular/forms';
import { reducer } from 'src/app/authModule/store/auth.reducers';
import { LoginComponent } from 'src/app/authModule/components/login/login.component';
import { RegisterComponent } from 'src/app/authModule/components/register/register.component';
import { RegisterEffect } from 'src/app/authModule/store/auth.effects';
export const AUTH_REDUCER_KEY = 'AUTH_REDUCER_KEY';
const routes = [
{
path: 'login',
component: LoginComponent,
},
{
path: 'register',
component: RegisterComponent,
},
];
@NgModule({
imports: [
CommonModule,
StoreModule.forFeature(AUTH_REDUCER_KEY, reducer),
EffectsModule.forFeature([RegisterEffect]),
RouterModule.forChild(routes),
ReactiveFormsModule,
],
declarations: [LoginComponent, RegisterComponent],
})
export class AuthModule {} |
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class RankTeams {
private static Map<String, TeamStats> teamStatsMap = new HashMap<>();
public static void main(String[] args) {
File file = new File("/Users/mt25190/GitHub/csvFormatter/VictiScout_2-8-24.csv");
try (Scanner scanner = new Scanner(file)) {
// Skip header
if (scanner.hasNextLine()) {
scanner.nextLine();
}
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] data = line.split(",");
String team = data[0];
int teleopNotesMade = data[9].isEmpty() ? 0 : Integer.parseInt(data[9]);
int teleopNotesInAmp = data[10].isEmpty() ? 0 : Integer.parseInt(data[10]);
TeamStats teamStats = teamStatsMap.getOrDefault(team, new TeamStats());
teamStats.addTeleopNotesMade(teleopNotesMade);
teamStats.addTeleopNotesInAmp(teleopNotesInAmp);
teamStatsMap.put(team, teamStats);
}
System.out.println("Team, Average Teleop Notes Made, Average Teleop Notes In Amp");
for (Map.Entry<String, TeamStats> entry : teamStatsMap.entrySet()) {
String team = entry.getKey();
TeamStats teamStats = entry.getValue();
System.out.println(team + ", " + teamStats.calculateAverageTeleopNotesMade() + ", " + teamStats.calculateAverageTeleopNotesInAmp());
}
} catch (FileNotFoundException e) {
System.out.println("Error! File not found: " + e.getMessage());
}
}
private static class TeamStats {
private int totalTeleopNotesMade = 0;
private int totalTeleopNotesInAmp = 0;
private int count = 0;
public void addTeleopNotesMade(int teleopNotesMade) {
totalTeleopNotesMade += teleopNotesMade;
count++;
}
public void addTeleopNotesInAmp(int teleopNotesInAmp) {
totalTeleopNotesInAmp += teleopNotesInAmp;
}
public double calculateAverageTeleopNotesMade() {
return count > 0 ? (double) totalTeleopNotesMade / count : 0;
}
public double calculateAverageTeleopNotesInAmp() {
return count > 0 ? (double) totalTeleopNotesInAmp / count : 0;
}
}
} |
<div class="container">
<%= form_for(resource, as: resource_name, url: session_path(resource_name), html: {class: "form-signin"}) do |f| %>
<h2 class="form-signin-heading"> Please sign in</h2>
<div class="field">
<%= f.label :email, 'Email Address', class 'sr-only' %>
<%= f.email_field :email, autofocus: true, class: 'form-control', placeholder 'Email Address'%>
</div>
<div class="field">
<%= f.label :password, 'Password', class: 'sr-only' %>
<%= f.password_field :password, autocomplete: "off", class: 'form-control', placeholder: 'Password' %>
</div>
<% if devise_mapping.rememberable? %>
<div class="field">
<label>
<%= f.check_box :remember_me, label: false %>
Remember me
</label>
</div>
<% end %>
<div class="actions">
<%= f.button "Sign in", class: 'btn btn-lg btn-primary btn-block' %>
<% end %>
</div> <!-- /container --> |
from fastapi import HTTPException, UploadFile, BackgroundTasks
from typing import List
from models import StatusEnum
from utils.app_exceptions import AppException
from cruds.submission import SubmissionCRUD
from services.main import AppService
from utils.service_result import ServiceResult
from schemas.submission import OrderIn, OrderEdit, RequestIn, RequestEdit, OfferIn, OfferEdit, FeedbackIn, \
FeedbackEdit, Feedback
import models
from cruds.user import UserCRUD
class OrderService(AppService):
async def create_order(self, data: OrderIn, user: models.user.Client, bg_tasks: BackgroundTasks):
order = await SubmissionCRUD(self.db).create_order(data, user, bg_tasks)
if not order:
return AppException.CreationException(detail='Не удалось создать заказ!')
return ServiceResult(order)
def get_order(self, id: int) -> ServiceResult:
order = SubmissionCRUD(self.db).get_order_by_id(id)
if not order:
return ServiceResult(AppException.NotFoundException(detail='Заказ не найден!'))
return ServiceResult(order)
def get_orders_by_client(self, client_id: int) -> ServiceResult:
orders = SubmissionCRUD(self.db).get_orders_by_client_id(client_id)
return ServiceResult(orders)
def get_orders_by_master(self, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
if not master:
return ServiceResult(AppException.NotFoundException('Мастер не найден!'))
orders = SubmissionCRUD(self.db).get_orders_by_master_username(master)
return ServiceResult(orders)
def patch_order(self, id: int, data: OrderEdit, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
new_order = SubmissionCRUD(self.db).update_order_by_id(id, data, master)
if not new_order:
return ServiceResult(AppException.NotFoundException('Not found!'))
return ServiceResult(new_order)
def finish_order(self, id: int, status: StatusEnum, user: models.user.Client) -> ServiceResult:
response = SubmissionCRUD(self.db).finish_order_by_id(id, status, user)
return ServiceResult(response)
def delete_order(self, id: int, user: models.user.Client) -> ServiceResult:
response = SubmissionCRUD(self.db).remove_order_by_id(id, user.id)
return ServiceResult(response)
class RequestService(AppService):
async def create_request(self, data: RequestIn, user: models.user.Client, bg_tasks: BackgroundTasks,
files: List[UploadFile]) -> ServiceResult:
request = await SubmissionCRUD(self.db).create_request(data, user, bg_tasks, files)
if not request:
return ServiceResult(AppException.NotFoundException('Not found!'))
return ServiceResult(request)
def get_request(self, id: int) -> ServiceResult:
request = SubmissionCRUD(self.db).get_request_by_id(id)
if not request:
return ServiceResult(AppException.NotFoundException('Заявка не найдена!'))
return ServiceResult(request)
def get_requests(self, user_id: int) -> ServiceResult:
requests = SubmissionCRUD(self.db).get_requests(user_id)
return ServiceResult(requests)
def get_requests_by_master(self, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
requests = SubmissionCRUD(self.db).get_requests_by_master_username(master)
return ServiceResult(requests)
def get_requests_by_client_id(self, client_id: int) -> ServiceResult:
requests = SubmissionCRUD(self.db).get_requests_by_client_id(client_id)
return ServiceResult(requests)
def patch_request(self, id: int, data: RequestEdit, user_id: int) -> ServiceResult:
request = SubmissionCRUD(self.db).update_request_by_id(id, data, user_id)
if not request:
return ServiceResult(AppException.NotFoundException('Заявка не найдена!'))
return ServiceResult(request)
def complete_request(self, id: int, user: models.user.Client, status: StatusEnum) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
response = SubmissionCRUD(self.db).complete_request_by_id(id, master, status)
return ServiceResult(response)
def delete_request(self, id: int, user_id: int) -> ServiceResult:
response = SubmissionCRUD(self.db).remove_request_by_id(id, user_id)
return ServiceResult(response)
class OfferService(AppService):
def create_offer(self, data: OfferIn, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
offer = SubmissionCRUD(self.db).create_offer(data, master.username)
if not offer:
return ServiceResult(AppException.NotFoundException('Not found!'))
return ServiceResult(offer)
def get_offer(self, request_id: int, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
offer = SubmissionCRUD(self.db).get_offer_by_submission(request_id, master.username)
if not offer:
return ServiceResult(AppException.NotFoundException('Предложение не найдено!'))
return ServiceResult(offer)
def get_offers_by_submission(self, request_id: int):
offers = SubmissionCRUD(self.db).get_offers_by_submission(request_id)
return ServiceResult(offers)
def get_offers_by_master(self, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
offers = SubmissionCRUD(self.db).get_offers_by_master(master.username)
return ServiceResult(offers)
def patch_offer(self, id: int, data: OfferEdit, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
offer = SubmissionCRUD(self.db).update_offer_by_id(id, data, master.username)
if not offer:
return ServiceResult(AppException.NotFoundException('Предложение не найдено!'))
return ServiceResult(offer)
def accept_offer(self, id: int, user: models.user.Client) -> ServiceResult:
response = SubmissionCRUD(self.db).accept_offer(id, user)
return ServiceResult(response)
def delete_offer(self, id: int, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
response = SubmissionCRUD(self.db).delete_offer_by_id(id, master.username)
return ServiceResult(response)
class FeedbackService(AppService):
def create_feedback(self, data: FeedbackIn, user_id: int, pictures: List[UploadFile] = None) -> ServiceResult:
feedback = SubmissionCRUD(self.db).create_feedback(data, user_id, pictures)
if not feedback:
return ServiceResult(AppException.NotFoundException('Not found!'))
return ServiceResult(feedback)
def get_feedback(self, offer_id: int | None, order_id: int | None, user: models.user.Client) -> ServiceResult:
try:
master = UserCRUD(self.db).get_master_by_client(user)
master_username = master.username
except HTTPException:
master_username = None
feedback = SubmissionCRUD(self.db).get_feedback_by_offer(offer_id, order_id, user.id, master_username)
return ServiceResult(feedback)
def get_feedbacks(self, master_username: str) -> ServiceResult:
feedbacks = SubmissionCRUD(self.db).get_feedbacks_by_master(master_username)
new_feedbacks = list()
for feedback in feedbacks:
pydantic_feedback = Feedback(**feedback.__dict__)
pydantic_feedback.client_avatar = feedback.client.avatar
pydantic_feedback.client_name = feedback.client.name
pydantic_feedback.client_lastname = feedback.client.lastname
pydantic_feedback.master_name = feedback.master.client.name
pydantic_feedback.master_lastname = feedback.master.client.lastname
pydantic_feedback.master_avatar = feedback.master.client.avatar
new_feedbacks.append(pydantic_feedback)
return ServiceResult(new_feedbacks)
def patch_feedback(self, id: int, data: FeedbackEdit, user: models.user.Client) -> ServiceResult:
master = UserCRUD(self.db).get_master_by_client(user)
new_feedback = SubmissionCRUD(self.db).update_feedback_by_id(id, data, master)
return ServiceResult(new_feedback)
def delete_feedback(self, id: int, user_id: int) -> ServiceResult:
response = SubmissionCRUD(self.db).delete_feedback_by_id(id, user_id)
return ServiceResult(response) |
package com.example.address.web;
import com.example.address.domain.dto.AddressRequestDto;
import com.example.address.domain.dto.AddressResponseDto;
import com.example.address.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping(value = "/v1/address", produces = "application/json")
@RequiredArgsConstructor
public class AddressController {
public final AddressService addressService;
private static final Logger logger = LoggerFactory.getLogger(AddressController.class);
@GetMapping("")
public Flux<AddressResponseDto> findAllActive(){
return this.addressService.findAllActive();
}
@GetMapping("/inactive")
public Flux<AddressResponseDto> findAllInactive(){
return this.addressService.findAllInactive();
}
@GetMapping(value = "/{id}")
public Mono<AddressResponseDto> finById(@PathVariable Integer id){
return this.addressService.findById(id);
}
@GetMapping(value = "/adolescente/{id}")
public Flux<AddressResponseDto> finByIdAdolescent(@PathVariable Integer id){
return this.addressService.findByIdAolescent(id);
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping()
public Mono<AddressResponseDto> create(@RequestBody AddressRequestDto dto){
dto.setActive("A");
return this.addressService.create(dto);
}
@PutMapping(value = "/{id}")
public Mono<AddressResponseDto> update(@RequestBody AddressRequestDto dto, @PathVariable Integer id){
return this.addressService.update(dto,id);
}
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/{id}")
public Mono<Void> delete(@PathVariable Integer id){
return this.addressService.delete(id);
}
} |
// main.rain file
//
// This is file for showcasing the syntax of my programming language aka. Rain.
// Syntax is inspired from many languages, heavily Jai, Javascript, C++, and Wren.
//
// Enjoy!
/// Main function, everything starts from here:
main :: () {
println("Hello world!")
return 0
}
/// Comments:
// In rain we accept only line comments: `// comment`
/// Variables:
// Mutuable variable
x := 5
// Constant
y :: 6
// Specify variable like this:
foo: int = 65
bar := float(3) // will be turned into 3.0
// You can initliaze more variables in same line:
x := 5, y := 5
/// Functions:
hello :: (name) {
println("Hello ${name}!")
}
hello("Sky") // > "Hello Sky!"
// squared2 :: (x) {
// return x ** 2
// }
// In Rain if you want to just straight up return the value (with calculations or not), just write it, and forget the return keyword:
squared :: (x) {
x ** 2
}
// This could be useful if you want just to return a value
// and that you don't want to run anything before that return statement
println("The squared of 5 is: ${squared(5)}") // > "The squared of 5 is: 25"
// Optional arguments need a default value (like you can see on y argument), and if you want you want specify what return value will be, just add the variable type after parantheses:
squared_by :: (x, y = 2) int {
return x ** y
}
/// Arrays:
numbers := [0, 1, 2, 3, 4]
names : string[5] = []
names[0] = "Evry"
names[1] = "Daniel"
names[2] = "Chandler"
/// Objects:
z :: object {
"foo": 1,
"bar": x
"baz": 2
}
/// Structs:
Vector2 :: struct
{
x: int;
y: int;
}
a := Vector2 { 6, 5 }
println(a.x) // > 6
println(a) // > Vector2 { x: 6, y: 5 }
// Functions for structs:
Vector2 : magnitude : () {
return int(sqrt(this.x * this.x + this.y * this.y));
}
println(a.magnitude()) // > 7.8
/// Fibers:
// Create a fiber like this:
foo :: fiber {
println("Fiber called")
}
// And call it:
foo.call() // > "Fiber called!"
// Yielding:
bar :: fiber {
println("passed to yield: {foo.call()}")
}
foo.yield("hello, world!") // > "passed to yield: hello, world!"
/// Operators:
// `::`:
// Initializator or `::` can be used to create a function, a struct or an constant that like a struct and function can't be modified after creation.
// You can specify the constants' variable type before the second `:`:
x: int : 5
// It's possible to initialize a function inside of a struct by giving it the function name after the first colon (`:`), and after that
StructName : FuncName : () {
// do something...
}
// `:=`:
// The second initializator (`:=`) also known as walrus operator, creates a modifiable variable:
x := 5
// You can specify the variable type before the `=` operator:
x: int = 5
x: int[] = []
/// Import and Modules
// in file.rain:
pub foo :: () {
println("foo");
}
// in main.rain file:
#import "file.rain"
main :: () {
foo()
}
/// Condtional statements
// If statmenet
x := 5
y := 3
if (x == y + 2) {
// true
} else {
// false
}
// for statement
// for can be used to loop trought arrays:
number := [0, 1, 2, 3, 4, 5]
for num in numbers {
println(num)
}
names := ["Sam", "Peter"]
for i, name in names {
println("{i}) {name}")
// > 0) Sam
// 1) Peter
}
// range numbers
for i in 0 .. 5 {
print(i)
}
// > 01234
// or condtional looping, also known as `while` loop in other languages
sum := 0
i := 0
for i <= 100 {
sum += i
i++
}
println(sum) // > 5050
/// References and heap
x := 6 |
package or.common;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.config.Config;
import com.reporting.Reporter;
import com.reporting.STATUS;
import com.selenium.CustomExceptionHandler;
import com.selenium.ReactTable;
import com.selenium.WebPage;
import com.selenium.webdriver.DriverFactory;
import com.util.Util;
/**
* this class will hold the objects common to Finance manager application
*
* @author Shailendra 31-Aug-2020
*/
public class UamCommon {
private WebPage com;
private ReactTable rt;
public UamCommon() {
PageFactory.initElements(DriverFactory.getDriver(), this);
com = new WebPage();
rt = new ReactTable(reactTable);
}
public By reactTable = By.xpath("//div[contains(@class,'ReactTable')]");
@FindBy(xpath = "//span[contains(@class,'left')]/..")
public WebElement icon_PreviousPage;
@FindBy(xpath = "//input[@aria-label='jump to page']")
public WebElement txt_PageNumber;
@FindBy(xpath = "//span[@class='-totalPages']")
public WebElement data_TotalPages;
@FindBy(xpath = "//select[@aria-label='rows per page']")
public WebElement select_RowsPerPage;
@FindBy(xpath = "//span[contains(@class,'right')]/..")
public WebElement icon_NextPage;
@FindBy(xpath = "//div[contains(@class,'ellipsis')]")
public WebElement icon_Loader;
@FindBy(xpath = "//div[.='No rows found']")
public WebElement data_NoDataFound_Msg;
@FindBy(xpath = "//div[.='Loading...']")
public WebElement data_LoadingText;
/**
* this method will verify the UI of pagination page objects
*
* @author Shailendra 31-Aug-2020
*/
public void verifyPaginationUi() {
Reporter.NODE("Pagination objects");
com.isElementPresent(icon_PreviousPage, "icon_PreviousPage");
com.isElementPresent(txt_PageNumber, "text_PageNumber");
com.isElementPresent(select_RowsPerPage, "select_RowsPerPage");
com.isElementPresent(data_TotalPages, "data_TotalPages");
com.isElementPresent(icon_NextPage, "icon_NextPage");
}
/**
* This method will verify the passed column String data is sorted in Ascending
* order or not It will verify maximum 5 rows
*
* @author Shailendra 04-Sep-2020
*/
public void verifyAscendingSort_Number(int colNum) {
verifySort_Number(colNum, null);
}
/**
* This method will verify the passed column String data is sorted in Ascending
* order or not It will verify maximum 5 rows
*
* @author Shailendra 04-Sep-2020
*/
public void verifyAscendingSort_String(int colNum) {
verifySort_String(colNum, null);
}
/**
* This method will verify the passed column String data is sorted in Descending
* order or not It will verify maximum 5 rows
*
* @author Shailendra 04-Sep-2020
*/
public void verifyDescendingSort_String(int colNum) {
verifySort_String(colNum, Collections.reverseOrder());
}
/**
* This method will verify the passed column String data is sorted in Descending
* order or not It will verify maximum 5 rows
*
* @author Shailendra 04-Sep-2020
*/
public void verifyDescendingSort_Number(int colNum) {
verifySort_Number(colNum, Collections.reverseOrder());
}
/**
* This method will verify the passed column Date data is sorted in Ascending
* order or not It will verify maximum 5 rows
*
* @author Shailendra 04-Sep-2020
*/
public void verifyAscendingSort_Date(int colNum) {
verifySort_Date(colNum, null);
}
/**
* This method will verify the passed column Date data is sorted in Descending
* order or not It will verify maximum 5 rows
*
* @author Shailendra 04-Sep-2020
*/
public void verifyDescendingSort_Date(int colNum) {
verifySort_Date(colNum, Collections.reverseOrder());
}
/**
* Will verify the ascending and descending sorting on the passed String column
*
* @author Shailendra 04-Sep-2020
*/
private void verifySort_Number(int colNum, Comparator<Object> comparator) {
String sortType = "";
int rows = rt.getRowCount();
int counter = 5;
if (rows < counter) {
counter = rows;
}
List<BigDecimal> dataList = new ArrayList<BigDecimal>();
for (int row = 2; row <= counter; row++) {
String temp = rt.getCellText(row, colNum);
dataList.add(Util.BD(temp));
}
List<BigDecimal> dataListSorted = new ArrayList<BigDecimal>();
dataListSorted.addAll(dataList);
if (comparator == null) {
Collections.sort(dataListSorted);
sortType = "Ascending";
} else {
Collections.sort(dataListSorted, comparator);
sortType = "Descending";
}
boolean flag = false;
for (int i = 0; i < dataList.size(); i++) {
if (!dataListSorted.get(i).equals(dataList.get(i))) {
flag = true;
break;
}
}
if (flag) {
Reporter.FAIL(sortType + " Sort on Numbers failed, Expected data " + dataListSorted + " actual data " + dataList);
} else {
Reporter.PASS(sortType + " Sort on Numbers is working, Expected data " + dataListSorted
+ " actual data " + dataList);
}
}
/**
* Will verify the ascending and descending sorting on the passed String column
*
* @author Shailendra 04-Sep-2020
*/
private void verifySort_String(int colNum, Comparator<Object> comparator) {
String sortType = "";
int rows = rt.getRowCount();
int counter = 5;
if (rows < counter) {
counter = rows;
}
List<String> dataList = new ArrayList<String>();
for (int row = 2; row <= counter; row++) {
dataList.add(rt.getCellText(row, colNum));
}
List<String> dataListSorted = new ArrayList<String>();
dataListSorted.addAll(dataList);
if (comparator == null) {
Collections.sort(dataListSorted);
sortType = "Ascending";
} else {
Collections.sort(dataListSorted, comparator);
sortType = "Descending";
}
boolean flag = false;
for (int i = 0; i < dataList.size(); i++) {
if (!dataListSorted.get(i).equals(dataList.get(i))) {
flag = true;
break;
}
}
if (flag) {
Reporter.FAIL(sortType + " Sort on Strings failed, Expected data " + dataListSorted + " actual data " + dataList);
} else {
Reporter.PASS(sortType + " Sort on Strings is working, Expected data " + dataListSorted
+ " actual data " + dataList);
}
}
/**
* Will verify the ascending and descending sorting on the passed Date column
*
* @author Shailendra 04-Sep-2020
*/
private void verifySort_Date(int colNum, Comparator<Object> comparator) {
com.waitForElementTobe_NotVisible(icon_Loader);
String sortType = "";
int rows = rt.getRowCount();
int counter = 5;
if (rows < counter) {
counter = rows;
}
List<Date> dataList = new ArrayList<Date>();
for (int row = 2; row <= counter; row++) {
String data = rt.getCellText(row, colNum);
dataList.add(Util.getDate_AsDate("dd/MM/yyyy", data));
}
List<Date> dataListSorted = new ArrayList<Date>();
dataListSorted.addAll(dataList);
if (comparator == null) {
Collections.sort(dataListSorted);
sortType = "Ascending";
} else {
Collections.sort(dataListSorted, comparator);
sortType = "Descending";
}
boolean flag = false;
for (int i = 0; i < dataList.size(); i++) {
if (!dataListSorted.get(i).equals(dataList.get(i))) {
flag = true;
break;
}
}
if (flag) {
Reporter.FAIL(sortType + " Sort on Date failed, Expected data " + dataListSorted + " actual data " + dataList);
} else {
Reporter.PASS(sortType + " Sort on Date is working, Expected data " + dataListSorted
+ " actual data " + dataList);
}
}
/**
* Will verify the pagination buttons func
*
* @author Shailendra 07-Sep-2020
*/
public void verifyPaginationFunc() {
Reporter.NODE("Verifying the pagination func");
// checking the prev icon is disabled
com.verifyObjectIsDisabled(icon_PreviousPage, "icon_PreviousPage");
// Getting the page count
String pageCountData = com.getText(data_TotalPages);
int pageCount = Integer.parseInt(pageCountData);
if (pageCount > 1) {
// Checking the next link, on clicking it, prev icon will be enabled and page
// number will increase by 1
String currentPageData = com.getAttribute(txt_PageNumber, "value");
int currentPage_Before = Integer.parseInt(currentPageData);
com.click(icon_NextPage, "icon_NextPage");
com.wait(2);
com.verifyObjectIsEnabled(icon_PreviousPage, "icon_PreviousPage");
currentPageData = com.getAttribute(txt_PageNumber, "value");
int currentPage_After = Integer.parseInt(currentPageData);
if (currentPage_After == (currentPage_Before + 1)) {
Reporter.PASS( "Current Page counter is increased by 1");
} else {
Reporter.FAIL( "Current Page counter is NOT increased by 1");
}
// Checking the Jump to page, by going to last page and checking the next button
// is disabled.
com.sendKeys("txt_PageNumber", txt_PageNumber, pageCountData, Keys.ENTER);
com.wait(2);
com.verifyObjectIsDisabled(icon_NextPage, "icon_NextPage");
// checking the Prev page button and page number will decrease by 1
currentPageData = com.getAttribute(txt_PageNumber, "value");
currentPage_Before = Integer.parseInt(currentPageData);
com.click(icon_PreviousPage, "icon_PreviousPage");
com.wait(2);
currentPageData = com.getAttribute(txt_PageNumber, "value");
currentPage_After = Integer.parseInt(currentPageData);
if (currentPage_After == (currentPage_Before - 1)) {
Reporter.PASS( "Current Page counter is decreased by 1");
} else {
Reporter.FAIL( "Current Page counter is NOT decreased by 1");
}
// checking the rows per page func
int rowCount_Before = rt.getRowCount();
com.selectByVisibleText(select_RowsPerPage, "100 rows", true);
com.wait(2);
int rowCount_After = rt.getRowCount();
if (rowCount_After > rowCount_Before) {
Reporter.PASS( "Rows Per page dropdown is working fine, ROWS COUNT Before "
+ rowCount_Before + " ROWS COUNT After " + rowCount_After);
} else {
Reporter.FAIL( "Rows Per page dropdown is NOT working fine, ROWS COUNT Before "
+ rowCount_Before + " ROWS COUNT After " + rowCount_After);
}
} else {
Reporter.FAIL( "Page does not have data for checking pagination functionality");
}
}
/**
* This will click on the date field to open the calendar, then it will select
* the passed date value
*
* @param text_Date WebElement/By object
* @param date string should be in dd/MM/YYYY format only
* @author Shailendra 09-Sep-2020
*/
public void selectDate(Object text_Date, String date) {
if (date == null || "".equals(date)) {
return;
}
String sep = "/";
By button_Next = By.xpath("//button[contains(.,'Next Month')]");
By button_Prev = By.xpath("//button[contains(.,'Previous Month')]");
By data_CurrentMonth = By.xpath("//div[contains(@class,'current-month')]");
// Clicking on Date field, to open calendar
com.click(text_Date);
com.wait(.5);
try {
// From the passed date String, getting the numeric day, month, and year values
int passedDay = Integer.parseInt(date.split(sep)[0]);
int passedMonth = Integer.parseInt(date.split(sep)[1]) - 1;
int passedYear = Integer.parseInt(date.split(sep)[2]);
// Creating dynamic xpath to select day from visible calendar [month year]
By day_Xpath = By.xpath(
"//div[contains(@class,'day')][contains(@aria-label,'day')][not(contains(@class,'outside'))][.='"
+ passedDay + "']");
// reading the currently displayed default month and year from calendar
String currentMonthFromCal = com.getText(data_CurrentMonth);
// converting the String month and year values to number
int currentMonthIndex = getMonthIndex(currentMonthFromCal.split(" ")[0]);
int currentYear = Integer.parseInt(currentMonthFromCal.split(" ")[1]);
// Now getting the difference in year to calculate how many clicks required on
// Next icon
if (passedYear > currentYear) {
int yearDiff = passedYear - currentYear;
if (yearDiff > 0) {
int loopCount = (11 - currentMonthIndex) + 12 * (yearDiff - 1) + 1;
for (int i = 0; i < loopCount; i++) {
com.click(button_Next);
}
}
} else {
int yearDiff = currentYear - passedYear;
if (yearDiff > 0) {
int loopCount = (currentMonthIndex + 1) * yearDiff;
for (int i = 0; i < loopCount; i++) {
com.click(button_Prev);
}
}
}
// After selecting the passed year, getting the current shown month to calculate
// clicks for going to passed month
currentMonthFromCal = com.getText(data_CurrentMonth);
currentMonthIndex = getMonthIndex(currentMonthFromCal.split(" ")[0]);
if (passedMonth > currentMonthIndex) {
int monthDiff = passedMonth - currentMonthIndex;
if (monthDiff > 0) {
for (int i = 0; i < monthDiff; i++) {
com.click(button_Next);
}
}
} else {
int monthDiff = currentMonthIndex - passedMonth;
if (monthDiff > 0) {
for (int i = 0; i < monthDiff; i++) {
com.click(button_Prev);
}
}
}
// Now we have reached to the desired month and year, selecting the valid day
// from the shown calendar
com.wait(1);
com.click(day_Xpath, "Date [" + date + "]");
} catch (Exception e) {
new CustomExceptionHandler(e, date);
}
}
/**
* This method returns the index of passed string month, used in selectDate
* method
*
* @author Shailendra 09-Sep-2020
*/
private int getMonthIndex(String monthName) {
switch (monthName) {
case "January":
return 0;
case "February":
return 1;
case "March":
return 2;
case "April":
return 3;
case "May":
return 4;
case "June":
return 5;
case "July":
return 6;
case "August":
return 7;
case "September":
return 8;
case "October":
return 9;
case "November":
return 10;
case "December":
return 11;
default:
Reporter.FAIL( "Invalid Input " + monthName + " to getMonthIndex method");
return 0;
}
}
/**
* This method will verify the passed success message is displayed or not with
* timeout in seconds
*
* @author Shailendra 10-Sep-2020
*/
public String verifySuccessMessage(String msgTxt, long wait) {
By xp = By.xpath("//div[@role='alert'][contains(.,'" + msgTxt + "')]");
com.waitForElementTobe_Visible(xp, wait,
"Success Message [" + msgTxt + "]");
return com.getText(xp);
}
/**
* without timeout
*
* @author adarsh 22 nov 2022
*/
public String verifySuccessMessage(String msgTxt) {
return verifySuccessMessage(msgTxt, Config.WAIT_EXPLICIT);
}
/**
* This method will upload the passed file path
*
* @author Shailendra 11-Sep-2020
*/
public void uploadFile(Object inputFileUploadObject, String absFilePath) {
try {
if (inputFileUploadObject instanceof By) {
((JavascriptExecutor) DriverFactory.getDriver()).executeScript("arguments[0].className='';arguments[0].style='';",
com.findElement((By) inputFileUploadObject));
} else {
((JavascriptExecutor) DriverFactory.getDriver()).executeScript("arguments[0].className='';arguments[0].style='';",
(WebElement) inputFileUploadObject);
}
com.sendKeys(inputFileUploadObject, absFilePath);
} catch (Exception e) {
new CustomExceptionHandler(e, inputFileUploadObject.toString() + "|" + absFilePath);
}
}
} |
import React from "react";
import { animated } from "react-spring";
import createAnimation from "./createAnimation";
import HistoryViewer from "./HistoryViewer";
import { formatForArray } from "./formatFunctions";
function ArrayAnimation({ numbers, colors, pointers, springs, api, boxWidth, boxSpacing, currentAction, nextStep, prevStep,
toggleHistory, showHistory, history}) {
const totalWidth = numbers.length * boxWidth + (numbers.length - 1) * boxSpacing;
const isOverlapping = (index1, index2) => index1 === index2;
return (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", margin: "20px" }}>
<div style={{ border: "1px solid #ccc", padding: "10px", borderRadius: "4px", backgroundColor: "#f5f5f5" }}>
<div style={{ fontWeight: "bold", marginBottom: "5px" }}>
Pointers Information
</div>
<div>pivot - pointer to the pivot element</div>
<div>A[p .. r] is the actual subarray</div>
<div>A[p .. i - 1] contains elements less or equal to the pivot</div>
<div>A[i .. j - 1] contains elements greater or equal to the pivot</div>
<div>A[j .. (r - 1)] contains the unprocessed elements</div>
</div>
<p>Steps:</p>
<div style={{ position: "relative", width: `${totalWidth}px`, display: "flex", justifyContent: "center", marginBottom: "70px", marginTop: "20px"}}>
{springs.map((props, idx) => (
<React.Fragment key={idx}>
<animated.div
style={{
...props,
width: `${boxWidth}px`,
height: `${boxWidth}px`,
display: "flex",
alignItems: "center",
justifyContent: "center",
position: "absolute",
left: `${idx * (boxWidth + boxSpacing)}px`,
fontSize: `${boxWidth / 3}px`,
border: "1px solid #ccc",
borderRadius: "4px",
boxShadow: "1px 1px 3px rgba(0,0,0,0.4)",
backgroundColor: `${colors[idx]}`,
}}> {numbers[idx]}
</animated.div>
</React.Fragment>
))}
{Object.entries(pointers).map(([key, index]) => {
if (index === null) return null;
const isPivot = key === "pivot";
const pivotIndex = pointers["pivot"];
const isJ = key === "j";
const isP = key === "p";
const isR = key === "r";
const isI = key === "i";
let pointerLeft = `${ index * (boxWidth + boxSpacing) + boxWidth / 2}px`;
if ( isJ && pivotIndex !== undefined && isOverlapping(index, pivotIndex)) {
pointerLeft = `${index * (boxWidth + boxSpacing) + boxWidth / 2 - boxWidth / 3}px`;
} else if ( isPivot && pointers["j"] !== undefined && isOverlapping(index, pointers["j"])) {
pointerLeft = `${index * (boxWidth + boxSpacing) + boxWidth / 2 + boxWidth / 3}px`;
}
let pointerTop;
if (isJ || isPivot) {
pointerTop = "-20px";
} else if (isI) {
pointerTop = `${boxWidth}px`;
} else if (isP || isR) {
pointerTop = "70px";
} else {
pointerTop = "0px";
}
return (
<animated.div
key={key}
style={{
position: "absolute",
top: pointerTop,
left: pointerLeft,
width: `${boxWidth / 1.7}px`,
height: `${boxWidth / 2.5}px`,
fontSize: `${boxWidth / 4.2}px`,
backgroundColor: isP || isR ? "#B0C4DE" : "#72A0C1",
color: "white",
transform: "translateX(-50%)",
display: "flex",
alignItems: "center",
justifyContent: "center",
boxShadow: "1px 1px 3px rgba(0,0,0,0.4)",
borderRadius: "4px",
transition: "left 300ms, width 300ms, height 300ms, font-size 300ms",
}}> {key}
</animated.div>
);
})}
</div>
<div style={{ display: "flex", justifyContent: "center", fontSize: "16px", color: "darkslategray", marginTop: "20px"}}>
{currentAction}
</div>
<div style={{ marginTop: "20px" }}>
<button onClick={prevStep} disabled={history.length === 0}> Previous </button>
<button onClick={nextStep} disabled={nextStep === null}> Next </button>
</div>
<button onClick={toggleHistory} disabled={history.length === 0}> View History </button>
{showHistory && <HistoryViewer history={history} dataStructure="array" />}
</div>
);
}
export default createAnimation(ArrayAnimation, formatForArray); |
#pragma once
#include <cstddef>
#include <limits>
struct LinearProbing
{
static constexpr std::size_t next(const std::size_t start, const std::size_t step, const std::size_t size) noexcept
{
return (start + step) & (size - 1);
}
};
struct QuadraticProbing
{
static constexpr std::size_t next(std::size_t start, std::size_t step, std::size_t size) noexcept
{
if ((size & (size - 1)) == 0) { // Is size is power of 2, then we can choose coefficients that will avoid ending up in cycle
return (start + ((step * step + step) >> 1)) & (size - 1);
}
return (start + step * step) % size;
}
};
struct MaskRangeHashing
{
static constexpr std::size_t hash(const std::size_t index, const std::size_t size) noexcept
{
return index & (size - 1);
}
};
struct Power2RehashPolicy
{
static constexpr float max_load_factor() noexcept
{
return 0.5;
}
static constexpr bool need_rehash(const std::size_t size, const std::size_t bucket_count) noexcept
{
return size > (bucket_count >> 1);
}
static constexpr std::size_t buckets_number(const std::size_t desired_size) noexcept
{
return desired_size << 1;
}
static constexpr std::size_t new_size(const std::size_t desired_size, std::size_t current_size = 64) noexcept
{
while (current_size < desired_size) {
current_size <<= 1;
}
return current_size;
}
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Examples</title>
<link rel="stylesheet" href="css/flex-styles.css" />
<link rel="stylesheet" href="css/styles.css" />
<script src="js/controls.js"></script>
</head>
<body>
<div id="example-selection">
<input type="radio" id="example-general" name="example-type" value="General" checked="selected" />
<label for="example-general">General</label>
<input type="radio" id="example-grow-shrink-basis" name="example-type" value="Grow/Shrink/Basis">
<label for="example-general">Grow/Shrink/Basis</label>
</div>
<div id="flex-container">
<div class="flex-item" id="item-1">Flex!</div>
<div class="flex-item" id="item-2">Flex!</div>
<div class="flex-item" id="item-3">Flex!</div>
<div class="flex-item" id="item-4">Flex!</div>
</div>
<div id="general-section">
<div id="general-inputs">
<label for="flex-dir">flex-direction</label>
<select id="flex-dir">
<option value="row" selected>row</option>
<option value="column">column</option>
<option value="row-reverse">row-reverse</option>
<option value="column-reverse">column-reverse</option>
</select>
<label for="justify-val">justify-content</label>
<select id="justify-val">
<option value="flex-start" selected>flex-start</option>
<option value="flex-end">flex-end</option>
<option value="center">center</option>
<option value="space-between">space-between</option>
<option value="space-around">space-around</option>
<option value="space-evenly">space-evenly</option>
</select>
<label for="align-val">align-items</label>
<select id="align-val">
<option value="flex-start" selected>flex-start</option>
<option value="flex-end">flex-end</option>
<option value="center">center</option>
<option value="stretch">stretch</option>
</select>
</div>
</div>
</div>
<div id="grow-shrink-basis-section" class="hide">
<div id="wrap-input">
<label for="wrap-val">Wrap: </label>
<select id="wrap-val">
<option value="nowrap">nowrap</option>
<option value="wrap">wrap</option>
<option value="wrap-reverse">wrap-reverse</option>
</select>
</div>
<div id="inputs">
<div id="blue-inputs">
<label for="blue-grow" class="input-label">Grow:</label>
<input id="blue-grow" value="0" type="number" />
<label for="blue-grow" class="input-label">Shrink:</label>
<input id="blue-shrink" value="0" type="number" />
<label for="blue-grow" class="input-label">Basis:</label>
<input id="blue-basis" value="auto" type="text" />
</div>
<div id="red-inputs">
<label for="red-grow" class="input-label">Grow:</label>
<input id="red-grow" value="0" type="text" />
<label for="red-grow" class="input-label">Shrink:</label>
<input id="red-shrink" value="0" type="text" />
<label for="red-grow" class="input-label">Basis:</label>
<input id="red-basis" value="auto" type="text" />
</div>
<div id="green-inputs">
<label for="green-grow" class="input-label">Grow:</label>
<input id="green-grow" value="0" type="text" />
<label for="green-grow" class="input-label">Shrink:</label>
<input id="green-shrink" value="0" type="text" />
<label for="green-grow" class="input-label">Basis:</label>
<input id="green-basis" value="auto" type="text" />
</div>
<div id="purple-inputs">
<label for="purple-grow" class="input-label">Grow:</label>
<input id="purple-grow" value="0" type="text" />
<label for="purple-grow" class="input-label">Shrink:</label>
<input id="purple-shrink" value="0" type="text" />
<label for="purple-grow" class="input-label">Basis:</label>
<input id="purple-basis" value="auto" type="text" />
</div>
<div id="clear-inputs">
<div class="clear-btn">
<label for="clear-grows">Grow:</label>
<button id="clear-grows">Clear</button>
</div>
<div class="clear-btn">
<label for="clear-shrinks">Shrinks</label>
<button id="clear-shrinks">Clear</button>
</div>
<div class="clear-btn">
<label for="clear-basis">Basis</label>
<button id="clear-basis">Clear</button>
</div>
</div>
<div id="clear-inputs">
<ul>
<li>
<div>flex-basis sets the initial main size of a flex item. auto means that the element will be
automatically sized based on its content, or on any height or width value if they are
defined.</div>
</li>
<li>
<div>flex-grow sets the flex grow factor of a flex item's main size.</div>
</li>
<li>
<div>flex-shrink sets the flex shrink factor of a flex item. If the size of all flex items is
larger than the flex container, items shrink to fit according to flex-shrink.</div>
</li>
</ul>
</div>
</div>
<div id="desc-container">
<div id="desc-text" class="desc-text desc-box">
</div>
</div>
<div id="example-nav">
<button id="next-example">Next Example</button>
<button id="previous-example">Previous Example</button>
<button id="current-example">Current Example</button>
</div>
</div>
</body>
</html> |
/*
* Copyright (c) 2003, the JUNG Project and the Regents of the University of California All rights reserved.
*
* This software is open-source under the BSD license; see either "license.txt" or
* http://jung.sourceforge.net/license.txt for a description.
*/
package edu.umd.cs.hcil.socialaction.jung.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import prefuse.data.Graph;
import cern.colt.list.DoubleArrayList;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.SparseDoubleMatrix2D;
/**
* Basic I/O handler for ascii matrix files. An ascii matrix is simply a square matrix where 0 values for cell (i,j)
* indicates no edge exists between vertex i and vertex j and non-zero values indicates there is an edge. If a non-null
* weight key is specified then it will be used to treat the non-zero values as a weight stored in the edges' user data
* keyed off the specified weight key value.
* <p>
* When loading a graph from a file, a symmetric graph will result in the construction of an undirected sparse graph
* while a non-symmetric graph will result in the construction of a directed sparse graph.
* <p>
* For example the following ascii matrix when loaded using the code:<br>
* <code>
* MatrixFile mf = new MatrixFile(null); <br>
* Graph g = mf.load(filename); </code><br>
* will produce an undirected sparse matrix with no weights: <br>
*
* <pre>
* 0 1 0 1
* 1 0 0 1
* 0 0 0 0
* 1 1 0 0
* </pre>
* <p>
* whereas the following ascii matrix when loaded using the code:<br>
* <code>
* MatrixFile mf = new MatrixFile("WEIGHT"); <br>
* Graph g = mf.load(filename); </code> <br>
* will produce a directed sparse matrix with double weight values stored in the edges user data under the key "WEIGHT"
* : <br>
*
* <pre>
* 0 .5 10 0
* 0 1 0 0
* 0 0 0 -30
* 5 0 0 0
* </pre>
*
* Modified from JUNG v1.7.4 (edu.uci.ics.jung.io.MatrixFile) to work with Prefuse.
*
* @author Scott
* @author Adam Perer
*/
public class MatrixFile {
// private String mWeightKey;
// /**
// * Constructs MatrixFile instance. If weightKey is not null then, it will attempt to use that key to store and
// * retreive weights from the edges' UserData.
// */
// public MatrixFile(String weightKey) {
// mWeightKey = weightKey;
// }
/**
* Loads a graph from an input reader
*
* @param reader
* the input reader
* @return the graph
*/
public Graph load(BufferedReader reader) {
Graph graph = null;
try {
/* DoubleMatrix2D matrix = */createMatrixFromFile(reader);
// graph = GraphMatrixOperations.matrixToGraph(matrix,mWeightKey);
} catch (Exception e) {
// throw new FatalException(
// "Fatal exception calling MatrixFile.load(...)",
// e);
}
return graph;
}
private DoubleMatrix2D createMatrixFromFile(BufferedReader reader) throws IOException, ParseException {
List<DoubleArrayList> rows = new ArrayList<DoubleArrayList>();
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(currentLine);
if (tokenizer.countTokens() == 0) {
break;
}
DoubleArrayList currentRow = new DoubleArrayList();
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
currentRow.add(Double.parseDouble(token));
}
rows.add(currentRow);
}
int size = rows.size();
DoubleMatrix2D matrix = new SparseDoubleMatrix2D(size, size);
for (int i = 0; i < size; i++) {
DoubleArrayList currentRow = (DoubleArrayList) rows.get(i);
if (currentRow.size() != size) {
throw new ParseException("Matrix must have the same number of rows as columns", 0);
}
for (int j = 0; j < size; j++) {
double currentVal = currentRow.get(j);
if (currentVal != 0) {
matrix.setQuick(i, j, currentVal);
}
}
}
return matrix;
}
/*
* Loads a graph from a file
*
* @see edu.uci.ics.jung.io.GraphFile#load(java.lang.String)
*/
public Graph load(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
Graph graph = load(reader);
reader.close();
return graph;
} catch (IOException ioe) {
return null;
// throw new FatalException("Error in loading file " + filename, ioe);
}
}
/*
* Saves a graph to a file
*
* @see edu.uci.ics.jung.io.GraphFile#save(edu.uci.ics.jung.graph.Graph, java.lang.String)
*/
// public void save(Graph graph, String filename) {
// try {
// BufferedWriter writer =
// new BufferedWriter(new FileWriter(filename));
// // Vertex currentVertex = null;
// DoubleMatrix2D matrix = GraphMatrixOperations.graphToSparseMatrix(graph,mWeightKey);
// Format labelFormat = new Format("%4.2f");
// for (int i=0;i<matrix.rows();i++) {
// for (int j=0;j<matrix.columns();j++) {
// writer.write(labelFormat.format(matrix.getQuick(i,j)) + " ");
// }
// writer.write("\n");
// }
// writer.close();
// } catch (Exception e) {
// throw new FatalException("Error saving file: " + filename, e);
// }
// }
} |
import { shallowMount } from '@vue/test-utils'
import NavigationBar from '@/components/NavigationBar.vue'
import { useRouter, useRoute } from 'vue-router'
jest.mock('vue-router', () => ({
useRouter: jest.fn(),
useRoute: jest.fn(),
}))
describe('NavigationBar.vue', () => {
let routerMock, routeMock
beforeEach(() => {
routerMock = {
push: jest.fn()
}
routeMock = {
path: '/'
}
useRouter.mockReturnValue(routerMock)
useRoute.mockReturnValue(routeMock)
})
afterEach(() => {
jest.clearAllMocks()
})
it('renders the component', () => {
const wrapper = shallowMount(NavigationBar)
expect(wrapper.exists()).toBe(true)
})
it('has a button with text "About Us"', () => {
const wrapper = shallowMount(NavigationBar)
expect(wrapper.text()).toContain('About Us')
})
it('navigates to Clients page when Clients button is clicked', async () => {
const wrapper = shallowMount(NavigationBar)
const clientsButton = wrapper.findAll('.button-client').at(1)
await clientsButton.trigger('click')
expect(routerMock.push).toHaveBeenCalledWith('/clients')
})
it('navigates to About Us page when About Us button is clicked', async () => {
const wrapper = shallowMount(NavigationBar)
const AboutUsButton = wrapper.findAll('.button-client').at(0)
await AboutUsButton.trigger('click')
expect(routerMock.push).toHaveBeenCalledWith('/about')
})
}) |
<script setup lang="ts">
import type { CatProducto } from '@/models/catproducto'
import { onMounted, ref } from 'vue'
import http from '@/plugins/axios'
import router from '@/router'
import Header from "../Header.vue";
import Footer from "../Footer.vue";
const props = defineProps<{
ENDPOINT_API: string
}>()
const ENDPOINT = props.ENDPOINT_API ?? ''
var catproductos = ref<CatProducto[]>([])
async function getCatProducto() {
catproductos.value = await http.get(ENDPOINT).then((response) => response.data)
}
function toEdit(id: number) {
router.push(`/interpretes/editar/${id}`)
}
async function toDelete(id: number) {
var r = confirm('¿Está seguro que se desea eliminar el Intérprete?')
if (r) {
await http.delete(`${ENDPOINT}/${id}`).then(() => getCatProducto())
}
}
onMounted(() => {
getCatProducto()
})
</script>
<template>
<Header />
<br>
<h2 class="intro-y text-lg font-medium">Adminitración de Productos</h2>
<div class="grid grid-cols-12 gap-6 mt-5">
<div class="intro-y col-span-12 flex flex-wrap sm:flex-nowrap items-center mt-2">
<RouterLink to="/interpretes/crear" class="btn btn-primary shadow-md mr-2">Crear Nuevo</RouterLink>
<div class="hidden md:block mx-auto text-slate-500">
</div>
<div class="w-full sm:w-auto mt-3 sm:mt-0 sm:ml-auto md:ml-0">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><RouterLink to="/">Inicio</RouterLink></li>
<li class="breadcrumb-item active" aria-current="page">Producto</li>
</ol>
</nav>
</div>
</div>
<!-- BEGIN: Data List -->
<div class="intro-y col-span-12 overflow-auto lg:overflow-visible">
<table class="table table-report -mt-2">
<thead>
<tr>
<th>#</th>
<th>NOMBRE</th>
<th>FECHA DE CREACIÓN</th>
<th>FECHA DE MODICACIÓN</th>
</tr>
</thead>
<tbody>
<tr v-for="(catproducto, index) in catproductos.values()" :key="catproducto.id">
<th scope="row">{{ index + 1 }}</th>
<td>{{ catproducto.nombre }}</td>
<td>{{ catproducto.fechaCreacion }}</td>
<td>{{ catproducto.fechaModificacion }}</td>
<td>
<button class="btn btn-link" @click="toEdit(catproducto.id)">
<span class="material-symbols-outlined">edit</span>
</button>
<button class="btn btn-link" @click="toDelete(catproducto.id)">
<span class="material-symbols-outlined">
delete
</span>
</button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- END: Data List -->
</div>
<!-- BEGIN: Delete Confirmation Modal -->
<Footer />
</template>
<style scoped></style> |
import { Pipe, PipeTransform } from '@angular/core';
import { IWorkingHour } from '../../features/working-hour/IWorkingHour';
@Pipe({
name: 'workingHoursPipe'
})
export class WorkingHoursPipe implements PipeTransform {
transform(items: IWorkingHour[], searchText: string): IWorkingHour[] {
if (!items) return [];
if (!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter((item: IWorkingHour) => {
return (
item.description.toLowerCase().includes(searchText) ||
item.employee.includes(searchText)
);
});
}
} |
package com.example.bookstore.service;
import com.example.bookstore.dto.book.BookDTO;
import com.example.bookstore.dto.book.InsertBookDTO;
import com.example.bookstore.entity.Book;
import com.example.bookstore.factory.BookFactory;
import com.example.bookstore.repository.BookRepository;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.modelmapper.ModelMapper;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* @author oksanapoliakova on 13.03.2024
* @projectName BookStore
*/
@ExtendWith(MockitoExtension.class)
class BookServiceTest {
@Mock
BookRepository bookRepository;
@Mock
ModelMapper modelMapper;
@Mock
UserService userService;
@InjectMocks
BookService bookService;
@BeforeEach
void init() {
bookService = new BookService(bookRepository,modelMapper,userService);
}
@Test
void getAllBooksSuccess() {
List<Book> books = BookFactory.createBooks();
when(bookRepository.findAll()).thenReturn(books);
var result = bookService.getAllBooks();
assertEquals(4, result.size());
assertEquals("Book1", result.get(0).getName());
assertEquals("Author1", result.get(0).getAuthor());
assertEquals("Description1", result.get(0).getDescription());
assertEquals(10.00, result.get(0).getPrice());
assertEquals("Book2", result.get(1).getName());
assertEquals("Book2", result.get(1).getName());
assertEquals("Author2", result.get(1).getAuthor());
assertEquals("Description2", result.get(1).getDescription());
assertEquals(20.00, result.get(1).getPrice());
}
@Test
public void testSaveBook() {
InsertBookDTO insertBookDTO = new InsertBookDTO();
Book book = new Book();
when(modelMapper.map(insertBookDTO, Book.class)).thenReturn(book);
when(bookRepository.saveAndFlush(book)).thenReturn(book);
Book savedBook = bookService.saveBook(insertBookDTO);
assertNotNull(savedBook);
verify(modelMapper, times(1)).map(insertBookDTO, Book.class);
verify(bookRepository, times(1)).saveAndFlush(book);
}
@Test
public void testGetBookById() {
UUID bookId = UUID.randomUUID();
Book book = new Book();
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
Optional<Book> retrievedBook = bookService.getBookById(bookId);
assertTrue(retrievedBook.isPresent());
verify(bookRepository, times(1)).findById(bookId);
}
@Test
public void testUpdateBookById() {
UUID bookId = UUID.randomUUID();
InsertBookDTO updatedBookDTO = new InsertBookDTO();
updatedBookDTO.setName("Updated Book");
updatedBookDTO.setAuthor("Updated Author");
updatedBookDTO.setDescription("Updated Description");
updatedBookDTO.setPrice(20.00);
Book existingBook = new Book();
existingBook.setId(bookId);
existingBook.setName("Existing Book");
existingBook.setAuthor("Existing Author");
existingBook.setDescription("Existing Description");
existingBook.setPrice(10.00);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(existingBook));
when(bookRepository.save(any(Book.class))).thenReturn(existingBook);
Optional<Book> updatedBook = bookService.updateBookById(bookId, updatedBookDTO);
assertTrue(updatedBook.isPresent());
assertEquals(updatedBookDTO.getName(), updatedBook.get().getName());
assertEquals(updatedBookDTO.getAuthor(), updatedBook.get().getAuthor());
assertEquals(updatedBookDTO.getDescription(), updatedBook.get().getDescription());
assertEquals(updatedBookDTO.getPrice(), updatedBook.get().getPrice());
}
@Test
public void testUpdateBookById_InvalidId() {
UUID invalidBookId = UUID.randomUUID();
InsertBookDTO updatedBookDto = new InsertBookDTO();
updatedBookDto.setName("Updated Title");
EntityNotFoundException entityNotFoundException = assertThrows(EntityNotFoundException.class, () -> {
bookService.updateBookById(invalidBookId, updatedBookDto);
});
assertEquals(entityNotFoundException.getMessage(), "Invalid id: " + invalidBookId);
verify(bookRepository, never()).save(any());
}
@Test
public void testUpdateBookById_NullId() {
InsertBookDTO updatedBookDto = new InsertBookDTO();
updatedBookDto.setName("Updated Title");
NullPointerException nullPointerException = assertThrows(NullPointerException.class, () -> {
bookService.updateBookById(null, updatedBookDto);
});
assertNotNull(nullPointerException);
verify(bookRepository, never()).save(any());
}
@Test
public void testFindBooksByNameContaining() {
Book book1 = BookFactory.createBook("Java Basic", "Herbert Schildt", "Java for beginners", 35.00);
Book book2 = BookFactory.createBook("Java Advanced", "Bruce Eckel", "Java for advanced programmers", 45.00);
Book book3 = BookFactory.createBook("test", "Bruce Eckel", "test for advanced programmers", 45.00);
Book book4 = BookFactory.createBook("Clean Code", "Robert C. Martin", "A Handbook of Agile Software Craftsmanship", 50.00);
List<Book> booksContainingJava = Arrays.asList(book1, book2);
List<Book> booksContainingTest = List.of(book3);
List<Book> allBooks = Arrays.asList(book1, book2, book3, book4);
when(bookRepository.findByNameContaining("Java")).thenReturn(booksContainingJava);
when(bookRepository.findByNameContaining("test")).thenReturn(booksContainingTest);
when(bookRepository.findByNameContaining("")).thenReturn(allBooks); // all books
List<Book> actualBooksContainingJava = bookService.findBooksByNameContaining("Java");
List<Book> actualBooksContainingTest = bookService.findBooksByNameContaining("test");
List<Book> actualAllBooks = bookService.findBooksByNameContaining("");
assertEquals(2, actualBooksContainingJava.size());
assertEquals(1, actualBooksContainingTest.size());
assertEquals(4, actualAllBooks.size());
}
@Test
public void testDeleteById() {
Book book = new Book();
UUID bookId = UUID.randomUUID();
lenient().when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
bookService.deleteById(bookId);
verify(bookRepository, times(1)).deleteById(bookId);
}
@Test
public void testDeleteById_InvalidId() {
assertThrows(NullPointerException.class, () -> {
bookService.deleteById(null);
});
verify(bookRepository, never()).deleteById(null);
}
@Test
public void testFindBookByName() {
String title = "Title";
Book expectedBook = new Book();
expectedBook.setName(title);
when(bookRepository.findBookByName(title)).thenReturn(Optional.of(expectedBook));
Optional<Book> foundBookOptional = bookService.findBookByName(title);
assertTrue(foundBookOptional.isPresent());
assertEquals(expectedBook, foundBookOptional.get());
verify(bookRepository, times(1)).findBookByName(title);
}
@Test
public void testFindBooksByAuthorContaining() {
Book book1 = BookFactory.createBook("Java Basic", "Test", "Java for beginners", 35.00);
Book book2 = BookFactory.createBook("Java Advanced", "Bruce Eckel", "Java for advanced programmers", 45.00);
Book book3 = BookFactory.createBook("Test", "Test", "test for advanced programmers", 45.00);
Book book4 = BookFactory.createBook("Clean Code", "Robert C. Martin", "A Handbook of Agile Software Craftsmanship", 50.00);
Book book5 = BookFactory.createBook("Java Basic", "Bruce Eckel", "Java for beginner programmers", 35.00);
List<Book> booksContainingTestAuthor = Arrays.asList(book1, book5);
when(bookRepository.findByAuthorContaining("Test")).thenReturn(booksContainingTestAuthor);
List<Book> actualBooksContainingTestAuthor = bookService.findBooksByAuthorContaining("Test");
assertEquals(2, booksContainingTestAuthor.size());
}
@Test
public void testFindBooksByOrderByPriceAsc() {
List<Book> books = BookFactory.createBooks();
when(bookRepository.findAllByOrderByPriceAsc()).thenReturn(books);
List<Book> actualBooks = bookService.findBooksByOrderByPriceAsc();
assertEquals(books, actualBooks);
}
@Test
public void testFindBooksByOrderByPriceDesc() {
List<Book> books = BookFactory.createBooks();
when(bookRepository.findAllByOrderByPriceDesc()).thenReturn(books);
List<Book> actualBooks = bookService.findBooksByOrderByPriceDesc();
assertEquals(books, actualBooks);
}
@Test
public void testMapToDTO() {
Book book = new Book();
book.setName("Test Book");
book.setAuthor("Test Author");
book.setDescription("Test Description");
book.setPrice(10.00);
BookDTO expectedBookDTO = new BookDTO();
expectedBookDTO.setName("Test Book");
expectedBookDTO.setAuthor("Test Author");
expectedBookDTO.setDescription("Test Description");
expectedBookDTO.setPrice(10.00);
when(modelMapper.map(book, BookDTO.class)).thenReturn(expectedBookDTO);
BookDTO actualBookDTO = bookService.mapToDTO(book);
assertEquals(expectedBookDTO, actualBookDTO);
}
} |
<template>
<div>
<div class="todo" v-for="(todo, index) in todos" :key="index">
<div class="taskList">
<i
class="fa-solid fa-check text-white"
@click="completed(todo)"
:class="{ checked: todo.isCompleted }"
></i>
<ul class="list-group border-none">
<li
class="list-group-item bg-dark text-light"
:class="{ textChecked: todo.isCompleted }"
>
{{ todo.text }}
</li>
</ul>
</div>
<div class="changeButton">
<i class="fa-solid fa-pen" @click="editTask(todo,index)"></i>
<i class="fa-solid fa-trash-can" @click="deleteTodo(index)"></i>
</div>
</div>
</div>
</template>
<script>
import { computed } from "vue";
export default {
props: ["todos"],
methods: {
deleteTodo(index) {
this.todos.splice(index, 1);
},
completed(todo) {
todo.isCompleted = !todo.isCompleted;
},
// edit
editTask(todo,index){
this.$emit('data', todo.text)
console.log('todolist'+ todo.text)
this.todos.splice(index, 1);
}
},
};
</script>
<style scoped>
.todo {
margin-top: 10px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.19);
padding: 5px 0;
}
.list-group-item {
border: none;
}
.taskList {
display: flex;
align-items: center;
}
i {
cursor: pointer;
}
.fa-trash-can {
color: #ff9292;
opacity: 0.2;
}
.todo:hover .fa-trash-can {
cursor: pointer;
opacity: 1;
transition: all .5s ease-in-out;
}
.checked {
color: lightgreen !important;
transition: all .5s ease-in-out;
}
.textChecked {
text-decoration: line-through;
color: #968d8d44 !important;
transition: all .5s ease-in;
}
.changeButton{
display: flex;
padding: 10px;
justify-content: space-between;
}
.fa-pen{
color: lightgreen;
margin-right:10px;
opacity: .2;
}
.todo:hover .fa-pen {
cursor: pointer;
opacity: 1;
transition: all .5s ease-in-out;
}
</style> |
import { loggerFile } from '../../configuration/logger';
import { Request, Response, NextFunction } from 'express';
import { ApiSuccess } from '../../utils/api';
import { fetchEnrolledCourses } from '../moodle/fetch';
import { getBaseUrl } from '../moodle/index';
import { MoodleSettings } from '../moodle/schemas/moodle.schema';
import { connectorService } from '../connectors/service';
/**
* GET /api/status
* Responds with a JSON object containing all currently available status info.
*
* @param req Request
* @param res Response
* @param next NextFunction
*/
export async function statusGetRequest(req: Request, res: Response, next: NextFunction) {
try {
// TODO: Better handling in #19
let moodleConnectionStatus = 'Unknown';
try {
const courses = await fetchEnrolledCourses(getBaseUrl()) as any;
if (courses.length) moodleConnectionStatus = 'Ok';
else if (courses.message) moodleConnectionStatus = courses.message;
} catch (error) {
moodleConnectionStatus = error.message;
}
const moodleCurrentFetchInterval = await MoodleSettings.getRefreshRate();
const moodleLastFetchTimestamp = await MoodleSettings.getLastFetch();
const moodleNextFetchTimestamp = await MoodleSettings.getNextFetch();
const [
connectorsLength,
connectorsActiveLength,
connectorsDefaultLength,
] = connectorService.status;
const responseObject = {
moodleConnectionStatus,
moodleLastFetchTimestamp,
moodleNextFetchTimestamp,
moodleCurrentFetchInterval,
connectorsLength,
connectorsActiveLength,
connectorsDefaultLength,
};
const response = new ApiSuccess(200, responseObject);
next(response);
} catch (err) {
loggerFile.error(err.message);
next(err);
}
} |
/*
Copyright 2023.
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 controllers
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/go-logr/logr"
plumberv1 "github.com/platform9/luigi/yoshi/api/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
kubevirtv1 "kubevirt.io/api/core/v1"
"github.com/platform9/luigi/yoshi/pkg/cni"
"github.com/platform9/luigi/yoshi/pkg/utils/constants"
"github.com/platform9/luigi/yoshi/pkg/utils/vmutils"
)
// NetworkWizardReconciler reconciles a NetworkWizard object
type NetworkWizardReconciler struct {
client.Client
Scheme *runtime.Scheme
Log logr.Logger
}
type NetReqWrapper struct {
Log logr.Logger
Client client.Client
needsUpdate bool
network *plumberv1.NetworkWizard
cni cni.CNIProvider
}
func NewNetReqWrapper(log logr.Logger, client client.Client) *NetReqWrapper {
reqInfo := new(NetReqWrapper)
reqInfo.Log = log
reqInfo.Client = client
reqInfo.needsUpdate = false
return reqInfo
}
func (req *NetReqWrapper) WithNetwork(network *plumberv1.NetworkWizard) *NetReqWrapper {
if req.network == nil {
req.network = &plumberv1.NetworkWizard{}
}
req.network = network
return req
}
func (req *NetReqWrapper) WithCNIProvider(provider cni.CNIProvider) *NetReqWrapper {
req.cni = provider
return req
}
//+kubebuilder:rbac:groups=plumber.k8s.pf9.io,resources=networkwizards,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=plumber.k8s.pf9.io,resources=networkwizards/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=plumber.k8s.pf9.io,resources=networkwizards/finalizers,verbs=update
//+kubebuilder:rbac:groups=*,resources=*,verbs=*
func (r *NetworkWizardReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.Log.WithValues("network", req.NamespacedName)
log.Info("Reconciling network")
network := &plumberv1.NetworkWizard{}
if err := r.Client.Get(ctx, req.NamespacedName, network); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
reqWrapper := NewNetReqWrapper(log, r.Client).WithNetwork(network)
cni, err := cni.NewCNIProvider(ctx, network.Spec.Plugin, &cni.CNIOpts{Client: r.Client, Log: log})
if err != nil {
log.Error(err, "Faled to get CNI Provider")
return ctrl.Result{}, err
}
reqWrapper = reqWrapper.WithCNIProvider(cni)
if !network.ObjectMeta.DeletionTimestamp.IsZero() {
if controllerutil.ContainsFinalizer(network, constants.NetworkFinalizerName) {
if err := r.ReconcileDelete(ctx, reqWrapper); err != nil {
return ctrl.Result{}, err
}
controllerutil.RemoveFinalizer(network, constants.NetworkFinalizerName)
if err := r.Client.Update(ctx, network); err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
return r.ReconcileNetwork(ctx, reqWrapper)
}
func (r *NetworkWizardReconciler) ReconcileNetwork(ctx context.Context, req *NetReqWrapper) (ctrl.Result, error) {
if req.network.Status.Created == true {
req.Log.Info("Network.Status is created", "status", req.network.Status)
if err := req.cni.VerifyNetwork(ctx, req.network.Name); err == nil {
req.Log.Info("Network is already created")
return ctrl.Result{}, nil
}
}
r.Log.Info("Reconciling network", "network", req.network.Name, "spec", req.network.Spec)
if !controllerutil.ContainsFinalizer(req.network, constants.NetworkFinalizerName) {
controllerutil.AddFinalizer(req.network, constants.NetworkFinalizerName)
if err := r.Client.Update(ctx, req.network); err != nil {
r.Log.Error(err, "unable to update NetworkWizard with finalizer")
return ctrl.Result{Requeue: true}, err
}
}
if err := req.cni.CreateNetwork(ctx, req.network); err != nil {
r.Log.Error(err, "Error creating network", "network", req.network.Spec)
req.network.Status.Created = false
req.network.Status.Reason = err.Error()
} else {
req.network.Status.Created = true
r.Log.Info("Success creating network")
}
if err := r.Status().Update(ctx, req.network); err != nil {
r.Log.Error(err, "unable to update NetworkWizard status")
return ctrl.Result{}, err
}
r.Log.Info("Updated network status", "Status", req.network.Status)
return ctrl.Result{}, nil
}
func (r *NetworkWizardReconciler) ReconcileDelete(ctx context.Context, req *NetReqWrapper) error {
r.Log.Info("Deleting network", "network", req.network.Name, "spec", req.network.Spec)
vmsOnNetwork, err := r.GetVMsForNetwork(req.network)
if err != nil {
return err
}
if len(vmsOnNetwork) > 0 {
r.Log.Info("VMs exist on network", "vms", len(vmsOnNetwork))
err := fmt.Errorf("VMs exist on network, can't delete")
return err
}
r.Log.Info("Deleting network %s", "network", req.network.Name)
if err := req.cni.DeleteNetwork(ctx, req.network.Name); err != nil {
r.Log.Error(err, "Plugin failed to delete network resource")
return err
}
return nil
}
func (r *NetworkWizardReconciler) GetVMsForNetwork(network *plumberv1.NetworkWizard) ([]*kubevirtv1.VirtualMachine, error) {
var matchingVMs []*kubevirtv1.VirtualMachine
vmList := &kubevirtv1.VirtualMachineList{}
err := r.Client.List(context.Background(), vmList)
if err != nil {
r.Log.Error(err, "Failed to list VMs")
return nil, err
}
for _, vm := range vmList.Items {
if vmutils.GetVMNetworkAnnotation(&vm) == network.Name {
matchingVMs = append(matchingVMs, &vm)
}
}
return matchingVMs, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *NetworkWizardReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&plumberv1.NetworkWizard{}).
Complete(r)
} |
---
title: "Conjunction Junction, what's your function in R?"
output:
html_document:
highlight: textmate
toc: yes
toc_float:
collapsed: no
theme: cosmo
---
## Introduction and Notes about Functions in R
R is a powerful programming language for statistical computing with many packages and tools.
The goal of this article is to arm you with tools and techniques for using creating and using functions.
Below are some notes from various resources. Below each link is text from the resource.
## Key info
http://dept.stat.lsa.umich.edu/~jerrick/courses/stat701/notes/functions.html
In R, every command you run is a function. Sometimes this is obvious, such as
lm(y ~ x)
We can examine the source code of any function by calling the function without parentheses:
library(stringr)
str_which
https://bids.github.io/2017-01-12-ucb/lessons/R/02-func-R.html
You see the result of this documentation when you look at the help file for a given function, e.g. ?read.csv.
http://pj.freefaculty.org/guides/Rcourse/functions-1/functions-1.pdf
3 reasons to write functions
1. Preserve your sanity: isolate specific work.
1.A Side benefit: preserve sanity of others who have to read your
code
2. Facilitate re-use of your ideas
3. Co-operate with R functions like lapply() and boot() which
REQUIRE functions from us.
http://adv-r.had.co.nz/
http://adv-r.had.co.nz/Functions.html
“To understand computations in R, two slogans are helpful:
Everything that exists is an object.
Everything that happens is a function call."
— John Chambers
Functions are a fundamental building block of R. The most important thing to understand about R is that functions are objects in their own right. You can work with them exactly the same way you work with any other type of object. All R functions have three parts:
the body(), the code inside the function.
the formals(), the list of arguments which controls how you can call the function.
the environment(), the “map” of the location of the function’s variables.
Scoping is the set of rules that govern how R looks up the value of a symbol. R has two types of scoping: lexical scoping, implemented automatically at the language level, and dynamic scoping, used in select functions to save typing during interactive analysis.
http://r4ds.had.co.nz/functions.html
https://jrnold.github.io/e4qf/functions.html
One of the best ways to improve your reach as a data scientist is to write functions. Functions allow you to automate common tasks in a more powerful and general way than copy-and-pasting.
When should you write a function?
You should consider writing a function whenever you’ve copied and pasted a block of code more than twice (i.e. you now have three copies of the same code).
Dot-dot-dot (…)
Many functions in R take an arbitrary number of inputs.
... (pronounced dot-dot-dot). This special argument captures any number of arguments that aren’t otherwise matched.
It’s useful because you can then send those ... on to another function. This is a useful catch-all if your function primarily wraps another function.
Writing pipeable functions
If you want to write your own pipeable functions, it’s important to think about the return value. Knowing the return value’s object type will mean that your pipeline will “just work”. For example, with dplyr and tidyr the object type is the data frame.
http://pj.freefaculty.org/guides/Rcourse/functions-1/functions-1.pdf
How To Name Functions
Don’t use names for functions that are already in widespread
use, like lm, seq, rep, etc.
Use Objective C style variable and function names that smash words together, as in myRegression myCode
R uses periods in function names to represent “object orientation” or “subclassing”, thus I avoid periods for simple punctuation.Ex: doSomething() is better than do.something
Underscores are now allowed in function names.
Ex: do something() would be OK
http://neondataskills.org/R/Working-With-Functions
Calling our own function is no different from calling any other built in R function that you are familiar with.
Introduction to Functions in R
https://www.youtube.com/watch?v=gl9opYcRxO8
https://rpubs.com/williamsurles/292234
Writing a function in R
The parts of a function
Argument
Body
Environment
Return value is the last evaluated expression or the first evaluated return() expression
Functions can be treated like usual R objects
http://dept.stat.lsa.umich.edu/~jerrick/courses/stat701/notes/functions.html
The output of the last line of code in the function is what the function returns. I’ve been implicitly using this earlier; myFunc returns x - y and table1 returns the results from table.
You can sometimes mess this up:
myFunc <- function(x, y) {
z <- x + y
}
myFunc(2, 3)
https://bids.github.io/2017-01-12-ucb/lessons/R/02-func-R.html
In R, it is not necessary to include the return statement. R automatically returns whichever variable is on the last line of the body of the function. Since we are just learning, we will explicitly define the return statement.
## Built-in Function
https://www.tutorialspoint.com/r/r_functions.htm
Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc. They are directly called by user written programs.
https://cran.r-project.org/doc/contrib/Short-refcard.pdf
# R Function Types
https://www.tutorialgateway.org/functions-in-r-programming/
There are two types of functions in R Programming language:
Library Functions: All the built-in functions supported by the R Language, or the R packages are called as Library function. You no need to worry about the logic inside the Library functions. In our previous articles, We used many library functions such as print(), sqrt() etc.
User Defined Functions: Instead of relying only on built-in functions, R Programming allows us to create our own functions called as user defined functions. For example, if we want to calculate the Sales profits, or any mathematical calculations then we can place them in separate function with proper function name, and later we can call that function multiple time.
https://www.datacamp.com/community/tutorials/functions-in-r-a-tutorial
User Defined Functions (UDF)
Whether you need to accomplish a particular task and are not aware that a dedicated function or library exists already or because by the time you spend googling for some existing solution, you can have already come out with your own, you will find yourself at some time typing...
## Arguments
https://bids.github.io/2017-01-12-ucb/lessons/R/02-func-R.html
To be precise, R has three ways that arguments supplied
by you are matched to the formal arguments of the function definition
by complete name,
by partial name (matching on initial n characters of the argument name), and
by position.
Arguments are matched in the manner outlined above in that order: by complete name, then by partial matching of names, and finally by position.
## Key Points
https://bids.github.io/2017-01-12-ucb/lessons/R/02-func-R.html
Define a function using name <- function(...args...) {...body...}.
Call a function using name(...values...).
Each time a function is called, a new stack frame is created on the call stack to hold its arguments and local variables.
R looks for variables in the current stack frame before looking for them at the top level.
Use help(thing) to view help for something.
Put comments at the beginning of functions to provide help for that function.
Annotate your code!
Specify default values for arguments when defining a function using name = value in the argument list.
Arguments can be passed by matching based on name, by position, or by omitting them (in which case the default value is used).
## Anonymous Functions in R
https://www.datacamp.com/community/tutorials/functions-in-r-a-tutorial
When you don’t give a name to a function, you are creating an anonymous function.
## Load the function into the R session
https://www.statmethods.net/management/userfunctions.html
https://www.statmethods.net/interface/customizing.html
You may want to store your own functions, and have them available in every session. You can customize the R environment to load your functions at start-up.
https://nicercode.github.io/guides/functions/
For R to be able to execute your function, it needs first to be read into memory. This is just like loading a library, until you do it the functions contained within it cannot be called.
There are two methods for loading functions into the memory:
Copy the function text and paste it into the console
Use the source() function to load your functions from file.
## Scoping
http://dept.stat.lsa.umich.edu/~jerrick/courses/stat701/notes/functions.html
Scoping and side effects
Scope is an important and really complicated topic for functions - the short version is this:
Any object created inside a function (including arguments passed to it) are destroyed when the functions returns.
If an object doesn’t exist inside the function, R will look for an object outside the function.
R functions should have no “side effects” - never modify an external object.
https://www.stat.berkeley.edu/~statcur/Workshop2/Presentations/functions.pdf
https://rpubs.com/Verley93/rprognotes
Scoping rules determine how a value is associated with a free variable in a function
Free variables = variables not explicitly defined in the function (not arguments, or local variables - variable defined in the function)
R uses lexical/static scoping
common alternative = dynamic scoping
lexical scoping = values of free vars are searched in the environment in which the function is defined
environment = collection of symbol/value pairs (x = 3.14)
each package has its own environment
only environment without parent environment is the empty environment
closure/function closure = function + associated environment
## Function components
https://bookdown.org/Tazinho/Advanced-R-Solutions/functions.html
Q: What function allows you to tell if an object is a function? What function allows you to tell if a function is a primitive function?
A: You can test objects with is.function and is.primitive.
Q: This code makes a list of all functions in the base package.
objs <- mget(ls("package:base"), inherits = TRUE)
funs <- Filter(is.function, objs)
## Examples
https://trendct.org/2017/03/17/tutorial-how-to-create-r-functions-and-packages/
http://stat545.com/block011_write-your-own-function-01.html
http://stat545.com/block011_write-your-own-function-02.html
http://stat545.com/block011_write-your-own-function-03.html
Powerful machines like dplyr, purrr, and the built-in apply family of functions, are ready and waiting to apply your purpose-built functions to various bits of your data. If you can express your analytical wishes in a function, these tools will give you great power.
Build that skateboard before you build the car or some fancy car part. A limited-but-functioning thing is very useful. It also keeps the spirits high.
http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/R/R3_BasicProgramming-R/R3_BasicProgramming-R8.html
## Chaining Functions
https://swcarpentry.github.io/r-novice-inflammation/02-func-R/
This example showed the output of fahr_to_kelvin assigned to temp_k, which is then passed to kelvin_to_celsius to get the final result. It is also possible to perform this calculation in one line of code, by “chaining” functions together
Key Points
Define a function using name <- function(...args...) {...body...}.
Call a function using name(...values...).
R looks for variables in the current stack frame before looking for them at the top level.
Use help(thing) to view help for something.
Put comments at the beginning of functions to provide help for that function.
Annotate your code!
Specify default values for arguments when defining a function using name = value in the argument list.
Arguments can be passed by matching based on name, by position, or by omitting them (in which case the default value is used).
# What makes for a good function?
https://nicercode.github.io/guides/functions/
https://nicercode.github.io/intro/writing-functions.html
It’s short
M Butcher @technosophos
If you've written a function whose body is 2,996 lines of code, you're doing it wrong.
12:55 PM - Apr 11, 2013
4 4 Replies 15 15 Retweets 8 8 likes
Performs a single operation
Tim Ottinger @tottinge
The reason for writing a function is not to reuse its code, but to name the operation it performs.
1:44 PM - Jan 22, 2013
6 6 Replies 86 86 Retweets 27 27 likes
Uses intuitive names
Gustavo Rod. Baldera @gbaldera
"The name of a variable, function, or class, should answer all the big questions." - Uncle Bob Martin, Clean Code
10:15 AM - Apr 24, 2013
Using functions is just one tool in ensuring that your code will be easy for you to read in future, but it is an essential tool.
Justin Kimbrell @justin_kimbrell
The more I write code, the more abstract it gets. And with more abstractions, the apps are easier to maintain. Been working for years...
10:07 PM - Apr 29, 2013
## Debugging
R provides a number of functions for debugging, such as:
traceback()
debug()
browser()
trace()
recover()
https://stackoverflow.com/questions/30119628/stepping-through-a-pipeline-with-intermediate-results
Use print
https://data-flair.training/blogs/debugging-in-r-programming/
traceback()
If our code has already crashed and we want to know where the offending line is, try traceback(). This will (sometimes) show where abouts in the code the problem occurred.
http://dept.stat.lsa.umich.edu/~jerrick/courses/stat701/notes/debugging.html
https://support.rstudio.com/hc/en-us/articles/205612627-Debugging-with-RStudio
https://www.rstudio.com/products/rstudio/release-notes/debugging-with-rstudio/
https://www.rstudio.com/products/rstudio/release-notes/breakpoint-troubleshooting-with-rstudio/
https://stat.ethz.ch/R-manual/R-devel/library/base/html/debug.html
http://seananderson.ca/2013/08/23/debugging-r.html
https://rforpublichealth.blogspot.com/2014/06/how-to-write-and-debug-r-function.html
https://rforpublichealth.blogspot.com/2014/07/
http://www.win-vector.com/blog/2017/03/debugging-pipelines-in-r-with-bizarro-pipe-and-eager-assignment/
http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/
https://geographicdatascience.com/2017/02/02/non-standard-evaluation-and-debugging-in-r/
https://github.com/rstudio/rstudio/issues/1548
http://cfss.uchicago.edu/program_pipes.html
## Packages Intro
https://www.datacamp.com/community/tutorials/r-packages-guide
What’s The Difference Between A Package And A Library?
Speaking about the library() function, sometimes there is a confusion between a package and a library, and you can find people calling “libraries” to packages.
Please don’t get confused: library() is the command used to load a package, and it refers to the place where the package is contained, usually a folder on your computer, while a package is the collection of functions bundled conveniently.
Maybe it can help a quote from Hadley Wickham, Chief data scientist at RStudio, and instructor of the “Writing functions in R” DataCamp course:
@ijlyttle a package is a like a book, a library is like a library; you use library() to check a package out of the library #rsats
— Hadley Wickham (@hadleywickham) December 8, 2014
help(vioplot, package = "vioplot")
library(babynames)
ls("package:babynames")
vignette(package = "ggplot2")
vignette("ggplot2-specs")
## Package
http://r-pkgs.had.co.nz
https://rpubs.com/nishantsbi/242168
https://github.com/jtleek/rpackages
When to start writing an R package
As soon as you have 2 functions.
Why 2? After you have more than one function it starts to get easy to lose track of what your functions do, it starts to be tempting to name your functions foo or tempfunction or some other such nonsense. You are also tempted to put all of the functions in one file and just source it. That was what I did whwn i started my first analytics project, which ended up being an epically comical set of about +2,000 lines of code in one R file. Ask my project lead about it sometime, he probably is still laughing about it.
https://hilaryparker.com/2014/04/29/writing-an-r-package-from-scratch/
Step 2: Add functions
If you’re reading this, you probably have functions that you’ve been meaning to create a package for.
The package roxygen2 that makes everything amazing and simple. The way it works is that you add special comments to the beginning of each function, that will later be compiled into the correct format for package documentation.
## Advanced
http://adv-r.had.co.nz/Functional-programming.html
http://adv-r.had.co.nz/Functionals.html#functionals
http://adv-r.had.co.nz/Function-operators.html#function-operators
## Other Resources
https://cran.r-project.org/doc/manuals/R-intro.html#Writing-your-own-R-intro.html#Writing-your-own-functions
https://www.programiz.com/r-programming/function
http://www.dummies.com/programming/r/how-to-create-a-function-in-r/
https://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_rfunc.html
http://faculty.nps.edu/sebuttre/home/R/functions.html
http://www.stat.cmu.edu/~cshalizi/402/programming/writing-functions.pdf
https://softwareengineering.stackexchange.com/questions/123159/what-are-the-specific-meanings-of-the-terms-functions-methods-procedures-and?rq=1 |
import { useMemo, useState } from 'react';
import './App.css';
function App() {
const [results, setResult] = useState([]);
const [searchText, setSearchText] = useState('');
const debounce = (callback, delay) => {
let timeOut = null;
return (...args) => {
clearTimeout(timeOut);
timeOut = setTimeout(() => {
callback(...args);
}, delay);
}
}
//debounce wrapper function - useCallback
//debounce wrapper function
const reqAPI = useMemo(() => {
return debounce((e) => {
fetch(
'https://dummyjson.com/users/search?' +
new URLSearchParams({
q: e.target.value,
})
)
.then((res) => res.json())
.then((res) => {
setResult(res?.users);
})
.catch((err) => {
console.error("Error: " + err);
});
}, 1000);
}, [])
const handleSearchChange = (e) => {
e.preventDefault();
setSearchText(e.target.value.trim());
reqAPI(e);
}
//debounce wrapper function - useCallback
//memoize the debounce function using useMemo
// const debouncedCallback = useMemo(() => debounce((value) => {
// fetch(
// 'https://dummyjson.com/users/search?' +
// new URLSearchParams({
// q: value,
// })
// )
// .then((res) => res.json())
// .then((res) => {
// setResult(res?.users);
// })
// .catch((err) => {
// console.error("Error: " + err);
// });
// }, 1000), []);
// const reqAPI = useCallback(
// (value) => debouncedCallback(value),
// [debouncedCallback]
// );
// const handleSearchChange = (e) => {
// e.preventDefault();
// const value = e.target.value.trim();
// setSearchText(value);
// reqAPI(value);
// };
console.log("Hello user", results)
return (
<>
<header>
<ul>
<li>
<a className="links" href="#user">
<button className="signbutton" type="button">
Sign in
</button>
</a>
</li>
<li>
<a href="#grid">
<img
className="grid"
src="https://cdn3.iconfinder.com/data/icons/navigation-and-settings/24/Material_icons-01-11-512.png"
title="Google apps"
alt="Google apps"
/>
</a>
</li>
<li>
<a href="#images">Images</a>
</li>
<li>
<a href="#gmail">Gmail</a>
</li>
</ul>
</header>
<div className="logo">
<img
alt="Google"
src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
/>
</div>
<div className="bar">
<i className="search-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="#5F6368">
<path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" />
</svg>
</i>
<input
className="searchbar"
type="text"
title="Search"
name="search_text"
id="search-field"
value={searchText}
onChange={handleSearchChange}
/>
<a href="#">
<img
className="voice"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Google_mic.svg/716px-Google_mic.svg.png"
title="Search by Voice"
alt="Voice Search"
/>
</a>
</div>
{results && results.length > 0 &&
<div className="result-list">
<div id="result-box">
{results.map((result) => (
<p key={result.id}>
{result.firstName} {result.lastName}
</p>
))}
</div>
</div>
}
<div className="buttons">
<button className="button" type="button">
#Debounce
</button>
<button className="button" type="button">
#Throttle
</button>
</div>
</>
);
}
export default App; |
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{{route('home')}}">Home</a></li>
<li class="breadcrumb-item"><a href="{{route('members.index')}}">Members</a></li>
<li class="breadcrumb-item active" aria-current="page">Edit Member</li>
</ol>
</nav>
<div class="card">
<div class="card-header">
Edit Member
</div>
<div class="card-body">
<form action="{{ route('members.update', $member->id) }}" method="post">
@csrf
@method('PATCH')
<div class="form-group-row">
<label for="name" class="col-sm-4 col-form-label-md-right">Nama</label>
<div class="col-md-6">
<input type="text" id="name" name="name" class="form-control {{ $errors->has('name') ? 'is_invalid' : '' }}" value="{{ $member->name }}" >
@if ($errors->has('name'))
<span class="invalied-feedback">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group-row">
<label for="email" class="col-sm-4 col-form-label-md-right">Email</label>
<div class="col-md-6">
<input type="email" id="email" name="email" class="form-control {{ $errors->has('email') ? 'is_invalid' : '' }}" value="{{ $member->email }}">
@if ($errors->has('email'))
<span class="invalied-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group-row">
<div class="col-sm-4"></div>
<div class="col-md-6">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection |
---
title: Get Roles
icon: 'user-pen'
---
This function takes a single parameter 'target', which is the ID of the player that the Discord user data should be retrieved. It returns a table that contains Discord user data, including the user's name, discriminator, and avatar. **If the user is not in the discord, or there data could not be loaded, it will return false for all functions**.
```lua
exports.trase_discord:getUser(serverId)
```
- serverId: ``integer``
- The server ID of the player you want to retrieve the discord info for.
Returns: ``false`` or ``table``
## Examples
```lua
RegisterCommand('getDiscordUser', function(src)
local user = exports.trase_discord:getUser(src)
if (not user) then
-- Player was not in the discord, no user found
return
end
print(json.encode(user, { indent = true }))
end)
``` |
<template>
<div>
<el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="店铺名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item label="详细详细地址" prop="address">
<el-input v-model="ruleForm.addres"></el-input>
</el-form-item>
<el-form-item label="联系电话" prop="moble">
<el-input v-model="ruleForm.moble"></el-input>
</el-form-item>
<el-form-item label="店铺简介" prop="jies">
<el-input v-model="ruleForm.jies"></el-input>
</el-form-item>
<el-form-item label="店铺标语" prop="slogan">
<el-input v-model="ruleForm.slogan"></el-input>
</el-form-item>
<el-form-item label="店铺分类" prop="sort">
<el-select v-model="ruleForm.sort" placeholder="请选择活动区域">
<el-option label="快餐便当/简餐" value="shanghai"></el-option>
<el-option label="异国料理/日韩料理" value="beijing"></el-option>
</el-select>
<el-form-item label="店铺特点">
<el-form-item label="品牌保证" prop="ensure">
<el-switch v-model="ruleForm.ensure"></el-switch>
</el-form-item>
<el-form-item label="蜂鸟专送" prop="send">
<el-switch v-model="ruleForm.send"></el-switch>
</el-form-item>
<el-form-item label="新开店铺" prop="xin">
<el-switch v-model="ruleForm.xin"></el-switch>
</el-form-item>
<el-form-item label="外卖保" prop="bao">
<el-switch v-model="ruleForm.bao"></el-switch>
</el-form-item>
<el-form-item label="准时达" prop="time">
<el-switch v-model="ruleForm.time"></el-switch>
</el-form-item>
<el-form-item label="开发票" prop="Inv">
<el-switch v-model="ruleForm.Inv"></el-switch>
</el-form-item>
</el-form-item>
</el-form-item>
<el-form-item label="营业时间" required>
<el-col :span="11">
<el-time-select
placeholder="起始时间"
v-model="startTime"
:picker-options="{
start: '08:30',
step: '00:15',
end: '18:30',
}"
>
</el-time-select>
<el-time-select
placeholder="结束时间"
v-model="endTime"
:picker-options="{
start: '08:30',
step: '00:15',
end: '18:30',
minTime: startTime,
}"
>
</el-time-select>
</el-col>
</el-form-item>
<!-- 上传店铺头像 -->
<el-form-item label="上传店铺头像">
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item label="上传营业执照">
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item label="上传餐饮服务许可证">
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')"
>立即创建</el-button
>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
ruleForm: {
name: "",
address: "",
moble: "",
jies: "",
slogan: "",
sort: "",
ensure: "",
send: "",
xin: "",
bao: "",
time: "",
Inv: "",
startTime: "",
endTime: "",
},
rule: {
name: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
address: [
{ required: true, message: "请输入店铺名称", trigger: "blur" },
],
moble: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
jies: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
slogan: [
{ required: true, message: "请输入店铺名称", trigger: "blur" },
],
},
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert("submit!");
} else {
console.log("error submit!!");
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
},
created() {
axios.get("https://elm.cangdu.org/v1/cities?type=guess").then((res) => {
console.log(res);
});
},
};
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style> |
package com.mb.menu.entity;
import java.io.Serializable;
import java.util.List;
/**
* id:节点ID,对加载远程数据很重要。 text:显示节点文本。 state:节点状态,'open'
* 或'closed',默认:'open'。如果为'closed'的时候,将不自动展开该节点。 checked:表示该节点是否被选中。 attributes:
* 被添加到节点的自定义属性。 children: 一个节点数组声明了若干节点。
*/
public class BaseTree implements Serializable {
private static final long serialVersionUID = 1424380006823987560L;
/**
* 节点ID,对加载远程数据很重要
*/
private String id;
/**
* 显示节点文本
*/
private String text;
/**
* state:节点状态,'open'或'closed',默认:'open'。如果为'closed'的时候,将不自动展开该节点
*/
private String state = "open";
/**
* checked:表示该节点是否被选中
*/
private boolean checked = false;
/**
* attributes:被添加到节点的自定义属性
*/
private Object attributes;
/**
* children: 一个节点数组声明了若干节点
*/
private List<BaseTree> children;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public Object getAttributes() {
return attributes;
}
public void setAttributes(Object attributes) {
this.attributes = attributes;
}
public List<BaseTree> getChildren() {
return children;
}
public void setChildren(List<BaseTree> children) {
this.children = children;
}
} |
## Plan: Task 1 of 2
Your pre-work assignment is to build a site using one of the following public APIs. Pick a topic that is of most interest to you:
- Open-Meteo - a weather API
- Spotify - a music API (requires a free Spotify account and use of an access token)
- Swapi.Tech - an API about Star Wars films
- Marvel - an API about the Marvel fandom
- ARTIC - an art API from the Art Institute of Chicago
- TheDogAPI or the TheCatAPI - APIs about (you guessed it!) Dogs or Cats
- SampleAPIs - an API for coffee lovers
The finished project you build as your pre-work assignment should contain the minimum of all the following:
#### STRUCTURE:
1. A public GitHub repository containing your project
2. An HTML document for the page
3. A CSS document to style the HTML page
4. A JavaScript file that retrieves data from one of several public API sources to display the data on your HTML page
5. A README file that includes the instructions for running the webpage
#### CONTENT:
1. **Display the data for at least 2 of the models in the API**
*Examples: If you choose the use the Weather API, use temperature and condition (rainy/sunny/etc) models. For the Star Wars API, use characters and film title models.*
2. **Include navigation from each model’s page to the other models that are displayed**
*Example: If you choose to use the Weather API, be able to click between a page that shows temperatures and a page that shows conditions. For the Star Wars API, have a page that shows character information and a page that shows film information.*
3. **Issue new GET requests for the linked data to display in the linked pages.**
#### FUNCTIONALITY:
- Be sure that we can get the code to run without issues by following the instructions in the README file
- Be sure navigation between the different models behaves properly and is not slowed down by requesting more data than needs to be displayed
- Be sure your code is readable and well structured
- If including a user-interactive feature like a search field, be sure that you appropriately handle error cases
- Be thoughtful about what type of styling is used (example: font-sizes are not too small or large, colors are not too dark/light to be easily seen, etc.)
***Now that you know the requirements, start planning your site!*** |
<?php
/**
* Copyright (c) Enalean, 2012. All Rights Reserved.
*
* This file is a part of Tuleap.
*
* Tuleap is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Tuleap is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Tuleap. If not, see <http://www.gnu.org/licenses/>.
*/
interface Logger {
const DEBUG = 'debug';
const INFO = 'info';
const WARN = 'warn';
const ERROR = 'error';
function debug($message);
function info($message);
/**
* Logs a warning into the log file.
*
* @param String $message the message to log.
* @param Exception $e the exception to log.
*/
function warn($message, Exception $e = null);
/**
* Logs a warning into the log file.
*
* @param String $message the message to log.
* @param Exception $e the exception to log.
*/
function error($message, Exception $e = null);
/**
* @deprecated use explicit methods
*/
function log($message, $level = null);
}
?> |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.glutenproject.columnarbatch;
import io.glutenproject.exception.GlutenException;
import io.glutenproject.exec.Runtime;
import io.glutenproject.exec.Runtimes;
import io.glutenproject.memory.arrowalloc.ArrowBufferAllocators;
import io.glutenproject.memory.nmm.NativeMemoryManager;
import io.glutenproject.utils.ArrowAbiUtil;
import io.glutenproject.utils.ArrowUtil;
import io.glutenproject.utils.ImplicitClass;
import io.glutenproject.vectorized.ArrowWritableColumnVector;
import com.google.common.base.Preconditions;
import org.apache.arrow.c.ArrowArray;
import org.apache.arrow.c.ArrowSchema;
import org.apache.arrow.c.CDataDictionaryProvider;
import org.apache.arrow.c.Data;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.catalyst.expressions.UnsafeRow;
import org.apache.spark.sql.vectorized.ColumnVector;
import org.apache.spark.sql.vectorized.ColumnarBatch;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ColumnarBatches {
private static final Field FIELD_COLUMNS;
static {
try {
Field f = ColumnarBatch.class.getDeclaredField("columns");
f.setAccessible(true);
FIELD_COLUMNS = f;
} catch (NoSuchFieldException e) {
throw new GlutenException(e);
}
}
private ColumnarBatches() {}
enum BatchType {
LIGHT,
HEAVY
}
private static BatchType identifyBatchType(ColumnarBatch batch) {
if (batch.numCols() == 0) {
// zero-column batch considered as heavy batch
return BatchType.HEAVY;
}
final ColumnVector col0 = batch.column(0);
if (col0 instanceof IndicatorVector) {
// it's likely a light batch
for (int i = 1; i < batch.numCols(); i++) {
ColumnVector col = batch.column(i);
if (!(col instanceof PlaceholderVector)) {
throw new IllegalStateException(
"Light batch should consist of one indicator vector "
+ "and (numCols - 1) placeholder vectors");
}
}
return BatchType.LIGHT;
}
// it's likely a heavy batch
for (int i = 0; i < batch.numCols(); i++) {
ColumnVector col = batch.column(i);
if (!(col instanceof ArrowWritableColumnVector)) {
throw new IllegalStateException("Heavy batch should consist of arrow vectors");
}
}
return BatchType.HEAVY;
}
private static void transferVectors(ColumnarBatch from, ColumnarBatch target) {
try {
if (target.numCols() != from.numCols()) {
throw new IllegalStateException();
}
final ColumnVector[] vectors = (ColumnVector[]) FIELD_COLUMNS.get(target);
for (int i = 0; i < target.numCols(); i++) {
vectors[i] = from.column(i);
}
} catch (IllegalAccessException e) {
throw new GlutenException(e);
}
}
/** Heavy batch: Data is readable from JVM and formatted as Arrow data. */
public static boolean isHeavyBatch(ColumnarBatch batch) {
return identifyBatchType(batch) == BatchType.HEAVY;
}
/**
* Light batch: Data is not readable from JVM, a long int handle (which is a pointer usually) is
* used to bind the batch to a native side implementation.
*/
public static boolean isLightBatch(ColumnarBatch batch) {
return identifyBatchType(batch) == BatchType.LIGHT;
}
/**
* This method will always return a velox based ColumnarBatch. This method will close the input
* column batch.
*/
public static ColumnarBatch select(
NativeMemoryManager nmm, ColumnarBatch batch, int[] columnIndices) {
switch (identifyBatchType(batch)) {
case LIGHT:
final IndicatorVector iv = getIndicatorVector(batch);
long outputBatchHandle =
ColumnarBatchJniWrapper.create()
.select(nmm.getNativeInstanceHandle(), iv.handle(), columnIndices);
return create(iv.runtime(), outputBatchHandle);
case HEAVY:
return new ColumnarBatch(
Arrays.stream(columnIndices).mapToObj(batch::column).toArray(ColumnVector[]::new),
batch.numRows());
default:
throw new IllegalStateException();
}
}
/**
* Ensure the input batch is offloaded as native-based columnar batch (See {@link IndicatorVector}
* and {@link PlaceholderVector}). This method will close the input column batch after offloaded.
*/
public static ColumnarBatch ensureOffloaded(BufferAllocator allocator, ColumnarBatch batch) {
if (ColumnarBatches.isLightBatch(batch)) {
return batch;
}
return offload(allocator, batch);
}
/**
* Ensure the input batch is loaded as Arrow-based Java columnar batch. ABI-based sharing will
* take place if loading is required, which means when the input batch is not loaded yet. This
* method will close the input column batch after loaded.
*/
public static ColumnarBatch ensureLoaded(BufferAllocator allocator, ColumnarBatch batch) {
if (isHeavyBatch(batch)) {
return batch;
}
return load(allocator, batch);
}
private static ColumnarBatch load(BufferAllocator allocator, ColumnarBatch input) {
if (!ColumnarBatches.isLightBatch(input)) {
throw new IllegalArgumentException(
"Input is not light columnar batch. "
+ "Please consider to use vanilla spark's row based input by setting one of the below"
+ " configs: \n"
+ "spark.sql.parquet.enableVectorizedReader=false\n"
+ "spark.sql.inMemoryColumnarStorage.enableVectorizedReader=false\n"
+ "spark.sql.orc.enableVectorizedReader=false\n");
}
IndicatorVector iv = (IndicatorVector) input.column(0);
try (ArrowSchema cSchema = ArrowSchema.allocateNew(allocator);
ArrowArray cArray = ArrowArray.allocateNew(allocator);
ArrowSchema arrowSchema = ArrowSchema.allocateNew(allocator);
CDataDictionaryProvider provider = new CDataDictionaryProvider()) {
ColumnarBatchJniWrapper.forRuntime(iv.runtime())
.exportToArrow(iv.handle(), cSchema.memoryAddress(), cArray.memoryAddress());
Data.exportSchema(
allocator, ArrowUtil.toArrowSchema(cSchema, allocator, provider), provider, arrowSchema);
ColumnarBatch output =
ArrowAbiUtil.importToSparkColumnarBatch(allocator, arrowSchema, cArray);
// Follow gluten input's reference count. This might be optimized using
// automatic clean-up or once the extensibility of ColumnarBatch is enriched
IndicatorVector giv = (IndicatorVector) input.column(0);
ImplicitClass.ArrowColumnarBatchRetainer retainer =
new ImplicitClass.ArrowColumnarBatchRetainer(output);
for (long i = 0; i < (giv.refCnt() - 1); i++) {
retainer.retain();
}
// close the input one
for (long i = 0; i < giv.refCnt(); i++) {
input.close();
}
// populate new vectors to input
transferVectors(output, input);
return input;
}
}
private static ColumnarBatch offload(BufferAllocator allocator, ColumnarBatch input) {
if (!isHeavyBatch(input)) {
throw new IllegalArgumentException("batch is not Arrow columnar batch");
}
if (input.numCols() == 0) {
throw new IllegalArgumentException("batch with zero columns cannot be offloaded");
}
final Runtime runtime = Runtimes.contextInstance();
try (ArrowArray cArray = ArrowArray.allocateNew(allocator);
ArrowSchema cSchema = ArrowSchema.allocateNew(allocator)) {
ArrowAbiUtil.exportFromSparkColumnarBatch(
ArrowBufferAllocators.contextInstance(), input, cSchema, cArray);
long handle =
ColumnarBatchJniWrapper.forRuntime(runtime)
.createWithArrowArray(cSchema.memoryAddress(), cArray.memoryAddress());
ColumnarBatch output = ColumnarBatches.create(runtime, handle);
// Follow input's reference count. This might be optimized using
// automatic clean-up or once the extensibility of ColumnarBatch is enriched
long refCnt = getRefCntHeavy(input);
final IndicatorVector giv = (IndicatorVector) output.column(0);
for (long i = 0; i < (refCnt - 1); i++) {
giv.retain();
}
// close the input one
for (long i = 0; i < refCnt; i++) {
input.close();
}
// populate new vectors to input
transferVectors(output, input);
return input;
}
}
public static Iterator<InternalRow> emptyRowIterator(int numRows) {
final int maxRows = numRows;
return new Iterator<InternalRow>() {
int rowId = 0;
@Override
public boolean hasNext() {
return rowId < maxRows;
}
@Override
public InternalRow next() {
if (rowId >= maxRows) {
throw new NoSuchElementException();
}
rowId++;
return new UnsafeRow(0);
}
};
}
private static long getRefCntLight(ColumnarBatch input) {
if (!isLightBatch(input)) {
throw new UnsupportedOperationException("Input batch is not light batch");
}
IndicatorVector iv = (IndicatorVector) input.column(0);
return iv.refCnt();
}
private static long getRefCntHeavy(ColumnarBatch input) {
if (!isHeavyBatch(input)) {
throw new UnsupportedOperationException("Input batch is not heavy batch");
}
if (input.numCols() == 0) {
throw new IllegalArgumentException(
"batch with zero columns doesn't have meaningful " + "reference count");
}
long refCnt = -1L;
for (int i = 0; i < input.numCols(); i++) {
ArrowWritableColumnVector col = ((ArrowWritableColumnVector) input.column(i));
long colRefCnt = col.refCnt();
if (refCnt == -1L) {
refCnt = colRefCnt;
} else {
if (colRefCnt != refCnt) {
throw new IllegalStateException();
}
}
}
if (refCnt == -1L) {
throw new IllegalStateException();
}
return refCnt;
}
private static long getRefCnt(ColumnarBatch input) {
switch (identifyBatchType(input)) {
case LIGHT:
return getRefCntLight(input);
case HEAVY:
return getRefCntHeavy(input);
default:
throw new IllegalStateException();
}
}
public static void forceClose(ColumnarBatch input) {
for (long i = 0; i < getRefCnt(input); i++) {
input.close();
}
}
private static IndicatorVector getIndicatorVector(ColumnarBatch input) {
if (!isLightBatch(input)) {
throw new UnsupportedOperationException("Input batch is not light batch");
}
return (IndicatorVector) input.column(0);
}
/**
* Combine multiple columnar batches horizontally, assuming each of them is already offloaded.
* Otherwise {@link UnsupportedOperationException} will be thrown.
*/
public static long compose(ColumnarBatch... batches) {
IndicatorVector[] ivs =
Arrays.stream(batches)
.map(ColumnarBatches::getIndicatorVector)
.toArray(IndicatorVector[]::new);
// We assume all input batches should be managed by same Runtime.
// FIXME: The check could be removed to adopt ownership-transfer semantic
final Runtime[] ctxs =
Arrays.stream(ivs).map(IndicatorVector::runtime).distinct().toArray(Runtime[]::new);
Preconditions.checkState(
ctxs.length == 1, "All input batches should be managed by same Runtime.");
final long[] handles = Arrays.stream(ivs).mapToLong(IndicatorVector::handle).toArray();
return ColumnarBatchJniWrapper.forRuntime(ctxs[0]).compose(handles);
}
public static ColumnarBatch create(Runtime runtime, long nativeHandle) {
final IndicatorVector iv = new IndicatorVector(runtime, nativeHandle);
int numColumns = Math.toIntExact(iv.getNumColumns());
int numRows = Math.toIntExact(iv.getNumRows());
if (numColumns == 0) {
return new ColumnarBatch(new ColumnVector[0], numRows);
}
final ColumnVector[] columnVectors = new ColumnVector[numColumns];
columnVectors[0] = iv;
long numPlaceholders = numColumns - 1;
for (int i = 0; i < numPlaceholders; i++) {
final PlaceholderVector pv = PlaceholderVector.INSTANCE;
columnVectors[i + 1] = pv;
}
return new ColumnarBatch(columnVectors, numRows);
}
public static void retain(ColumnarBatch b) {
switch (identifyBatchType(b)) {
case LIGHT:
IndicatorVector iv = (IndicatorVector) b.column(0);
iv.retain();
return;
case HEAVY:
for (int i = 0; i < b.numCols(); i++) {
ArrowWritableColumnVector col = ((ArrowWritableColumnVector) b.column(i));
col.retain();
}
return;
default:
throw new IllegalStateException();
}
}
public static void release(ColumnarBatch b) {
b.close();
}
public static long getNativeHandle(ColumnarBatch batch) {
return getIndicatorVector(batch).handle();
}
public static Runtime getRuntime(ColumnarBatch batch) {
return getIndicatorVector(batch).runtime();
}
} |
import { getLlantasAll, postLlantas, deleteLlantas, updLlantasOne, getLlantasOne, getUsuarioOne } from "./API/API.js";
addEventListener("DOMContentLoaded", iniciar())
async function iniciar(){
const token = localStorage.getItem('token');
const oneUsuario = parseJwt(token);
const usuarioId = oneUsuario.uid
const rolUsuario = await getUsuarioOne(usuarioId);
const datos = await getLlantasAll();
const tablas = document.querySelector(".listadoProductos");
const thead = document.querySelector(".thead");
const boton = document.querySelector(".titulo2");
datos.forEach(element => {
const {_id, Tipo, Ubicacion, Ancho, Perfil, Carga, Precio, Marca, Stock} = element
const {rol} = rolUsuario;
if(rol == "ADMIN"){
boton.innerHTML = `
<div class="button-modal container-fluid" style="width: 50px; margin-right: 0px; margin-left: 20px;">
<i class="plus bi bi-plus-circle fs-1 text-white" data-bs-toggle="modal"data-bs-target="#addCategorias" type="button" ></i>
</div>
`
thead.innerHTML = `
<tr class="encabezadoTabla">
<th>ID</th>
<th>MARCA</th>
<th>TIPO</th>
<th>UBICACION</th>
<th>ANCHO</th>
<th>PERFIL</th>
<th>CARGA</th>
<th>PRECIO</th>
<th>MARCA</th>
<th>STOCK</th>
<th>EDITAR</th>
<th>ELIMINAR</th>
</tr>
`
tablas.innerHTML += `
<tr>
<th scope="row">${_id}</th>
<td>${Marca}</td>
<td>${Tipo}</td>
<td>${Ubicacion}</td>
<td>${Ancho}</td>
<td>${Perfil}</td>
<td>${Carga}</td>
<td>${Precio}</td>
<td>${Marca}</td>
<td>${Stock}</td>
<td><button class="btn btn-outline-danger delete" id="${_id}">Eliminar</button></td>
<td><button class="btn btn-outline-warning edit" data-bs-toggle="modal" data-bs-target="#modalUpdate" id="${_id}">Editar</button></td>
</tr>`
}
else if(rol == "VENTAS"){
boton.innerHTML = ``
thead.innerHTML = `
<tr class="encabezadoTabla">
<th>ID</th>
<th>MARCA</th>
<th>TIPO</th>
<th>UBICACION</th>
<th>ANCHO</th>
<th>PERFIL</th>
<th>CARGA</th>
<th>PRECIO</th>
<th>MARCA</th>
<th>STOCK</th>
</tr>
`
tablas.innerHTML += `
<tr>
<th scope="row">${_id}</th>
<td>${Marca}</td>
<td>${Tipo}</td>
<td>${Ubicacion}</td>
<td>${Ancho}</td>
<td>${Perfil}</td>
<td>${Carga}</td>
<td>${Precio}</td>
<td>${Marca}</td>
<td>${Stock}</td>
</tr>`
}
});
}
const formulario = document.getElementById('formularioVarios');
formulario.addEventListener("submit", postDatos);
function postDatos(e){
e.preventDefault();
const Tipo = document.querySelector('#Tipo').value;
const Ubicacion = document.querySelector('#Ubicacion').value;
const Ancho = document.querySelector('#Ancho').value;
const Perfil = document.querySelector('#Perfil').value;
const Carga = document.querySelector('#Carga').value;
const Precio = document.querySelector('#Precio').value;
const Marca = document.querySelector('#Marca').value;
const Stock = document.querySelector('#Stock').value;
const registro = {
Tipo,
Ubicacion,
Ancho,
Perfil,
Carga,
Precio,
Marca,
Stock
}
console.log(registro);
if(validation(registro)){
postLlantas(registro)
}else{
console.log("Hubo un error en la validación de datos. Intenta nuevamente.");
}
}
//DELETE
const laTabla = document.querySelector(".listadoProductos");
laTabla.addEventListener("click", detectarID);
async function detectarID(e){
if(e.target.classList.contains("delete")){
const id_Llantas = e.target.getAttribute("id");
console.log(id_Llantas);
const confir = confirm("¿Seguro que deseas eliminar el dato?")
if(confir){
deleteLlantas(id_Llantas);
}
}
if(e.target.classList.contains("edit")){
e.preventDefault();
const id_Llantas = e.target.getAttribute("id");
const datos = await getLlantasOne(id_Llantas);
console.log(datos);
const Tipo = document.querySelector("#TipoEdit");
const Ubicacion = document.querySelector("#UbicacionEdit");
const Ancho = document.querySelector("#AnchoEdit");
const Perfil = document.querySelector("#PerfilEdit");
const Carga = document.querySelector("#CargaEdit");
const Precio = document.querySelector("#PrecioEdit");
const Marca = document.querySelector("#MarcaEdit");
const Stock = document.querySelector("#StockEdit");
Tipo.value = datos.Tipo;
Ubicacion.value = datos.Ubicacion;
Ancho.value = datos.Ancho;
Perfil.value = datos.Perfil;
Carga.value = datos.Carga;
Precio.value = datos.Precio;
Marca.value = datos.Marca;
Stock.value = datos.Stock;
const formularioEdit = document.querySelector("#formularioEdit");
formularioEdit.addEventListener("submit", updEquipo);
function updEquipo(e){
e.preventDefault();
const Tipo = document.querySelector("#TipoEdit").value
const Ubicacion = document.querySelector("#UbicacionEdit").value
const Ancho = document.querySelector("#AnchoEdit").value
const Perfil = document.querySelector("#PerfilEdit").value
const Carga = document.querySelector("#CargaEdit").value
const Precio = document.querySelector("#PrecioEdit").value
const Marca = document.querySelector("#MarcaEdit").value
const Stock = document.querySelector("#StockEdit").value
const datosUpd = {
Tipo,
Ubicacion,
Ancho,
Perfil,
Tipo,
Carga,
Precio,
Marca,
Stock
}
console.log(datosUpd);
if(validation(datosUpd)){
updLlantasOne(datosUpd, id_Llantas);
}
}
}
}
function validation(Objeto){
return Object.values(Objeto).every(element => element !== '')
}
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}; |
declare global {
namespace jest {
interface Expect {
/**
* Asserts that a value is a `true`, `false`, `new Boolean(true)`, or `new Boolean(false)`.
* @param divisor
* @example
* expect(onPress).toHaveBeenCalledWith(
* expect.objectContaining({
* isActive: expect.toBeBoolean()
* })
* );
*/
toBeBoolean<T>(): Matchers<T>;
}
interface Matchers<R> {
/**
* Asserts that a value is a `true`, `false`, `new Boolean(true)`, or `new Boolean(false)`.
* @example
* expect(player.isActive).toBeBoolean();
*/
toBeBoolean(): R;
}
}
}
export declare const toBeBooleanMatcher: (received: any) => {
message: () => string;
pass: boolean;
}; |
package mil.af.abms.midas.api.comment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;
import org.junit.jupiter.api.Test;
import mil.af.abms.midas.api.assertion.Assertion;
import mil.af.abms.midas.api.comment.dto.CommentDTO;
import mil.af.abms.midas.api.helper.Builder;
import mil.af.abms.midas.api.user.User;
class CommentTests {
private static final int ENTITY_DTO_FIELD_OFFSET = 2;
private final User createdBy = Builder.build(User.class).with(u -> u.setId(1L)).get();
private final Assertion assertion = Builder.build(Assertion.class)
.with(a -> a.setId(1L))
.with(a -> a.setText("First"))
.with(a -> a.setCreatedBy(createdBy)).get();
private final Comment parentComment = Builder.build(Comment.class).with(c -> c.setId(55L)).get();
private final Comment comment = Builder.build(Comment.class)
.with(c -> c.setId(1L))
.with(c -> c.setText("New Idea"))
.with(c -> c.setParent(parentComment))
.with(c -> c.setAssertion(assertion))
.with(c -> c.setCreatedBy(createdBy))
.get();
private final CommentDTO commentDTO = Builder.build(CommentDTO.class)
.with(c -> c.setId(1L))
.with(c -> c.setText("New Idea"))
.with(c -> c.setParentId(parentComment.getId()))
.with(c -> c.setAuthor(createdBy.toDto()))
.with(d -> d.setCreationDate(comment.getCreationDate()))
.with(d -> d.setChildren(Set.of()))
.get();
@Test
void should_have_all_dto_fields() {
List<Field> fields = new LinkedList<>();
ReflectionUtils.doWithFields(Comment.class, fields::add);
assertThat(fields).hasSize(CommentDTO.class.getDeclaredFields().length + ENTITY_DTO_FIELD_OFFSET);
}
@Test
void should_be_equal() {
Comment comment2 = new Comment();
BeanUtils.copyProperties(comment, comment2);
assertEquals(comment, comment);
assertNotEquals(comment, null);
assertNotEquals(comment, new User());
assertNotEquals(comment, new Comment());
assertEquals(comment, comment2);
}
@Test
void should_get_properties() {
assertThat(comment.getId()).isEqualTo(1L);
assertThat(comment.getText()).isEqualTo("New Idea");
assertThat(comment.getParent()).isEqualTo(parentComment);
assertThat(comment.getCreatedBy()).isEqualTo(createdBy);
assertThat(comment.getAssertion()).isEqualTo(assertion);
}
@Test
void can_return_dto() { assertThat(comment.toDto()).isEqualTo(commentDTO); }
} |
AgentMover mover;
int MASS_TO_PIXEL=10;
float mass_mover = 10;
float mass_attractor;
PVector pos_attractor;
float radius_attractor;
float area;
float dist=0;
String[] getFilenames(){
String path=sketchPath()+"/sounds";
File dir = new File(path);
String all_filenames[] = dir.list();
int N_wavs=0;
for(int i=0; i<all_filenames.length; i++){
if (all_filenames[i].endsWith(".wav")){ N_wavs++;}
}
String[] wav_filenames= new String[N_wavs];
int j=0;
for(int i=0; i<all_filenames.length; i++){
if (all_filenames[i].endsWith(".wav")){
wav_filenames[j]=sketchPath()+"/sounds/" + all_filenames[i];
j++;}
}
return wav_filenames;
}
void setup(){
mover=new AgentMover(10);
mass_attractor=random(800, 1200);
pos_attractor = new PVector(width/2., height/2.);
radius_attractor = sqrt(mass_attractor/PI)*MASS_TO_PIXEL;
size(1280, 720);
background(0);
}
PVector computeGravityForce(AgentMover mover){
PVector attr_force = mover.position.copy();
attr_force.sub(pos_attractor);
dist= attr_force.mag();
dist=constrain(dist, dist_min,dist_max);
attr_force.normalize();
attr_force.mult(-1*mass_attractor*mover.mass/(dist*dist));
return attr_force;
}
void draw(){
rectMode(CORNER);
fill(0,20);
rect(0,0,width, height);
fill(200, 0, 200, 40);
ellipse(pos_attractor.x, pos_attractor.y,
radius_attractor, radius_attractor);
PVector force = computeGravityForce(mover);
mover.applyForce(force);
mover.update();
mover.draw();
} |
const { Actor, Movie } = require("../models");
const { movieExistsError } = require("../helpers/index.js");
const { formatMovieResponse } = require("../helpers/index.js");
const createMovie = async (req, res) => {
try {
const { title, year, format, actors } = req.body;
const existingMovie = await Movie.findOne({ where: { title } });
if (existingMovie) {
return res.status(400).json(movieExistsError);
}
const invalidActors = actors.filter(actor => {
const regex = /^[A-Za-z\-,\s]+$/;
return !regex.test(actor);
});
if (invalidActors.length > 0) {
return res.status(400).json({ error: "Actor names must not contain numbers or symbols except ',' and '-'." });
}
const newMovie = await Movie.create({ title, year, format });
const createdActors = await Promise.all(
actors.map((actor) => Actor.create({ name: actor, MovieId: newMovie.id }))
);
await newMovie.addActors(createdActors);
const fetchedMovie = await Movie.findByPk(newMovie.id, {
include: Actor,
});
res.status(201).json(formatMovieResponse(fetchedMovie));
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
};
module.exports = { createMovie }; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS + CSS Clock</title>
</head>
<body>
<div class="clock">
<div class="clock-face">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand second-hand"></div>
</div>
</div>
<style>
html {
background: #018DED url(http://unsplash.it/1500/1000?image=881&blur=50);
background-size: cover;
font-family: 'helvetica neue';
text-align: center;
font-size: 10px;
}
body {
margin: 0;
font-size: 2rem;
display: flex;
flex: 1;
min-height: 100vh;
align-items: center;
}
.clock {
width: 30rem;
height: 30rem;
border: 20px solid white;
border-radius: 50%;
margin: 50px auto;
position: relative;
padding: 2rem;
box-shadow:
0 0 0 4px rgba(0,0,0,0.1),
inset 0 0 0 3px #EFEFEF,
inset 0 0 10px black,
0 0 10px rgba(0,0,0,0.2);
}
.clock-face {
position: relative;
width: 100%;
height: 100%;
transform: translateY(-3px); /* account for the height of the clock hands */
}
.hand {
width: 50%;
height: 6px;
background: black;
position: absolute;
top: 50%;
transform-origin: 100% 60%;
}
</style>
<script>
//get the divs
const secHandEle = document.querySelector('.second-hand');
const minHandEle = document.querySelector('.min-hand');
const hourHandEle = document.querySelector('.hour-hand');
//initial angle variables
let initSecAngle;
let initMinAngle;
let initHourAngle;
//angle of each hand per second,per min and per min respectively
let secAngle = 6;
let minAngle = 6;
let hourAngle = 0.5;
//get current date,sec,min and hour
//get initial angle of the clock hands
//style the clock hands to rotate in calculated degrees
function init(){
let currentDate = new Date();
const timeSec = currentDate.getSeconds();
const timeMin = currentDate.getMinutes();
const timeHrs = currentDate.getHours();
initSecAngle = 90 + timeSec * 6;
initMinAngle = 90 + timeMin * 6;
initHourAngle = 90 + timeHrs * 30 + timeMin * 0.5;
secHandEle.style.transform = `rotate(${initSecAngle}deg)`;
minHandEle.style.transform = `rotate(${initMinAngle}deg)`;
hourHandEle.style.transform = `rotate(${initHourAngle}deg)`;
}
//rotate the clock hands
function dial(){
secHandEle.style.transform = `rotate(${initSecAngle + secAngle}deg)`;
secAngle = (secAngle + 6);
if(secAngle === 360){
secAngle = 6;
minHandEle.style.transform = `rotate(${initMinAngle + minAngle}deg)`;
minAngle = (minAngle + 6);
hourHandEle.style.transform = `rotate(${initHourAngle + hourAngle}deg)`;
hourAngle = (hourAngle + 0.5);
}
}
//call init() and call dial at every second
init();
window.setInterval(function(){
dial();
},1000);
</script>
</body>
</html> |
---
date: "2022-01-18T00:00:00Z"
external_link: ""
links:
- icon: link
icon_pack: fa
name: Slides
url: https://zoterotutorials.netlify.app/#1
- icon: youtube
icon_pack: fab
name: Videos
url: https://www.youtube.com/watch?v=REfQTIYxeMU&list=PL8dil_YRqri670TX9LOzb3NDwKSCuf8ro
- icon: github
icon_pack: fab
name: Materials
url: https://github.com/eemilmitikka/zotero-tutorials
- icon: file-pdf
icon_pack: fa
name: PDF
url: https://github.com/eemilmitikka/zotero-tutorials/blob/main/zotero_tutorials_slides.pdf
summary: Zotero instructions videos and presentation slides.
tags:
- reference management
- Zotero
- MS Word
- xaringan
- scientific writing
title: Zotero Tutorials & (xaringan) Slides
bibliography: "zotero-tutorials-references.bib"
csl: american-political-science-association.csl
---
```{r include=FALSE, warning=FALSE}
# citation("xaringan")
# knitr::write_bib("xaringan", file = "zotero-tutorials-references.bib")
```
# Purpose
This short blog post is just to inform you that I've done some instruction videos on how to use Zotero for more efficient reference management in Microsoft Word. Videos and related presentation slides and GitHub materials can be accessed by clicking the buttons under the title of this post.
Videos were done for University of Helsinki's [Master's Programme in Russian Studies](https://www.helsinki.fi/en/degree-programmes/russian-studies-masters-programme) students, and thus the contents were designed with these students in mind.
## Why do I teach using Zotero in MS Word instead of using it in RStudio?
Since I'm an R user myself, some of you might ask: why do you want to demonstrate the use of Zotero in ***MS Word environment*** (commercial software) instead of ***RStudio environment*** (free software)?
The reason for this is that although I love R and RStudio (like other good free and open-source softwares), based on my experience most social scientists and humanists are (still, hopefully this will change in the future!) using MS Word to write their texts. I'm aware that MS Word is quite clumsy software and might unjustly enjoy a near-monopolist position in the text processing field, as Charlie Stross [-@stross_why_nodate] has stated. However, since most people in my target group (here: students of Russia Studies) aren't R users and I had only limited time to teach them, I thought it will be more useful to them to show how to use Zotero with Word first. Besides, if you can use Zotero fluently with Word, you should be able to apply the same principles in using it with RStudio -- so videos should be useful for current and future R users too!
## Future plans
Next, I'm planning to do some instruction videos on how to use Zotero with RStudio/RMarkdown. I already found some interesting videos on the topic by Ulrik Lyngs [@lyngs_ulrik_nodate], so I should check them out before going on with this plan.
### Technical details
For those who are interested, here's how videos and other materials were produced:
* Videos were recorded with MacBook Pro's default QuickTime Player.
* Videos were edited in YouTube Studio (mainly added the subtitles and cut some extra seconds from the beginning and end of the videos).
* Presentation materials were done using the **xaringan package** by Yihui Xie [-@R-xaringan].
### References |
<script>
export default {
props: [
"table",
"movies",
"genres",
"logs",
"optionStatus",
"role",
"idUser",
],
methods: {
deleteGenreHandler(id, name) {
Swal.fire({
title: `Are you sure want to delete genre ${name}?`,
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
}).then((result) => {
if (result.isConfirmed) {
this.$emit("deleteGenre", { id, name });
Swal.fire({
position: "top",
icon: "success",
title: `Delete ${name} Success!`,
showConfirmButton: false,
timer: 1500,
});
}
});
},
editMovieHandler(id) {
this.$emit("editMovieHandler", id);
},
updateStatusHandler(id, event) {
let payload = {
id,
status: event.target.value,
};
this.$emit("updateStatus", payload);
},
editGenreHandler(name, id) {
let payload = {
name,
id,
};
this.$emit("editGenre", payload);
},
},
};
</script>
<template>
<tr v-if="table === 'movies'" v-for="(movie, index) in movies" :key="index">
<td scope="row">{{ index + 1 }}</td>
<td class="fw-bold">{{ movie.title }}</td>
<td>
<img :src="movie.imgUrl" class="img-fluid" />
</td>
<td>{{ movie.synopsis }}</td>
<td>
<iframe width="200" height="150" :src="movie.trailerUrl"> </iframe>
</td>
<td class="fw-bold">{{ movie.rating }}</td>
<td>{{ movie.Genre.name }}</td>
<td>{{ movie.User.email }}</td>
<td>
<select
v-if="role === 'admin'"
name="Status"
id=""
v-on:change="updateStatusHandler(movie.id, $event)"
>
<option
v-for="status in optionStatus"
:value="status"
:selected="movie.status === status"
>
{{ status }}
</option>
</select>
<span v-if="role !== 'admin'">{{ movie.status }} </span>
</td>
<td>
<a
v-if="role === 'admin' || movie.authorId == idUser"
href=""
class="ms-3 btn btn-info"
v-on:click.prevent="editMovieHandler(movie.id)"
>Edit</a
>
</td>
</tr>
<tr v-if="table === 'genres'" v-for="(genre, index) in genres" :key="index">
<td scope="row">{{ index + 1 }}</td>
<td class="fw-bold">{{ genre.name }}</td>
<td>
<a
href=""
class="ms-3 btn btn-info"
v-on:click.prevent="editGenreHandler(genre.name, genre.id)"
>EDIT</a
>
</td>
<td>
<a
href=""
class="ms-3 btn btn-danger"
v-on:click.prevent="deleteGenreHandler(genre.id, genre.name)"
>DELETE
</a>
</td>
</tr>
<tr v-if="table === 'logs'" v-for="(log, index) in logs" :key="index">
<td scope="row">#{{ index + 1 }}</td>
<td class="fw-bold">{{ log.title }}</td>
<td>{{ log.description }}</td>
<td>
{{ new Date(log.createdAt).toLocaleString() }}
</td>
<td>
{{ log.updatedBy }}
</td>
</tr>
</template>
<style>
img {
width: 50px;
}
</style> |
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-hot-toast'
import copy from 'copy-to-clipboard'
import {ACCOUNT_TYPE} from "../../../utils/constants"
import { addToCart } from '../../../Slices/cartSlice'
import { BsFillCaretRightFill } from "react-icons/bs"
import { FaShareSquare } from "react-icons/fa"
const CourseDetailsCard = ({course,setConfirmationModal,handleBuyCourse}) => {
const {user}=useSelector((state)=>state.profile)
const {token}=useSelector((state)=>state.auth)
const navigate=useNavigate()
const dispatch=useDispatch()
const handleAddToCart=()=>{
if(user&& user?.accountType===ACCOUNT_TYPE.INSTRUCTOR){
toast.error("You are an Insructor,you can not buy a course")
return
}
if(token){
console.log("dispatching add to cart")
dispatch(addToCart(course));
return;
}
setConfirmationModal({
text1:"you are not logged in",
text2:"Please login to add to cart",
btn1Text:"login",
btn2Text:"cancel",
btn1Handler:()=>navigate("/login"),
btn2Handler: ()=> setConfirmationModal(null),
})
}
const handleShare=()=>{
copy(window.location.href)
toast.success("Link Copied To Clickboard")
}
return (
<div className={`flex flex-col gap-4 rounded-md bg-richblack-700 p-4 text-richblack-5`}>
<img src={course?.thumbnail} alt='thumbnail' className="max-h-[300px] min-h-[180px] w-[400px] overflow-hidden rounded-2xl object-cover md:max-w-full"/>
<div className="px-4">
<div className="space-x-3 pb-4 text-3xl font-semibold">Rs. {course?.price}</div>
<div className="flex flex-col gap-4">
<button className="yellowButton" onClick={ user && course?.studentsEnrolled.includes(user?._id)? ()=>{navigate("/dashboard/enrolled-courses")}:handleBuyCourse }>
{
user && course?.studentsEnrolled.includes(user?._id)? "Go To Course":"Buy Now"
}
</button>
{
(!course?.studentsEnrolled.includes(user?._id)) &&(
<button className="blackButton" onClick={handleAddToCart}>
Add To Cart
</button>
)
}
</div>
<div>
<p className="pb-3 pt-6 text-center text-sm text-richblack-25">
30-Day Money-Back Guarantee
</p>
</div>
<div className={``}>
<p className={`my-2 text-xl font-semibold `}>
This Course Includes :
</p>
<div className="flex flex-col gap-3 text-sm text-caribbeangreen-100">
{course?.instructions?.map((item, i) => {
return (
<p className={`flex gap-2`} key={i}>
<BsFillCaretRightFill />
<span>{item}</span>
</p>
)
})}
</div>
</div>
<div className="text-center">
<button
className="mx-auto flex items-center gap-2 py-6 text-yellow-100 "
onClick={handleShare}
>
<FaShareSquare size={15} /> Share
</button>
</div>
</div>
</div>
)
}
export default CourseDetailsCard |
<template>
<div class="v-search-container">
<div class="v-search-container__block">
<v-my-input :model-value="this.searchQuery"
@update:model-value="SET_SEARCH_QUERY"/>
<button @click="showDialog"
class="v-search-container__btn"
v-if="COUNT_ACTIVE_FILTERS === 0"
>
<span class="material-symbols-outlined">
filter_alt
</span>
Фильтр
</button>
<button @click="showDialog"
class="v-search-container__btn_filter"
v-else>
<span class="material-symbols-outlined">
filter_alt
</span>
Фильтр ({{COUNT_ACTIVE_FILTERS}})
</button>
<v-filter-container v-model:show="dialogVisible">
<v-filter-form/>
</v-filter-container>
</div>
</div>
</template>
<script>
import VMyInput from "@/components/content/search/v-my-input.vue";
import {mapGetters, mapMutations, mapState} from "vuex";
import VFilterContainer from "@/components/filters/v-filter-container.vue";
import VFilterForm from "@/components/filters/v-filter-form.vue";
export default {
name: 'v-search-container',
components: {VFilterForm, VFilterContainer, VMyInput},
data() {
return {
dialogVisible: false,
}
},
methods: {
showDialog() {
this.dialogVisible = true;
},
...mapMutations({
SET_SEARCH_QUERY: "users/SET_SEARCH_QUERY"
})
},
computed: {
...mapState({
users: state => state.users.users,
searchQuery: state => state.users.searchQuery,
countActiveFilters: state => state.countActiveFilters
}),
...mapGetters({
COUNT_ACTIVE_FILTERS: "users/COUNT_ACTIVE_FILTERS"
})
}
}
</script>
<style lang="scss" scoped>
.v-search-container {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 30px;
margin-top: 30px;
&__block {
width: 95%;
display: flex;
align-items: center;
justify-content: space-between;
}
&__btn, &__btn_filter {
z-index: 1;
cursor: pointer;
width: 175px;
height: 55px;
border: 1px solid transparent;
border-radius: 7px;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
color: rgb(3,158,247);
font-weight: 600;
transition: 300ms;
background: rgb(241,250,255);
}
@media (hover: hover) {
&__btn:hover, &__btn_filter:hover{
color: white;
background: rgb(3,158,247);
border: 1px solid rgba(3, 158, 247, 0.45);
}
}
&__btn span {
font-weight: 600;
margin-right: 5px;
font-size: 18px;
}
}
@media screen and (max-width: 500px) {
.v-search-container {
&__block {
flex-direction: column;
align-items: flex-start;
}
&__btn, &__btn_filter {
margin-top: 10px;
}
}
}
</style> |
from rest_framework.generics import ListCreateAPIView, RetrieveAPIView, DestroyAPIView, UpdateAPIView, ListAPIView
# rest methods
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import NotFound
# serializer
from api.serializers import TodoSerializer, CategorySerializer
#permissions & authentication
from rest_framework import permissions
from rest_framework import authentication
#models
from todo_app.models import Todo, Category
# VIEWS
### Todos
class TodoListCreateView(ListCreateAPIView):
serializer_class = TodoSerializer
def get_queryset(self):
user = self.request.user
return Todo.objects.filter(user=user)
def perform_create(self, serializer):
user = self.request.user
serializer.save(user=user)
class TodoDetailView(RetrieveAPIView):
serializer_class = TodoSerializer
lookup_field = 'id'
def get_object(self):
obj = Todo.objects.filter(id=self.kwargs.get('id'), user=self.request.user).first()
if obj is not None:
return obj
else:
raise NotFound({'info':'Todo not found!'})
class TodoDestroyView(DestroyAPIView):
def delete(self, request, *args, **kwargs):
id = self.kwargs.get('id')
item_to_delete = Todo.objects.filter(pk=id, user=request.user).first()
if item_to_delete:
item_to_delete.delete()
return Response({'Info':'Item Succesfully Deleted', 'status':'200'}, status=status.HTTP_200_OK)
return Response({'Info':'Item not found', 'status':'404'}, status=status.HTTP_404_NOT_FOUND)
class TodoUpdateView(UpdateAPIView):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
lookup_field = 'id'
def update(self, request, *args, **kwargs):
id = kwargs.get('id')
obj = Todo.objects.filter(pk=id, user=request.user).first()
if not obj:
return Response({'info':'Instance that you are trying to update not found!', 'status':'404'}, status=status.HTTP_404_NOT_FOUND)
super().update(request, *args, **kwargs) # UpdateAPIView default update method. It calls UpdateMixin
return Response({'info':'Instance Succesfully Updated', 'status':'200'}, status=status.HTTP_200_OK)
### Category
class CategoryListCreateView(ListCreateAPIView):
serializer_class = CategorySerializer
def get_queryset(self):
user = self.request.user
return Category.objects.filter(user=user)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class CategoryDetailView(RetrieveAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializer
def get_object(self):
id = self.kwargs.get('id')
user = self.request.user
try:
obj = Category.objects.get(pk=id, user=user)
except:
raise NotFound({'info':'Category Instance Not Found!'})
else:
return obj
class CategoryDeleteView(DestroyAPIView):
def delete(self, request, *args, **kwargs):
id = kwargs.get('id')
user = request.user
try:
obj = Category.objects.get(pk=id, user=user)
except:
return Response({'info':'Category Instance Not Found!'}, status=status.HTTP_404_NOT_FOUND)
else:
obj.delete()
return Response({'info':'Category Instance Succesfully Deleted'}, status=status.HTTP_200_OK)
class CategoryUpdateView(UpdateAPIView):
queryset = Category.objects.all()
lookup_field = 'id'
serializer_class = CategorySerializer
def update(self, request, *args, **kwargs):
try:
obj = Category.objects.get(pk=kwargs.get('id'), user=request.user) # if there is an instance
except:
return Response({'info':'Category Instance Not Found!'}, status=status.HTTP_404_NOT_FOUND)
else:
super().update(request, *args, **kwargs)
return Response({'info':'Category Instance Succesfully Updated'}, status=status.HTTP_200_OK)
# Category Based Todo Filtering
class TodoCategoryListView(ListAPIView):
serializer_class = TodoSerializer
lookup_field = 'slug'
queryset = Todo.objects.all()
def get_queryset(self):
slug = self.kwargs.get('category_slug')
try:
category = Category.objects.get(slug=slug)
except:
# return Response({'info':'Category Instance Not Found'}) -> get query set metodunda bu şekilde Response Dönemiyoruz.
raise NotFound({'info':'Category Instance Not Found'}, code=status.HTTP_404_NOT_FOUND)
else:
return category.todo_set.all() |
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2016.
*/
import harness.x10Test;
import x10.matrix.DenseMatrix;
import x10.matrix.ElemType;
import x10.matrix.block.Grid;
import x10.matrix.block.DenseBlockMatrix;
import x10.matrix.dist.DistDenseMatrix;
public class TestDistDense extends x10Test {
static def ET(a:Double)= a as ElemType;
static def ET(a:Float)= a as ElemType;
public val nzp:Float;
public val M:Long;
public val N:Long;
public val K:Long;
public def this(args:Rail[String]) {
M = args.size > 0 ? Long.parse(args(0)):4;
nzp = args.size > 1 ?Float.parse(args(1)):0.5f;
N = args.size > 2 ? Long.parse(args(2)):(M as Int)+1;
K = args.size > 3 ? Long.parse(args(3)):(M as Int)+2;
}
public def run():Boolean {
Console.OUT.println("Starting dist dense matrix clone/add/sub/scaling tests");
Console.OUT.printf("Matrix M:%d K:%d N:%d\n", M, N, K);
var ret:Boolean = true;
ret &= (testClone());
ret &= (testInit());
ret &= (testCopyTo());
ret &= (testScale());
ret &= (testAdd());
ret &= (testAddSub());
ret &= (testAddAssociative());
ret &= (testScaleAdd());
ret &= (testCellMult());
ret &= (testCellDiv());
return ret;
}
public def testClone():Boolean{
var ret:Boolean = true;
Console.OUT.println("Dist dense Matrix clone test");
val ddm = DistDenseMatrix.make(M, N);
ddm.initRandom();
val ddm1 = ddm.clone();
ret = ddm.equals(ddm1);
if (!ret)
Console.OUT.println("--------DistDense Matrix Clone test failed!--------");
ddm(1, 1) = ddm(2,2) = ET(10.0);
if ((ddm(1,1)==ddm(2,2)) && (ddm(1,1)==ET(10.0))) {
ret &= true;
} else {
ret &= false;
Console.OUT.println("----------Dist Dense Matrix chain assignment test failed!-------");
}
return ret;
}
public def testInit():Boolean {
Console.OUT.println("Dist Dense Matrix initialization test");
var ret:Boolean = true;
val ddm = DistDenseMatrix.make(M,N).init((r:Long, c:Long)=>ET(1.0+r+c));
for (var c:Long=0; c<M; c++)
for (var r:Long=0; r<M; r++)
ret &= (ddm(r,c) == ET(1.0+r+c));
if (!ret)
Console.OUT.println("--------Dist Dense matrix initialization func failed!--------");
return ret;
}
public def testCopyTo():Boolean {
var ret:Boolean = true;
Console.OUT.println("Dist dense Matrix copyTo test");
val ddm = DistDenseMatrix.make(M, N);
val dbm = DenseBlockMatrix.make(ddm.grid);
val dm = DenseMatrix.make(M,N);
ddm.initRandom();
ddm.copyTo(dbm);
ret &= ddm.equals(dbm);
dbm.copyTo(dm);
ret &= dbm.equals(dm);
if (!ret)
Console.OUT.println("--------Dist dense matrix copyTo test failed!--------");
return ret;
}
public def testScale():Boolean{
Console.OUT.println("Dist dense matrix scaling test");
val dm = DistDenseMatrix.make(M, N);
dm.initRandom();
val dm1 = dm * ET(2.5);
val m = dm.toDense();
val m1 = m * ET(2.5);
val ret = dm1.equals(m1);
if (!ret)
Console.OUT.println("--------Dist dense matrix Scaling test failed!--------");
return ret;
}
public def testAdd():Boolean {
Console.OUT.println("Dist dense matrix addition test");
val dm = DistDenseMatrix.make(M, N);
dm.initRandom();
val dm1 = dm * ET(-1.0);
val dm0 = dm + dm1;
val ret = dm0.equals(ET(0.0));
if (!ret)
Console.OUT.println("--------DistDenseMatrix Add: dm + dm*-1 test failed--------");
return ret;
}
public def testAddSub():Boolean {
Console.OUT.println("Dist dense matrix add-sub test");
val dm = DistDenseMatrix.make(M, N);
dm.initRandom();
val dm1= DistDenseMatrix.make(M, N);
dm.initRandom();
val dm2= dm + dm1;
val dm_c = dm2 - dm1;
val ret = dm.equals(dm_c);
if (!ret)
Console.OUT.println("--------DistDenseMatrix Add-sub test failed!--------");
return ret;
}
public def testAddAssociative():Boolean {
Console.OUT.println("Dist dense matrix associative test");
val a = DistDenseMatrix.make(M, N);
val b = DistDenseMatrix.make(M, N);
val c = DistDenseMatrix.make(M, N);
a.initRandom();
b.initRandom();
c.initRandom();
val c1 = a + b + c;
val c2 = a + (b + c);
val ret = c1.equals(c2);
if (!ret)
Console.OUT.println("--------DistDenseMatrix Add associative test failed!--------");
return ret;
}
public def testScaleAdd():Boolean {
Console.OUT.println("Dist dense Matrix scaling-add test");
val a = DistDenseMatrix.make(M, N);
a.initRandom();
val m = a.toDense();
val a1= a * ET(0.2);
val a2= ET(0.8) * a;
var ret:Boolean = a.equals(a1+a2);
ret &= a.equals(m);
if (!ret)
Console.OUT.println("--------DistDenseMatrix scaling-add test failed!--------");
return ret;
}
public def testCellMult():Boolean {
Console.OUT.println("Dist dense Matrix cellwise mult test");
val a = DistDenseMatrix.make(M, N);
val b = DistDenseMatrix.make(M, N);
a.initRandom();
b.initRandom();
val c = (a + b) * a;
val d = a * a + b * a;
var ret:Boolean = c.equals(d);
val da= a.toDense();
val db= b.toDense();
val dc= (da + db) * da;
ret &= dc.equals(c);
if (!ret)
Console.OUT.println("--------Dist dense matrix cellwise mult test failed!--------");
return ret;
}
public def testCellDiv():Boolean {
Console.OUT.println("Dist dense matrix cellwise mult-div test");
val a = DistDenseMatrix.make(M, N);
val b = DistDenseMatrix.make(M, N);
a.initRandom();
b.initRandom();
val c = (a + b) * a;
val d = c / (a + b);
var ret:Boolean = d.equals(a);
if (!ret)
Console.OUT.println("--------Dist dense matrix cellwise mult-div test failed!--------");
return ret;
}
public static def main(args:Rail[String]) {
new TestDistDense(args).execute();
}
} |
import java.util.Scanner;
class Student
{
Scanner sc = new Scanner(System.in);
private int Roll;
private String Name;
private int Age;
private int Marks;
public Student()
{
Roll = 0;
Name = "Empty";
Age = 0;
Marks = 0;
}
public void SetStudent()
{
System.out.print("\nEnter Student Full Name : ");
Name = sc.nextLine();
System.out.print("\nEnter Student Roll No : ");
Roll = sc.nextInt();
System.out.print("\nEnter Student Age : ");
Age = sc.nextInt();
System.out.print("\nEnter Student Total Marks : ");
Marks = sc.nextInt();
System.out.print("\n");
}
public void ShowStudent()
{
System.out.print("\nStudent Informations Are Given Bellow : \n\n");
System.out.print("\nRoll : "+Roll+"\n");
System.out.print("\nName : "+Name+"\n");
System.out.print("\nAge : "+Age+"\n");
System.out.print("\nMarks : "+Marks+"\n");
System.out.print("\n");
}
}
public class ArrayOfObjects
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Student []srr = new Student [3];
for(int i=0; i<3; i++)
{
srr[i] = new Student();
}
System.out.print("\nEnter 3 Student Details : \n\n");
for(int i=0; i<3; i++)
{
srr[i].SetStudent();
}
System.out.print("\nThe 3 Student Details Are : \n\n");
for(int i=0; i<3; i++)
{
srr[i].ShowStudent();
}
System.out.print("\n");
System.out.print("\n");
sc.close();
}
} |
import http from 'node:http'
import { Transform } from 'node:stream'
class InverseNumberStream extends Transform {
_transform (chunk, encoding, callback) {
const transformed = Number(chunk.toString()) * -1
console.log(transformed)
callback(null, Buffer.from(String(transformed)))
}
}
/*
request => ReadableStream
response => WritableStream
*/
const server = http.createServer(async (request, response) => {
const buffers = []
for await (const chunk of request) {
buffers.push(chunk)
}
const fullStreamContent = Buffer.concat(buffers).toString()
console.log(fullStreamContent)
return response.end(fullStreamContent)
// return request
// .pipe(new InverseNumberStream())
// .pipe(response)
})
const port = 3334
server.listen(port, () => console.log(`🚀 Server running on http://localhost:${port}`)) |
# WadidawTheater API Documentation
## Models :
### User
```
username : string
email : string, unique (required) emailFormat
password : string (required) length>=5
```
### Ticket
```
MovieId : integer (required)
UserId : integer (required)
movieName : string
price : integer (required)
```
### Relationship :
```
User to Ticket : One-to-Many
```
## Base URL
www.wadidawclothing.shop
## Endpoints :
List of available endpoints:
- `POST /login`
- `POST /register`
- `POST /forget-password`
- `GET /reset-password/:id/:token`
- `PATCH /new-password/:id/:token`
- `POST /google-login`
- `GET /getMovies`
- `GET /movie/detail/:id`
And routes below need authentication
- `GET /ticket/:id`
- `POST /create-ticket/:id`
- `GET /my-ticket`
- `POST /payment`
- `PATCH /payment/status/:id`
## 1. POST /login
Description:
- Login
Request:
- body:
```json
{
"email": "string",
"password": "string"
}
```
_Response (200 - OK)_
```json
{
"message": "Login Success",
"access_token": "string"
}
```
_Response (400 - Bad Request)_
```json
{
"message": "Email is required"
}
OR
{
"message": "Password is required"
}
```
_Response (401 - Unauthorized)_
```json
{
"message": "Invalid Email/Password"
}
```
## 2. POST /register
Description:
- Add user
Request:
- body:
```json
{
"username" : "string",
"email" : "string",
"password" : "string",
}
```
_Response (201 - Created)_
```json
{
"message": "User has been created",
}
```
_Response (400 - Bad Request)_
```json
{
"message": "Email must be unique"
}
OR
{
"message": "Must be a valid email format"
}
OR
{
"message": "Email cannot be empty"
}
OR
{
"message": "Password cannot be empty"
}
OR
{
"message": "Passwords length must be 5 or more"
}
```
## 3. POST /forget-password
Description:
- Forget Password
Request:
- body:
```json
{
"email" : "string",
}
```
_Response (200 - OK)_
```json
{
"message": "string",
}
```
_Response (401 - Unauthorized)_
```json
{
"message": "Invalid Email"
}
```
## 4. GET /reset-password/:id/:token
Description:
- Link Reset Password
Request:
- params :
```json
{
"id" : "integer",
"token" : "string"
}
```
- body:
```json
{
"email" : "string",
}
```
_Response (200 - OK)_
```json
{
"message": "Check your email",
}
```
_Response (401 - Unauthorized)_
```json
{
"message": "Invalid Email"
}
```
_Response (403 - Forbidden)_
```json
{
"message": "Forbidden"
}
```
## 5. PATCH /new-password/:id/:token
Description:
- Update new passowrd
Request:
- params :
```json
{
"id" : "integer",
"token" : "string"
}
```
- body:
```json
{
"password" : "string",
}
```
_Response (200 - OK)_
```json
{
"message": "berhasil ubah password",
}
```
_Response (403 - Forbidden)_
```json
{
"message": "Forbidden"
}
```
## 6. POST /google-login
Description:
- google login
Request:
- body:
```json
{
"googleToken" : "string",
}
```
_Response (200 - OK)_
```json
{
"message": "Login Google Success",
"access_token" : "string"
}
```
_Response (401 - Unauthorize)_
```json
{
"message": "Invalid Token"
}
```
## 7. GET /getMovies
Description:
- Get Movies from tmdb Api
Request:
- headers :
```json
{
accept: "application/json",
Authorization : Bearer + Api_key
}
```
_Response (200 - Ok)_
```json
{
"dates": {
"maximum": "2024-03-20",
"minimum": "2024-02-07"
},
"page": 1,
"results": [
{
"adult": false,
"backdrop_path": "/gJL5kp5FMopB2sN4WZYnNT5uO0u.jpg",
"genre_ids": [
28,
12,
16,
35,
10751
],
"id": 1011985,
"original_language": "en",
"original_title": "Kung Fu Panda 4",
"overview": "Po is gearing up to become the spiritual leader of his Valley of Peace, but also needs someone to take his place as Dragon Warrior. As such, he will train a new kung fu practitioner for the spot and will encounter a villain called the Chameleon who conjures villains from the past.",
"popularity": 1929.496,
"poster_path": "/kDp1vUBnMpe8ak4rjgl3cLELqjU.jpg",
"release_date": "2024-03-02",
"title": "Kung Fu Panda 4",
"video": false,
"vote_average": 6.864,
"vote_count": 121
},
...
],
"total_pages": 186,
"total_results": 3716
}
```
## 8. GET /movie/detail/id
Description:
- Get Movies from tmdb Api
Request:
- params :
```json
{
"id": "integer (required)"
}
```
- headers :
```json
{
accept: "application/json",
Authorization : Bearer + Api_key
}
```
_Response (200 - Ok)_
```json
{
"adult": false,
"backdrop_path": "/ehumsuIBbgAe1hg343oszCLrAfI.jpg",
"belongs_to_collection": null,
"budget": 175000000,
"genres": [
{
"id": 16,
"name": "Animation"
},
{
"id": 10751,
"name": "Family"
},
{
"id": 14,
"name": "Fantasy"
},
{
"id": 12,
"name": "Adventure"
}
],
"homepage": "https://movies.disney.com/wish",
"id": 1022796,
"imdb_id": "tt11304740",
"original_language": "en",
"original_title": "Wish",
"overview": "Asha, a sharp-witted idealist, makes a wish so powerful that it is answered by a cosmic force – a little ball of boundless energy called Star. Together, Asha and Star confront a most formidable foe - the ruler of Rosas, King Magnifico - to save her community and prove that when the will of one courageous human connects with the magic of the stars, wondrous things can happen.",
"popularity": 377.756,
"poster_path": "https://image.tmdb.org/t/p/w500/AcoVfiv1rrWOmAdpnAMnM56ki19.jpg",
"production_companies": [
{
"id": 2,
"logo_path": "/wdrCwmRnLFJhEoH8GSfymY85KHT.png",
"name": "Walt Disney Pictures",
"origin_country": "US"
},
{
"id": 6125,
"logo_path": "/tzsMJBJZINu7GHzrpYzpReWhh66.png",
"name": "Walt Disney Animation Studios",
"origin_country": "US"
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "2023-11-13",
"revenue": 251720820,
"runtime": 95,
"spoken_languages": [
{
"english_name": "English",
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "Be careful what you wish for.",
"title": "Wish",
"video": false,
"vote_average": 6.615,
"vote_count": 864
}
```
## 9. POST /create-ticket/:id
Description:
- Create ticket
Request:
- params :
```json
{
"id": "integer (required)"
}
```
- headers :
```json
{
"access_token": "string"
}
```
- body :
```json
{
"MovieId": "integer",
"UserId": "integer",
"movieName": "string",
"price": "integer",
}
```
_Response (201 - Ok)_
```json
{
"MovieId": "integer",
"UserId": "integer",
"movieName": "string",
"price": "integer",
"paymentStatus" : "boolean"
}
```
## 10. GET /my-ticket
Description:
- Get User Tickets
Request:
- params :
```json
{
"id": "integer (required)"
}
```
- headers :
```json
{
"access_token": "string"
}
```
_Response (200 - Ok)_
```json
{
"MovieId": "integer",
"UserId": "integer",
"movieName": "string",
"price": "integer",
"paymentStatus" : "boolean"
},
...
```
_Response (401 - Unauthorize)_
```json
{
"message" : "Invalid Token"
}
```
## 11. GET /ticket/:id
Description:
- Get Detail Ticket
Request:
- params :
```json
{
"id": "integer (required)"
}
```
- headers :
```json
{
"access_token": "string"
}
```
_Response (200 - Ok)_
```json
{
"MovieId": "integer",
"UserId": "integer",
"movieName": "string",
"price": "integer",
"paymentStatus" : "boolean"
}
```
_Response (404 - Not Found)_
```json
{
"message" : "Not Found"
}
```
## 12. POST /payment
Description:
- Get payment detail
Request:
- 3rd Party Api = Midtrans
_Response (200 - Ok)_
```json
{
"message": "Order created",
"transactionToken": "integer",
"order_id": "integer",
}
```
## 12. POST /payment
Description:
- Get payment detail
Request:
- 3rd Party Api = Midtrans
_Response (200 - Ok)_
```json
{
"message": "Order created",
"transactionToken": "integer",
"order_id": "integer",
}
```
## 13. POST /payment/status/id
Description:
- Changing paymentStatus & Send Email Confirmation
Request:
- params :
```json
{
"id" : "integer"
}
```
_Response (200 - Ok)_
```json
{
"message": "Pemayaran Berhasil",
}
```
_Response (400 - Bad Request)_
```json
{
"message": "Already Paid",
}
```
_Response (401 - Unauthorize)_
```json
{
"message": "Invalid Email",
}
```
## 14. POST /ticket/delete/:id
Description:
- Delete ticket
Request:
- params :
```json
{
"id" : "integer"
}
```
_Response (200 - Ok)_
```json
{
"message": "Pemayaran Berhasil",
}
```
_Response (400 - Bad Request)_
```json
{
"message": "Already Paid",
}
OR
{
"message": "Cant delete Payed Ticket",
}
```
_Response (403 - forbidden)_
```json
{
"message": "Forbidden",
}
```
|
import { DndContext, closestCenter } from "@dnd-kit/core";
import {
arrayMove,
SortableContext,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { useState } from "react";
import DraggableItem from "./component/DraggableItem/DraggableItem.jsx";
const ITEMS = [
{
id: crypto.randomUUID(),
title: "Item 1",
},
{
id: crypto.randomUUID(),
title: "Item 2",
},
{
id: crypto.randomUUID(),
title: "Item 3",
},
];
function App() {
const [items, setItems] = useState(ITEMS);
function handleDragEnd(event) {
const { active, over } = event;
if (active.id === over.id) {
return;
}
setItems((items) => {
const activeIndex = items.findIndex((item) => item.id === active.id);
const overIndex = items.findIndex((item) => item.id === over.id);
return arrayMove(items, activeIndex, overIndex);
});
}
return (
<div className="text-center flow">
<h1>React Drag and Drop</h1>
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={items} strategy={verticalListSortingStrategy}>
<ul className="draggable__list flow">
{items.map((item) => (
<DraggableItem key={item.id} id={item.id} title={item.title} />
))}
</ul>
</SortableContext>
</DndContext>
</div>
);
}
export default App; |
package org.example.presentation.grpc;
import com.google.protobuf.Empty;
import com.google.protobuf.Int32Value;
import io.grpc.stub.StreamObserver;
import lombok.RequiredArgsConstructor;
import net.devh.boot.grpc.server.service.GrpcService;
import org.example.appcore.appservice.ProductService;
import org.example.appcore.domain.Product;
import org.example.grpc.model.ProductIdRequest;
import org.example.grpc.model.ProductRequest;
import org.example.grpc.model.ProductServiceGrpc;
@GrpcService
@RequiredArgsConstructor
public class ProductGRPC extends ProductServiceGrpc.ProductServiceImplBase {
private final ProductService productService;
@Override
public StreamObserver<ProductRequest> countProduct(StreamObserver<Int32Value> responseObserver) {
System.out.println("hello context: " + HelloInterceptor.HELLO_MSG.get());
return new StreamObserver<ProductRequest>() {
int count = 0;
@Override
public void onNext(ProductRequest value) {
System.out.println(Thread.currentThread());
count++;
}
@Override
public void onError(Throwable t) {
}
@Override
public void onCompleted() {
responseObserver.onNext(Int32Value.of(count));
responseObserver.onCompleted();
}
};
}
@Override
public void getAllProduct(Empty request, StreamObserver<ProductRequest> responseObserver) {
for (int i = 0; i < 10; i++) {
responseObserver.onNext(ProductRequest.newBuilder()
.setId("id: " + i)
.setName("name: " + i)
.setDescription("description: " + i)
.build()
);
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
responseObserver.onCompleted();
}
@Override
public void getProduct(ProductIdRequest request, StreamObserver<ProductRequest> responseObserver) {
Product p = productService.getProduct(request.getId());
ProductRequest pr = ProductRequest.newBuilder()
.setId(p.getId())
.setName(p.getName())
.setDescription(p.getDescription())
.build();
responseObserver.onNext(pr);
responseObserver.onCompleted();
}
@Override
public void addProduct(ProductRequest request, StreamObserver<ProductRequest> responseObserver) {
Product p = productService.addProduct(request.getName(), request.getDescription());
ProductRequest pr = ProductRequest.newBuilder()
.setId(p.getId())
.setName(p.getName())
.setDescription(p.getDescription())
.build();
responseObserver.onNext(pr);
responseObserver.onCompleted();
}
} |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library fuchsia.diagnostics.stream;
using fuchsia.diagnostics;
using zx;
/// Maximum number of arguments that can be encoded per record, as specified by the tracing format:
///
/// https://fuchsia.dev/fuchsia-src/development/tracing/trace-format#arguments
const uint32 MAX_ARGS = 15;
/// A small(ish) limit on the length of argument names is used because argument names are expected
/// to be used repeatedly, many times.
const uint32 MAX_ARG_NAME_LENGTH = 256;
/// The maximum string length which we can encode into the tracing format.
const uint32 MAX_TEXT_ARG_LENGTH = 32768;
/// A record in the diagnostic stream.
[MaxHandles = "0"]
struct Record {
/// The monotonic time at which the record was generated.
zx.time timestamp;
/// Severity of the record.
fuchsia.diagnostics.Severity severity;
/// The key-value pairs which make up this record.
vector<Argument>:MAX_ARGS arguments;
};
/// A named key-value pair in the diagnostic record.
[MaxHandles = "0"]
struct Argument {
/// The name of the argument.
string:MAX_ARG_NAME_LENGTH name;
/// The value of the argument.
Value value;
};
/// An argument value which can be one of several types.
[MaxHandles = "0"]
flexible union Value {
/// A signed integral argument.
1: int64 signed_int;
/// An unsigned integral argument.
2: uint64 unsigned_int;
/// A double-precision floating-point argument.
3: float64 floating;
/// A UTF8 text argument.
4: string:MAX_TEXT_ARG_LENGTH text;
}; |
import { Card, Error, LetterAvatar, Loading } from '@/components/ui'
import { getAxiosError } from '@/lib/common'
import { DBConnection } from '@prisma/client'
import axios from 'axios'
import useConnections from 'hooks/useConnections'
import { useTranslation } from 'next-i18next'
import Link from 'next/link'
import { Button } from 'react-daisyui'
import toast from 'react-hot-toast'
import { ApiResponse } from 'types'
const Connections = () => {
const { isLoading, isError, connections, mutateConnection } = useConnections()
const { t } = useTranslation('common')
if (isLoading) {
return <Loading />
}
if (isError) {
return <Error />
}
const removeConnection = async (connection: DBConnection) => {
try {
await axios.delete<ApiResponse>(`/api/connections/${connection.id}`)
toast.success(t('delete-success'))
mutateConnection()
} catch (error: any) {
toast.error(getAxiosError(error))
}
}
return (
<Card heading="Your Connections">
<Card.Body>
<table className="w-full table table-zebra table-fixed text-left text-sm ">
<thead className="text-xs uppercase">
<tr>
<th scope="col" className="px-6 py-3">
{t('id')}
</th>
<th scope="col" className="px-6 py-3">
{t('host')}
</th>
<th scope="col" className="px-6 py-3">
{t('database')}
</th>
<th scope="col" className="px-6 py-3">
{t('actions')}
</th>
</tr>
</thead>
<tbody>
{connections &&
connections.map((connection) => {
return (
<tr
key={connection.id}
className="border-b hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-600"
>
<td className="px-6 py-3">
{connection.id}
</td>
<td className="px-6 py-3">{connection.host}</td>
<td className="px-6 py-3">
{connection.database}
</td>
<td className="px-6 py-3">
<Button
size="sm"
variant="outline"
onClick={() => {
removeConnection(connection)
}}
>
{t('remove-connection')}
</Button>
</td>
</tr>
)
})}
</tbody>
</table>
</Card.Body>
</Card>
)
}
export default Connections |
import {FC} from "react";
import {Avatar, Box, Button, Dialog, DialogContent, DialogTitle, Typography} from "@mui/material";
import {ICharacter} from "../../../../interfaces";
import css from './CharacterPopUp.module.css';
interface IProps {
character: ICharacter,
open: boolean,
setOpen: (open: boolean) => void
}
const CharacterPopUp: FC<IProps> = ({character, open, setOpen}) => {
return (
<Dialog
onClose={() => setOpen(false)}
fullWidth={true}
maxWidth={'sm'}
open={open}
>
<DialogTitle className={css.card_title}>
<Typography fontSize={'25px'}>{character.name}</Typography>
<Button onClick={() => setOpen(false)}>Close</Button>
</DialogTitle>
<DialogContent dividers className={css.card_content}>
<Avatar alt={character.name}
src={character.image}
className={css.card_avatar}/>
<Box>
<Typography gutterBottom>
Species - {character.species}
</Typography>
<Typography gutterBottom>
Status - {character.status}
</Typography>
<Typography gutterBottom>
Origin - {character.origin.name}
</Typography>
</Box>
</DialogContent>
</Dialog>
)
}
export {CharacterPopUp} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>Your Bootstrap Website</title>
<style>
/* Add custom styles here */
.fixed-background {
background-image: url("pexels-miguel-á-padriñán-255379.jpg");
background-size: cover;
background-position: center;
background-attachment: fixed;
height: 500px; /* Set the desired height */
color: white;
text-align: center;
padding: 100px 0;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<!-- Image Slider -->
<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="./p1.jpeg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="./b5-new-logo.png" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="./p2.png" class="d-block w-100" alt="...">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<!-- Jumbotron -->
<!-- Jumbotron -->
<div class="jumbotron jumbotron-fluid text-center bg-primary text-white">
<div class="container">
<h1 class="display-4">Welcome to Our Awesome Website</h1>
<p class="lead">Discover the best in creativity and innovation.</p>
<hr class="my-4">
<p>Join us on a journey of exploration and inspiration.</p>
<a class="btn btn-light btn-lg" href="#" role="button">Get Started</a>
</div>
</div>
<!-- Three Column Section -->
<div class="container">
<div class="row">
<div class="col">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod quam eu semper aliquet. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum odit, architecto rerum quisquam ab aperiam obcaecati eligendi, sapiente assumenda natus iusto neque. Ipsa cupiditate impedit molestias itaque in at nihil id excepturi facilis ratione, enim maiores molestiae pariatur totam eveniet voluptatem beatae tenetur earum esse? Ut, sed earum molestiae vel cum voluptates unde mollitia esse! Molestias fuga quisquam nobis sit eius doloremque provident molestiae. Numquam repudiandae, voluptatum ex exercitationem itaque alias deserunt consectetur in soluta aliquid neque, sit perspiciatis voluptate modi. Debitis rerum adipisci nisi doloremque quas, cumque tenetur repellat praesentium porro accusantium, tempore incidunt iusto quo fugiat perferendis voluptatem!
</div>
<div class="col">
Sed cursus justo vel dapibus cursus. Praesent ac consectetur justo, non congue nulla. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum odit, architecto rerum quisquam ab aperiam obcaecati eligendi, sapiente assumenda natus iusto neque. Ipsa cupiditate impedit molestias itaque in at nihil id excepturi facilis ratione, enim maiores molestiae pariatur totam eveniet voluptatem beatae tenetur earum esse? Ut, sed earum molestiae vel cum voluptates unde mollitia esse! Molestias fuga quisquam nobis sit eius doloremque provident molestiae. Numquam repudiandae, voluptatum ex exercitationem itaque alias deserunt consectetur in soluta aliquid neque, sit perspiciatis voluptate modi. Debitis rerum adipisci nisi doloremque quas, cumque tenetur repellat praesentium porro accusantium, tempore incidunt iusto quo fugiat perferendis voluptatem!
</div>
<div class="col">
Fusce hendrerit libero sed odio convallis, ut volutpat orci mollis. Ut nec augue eget justo varius varius. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum odit, architecto rerum quisquam ab aperiam obcaecati eligendi, sapiente assumenda natus iusto neque. Ipsa cupiditate impedit molestias itaque in at nihil id excepturi facilis ratione, enim maiores molestiae pariatur totam eveniet voluptatem beatae tenetur earum esse? Ut, sed earum molestiae vel cum voluptates unde mollitia esse! Molestias fuga quisquam nobis sit eius doloremque provident molestiae. Numquam repudiandae, voluptatum ex exercitationem itaque alias deserunt consectetur in soluta aliquid neque, sit perspiciatis voluptate modi. Debitis rerum adipisci nisi doloremque quas, cumque tenetur repellat praesentium porro accusantium, tempore incidunt iusto quo fugiat perferendis voluptatem!
</div>
</div>
</div>
<!-- Two Column Section -->
<div class="example-container">
<div class="example-row">
<div class="example-content-main">
<h2>Exploring the World Through Photography</h2>
<p>Photography is a powerful art form that allows us to capture moments, emotions, and stories in a single frame. Through the lens of a camera, we can freeze time and immortalize scenes that evoke feelings and memories.</p>
<p>Whether it's a breathtaking landscape, a candid portrait, or an intricate macro shot, photography enables us to see the world from different perspectives. It's a way to communicate without words, conveying the beauty, diversity, and complexity of our surroundings.</p>
</div>
<div class="example-content-secondary">
<h3>The Art of Composition</h3>
<p>Photography isn't just about pointing and shooting; it's about composing an image that tells a story. Elements like framing, lighting, and perspective come together to create visually compelling photographs.</p>
<p>By understanding the interplay of these elements, photographers can capture the essence of a moment. From the rule of thirds to leading lines, composition techniques guide us in creating images that are not only aesthetically pleasing but also thought-provoking.</p>
</div>
</div>
</div>
<!-- Fixed Background Image Section -->
<div class="fixed-background">
<h2>Discover the Beauty of Nature</h2>
<p>Immerse yourself in the wonders of our planet.</p>
<a href="#" class="btn btn-light">Explore Now</a>
</div>
<!-- Emoji 4 Column Section -->
<div class="container">
<div class="row">
<div class="col-md-4">😃</div>
<div class="col-md-4 offset-md-4">😄</div>
</div>
<div class="row">
<div class="col-md-3 offset-md-3">🎉</div>
<div class="col-md-3 offset-md-3">🚀</div>
</div>
<div class="row">
<div class="col-md-6 offset-md-3">🌟</div>
</div>
</div>
<!-- Meet The Team Cards Section -->
<div class="row">
<div class="col-md-3">
<div class="card" style="width: 18rem;">
<img src="./p1.jpeg" class="card-img-top" alt="Image 1">
<div class="card-body">
<h5 class="card-title">Card Title 1</h5>
<p class="card-text">Some quick example text for Card 1.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card" style="width: 18rem;">
<img src="./p1.jpeg" class="card-img-top" alt="Image 2">
<div class="card-body">
<h5 class="card-title">Card Title 2</h5>
<p class="card-text">Some quick example text for Card 2.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card" style="width: 18rem;">
<img src="./p1.jpeg" class="card-img-top" alt="Image 3">
<div class="card-body">
<h5 class="card-title">Card Title 3</h5>
<p class="card-text">Some quick example text for Card 3.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card" style="width: 18rem;">
<img src="./p1.jpeg" class="card-img-top" alt="Image 4">
<div class="card-body">
<h5 class="card-title">Card Title 4</h5>
<p class="card-text">Some quick example text for Card 4.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</div>
<!-- Second Two Column Section -->
<div class="example-container">
<div class="example-row">
<div class="example-content-main">
<h2>Exploring the World Through Photography</h2>
<p>Photography is a powerful art form that allows us to capture moments, emotions, and stories in a single frame. Through the lens of a camera, we can freeze time and immortalize scenes that evoke feelings and memories.</p>
<p>Whether it's a breathtaking landscape, a candid portrait, or an intricate macro shot, photography enables us to see the world from different perspectives. It's a way to communicate without words, conveying the beauty, diversity, and complexity of our surroundings.</p>
</div>
<div class="example-content-secondary">
<h3>The Art of Composition</h3>
<p>Photography isn't just about pointing and shooting; it's about composing an image that tells a story. Elements like framing, lighting, and perspective come together to create visually compelling photographs.</p>
<p>By understanding the interplay of these elements, photographers can capture the essence of a moment. From the rule of thirds to leading lines, composition techniques guide us in creating images that are not only aesthetically pleasing but also thought-provoking.</p>
</div>
</div>
</div>
<!-- Social Media Icons -->
<div class="social-media-icons">
<a href="./facebook.png"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
<a href="#"><i class="fab fa-instagram"></i></a>
</div>
<!-- Footer Section -->
<footer class="row row-cols-5 py-5 my-5 border-top">
<div class="col">
<a href="/" class="d-flex align-items-center mb-3 link-dark text-decoration-none">
<svg class="bi me-2" width="40" height="32"><use xlink:href="#bootstrap"></use></svg>
</a>
<p class="text-muted">© 2021</p>
</div>
<div class="col">
</div>
<div class="col">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
<div class="col">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
<div class="col">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
</footer>
<!-- Scripts -->
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html> |
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { Product } from 'src/app/shared';
@Injectable({
providedIn: 'root',
})
export class ProductService {
private apiUrl: string = `${environment.apiUrl}/products`;
constructor(private http: HttpClient) {}
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.apiUrl);
}
public getProduct(id: number): Observable<Product> {
return this.http.get<Product>(`${this.apiUrl}/${id}`);
}
public createProduct(product: Product): Observable<Product> {
return this.http.post<Product>(this.apiUrl, product);
}
public updateProduct(product: Product): Observable<Product> {
return this.http.put<Product>(this.apiUrl, product);
}
public deleteProduct(product: Product): Observable<any> {
return this.http.delete<void>(this.apiUrl, {
body: {
id: product.id,
description: product.description,
},
});
}
} |
class Graph {
adjacencyList: Map<number, number[]>;
constructor() {
this.adjacencyList = new Map();
}
addNode(node: number) {
this.adjacencyList.set(node, []);
}
addEdge(node1: number, node2: number) {
this.adjacencyList.get(node1)?.push(node2);
this.adjacencyList.get(node2)?.push(node1);
}
}
class CourseScheduler {
graph: Graph;
constructor() {
this.graph = new Graph();
}
scheduleCourses(): Map<number, number> {
const colors: Map<number, number> = new Map();
const nodes = Array.from(this.graph.adjacencyList.keys());
for (const node of nodes) {
const adjacentColors = new Set<number>();
const neighbors = this.graph.adjacencyList.get(node);
if (neighbors) {
for (const neighbor of neighbors) {
if (colors.has(neighbor)) {
adjacentColors.add(colors.get(neighbor)!);
}
}
}
const color = this.getAvailableColor(adjacentColors);
colors.set(node, color);
}
return colors;
}
private getAvailableColor(adjacentColors: Set<number>): number {
for (let color = 1; ; color++) {
if (!adjacentColors.has(color)) {
return color;
}
}
}
}
const scheduler = new CourseScheduler();
export default scheduler; |
/*
* Copyright (C) 2022 FreeLancer Development Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* File: NDeclaration.h
* Author: Javier Marrero
*
* Created on March 19, 2022, 1:26 PM
*/
#ifndef NDECLARATION_H
#define NDECLARATION_H
#include <amanda-vm/IL/AstNodeBase.h>
#include <amanda-c/ast/Lists.h>
#include <vector>
namespace amanda
{
namespace compiler
{
namespace ast
{
class NDeclarationBlock;
class NDeclaration : public il::AstNodeBase
{
AMANDA_OBJECT(NDeclaration, il::AstNodeBase)
public:
NDeclaration();
virtual ~NDeclaration();
void addDeclarations(NDeclarationBlock* declarations);
} ;
/**
* The declaration block class is a container class for multiple declaration
* objects. It does not contains encapsulated data in order to keep the code
* simple.
*
* @author J. Marrero
*/
class NDeclarationBlock : public il::AstNodeBase
{
AMANDA_OBJECT(NDeclarationBlock, il::AstNodeBase);
public:
NDeclarationBlock();
virtual ~NDeclarationBlock();
void addDeclaration(NDeclaration* declaration);
const DeclarationList& getDeclarations() const ;
protected:
DeclarationList declarations;
};
}
}
}
#endif /* NDECLARATION_H */ |
import { type NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import prisma from '@/lib/prisma';
interface CredentialsProps {
email: string;
password: string;
}
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
type: 'credentials',
name: 'Credentials',
credentials: {},
async authorize(credentials) {
const { email, password } = credentials as CredentialsProps;
const user = await prisma.user.findFirst({
where: {
email,
password,
},
select: {
id: true,
name: true,
email: true,
},
});
if (user) {
return user;
}
return null;
},
}),
],
callbacks: {
jwt: async ({ token, user }) => {
if (user) {
token.id = user.id;
}
return token;
},
session: async ({ session, token }) => {
if (token) {
session.user.id = token.id as string;
}
return session;
},
},
pages: {
signIn: '/login',
},
session: {
strategy: 'jwt',
maxAge: 60 * 60 * 1, // 1 hour
},
secret: process.env.NEXTAUTH_SECRET,
}; |
<?php
namespace Illuminate\Foundation\Support\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [];
/**
* Register the application's policies.
*
* @return void
*/
public function registerPolicies()
{
foreach ($this->policies() as $model => $policy) {
Gate::policy($model, $policy);
}
}
/**
* Get the policies defined on the provider.
*
* @return array<class-string, class-string>
*/
public function policies()
{
return $this->policies;
}
} |
# Builder Fork
This is a fork of the official repo to provide a lightweight way to build TensorRT-LLM engines.
<div align="center">
TensorRT-LLM
<h4> A TensorRT Toolbox for Optimized Large Language Model Inference</h4>
[](https://nvidia.github.io/TensorRT-LLM/)
[](https://www.python.org/downloads/release/python-31012/)
[](https://developer.nvidia.com/cuda-downloads)
[](https://developer.nvidia.com/tensorrt)
[](./setup.py)
[](./LICENSE)
[Architecture](./docs/source/architecture.md) | [Results](./docs/source/performance.md) | [Examples](./examples/) | [Documentation](./docs/source/)
---
<div align="left">
## Latest News
* [2023/11/13] [**H200** achieves nearly **12,000 tok/sec on Llama2-13B**](./docs/source/blogs/H200launch.md)
<img src="./docs/source/blogs/media/H200launch_tps.png" alt="H200 TPS" width="500" height="auto">
H200 FP8 achieves 11,819 tok/s on Llama2-13B on a single GPU, and is up to 1.9x faster than H100.
* [2023/11/03] [TensorRT-LLM is up to **4.6x faster on H100 than A100**, achieving **10,000 tok/s at 100ms to first token.**](./docs/source/blogs/H100vsA100.md)
* [2023/10/22] [🚀 RAG on Windows using TensorRT-LLM and LlamaIndex 🦙](https://github.com/NVIDIA/trt-llm-rag-windows#readme)
* [2023/10/19] Getting Started Guide - [Optimizing Inference on Large Language Models with NVIDIA TensorRT-LLM, Now Publicly Available
](https://developer.nvidia.com/blog/optimizing-inference-on-llms-with-tensorrt-llm-now-publicly-available/)
* [2023/10/17] [Large Language Models up to 4x Faster on RTX With TensorRT-LLM for Windows
](https://blogs.nvidia.com/blog/2023/10/17/tensorrt-llm-windows-stable-diffusion-rtx/)
* [2023/9/9] [NVIDIA TensorRT-LLM Supercharges Large Language Model Inference on NVIDIA H100 GPUs](https://developer.nvidia.com/blog/nvidia-tensorrt-llm-supercharges-large-language-model-inference-on-nvidia-h100-gpus/)
[2023/10/31 - Phind](https://www.phind.com/blog/phind-model-beats-gpt4-fast) ; [2023/10/12 - Databricks (MosaicML)](https://www.databricks.com/blog/llm-inference-performance-engineering-best-practices) ;
[2023/10/4 - Perplexity](https://blog.perplexity.ai/blog/introducing-pplx-api) ;
[2023/9/27 - CloudFlare](https://www.cloudflare.com/press-releases/2023/cloudflare-powers-hyper-local-ai-inference-with-nvidia/);
## Table of Contents
- [TensorRT-LLM Overview](#tensorrt-llm-overview)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Support Matrix](#support-matrix)
- [Devices](#devices)
- [Precision](#precision)
- [Key Features](#key-features)
- [Models](#models)
- [Performance](#performance)
- [Advanced Topics](#advanced-topics)
- [Quantization](#quantization)
- [In-flight Batching](#in-flight-batching)
- [Attention](#attention)
- [Graph Rewriting](#graph-rewriting)
- [Benchmark](#benchmark)
- [Troubleshooting](#troubleshooting)
- [Release notes](#release-notes)
- [Change Log](#change-log)
- [Known Issues](#known-issues)
- [Report Issues](#report-issues)
## TensorRT-LLM Overview
TensorRT-LLM provides users with an easy-to-use Python API to define Large
Language Models (LLMs) and build
[TensorRT](https://developer.nvidia.com/tensorrt) engines that contain
state-of-the-art optimizations to perform inference efficiently on NVIDIA GPUs.
TensorRT-LLM also contains components to create Python and C++ runtimes that
execute those TensorRT engines. It also includes a
[backend](https://github.com/triton-inference-server/tensorrtllm_backend)
for integration with the
[NVIDIA Triton Inference Server](https://developer.nvidia.com/nvidia-triton-inference-server);
a production-quality system to serve LLMs. Models built with TensorRT-LLM can
be executed on a wide range of configurations going from a single GPU to
multiple nodes with multiple GPUs (using
[Tensor Parallelism](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/nlp/nemo_megatron/parallelisms.html#tensor-parallelism)
and/or
[Pipeline Parallelism](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/nlp/nemo_megatron/parallelisms.html#pipeline-parallelism)).
The Python API of TensorRT-LLM is architectured to look similar to the
[PyTorch](https://pytorch.org) API. It provides users with a
[functional](./tensorrt_llm/functional.py) module containing functions like
`einsum`, `softmax`, `matmul` or `view`. The [layers](./tensorrt_llm/layers)
module bundles useful building blocks to assemble LLMs; like an `Attention`
block, a `MLP` or the entire `Transformer` layer. Model-specific components,
like `GPTAttention` or `BertAttention`, can be found in the
[models](./tensorrt_llm/models) module.
TensorRT-LLM comes with several popular models pre-defined. They can easily be
modified and extended to fit custom needs. See below for a list of supported
[models](#Models).
To maximize performance and reduce memory footprint, TensorRT-LLM allows the
models to be executed using different quantization modes (see
[`examples/gpt`](./examples/gpt) for concrete examples). TensorRT-LLM supports
INT4 or INT8 weights (and FP16 activations; a.k.a. INT4/INT8 weight-only) as
well as a complete implementation of the
[SmoothQuant](https://arxiv.org/abs/2211.10438) technique.
For a more detailed presentation of the software architecture and the key
concepts used in TensorRT-LLM, we recommend you to read the following
[document](./docs/source/architecture.md).
## Installation
*For Windows installation, see [`Windows`](windows/README.md).*
TensorRT-LLM must be built from source, instructions can be found
[here](./docs/source/installation.md). An image of a Docker container with
TensorRT-LLM and its Triton Inference Server Backend will be made available
soon.
The remaining commands in that document must be executed from the TensorRT-LLM
container.
## Quick Start
To create a TensorRT engine for an existing model, there are 3 steps:
1. Download pre-trained weights,
2. Build a fully-optimized engine of the model,
3. Deploy the engine.
The following sections show how to use TensorRT-LLM to run the
[BLOOM-560m](https://huggingface.co/bigscience/bloom-560m) model.
***0. In the BLOOM folder***
Inside the Docker container, you have to install the requirements:
```bash
pip install -r examples/bloom/requirements.txt
git lfs install
```
***1. Download the model weights from HuggingFace***
From the BLOOM example folder, you must download the weights of the model.
```bash
cd examples/bloom
rm -rf ./bloom/560M
mkdir -p ./bloom/560M && git clone https://huggingface.co/bigscience/bloom-560m ./bloom/560M
```
***2. Build the engine***
```python
# Single GPU on BLOOM 560M
python build.py --model_dir ./bloom/560M/ \
--dtype float16 \
--use_gemm_plugin float16 \
--use_gpt_attention_plugin float16 \
--output_dir ./bloom/560M/trt_engines/fp16/1-gpu/
```
See the BLOOM [example](examples/bloom) for more details and options regarding the `build.py` script.
***3. Run***
The `../summarize.py` script can be used to perform the summarization of articles
from the CNN Daily dataset:
```python
python ../summarize.py --test_trt_llm \
--hf_model_dir ./bloom/560M/ \
--data_type fp16 \
--engine_dir ./bloom/560M/trt_engines/fp16/1-gpu/
```
More details about the script and how to run the BLOOM model can be found in
the example [folder](examples/bloom). Many more [models](#models) than BLOOM
are implemented in TensorRT-LLM. They can be found in the
[examples](./examples/) directory.
## Support Matrix
TensorRT-LLM optimizes the performance of a range of well-known models on
NVIDIA GPUs. The following sections provide a list of supported GPU
architectures as well as important features implemented in TensorRT-LLM.
### Devices
TensorRT-LLM is rigorously tested on the following GPUs:
* [H100](https://www.nvidia.com/en-us/data-center/h100/)
* [L40S](https://www.nvidia.com/en-us/data-center/l40s/)
* [A100](https://www.nvidia.com/en-us/data-center/a100/)
* [A30](https://www.nvidia.com/en-us/data-center/products/a30-gpu/)
* [V100](https://www.nvidia.com/en-us/data-center/v100/) (experimental)
If a GPU is not listed above, it is important to note that TensorRT-LLM is
expected to work on GPUs based on the Volta, Turing, Ampere, Hopper and Ada
Lovelace architectures. Certain limitations may, however, apply.
### Precision
Various numerical precisions are supported in TensorRT-LLM. The support for
some of those numerical features require specific architectures:
| | FP32 | FP16 | BF16 | FP8 | INT8 | INT4 |
| :------------------ | :--- | :--- | :--- | :--- | :--- | :--- |
| Volta (SM70) | Y | Y | N | N | Y | Y |
| Turing (SM75) | Y | Y | N | N | Y | Y |
| Ampere (SM80, SM86) | Y | Y | Y | N | Y | Y |
| Ada-Lovelace (SM89) | Y | Y | Y | Y | Y | Y |
| Hopper (SM90) | Y | Y | Y | Y | Y | Y |
In this release of TensorRT-LLM, the support for FP8 and quantized data types
(INT8 or INT4) is not implemented for all the models. See the
[precision](./docs/source/precision.md) document and the
[examples](./examples/.) folder for additional details.
### Key Features
TensorRT-LLM contains examples that implement the following features.
* Multi-head Attention([MHA](https://arxiv.org/abs/1706.03762))
* Multi-query Attention ([MQA](https://arxiv.org/abs/1911.02150))
* Group-query Attention([GQA](https://arxiv.org/abs/2307.09288))
* In-flight Batching
* Paged KV Cache for the Attention
* Tensor Parallelism
* Pipeline Parallelism
* INT4/INT8 Weight-Only Quantization (W4A16 & W8A16)
* [SmoothQuant](https://arxiv.org/abs/2211.10438)
* [GPTQ](https://arxiv.org/abs/2210.17323)
* [AWQ](https://arxiv.org/abs/2306.00978)
* [FP8](https://arxiv.org/abs/2209.05433)
* Greedy-search
* Beam-search
* RoPE
In this release of TensorRT-LLM, some of the features are not enabled for all
the models listed in the [examples](examples/.) folder.
### Models
The list of supported models is:
* [Baichuan](examples/baichuan)
* [Bert](examples/bert)
* [Blip2](examples/blip2)
* [BLOOM](examples/bloom)
* [ChatGLM](examples/chatglm)
* [Falcon](examples/falcon)
* [Flan-T5](examples/enc_dec)
* [GPT](examples/gpt)
* [GPT-J](examples/gptj)
* [GPT-Nemo](examples/gpt)
* [GPT-NeoX](examples/gptneox)
* [InternLM](examples/internlm)
* [LLaMA](examples/llama)
* [LLaMA-v2](examples/llama)
* [Mistral](examples/llama)
* [MPT](examples/mpt)
* [mT5](examples/enc_dec)
* [OPT](examples/opt)
* [Qwen](examples/qwen)
* [Replit Code](examples/mpt)
* [SantaCoder](examples/gpt)
* [StarCoder](examples/gpt)
* [T5](examples/enc_dec)
Note: [Encoder-Decoder](examples/enc_dec/) provides general encoder-decoder
support that contains many encoder-decoder models such as T5, Flan-T5, etc. We
unroll the exact model names in the list above to let users find specific
models easier.
## Performance
Please refer to the [performance](./docs/source/performance.md) page for
performance numbers. That page contains measured numbers for four variants of
popular models (GPT-J, LLAMA-7B, LLAMA-70B, Falcon-180B), measured on the H100,
L40S and A100 GPU(s).
## Advanced Topics
### Quantization
This [document](./docs/source/precision.md) describes the different
quantization methods implemented in TensorRT-LLM and contains a support matrix
for the different models.
### In-flight Batching
TensorRT-LLM supports in-flight batching of requests (also known as continuous
batching or iteration-level batching). It's a
[technique](./docs/source/batch_manager.md) that aims at reducing wait
times in queues, eliminating the need for padding requests and allowing for
higher GPU utilization.
### Attention
TensorRT-LLM implements several variants of the Attention mechanism that
appears in most the Large Language Models. This
[document](./docs/source/gpt_attention.md) summarizes those implementations and
how they are optimized in TensorRT-LLM.
### Graph Rewriting
TensorRT-LLM uses a declarative approach to define neural networks and contains
techniques to optimize the underlying graph. For more details, please refer to
[doc](./docs/source/graph-rewriting.md)
### Benchmark
TensorRT-LLM provides [C++](./benchmarks/cpp/README.md) and
[Python](./benchmarks/python/README.md) tools to perform benchmarking. Note,
however, that it is recommended to use the C++ version.
## Troubleshooting
* It's recommended to add options `–shm-size=1g –ulimit memlock=-1` to the
docker or nvidia-docker run command. Otherwise you may see NCCL errors when
running multiple GPU inferences. See
https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/troubleshooting.html#errors
for details.
* When building models, memory-related issues such as
```
[09/23/2023-03:13:00] [TRT] [E] 9: GPTLMHeadModel/layers/0/attention/qkv/PLUGIN_V2_Gemm_0: could not find any supported formats consistent with input/output data types
[09/23/2023-03:13:00] [TRT] [E] 9: [pluginV2Builder.cpp::reportPluginError::24] Error Code 9: Internal Error (GPTLMHeadModel/layers/0/attention/qkv/PLUGIN_V2_Gemm_0: could not find any supported formats consistent with input/output data types)
```
may happen. One possible solution is to reduce the amount of memory needed by
reducing the maximum batch size, input and output lengths. Another option is to
enable plugins, for example: `--use_gpt_attention_plugin`.
* MPI + Slurm
TensorRT-LLM is a
[MPI](https://en.wikipedia.org/wiki/Message_Passing_Interface)-aware package
that uses [`mpi4py`](https://mpi4py.readthedocs.io/en/stable/). If you are
running scripts in a [Slurm](https://slurm.schedmd.com/) environment, you might
encounter interferences:
```
--------------------------------------------------------------------------
PMI2_Init failed to initialize. Return code: 14
--------------------------------------------------------------------------
--------------------------------------------------------------------------
The application appears to have been direct launched using "srun",
but OMPI was not built with SLURM's PMI support and therefore cannot
execute. There are several options for building PMI support under
SLURM, depending upon the SLURM version you are using:
version 16.05 or later: you can use SLURM's PMIx support. This
requires that you configure and build SLURM --with-pmix.
Versions earlier than 16.05: you must use either SLURM's PMI-1 or
PMI-2 support. SLURM builds PMI-1 by default, or you can manually
install PMI-2. You must then build Open MPI using --with-pmi pointing
to the SLURM PMI library location.
Please configure as appropriate and try again.
--------------------------------------------------------------------------
```
As a rule of thumb, if you are running TensorRT-LLM interactively on a Slurm
node, prefix your commands with `mpirun -n 1` to run TensorRT-LLM in a
dedicated MPI environment, not the one provided by your Slurm allocation.
For example: `mpirun -n 1 python3 examples/gpt/build.py ...`
## Release notes
* TensorRT-LLM requires TensorRT 9.2 and 23.10 containers.
### Change Log
#### Versions 0.6.0 / 0.6.1
* Models
* ChatGLM3
* InternLM (contributed by @wangruohui)
* Mistral 7B (developed in collaboration with Mistral.AI)
* MQA/GQA support to MPT (and GPT) models (contributed by @bheilbrun)
* Qwen (contributed by @Tlntin and @zhaohb)
* Replit Code V-1.5 3B (external contribution)
* T5, mT5, Flan-T5 (Python runtime only)
* Features
* Add runtime statistics related to active requests and KV cache
utilization from the batch manager (see
the [batch manager](docs/source/batch_manager.md) documentation)
* Add `sequence_length` tensor to support proper lengths in beam-search
(when beam-width > 1 - see
[tensorrt_llm/batch_manager/GptManager.h](cpp/include/tensorrt_llm/batch_manager/GptManager.h))
* BF16 support for encoder-decoder models (Python runtime - see
[examples/enc_dec](examples/enc_dec/README.md))
* Improvements to memory utilization (CPU and GPU - including memory
leaks)
* Improved error reporting and memory consumption
* Improved support for stop and bad words
* INT8 SmoothQuant and INT8 KV Cache support for the Baichuan models (see
[examples/baichuan](examples/baichuan/README.md))
* INT4 AWQ Tensor Parallelism support and INT8 KV cache + AWQ/weight-only
support for the GPT-J model (see [examples/gptj](examples/gptj/README.md))
* INT4 AWQ support for the Falcon models
(see [examples/falcon](examples/falcon/README.md))
* LoRA support (functional preview only - limited to the Python runtime,
only QKV support and not optimized in terms of runtime performance) for
the GPT model (see the
[Run LoRA with the Nemo checkpoint](examples/gpt/README.md#Run-LoRA-with-the-Nemo-checkpoint)
in the GPT example)
* Multi-GPU support for encoder-decoder models (Python runtime - see
[examples/enc_dec](examples/enc_dec/README.md))
* New heuristic for launching the Multi-block Masked MHA kernel (similar
to FlashDecoding - see
[decoderMaskedMultiheadAttentionLaunch.h](cpp/tensorrt_llm/kernels/decoderMaskedMultiheadAttention/decoderMaskedMultiheadAttentionLaunch.h))
* Prompt-Tuning support for GPT and LLaMA models (see the
[Prompt-tuning](examples/gpt/README.md#Prompt-tuning) Section in the GPT example)
* Performance optimizations in various CUDA kernels
* Possibility to exclude input tokens from the output (see `excludeInputInOutput` in
[`GptManager`](cpp/include/tensorrt_llm/batch_manager/GptManager.h))
* Python binding for the C++ runtime (GptSession - see [`pybind`](cpp/tensorrt_llm/pybind))
* Support for different micro batch sizes for context and generation
phases with pipeline parallelism (see `GptSession::Config::ctxMicroBatchSize` and
`GptSession::Config::genMicroBatchSize` in
[tensorrt_llm/runtime/gptSession.h](cpp/include/tensorrt_llm/runtime/gptSession.h))
* Support for "remove input padding" for encoder-decoder models (see
[examples/enc_dec](examples/enc_dec/README.md))
* Support for context and generation logits (see `mComputeContextLogits` and
`mComputeGenerationLogits` in
[tensorrt_llm/runtime/gptModelConfig.h](cpp/include/tensorrt_llm/runtime/gptModelConfig.h))
* Support for `logProbs` and `cumLogProbs` (see `"output_log_probs"` and
`"cum_log_probs"` in [`GptManager`](cpp/include/tensorrt_llm/batch_manager/GptManager.h))
* Update to CUTLASS 3.x
* Bug fixes
* Fix for ChatGLM2 #93 and #138
* Fix tensor names error "RuntimeError: Tensor names
(`host_max_kv_cache_length`) in engine are not the same as expected in
the main branch" #369
* Fix weights split issue in BLOOM when `world_size = 2` ("array split
does not result in an equal division") #374
* Fix SmoothQuant multi-GPU failure with tensor parallelism is 2 #267
* Fix a crash in GenerationSession if stream keyword argument is not None
#202
* Fix a typo when calling PyNVML API [BUG] code bug #410
* Fix bugs related to the improper management of the `end_id` for various
models [C++ and Python]
* Fix memory leaks [C++ code and Python models]
* Fix the std::alloc error when running the gptManagerBenchmark -- issue
gptManagerBenchmark std::bad_alloc error #66
* Fix a bug in pipeline parallelism when beam-width > 1
* Fix a bug with Llama GPTQ due to improper support of GQA
* Fix issue #88
* Fix an issue with the Huggingface Transformers version #16
* Fix link jump in windows readme.md #30 - by @yuanlehome
* Fix typo in batchScheduler.h #56 - by @eltociear
* Fix typo #58 - by @RichardScottOZ
* Fix Multi-block MMHA: Difference between `max_batch_size` in the engine
builder and `max_num_sequences` in TrtGptModelOptionalParams? #65
* Fix the log message to be more accurate on KV cache #224
* Fix Windows release wheel installation: Failed to install the release
wheel for Windows using pip #261
* Fix missing torch dependencies: [BUG] The batch_manage.a choice error
in --cpp-only when torch's cxx_abi version is different with gcc #151
* Fix linking error during compiling google-test & benchmarks #277
* Fix logits dtype for Baichuan and ChatGLM: segmentation fault caused by
the lack of bfloat16 #335
* Minor bug fixes
#### Version 0.5.0
* TensorRT-LLM v0.5.0 is the first public release.
### Known Issues
* The hang reported in issue
[#149](https://github.com/triton-inference-server/tensorrtllm_backend/issues/149)
has not been reproduced by the TensorRT-LLM team. If it is caused by a bug
in TensorRT-LLM, that bug may be present in that release
### Report Issues
You can use GitHub issues to report issues with TensorRT-LLM. |
{
Implementar un programa que invoque a los siguientes módulos.
a. Un módulo recursivo que permita leer una secuencia de caracteres terminada en punto, los
almacene en un vector con dimensión física igual a 10 y retorne el vector.
b. Un módulo que reciba el vector generado en a) e imprima el contenido del vector.
c. Un módulo recursivo que reciba el vector generado en a) e imprima el contenido del vector..
d. Un módulo recursivo que permita leer una secuencia de caracteres terminada en punto y
retorne la cantidad de caracteres leídos. El programa debe informar el valor retornado.
e. Un módulo recursivo que permita leer una secuencia de caracteres terminada en punto y
retorne una lista con los caracteres leídos.
f. Un módulo recursivo que reciba la lista generada en e) e imprima los valores de la lista en el
mismo orden que están almacenados.
g. Implemente un módulo recursivo que reciba la lista generada en e) e imprima los valores de
la lista en orden inverso al que están almacenados.
}
program ejercicio01;
const
dimf=10;
type
letras=array[1..dimf] of char;
lista=^nodo;
nodo=record
sig:lista;
dato:char;
end;
procedure descomponer_palabra(var vec:letras;var dimlog:integer);
var
caracter:char;
begin
readln(caracter);
if ( caracter <> '.') and (dimlog < dimF) then
begin
dimlog:=dimlog+1;
vec[dimlog]:=caracter;
descomponer_palabra(vec,dimlog);
end
else
end;
procedure imprimir_vector (vec:letras;dimlog:integer);
var
i:integer;
begin
for i:=1 to dimlog do
begin
writeln(vec[i]);
end;
end;
procedure imprimir_vector_recursivo (vec:letras;dimlog:integer);
begin
if dimlog > 0 then
begin
writeln(vec[dimlog]);
dimlog:=dimlog-1;
imprimir_vector_recursivo (vec,dimlog);
end;
end;
function contar_caracteres ():integer;
var
caracter:char;
begin
readln(caracter);
if caracter <> '.' then
contar_caracteres:=contar_caracteres()+1
else
contar_caracteres:=0
end;
procedure lista_caracteres (var l:lista; var pri:lista);
var
caracter:char;
nuevo:lista;
begin
readln(caracter);
if caracter <> '.' then
begin
new(nuevo);
nuevo^.sig:=nil;
nuevo^.dato:=caracter;
if l=nil then
begin
l:=nuevo;
pri:=nuevo;
end
else begin
l^.sig:=nuevo;
l:=nuevo;
end;
lista_caracteres(l,pri);
end;
end;
procedure leer_lista(pri:lista);
begin
if pri <> nil then
writeln(pri^.dato);
leer_lista(pri^.sig);
end;
procedure apilar (var p:lista; l:lista);
var
nuevo:lista;
begin
if l <> nil then begin
new(nuevo);
nuevo^.sig:=p;
nuevo^.dato:=l^.dato;
apilar (p,l^.sig);
end;
end;
procedure desapilar (p:lista);
begin
if p <> nil then
writeln(p^.dato);
desapilar(p^.sig);
end;
procedure leer_pila (p:lista; l:lista);
begin
apilar(p,l);
desapilar(p);
end;
var
vec:letras;
dimlog:integer;
pri,l,pila:lista;
begin
dimlog:=0;
l:=nil;
pri:=nil;
pila:=nil;
descomponer_palabra(vec,dimlog);
imprimir_vector (vec,dimlog);
imprimir_vector_recursivo (vec,dimlog);
writeln(contar_caracteres());
lista_caracteres(l,pri);
leer_lista(pri);
leer_pila(pila,l)
end. |
import React, { useEffect, useState } from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const PostCard = () => {
const Navigate = useNavigate();
const [preview, setPreview] = useState('');
const [image, setImage] = useState('');
const [text, setText] = useState('');
const [loading, setLoading] = useState(false);
const [user, setUser] = useState('');
useEffect(() => {
fetchUserDetails();
}, [])
const selectFile = (event) => {
setPreview(URL.createObjectURL(event.target.files[0]));
setImage(event.target.files[0]);
}
const savePost = async () => {
if(image && text)
{
setLoading(true);
const data = new FormData();
data.append("file", image);
data.append("upload_preset", "hackerInsta");
data.append("cloud_name", "hacker03");
const photoRes = await axios.post('https://api.cloudinary.com/v1_1/hacker03/image/upload', data);
const response = await fetch("/instagram/posts/createPosts", {
method: "POST",
headers: {
"Content-Type": "application/json",
"authToken": localStorage.getItem('token1')
},
body: JSON.stringify({ description: text, photo: photoRes.data.url })
});
const result = await response.json()
if (result.success) {
setLoading(false);
Navigate('/');
}
}
else
{
alert("Please select something to post...");
}
}
const fetchUserDetails = async () => {
const response = await fetch('/instagram/auth/getUser', {
method: "GET",
headers: {
"Content-Type": "application/json",
"authToken": localStorage.getItem('token1')
}
})
const userDetails = await response.json();
setUser(userDetails);
}
return (
<>
{
loading ?
<img src="/images/spinner.gif" alt="loader" />
:
<div className=' p-2 w-[90%] m-auto bg-white rounded-2xl createdPostCard flex flex-col justify-evenly'>
<h1 className='p-2 text-center font-bold text-xl'>Create Post and Share Your Best Time</h1>
<hr />
<div className='m-2 flex items-center'>
<img src="https://cdn-icons-png.flaticon.com/128/3135/3135715.png" className='w-8' alt="logo" />
<h5 className='ml-2 font-bold'>{user.name}</h5>
</div>
<div className='py-3'>
{preview ? <img src={preview} alt="preview" className='w-[50%] m-auto' id='preview' /> : <img src='/images/default_images.png' className='w-[50%] m-auto' alt="preview" id='preview' />}
</div>
<div className='p-2'>
<input type="file" name="file" id="file" className='my-2 text-xs' onChange={selectFile} />
<div className='flex'>
<textarea name="description" id="description" className='border-2 border-gray-400 text-black px-2 text-sm w-full' placeholder='write something about your post...' onChange={(event) => { setText(event.target.value) }}></textarea>
<button className='py-1 ml-2 px-5 rounded-full bg-gray-300 hover:bg-gray-400 transition-all' onClick={savePost}><i className="fa-solid fa-arrow-right fa-xl"></i></button>
</div>
</div>
</div>
}
</>
)
}
export default PostCard |
import { LoginHandler } from './login.handler';
import { AuthService } from 'src/auth/auth.service';
import { Test } from '@nestjs/testing';
import { Repository } from 'typeorm';
import { UserEntity } from 'src/users/infra/db/entities/user.entity';
import { getRepositoryToken } from '@nestjs/typeorm';
import { LoginCommand } from './login.command';
import { NotFoundException } from '@nestjs/common';
describe('LoginHandler', () => {
let loginHandler: LoginHandler;
let authService: AuthService;
let userRepository: Repository<UserEntity>;
beforeAll(async () => {
const module = await Test.createTestingModule({
providers: [
LoginHandler,
{
provide: getRepositoryToken(UserEntity),
useValue: {
findOne: jest.fn(),
},
},
{
provide: AuthService,
useValue: {
login: jest.fn(),
},
},
],
}).compile();
loginHandler = module.get(LoginHandler);
authService = module.get(AuthService);
userRepository = module.get(getRepositoryToken(UserEntity));
});
const email = 'to22me@gmail.com';
const password = 'pass1234';
const name = undefined;
const id = undefined;
describe('execute', () => {
it('should throw NotFoundException when user does not exist', async () => {
// Given
// When
const loginCommand = new LoginCommand(email, password);
const executePromise = loginHandler.execute(loginCommand);
// Then
await expect(executePromise).rejects.toThrowError(NotFoundException);
});
it('should login user when user exists', async () => {
// Given
userRepository.findOne = jest.fn().mockResolvedValue({
email,
password,
});
// When
const loginCommand = new LoginCommand(email, password);
await loginHandler.execute(loginCommand);
// Then
expect(authService.login).toBeCalledWith({ email, id, name });
});
});
}); |
import { Calendar } from 'react-big-calendar';
import withDragAndDrop from "react-big-calendar/lib/addons/dragAndDrop";
import "react-big-calendar/lib/addons/dragAndDrop/styles.css";
import 'react-big-calendar/lib/css/react-big-calendar.css';
import { CalendarLayout } from '../../layouts';
import { useCalendar } from '../../hooks';
import { localizer, getMessagesES } from '../../helpers';
import { AddEventButton, CalendarEventBox, CalendarModal, DeleteEventButton, CalendarTollbar } from '../../components';
export const CalendarPage = () => {
const DnDCalendar = withDragAndDrop(Calendar);
const {
events, lastView, formats, eventStyleGetter, handleDobleClick, handleSelect, handleSelectSlot, handleViewChange
} = useCalendar();
//Resize
const onEventResize = (data) => {
const { start, end } = data;
console.log(start, end, data, 'resize');
};
//Drop
const onEventDrop = (data) => {
console.log(data, 'drop');
};
return (
<CalendarLayout>
<Calendar
views={['month', 'week', 'day', 'agenda', 'work_week']}
defaultView={ lastView }
events={ events }
startAccessor="start"
endAccessor="end"
backgroundEvents={ events }
culture='es-ES'
localizer={ localizer }
formats={ formats }
style={{ height: 'calc( 100vh)', border: 'none' }}
messages={ getMessagesES() }
components={{
event: CalendarEventBox,
toolbar: CalendarTollbar,
}}
dayLayoutAlgorithm='no-overlap'
//Actions
eventPropGetter={ eventStyleGetter }
onDoubleClickEvent={ handleDobleClick }
onSelectEvent={ handleSelect }
onView={ handleViewChange }
onSelectSlot={ handleSelectSlot }
selectable
/* DROP */
onEventDrop={onEventDrop}
onEventResize={onEventResize}
resizable
/>
<CalendarModal />
<AddEventButton />
<DeleteEventButton />
</CalendarLayout>
)
} |
// https://adventofcode.com/2017/day/25 The Halting Problem
package main
import (
"fmt"
"time"
)
type SubInstruction struct {
write, move int
next string
}
type Instruction struct {
instructions [2]SubInstruction
}
var (
pos int
tape map[int]int = make(map[int]int)
)
// input has states A .. F
// only ever move one slot at a time
// at this point, I figured it would be quicker to parse the input by hand...
// var (
// state string = "A"
// steps int = 6
// program map[string]Instruction = map[string]Instruction{
// "A": {[2]SubInstruction{{1, 1, "B"}, {0, -1, "B"}}},
// "B": {[2]SubInstruction{{1, -1, "A"}, {1, 1, "A"}}},
// }
// )
var (
state string = "A"
steps int = 12425180
program map[string]Instruction = map[string]Instruction{
"A": {[2]SubInstruction{{1, 1, "B"}, {0, 1, "F"}}},
"B": {[2]SubInstruction{{0, -1, "B"}, {1, -1, "C"}}},
"C": {[2]SubInstruction{{1, -1, "D"}, {0, 1, "C"}}},
"D": {[2]SubInstruction{{1, -1, "E"}, {1, 1, "A"}}},
"E": {[2]SubInstruction{{1, -1, "F"}, {0, -1, "D"}}},
"F": {[2]SubInstruction{{1, 1, "A"}, {0, -1, "E"}}},
}
)
func duration(invocation time.Time, name string) {
fmt.Println(name, time.Since(invocation))
}
func partOne() int {
defer duration(time.Now(), "part 1")
for i := 0; i < steps; i++ {
var subinstr SubInstruction = program[state].instructions[tape[pos]]
tape[pos] = subinstr.write
pos += subinstr.move
state = subinstr.next
}
// fmt.Println("tape length", len(tape)) // 6196
var result int
for _, v := range tape {
result += v
}
return result
}
func main() {
defer duration(time.Now(), "main")
fmt.Println(partOne()) // 3099
}
/*
$ go run main.go
part 1 499.425801ms
3099
main 499.446435ms
*/ |
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import {useForm} from "react-hook-form";
import { useState,useEffect } from "react";
import * as z from "zod";
import { Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle} from "@/components/ui/dialog"
import {Form,FormControl,FormField,FormItem,FormLabel,FormMessage} from "@/components/ui/form";
import{Input} from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { FileUpload } from "../file-upload";
import axios from "axios";
import { useRouter } from "next/navigation";
const formSchema = z.object({name:z.string().min(1,{message:"Server name is required"}),imageUrl:z.string().min(1,{message:"Server image is required"})});
export const InitialModal = () => {
const [isMouted,setIsMouted] = useState(false);
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {name:"",imageUrl:"",}});
const isLoading = form.formState.isSubmitting;
const routes = useRouter();
const onSubmit = async (values:z.infer<typeof formSchema>) => {
try {
await axios.post("/api/servers",values);
form.reset();
routes.refresh();
window.location.reload();
}
catch (error){
console.log(error);
}
};
useEffect(() => {
setIsMouted(true);
},[]);
if (!isMouted) {
return null;
}
return (
<Dialog open>
<DialogContent className="bg-white text-black p-0 overflow-hidden">
<DialogHeader className="pt-8 px-6">
<DialogTitle className="text-2xl text-center font-bold">Customize your server</DialogTitle>
<DialogDescription className="text-center text-zinc-500">Give your new server a personality with a name and an icon. You can always change it later.</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<div className="space-y-8 px-6">
<div className="flex items-center justify-center text-center">
<FormField control={form.control} name="imageUrl" render={({field}) =>(<FormItem><FormControl><FileUpload endpoint="serverImage" value ={field.value} onChange={field.onChange}/></FormControl></FormItem>)}/>
</div>
<FormField control={form.control} name="name" render ={({field}) =>(<FormItem><FormLabel className="uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70">Server name</FormLabel>
<FormControl><Input disabled={isLoading} className="bg-zinc-300/50 border-0 focus-visible:ring-0 text-black focus-visible:ring-offset" placeholder="Enter server name" {...field}/></FormControl></FormItem>)} />
</div>
<DialogFooter className="bg-gray-100 px-6 py-4">
<Button disabled={isLoading} variant="primary">
Create
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)} |
import {
Controller,
Get,
Post,
Body,
Param,
Delete,
Put,
HttpCode,
UseGuards,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ApiBearerAuth, ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
import { IsPublic } from 'src/auth/decorators/is-public.decorator';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
@Controller('users')
@ApiTags('Users')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
@IsPublic()
@ApiOperation({ summary: 'Create an user' })
@ApiBody({ type: CreateUserDto })
async create(@Body() createUserDto: CreateUserDto) {
const newUser = await this.usersService.create(createUserDto);
return { user: newUser };
}
@Get()
@ApiOperation({ summary: 'Get all users' })
findAll() {
return this.usersService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get an unique user' })
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
@Put(':id')
@ApiOperation({ summary: 'Update an unique user' })
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(id, updateUserDto);
}
@Delete(':id')
@HttpCode(204)
@ApiOperation({ summary: 'Delete an unique user' })
remove(@Param('id') id: string) {
return this.usersService.remove(id);
}
} |
import socket
##########################################################
# Terminal coloring #
##########################################################
class BeautifyTerminal:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
##########################################################
# Server-client for 1 connection #
##########################################################
# Using AF_INET for TCP/IP connection, SOCK_STREAM for 2 parties connection, aka client and server
# Using SOL_SOCKET for setting the SOCKET options (it's a socket layer), SO_REUSEADDR - allows duplicate binding
# Duplicate binding is when the same IP and port could be used on different sockets at the same time
backend = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
backend.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
backend.bind(('localhost', 1969))
backend.listen()
while True:
print(f' {BeautifyTerminal.WARNING} \n Awaiting connection from the client \n {BeautifyTerminal.ENDC}')
client_socket, client_address = backend.accept()
print(f'{BeautifyTerminal.WARNING} Spotted connection from: {client_address} {BeautifyTerminal.ENDC}')
while True:
client_request = client_socket.recv(2048)
# If no request under the binded address and port, wait for upcoming connection
if not client_request:
break
else:
response_for_client = f'\n Hey pal, you serving or just hanging out? I want some food 0____0 \n'.encode()
client_socket.send(response_for_client)
client_socket.close() |
from project.task import Task
class Section:
def __init__(self, name: str):
self.name = name
self.tasks = []
def add_task(self, new_task: Task) -> str:
if new_task in self.tasks:
return f"Task is already in the section {self.name}"
self.tasks.append(new_task)
return f"Task {new_task.details()} is added to the section"
def complete_task(self, task_name: str) -> str:
try:
completed_task = next(filter(lambda x: x.name == task_name, self.tasks))
except StopIteration:
return f"Could not find task with the name {task_name}"
completed_task.completed = True
return f"Completed task {task_name}"
def clean_section(self) -> str:
count_tasks = 0
for task in self.tasks:
if task.completed:
count_tasks += 1
self.tasks.remove(task)
return f"Cleared {count_tasks} tasks."
def view_section(self) -> str:
tasks_with_details = "\n".join(t.details() for t in self.tasks)
return f"Section {self.name}:\n{tasks_with_details}" |
################################################################################
# #
# Project: Population segmentation and transition probability estimation #
# using data on health and health-related social service needs from the #
# US Health and Retirement Study #
# Project section: Transition probability estimation #
# R version: 4.2.1 #
# File name: 02_markov_trace_HS.R #
# Data required: dataT.RData, data_msm_HS.RData #
# Author: Lize Duminy #
# Date: 2023.03.19 #
# #
################################################################################
################################################################################
# #
# STUDY SETUP #
# #
################################################################################
# Clear workspace
rm(list=ls())
save.image()
graphics.off()
gc()
# Set memory
#options(java.parameters = "-Xmx3000m")
# Load packages
packages <- c('msm','gridExtra', 'grid', 'lattice', 'readr', 'dplyr',
'data.table', 'ggplot2')
lapply(packages, function(x)
if( !require(x, character.only = TRUE)){
install.packages(x, dependencies = TRUE)
library(x, character.only = TRUE)
} else {
library(x, character.only = TRUE)
})
rm(packages)
# Re-assign select to avoid MASS dplyr conflict
select <- dplyr::select
################################################################################
# #
# Import data #
# #
################################################################################
# Interview observations (panel data)
load("~/Health_and_Retirement_Study/HRS_markov/00_data/dataT.RData")
# Transition probabilities (msm-fitted model)
load("~/Health_and_Retirement_Study/HRS_markov/00_data/data_msm_HS.RData")
################################################################################
# #
# Prepare reference dataset (HRS) #
# #
################################################################################
# Extract target cohort
# Look at interview opportunities since target age
###### Select age to investigate
agex <- c(50:120)
int_wavex <- c(8)
HSx <- c(1:10)
#q <- dataT[dataT$HS!=999,]
q <- dataT
#round age to nearest whole number
q$age_round <- floor(q$age_years)
#identify everyone that were "agex" years old in interview wave "int_wavex"
q2 <- q[(q$age_round %in% agex) & (q$wave %in% int_wavex) & (q$HS %in% HSx),]
#cut down dataset to include only entries of individuals who were "agex"
#years old during interview wave "int_wavex"
q <- q[q$hhidpn %in% q2$hhidpn,]
rm(q2)
#-------------------------------------------------------------------------------
# Continue with preparing the data
#-------------------------------------------------------------------------------
#Save the sample size for reporting purposes
n_sample <- length(unique(q$hhidpn))
q <- q %>%
filter(wave >= min(int_wavex)) %>% #exclude entries of recorded before
#interview wave "int_wavex"
group_by(hhidpn) %>%
arrange(hhidpn, age_round) %>%
mutate(int_op = (wave - first(wave))*2) %>% #the number of interview
#opportunities since agex
ungroup()
#Save current dataset to be fitted with msm later in the code
dataT2 <- q
q <- q %>%
group_by(int_op, HS) %>%
mutate(HS_tot = n()) %>%
slice(1) %>%
select(int_op, HS, HS_tot) %>%
ungroup()
#create new dataset with only deatHS as deatHS need to be reported cumulatively
#and remove deatHS from original dataset
q11 <- q[q$HS==11,]
q <- q[q$HS!=11,]
#create a death row for every single interview opportunity to correctly
#estimate cumulative deatHS
q11.2 <- as.data.table(unique(q$int_op))
q11 <- merge(q11, q11.2, by.x = "int_op", by.y = "V1", all = TRUE)
rm(q11.2)
q11[,"HS"] <- 11
q11[is.na(q11$HS_tot),"HS_tot"] <- 0
#calculate the cumulative number of deatHS per age group
q11 <- q11 %>%
arrange(int_op) %>%
mutate(HS_tot_cum = cumsum(HS_tot))
#re-assign variable HS_tot the cumulative total
q11$HS_tot <- q11$HS_tot_cum
#drop the variable HS_tot_cum
q11$HS_tot_cum <- NULL
#joint two datasets together
q <- rbind(q, q11)
#rm(q11)
#fractional HS per age
q <- q %>%
group_by(int_op) %>%
mutate(HS_frac = HS_tot/sum(HS_tot)) %>%
mutate(group = "Data") %>%
arrange(int_op, HS) %>%
filter(HS!=999) %>%
ungroup() %>%
select(int_op, HS, HS_tot, HS_frac, group)
#-------------------------------------------------------------------------------
# Ensure only every second interview opportunity is included
#-------------------------------------------------------------------------------
#extract interview opportunities listed in dataset
int_ops <- unique(q$int_op)
#select every second wave
#(persons are interviewed in-person only every second wave)
int_ops <- int_ops[seq(1, length(int_ops), 2)]
#constrain results to
q <- q[q$int_op %in% int_ops,]
rm(int_ops)
#-------------------------------------------------------------------------------
# Calculate adjusted "Deceased fraction" as health state 12
#-------------------------------------------------------------------------------
q12 <- q11
rm(q11)
#q12[,"HS"] <- 12
#re-assign variable HS_tot the cumulative total
q12$HS_frac <- q12$HS_tot/n_sample
#remove any waves not shown in final dataset
q12 <- q12[q12$int_op<=max(q$int_op),]
q12$group <- "Data"
q12 <- q12[,c("int_op", "HS", "HS_frac", "group")]
################################################################################
# #
# Run Markov trace #
# #
################################################################################
#decide to make x-axis calander time with years starting at 0 for 1st interview
dataT2 <- dataT2 %>%
group_by(hhidpn) %>%
mutate(years = age_years - first(age_years)) %>%
ungroup()
# fetch estimated transition probabilities
model <- data_msm_GI[["30000"]]
(pmat.msm <- pmatrix.msm(model, t=1, ci=c("normal"), cl=0.95, B=1000)$estimates)
#Reduce columns
q <- q %>%
select(int_op, HS, HS_frac, group)
# Markov model
maxtime <- max(q$int_op)+1
j_init <- q[q$int_op==0,c("HS", "HS_frac")]
j_init2 <- as.data.table(1:11)
j_init <- merge(j_init, j_init2, by.x = "HS", by.y = "V1", all = TRUE)
rm(j_init2)
j_init[is.na(j_init$HS_frac),"HS_frac"] <- 0
j_init <- t(j_init$HS_frac)
#Markov Model: using pmatrix determined by msm to model future health prevalence
j <- NULL
for(i in 1:maxtime) {
if (i == 1) {
j <- j_init
} else {
iprev <- i-1
k <- as.double(j[iprev,1:11]) %*% pmat.msm
j <- rbind(j,k)
}}
rownames(j) <- 1:nrow(j)
int_op <- nrow(j)-1
int_op <- 0:int_op
j <- cbind(j,int_op)
rm(j_init, k, iprev, int_op, maxtime)
################################################################################
# #
# Plot results #
# #
################################################################################
#prepare data for database restructuring
j <- as.data.table(j)
q$HS <- as.factor(q$HS)
ylim_max <- ceiling(max(j[,1:11])*10)/10+0.1
#State 1: GI I, CF 0
j1 <- cbind(j[,"int_op"], 1, j[,"State 1"], rep("Markov trace",nrow(j)))
colnames(j1) <- c("int_op", "HS", "HS_frac", "group")
q1 <- q[q$HS == 1,]
w1 <- rbind(q1,j1)
w1$group <- as.factor(w1$group)
w1$HS_frac <- as.double(w1$HS_frac)
w1$int_op <- as.double(w1$int_op)
p1 <- ggplot(w1, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI I, CF 0 ") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p1
#State 2: GI I, CF 1
j2 <- cbind(j[,"int_op"], 2, j[,"State 2"], rep("Markov trace",nrow(j)))
colnames(j2) <- c("int_op", "HS", "HS_frac", "group")
q2 <- q[q$HS == 2,]
w2 <- rbind(q2,j2)
w2$group <- as.factor(w2$group)
w2$HS_frac <- as.double(w2$HS_frac)
w2$int_op <- as.double(w2$int_op)
p2 <- ggplot(w2, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI I, CF 1") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p2
#State 3: GI II, CF 0
j3 <- cbind(j[,"int_op"], 3, j[,"State 3"], rep("Markov trace",nrow(j)))
colnames(j3) <- c("int_op", "HS", "HS_frac", "group")
q3 <- q[q$HS == 3,]
w3 <- rbind(q3,j3)
w3$group <- as.factor(w3$group)
w3$HS_frac <- as.double(w3$HS_frac)
w3$int_op <- as.double(w3$int_op)
p3 <- ggplot(w3, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI II, CF 0") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p3
#State 4: GI II, CF 1
j4 <- cbind(j[,"int_op"], 4, j[,"State 4"], rep("Markov trace",nrow(j)))
colnames(j4) <- c("int_op", "HS", "HS_frac", "group")
q4 <- q[q$HS == 4,]
w4 <- rbind(q4,j4)
w4$group <- as.factor(w4$group)
w4$HS_frac <- as.double(w4$HS_frac)
w4$int_op <- as.double(w4$int_op)
p4 <- ggplot(w4, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI II, CF 1") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p4
#State 5: GI III, CF 0
j5 <- cbind(j[,"int_op"], 5, j[,"State 5"], rep("Markov trace",nrow(j)))
colnames(j5) <- c("int_op", "HS", "HS_frac", "group")
q5 <- q[q$HS == 5,]
w5 <- rbind(q5,j5)
w5$group <- as.factor(w5$group)
w5$HS_frac <- as.double(w5$HS_frac)
w5$int_op <- as.double(w5$int_op)
p5 <- ggplot(w5, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI III, CF 0") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p5
#State 6: GI III, CF I
j6 <- cbind(j[,"int_op"], 6, j[,"State 6"], rep("Markov trace",nrow(j)))
colnames(j6) <- c("int_op", "HS", "HS_frac", "group")
q6 <- q[q$HS == 6,]
w6 <- rbind(q6,j6)
w6$group <- as.factor(w6$group)
w6$HS_frac <- as.double(w6$HS_frac)
w6$int_op <- as.double(w6$int_op)
p6 <- ggplot(w6, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI III, CF I") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p6
#State 7: GI IV, CF 0
j7 <- cbind(j[,"int_op"], 7, j[,"State 7"], rep("Markov trace",nrow(j)))
colnames(j7) <- c("int_op", "HS", "HS_frac", "group")
q7 <- q[q$HS == 7,]
w7 <- rbind(q7,j7)
w7$group <- as.factor(w7$group)
w7$HS_frac <- as.double(w7$HS_frac)
w7$int_op <- as.double(w7$int_op)
p7 <- ggplot(w7, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI IV, CF 0") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p7
#State 8: GI IV, CF 1
j8 <- cbind(j[,"int_op"], 8, j[,"State 8"], rep("Markov trace",nrow(j)))
colnames(j8) <- c("int_op", "HS", "HS_frac", "group")
q8 <- q[q$HS == 8,]
w8 <- rbind(q8,j8)
w8$group <- as.factor(w8$group)
w8$HS_frac <- as.double(w8$HS_frac)
w8$int_op <- as.double(w8$int_op)
p8 <- ggplot(w8, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI IV, CF 1") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p8
#State 9: GI V, CF 0
j9 <- cbind(j[,"int_op"], 9, j[,"State 9"], rep("Markov trace",nrow(j)))
colnames(j9) <- c("int_op", "HS", "HS_frac", "group")
q9 <- q[q$HS == 9,]
w9 <- rbind(q9,j9)
w9$group <- as.factor(w9$group)
w9$HS_frac <- as.double(w9$HS_frac)
w9$int_op <- as.double(w9$int_op)
p9 <- ggplot(w9, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI V, CF 0") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p9
#State 10: GI V, CF 1
j10 <- cbind(j[,"int_op"], 10, j[,"State 10"], rep("Markov trace",nrow(j)))
colnames(j10) <- c("int_op", "HS", "HS_frac", "group")
q10 <- q[q$HS == 10,]
w10 <- rbind(q10,j10)
w10$group <- as.factor(w10$group)
w10$HS_frac <- as.double(w10$HS_frac)
w10$int_op <- as.double(w10$int_op)
p10 <- ggplot(w10, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("GI V, CF 1") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
ylim(0,ylim_max)
p10
#State 11: Death
j11 <- cbind(j[,"int_op"], 11, j[,"State 11"], rep("Markov trace",nrow(j)))
colnames(j11) <- c("int_op", "HS", "HS_frac", "group")
q11 <- q[(q$HS == 11), ]
w11 <- rbind(j11,q12)
w11$group <- as.factor(w11$group)
w11$HS_frac <- as.double(w11$HS_frac)
w11$int_op <- as.double(w11$int_op)
p11 <- ggplot(w11, aes(x=int_op, y=HS_frac, color = group)) +
geom_line(aes(color=group), size = 1)+
geom_point(aes(color=group), size = 1) +
ggtitle("Deceased") +
xlab("Years") +
ylab("Prevalence (%)") +
theme(legend.position="bottom") +
ylim(0,ylim_max) +
theme(legend.title=element_blank())
p11
# Generate Plot
agemin <- min(agex)
agemax <- max(agex)
chart_title <- paste("Cohort aged between ",agemin," and ",agemax,
" in interview wave ",int_wavex, ", n = ", n_sample,
sep = "", collapse = NULL)
#Generate file name for plot
chart_name <- paste("02_results/02_traces/HS_age",agemin,"_",agemax,"_int",
int_wavex, ".png", sep = "", collapse = NULL)
grid.arrange(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, ncol=4,
top = chart_title)
dev.copy(png,filename=chart_name)
dev.off () |
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.List;
import model.Epic;
import model.Subtask;
import model.Task;
import service.Managers;
import service.TaskManagerService;
import service.impl.FileBackedTaskManager;
/**
* Класс для тестирования менеджеров
*/
public class Main {
private static final String saveFile = "save/saveFile.csv";
public static void main(String[] args) {
System.out.println("Программа стартовала в: " + OffsetDateTime.now());
TaskManagerService taskManager = Managers.getDefault();
Task task1 = new Task("Закончить выполнение ТЗ", "Желательно сегодня", Duration.ofDays(1), LocalDateTime.now());
Task task2 = new Task("Поиграть с котом", "давно с ним не играли", Duration.ofDays(1),
LocalDateTime.now().plusDays(2));
Epic epic1 = new Epic("Сходить в магазин", "сегодня");
Epic epic2 = new Epic("Навести порядок в квартире", "завтра");
Task createdTask = taskManager.createTask(task1);
Task createdTask2 = taskManager.createTask(task2);
Epic createdEpic = taskManager.createEpic(epic1);
Epic createdEpic2 = taskManager.createEpic(epic2);
Subtask subtask1 = new Subtask("Купить молоко", "Простоквашино", createdEpic.getId(), Duration.ofDays(1),
LocalDateTime.now().plusDays(6));
Subtask subtask2 = new Subtask("Купить мясо", "Свинину", createdEpic.getId(), Duration.ofDays(1),
LocalDateTime.now().plusDays(8));
Subtask subtask3 = new Subtask("Купить картошку", "Мытую", createdEpic.getId(), Duration.ofDays(1),
LocalDateTime.now().plusDays(10));
Subtask createdSubtask = taskManager.createSubtask(subtask1);
Subtask createdSubtask2 = taskManager.createSubtask(subtask2);
Subtask createdSubtask3 = taskManager.createSubtask(subtask3);
System.out.println(taskManager.getTaskById(createdTask.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getSubTaskById(createdSubtask3.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getEpicById(createdEpic.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getTaskById(createdTask2.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getEpicById(createdEpic2.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getSubTaskById(createdSubtask2.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getSubTaskById(createdSubtask.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getTaskById(createdTask.getId()));
System.out.println("--------------ИСТОРИЯ ПРОСМОТРОВ ПЕРВОЙ ТАСКИ НЕ ДОЛЖНО БЫТЬ В КОНЦЕ--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getHistory().size());
taskManager.removeEpicById(epic1.getId());
System.out.println(
"--------------ИСТОРИЯ ПРОСМОТРОВ ДОЛЖНА БЫТЬ БЕЗ ПЕРВОГО ЭПИКА И ЕГО САБТАСОК--------------");
System.out.println(taskManager.getHistory());
System.out.println("----------------------------------------------");
System.out.println(taskManager.getHistory().size());
TaskManagerService newTaskManager = FileBackedTaskManager.loadFromFile(saveFile);
System.out.println(
"--------------ТАСКИ ДОЛЖНЫ СОВПАДАТЬ В ОБОИХ МЕНЕДЖЕРАХ--------------");
List<List<? extends Task>> taskBeforeExit = List.of(taskManager.getTasks(), taskManager.getEpics(),
taskManager.getSubTasks());
List<List<? extends Task>> tasksAfterExit = List.of(newTaskManager.getTasks(), newTaskManager.getEpics(),
newTaskManager.getSubTasks());
System.out.println("tasksBeforeExit: " + taskBeforeExit);
System.out.println("tasksAfterExit: " + tasksAfterExit);
}
} |
import 'package:flutter/material.dart';
import 'package:pasya/theme.dart';
import 'package:pasya/ui/changeAddress/change_address_page.dart';
class AddressCard extends StatelessWidget {
const AddressCard(
{super.key,
required this.title,
required this.name,
required this.number,
required this.address,
required this.icon,
this.check = false,
this.opacity = false});
final String title;
final String name;
final String number;
final String address;
final bool icon;
final bool check;
final bool opacity;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ChangeAddressPage()),
),
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
border: Border.all(color: blueColor.withOpacity(0.5), width: 1),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(
Icons.home_filled,
color: blueColor,
size: 20,
),
const SizedBox(
width: 8,
),
Text(
title,
style: blackText.copyWith(
fontSize: 16, fontWeight: semibold),
)
],
),
Container(
width: icon ? 28 : 0,
height: 28,
decoration: BoxDecoration(
color: opacity ? yellowColor.withOpacity(0.4) : yellowColor,
borderRadius: BorderRadius.circular(20.0),
),
child: Center(
child: Icon(
check ? Icons.check : Icons.arrow_forward_ios_outlined,
color: blueColor,
size: icon ? 20.0 : 0,
),
),
),
],
),
const SizedBox(
height: 8,
),
Text(
'$name ($number)',
style: blackText,
),
Text(
address,
style: blackText,
)
],
),
),
);
}
} |
# Practice 6: Regular Expressions
import re
# Validate an Email Address
# Write a function `validate_email_address` which returns `True` if the given string is an email address, `False` is it isn't.
def validate_email_address(email):
if re.match(r'\w+@\w+\.com', email):
return True
else:
return False
def test_validate_email_address():
assert validate_email_address('test@gmail.com') == True
assert validate_email_address('abc123@gmail.com') == True
assert validate_email_address('test') == False
assert validate_email_address('test@gmail') == False
assert validate_email_address('test@gmail@com') == False
# Validate a Phone Number
# Write a function `validate_phone_number` which returns `True` if the given string is a phone number, `False` if it isn't.
# https://regex101.com/r/lCV6nR/1
def validate_phone_number(phone_number):
if re.match(r'\(?\d{3}\)?-? ?\d{3}-?\d{4}', phone_number):
return True
else:
return False
def test_validate_phone_number():
assert validate_phone_number('0123456789') == True
assert validate_phone_number('012-345-6789') == True
assert validate_phone_number('(012) 345-6789') == True
assert validate_phone_number('012-3A5-6789') == False
assert validate_phone_number('1-1-1') == False
# Clean a Phone Number
# Write a function `clean_phone_number` which returns a string containing just the numbers of a phone number if it's valid, `None` if it's not. Hint: use capture groups.
def clean_phone_number(phone_number):
regex = r'^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})'
match = re.match(regex, phone_number)
if match:
match = match.group(1, 2, 3)
match = ''.join(match)
return match
def test_clean_phone_number():
assert clean_phone_number('0123456789') == '0123456789'
assert clean_phone_number('012-345-6789') == '0123456789'
assert clean_phone_number('(012) 345-6789') == '0123456789'
assert clean_phone_number('012-3A5-6789') == None
assert clean_phone_number('1-1-1') == None
# Find All Numbers
# Write a function `find_numbers` which returns a list of floats found in the given string.
def find_numbers(text):
match = re.findall(r'-?\d+\.\d+', text)
match = [float(num) for num in match]
return match
def test_find_numbers():
text = '''
name favorite number
joe 1.23
jane 5.45
julie -1.34
bob 43.123
'''
assert find_numbers(text) == [1.23, 5.45, -1.34, 43.123] |
import { useGetSuppliesQuery } from "@/features/api/apiSlice";
import Container from "@/lib/container";
import { useState } from "react";
import { Button } from "../ui/button";
import { Link } from "react-router-dom";
import { CardModal } from "./CardModal";
interface Donation {
amount: number;
category: string;
description: string;
imageUrl: string;
title: string;
_id: string;
}
export default function SupplyCard() {
const [showAll, setShowAll] = useState(true);
const {
data: supplyPosts,
isLoading,
isError,
} = useGetSuppliesQuery(undefined);
let content = undefined;
if (isLoading) {
content = <h1>this is loading</h1>;
}
if (!isLoading && isError) {
content = <h1>this is error</h1>;
}
if (!isLoading && !isError && supplyPosts?.length === 0) {
content = <h1>data not found</h1>;
}
return (
<Container>
<div>
<div className="flex justify-between items-center my-16">
<div className=" font-bold text-2xl ">All Supplies</div>
<div>{<CardModal />}</div>
</div>
</div>
{}
<div className="grid lg:grid-cols-3 gap-10">
{showAll
? supplyPosts?.slice(0, 6).map((s: Donation) => (
<div
key={s._id}
className="overflow-hidden rounded bg-white text-slate-500 shadow-md shadow-slate-200"
>
{/* <!-- Image --> */}
<figure>
<img
src={s.imageUrl}
alt="card image"
className="aspect-video "
/>
</figure>
{/* <!-- Body--> */}
<div className="p-6">
<header className="mb-4">
<h3 className="text-xl font-medium text-slate-700">
{s.title}
</h3>
<p className=" text-slate-400"> {s.amount}</p>
</header>
<p>{s.category}</p>
</div>
{/* <!-- Action base sized basic button --> */}
<div className="flex justify-end p-6 pt-0">
<Link to={`/supplies/${s._id}`}>
<button
onClick={() => console.log(s._id)}
className="inline-flex h-10 w-full items-center justify-center gap-2 whitespace-nowrap rounded bg-gray-500 px-5 text-sm font-medium tracking-wide text-white transition duration-300 hover:bg-gray-600 focus:bg-gray-700 focus-visible:outline-none disabled:cursor-not-allowed disabled:border-gray-300 disabled:bg-gray-300 disabled:shadow-none"
>
<span>View Details</span>
</button>
</Link>
</div>
</div>
))
: supplyPosts?.map((s: Donation) => (
<div
key={s._id}
className="overflow-hidden rounded bg-white text-slate-500 shadow-md shadow-slate-200"
>
{/* <!-- Image --> */}
<figure>
<img
src={s.imageUrl}
alt="card image"
className="aspect-video "
/>
</figure>
{/* <!-- Body--> */}
<div className="p-6">
<header className="mb-4">
<h3 className="text-xl font-medium text-slate-700">
{s.title}
</h3>
<p className=" text-slate-400"> {s.amount}</p>
</header>
<p>{s.category}</p>
</div>
{/* <!-- Action base sized basic button --> */}
<div className="flex justify-end p-6 pt-0">
<Link to={`/supplies/${s._id}`}>
<button
onClick={() => console.log(s._id)}
className="inline-flex h-10 w-full items-center justify-center gap-2 whitespace-nowrap rounded bg-gray-500 px-5 text-sm font-medium tracking-wide text-white transition duration-300 hover:bg-gray-600 focus:bg-gray-700 focus-visible:outline-none disabled:cursor-not-allowed disabled:border-gray-300 disabled:bg-gray-300 disabled:shadow-none"
>
<span>View Details</span>
</button>
</Link>
</div>
</div>
))}
</div>
{content}
<Button
onClick={() => setShowAll(!showAll)}
className="ml-[40%] mt-12 px-20 py-8 text-lg"
>
{showAll ? <span>view All</span> : <span>View Less</span>}
</Button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Glide.js/3.0.2/glide.js"></script>
{/*<!-- End Carousel with controls inside --> */}
</Container>
);
}
// useEffect(() => {
// const slider = new Glide(".glide-01", {
// type: "carousel",
// focusAt: "center",
// perView: 3,
// autoplay: 3000,
// animationDuration: 700,
// gap: 24,
// classNames: {
// nav: {
// active: "[&>*]:bg-wuiSlate-700",
// },
// },
// breakpoints: {
// 1024: {
// perView: 2,
// },
// 640: {
// perView: 1,
// },
// },
// }).mount();
// return () => {
// slider.destroy();
// };
// }, []); |
package br.com.rafaelbiasi.blog.facade.impl;
import br.com.rafaelbiasi.blog.data.AccountData;
import br.com.rafaelbiasi.blog.data.CommentData;
import br.com.rafaelbiasi.blog.data.PostData;
import br.com.rafaelbiasi.blog.facade.CommentFacade;
import br.com.rafaelbiasi.blog.model.Comment;
import br.com.rafaelbiasi.blog.service.CommentService;
import br.com.rafaelbiasi.blog.transformer.impl.Transformer;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.security.Principal;
import static java.util.Objects.requireNonNull;
@Component
@Transactional
public class CommentFacadeImpl implements CommentFacade {
private final CommentService commentService;
private final Transformer<CommentData, Comment> commentTransformer;
public CommentFacadeImpl(
CommentService commentService,
@Qualifier("commentTransformer") Transformer<CommentData, Comment> commentTransformer) {
this.commentService = commentService;
this.commentTransformer = commentTransformer;
}
@Override
public void save(CommentData comment, String postCode, Principal principal) {
requireNonNull(comment, "Comment is null");
requireNonNull(postCode, "Post Code is null");
requireNonNull(principal, "Principal is null");
comment.setAuthor(AccountData.builder().username(principal.getName()).build());
comment.setPost(PostData.builder().code(postCode).build());
commentService.save(commentTransformer.convert(comment));
}
@Override
public void delete(String code) {
Comment comment = commentService.findByCode(code).orElseThrow(() -> new RuntimeException("Comment not found"));
commentService.delete(comment);
}
} |
"use client";
import { useState, useRef, useEffect } from "react";
import arrowLeft from "@/app/images/arrow-left-solid.svg";
import Image from "next/image";
import { useDispatch } from "react-redux";
import { createPost } from "@/app/store/slices/postSlice";
export default function AddPost({onClose}) {
const inputRef = useRef(null);
const ref = useRef();
const [file, setFile] = useState(null);
const [desc, setDesc] = useState('')
const dispatch = useDispatch()
const handleFileChange = (e) => {
const files = e.target.files;
if (files.length > 0) {
setFile(URL.createObjectURL(e.target.files[0]));
} else {
setFile(null);
}
};
console.log(file);
console.log(desc);
const handleButtonClick = () => {
inputRef.current?.click();
};
const handleClearFile = () => {
setFile(null);
};
const handleSubmit = (e) => {
const formData = new FormData()
formData.append("image", file)
formData.append("description", desc)
dispatch(createPost(formData))
}
useEffect(() => {
const checkIfClickedOutside = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
onClose();
}
};
document.addEventListener("click", checkIfClickedOutside);
return () => {
document.removeEventListener("click", checkIfClickedOutside);
};
}, [onClose]);
return (
<div className="modal-background">
<div className="modal" ref={ref}>
<div className="modal-top">
{file && (
<button className="btn-none" onClick={handleClearFile}>
<Image
src={arrowLeft}
className="modal-icon"
alt=""
/>
</button>
)}
<p>Create new post</p>
{file && <button onClick={handleSubmit} className="btn-text btn-none">Share</button>}
</div>
<div className="modal-main">
{file && (
<div className="modal-caption-step">
<div className="modal-img">
<img src={file} alt="" />
</div>
<div className="modal-caption">
<textarea
className="modal-textarea"
name=""
id=""
rows="8"
value={desc}
onChange={(e) => setDesc(e.target.value)}
placeholder="Write a caption"
></textarea>
</div>
</div>
)}
{!file && (
<div className="modal-addfile">
<p className="mb-3">Drag photos and videos here</p>
<div>
<input
ref={inputRef}
type="file"
hidden
onChange={handleFileChange}
/>
<button
className="btn btn-sized"
onClick={handleButtonClick}
>
Select from computer
</button>
</div>
</div>
)}
</div>
</div>
</div>
);
} |
library(readxl)
library(tidyverse)
library(readr)
library(tidycensus)
### Census Bureau Building Permits annual files ("a" files)
permits17 <- read_csv("./Data/RawData/USCB/Building Permits Survey/co2017a.txt") %>% filter(FIPS...2 == "19") %>%
rename(Bldgs1 = ...7, Units1 = `1-unit`, Value1 =...9,
Bldgs2 = ...10, Units2 = `2-units`, Value2 =...12,
Bldgs3.4 = ...13, Units3.4 = `3-4 units`, Value3.4 =...15,
Bldgs5 = ...16, Units5 = `5+ units`, Value5 =...18)
permits18 <- read_csv("./Data/RawData/USCB/Building Permits Survey/co2018a.txt") %>% filter(FIPS...2 == "19") %>%
rename(Bldgs1 = ...7, Units1 = `1-unit`, Value1 =...9,
Bldgs2 = ...10, Units2 = `2-units`, Value2 =...12,
Bldgs3.4 = ...13, Units3.4 = `3-4 units`, Value3.4 =...15,
Bldgs5 = ...16, Units5 = `5+ units`, Value5 =...18)
permits19 <- read_csv("./Data/RawData/USCB/Building Permits Survey/co2019a.txt") %>% filter(FIPS...2 == "19") %>%
rename(Bldgs1 = ...7, Units1 = `1-unit`, Value1 =...9,
Bldgs2 = ...10, Units2 = `2-units`, Value2 =...12,
Bldgs3.4 = ...13, Units3.4 = `3-4 units`, Value3.4 =...15,
Bldgs5 = ...16, Units5 = `5+ units`, Value5 =...18)
permits20 <- read_csv("./Data/RawData/USCB/Building Permits Survey/co2020a.txt") %>% filter(FIPS...2 == "19") %>%
rename(Bldgs1 = ...7, Units1 = `1-unit`, Value1 =...9,
Bldgs2 = ...10, Units2 = `2-units`, Value2 =...12,
Bldgs3.4 = ...13, Units3.4 = `3-4 units`, Value3.4 =...15,
Bldgs5 = ...16, Units5 = `5+ units`, Value5 =...18)
permits21 <- read_csv("./Data/RawData/USCB/Building Permits Survey/co2021a.txt") %>% filter(FIPS...2 == "19") %>%
rename(Bldgs1 = ...7, Units1 = `1-unit`, Value1 =...9,
Bldgs2 = ...10, Units2 = `2-units`, Value2 =...12,
Bldgs3.4 = ...13, Units3.4 = `3-4 units`, Value3.4 =...15,
Bldgs5 = ...16, Units5 = `5+ units`, Value5 =...18)
# add 2021
# Every year joined together into a single permits dataframe
permits_df <- rbind(permits17, permits18, permits19, permits20, permits21)
permits_df$FIPS <- str_c(permits_df$FIPS...2, permits_df$FIPS...3)
## Table B25024 Units in Structure from ACS 2016-20
units <- get_acs(
geography = "county",
state = "Iowa",
variables = c(FamDetached = "B25024_002", FamAttached = "B25024_003"),
year = 2020,
cache_table = T,
output = "wide"
)
## Summed number of single family buildings built per county from 2017-2021
# (Building Permits Survey)
permits_df$Units1 <- as.numeric(permits_df$Units1)
sum_Units1_county <- permits_df %>%
group_by(County) %>%
select(Units1) %>%
summarise(sum(Units1))
# Calculate a ratio with the average, annual number of permits
# for single-family units issued over the last five years (2017-2021)
# in the numerator and the number of single family units (ACS 2016-20)
# in the denominator.
SingleFamHomeConstructPct <- (sum_Units1_county$`sum(Units1)`/5)/ (units$FamAttachedE + units$FamDetachedE) * 100
# Data frame containing the Single Family Home Construction Percentages
SingFamCRate <- data.frame(
FIPS = as.numeric(unique(permits_df$FIPS)),
SingleFamHomeConstructPct
)
View(SingFamCRate)
write.csv(SingFamCRate, "Data/CleanData/Ready_SingleFamCRate.csv",
row.names = F) |
import { useState } from "react";
import "./SearchBar.css";
import { signInGoogle } from "../Firebase";
function SearchBar({ meals, setMeals }) {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState([]);
const handleInputChange = (event) => {
setSearchTerm(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
const URL1 = `https://www.themealdb.com/api/json/v1/1/search.php?s=${searchTerm}`;
const URL2 = `https://www.themealdb.com/api/json/v1/1/filter.php?i=${searchTerm}`;
const URL3 = `https://www.themealdb.com/api/json/v1/1/filter.php?a=${searchTerm}`;
Promise.all([fetch(URL1), fetch(URL2), fetch(URL3)])
.then((responses) =>
Promise.all(responses.map((response) => response.json()))
)
.then((data) => {
const filteredData = data.filter((d) => d.meals !== null);
if (filteredData.length === 0) {
setSearchResults([]);
} else {
const combinedMeals = filteredData.reduce(
(meals, current) => meals.concat(current.meals),
[]
);
const filteredMeals = combinedMeals.filter(
(obj, index) =>
combinedMeals.findIndex(
(item) => item.strMeal === obj.strMeal
) === index
);
console.log(filteredMeals);
setSearchResults(filteredMeals);
}
});
};
return (
<div className="search-bar">
<h1 className="search-bar-title">Meally Meaty</h1>
<form onSubmit={handleSubmit} className="search-form">
<input
type="text"
placeholder="Nombre, letra, ingrediente.."
value={searchTerm}
onChange={handleInputChange}
className="search-input"
/>
<button type="submit" className="search-button">
Search
</button>
<button onClick={signInGoogle}>Sign in Google</button>
</form>
{searchResults.length > 0 && (
setMeals(searchResults)
)}
</div>
);
}
export default SearchBar; |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" th:href="@{/css/shared/shared.css}">
<link rel="stylesheet" th:href="@{/css/mechanic-styles/mechanic-reg-form.css}">
</head>
<body>
<header class="heading">
<nav class="nav">
<ul class="navbar">
<li class="navbar-title"><a th:href="@{/}">Mechanic Finder</a></li>
<li><a th:href="@{/api/task/all}">Services</a></li>
<li><a th:href="@{/logout}">Logout</a></li>
</ul>
</nav>
</header>
<section class="form-section">
<div class="container">
<div class="card">
<h1>Update mechanic details</h1>
<form th:action="@{${'/api/mechanic/process-update-mechanic/'+appUser.id}}" th:object="${mechanic}" method="post">
<input type="hidden" th:field="*{id}">
<input type="hidden" th:field="*{availability}">
<input type="hidden" th:field="*{applicationStatus}">
<input type="hidden" th:field="*{createdAt}">
<input type="hidden" th:field="*{profileImage}">
<input type="hidden" th:field="*{qualification}">
<div class="form-control">
<label for="firstName">First Name</label>
<input type="text" th:field="*{firstName}" id="firstName">
<p th:if="${#fields.hasErrors('firstName')}" th:errorclass="error" th:errors="*{firstName}"></p>
</div>
<div class="form-control">
<label for="lastName">Last Name</label>
<input type="text" th:field="*{lastName}" id="lastName">
<p th:if="${#fields.hasErrors('lastName')}" th:errorclass="error" th:errors="*{lastName}"></p>
</div>
<div class="form-control">
<label for="email">Email</label>
<input th:field="*{email}" id="email">
<p th:if="${#fields.hasErrors('email')}" th:errorclass="error" th:errors="*{email}"></p>
</div>
<div class="form-control">
<label for="location">Location</label>
<input type="text" th:field="*{location}" id="location">
<p th:if="${#fields.hasErrors('location')}" th:errorclass="error" th:errors="*{location}"></p>
</div>
<div class="form-control">
<label for="phoneNumber">contact details</label>
<input type="text" th:field="*{phoneNumber}" id="phoneNumber">
<p th:if="${#fields.hasErrors('phoneNumber')}" th:errorclass="error" th:errors="*{phoneNumber}"></p>
</div>
<div class="form-control register-mechanic">
<div>
<input class="btn btn-primary" type="submit" value="update">
</div>
</div>
</form>
</div>
</div>
</section>
</body>
</html> |
# Anderson Lorena CMS Application demonstration.
## Introduction
This CMS Application is built using the ABP framework with Angular. It allows users to manage (list, create, edit, delete) CMS pages and access them through a dynamically generated menu.
## Features
- **CMS Pages**: Home menu to CMS management.
- **New CMS Page**: Users can add new pages to the CMS.
- **Actions: Edit**: Existing pages can be edited.
- **Actions: Delete**: Users can delete pages from the CMS.
- **Pages List Menu**: The menu updates dynamically to reflect the current pages in the CMS.
- **Content Rendering**: Accessing a page from the menu displays its HTML content.
## Getting Started
### Prerequisites
- .NET Core SDK
- Node.js
- Angular CLI
### Setup
#### API
1. Navigate to the API project directory.
2. Run `dotnet restore` to restore the dependencies.
3. Start the API with `dotnet run`.
#### Angular Frontend
1. Navigate to the Angular project directory.
2. Run `npm install` to install dependencies.
3. Start the Angular server with `ng serve`.
4. Access the application at `http://localhost:4200`.
## Usage
- To add a new page, navigate to the CMS Pages section and use the 'New CMS Page' feature.
- Edit or delete pages using the options provided in the CMS pages list.
- Access pages from the dynamic menu; clicking a menu item displays the page content.
# Simple Demonstration Video
https://youtu.be/bmuGk3_pa8Q
## Contributing
Contributions to this project are welcome. Please follow the standard Git workflow - fork, branch, and submit a pull request for review.
## License
GPL-3.0 license
## Contact
Anderson Lorena
https://www.linkedin.com/in/andersonlorena
---
This project adheres to the best practices and standards of the ABP framework and Angular development. |
package com.pingidentity.pingone.connection;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
* Singleton class
* This class is responsible for executing HTTP requests using OkHttp library
*/
public class ConnectionManager {
private static OkHttpClient client;
private static ConnectionManager instance;
private ConnectionManager (){}
synchronized public static ConnectionManager getInstance() {
if (instance == null) {
client = new OkHttpClient();
instance = new ConnectionManager();
}
return instance;
}
public void executeGetRequest(String url, Callback callback) {
Request request = new Request.Builder()
.url(url)
.build();
executeRequest(request, callback);
}
private void executeRequest(Request request, Callback callback) {
client.newCall(request).enqueue(callback);
}
} |
import 'normalize.css'
import '../styles/scss/main.scss'
import type { AppProps } from 'next/app'
import Head from 'next/head'
import { useEffect, useState } from 'react'
import { wrapper } from '../store/store'
import lemon from '../public/images/lemon.svg'
import Aos from 'aos'
import 'aos/dist/aos.css'
import Script from 'next/script'
import Plug from '../components/shared/plug/plug'
import { DevSupport } from '@react-buddy/ide-toolbox'
import { ComponentPreviews, useInitial } from '../dev'
function MyApp({ Component, pageProps }: AppProps) {
const [stripe, setStripe] = useState<boolean>(true)
useEffect(() => {
Aos.init({
disable: 'mobile', once: true, duration: 800,
})
}, [])
return (<>
<Head>
<title>Правильное питание с доставкой</title>
</Head>
{stripe && <Plug/>}
<DevSupport ComponentPreviews={ComponentPreviews}
useInitialHook={useInitial}
>
<Component {...pageProps} />
</DevSupport>
<Script
id="stripe-js"
src="https://js.stripe.com/v3/"
onLoad={() => {
setStripe(false)
}}
/>
</>)
}
export default wrapper.withRedux(MyApp) |
package com.example.costarepair.controller;
import com.example.costarepair.domain.Cliente;
import com.example.costarepair.domain.Vehiculo;
import com.example.costarepair.service.ClienteService;
import com.example.costarepair.service.VehiculoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Slf4j
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/v1/api/vehiculos")
public class VehiculoController {
private final VehiculoService vehiculoService;
public VehiculoController(VehiculoService vehiculoService){
this.vehiculoService = vehiculoService;
}
@GetMapping(value = {"" , "/"}, params = {"!buscar", "!ordenar", "!pagina", "!tamano"})
public List<Vehiculo> all(){
log.info("Accediendo a todos los vehiculos");
return this.vehiculoService.all();
}
@GetMapping(value = {"", "/"}, params={"!buscar", "!ordenar"} )
public ResponseEntity<Map<String, Object>> all(@RequestParam(value = "pagina", defaultValue = "0") int pagina,
@RequestParam(value="tamano", defaultValue = "3") int tamano) {
log.info("Accediendo a todos los vehiculos con paginación");
Map<String, Object> responseAll = this.vehiculoService.all(pagina, tamano);
return ResponseEntity.ok(responseAll);
}
@GetMapping(value = {"","/"}, params = {"!pagina", "!tamano"})
public List<Vehiculo> all(@RequestParam("buscar") Optional<String> buscarOptional,
@RequestParam("ordenar") Optional<String> ordenarOptional
) {
log.info("Accediendo a todos los vehiculos con filtro buscar: %s y ordenar: %s" +
buscarOptional.orElse("VOID"), ordenarOptional.orElse("VOID")
);
return this.vehiculoService.allByQueryFiltersStream(buscarOptional, ordenarOptional);
}
@PostMapping(value = {"", "/"})
public Vehiculo newVehiculo(@RequestBody Vehiculo vehiculo){return this.vehiculoService.save(vehiculo);}
@GetMapping("/{id}")
public Vehiculo one(@PathVariable("id") Long id) {
return this.vehiculoService.one(id);
}
@PutMapping("/{id}")
public Vehiculo replceVehiculo(@PathVariable("id") Long id, @RequestBody Vehiculo vehiculo) {
return this.vehiculoService.replace(id, vehiculo);
}
@ResponseBody
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/{id}")
public void deleteVehiculo(@PathVariable("id") Long id) {
this.vehiculoService.delete(id);
}
} |
package testFx.Librarian;
import com.example.kthimi.Controller.BookController;
import com.example.kthimi.Controller.LibrarianFuncController;
import com.example.kthimi.Controller.MainController;
import com.example.kthimi.Controller.Mockers.FileBasedStockBookRepository;
import com.example.kthimi.Controller.Mockers.MockAuthenticationModel;
import com.example.kthimi.Model.AuthenticationModel;
import com.example.kthimi.Model.BookModel;
import com.example.kthimi.Model.LibrarianModel;
import com.example.kthimi.View.Librarian.LibrarianView;
import com.example.kthimi.View.MainView;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.junit.jupiter.api.Test;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationTest;
import org.testfx.util.WaitForAsyncUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.testfx.util.WaitForAsyncUtils.waitForFxEvents;
public class PrintBillTest extends ApplicationTest {
private MainController mainController;
private MainView mainView;
private Stage primaryStage;
@Override
public void start(Stage primaryStage) throws IOException, InterruptedException, TimeoutException {
//kjo eshte view kryesore dhe eshte njesoj si tek starti i BookstoreApplication class
this.primaryStage = primaryStage;
mainView = new MainView();
mainController = new MainController(mainView);
mainView.setPrimaryStage(primaryStage);
primaryStage.setScene(new Scene(mainView.mainPage(), 800, 600));
primaryStage.setTitle("Bookstore Application");
primaryStage.show();
}
@Test
public void runSystemTest() throws IOException, InterruptedException, TimeoutException {
//krijojm nje temp file testBooks dhe fusim nje test Book brenda ne menyre qe kjo klasa e testit
//te mos perdor dhe mos e modifikoj(te mos ja uli quantityn) librit real
File tempFile = createTestFile();
//i ndryshojme pathet te gjitha klasave qe perdorin Books.bin ne menyre qe kur klasa e testit te behet run
//pathet te ndryshohen ne testBooks.bin
BookController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
FileBasedStockBookRepository.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianFuncController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianModel.STOCK_FILE_PATH = tempFile.getAbsolutePath();
//nje wait per programin qe te presi derisa te klikohet butoni submit
WaitForAsyncUtils.waitFor(5, TimeUnit.SECONDS, () -> !lookup("#Submit").queryAll().isEmpty());
//keto jane te credencialet per tu loguar tek view e librarian qe kompjuteri do te shkruaj ne hapesirat boshe
String validLibrarianUsername = "1";
String validLibrarianPassword = "11";
//mockModeli permban kredencialet e mockuara qe useri te logohet tek librarian
//psh nese programi i ka kredencialet u:1 pass:11 atehere ne mock ne mund te perdorim kredenciale sipas deshires tone
//per ta lehtesuar punen i kam vendosur kredencialet e librarian tek mocku njesoj sic jane ne te vertet
AuthenticationModel mockModel = new MockAuthenticationModel();
mainController.setAuthenticationModel(mockModel);
clickOn(mainView.getUsername()).write(validLibrarianUsername);
Thread.sleep(1000);
clickOn(mainView.getPassword()).write(validLibrarianPassword);
Thread.sleep(1000);
clickOn("#Submit");
waitForFxEvents();
//assertNotNull(mainView.getMainLoginWarning());
// assert(mainView.getMainLoginWarning().getText().isEmpty());
//pasi eshte hapur view e librarian kompjuteri do te selektoj librin Test nga comboboxi dhe
//do te shkruaj quantityn 5 tek textfieldi dhe do klikoj butonin add dhe me pas bill
LibrarianView librarianView = new LibrarianView("1", mainView);
assertNotNull(librarianView);
ComboBox<String> comboBox = lookup("#comboBoxLibrarian").query();
TextField quantityField = lookup("#quantity").query();
FxRobot robot = new FxRobot();
// robot.interact(() -> comboBox.getSelectionModel().select("Test Book"));
robot.interact(() -> {
// Get the items from the ComboBox
ObservableList<String> items = comboBox.getItems();
// Check if there are items in the ComboBox
if (!items.isEmpty()) {
// Generate a random index
int randomIndex = new Random().nextInt(items.size());
// Select the item at the random index
comboBox.getSelectionModel().select(randomIndex);
}
});
robot.clickOn(quantityField).write("5");
robot.clickOn((Button) lookup("#bttAdd").query());
assertEquals("Added", ((TextField) lookup("#warningsLibrarian").query()).getText());
// robot.clickOn((Button) lookup("#bttBill").query());
//
// assertEquals("Bill File Created!", ((TextField) lookup("#warningsLibrarian").query()).getText());
tempFile.delete();
}
@Test
public void runSystemEmptyQuantityTest() throws IOException, InterruptedException, TimeoutException {
//krijojm nje temp file testBooks dhe fusim nje test Book brenda ne menyre qe kjo klasa e testit
//te mos perdor dhe mos e modifikoj(te mos ja uli quantityn) librit real
File tempFile = createTestFile();
//i ndryshojme pathet te gjitha klasave qe perdorin Books.bin ne menyre qe kur klasa e testit te behet run
//pathet te ndryshohen ne testBooks.bin
BookController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
FileBasedStockBookRepository.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianFuncController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianModel.STOCK_FILE_PATH = tempFile.getAbsolutePath();
//nje wait per programin qe te presi derisa te klikohet butoni submit
WaitForAsyncUtils.waitFor(5, TimeUnit.SECONDS, () -> !lookup("#Submit").queryAll().isEmpty());
//keto jane te credencialet per tu loguar tek view e librarian qe kompjuteri do te shkruaj ne hapesirat boshe
String validLibrarianUsername = "1";
String validLibrarianPassword = "11";
//mockModeli permban kredencialet e mockuara qe useri te logohet tek librarian
//psh nese programi i ka kredencialet u:1 pass:11 atehere ne mock ne mund te perdorim kredenciale sipas deshires tone
//per ta lehtesuar punen i kam vendosur kredencialet e librarian tek mocku njesoj sic jane ne te vertet
AuthenticationModel mockModel = new MockAuthenticationModel();
mainController.setAuthenticationModel(mockModel);
clickOn(mainView.getUsername()).write(validLibrarianUsername);
Thread.sleep(1000);
clickOn(mainView.getPassword()).write(validLibrarianPassword);
Thread.sleep(1000);
clickOn("#Submit");
waitForFxEvents();
//assertNotNull(mainView.getMainLoginWarning());
// assert(mainView.getMainLoginWarning().getText().isEmpty());
//pasi eshte hapur view e librarian kompjuteri do te selektoj librin Test nga comboboxi dhe
//do te shkruaj quantityn 5 tek textfieldi dhe do klikoj butonin add dhe me pas bill
LibrarianView librarianView = new LibrarianView("1", mainView);
assertNotNull(librarianView);
ComboBox<String> comboBox = lookup("#comboBoxLibrarian").query();
TextField quantityField = lookup("#quantity").query();
FxRobot robot = new FxRobot();
robot.interact(() -> comboBox.getSelectionModel().select("Test Book"));
//robot.clickOn(quantityField).write("5");
robot.clickOn((Button) lookup("#bttAdd").query());
// assertEquals("Added", ((TextField) lookup("#warningsLibrarian").query()).getText());
robot.clickOn((Button) lookup("#bttBill").query());
assertEquals("Failed, Empty Quantity", ((TextField) lookup("#warningsLibrarian").query()).getText());
tempFile.delete();
}
@Test
public void runSystemEmptyISBNTest() throws IOException, InterruptedException, TimeoutException {
//krijojm nje temp file testBooks dhe fusim nje test Book brenda ne menyre qe kjo klasa e testit
//te mos perdor dhe mos e modifikoj(te mos ja uli quantityn) librit real
File tempFile = createTestFile();
//i ndryshojme pathet te gjitha klasave qe perdorin Books.bin ne menyre qe kur klasa e testit te behet run
//pathet te ndryshohen ne testBooks.bin
BookController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
FileBasedStockBookRepository.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianFuncController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianModel.STOCK_FILE_PATH = tempFile.getAbsolutePath();
//nje wait per programin qe te presi derisa te klikohet butoni submit
WaitForAsyncUtils.waitFor(5, TimeUnit.SECONDS, () -> !lookup("#Submit").queryAll().isEmpty());
//keto jane te credencialet per tu loguar tek view e librarian qe kompjuteri do te shkruaj ne hapesirat boshe
String validLibrarianUsername = "1";
String validLibrarianPassword = "11";
//mockModeli permban kredencialet e mockuara qe useri te logohet tek librarian
//psh nese programi i ka kredencialet u:1 pass:11 atehere ne mock ne mund te perdorim kredenciale sipas deshires tone
//per ta lehtesuar punen i kam vendosur kredencialet e librarian tek mocku njesoj sic jane ne te vertet
AuthenticationModel mockModel = new MockAuthenticationModel();
mainController.setAuthenticationModel(mockModel);
clickOn(mainView.getUsername()).write(validLibrarianUsername);
Thread.sleep(1000);
clickOn(mainView.getPassword()).write(validLibrarianPassword);
Thread.sleep(1000);
clickOn("#Submit");
waitForFxEvents();
//assertNotNull(mainView.getMainLoginWarning());
// assert(mainView.getMainLoginWarning().getText().isEmpty());
//pasi eshte hapur view e librarian kompjuteri do te selektoj librin Test nga comboboxi dhe
//do te shkruaj quantityn 5 tek textfieldi dhe do klikoj butonin add dhe me pas bill
LibrarianView librarianView = new LibrarianView("1", mainView);
assertNotNull(librarianView);
ComboBox<String> comboBox = lookup("#comboBoxLibrarian").query();
TextField quantityField = lookup("#quantity").query();
FxRobot robot = new FxRobot();
//robot.interact(() -> comboBox.getSelectionModel().select("Test Book"));
robot.clickOn(quantityField).write("5");
robot.clickOn((Button) lookup("#bttAdd").query());
// assertEquals("Added", ((TextField) lookup("#warningsLibrarian").query()).getText());
robot.clickOn((Button) lookup("#bttBill").query());
assertEquals("Failed to add,Empty ISBN", ((TextField) lookup("#warningsLibrarian").query()).getText());
tempFile.delete();
}
@Test
public void runSystemEmptyFieldsTest() throws IOException, InterruptedException, TimeoutException {
//krijojm nje temp file testBooks dhe fusim nje test Book brenda ne menyre qe kjo klasa e testit
//te mos perdor dhe mos e modifikoj(te mos ja uli quantityn) librit real
File tempFile = createTestFile();
//i ndryshojme pathet te gjitha klasave qe perdorin Books.bin ne menyre qe kur klasa e testit te behet run
//pathet te ndryshohen ne testBooks.bin
BookController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
FileBasedStockBookRepository.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianFuncController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianModel.STOCK_FILE_PATH = tempFile.getAbsolutePath();
//nje wait per programin qe te presi derisa te klikohet butoni submit
WaitForAsyncUtils.waitFor(5, TimeUnit.SECONDS, () -> !lookup("#Submit").queryAll().isEmpty());
//keto jane te credencialet per tu loguar tek view e librarian qe kompjuteri do te shkruaj ne hapesirat boshe
String validLibrarianUsername = "1";
String validLibrarianPassword = "11";
//mockModeli permban kredencialet e mockuara qe useri te logohet tek librarian
//psh nese programi i ka kredencialet u:1 pass:11 atehere ne mock ne mund te perdorim kredenciale sipas deshires tone
//per ta lehtesuar punen i kam vendosur kredencialet e librarian tek mocku njesoj sic jane ne te vertet
AuthenticationModel mockModel = new MockAuthenticationModel();
mainController.setAuthenticationModel(mockModel);
clickOn(mainView.getUsername()).write(validLibrarianUsername);
Thread.sleep(1000);
clickOn(mainView.getPassword()).write(validLibrarianPassword);
Thread.sleep(1000);
clickOn("#Submit");
waitForFxEvents();
//assertNotNull(mainView.getMainLoginWarning());
// assert(mainView.getMainLoginWarning().getText().isEmpty());
//pasi eshte hapur view e librarian kompjuteri do te selektoj librin Test nga comboboxi dhe
//do te shkruaj quantityn 5 tek textfieldi dhe do klikoj butonin add dhe me pas bill
LibrarianView librarianView = new LibrarianView("1", mainView);
assertNotNull(librarianView);
ComboBox<String> comboBox = lookup("#comboBoxLibrarian").query();
TextField quantityField = lookup("#quantity").query();
FxRobot robot = new FxRobot();
//robot.interact(() -> comboBox.getSelectionModel().select("Test Book"));
//robot.clickOn(quantityField).write("5");
robot.clickOn((Button) lookup("#bttAdd").query());
// assertEquals("Added", ((TextField) lookup("#warningsLibrarian").query()).getText());
robot.clickOn((Button) lookup("#bttBill").query());
assertEquals("Failed, Empty fields", ((TextField) lookup("#warningsLibrarian").query()).getText());
tempFile.delete();
}
@Test
public void runSystemInvalidQuantityTest() throws IOException, InterruptedException, TimeoutException {
//krijojm nje temp file testBooks dhe fusim nje test Book brenda ne menyre qe kjo klasa e testit
//te mos perdor dhe mos e modifikoj(te mos ja uli quantityn) librit real
File tempFile = createTestFile();
//i ndryshojme pathet te gjitha klasave qe perdorin Books.bin ne menyre qe kur klasa e testit te behet run
//pathet te ndryshohen ne testBooks.bin
BookController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
FileBasedStockBookRepository.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianFuncController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianModel.STOCK_FILE_PATH = tempFile.getAbsolutePath();
//nje wait per programin qe te presi derisa te klikohet butoni submit
WaitForAsyncUtils.waitFor(5, TimeUnit.SECONDS, () -> !lookup("#Submit").queryAll().isEmpty());
//keto jane te credencialet per tu loguar tek view e librarian qe kompjuteri do te shkruaj ne hapesirat boshe
String validLibrarianUsername = "1";
String validLibrarianPassword = "11";
//mockModeli permban kredencialet e mockuara qe useri te logohet tek librarian
//psh nese programi i ka kredencialet u:1 pass:11 atehere ne mock ne mund te perdorim kredenciale sipas deshires tone
//per ta lehtesuar punen i kam vendosur kredencialet e librarian tek mocku njesoj sic jane ne te vertet
AuthenticationModel mockModel = new MockAuthenticationModel();
mainController.setAuthenticationModel(mockModel);
clickOn(mainView.getUsername()).write(validLibrarianUsername);
Thread.sleep(1000);
clickOn(mainView.getPassword()).write(validLibrarianPassword);
Thread.sleep(1000);
clickOn("#Submit");
waitForFxEvents();
//assertNotNull(mainView.getMainLoginWarning());
// assert(mainView.getMainLoginWarning().getText().isEmpty());
//pasi eshte hapur view e librarian kompjuteri do te selektoj librin Test nga comboboxi dhe
//do te shkruaj quantityn 5 tek textfieldi dhe do klikoj butonin add dhe me pas bill
LibrarianView librarianView = new LibrarianView("1", mainView);
assertNotNull(librarianView);
ComboBox<String> comboBox = lookup("#comboBoxLibrarian").query();
TextField quantityField = lookup("#quantity").query();
FxRobot robot = new FxRobot();
robot.interact(() -> comboBox.getSelectionModel().select("Test Book"));
robot.clickOn(quantityField).write("-1");
robot.clickOn((Button) lookup("#bttAdd").query());
// assertEquals("Added", ((TextField) lookup("#warningsLibrarian").query()).getText());
robot.clickOn((Button) lookup("#bttBill").query());
assertEquals("Failed, Invalid Quantity", ((TextField) lookup("#warningsLibrarian").query()).getText());
tempFile.delete();
}
@Test
public void runSystemInvalidQuantityZeroTest() throws IOException, InterruptedException, TimeoutException {
//krijojm nje temp file testBooks dhe fusim nje test Book brenda ne menyre qe kjo klasa e testit
//te mos perdor dhe mos e modifikoj(te mos ja uli quantityn) librit real
File tempFile = createTestFile();
//i ndryshojme pathet te gjitha klasave qe perdorin Books.bin ne menyre qe kur klasa e testit te behet run
//pathet te ndryshohen ne testBooks.bin
BookController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
FileBasedStockBookRepository.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianFuncController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianModel.STOCK_FILE_PATH = tempFile.getAbsolutePath();
//nje wait per programin qe te presi derisa te klikohet butoni submit
WaitForAsyncUtils.waitFor(5, TimeUnit.SECONDS, () -> !lookup("#Submit").queryAll().isEmpty());
//keto jane te credencialet per tu loguar tek view e librarian qe kompjuteri do te shkruaj ne hapesirat boshe
String validLibrarianUsername = "1";
String validLibrarianPassword = "11";
//mockModeli permban kredencialet e mockuara qe useri te logohet tek librarian
//psh nese programi i ka kredencialet u:1 pass:11 atehere ne mock ne mund te perdorim kredenciale sipas deshires tone
//per ta lehtesuar punen i kam vendosur kredencialet e librarian tek mocku njesoj sic jane ne te vertet
AuthenticationModel mockModel = new MockAuthenticationModel();
mainController.setAuthenticationModel(mockModel);
clickOn(mainView.getUsername()).write(validLibrarianUsername);
Thread.sleep(1000);
clickOn(mainView.getPassword()).write(validLibrarianPassword);
Thread.sleep(1000);
clickOn("#Submit");
waitForFxEvents();
//assertNotNull(mainView.getMainLoginWarning());
// assert(mainView.getMainLoginWarning().getText().isEmpty());
//pasi eshte hapur view e librarian kompjuteri do te selektoj librin Test nga comboboxi dhe
//do te shkruaj quantityn 5 tek textfieldi dhe do klikoj butonin add dhe me pas bill
LibrarianView librarianView = new LibrarianView("1", mainView);
assertNotNull(librarianView);
ComboBox<String> comboBox = lookup("#comboBoxLibrarian").query();
TextField quantityField = lookup("#quantity").query();
FxRobot robot = new FxRobot();
robot.interact(() -> comboBox.getSelectionModel().select("Test Book"));
robot.clickOn(quantityField).write("0");
robot.clickOn((Button) lookup("#bttAdd").query());
// assertEquals("Added", ((TextField) lookup("#warningsLibrarian").query()).getText());
robot.clickOn((Button) lookup("#bttBill").query());
assertEquals("Failed, Invalid Quantity", ((TextField) lookup("#warningsLibrarian").query()).getText());
tempFile.delete();
}
@Test
public void runSystemNotEnoughStockTest() throws IOException, InterruptedException, TimeoutException {
//krijojm nje temp file testBooks dhe fusim nje test Book brenda ne menyre qe kjo klasa e testit
//te mos perdor dhe mos e modifikoj(te mos ja uli quantityn) librit real
File tempFile = createTestFile();
//i ndryshojme pathet te gjitha klasave qe perdorin Books.bin ne menyre qe kur klasa e testit te behet run
//pathet te ndryshohen ne testBooks.bin
BookController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
FileBasedStockBookRepository.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianFuncController.STOCK_FILE_PATH = tempFile.getAbsolutePath();
LibrarianModel.STOCK_FILE_PATH = tempFile.getAbsolutePath();
//nje wait per programin qe te presi derisa te klikohet butoni submit
WaitForAsyncUtils.waitFor(5, TimeUnit.SECONDS, () -> !lookup("#Submit").queryAll().isEmpty());
//keto jane te credencialet per tu loguar tek view e librarian qe kompjuteri do te shkruaj ne hapesirat boshe
String validLibrarianUsername = "1";
String validLibrarianPassword = "11";
//mockModeli permban kredencialet e mockuara qe useri te logohet tek librarian
//psh nese programi i ka kredencialet u:1 pass:11 atehere ne mock ne mund te perdorim kredenciale sipas deshires tone
//per ta lehtesuar punen i kam vendosur kredencialet e librarian tek mocku njesoj sic jane ne te vertet
AuthenticationModel mockModel = new MockAuthenticationModel();
mainController.setAuthenticationModel(mockModel);
clickOn(mainView.getUsername()).write(validLibrarianUsername);
Thread.sleep(1000);
clickOn(mainView.getPassword()).write(validLibrarianPassword);
Thread.sleep(1000);
clickOn("#Submit");
waitForFxEvents();
//assertNotNull(mainView.getMainLoginWarning());
// assert(mainView.getMainLoginWarning().getText().isEmpty());
//pasi eshte hapur view e librarian kompjuteri do te selektoj librin Test nga comboboxi dhe
//do te shkruaj quantityn 5 tek textfieldi dhe do klikoj butonin add dhe me pas bill
LibrarianView librarianView = new LibrarianView("1", mainView);
assertNotNull(librarianView);
ComboBox<String> comboBox = lookup("#comboBoxLibrarian").query();
TextField quantityField = lookup("#quantity").query();
FxRobot robot = new FxRobot();
robot.interact(() -> comboBox.getSelectionModel().select("Test Book"));
robot.clickOn(quantityField).write("100");
robot.clickOn((Button) lookup("#bttAdd").query());
// assertEquals("Added", ((TextField) lookup("#warningsLibrarian").query()).getText());
robot.clickOn((Button) lookup("#bttBill").query());
assertEquals("Failed,not enough stock", ((TextField) lookup("#warningsLibrarian").query()).getText());
tempFile.delete();
}
private File createTestFile() throws IOException {
File tempFile = File.createTempFile("testBooks", ".bin");
String testFilePath = tempFile.getAbsolutePath();
ArrayList<BookModel> testData = new ArrayList<>();
testData.add(new BookModel("1234567898765", "Test Book", "War", "Supplier", 20.0, 15.0, "Author", 50));
try (ObjectOutputStream objout = new ObjectOutputStream(new FileOutputStream(testFilePath))) {
objout.writeObject(testData);
} catch (IOException e) {
e.printStackTrace();
throw e;
}
return tempFile;
}
} |
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { BehaviorSubject, tap } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class AuthService {
private baseUrl = 'http://localhost:5051';
loggedInUser = new BehaviorSubject<string | undefined>(undefined);
constructor(private httpClient: HttpClient) {
}
login(username: string, password: string) {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.httpClient.post<string>(`${this.baseUrl}/api/login`, { username, password }, {
headers,
responseType: 'text' as 'json' // this is a workaround because the responseType allows only 'json'
})
.pipe(tap((token) => {
this.loggedInUser.next(username);
localStorage.setItem('token', token)
}));
}
logout() {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.httpClient.post<string>(`${this.baseUrl}/api/logout`, undefined, {
headers,
responseType: 'text' as 'json' // this is a workaround because the responseType allows only 'json'
})
.pipe(tap(() => {
this.loggedInUser.next(undefined);
localStorage.removeItem('token');
}));
}
} |
pragma solidity 0.5.0;
import "./ERC721Full.sol";
import "./AccessControl.sol";
import "./Log.sol";
contract CryptoJourney is AccessControl, ERC721Full, Log {
// using SafeMath32 for uint32;
constructor() ERC721Full("CryptoJourney", "CJ") public {
/// Starts paused.
// paused = true;
/// The creator of the contract is the initial owner
setOwner(msg.sender);
}
uint normalPrice = 0.002 ether;
function setNormalPrice(uint price) external onlyContractOwner {
normalPrice = price;
}
struct Attraction {
string name;
int32 lang;
int32 long;
string image;
uint price;
}
Attraction[] public attractions;
function addAttraction(string calldata _name,
int32 _lang,
int32 _long,
string calldata _image) external onlyContractOwner returns (uint) {
return attractions.push(Attraction({name: _name, lang: _lang, long: _long, image: _image, price: normalPrice})) - 1;
}
struct AttractionToken {
string name;
int32 lang;
int32 long;
string image;
}
AttractionToken[] attractionTokens;
/// @dev A mapping from attraction token IDs to the address that owns them.
mapping (uint256 => address) public attractionTokenIdToOwner;
/// @dev A mapping from owner address to count of tokens that address owns.
/// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev Assigns ownership of a specific attraction token to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of attractions is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
attractionTokenIdToOwner[_tokenId] = _to;
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @notice Returns all the relevant information about a specific attraction.
/// @param _id The ID of the attraction of interest.
function getAttractionToken(uint256 _id)
external
view
returns (
string memory name,
int32 lang,
int32 long,
string memory image
) {
AttractionToken storage attractionToken = attractionTokens[_id];
name = attractionToken.name;
lang = attractionToken.lang;
long = attractionToken.long;
image = attractionToken.image;
}
/// @dev An internal method that creates a new attraction token and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate a Transfer event.
function _createAttractionToken(
uint256 _attractionId,
address _owner
)
internal
returns (uint)
{
Attraction memory attraction = attractions[_attractionId];
AttractionToken memory _attractionToken = AttractionToken({
name: attraction.name,
lang: attraction.lang,
long: attraction.long,
image: attraction.image
});
uint256 newAttractionTokenId = attractionTokens.push(_attractionToken) - 1;
// It's probably never going to happen, 4 billion cats is A LOT, but
// let's just be 100% sure we never let this happen.
require(newAttractionTokenId == uint256(uint32(newAttractionTokenId)));
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newAttractionTokenId);
return newAttractionTokenId;
}
} |
import { apiKey, apiURL } from '../consts'
import getCountryName from './getCountryName'
const getCurrentWeatherData = async ({ lat, lon, name, state, country }) => {
const url = `${apiURL}/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`
const response = await fetch(url)
const data = await response.json()
console.log(data)
const { main, wind, weather, visibility } = data
const { feels_like, humidity, pressure, temp } = main
const { description, icon } = weather[0]
const { speed } = wind
const newDescription = description[0].toUpperCase() + description.slice(1)
return {
location: {
name,
state,
country: getCountryName(country),
},
weather: {
description: newDescription,
icon: `${icon}@2x.png`,
temperature: temp.toFixed(1),
feels_like: `${feels_like.toFixed(1)} °C`,
humidity: `${humidity} %`,
pressure: `${pressure} hPa`,
wind_speed: `${speed.toFixed(1)} m/s`,
visibility: `${visibility / 1000} km`,
},
}
}
export default getCurrentWeatherData |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Clientes</title>
<!-- Bootstrap CSS -->
<link href="../static/css/bootstrap.css" rel="stylesheet"
th:href="@{/css/bootstrap.css}">
<link href="../static/css/bootstrap.css" rel="stylesheet"
th:href="@{/css/bootstrap.min.css}">
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Prueba Martin Diaz </h1>
</div>
<br>
<div>
<a href="/save/0" class="btn btn-primary">Agregar</a>
</div>
<h2 th:if="${list.isEmpty()}">No hay personas</h2>
<div th:if="${!list.isEmpty()}">
<h2>Clientes</h2>
<table class="table">
<thead>
<tr>
<th>llave</th>
<th>Nombre</th>
<th>Dirección</th>
<th>Ciudad</th>
<th>Departamento</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="cliente : ${list}">
<td th:text="${cliente.llave}"></td>
<td th:text="${cliente.nombre}"></td>
<td th:text="${cliente.direccion}"></td>
<td th:text="${cliente.ciudad}"></td>
<td th:text="${cliente.departamento}"></td>
<td><a class="btn btn-secondary"
th:href="@{/save/{id}(id=${cliente.id})}">Editar</a></td>
<td><a class="btn btn-danger"
th:href="@{/delete/{id}(id=${cliente.id})}">Eliminar</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html> |
import { GenreResponseProps } from "../App";
import { Button } from "./Button";
interface SideBarProps {
genres: GenreResponseProps[];
onClick: (genreId: number) => void;
selected: number;
}
export const SideBar: React.FC<SideBarProps> = ({
genres,
onClick,
selected,
}) => {
return (
<nav className="sidebar">
<span>
Watch<p>Me</p>
</span>
<div className="buttons-container">
{genres.map((genre) => (
<Button
key={String(genre.id)}
title={genre.title}
iconName={genre.name}
onClick={() => onClick(genre.id)}
selected={selected === genre.id}
/>
))}
</div>
</nav>
);
}; |
package utils
import (
"encoding/base64"
"fmt"
"time"
"github.com/golang-jwt/jwt"
)
func GenerateToken(payload interface{}, privateKey string, ttl time.Duration) (string, error) {
decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
if err != nil {
return "", fmt.Errorf("Could not decode private key: %w", err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(decodedPrivateKey)
if err != nil {
return "", fmt.Errorf("Could not parse private key: %w", err)
}
now := time.Now().UTC()
claims := jwt.MapClaims{
"sub": payload,
"exp": now.Add(ttl).Unix(),
"iat": now.Unix(),
"nbf": now.Unix(),
}
token, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(key)
if err != nil {
return "", fmt.Errorf("Could not create token: %w", err)
}
return token, nil
}
func ValidateToken(token string, publicKey string) (interface{}, error) {
decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
if err != nil {
return nil, fmt.Errorf("Could not decode public key: %w", err)
}
key, err := jwt.ParseRSAPublicKeyFromPEM(decodedPublicKey)
if err != nil {
return nil, fmt.Errorf("Could not parse public key: %w", err)
}
claims := jwt.MapClaims{}
_, err = jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
return nil, fmt.Errorf("Could not parse token: %w", err)
}
return claims["sub"], nil
} |
//
// URLProtocolStub.swift
// EssentialFeedTests
//
// Created by Finn Ebeling on 02.04.24.
//
import Foundation
class URLProtocolStub: URLProtocol {
private struct Stub {
let onStartLoading: (URLProtocolStub) -> Void
}
private static var _stub: Stub?
private static var stub: Stub? {
get { queue.sync { _stub } }
set { queue.sync { _stub = newValue } }
}
private static let queue = DispatchQueue(label: "URLProtocolStub.queue")
static func stub(data: Data?, response: URLResponse?, error: Error?) {
stub = Stub(onStartLoading: { urlProtocol in
guard let client = urlProtocol.client else { return }
if let data {
client.urlProtocol(urlProtocol, didLoad: data)
}
if let response {
client.urlProtocol(urlProtocol, didReceive: response, cacheStoragePolicy: .notAllowed)
}
if let error {
client.urlProtocol(urlProtocol, didFailWithError: error)
} else {
client.urlProtocolDidFinishLoading(urlProtocol)
}
})
}
static func removeStub() {
stub = nil
}
static func observeRequest(observer: @escaping (URLRequest) -> Void) {
stub = Stub(onStartLoading: { urlProtocol in
urlProtocol.client?.urlProtocolDidFinishLoading(urlProtocol)
observer(urlProtocol.request)
})
}
static func onStartLoading(observer: @escaping () -> Void) {
stub = Stub(onStartLoading: { _ in observer() })
}
override class func canInit(with request: URLRequest) -> Bool {
true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
request
}
override func startLoading() {
Self.stub?.onStartLoading(self)
}
override func stopLoading() {}
} |
import 'package:admin_dashboard/providers/auth_provider.dart';
import 'package:admin_dashboard/providers/login_from_provider.dart';
import 'package:admin_dashboard/router/router.dart';
import 'package:admin_dashboard/ui/buttons/custom_outlined_button.dart';
import 'package:admin_dashboard/ui/buttons/link_text.dart';
import 'package:admin_dashboard/ui/inputs/custom_input.dart';
import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class LoginView extends StatelessWidget {
const LoginView({super.key});
@override
Widget build(BuildContext context) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
return ChangeNotifierProvider(
create: (_) => LoginFromProvider(),
child: Builder(builder: (context) {
final loginFromProvider =
Provider.of<LoginFromProvider>(context, listen: false);
return Container(
margin: EdgeInsets.only(top: 100),
padding: EdgeInsets.symmetric(horizontal: 20),
color: Colors.black,
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 370),
child: Form(
key: loginFromProvider.formKey,
autovalidateMode: AutovalidateMode.always,
child: Column(
children: [
//Email
TextFormField(
onChanged: (value) => loginFromProvider.email = value,
validator: (value) {
if (!EmailValidator.validate(value ?? '')) {
return 'Please enter the email';
}
return null;
},
style: TextStyle(color: Colors.white),
decoration: CustomInput.CustomInputDecoration(
hint: 'Ingrese su correo',
label: 'Email',
icon: Icons.email_outlined),
),
SizedBox(height: 20),
TextFormField(
onChanged: (value) =>
loginFromProvider.password = value,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter the password';
}
return null;
},
obscureText: true,
style: TextStyle(color: Colors.white),
decoration: CustomInput.CustomInputDecoration(
hint: '*********',
label: 'Ingrese su password',
icon: Icons.lock_clock_rounded),
),
SizedBox(height: 20),
CustomOutlinedButton(
text: 'Ingresar',
onPressed: () {
final isValid = loginFromProvider.validateFrom();
if (isValid) {
authProvider.login(loginFromProvider.email,
loginFromProvider.password);
}
print('Ingresando...');
},
),
SizedBox(height: 20),
LinkText(
text: 'Nueva Cuenta',
onPressed: () {
Navigator.pushNamed(
context, Flurorouter.registerRoute);
}),
],
)),
),
),
);
}),
);
}
} |
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
#define VIBRATOR_PIN 6 // Change this to the pin connected to your vibrator
Adafruit_BME280 bme;
Adafruit_MPU6050 mpu;
void triggerVibrator(); // Function prototype
void setup()
{
Serial.begin(115200);
pinMode(VIBRATOR_PIN, OUTPUT);
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS))
{
Serial.println(F("SSD1306 allocation failed"));
for (;;)
;
}
display.display();
delay(2000);
display.clearDisplay();
if (!bme.begin(0x76))
{
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1)
;
}
if (!mpu.begin())
{
Serial.println("Failed to find MPU6050 chip");
while (1)
;
}
Serial.println("Ready!");
}
void loop()
{
// sensors_event_t event;
bme.takeForcedMeasurement();
/* Get new sensor events with the readings */
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
float temperature = bme.readTemperature();
float humidity = bme.readHumidity();
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Temperature: ");
display.println(temperature);
display.print("Humidity: ");
display.println(humidity);
display.print("Accel X: ");
display.println(a.acceleration.x);
display.print("Accel Y: ");
display.println(a.acceleration.y);
display.print("Accel Z: ");
display.println(a.acceleration.z);
display.display();
Serial.println('hello');
// Check for motion
if (abs(a.acceleration.x) > 2 || abs(a.acceleration.y) > 2 || abs(a.acceleration.z) > 2)
{
triggerVibrator();
}
delay(1000); // Adjust the delay as needed
}
void triggerVibrator()
{
digitalWrite(VIBRATOR_PIN, HIGH);
delay(1000); // Adjust the vibration duration as needed
digitalWrite(VIBRATOR_PIN, LOW);
} |
/**
* Copyright (C) 2018-2021 Jessica James.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Written by Jessica James <jessica.aj@outlook.com>
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <map>
#include <variant>
#include <utility>
#include "type_traits.hpp"
namespace jessilib {
class object {
public:
using array_type = std::vector<object>;
using text_char_type = char8_t;
using text_type = std::basic_string<text_char_type>;
using text_view_type = std::basic_string_view<text_char_type>;
using data_type = std::vector<unsigned char>;
using string_type = text_type;
using string_view_type = text_view_type;
using map_type = std::map<string_type, object>;
using index_type = std::size_t;
/** is_backing */
template<typename T, typename enable = void>
struct is_backing {
static constexpr bool value = false;
};
template<typename T>
struct is_backing<T, typename std::enable_if<std::is_same<T, bool>::value>::type> {
static constexpr bool value = true;
using type = bool;
};
template<typename T>
struct is_backing<T, typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value>::type> {
static constexpr bool value = true;
using type = intmax_t;
};
template<typename T>
struct is_backing<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
static constexpr bool value = true;
using type = long double;
};
template<typename T>
struct is_backing<T, typename std::enable_if<std::is_same<T, string_type>::value>::type> {
static constexpr bool value = true;
using type = string_type;
};
template<typename T>
struct is_backing<T, typename std::enable_if<is_sequence_container<T>::value>::type> {
static constexpr bool value = true;
using type = array_type;
};
template<typename T>
struct is_backing<T, typename std::enable_if<is_associative_container<T>::value>::type> {
static constexpr bool value = std::is_same<typename is_associative_container<T>::key_type, string_type>::value;
using type = map_type;
};
/** type */
enum class type : size_t {
null = 0,
boolean,
integer,
decimal,
text,
data,
array,
map
};
// Standard constructors
object() = default;
object(const object& in_config);
object(object&& in_config);
~object() = default;
// Value constructors
template<typename T,
typename std::enable_if<is_backing<typename std::decay<T>::type>::value
&& !is_sequence_container<typename std::decay<T>::type>::value
&& (!is_associative_container<typename std::decay<T>::type>::value || std::is_same<typename std::remove_cvref<T>::type, map_type>::value)>::type* = nullptr>
object(T&& in_value)
: m_value{ typename is_backing<typename std::decay<T>::type>::type{ std::forward<T>(in_value) } } {
// Empty ctor body
}
template<typename T,
typename std::enable_if<is_sequence_container<typename std::decay<T>::type>::value
&& !std::is_same<typename std::decay<T>::type, std::vector<bool>>::value>::type* = nullptr>
object(T&& in_value)
: m_value{ array_type{ in_value.begin(), in_value.end() } } {
// Empty ctor body
}
// std::vector<bool>
template<typename T,
typename std::enable_if<std::is_same<typename std::decay<T>::type, std::vector<bool>>::value>::type* = nullptr>
object(T&& in_value)
: m_value{ array_type{} } {
auto& array = std::get<array_type>(m_value);
array.reserve(in_value.size());
for (const auto& item : in_value) {
array.emplace_back(bool{item});
}
}
// std::unordered_map<string_type, object>
template<typename T,
typename std::enable_if<is_unordered_map<typename std::decay<T>::type>::value
&& std::is_same<typename is_unordered_map<typename std::decay<T>::type>::key_type, string_type>::value
&& std::is_same<typename is_unordered_map<typename std::decay<T>::type>::value_type, object>::value>::type* = nullptr>
object(T&& in_value)
: m_value{ map_type{ in_value.begin(), in_value.end() } } {
// Empty ctor body
}
// Non-map_type associative containers (container<string_type, T>)
template<typename T,
typename std::enable_if<is_associative_container<typename std::remove_cvref<T>::type>::value
&& (std::is_convertible<typename is_associative_container<typename std::remove_cvref<T>::type>::key_type, string_type>::value
|| std::is_convertible<typename is_associative_container<typename std::remove_cvref<T>::type>::key_type, string_view_type>::value)
&& !std::is_same<typename is_associative_container<typename std::remove_cvref<T>::type>::value_type, object>::value>::type* = nullptr>
object(T&& in_value)
: m_value{ map_type{} } {
auto& map = std::get<map_type>(m_value);
for (auto& pair : in_value) {
map.emplace(pair.first, pair.second);
}
}
object(const text_char_type* in_str);
object(const string_view_type& in_str);
// Comparison operators
bool operator==(const object& rhs) const {
return m_value == rhs.m_value;
}
bool operator!=(const object& rhs) const {
return m_value != rhs.m_value;
}
bool operator<(const object& rhs) const {
return m_value < rhs.m_value;
}
bool operator>(const object& rhs) const {
return m_value > rhs.m_value;
}
bool operator<=(const object& rhs) const {
return m_value <= rhs.m_value;
}
bool operator>=(const object& rhs) const {
return m_value >= rhs.m_value;
}
// Assignment operators
object& operator=(const object& in_config) = default;
object& operator=(object&& in_config) = default;
// Non-copy/move assignment operator; forwards to set()
template<typename T,
typename std::enable_if<!std::is_same<typename std::decay<T>::type, object>::value>::type* = nullptr>
object& operator=(T&& in) {
set(std::forward<T>(in));
return *this;
}
const object& operator[](const string_type& in_key) const;
object& operator[](const string_type& in_key);
const object& operator[](index_type in_index) const;
object& operator[](index_type in_index);
/** Accessors */
bool null() const;
size_t size() const;
template<typename T>
bool has() const {
using backing_t = typename is_backing<T>::type;
return std::holds_alternative<backing_t>(m_value);
}
type type() const {
return static_cast<decltype(type::null)>(m_value.index());
}
/** arithmetic types (numbers, bool) */
template<typename T,
typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
T get(T in_default_value = {}) const {
using backing_t = typename is_backing<T>::type;
const backing_t* result = std::get_if<backing_t>(&m_value);
if (result != nullptr) {
return static_cast<T>(*result);
}
return in_default_value;
}
/** strings */
// TODO: support other basic_string types
template<typename T, typename DefaultT = T,
typename std::enable_if<std::is_same<T, string_type>::value && std::is_convertible<typename std::decay<DefaultT>::type, T>::value>::type* = nullptr>
T get(DefaultT&& in_default_value = {}) const {
const string_type* result = std::get_if<string_type>(&m_value);
if (result != nullptr) {
return *result;
}
return std::forward<DefaultT>(in_default_value);
}
// TODO: support other basic_string_view types
template<typename T, typename DefaultT = T,
typename std::enable_if<std::is_same<T, string_type>::value && std::is_same<typename std::decay<DefaultT>::type, string_view_type>::value>::type* = nullptr>
T get(DefaultT&& in_default_value) const {
const string_type* result = std::get_if<string_type>(&m_value);
if (result != nullptr) {
return T{ *result };
}
return { in_default_value.begin(), in_default_value.end() };
}
// TODO: support other basic_string_view types
template<typename T, typename DefaultT = T,
typename std::enable_if<std::is_same<T, string_view_type>::value && std::is_same<typename std::decay<DefaultT>::type, string_view_type>::value>::type* = nullptr>
T get(DefaultT&& in_default_value) const {
const string_type* result = std::get_if<string_type>(&m_value);
if (result != nullptr) {
return T{ *result };
}
return in_default_value;
}
/** arrays */
// reference getter (array_type)
template<typename T,
typename std::enable_if<std::is_same<T, array_type>::value>::type* = nullptr>
const T& get(const T& in_default_value) const {
const array_type* result = std::get_if<array_type>(&m_value);
if (result != nullptr) {
return *result;
}
return in_default_value;
}
// copy getter (array_type)
template<typename T,
typename std::enable_if<std::is_same<T, array_type>::value>::type* = nullptr>
T get(T&& in_default_value = {}) const {
const array_type* result = std::get_if<array_type>(&m_value);
if (result != nullptr) {
return *result;
}
return std::move(in_default_value);
}
// conversion getter (non-array_type)
template<typename T, typename DefaultT = T,
typename std::enable_if<is_sequence_container<T>::value && !std::is_same<T, array_type>::value && std::is_same<typename std::decay<DefaultT>::type, T>::value>::type* = nullptr>
T get(DefaultT&& in_default_value = {}) const {
using backing_t = typename is_sequence_container<T>::type;
const array_type* array = std::get_if<array_type>(&m_value);
if (array != nullptr) {
T result;
// Expand capacity to fit values (if possible)
if constexpr (is_vector<T>::value) {
result.reserve(array->size());
}
// Populate result from array
if constexpr (is_forward_list<T>::value) {
// forward_list
if constexpr (std::is_same<backing_t, class object>::value) {
// forward_list<object>
result.insert_after(result.begin(), array->begin(), array->end());
}
else {
for (auto itr = array->rend(); itr != array->rbegin(); ++itr) {
if (itr->has<backing_t>()) {
result.push_front(itr->get<backing_t>());
}
}
}
}
else if constexpr (is_set<T>::value || is_multiset<T>::value || is_unordered_set<T>::value || is_unordered_multiset<T>::value) {
// set, unordered_set, multiset, unordered_multiset
if constexpr (std::is_same<backing_t, class object>::value) {
// <object>
result.insert(array->begin(), array->end());
}
else {
for (auto& object : *array) {
if (object.has<backing_t>()) {
result.insert(object.get<backing_t>());
}
}
}
}
else {
// vector, list, etc
for (auto& object : *array) {
if constexpr (std::is_same<backing_t, class object>::value) {
// <object>
result.push_back(object);
}
else if (object.has<backing_t>()) {
result.push_back(object.get<backing_t>());
}
}
}
return result;
}
return std::forward<DefaultT>(in_default_value);
}
/** maps */
// TODO: implement in a way that does not require exposing map_type
// reference getter (map_type)
template<typename T,
typename std::enable_if<std::is_same<T, map_type>::value>::type* = nullptr>
const T& get(const T& in_default_value) const {
const map_type* result = std::get_if<map_type>(&m_value);
if (result != nullptr) {
return *result;
}
return in_default_value;
}
// copy getter (map_type)
template<typename T,
typename std::enable_if<std::is_same<T, map_type>::value>::type* = nullptr>
T get(T&& in_default_value = {}) const {
const map_type* result = std::get_if<map_type>(&m_value);
if (result != nullptr) {
return *result;
}
return std::move(in_default_value);
}
// TODO: conversion getter (non-map_type, i.e: unordered_map)
/** set */
// arithmetic types
template<typename T,
typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
void set(T in_value) {
using backing_t = typename is_backing<T>::type;
m_value.emplace<backing_t>(in_value);
}
// string
template<typename T,
typename std::enable_if<std::is_convertible<typename std::decay<T>::type, string_type>::value>::type* = nullptr>
void set(T&& in_value) {
m_value.emplace<string_type>(std::forward<T>(in_value));
}
// string_view
template<typename T,
typename std::enable_if<std::is_same<T, string_view_type>::value>::type* = nullptr>
void set(const T& in_value) {
m_value.emplace<string_type>(in_value.begin(), in_value.end());
}
// array_type
template<typename T,
typename std::enable_if<std::is_same<typename std::decay<T>::type, array_type>::value>::type* = nullptr>
void set(T&& in_value) {
m_value.emplace<array_type>(std::forward<T>(in_value));
}
// is_sequence_container
template<typename T,
typename std::enable_if<is_sequence_container<typename std::decay<T>::type>::value
&& !std::is_same<typename std::decay<T>::type, array_type>::value
&& !std::is_same<typename std::decay<T>::type, std::vector<bool>>::value>::type* = nullptr>
void set(T&& in_value) {
m_value.emplace<array_type>(in_value.begin(), in_value.end());
}
// std::vector<bool>
template<typename T,
typename std::enable_if<std::is_same<typename std::decay<T>::type, std::vector<bool>>::value>::type* = nullptr>
void set(T&& in_value) {
auto& array = m_value.emplace<array_type>();
array.reserve(in_value.size());
for (const auto& item : in_value) {
array.emplace_back(bool{item});
}
}
// object
template<typename T,
typename std::enable_if<std::is_same<typename std::decay<T>::type, object>::value>::type* = nullptr>
void set(T&& in_value) {
operator=(std::forward<T>(in_value));
}
size_t hash() const {
return std::visit([](auto&& value) -> size_t {
using T = typename std::decay<decltype(value)>::type;
if constexpr (std::is_same<T, null_variant_t>::value) {
return 0;
}
else if constexpr (std::is_same<T, array_type>::value) {
size_t result{};
for (auto& obj : value) {
result += obj.hash();
}
return result;
}
else if constexpr (std::is_same<T, map_type>::value) {
size_t result{};
for (auto& pair : value) {
result += std::hash<string_type>{}(pair.first);
}
return result;
}
else if constexpr (std::is_same<T, data_type>::value) {
// TODO: pull this into a separate method
uint64_t hash = 14695981039346656037ULL;
for (auto byte : value) {
hash = hash ^ byte;
hash = hash * 1099511628211ULL;
}
return hash;
}
else {
return std::hash<T>{}(std::forward<decltype(value)>(value));
}
}, m_value);
}
private:
using null_variant_t = void*;
// TODO: consider replacing std::string with std::u8string (for strings) & std::vector<unsigned char> (for data)
// TODO: consider some more generic mechanism for underlying string type, to support utf-16 & utf-32 strings
std::variant<null_variant_t, bool, intmax_t, long double, text_type, data_type, array_type, map_type> m_value;
// TODO: note for future self, just use either first or last element in array_type to hold XML attributes
// OR, have every XML tag objects be a map, with all subobjects being in a "__values" array subobject or such
// For extra syntactical sugar, could have xml_object class extend object w/o additional members to allow arbitrary
// static_cast usage
// This may be a good justification for separate 'xml_config' and 'xml' parsers, as config files are easier to
// represent as a map, whereas an actual xml document is sequenced
}; // object
namespace container {
template<typename ContainerT, typename LeftT, typename RightT,
typename std::enable_if_t<std::is_same_v<ContainerT, object>>* = nullptr>
constexpr void push(ContainerT& inout_container, LeftT&& in_key, RightT&& in_value) {
auto object_type = inout_container.type();
if (object_type == object::type::null || object_type == object::type::map) {
// Push to map if null or map type
inout_container[in_key] = in_value;
}
else if (object_type == object::type::array) {
// Push to back of array if array type
inout_container[inout_container.size()][in_key] = in_value;
}
// else // do nothing; pushing a key/value pair isn't valid here
}
} // namespace container
} // namespace jessilib
namespace std {
template<>
struct hash<jessilib::object> {
using argument_type = jessilib::object;
using result_type = size_t;
result_type operator()(const argument_type& in_object) const noexcept {
return in_object.hash();
}
};
} // namepsace std |
// Coding Train
// Coding Challenge 22 - Julia Set
// https://www.youtube.com/watch?v=fAsaSkmbF5s&list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH&index=25
float angle = 0;
void setup(){
size(640, 320);
colorMode(HSB,1);
}
void draw(){
//float ca = -0.8;
//float cb = 0.156;
//float ca = map(mouseX, 0, width, -1, 1);
//float cb = map(mouseY, 0, height, -1, 1);
float ca = cos(angle*3.213);
float cb = sin(angle);
angle += 0.02;
background(1);
//float w = 5;
float w = abs(sin(angle))*5;
float h = (w * height) / width;
float xmin = -w/2;
float ymin = -h/2;
loadPixels();
int maxiterations = 100;
float xmax = xmin + w;
float ymax = ymin + h;
float dx = (xmax - xmin) / (width);
float dy = (ymax - ymin) / (height);
float y = ymin;
for (int j = 0; j < height; j++){
float x = xmin;
for (int i = 0; i < width; i++){
float a = x;
float b = y;
int n = 0;
while (n < maxiterations){
float aa = a * a;
float bb = b * b;
if (aa + bb > 4.0){
break;
}
float twoab = 2.0 * a * b;
a = aa - bb + ca;
b = twoab + cb;
n++;
}
int pix = (i + j * width);
if (n == maxiterations){
pixels[pix] = color(0);
} else {
float hue = sqrt(float(n)/maxiterations);
pixels[pix] = color(hue, 255, 150);
}
x += dx;
}
y += dy;
}
updatePixels();
println(frameRate);
} |
<template>
<h1>{{title}}</h1>
<br/>
<p>Lasagna con camaroni</p>
<br/>
<!-- Temp refs example -->
<input type="text" ref="name">
<br/>
<button @click="handleClick">Click me</button>
<!-- Modal -->
<teleport to="#modals" v-if="showModal">
<Modal theme="sale" @close="toggleModal">
<template v-slot:links>
<a href="#">Sign up</a>
<a href="#">More info</a>
</template>
<h1>Sign un for the Giveaway</h1>
<p>Grab your comfy clothes for half the price.</p>
</Modal>
</teleport>
<!-- Second Modal -->
<teleport to="#modals" v-if="showSecondModal">
<Modal @close="toggleSecondModal">
<p>Original Price $399.99</p>
<p>Now only $199.99</p>
</Modal>
</teleport>
<!-- Modal btns -->
<button @click.alt="toggleModal">Open Modal (Hold alt)</button>
<button @click="toggleSecondModal">Open Prices</button>
<br/>
</template>
<script>
import Modal from './components/Modal.vue'
// represents the root component of the Vue app
export default {
name: 'App',
components: {
Modal
},
data() {
return {
title: 'My first Vue App',
showModal: false,
showSecondModal: false
}
},
methods: {
// temp refs example
handleClick() {
console.log(this.$refs.name.value)
this.$refs.name.classList.add('active')
this.$refs.name.focus()
},
toggleModal() {
this.showModal = !this.showModal
},
toggleSecondModal() {
this.showSecondModal = !this.showSecondModal
}
}
}
</script>
<style>
#app, #modals {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
h1 {
border-bottom: 1px solid #ddd;
display: inline-block;
padding-bottom: 10px;
}
.active {
border: 1px solid red;
}
</style> |
---
title: Introduction
toc: false
---
<style>
.hero {
display: flex;
flex-direction: column;
align-items: center;
font-family: var(--sans-serif);
margin: 4rem 0 8rem;
text-wrap: balance;
text-align: center;
}
.hero h1 {
margin: 2rem 0;
max-width: none;
font-size: 14vw;
font-weight: 900;
line-height: 1;
background: linear-gradient(30deg, var(--theme-foreground-focus), currentColor);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.hero h2 {
margin: 0;
max-width: 34em;
font-size: 20px;
font-style: initial;
font-weight: 500;
line-height: 1.5;
color: var(--theme-foreground-muted);
}
@media (min-width: 640px) {
.hero h1 {
font-size: 90px;
}
}
</style>
<div class="hero">
<h1>Raided Lost Ark</h1>
</div>
## TL;DR
[Click here to see the charts](https://raided.pro/loa-logs). We rank classes
based on their DPS. The boxes represent a reasonable range for
the typical DPS of each build. Compare classes primarily based on these
boxes, farther right is better. The right whisker provides a reasonable ceiling,
but do not expect most players to reach this. There are many factors we do not
account for such as gear, player skill, and supports.
---
## How to read
In general, you should compare classes based on their box (the colored part), as
that's where a majority of players will fall, in terms of performance. Note that
we do not account for differences in gear outside of ilevel (which means tripods,
gems, elixirs, and transcendence will affect this). Indeed player skill matters
quite a bit. If you would like to compare performance
with more similar gear, you can try to reduce the ilevel ranges in the advanced
options to cut out certain progression systems. Be careful of the low sample
sizes when doing this.
If you would like to look at a "reasonable ceiling" performance for each class,
the right whisker provides a reasonable estimate. Note that this "reasonable ceiling" does not mean
you cannot perform above it, this is exemplified by the stars that show the
literal best performance given the filters.
## Method
We scrape data from [Faust's Lost Ark logs](https://logs.fau.dev/logs) every
night and classify each player in the logs based on their build. We produce
box plots using this data. The boxplots follow the typical procedures. It should
be noted that the whiskers [Q1 - 1.5 * IQR, Q3 + 1.5 * IQR] are truncated to the
minimum and maximum values for that build to guarantee that it represents a
possible value. The line in the middle represents the median and the dot in the
bar represents the mean.
The default filters, in general, seek to provide a representative dataset for on
ilevel players in the typical situations in the current balance patch.
To ensure we do not use data that is not representative of the typical situation,
we classify logs as "Weird" if they do not have the expected number of players (
4 or 8, depending on content), if they have a Princess Gunlancer, if they do not
have the expected number of supports (either none or more than 1 per party), or
if we fail to classify a player's build. Additonally, we filter out players that
were dead when they cleared. These filters are on by default but can be toggled
in the advanced options.
There is no guarantee that we classify builds correctly but we do our best with
the following procedures:
<details>
<summary>Build classification criteria</summary>
Most builds are binary under a class, so if a player doesn't meet the criteria,
they're the other build. All builds (except for Princess Maker) are named after
their main engraving.
- Berserker: Checking for the Mayhem buff
- Destroyer: Checking for the special Gravity Training weapon attack
- Gunlancer: If they do less than 5% damage, they're Princess Maker; if they have Nightmare or Hallucination set they're Combat Readiness
- Paladin: If they do more than 10% of the team damage, they're Judgment.
- Slayer: Checking for the Predator buff
---
- Arcanist: If they did damage with the card Emperor
- Summoner: If they did damage with the skill Kelsion (Communication Overflow)
- Bard: If they do more than 10% of the team damage, they're True Courage
- Sorceress: Checking for the Igniter buff
---
- Wardancer: Checking for Esoteric Skills
- Scrapper: Checking for the unique Shock Training buff
- Soulfist: Checking for the unique Robust Spirit buff
- Glaivier: Checking for the Pinnacle buff
- Striker: Checking for the skill Call of the Wind God (Esoteric Flurry)
- Breaker: Checking for the special Asura weapon attack.
---
- Deathblade: Checking for the unique Remaining Energy Death Trance doing more than 10% damage
- Shadowhunter: Checking for Demonic Impulse buff
- Reaper: Checking for the Lunar Voice buff
- Souleater: Checking for the Soul Snatch buff (Night's Edge)
---
- Sharpshooter: Checking for the Loyal Companion buff
- Deadeye: Checking for the Enhanced Weapon buff
- Artillerist: Checking for the Barrage: Focus Fire skill doing more than 10% damage
- Machinist: Checking for the Evolutionary Legacy buff
- Gunslinger: Checking for Sharpshooter skill (Peacemaker)
---
- Artist: If they do more than 10% of the team damage, they're Recurrence.
- Aeromancer: Checking for the Sunshower synergy buff on their own Sunshower skill (Wind Fury)
</details>
The data scraping is written in Python and the site/visualization is written
with Javascript in the Observable Framework. Data scraping and deployment is
automated through Github Actions and Github Pages. Observable Framework builds
the static files to serve the site with useful features such as responsivity,
interaction, light/dark modes, and mobile layouts. Repos are available for the
[site](https://github.com/evilandrex/raided-loa) and the
[scraper](https://github.com/evilandrex/raided-loa-scraper), contributions are
welcomed.
## Limitations
All data we get is from Faust's fork of Lost Ark Logs. This means that the data
we have is a subset of a subset of a subset. This may not be a perfectly
representative sample of the population.
Build classification (and weird logs classification) may be incorrect as we are
only inferring what we can using simple rules given the available data. Future
improvements to the data source (Faust's logs) may improve accuracy of the
classifications.
Especially for the latest content early in the balance patch cycles, we have
relatively low sample sizes meaning the estimates of performance for uncommon
builds may not be precise. We do not attempt to account for all possible causes
of performance differences, such as tripods, gems, cards, engravings, quality,
elixirs, transcendence, or player skill. Additionally, the support in the party
of each player will largely affect performance. In all, with sufficient sample
size, we should be able to estimate a reasonable range of performance (where the
true median build performance is) given the
variance from factors other than the build itself. However, it is difficult to
determine the exact cause of performance differences without more detailed data.
This means that the data should be used as a rough guide of relative balance and
not an exact representation of the true ranks of each build.
## Acknowledgements
Thanks to Faust for providing the logs and the API. Thanks to Snow for creating
Lost Ark Logs. Thanks to PoisonSandwich and Kennethnyu for inspiration and early
feedback.
[](https://github.com/evilandrex/raided-loa-scraper/actions/workflows/scrape_daily.yml)
[](https://github.com/evilandrex/raided-loa/actions/workflows/deploySite.yml) |
from http import HTTPStatus
from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Path, Query
import app.db.models as db
from app.api.api_v1.dependencies import (
CharacterSearchParameters,
DBSession,
FilterParameters,
ListParameters,
UnicodeBlockQueryParamResolver,
get_session,
)
from app.api.api_v1.dependencies.filter_param_matcher import FilterParameterMatcher
from app.api.api_v1.endpoints.util import get_character_details
from app.api.api_v1.pagination import paginate_search_results
from app.core.config import get_settings
from app.data.cache import cached_data
from app.data.encoding import get_codepoint_string
from app.docs.dependencies.custom_parameters import (
UNICODE_CHAR_STRING_DESCRIPTION,
VERBOSE_DESCRIPTION,
get_description_and_values_table_for_property_group,
)
from app.schemas.enums import CharPropertyGroup
PropertyGroupMatcher = FilterParameterMatcher[CharPropertyGroup]("show_props", CharPropertyGroup)
router = APIRouter()
@router.get(
"",
response_model=db.PaginatedList[db.UnicodeCharacterResponse],
response_model_exclude_unset=True,
)
def list_all_unicode_characters(
db_ctx: Annotated[DBSession, Depends(get_session)],
list_params: Annotated[ListParameters, Depends()],
block: Annotated[UnicodeBlockQueryParamResolver, Depends()],
):
(start, stop) = get_char_list_endpoints(list_params, block)
return {
"url": f"{get_settings().API_VERSION}/characters",
"has_more": stop <= block.finish,
"data": [get_character_details(db_ctx, codepoint, []) for codepoint in range(start, stop)],
}
@router.get(
"/search",
response_model=db.PaginatedSearchResults[db.UnicodeCharacterResult],
response_model_exclude_unset=True,
)
def search_unicode_characters_by_name(
db_ctx: Annotated[DBSession, Depends(get_session)],
search_parameters: Annotated[CharacterSearchParameters, Depends()],
):
response_data = {"url": f"{get_settings().API_VERSION}/characters/search", "query": search_parameters.name}
search_results = cached_data.search_characters_by_name(search_parameters.name, search_parameters.min_score)
return get_paginated_character_list(
db_ctx,
search_results,
[CharPropertyGroup.MINIMUM],
search_parameters.per_page,
search_parameters.page,
response_data,
False,
)
@router.get(
"/filter",
response_model=db.PaginatedSearchResults[db.UnicodeCharacterResponse],
response_model_exclude_unset=True,
)
def filter_unicode_characters(
db_ctx: Annotated[DBSession, Depends(get_session)], filter_parameters: Annotated[FilterParameters, Depends()]
):
response_data = {
"url": f"{get_settings().API_VERSION}/characters/filter",
"filter_settings": filter_parameters.settings,
}
codepoints = db_ctx.filter_all_characters(filter_parameters)
filter_results = [(cp, None) for cp in codepoints]
return get_paginated_character_list(
db_ctx,
filter_results,
filter_parameters.show_props,
filter_parameters.per_page,
filter_parameters.page,
response_data,
filter_parameters.verbose,
)
@router.get(
"/-/{string:path}",
response_model=list[db.UnicodeCharacterResponse],
response_model_exclude_unset=True,
)
def get_unicode_character_details(
db_ctx: Annotated[DBSession, Depends(get_session)],
string: Annotated[str, Path(description=UNICODE_CHAR_STRING_DESCRIPTION)],
show_props: Annotated[
list[str] | None, Query(description=get_description_and_values_table_for_property_group())
] = None,
verbose: Annotated[bool | None, Query(description=VERBOSE_DESCRIPTION)] = None,
):
if show_props:
result = PropertyGroupMatcher.parse_enum_values(show_props)
if result.failure:
raise HTTPException(status_code=int(HTTPStatus.BAD_REQUEST), detail=result.error)
prop_groups = result.value
else:
prop_groups = None
if not verbose:
verbose = False
return [get_character_details(db_ctx, ord(char), prop_groups, verbose=verbose) for char in string]
def get_char_list_endpoints(list_params: ListParameters, block: UnicodeBlockQueryParamResolver) -> tuple[int, int]:
start = block.start
if list_params.starting_after:
start = list_params.starting_after + 1
if list_params.ending_before:
start = list_params.ending_before - list_params.limit
stop = min(block.finish + 1, start + list_params.limit)
if start < block.start or start > stop:
raise HTTPException(
status_code=int(HTTPStatus.BAD_REQUEST),
detail=(
f"The starting codepoint value {get_codepoint_string(start)} is outside the range of characters "
f"{get_codepoint_string(block.start)}...{get_codepoint_string(block.finish)} ({block.name})"
),
)
return (start, stop)
def get_paginated_character_list(
db_ctx: DBSession,
results: list[tuple[int, Any]],
show_props: list[CharPropertyGroup] | None,
per_page: int,
page: int,
response_data: dict[str, str],
verbose: bool,
):
codepoints = [cp for (cp, _) in results]
if codepoints:
result = paginate_search_results(codepoints, per_page, page)
if result.failure:
raise HTTPException(status_code=int(HTTPStatus.BAD_REQUEST), detail=result.error)
paginated = result.value or {}
start = paginated.pop("start", 0)
end = paginated.pop("end", 0)
paginated["results"] = [
get_character_details(db_ctx, cp, show_props, score, verbose) for (cp, score) in results[start:end]
]
return response_data | paginated
return response_data | {
"current_page": 0,
"total_results": 0,
"has_more": False,
"results": [],
} |
**Zadanie 1** Paradygmaty
:white_check_mark: Procedura do generowania 50 losowych liczb od 0 do 100
:white_check_mark: Procedura do sortowania liczb
:white_check_mark: Dodanie parametrów do procedury losującej określającymi zakres losowania: od, do, ile
:white_check_mark: 5 testów jednostkowych testujące procedury
:white_check_mark: Skrypt w bashu do uruchamiania aplikacji w Pascalu via docker
Kod: [lab1](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab1)
Demo: [lab1-demo.zip](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/demos)
**Zadanie 2** Wzorce architektury
:white_check_mark: Należy stworzyć jeden model z kontrolerem z produktami, zgodnie z CRUD
:white_check_mark: Należy stworzyć skrypty do testów endpointów via curl
:white_check_mark: Należy stworzyć dwa dodatkowe kontrolery wraz z modelami
:white_check_mark: Należy stworzyć widoki do wszystkich kontrolerów
:x: Stworzenie panelu administracyjnego z mockowanym logowaniem
Kod: [lab2](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab1)
Demo: [lab2-mw-projobj](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/demos)
**Zadanie 3** Wzorce kreacyjne
:white_check_mark: Należy stworzyć jeden kontroler wraz z danymi wyświetlanymi z listy na endpoint’cie w formacie JSON - Kotlin + Spring Boot
:white_check_mark: Należy stworzyć klasę do autoryzacji (mock) jako Singleton w formie eager
:white_check_mark: Należy obsłużyć dane autoryzacji przekazywane przez użytkownika
:white_check_mark: Należy wstrzyknąć singleton do głównej klasy via @Autowired
:white_check_mark: Obok wersji Eager do wyboru powinna być wersja Singletona w wersji lazy
Kod: [lab3](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab3)
Demo: [lab3-demo](https://github.com/cr0ow/Object-Oriented-Design-2024/assets/70718059/111ba521-069d-419e-b6a1-5da06e8e13f1)
**Zadanie 4** Wzorce strukturalne
:white_check_mark: Należy stworzyć aplikację we frameworki echo w j. Go, która będzie miała kontroler Pogody, która pozwala na pobieranie danych o pogodzie (lub akcjach giełdowych)
:white_check_mark: Należy stworzyć model Pogoda (lub Giełda) wykorzystując gorm, a dane załadować z listy przy uruchomieniu
:white_check_mark: Należy stworzyć klasę proxy, która pobierze dane z serwisu zewnętrznego podczas zapytania do naszego kontrolera
:white_check_mark: Należy zapisać pobrane dane z zewnątrz do bazy danych
:white_check_mark: Należy rozszerzyć endpoint na więcej niż jedną lokalizację (Pogoda), lub akcje (Giełda) zwracając JSONa
Kod: [lab4](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab4)
Demo: [lab4-demo](https://github.com/cr0ow/Object-Oriented-Design-2024/assets/70718059/c250ed21-cae6-4eb1-b124-ca1d91bc1068)
**Zadanie 5** Wzorce behawioralne
:white_check_mark: W ramach projektu należy stworzyć dwa komponenty: Produkty oraz Płatności; Płatności powinny wysyłać do aplikacji serwerowej dane, a w Produktach powinniśmy pobierać dane o produktach z aplikacji serwerowej
:white_check_mark: Należy dodać Koszyk wraz z widokiem; należy wykorzystać routing
:white_check_mark: Dane pomiędzy wszystkimi komponentami powinny być przesyłane za pomocą React hooks
:white_check_mark: Należy dodać skrypt uruchamiający aplikację serwerową oraz kliencką na dockerze via docker-compose
:x: Należy wykorzystać axios’a oraz dodać nagłówki pod CORS
Kod: [lab5](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab5)
Demo: [lab5-demo](https://github.com/cr0ow/Object-Oriented-Design-2024/assets/70718059/2ab69645-2164-404f-9c3e-35c3b018b3e0)
**Zadanie 6** Zapaszki
:white_check_mark: Należy dodać eslint w hookach gita
:white_check_mark: Należy wyeliminować wszystkie bugi w kodzie w Sonarze (kod aplikacji klienckiej)
:white_check_mark: Należy wyeliminować wszystkie zapaszki w kodzie w Sonarze (kod aplikacji klienckiej)
:white_check_mark: Należy wyeliminować wszystkie podatności oraz błędy bezpieczeństwa w kodzie w Sonarze (kod aplikacji klienckiej)
:x: Zredukować duplikaty kodu do 0%
Kod: [lab6](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab6)
Demo: 
**Zadanie 7** Antywzorce
:white_check_mark: Należy stworzyć kontroler wraz z modele Produktów zgodny z CRUD w ORM Fluent
:white_check_mark: Należy stworzyć szablony w Leaf
:white_check_mark: Należy stworzyć drugi model oraz kontroler Kategorii wraz z relacją
:x: Należy wykorzystać Redis do przechowywania danych
:x: Wrzucić aplikację na heroku
Kod: [lab7](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab7)
Demo: [lab7-demo](https://github.com/cr0ow/Object-Oriented-Design-2024/assets/70718059/26349b84-a29b-46b0-adb8-bf0c1932bd43)
**Zadanie 8** Mobile first
:white_check_mark: stworzenie listy kategorii oraz produktów
:white_check_mark: dodać koszyk
:x: stworzyć bazę w Realmie
:x: dodać płatności w Stripe
:x: logowanie i rejestrację via Oauth2 dodać
Kod: [lab8](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab8)
Demo: [lab8-demo](https://github.com/cr0ow/Object-Oriented-Design-2024/assets/70718059/90afb2fd-8384-4f10-88b2-b8508146e3f5)
**Zadanie 9** Testy
:white_check_mark: Należy stworzyć 20 przypadków testowych w CypressJS lub Selenium (Kotlin, Python, Java, JS, Go, Scala)
:white_check_mark: Należy rozszerzyć testy funkcjonalne, aby zawierały minimum 50 asercji
:white_check_mark: Należy stworzyć testy jednostkowe do wybranego wcześniejszego projektu z minimum 50 asercjami
:x: Należy dodać testy API, należy pokryć wszystkie endpointy z minimum jednym scenariuszem negatywnym per endpoint
:x: Należy uruchomić testy funkcjonalne na Browserstacku
Kod: [lab9](https://github.com/cr0ow/Object-Oriented-Design-2024/tree/master/lab9)
Demo: [lab9-demo](https://github.com/cr0ow/Object-Oriented-Design-2024/assets/70718059/4399c594-ed9b-427d-8ec3-221e4c5ff913) |
import * as mongoose from 'mongoose'
import UserModel, {User} from './user'
import GroupModel, {Group} from './group'
import IdeaModel, {Idea} from './idea'
import {RootIdeaType, IdeaType, VoteType} from './_enums'
import chalk from 'chalk'
const connected = chalk.cyan;
const error = chalk.yellow;
const disconnected = chalk.red;
const termination = chalk.magenta;
export {RootIdeaType, IdeaType, VoteType} from './_enums'
export const ObjectId = mongoose.Types.ObjectId;
export type MongoIdType = string | mongoose.Types.ObjectId;
export default class ORM {
private credentials: string;
private verbose: boolean;
private reconnect: boolean;
public connection: mongoose.Connection;
static User = UserModel;
static Group = GroupModel;
static Idea = IdeaModel;
static RootIdeaType = RootIdeaType;
static IdeaType = IdeaType;
static VoteType = VoteType;
constructor (credentials: string, verbose: boolean = false) {
this.credentials = credentials;
this.verbose = verbose;
this.reconnect = true;
this.connection = mongoose.connection;
process.on('SIGINT', () => {
this.reconnect = false;
this.connection.close(() => {
if (this.verbose) console.log(termination('Mongoose default connection is disconnected due to application termination'));
process.exit(0);
});
});
this.connection.on('connected', () => {
if (this.verbose) console.log(connected('Mongoose default connection is open to', this.credentials));
});
this.connection.on('error', (err) => {
if (this.verbose) console.log(error(`Mongoose default connection has occured ${err} error`));
});
this.connection.on('disconnected', async () => {
if (this.verbose) console.log(disconnected('Mongoose default connection is disconnected'));
if (this.reconnect) {
await this.connect();
}
});
}
async connect () {
mongoose.set('useCreateIndex', true); // https://github.com/Automattic/mongoose/issues/6890
const connectPromise = mongoose.connect(this.credentials, {
keepAlive: 300000,
reconnectTries: 3,
useNewUrlParser: true,
});
return await connectPromise;
}
async disconnect () {
this.reconnect = false;
await mongoose.connection.close();
}
} |
// import React, { useState } from 'react';
// import * as S from './styles';
// import Modal from '@mui/material/Modal';
// import Box from '@mui/material/Box';
// import { Typography, TextField } from '@mui/material';
// import { RiAlarmWarningFill } from 'react-icons/ri';
// import { useEffect } from 'react';
// import { useSelector, useDispatch } from 'react-redux/es/exports';
// import apiPath from '../../../api/apiPath';
// import { authAxios } from '../../../api/common';
// import { SET_POSITION } from '../../../reducers/userReducer';
// const SirenModal2 = (props) => {
// // console.log(props.siren)
// // console.log(props)
// const [count, setCount] = useState(5);
// const audio = new Audio('../../../assets/audio/siren.mp3');
// const dispatch = useDispatch();
// const username = useSelector((state) => state.userReducer.user);
// const userContacts = useSelector((state) => state.userReducer.contacts);
// const currentLat = useSelector((state) => state.tmapReducer.latitude);
// const currentLng = useSelector((state) => state.tmapReducer.longitude);
// const position = useSelector((state) => state.userReducer.position);
// const play = () => {
// audio.play();
// };
// const stop = () => {
// audio.stop();
// };
// const getPositionName = async () => {
// const options = {
// method: 'GET',
// headers: { accept: 'application/json', appKey: 'l7xx49e27051d70e475a8285bb568e35a081' },
// };
// await fetch(
// `https://apis.openapi.sk.com/tmap/geo/reversegeocoding?version=1&lat=${currentLat}&lon=${currentLng}&coordType=WGS84GEO&addressType=A02&newAddressExtend=Y`,
// options
// )
// .then((response) => response.json())
// .then((response) => {
// console.log(response);
// dispatch(SET_POSITION(response.addressInfo.fullAddress));
// })
// .catch((err) => console.error(err));
// };
// useEffect(() => {
// if (count === 0) {
// getPositionName();
// if (userContacts.length === 0) alert('비상연락망 1개 이상 등록은 필수 입니다! \n 마이페이지에서 등록하실 수 있습니다 :)');
// else {
// // 문자 API
// authAxios
// .post(apiPath.message.post(), {
// name: username,
// contact: userContacts[0].contact,
// location: position,
// })
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
// }
// props.setSiren(false);
// }
// if (!props.siren) stop();
// play();
// let timer = setInterval(() => {
// setCount(count - 1);
// }, 1000);
// return () => clearInterval(timer);
// }, [count]);
// return (
// <>
// {/* <div style={{position: `absolute`, top:`50px`, left:`50px`, backgroundColor: `blue`, color: `white`}}>
// test
// </div> */}
// <Modal
// open={props.siren}
// onClose={() => props.setSiren(false)}
// aria-labelledby="modal-modal-title"
// aria-describedby="modal-modal-description"
// >
// <Box sx={S.Box}>
// <S.Container>
// <Typography id="modal-modal-title" variant="h6" component="h2">
// <RiAlarmWarningFill size="200" color="red" />
// </Typography>
// <Typography id="modal-modal-description" sx={{ mt: 2 }}>
// {count} 초 후에 문자메시지가 발송됩니다.
// </Typography>
// </S.Container>
// </Box>
// </Modal>
// </>
// );
// };
// export default SirenModal2; |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCardSubscriptionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('card_subscriptions', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('card_id');
$table->timestamps();
$table->unique(['user_id', 'card_id']);
$table->foreign('card_id')
->references('id')
->on('cards')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('card_subscriptions');
}
} |
import { colors } from '@app/constants';
import { CustomButtonProps } from '@app/utils/interface';
import React, { FC } from 'react';
import { TouchableOpacity, Text, Image, ActivityIndicator } from 'react-native';
import styles from './style'
const PrimaryButton: FC<CustomButtonProps> = (props: CustomButtonProps) => {
const {
isLeft,
isRight,
onPress,
imageLeft,
touchablestyle,
textstyle,
imageRight,
title,
imageLeftStyle,
imageRightStyle,
activeopacity,
isdisabled,
onlongpress,
onfocus,
onblur,
isLoading
} = props;
return (
<TouchableOpacity
style={[styles.buttonStyle, touchablestyle]}
onPress={onPress}
activeOpacity={activeopacity}
disabled={isdisabled}
onLongPress={onlongpress}
onFocus={onfocus}
onBlur={onblur}
>
{isLeft &&
<Image source={imageLeft} style={imageLeftStyle} />
}
{!isLoading ?
<Text style={[styles.textstyle, textstyle]}>{title}</Text>
: <ActivityIndicator size="small" color={colors.color_135B2C} />}
{isRight &&
<Image source={imageRight} style={imageRightStyle} />
}
</TouchableOpacity>
);
};
PrimaryButton.defaultProps = {
isLeft: false,
isRight: false,
onPress: () => {
//default function for the onPress
},
touchablestyle: styles.buttonStyle,
textstyle: styles.textstyle,
title: "",
imageLeftStyle: styles.leftimage,
imageRightStyle: styles.rightimage,
activeopacity: 0.8,
isdisabled: false,
onlongpress: () => {
}
};
export default PrimaryButton; |
<section class="layout">
<mat-card class="content-todo-list">
<mat-card-header class="justify-content-center">
<div class="row w-100">
<div class="col-8">
<h1 class="vivify fadeIn">{{currentDate | date: 'EEEE, d'}}</h1>
</div>
<div class="col-4 d-flex justify-content-end actions mat-elevation-z1 vivify popIn">
<button mat-icon-button color="primary" class="pdf" type="button" [disabled]="list.length === 0"
[matTooltip]="list.length === 0 ? '' : 'Descargar PDF'" (click)="exportAsPDF()">
<fa-icon [icon]="pdfIcon"></fa-icon>
</button>
<button mat-icon-button color="primary" class="xlsx" type="button" [disabled]="list.length === 0"
[matTooltip]="list.length === 0 ? '' : 'Descargar XLSX'" (click)="exportAsXLSX()">
<fa-icon [icon]="xlsIcon"></fa-icon>
</button>
</div>
<div class="col-8">
<h3 class="text-body-tertiary vivify fadeIn">{{currentDate | date: 'MMMM'}}</h3>
</div>
<div class="col-4 d-flex justify-content-end">
<h3 class="text-body-tertiary vivify fadeIn"><strong>{{list.length}}</strong> Tareas</h3>
</div>
<form [formGroup]="form" (ngSubmit)="onSubmit();" class="search">
<mat-form-field appearance="outline">
<input matInput type="text" placeholder="Nueva tarea" formControlName="name" maxlength="100" #fieldName autofocus/>
<button mat-mini-fab color="primary" matSuffix class="me-2 vivify popIn" matTooltip="Agregar">
<mat-icon>add</mat-icon>
</button>
</mat-form-field>
</form>
</div>
</mat-card-header>
<mat-card-content>
<mat-list role="list" *ngIf="list.length > 0" id="pdf-data">
<ng-container *ngFor="let item of (list | transformTasks); let index = index;">
<h5 class="list-subtitle">
<mat-icon class="me-2">calendar_month</mat-icon>
{{item.groupName === 'Hoy' ? item.groupName : (item.groupName | date : 'MMMM d, y')}}
</h5>
<mat-list-item
role="listitem" [ngClass]="{'task-ended': task.selected}"
*ngFor="let task of item.tasks;" [matTooltip]="task.selected ? 'Tarea finalizada' : ''">
<mat-icon
[ngClass]="{'selected': task.selected}" matListItemIcon (click)="markAsComplete(task)"
[matTooltip]="!task.selected ? 'Finalizar tarea' : ''">
{{task.selected ? 'check_circle' : 'circle'}}
</mat-icon>
<div matListItemTitle class="d-flex align-items-center">
<p class="w-75 m-0 text-task text-truncate"
[ngClass]="{'text-decoration-line-through text-secondary' : task.selected}">{{task.name}}</p>
<div class="date-delete-content d-flex align-items-center justify-content-end w-25">
<mat-icon class="icon-delete ms-3" (click)="deleteTask(task, index)" matTooltip="Eliminar tarea">delete</mat-icon>
</div>
</div>
</mat-list-item>
</ng-container>
</mat-list>
</mat-card-content>
</mat-card>
</section> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.