text
stringlengths 184
4.48M
|
---|
/**
* Desktop number plugin to lxpanel
*
* Copyright (c) 2008 LxDE Developers, see the file AUTHORS for details.
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// reused dclock.c and variables from pager.c
// 11/23/04 by cmeury
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib/gi18n.h>
#include "panel.h"
#include "misc.h"
#include "plugin.h"
#include "dbg.h"
/* Private context for desktop number plugin. */
typedef struct {
Panel * panel; /* Back pointer to Panel */
GtkWidget * label; /* The label */
int number_of_desktops; /* Number of desktops */
char * * desktop_labels; /* Vector of desktop labels */
gboolean bold; /* User preference: True if bold font */
gboolean wm_labels; /* User preference: True to display window manager labels */
} DesknoPlugin;
static gboolean deskno_name_update(GtkWidget * widget, DesknoPlugin * dc);
static void deskno_redraw(GtkWidget * widget, DesknoPlugin * dc);
static gboolean deskno_button_press_event(GtkWidget * widget, GdkEventButton * event, Plugin * p);
static int deskno_constructor(Plugin * p, char ** fp);
static void deskno_destructor(Plugin * p);
static void deskno_apply_configuration(Plugin * p);
static void deskno_configure(Plugin * p, GtkWindow * parent);
static void deskno_save_configuration(Plugin * p, FILE * fp);
static void deskno_panel_configuration_changed(Plugin * p);
/* Handler for current_desktop event from window manager. */
static gboolean deskno_name_update(GtkWidget * widget, DesknoPlugin * dc)
{
/* Compute and redraw the desktop number. */
int desktop_number = get_net_current_desktop();
if (desktop_number < dc->number_of_desktops)
panel_draw_label_text(dc->panel, dc->label, dc->desktop_labels[desktop_number], dc->bold, TRUE);
return TRUE;
}
/* Handler for desktop_name and number_of_desktops events from window manager.
* Also used on a configuration change to get a full redraw. */
static void deskno_redraw(GtkWidget * widget, DesknoPlugin * dc)
{
/* Get the NET_DESKTOP_NAMES property. */
dc->number_of_desktops = get_net_number_of_desktops();
int number_of_desktop_names;
char * * desktop_names;
desktop_names = get_utf8_property_list(GDK_ROOT_WINDOW(), a_NET_DESKTOP_NAMES, &number_of_desktop_names);
/* Reallocate the vector of labels. */
if (dc->desktop_labels != NULL)
g_strfreev(dc->desktop_labels);
dc->desktop_labels = g_new0(gchar *, dc->number_of_desktops + 1);
/* Loop to copy the desktop names to the vector of labels.
* If there are more desktops than labels, label the extras with a decimal number. */
int i = 0;
if (dc->wm_labels)
for ( ; ((desktop_names != NULL) && (i < MIN(dc->number_of_desktops, number_of_desktop_names))); i++)
dc->desktop_labels[i] = g_strdup(desktop_names[i]);
for ( ; i < dc->number_of_desktops; i++)
dc->desktop_labels[i] = g_strdup_printf("%d", i + 1);
/* Free the property. */
if (desktop_names != NULL)
g_strfreev(desktop_names);
/* Redraw the label. */
deskno_name_update(widget, dc);
}
/* Handler for button-press-event on top level widget. */
static gboolean deskno_button_press_event(GtkWidget * widget, GdkEventButton * event, Plugin * p)
{
/* Standard left-click handling. */
if (plugin_button_press_event(widget, event, p))
return TRUE;
/* Right-click goes to next desktop, wrapping around to first. */
int desknum = get_net_current_desktop();
int desks = get_net_number_of_desktops();
int newdesk = desknum + 1;
if (newdesk >= desks)
newdesk = 0;
/* Ask the window manager to make the new desktop current. */
Xclimsg(GDK_ROOT_WINDOW(), a_NET_CURRENT_DESKTOP, newdesk, 0, 0, 0, 0);
return TRUE;
}
/* Plugin constructor. */
static int deskno_constructor(Plugin * p, char ** fp)
{
/* Allocate plugin context and set into Plugin private data pointer. */
DesknoPlugin * dc = g_new0(DesknoPlugin, 1);
g_return_val_if_fail(dc != NULL, 0);
p->priv = dc;
dc->panel = p->panel;
/* Default parameters. */
dc->wm_labels = TRUE;
/* Load parameters from the configuration file. */
line s;
s.len = 256;
if (fp != NULL)
{
while (lxpanel_get_line(fp, &s) != LINE_BLOCK_END)
{
if (s.type == LINE_NONE)
{
ERR( "deskno: illegal token %s\n", s.str);
return 0;
}
if (s.type == LINE_VAR)
{
if (g_ascii_strcasecmp(s.t[0], "BoldFont") == 0)
dc->bold = str2num(bool_pair, s.t[1], 0);
else if (g_ascii_strcasecmp(s.t[0], "WMLabels") == 0)
dc->wm_labels = str2num(bool_pair, s.t[1], 0);
else
ERR( "deskno: unknown var %s\n", s.t[0]);
}
else
{
ERR( "deskno: illegal in this context %s\n", s.str);
return 0;
}
}
}
/* Allocate top level widget and set into Plugin widget pointer. */
p->pwid = gtk_event_box_new();
gtk_container_set_border_width(GTK_CONTAINER (p->pwid), 1);
/* Allocate label widget and add to top level. */
dc->label = gtk_label_new(NULL);
gtk_container_add(GTK_CONTAINER(p->pwid), dc->label);
/* Connect signals. Note use of window manager event object. */
g_signal_connect(p->pwid, "button_press_event", G_CALLBACK(deskno_button_press_event), p);
g_signal_connect(G_OBJECT(fbev), "current_desktop", G_CALLBACK(deskno_name_update), (gpointer) dc);
g_signal_connect(G_OBJECT(fbev), "desktop_names", G_CALLBACK(deskno_redraw), (gpointer) dc);
g_signal_connect(G_OBJECT(fbev), "number_of_desktops", G_CALLBACK(deskno_redraw), (gpointer) dc);
/* Initialize value and show the widget. */
deskno_redraw(NULL, dc);
gtk_widget_show_all(p->pwid);
return 1;
}
/* Plugin destructor. */
static void deskno_destructor(Plugin * p)
{
DesknoPlugin * dc = (DesknoPlugin *) p->priv;
/* Disconnect signal from window manager event object. */
g_signal_handlers_disconnect_by_func(G_OBJECT(fbev), deskno_name_update, dc);
/* Deallocate all memory. */
if (dc->desktop_labels != NULL)
g_strfreev(dc->desktop_labels);
g_free(dc);
}
/* Callback when the configuration dialog has recorded a configuration change. */
static void deskno_apply_configuration(Plugin * p)
{
DesknoPlugin * dc = (DesknoPlugin *) p->priv;
deskno_redraw(NULL, dc);
}
/* Callback when the configuration dialog is to be shown. */
static void deskno_configure(Plugin * p, GtkWindow * parent)
{
DesknoPlugin * dc = (DesknoPlugin *) p->priv;
GtkWidget * dlg = create_generic_config_dlg(
_(p->class->name),
GTK_WIDGET(parent),
(GSourceFunc) deskno_apply_configuration, (gpointer) p,
_("Bold font"), &dc->bold, CONF_TYPE_BOOL,
_("Display desktop names"), &dc->wm_labels, CONF_TYPE_BOOL,
NULL);
gtk_widget_set_size_request(GTK_WIDGET(dlg), 400, -1); /* Improve geometry */
gtk_window_present(GTK_WINDOW(dlg));
}
/* Callback when the configuration is to be saved. */
static void deskno_save_configuration(Plugin * p, FILE * fp)
{
DesknoPlugin * dc = (DesknoPlugin *) p->priv;
lxpanel_put_int(fp, "BoldFont", dc->bold);
lxpanel_put_int(fp, "WMLabels", dc->wm_labels);
}
/* Callback when panel configuration changes. */
static void deskno_panel_configuration_changed(Plugin * p)
{
DesknoPlugin * dc = (DesknoPlugin *) p->priv;
deskno_name_update(NULL, dc);
}
/* Plugin descriptor. */
PluginClass deskno_plugin_class = {
PLUGINCLASS_VERSIONING,
type : "deskno",
name : N_("Desktop Number / Workspace Name"),
version: "0.6",
description : N_("Display workspace number, by cmeury@users.sf.net"),
constructor : deskno_constructor,
destructor : deskno_destructor,
config : deskno_configure,
save : deskno_save_configuration,
panel_configuration_changed : deskno_panel_configuration_changed
}; |
#!/usr/bin/python3
'''This module contains unit tests for the class City '''
import unittest
from models.base_model import BaseModel
from models.city import City
from models.state import State
class TestCity(unittest.TestCase):
''' Tests the class City '''
def setUp(self):
''' Set up '''
self.city = City()
self.state = State()
def tearDown(self):
''' Tear down '''
del self.city
del self.state
def test_city_creation(self):
''' Tests if city is created and all elements are initialised properly
'''
self.assertIsInstance(self.city, City)
self.assertEqual(self.city.state_id, "")
self.assertEqual(self.city.name, "")
def test_city_assignment(self):
''' Tests if things are assigned properly '''
self.city.state_id = self.state.id
self.city.name = "Zootopia"
self.assertEqual(self.city.state_id, self.state.id)
self.assertEqual(self.city.name, "Zootopia")
if __name__ == "__main__":
unittest.main() |
<?php
/**
* acm : Algae Culture Management (https://github.com/singularfactory/ACM)
* Copyright 2012, Singular Factory <info@singularfactory.com>
*
* This file is part of ACM
*
* ACM 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.
*
* ACM 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 ACM. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2012, Singular Factory <info@singularfactory.com>
* @package ACM.Frontend
* @since 1.0
* @link https://github.com/singularfactory/ACM
* @license GPLv3 License (http://www.gnu.org/licenses/gpl.txt)
*/
/**
* external_strain actions
*
* @package ACM.Frontend
* @subpackage external_strain
* @version 1.2
*/
class external_strainActions extends MyActions {
/**
* Index action
*/
public function executeIndex(sfWebRequest $request) {
// Initiate the pager with default parameters but delay pagination until search criteria has been added
$this->pager = $this->buildPagination($request, 'ExternalStrain', array('init' => false, 'sort_column' => 'id'));
$filters = $this->_processFilterConditions($request, 'external_strain');
$query = null;
// Deal with search criteria
if (count($filters)) {
if (!empty($filters['group_by'])) {
$query = ExternalStrainTable::getInstance()->createQuery($this->mainAlias())->select("{$this->mainAlias()}.*");
$this->groupBy = $filters['group_by'];
if (in_array($this->groupBy, array('transfer_interval', 'is_epitype', 'is_axenic'))) {
$relatedAlias = $this->groupBy;
$relatedForeignKey = $this->groupBy;
$recursive = false;
} else {
$relatedAlias = sfInflector::camelize($this->groupBy);
$relatedForeignKey = sfInflector::foreign_key($this->groupBy);
$recursive = true;
}
$query = $query
->addSelect("COUNT(DISTINCT {$this->mainAlias()}.id) as n_strains")
->groupBy("{$this->mainAlias()}.$relatedForeignKey");
if ($recursive) {
$query = $query->innerJoin("{$this->mainAlias()}.$relatedAlias m");
if (in_array($this->groupBy, array('sample'))) {
$query = $query->addSelect('m.id as value');
} else {
$query = $query->addSelect('m.name as value');
}
} else {
$query = $query->addSelect("{$this->mainAlias()}.$relatedAlias as value");
}
} else {
$query = $this->pager->getQuery();
}
$query = $query
->leftJoin("{$this->mainAlias()}.Sample sa")
->leftJoin("sa.Location loc")
->leftJoin("{$this->mainAlias()}.TaxonomicClass tc")
->leftJoin("{$this->mainAlias()}.Genus g")
->leftJoin("{$this->mainAlias()}.Species s")
->where('1=1');
foreach (array('taxonomic_class_id', 'genus_id', 'species_id', 'authority_id') as $filter) {
if (!empty($filters[$filter])) {
$query = $query->andWhere("{$this->mainAlias()}.$filter = ?", $filters[$filter]);
$table = sprintf('%sTable', sfInflector::camelize(str_replace('_id', '', $filter)));
$table = call_user_func(array($table, 'getInstance'));
$this->filters[$filter] = $table->find($filters[$filter])->getName();
}
}
foreach (array('maintenance_status_id', 'culture_medium_id') as $filter) {
if (!empty($filters[$filter])) {
$intermediateModel = '';
switch ($filter) {
case 'culture_medium_id':
$intermediateModel = 'CultureMedia';
break;
case 'maintenance_status_id':
$intermediateModel = 'MaintenanceStatus';
break;
}
$query = $query->andWhere("{$this->mainAlias()}.ExternalStrain$intermediateModel.{$filter} = ?", $filters[$filter]);
$table = sprintf('%sTable', sfInflector::camelize(str_replace('_id', '', $filter)));
$table = call_user_func(array($table, 'getInstance'));
$this->filters[$filter] = $table->find($filters[$filter])->getName();
}
}
if (!empty($filters['is_epitype']) && $filters['is_epitype'] > 0) {
$this->filters['Epitype'] = ($filters['is_epitype'] == 1) ? 'no' : 'yes';
$query = $query->andWhere("{$this->mainAlias()}.is_epitype = ?", ($filters['is_epitype'] == 1) ? 0 : 1);
}
if (!empty($filters['is_axenic']) && $filters['is_axenic'] > 0) {
$this->filters['Axenic'] = ($filters['is_axenic'] == 1) ? 'no' : 'yes';
$query = $query->andWhere("{$this->mainAlias()}.is_axenic = ?", ($filters['is_axenic'] == 1) ? 0 : 1);
}
if (!empty($filters['transfer_interval'])) {
$this->filters['Transfer interval'] = $filters['transfer_interval'];
$query = $query->andWhere("{$this->mainAlias()}.transfer_interval = ?", $filters['transfer_interval']);
}
if (!empty($filters['id'])) {
$this->filters['Code'] = $filters['id'];
preg_match('/^[Bb]?[Ee]?[Aa]?\s*[Rr]?\s*[Cc]?\s*(\d{1,4})\s*[Bb]?.*$/', $filters['id'], $matches);
$query = $query->andWhere("{$this->mainAlias()}.id = ?", $matches[1]);
}
}
else {
$query = $this->pager->getQuery()
->leftJoin("{$this->mainAlias()}.Sample sa")
->leftJoin("sa.Location loc")
->leftJoin("{$this->mainAlias()}.TaxonomicClass c")
->leftJoin("{$this->mainAlias()}.Genus g")
->leftJoin("{$this->mainAlias()}.Species s");
}
if (empty($filters['group_by'])) {
$this->pager->setQuery($query);
$this->pager->init();
$this->results = $this->pager->getResults();
} else {
$this->results = $query->execute();
}
// Keep track of the last page used in list
$this->getUser()->setAttribute('external_strain.index_page', $request->getParameter('page'));
// Add a form to filter results
$this->form = new ExternalStrainForm(array(), array('search' => true));
}
/**
* Shows a ExternalStrain record
*/
public function executeShow(sfWebRequest $request) {
$this->externalStrain = ExternalStrainTable::getInstance()->find(array($request->getParameter('id')));
$this->forward404Unless($this->externalStrain);
}
/**
* Shows form for creating a new ExternalStrain record
*/
public function executeNew(sfWebRequest $request) {
if ( $lastStrain = $this->getUser()->getAttribute('external_strain.last_object_created') ) {
$externalStrain = new ExternalStrain();
$externalStrain->setKingdomId($lastStrain->getKingdomId());
$externalStrain->setPhylumId($lastStrain->getPhylumd());
$externalStrain->setFamilyId($lastStrain->getFamilyId());
$externalStrain->setTaxonomicClassId($lastStrain->getTaxonomicClassId());
$externalStrain->setTaxonomicOrderId($lastStrain->getTaxonomicOrderId());
$externalStrain->setGenusId($lastStrain->getGenusId());
$externalStrain->setSpeciesId($lastStrain->getSpeciesId());
$externalStrain->setAuthorityId($lastStrain->getAuthorityId());
$externalStrain->setIsolationDate($lastStrain->getIsolationDate());
$externalStrain->setIdentifierId($lastStrain->getIdentifierId());
$externalStrain->setSupervisorId($lastStrain->getSupervisorId());
$externalStrain->setTransferInterval($lastStrain->getTransferInterval());
$externalStrain->setObservation($lastStrain->getObservation());
$externalStrain->setCitations($lastStrain->getCitations());
$externalStrain->setRemarks($lastStrain->getRemarks());
$externalStrain->setDepositorId($lastStrain->getDepositorId());
$this->form = new ExternalStrainForm($externalStrain);
$this->getUser()->setAttribute('external_strain.last_object_created', null);
}
else {
$this->form = new ExternalStrainForm();
}
$this->hasIdentifiers = (IdentifierTable::getInstance()->count() > 0)?true:false;
$this->hasSamples = (SampleTable::getInstance()->count() > 0)?true:false;
$this->hasCultureMedia = (CultureMediumTable::getInstance()->count() > 0)?true:false;
}
/**
* Saves a new ExternalStrain record
*/
public function executeCreate(sfWebRequest $request) {
$this->forward404Unless($request->isMethod(sfRequest::POST));
$this->form = new ExternalStrainForm();
$this->hasIdentifiers = (IdentifierTable::getInstance()->count() > 0)?true:false;
$this->hasSamples = (SampleTable::getInstance()->count() > 0)?true:false;
$this->hasCultureMedia = (CultureMediumTable::getInstance()->count() > 0)?true:false;
$this->processForm($request, $this->form);
$this->setTemplate('new');
}
/**
* Shows form for editing a ExternalStrain record
*/
public function executeEdit(sfWebRequest $request) {
$this->forward404Unless($externalStrain = ExternalStrainTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object strain does not exist (%s).', $request->getParameter('id')));
$this->form = new ExternalStrainForm($externalStrain);
}
/**
* Saves changes in a ExternalStrain record
*/
public function executeUpdate(sfWebRequest $request) {
$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
$this->forward404Unless($externalStrain = ExternalStrainTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object strain does not exist (%s).', $request->getParameter('id')));
$this->form = new ExternalStrainForm($externalStrain);
$this->processForm($request, $this->form);
$this->setTemplate('edit');
}
protected function processForm(sfWebRequest $request, sfForm $form) {
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
// Validate form
if ( $form->isValid() ) {
$flashMessage = null;
$url = null;
$isNew = $form->getObject()->isNew();
$externalStrain = null;
try {
$externalStrain = $form->save();
if ( $request->hasParameter('_save_and_add') ) {
$message = 'Strain created successfully. Now you can add another one';
$url = '@external_strain_new';
// Reuse last object values
$this->getUser()->setAttribute('external_strain.last_object_created', $sample);
}
elseif ( !$isNew ) {
$message = 'Changes saved';
$url = '@external_strain_show?id='.$externalStrain->getId();
}
else {
$message = 'Strain created successfully';
$url = '@external_strain_show?id='.$externalStrain->getId();
}
}
catch (Exception $e) {
$message = $e->getMessage();
}
if ( $externalStrain != null ) {
$this->dispatcher->notify(new sfEvent($this, 'bna_green_house.event_log', array('id' => $externalStrain->getId())));
$this->getUser()->setFlash('notice', $message);
if ( $url !== null ) {
$this->redirect($url);
}
}
}
$this->getUser()->setFlash('notice', 'The information on this strain has some errors you need to fix', false);
}
/**
* Create labels for Strain records
*
* @param sfWebRequest $request Request information
* @return void
*/
public function executeCreateLabel(sfWebRequest $request) {
$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::GET));
if ($request->isMethod(sfRequest::POST)) {
$values = $request->getPostParameters();
$this->labels = ExternalStrainTable::getInstance()->availableExternalStrainsForLabelConfiguration($values);
$this->copies = $values['copies'];
$this->cultureMedium = CultureMediumTable::getInstance()->findOneById($values['culture_medium_id']);
$this->setLayout(false);
$pdf = new WKPDF();
$pdf->set_html($this->getPartial('create_pdf'));
$pdf->set_orientation('Landscape');
$pdf->render();
$pdf->output(WKPDF::$PDF_DOWNLOAD, "research_collection_labels.pdf");
throw new sfStopException();
} else {
$this->getUser()->setAttribute('external_strain_label_configuration', array());
$this->form = new ExternalStrainLabelForm();
$this->form->setWidgets(array(
'supervisor_id' => new sfWidgetFormDoctrineChoice(array(
'model' => 'Supervisor',
'query' => ExternalStrainTable::getInstance()->availableSupervisorsQuery(),
'add_empty' => true,
)),
));
}
}
/**
* Returns the HTML form section of a label field
*
* @param sfWebRequest $request
* @return string HTML content
*/
public function executeGetLabelField(sfWebRequest $request) {
if ($request->isXmlHttpRequest()) {
$div = $request->getParameter('field');
$value = $request->getParameter('value');
$externalStrains = array();
if (empty($div) || empty($value)) {
return sfView::NONE;
}
$labelConfiguration = $this->getUser()->getAttribute('external_strain_label_configuration');
$form = new ExternalStrainLabelForm();
switch ($div) {
case 'transfer_intervals':
$labelConfiguration['supervisor_id'] = $value;
$field = 'transfer_interval';
$form->setWidgets(array(
'transfer_interval' => new sfWidgetFormChoice(array(
'choices' => ExternalStrainTable::getInstance()->availableTransferIntervalChoices($labelConfiguration['supervisor_id']),
))));
break;
case 'genus':
$labelConfiguration['transfer_interval'] = $value;
$field = 'genus_id';
$form->setWidgets(array(
'genus_id' => new sfWidgetFormDoctrineChoice(array(
'model' => 'Genus',
'query' => ExternalStrainTable::getInstance()->availableGenusQuery(
$labelConfiguration['supervisor_id'], $labelConfiguration['transfer_interval']),
'add_empty' => true,
)),
));
break;
case 'axenicity':
$labelConfiguration['genus_id'] = $value;
$field = 'is_axenic';
$form->setWidgets(array('is_axenic' => new sfWidgetFormChoice(array('choices' => ExternalStrainLabelForm::$booleanChoices))));
break;
case 'container':
$labelConfiguration['is_axenic'] = $value;
$field = 'container_id';
$form->setWidgets(array(
'container_id' => new sfWidgetFormDoctrineChoice(array(
'model' => 'Container',
'query' => ExternalStrainTable::getInstance()->availableContainersQuery(
$labelConfiguration['supervisor_id'], $labelConfiguration['transfer_interval'], $labelConfiguration['genus_id'], $labelConfiguration['is_axenic']),
'add_empty' => true,
)),
));
break;
case 'culture_medium':
$labelConfiguration['container_id'] = $value;
$field = 'culture_medium_id';
$form->setWidgets(array(
'culture_medium_id' => new sfWidgetFormDoctrineChoice(array(
'model' => 'CultureMedium',
'query' => ExternalStrainTable::getInstance()->availableCultureMediaQuery(
$labelConfiguration['supervisor_id'], $labelConfiguration['transfer_interval'], $labelConfiguration['genus_id'], $labelConfiguration['is_axenic'], $labelConfiguration['container_id']),
'add_empty' => true,
)),
));
break;
case 'strain':
$labelConfiguration['culture_medium_id'] = $value;
$externalStrains = ExternalStrainTable::getInstance()->availableExternalStrainsForLabelConfiguration($labelConfiguration);
break;
}
$this->getUser()->setAttribute('external_strain_label_configuration', $labelConfiguration);
$this->setLayout(false);
if ($div === 'strain') {
return $this->renderPartial('labelExternalStrains', array('externalStrains' => $externalStrains));
} else {
return $this->renderPartial('labelFieldForm', array('div' => $div, 'field' => $field, 'form' => $form));
}
}
return sfView::NONE;
}
} |
import React, { useState } from 'react';
import { Button, Modal, Box, Input, Typography } from '@mui/material';
import {
ref,
uploadBytes,
getDownloadURL,
listAll,
list,
} from "firebase/storage";
import { storage } from "../../chat/firebase/index";
import { v4 } from "uuid";
import api from '../../api'
import { set } from 'date-fns';
const Modal_foto = (props) => {
const [selectedFile, setSelectedFile] = useState(null);
const [imageUpload, setImageUpload] = useState(null);
const [imageUrls, setImageUrls] = useState([]);
const id = sessionStorage.getItem('id');
const token = sessionStorage.getItem('token');
const handleOpen = () => {
props.setOpen(true);
};
const handleClose = () => {
props.setOpen(false);
};
const handleFileChange = (event) => {
const file = event.target.files[0];
setSelectedFile(file);
};
const handleUpload = () => {
console.log(selectedFile)
// console.log("img upload", imageUpload)
const foto = {
"url":"",
"usuario":{
"idUsuario": id
}
}
const config = {
headers: {
Authorization: `Bearer ${token}`
},
};
const imagesListRef = ref(storage, "images/");
if (selectedFile== null) return;
const imageRef = ref(storage, `images/${selectedFile.name + v4()}`);
console.log(imageRef)
uploadBytes(imageRef, selectedFile).then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
setImageUrls((prev) => [...prev, url]);
console.log(url)
foto.url = url;
api.post("/fotos", foto, config)
window.location.reload();
});
});
// Fechar o modal após o upload
props.setOpen(false);
};
return (
<Modal open={props.open}
onClose={handleClose}>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
height: 200,
bgcolor: 'background.paper',
boxShadow: 24,
p: 4,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center'
}}
>
<Typography variant="h6" component="div">
Selecione uma foto
</Typography>
<Input type="file" onChange={handleFileChange} />
<Box>
<Button variant="contained" onClick={handleUpload} sx={{ backgroundColor: '#FF9200'}}>
Enviar Foto
</Button>
<Button variant='contained' onClick={handleClose} sx={{marginLeft: '20px', backgroundColor: '#FF9200'}}>
fechar
</Button>
</Box>
</Box>
</Modal>
);
};
export default Modal_foto; |
import React, { Component } from "react"
import {
FormControl,
FormLabel,
FormErrorMessage,
Input,
Button,
Heading,
} from '@chakra-ui/react'
import axios from 'axios'
import toast, { Toaster } from 'react-hot-toast'
class RegisterParticipantForm extends Component {
constructor() {
super()
this.state = {
eventInput: '',
participantInput: '',
}
this.resetState = this.resetState.bind(this)
}
handleEventChange = (e) => this.setState({ eventInput: e.target.value})
handleParticipantChange = (e) => this.setState({ participantInput: e.target.value})
resetState = () => this.setState({
eventInput: '',
participantInput: '',
})
render() {
const { eventInput, participantInput } = this.state
const isEventError = eventInput === ''
const isParticipantError = participantInput === ''
const submitDisabled = Boolean(isEventError | isParticipantError)
const handleSubmit = () => {
let apiURL = `http://localhost:3001/api/register-participant?participantId=${participantInput}&eventId=${eventInput}`
axios.put(apiURL)
.then(response => {
this.resetState()
this.props.setEvents(this.props.events.map(e => e.id === response.data.id ? response.data : e))
toast.success("Participant registered successfully")
})
.catch(function (error) {
console.log(error)
toast.error(error.response.data.message)
});
}
return (
<>
<Toaster
position="bottom-right"
reverseOrder={false}
/>
<div>
<Heading>Register Participant</Heading>
<FormControl isInvalid={isEventError}>
<FormLabel>Event UUID</FormLabel>
<Input type='text' value={eventInput} onChange={this.handleEventChange} placeholder="" />
{isEventError &&
<FormErrorMessage>Event UUID is required</FormErrorMessage>
}
</FormControl>
<FormControl isInvalid={isParticipantError}>
<FormLabel>Participant UUID</FormLabel>
<Input type='text' value={participantInput} onChange={this.handleParticipantChange} placeholder="" />
{isParticipantError &&
<FormErrorMessage>Participant UUID is required</FormErrorMessage>
}
</FormControl>
<Button onClick={handleSubmit} isDisabled={submitDisabled}>Submit</Button>
</div>
</>
)
}
} export default RegisterParticipantForm |
import React, { useState, useEffect } from 'react';
const GasPriceTracker = () => {
const [gasPrices, setGasPrices] = useState({
safeGasPrice: null,
proposedGasPrice: null,
fastGasPrice: null,
});
const fetchGasPrices = () => {
const apiKey = 'IV8ZDP33SVEDUJEBV429FUCMXNBS1TZSJZ';
const apiUrl = `https://api.etherscan.io/api?module=gastracker&action=gasoracle&apikey=${apiKey}`;
fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
const { result } = data;
if (result) {
setGasPrices({
safeGasPrice: result.SafeGasPrice,
proposedGasPrice: result.ProposeGasPrice,
fastGasPrice: result.FastGasPrice,
});
}
})
.catch((error) => {
console.error('Error fetching gas prices:', error);
});
};
useEffect(() => {
// Initial fetch
fetchGasPrices();
// 14-second interval to fetch gas prices periodically
const intervalId = setInterval(fetchGasPrices, 14000);
// Clean up the interval when the component unmounts
return () => clearInterval(intervalId);
}, []);
return (
<div>
<h2>Ethereum Gas Prices</h2>
<p>Safe Gas Price: {gasPrices.safeGasPrice} Gwei</p>
<p>Proposed Gas Price: {gasPrices.proposedGasPrice} Gwei</p>
<p>Fast Gas Price: {gasPrices.fastGasPrice} Gwei</p>
</div>
);
};
export default GasPriceTracker; |
const {response, request} = require('express');
const {Producto} = require('../models');
const productosGet = async (req = request, res = response) => {
const {limit = 5, desde = 0} = req.query;
const query = {estado: true};
const [total, productos] = await Promise.all([
Producto.countDocuments(query),
Producto.find(query)
.populate('usuario', 'nombre')
.populate('categoria', 'nombre')
.skip(Number(desde))
.limit(Number(limit))
]);
res.json({
total,
productos
});
}
const productoGetById = async (req, res = response) => {
const {id} = req.params;
const producto = await Producto.findById(id)
.populate('usuario', 'nombre')
.populate('categoria', 'nombre');
res.json({
producto
});
}
const productosPut = async (req, res) => {
const {id} = req.params;
const {estado, usuario, ...data} = req.body;
if (data.nombre) {
data.nombre = data.nombre.toUpperCase();
}
data.usuario = req.usuario._id;
const producto = await Producto.findByIdAndUpdate(id, data, {new: true});
res.json(producto);
}
const productosPost = async (req, res = Response) => {
const {estado, usuario, ...body} = req.body;
const productoDB = await Producto.findOne({nombre: body.nombre});
if (productoDB) {
return res.status(400).json({
msg: `El producto ${productoDB.nombre} ya existe`
});
}
const data = {
...body,
nombre: body.nombre.toUpperCase(),
usuario: req.usuario._id,
}
const producto = new Producto(data);
await producto.save();
res.status(201).json({
producto
});
}
const productosDelete = async (req, res) => {
const {id} = req.params;
const producto = await Producto.findByIdAndUpdate(id, {estado: false}, {new: true});
res.json(producto);
}
module.exports = {
productosGet,
productoGetById,
productosPut,
productosPost,
productosDelete
} |
/*
* Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @modules java.base/java.lang:open
* @enablePreview
* @run testng/othervm test.DefineClassTest
* @summary Basic test for java.lang.invoke.MethodHandles.Lookup.defineClass
*/
package test;
import java.lang.classfile.ClassFile;
import java.lang.constant.ClassDesc;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.AccessFlag;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.testng.annotations.Test;
import static java.lang.classfile.ClassFile.ACC_PUBLIC;
import static java.lang.classfile.ClassFile.ACC_STATIC;
import static java.lang.constant.ConstantDescs.CD_Object;
import static java.lang.constant.ConstantDescs.CLASS_INIT_NAME;
import static java.lang.constant.ConstantDescs.INIT_NAME;
import static java.lang.constant.ConstantDescs.MTD_void;
import static java.lang.invoke.MethodHandles.*;
import static java.lang.invoke.MethodHandles.Lookup.*;
import static org.testng.Assert.*;
public class DefineClassTest {
private static final String THIS_PACKAGE = DefineClassTest.class.getPackageName();
private static final ClassDesc CD_Runnable = Runnable.class.describeConstable().orElseThrow();
private static final ClassDesc CD_MissingSuperClass = ClassDesc.of("MissingSuperClass");
/**
* Test that a class has the same class loader, and is in the same package and
* protection domain, as a lookup class.
*/
void testSameAbode(Class<?> clazz, Class<?> lc) {
assertTrue(clazz.getClassLoader() == lc.getClassLoader());
assertEquals(clazz.getPackageName(), lc.getPackageName());
assertTrue(clazz.getProtectionDomain() == lc.getProtectionDomain());
}
/**
* Tests that a class is discoverable by name using Class.forName and
* lookup.findClass
*/
void testDiscoverable(Class<?> clazz, Lookup lookup) throws Exception {
String cn = clazz.getName();
ClassLoader loader = clazz.getClassLoader();
assertTrue(Class.forName(cn, false, loader) == clazz);
assertTrue(lookup.findClass(cn) == clazz);
}
/**
* Basic test of defineClass to define a class in the same package as test.
*/
@Test
public void testDefineClass() throws Exception {
final String CLASS_NAME = THIS_PACKAGE + ".Foo";
Lookup lookup = lookup();
Class<?> clazz = lookup.defineClass(generateClass(CLASS_NAME));
// test name
assertEquals(clazz.getName(), CLASS_NAME);
// test loader/package/protection-domain
testSameAbode(clazz, lookup.lookupClass());
// test discoverable
testDiscoverable(clazz, lookup);
// attempt defineClass again
try {
lookup.defineClass(generateClass(CLASS_NAME));
assertTrue(false);
} catch (LinkageError expected) { }
}
/**
* Test public/package/protected/private access from class defined with defineClass.
*/
@Test
public void testAccess() throws Exception {
final String THIS_CLASS = this.getClass().getName();
final String CLASS_NAME = THIS_PACKAGE + ".Runner";
Lookup lookup = lookup();
// public
byte[] classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method1");
testInvoke(lookup.defineClass(classBytes));
// package
classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method2");
testInvoke(lookup.defineClass(classBytes));
// protected (same package)
classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method3");
testInvoke(lookup.defineClass(classBytes));
// private
classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method4");
Class<?> clazz = lookup.defineClass(classBytes);
Runnable r = (Runnable) clazz.newInstance();
try {
r.run();
assertTrue(false);
} catch (IllegalAccessError expected) { }
}
public static void method1() { }
static void method2() { }
protected static void method3() { }
private static void method4() { }
void testInvoke(Class<?> clazz) throws Exception {
Object obj = clazz.newInstance();
((Runnable) obj).run();
}
/**
* Test that defineClass does not run the class initializer
*/
@Test
public void testInitializerNotRun() throws Exception {
final String THIS_CLASS = this.getClass().getName();
final String CLASS_NAME = THIS_PACKAGE + ".ClassWithClinit";
byte[] classBytes = generateClassWithInitializer(CLASS_NAME, THIS_CLASS, "fail");
Class<?> clazz = lookup().defineClass(classBytes);
// trigger initializer to run
try {
clazz.newInstance();
assertTrue(false);
} catch (ExceptionInInitializerError e) {
assertTrue(e.getCause() instanceof IllegalCallerException);
}
}
static void fail() { throw new IllegalCallerException(); }
/**
* Test defineClass to define classes in a package containing classes with
* different protection domains.
*/
@Test
public void testTwoProtectionDomains() throws Exception {
Path here = Paths.get("");
// p.C1 in one exploded directory
Path dir1 = Files.createTempDirectory(here, "classes");
Path p = Files.createDirectory(dir1.resolve("p"));
Files.write(p.resolve("C1.class"), generateClass("p.C1"));
URL url1 = dir1.toUri().toURL();
// p.C2 in another exploded directory
Path dir2 = Files.createTempDirectory(here, "classes");
p = Files.createDirectory(dir2.resolve("p"));
Files.write(p.resolve("C2.class"), generateClass("p.C2"));
URL url2 = dir2.toUri().toURL();
// load p.C1 and p.C2
ClassLoader loader = new URLClassLoader(new URL[] { url1, url2 });
Class<?> target1 = Class.forName("p.C1", false, loader);
Class<?> target2 = Class.forName("p.C2", false, loader);
assertTrue(target1.getClassLoader() == loader);
assertTrue(target1.getClassLoader() == loader);
assertNotEquals(target1.getProtectionDomain(), target2.getProtectionDomain());
// protection domain 1
Lookup lookup1 = privateLookupIn(target1, lookup());
Class<?> clazz = lookup1.defineClass(generateClass("p.Foo"));
testSameAbode(clazz, lookup1.lookupClass());
testDiscoverable(clazz, lookup1);
// protection domain 2
Lookup lookup2 = privateLookupIn(target2, lookup());
clazz = lookup2.defineClass(generateClass("p.Bar"));
testSameAbode(clazz, lookup2.lookupClass());
testDiscoverable(clazz, lookup2);
}
/**
* Test defineClass defining a class to the boot loader
*/
@Test
public void testBootLoader() throws Exception {
Lookup lookup = privateLookupIn(Thread.class, lookup());
assertTrue(lookup.getClass().getClassLoader() == null);
Class<?> clazz = lookup.defineClass(generateClass("java.lang.Foo"));
assertEquals(clazz.getName(), "java.lang.Foo");
testSameAbode(clazz, Thread.class);
testDiscoverable(clazz, lookup);
}
@Test(expectedExceptions = { IllegalArgumentException.class })
public void testWrongPackage() throws Exception {
lookup().defineClass(generateClass("other.C"));
}
@Test(expectedExceptions = { IllegalAccessException.class })
public void testNoPackageAccess() throws Exception {
Lookup lookup = lookup().dropLookupMode(PACKAGE);
lookup.defineClass(generateClass(THIS_PACKAGE + ".C"));
}
@Test(expectedExceptions = { ClassFormatError.class })
public void testTruncatedClassFile() throws Exception {
lookup().defineClass(new byte[0]);
}
@Test(expectedExceptions = { NullPointerException.class })
public void testNull() throws Exception {
lookup().defineClass(null);
}
@Test(expectedExceptions = { NoClassDefFoundError.class })
public void testLinking() throws Exception {
lookup().defineClass(generateNonLinkableClass(THIS_PACKAGE + ".NonLinkableClass"));
}
@Test(expectedExceptions = { IllegalArgumentException.class })
public void testModuleInfo() throws Exception {
lookup().defineClass(generateModuleInfo());
}
/**
* Generates a class file with the given class name
*/
byte[] generateClass(String className) {
return ClassFile.of().build(ClassDesc.of(className), clb -> {
clb.withFlags(AccessFlag.PUBLIC, AccessFlag.SUPER);
clb.withSuperclass(CD_Object);
clb.withMethodBody(INIT_NAME, MTD_void, PUBLIC, cob -> {
cob.aload(0);
cob.invokespecial(CD_Object, INIT_NAME, MTD_void);
cob.return_();
});
});
}
/**
* Generate a class file with the given class name. The class implements Runnable
* with a run method to invokestatic the given targetClass/targetMethod.
*/
byte[] generateRunner(String className,
String targetClass,
String targetMethod) throws Exception {
return ClassFile.of().build(ClassDesc.of(className), clb -> {
clb.withSuperclass(CD_Object);
clb.withInterfaceSymbols(CD_Runnable);
clb.withMethodBody(INIT_NAME, MTD_void, PUBLIC, cob -> {
cob.aload(0);
cob.invokespecial(CD_Object, INIT_NAME, MTD_void);
cob.return_();
});
clb.withMethodBody("run", MTD_void, PUBLIC, cob -> {
cob.invokestatic(ClassDesc.of(targetClass), targetMethod, MTD_void);
cob.return_();
});
});
}
/**
* Generate a class file with the given class name. The class will initializer
* to invokestatic the given targetClass/targetMethod.
*/
byte[] generateClassWithInitializer(String className,
String targetClass,
String targetMethod) throws Exception {
return ClassFile.of().build(ClassDesc.of(className), clb -> {
clb.withFlags(AccessFlag.PUBLIC, AccessFlag.SUPER);
clb.withSuperclass(CD_Object);
clb.withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, cob -> {
cob.aload(0);
cob.invokespecial(CD_Object, INIT_NAME, MTD_void);
cob.return_();
});
clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, cob -> {
cob.invokestatic(ClassDesc.of(targetClass), targetMethod, MTD_void);
cob.return_();
});
});
}
/**
* Generates a non-linkable class file with the given class name
*/
byte[] generateNonLinkableClass(String className) {
return ClassFile.of().build(ClassDesc.of(className), clb -> {
clb.withFlags(AccessFlag.PUBLIC, AccessFlag.SUPER);
clb.withSuperclass(CD_MissingSuperClass);
clb.withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, cob -> {
cob.aload(0);
cob.invokespecial(CD_MissingSuperClass, INIT_NAME, MTD_void);
cob.return_();
});
});
}
/**
* Generates a class file with the given class name
*/
byte[] generateModuleInfo() {
return ClassFile.of().build(ClassDesc.of("module-info"), cb -> cb.withFlags(AccessFlag.MODULE));
}
private int nextNumber() {
return ++nextNumber;
}
private int nextNumber;
} |
import { RefObject, useEffect } from "react";
export const useClickOutside = (ref: RefObject<HTMLElement>, callback: () => void) => {
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as HTMLElement)) {
callback();
}
};
// delay the subscription to click events to avoid triggering the callback on mount
// fixed by Dan Abramov: https://github.com/facebook/react/issues/24657#issuecomment-1150119055
const timeoutId = setTimeout(() => {
document.addEventListener("click", handleClick, false);
}, 0);
return () => {
clearTimeout(timeoutId);
document.removeEventListener("click", handleClick, false);
};
}, [callback, ref]);
}; |
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import LocizeBackend from 'i18next-locize-backend';
const LOCIZE_PROJECT_ID = process.env.LOCIZE_PROJECT_ID;
const LOCIZE_API_KEY = process.env.LOCIZE_API_KEY;
export const initI18n = () => {
// taken from:
// https://github.com/locize/react-tutorial/blob/main/step_2/src/i18n.js
i18n
// i18next-locize-backend
// loads translations from your project, saves new keys to it (saveMissing: true)
// https://github.com/locize/i18next-locize-backend
.use(LocizeBackend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
lng: 'en',
fallbackLng: 'en',
saveMissing: true,
// keySeparator: false,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
backend: {
projectId: LOCIZE_PROJECT_ID,
apiKey: LOCIZE_API_KEY,
referenceLng: 'en',
},
});
};
initI18n(); |
// ********* Imports *******************************************/
require("dotenv").config(); // Load environment variables from .env file
const sessionSecret = process.env.SESSION_SECRET;
const express = require("express");
const session = require("express-session");
const path = require("path"); // gives access to the path module
const app = express(); // call express function to start new Express application
const { StatusCodes, getReasonPhrase } = require("http-status-codes");
// routes imports
const userRoutes = require("./routes/user.routes");
const productRoutes = require("./routes/product.routes");
// *********** CORS Authorization ********************************/
// Middleware that allows cross-origin requests
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content, Accept, Content-Type, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
next();
});
// *********** Session ***************************************/
// Middleware that creates a session object in the request object
app.use(
session({
secret: sessionSecret, // Secret used to sign the session ID cookie
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't save empty sessions
// cookie: { secure: true }, //! cookie settings: secure: true for https -> disabled in dev environment
})
);
app.use(express.json()); // parse incoming requests with JSON payloads
// ********* Mongoose DB connexion ***********************************/
const mongodbCredendials = process.env.MONGODB_CREDENTIALS;
const mongoose = require("mongoose");
mongoose
.connect(mongodbCredendials, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Succesfully connected to MongoDB"))
.catch(() => console.log("Connection to MongoDB failed !", error));
// ******** Routes *********************************************/
app.use("/users", userRoutes);
app.use("/products", productRoutes);
// ****** Error handling ****************************************/
app.use((req, res) => {
res
.status(StatusCodes.NOT_FOUND)
.send({ error: getReasonPhrase(StatusCodes.NOT_FOUND) });
});
// error handling for async functions in controllers ("err" comes first to catch errors coming from the catchAsync function)
app.use((err, req, res, next) => {
console.log(err);
res
.status(StatusCodes.INTERNAL_SERVER_ERROR)
.send({ error: getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR) });
});
// ******* Port ************************************************/
// normalize port number
const normalizePort = (val) => {
const port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false;
};
const port = normalizePort(process.env.PORT || 3000); // port number
//******* Listening to port 3000 ******************************/
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
}); |
import 'package:dartz/dartz.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_frontend/domain/core/value_objects.dart';
import 'package:flutter_frontend/domain/event/event.dart';
import 'package:flutter_frontend/presentation/pages/core/widgets/Post/unscrollable_post_container.dart';
import 'package:flutter_frontend/presentation/pages/core/widgets/animations/LoadingEventsAnimation.dart';
import 'package:flutter_frontend/presentation/pages/core/widgets/error_message.dart';
import 'package:flutter_frontend/presentation/pages/core/widgets/loading_overlay.dart';
import 'package:flutter_frontend/presentation/pages/core/widgets/styling_widgets.dart';
import '../../pages/core/widgets/Post/write_widget/write_widget.dart';
import 'cubit/post_screen_cubit.dart';
class PostsScreen extends StatelessWidget {
final Event event;
const PostsScreen({Key? key, required this.event});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => PostScreenCubit(event: event),
child: BlocBuilder<PostScreenCubit, PostScreenState>(
builder: (context, state) {
return BasicContentContainer(
scrollable: true,
child_ren: left(state.maybeMap(
/// if the error state is not active, load the contents
error: (errState) => [ErrorMessage(errorText: errState.error)],
loaded: (loadedState) => [
WriteWidget(
changeImages: context.read<PostScreenCubit>().changePictures,
onSubmit: (content) {
context.read<PostScreenCubit>().postPost(content, event.id.value.toString());
}),
UnscrollablePostContainer(event: event, posts: loadedState.posts, showAuthor: true),
],
orElse: () => [
SizedBox(
child: LoadingEventsAnimation(), height: MediaQuery.of(context).size.height*.8,)
]
)),
);
},
),
);
}
} |
import {Card, CardContent, CardActions, Typography, Button} from "@mui/material"
import {useDispatch, useSelector} from "react-redux"
import { setSelectedPokemon } from "../redux/pokemonSlice";
const PokemonInfo = () =>
{
const selectedPokemon = useSelector((state)=> state.pokemon.selectedPokemon) ;
const dispatch = useDispatch();
return selectedPokemon && (
<Card sx={{heigh: 340, minWidth: 200, display:'flex', flexDirection:"column", justifyContent: 'center', alignItems:"center"}}>
<CardContent>
<Typography variant="h5" gutterBottom>{selectedPokemon.name.english}</Typography>
{Object.keys(selectedPokemon.base).map((key) =>
<Typography key={key}> {key}: {selectedPokemon.base[key]}</Typography>
)}
</CardContent>
<CardActions>
<Button variant="contained" color="secondary" onClick={() => dispatch(
setSelectedPokemon(null))}>Dimiss
</Button>
</CardActions>
</Card>
)
}
export default PokemonInfo |
---
title: Marker Interface
category: Structural
language: es
tag:
- Decoupling
---
## Propósito
Utilización de interfaces vacías como marcadores para distinguir objetos con un tratamiento especial.
## Diagrama de clases

## Aplicabilidad
Utilice el patrón de interfaz de marcador cuando
* Desea identificar los objetos especiales de los objetos normales (para tratarlos de forma diferente)
* Desea indicar que un objeto está disponible para cierto tipo de operaciones.
## Ejemplos del mundo real
* [javase.8.docs.api.java.io.Serializable](https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html)
* [javase.8.docs.api.java.lang.Cloneable](https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html)
## Créditos
* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) |
create or replace PROCEDURE SP_HOSPITAL_ACTUALIZAR
--Definicion de los parametros de entrada
(sp_idHospital IN Hospital.idHospital%TYPE,
sp_idSede IN Hospital.idSede%TYPE,
sp_idDistrito IN Hospital.idDistrito%TYPE,
sp_idGerente IN Hospital.idGerente%TYPE,
sp_idCondicion IN Hospital.idCondicion%TYPE)
IS
--Declaracion de cursores
cursor c_sede is select descSede from Sede where idSede = sp_idSede;
cursor c_gerente is select descGerente from Gerente where idGerente = sp_idGerente;
cursor c_distrito is select descDistrito from Distrito where idDistrito = sp_idDistrito;
cursor c_condicion is select descCondicion from Condicion where idCondicion = sp_idCondicion;
--Declaracion de variables de asignacion
v_descSede Sede.descSede%TYPE;
v_descGerente Gerente.descGerente%TYPE;
v_descDistrito Distrito.descDistrito%TYPE;
v_descCondicion Condicion.descCondicion%TYPE;
v_count NUMBER;
v_idGerente Hospital.idGerente%TYPE;
v_nombreGerente Hospital.nombre%TYPE;
BEGIN
-- Validar si se está modificando el idGerente
SELECT idGerente,nombre INTO v_idGerente,v_nombreGerente FROM Hospital WHERE idHospital = sp_idHospital;
--Existencia de valor unico Gerente
IF sp_idGerente != v_idGerente THEN
SELECT COUNT(*) INTO v_count FROM Hospital WHERE idGerente = sp_idGerente;
IF v_count > 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'El Gerente ya está siendo utilizado por otro hospital');
END IF;
END IF;
--Validacion de existencia de datos por bloques
BEGIN
SELECT descSede INTO v_descSede FROM Sede WHERE idSede = sp_idSede;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20002, 'Sede no encontrada');
END;
BEGIN
SELECT descGerente INTO v_descGerente FROM Gerente WHERE idGerente = sp_idGerente;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20002, 'Gerente no encontrado');
END;
BEGIN
SELECT descDistrito INTO v_descDistrito FROM Distrito WHERE idDistrito = sp_idDistrito;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20002, 'Distrito no encontrado');
END;
BEGIN
SELECT descCondicion INTO v_descCondicion FROM Condicion WHERE idCondicion = sp_idCondicion;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20002, 'Condición no encontrada');
END;
-- Actualizar el registro del hospital
UPDATE Hospital
SET idSede = sp_idSede,
idDistrito = sp_idDistrito,
idGerente = sp_idGerente,
idCondicion = sp_idCondicion
WHERE idHospital= sp_idHospital;
-- Verificar si se realizó la actualización
IF SQL%ROWCOUNT = 1 THEN
DBMS_OUTPUT.PUT_LINE( v_nombreGerente ||' actualizado exitosamente');
ELSE
DBMS_OUTPUT.PUT_LINE('No se encontró ningún hospital con el ID proporcionado');
END IF;
--Recorrido de Cursores para mostrar resultados
for f_sede in c_sede loop
dbms_output.put_line('Sede : ' || f_sede.descSede);
end loop;
for f_gerente in c_gerente loop
dbms_output.put_line('Gerente : ' || f_gerente.descGerente);
end loop;
for f_distrito in c_distrito loop
dbms_output.put_line('Distrito: ' || f_distrito.descDistrito);
end loop;
for f_condicion in c_condicion loop
dbms_output.put_line('Valor recuperado: ' || f_condicion.descCondicion);
end loop;
--Caputar exception no validado anteriormente
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20002, 'ID Hospital no encontrada');
RAISE;
END ; |
class FindAccountModel {
int? _subId;
int? _custId;
String? _typeOfService;
String? _plan;
String? _serviceNumber;
bool? _active;
int? _idType;
String? _idNumber;
String? _name;
String? _phone;
String? _account;
String? _address;
String? _provinceName;
String? _districtName;
String? _precinctName;
String? _province;
String? _district;
String? _precinct;
FindAccountModel();
FindAccountModel.fromJson(Map<String, dynamic> json) {
_subId = json['subId'];
_custId = json['custId'];
_typeOfService = json['typeOfService'];
_plan = json['plan'];
_serviceNumber = json['serviceNumber'];
_active = json['active'];
_idType = json['idType'];
_idNumber = json['idNumber'];
_name = json['name'];
_phone = json['phone'];
_account = json['account'];
_address = json['address'];
_provinceName = json['provinceName'];
_districtName = json['districtName'];
_precinctName = json['precinctName'];
_province = json['province'];
_district = json['district'];
_precinct = json['precinct'];
}
int get subId {
return _subId ?? 0;
}
int get custId {
return _custId ?? 0;
}
String get typeOfService {
return _typeOfService ?? '---';
}
String get plan {
return _plan ?? '---';
}
String get serviceNumber {
return _serviceNumber ?? '---';
}
bool get active {
return _active ?? false;
}
int get idType {
return _idType ?? 0;
}
String get idNumber {
return _idNumber ?? '---';
}
String get name {
return _name ?? '---';
}
String get phone {
return _phone ?? '---';
}
String get account {
return _account ?? '---';
}
String get address {
return _address ?? '---';
}
String get precinct => _precinct ?? "";
String get district => _district ?? "";
String get province => _province ?? "";
String get provinceName => _provinceName ?? "";
String get districtName => _districtName ?? "";
String get precinctName => _precinctName ?? "";
String getInstalAddress() {
return "$precinctName, $districtName, $provinceName";
}
} |
---
uid: mvc/overview/older-versions-1/security/authenticating-users-with-forms-authentication-vb
title: Ověřování uživatelů pomocí ověřování pomocí formulářů (VB) | Dokumenty společnosti Microsoft
author: rick-anderson
description: Přečtěte si, jak používat atribut [Authorize] k ochraně určitých stránek heslem v aplikaci MVC. Naučíte se, jak používat webové stránky správy příliš ...
ms.author: riande
ms.date: 01/27/2009
ms.assetid: 4341f5b1-6fe5-44c5-8b8a-18fa84f80177
msc.legacyurl: /mvc/overview/older-versions-1/security/authenticating-users-with-forms-authentication-vb
msc.type: authoredcontent
ms.openlocfilehash: 9e3117af55db2effed20b6421c2322f1c265f1c7
ms.sourcegitcommit: 022f79dbc1350e0c6ffaa1e7e7c6e850cdabf9af
ms.translationtype: MT
ms.contentlocale: cs-CZ
ms.lasthandoff: 04/17/2020
ms.locfileid: "81540815"
---
# <a name="authenticating-users-with-forms-authentication-vb"></a>Ověřování uživatelů pomocí formulářů (VB)
podle [společnosti Microsoft](https://github.com/microsoft)
> Přečtěte si, jak používat atribut [Authorize] k ochraně určitých stránek heslem v aplikaci MVC. Dozvíte se, jak pomocí Nástroje pro správu webu vytvářet a spravovat uživatele a role. Dozvíte se také, jak nakonfigurovat, kde jsou uloženy informace o uživatelském účtu a roli.
Cílem tohoto kurzu je vysvětlit, jak můžete pomocí ověřování pomocí formulářů chránit zobrazení v aplikacích ASP.NET MVC. Dozvíte se, jak pomocí Nástroje pro správu webu vytvářet uživatele a role. Dozvíte se také, jak zabránit neoprávněným uživatelům v vyvolání akcí řadiče. Nakonec se dozvíte, jak nakonfigurovat, kde jsou uložena uživatelská jména a hesla.
#### <a name="using-the-web-site-administration-tool"></a>Použití Nástroje pro správu webu
Než budeme dělat něco jiného, měli bychom začít tím, že vytvoří některé uživatele a role. Nejjednodušší způsob, jak vytvořit nové uživatele a role, je využít výhod nástroje pro správu webu sady Visual Studio 2008. Tento nástroj můžete spustit výběrem možnosti nabídky **Projekt, ASP.NET Konfigurace**. Případně můžete spustit Nástroj pro správu webu kliknutím na (poněkud děsivou) ikonu kladiva, která zasáhne svět, který se zobrazí v horní části okna Průzkumníka řešení (viz obrázek 1).
**Obrázek 1 – Spuštění nástroje pro správu webu**

V nástroji pro správu webu vytvoříte nové uživatele a role výběrem karty Zabezpečení. Klepnutím na odkaz **Vytvořit uživatele** vytvoříte nového uživatele s názvem Stephen (viz obrázek 2). Zadejte uživateli Stephen libovolné heslo, které chcete (například *tajné).*
**Obrázek 2 – Vytvoření nového uživatele**

Nové role vytvoříte tak, že nejprve povolíte role a definujete jednu nebo více rolí. Povolte role kliknutím na odkaz **Povolit role.** Dále vytvořte roli s názvem *Správci* kliknutím na odkaz **Vytvořit nebo spravovat role** (viz obrázek 3).
**Obrázek 3 – Vytvoření nové role**

Nakonec vytvořte nového uživatele s názvem Sally a přidružte Sally k roli Administrators klepnutím na odkaz Vytvořit uživatele a výběrem správců při vytváření Sally (viz obrázek 4).
**Obrázek 4 – Přidání uživatele do role**

Když je vše řečeno a vykonáno, měli byste mít dva nové uživatele jménem Stephen a Sally. Měli byste mít také novou roli s názvem Správci. Sally je členem role Administrators a Stephen není.
#### <a name="requiring-authorization"></a>Vyžadování autorizace
Můžete vyžadovat, aby byl uživatel ověřen dříve, než uživatel vyvolá akci kontroleru přidáním atributu [Authorize] k akci. Atribut [Authorize] můžete použít na jednotlivé akce řadiče nebo můžete použít tento atribut pro celou třídu kontroleru.
Například řadič v Listing 1 zpřístupňuje akci s názvem CompanySecrets(). Vzhledem k tomu, že tato akce je dekorována atributem [Authorize], nelze tuto akci vyvolat, pokud není ověřen uživatel.
**Výpis 1 – Řadiče\HomeController.vb**
[!code-vb[Main](authenticating-users-with-forms-authentication-vb/samples/sample1.vb)]
Pokud vyvoláte akci CompanySecrets() zadáním adresy URL /Home/CompanySecrets do adresního řádku prohlížeče a nejste ověřeným uživatelem, budete automaticky přesměrováni do zobrazení Přihlášení (viz obrázek 5).
**Obrázek 5 – Zobrazení přihlášení**

Pomocí zobrazení Přihlášení můžete zadat své uživatelské jméno a heslo. Pokud nejste registrovaným uživatelem, můžete kliknutím na odkaz **registru** přejít do zobrazení Registr (viz obrázek 6). Pomocí zobrazení Registr můžete vytvořit nový uživatelský účet.
**Obrázek 6 – Zobrazení registru**

Po úspěšném přihlášení se zobrazí zobrazení CompanySecrets (viz obrázek 7). Ve výchozím nastavení budete nadále přihlášeni, dokud nezavřete okno prohlížeče.
**Obrázek 7 – Zobrazení CompanySecrets**

#### <a name="authorizing-by-user-name-or-user-role"></a>Autorizace podle uživatelského jména nebo uživatelské role
Atribut [Authorize] můžete použít k omezení přístupu k akci kontroleru na určitou sadu uživatelů nebo určitou sadu uživatelských rolí. Například upravený domácí řadič v seznamu 2 obsahuje dvě nové akce s názvem StephenSecrets() a AdministratorSecrets().
**Výpis 2 – Řadiče\HomeController.vb**
[!code-vb[Main](authenticating-users-with-forms-authentication-vb/samples/sample2.vb)]
Pouze uživatel s uživatelským jménem Stephen může vyvolat StephenSecrets() akce. Všichni ostatní uživatelé budou přesměrováni do zobrazení Přihlášení. Vlastnost Users přijímá seznam názvů uživatelských účtů oddělených čárkami.
Akci AdministratorSecrets() mohou vyvolat pouze uživatelé v roli Administrators. Například protože Sally je členem skupiny Administrators, může vyvolat akci AdministratorSecrets(). Všichni ostatní uživatelé budou přesměrováni do zobrazení Přihlášení. Vlastnost Role přijímá seznam názvů rolí oddělený chod čárek.
#### <a name="configuring-authentication"></a>Konfigurace ověřování
V tomto okamžiku se možná divíte, kde jsou uloženy informace o uživatelském účtu a roli. Ve výchozím nastavení jsou informace uloženy v databázi (RANU) SQL Express s názvem ASPNETDB.mdf umístěné ve složce Data aplikací\_aplikace MVC. Tato databáze je generována ASP.NET rámci automaticky při spuštění členství.
Chcete-li zobrazit databázi ASPNETDB.mdf v okně Průzkumník řešení, musíte nejprve vybrat možnost nabídky Projekt, Zobrazit všechny soubory.
Použití výchozí databáze SQL Express je v pořádku při vývoji aplikace. S největší pravděpodobností však nebudete chtít použít výchozí databázi ASPNETDB.mdf pro produkční aplikaci. V takovém případě můžete změnit, kde jsou uloženy informace o uživatelském účtu, provedením následujících dvou kroků:
1. Přidání databázových objektů aplikačních služeb do produkční databáze – Změňte připojovací řetězec aplikace tak, aby přectol na produkční databázi.
Prvním krokem je přidání všech potřebných databázových objektů (tabulek a uložených procedur) do produkční databáze. Nejjednodušší způsob, jak přidat tyto objekty do nové databáze, je využít ASP.NET Průvodce instalací serveru SQL Server (viz obrázek 8). Tento nástroj můžete spustit otevřením příkazového řádku sady Visual Studio 2008 ze skupiny programů sady Microsoft Visual Studio 2008 a spuštěním následujícího příkazu z příkazového řádku:
aspnet\_regsql
**Obrázek 8 – Průvodce instalací serveru ASP.NET SQL Server**

Průvodce instalací serveru ASP.NET SQL Server umožňuje vybrat databázi serveru SQL Server v síti a nainstalovat všechny databázové objekty vyžadované ASP.NET aplikačními službami. Databázový server nemusí být umístěn v místním počítači.
> [!NOTE]
> Pokud nechcete používat Průvodce instalací ASP.NET serveru SQL Server, můžete najít skripty SQL pro přidání databázových objektů aplikačních služeb v následující složce:
>
>
> C:\Windows\Microsoft.NET\Framework\v2.0.50727
Po vytvoření potřebných databázových objektů je třeba upravit připojení databáze používané aplikací MVC. Upravte připojovací řetězec ApplicationServices ve webové konfiguraci (web.config) souboru tak, aby odkazuje na produkční databázi. Například upravené připojení v Výpis 3 odkazuje na databázi s názvem MyProductionDB (původní applicationservices připojovací řetězec byl zakomentován).
**Výpis 3 - Web.config**
[!code-xml[Main](authenticating-users-with-forms-authentication-vb/samples/sample3.xml)]
#### <a name="configuring-database-permissions"></a>Konfigurace oprávnění databáze
Pokud používáte integrované zabezpečení pro připojení k databázi, pak budete muset přidat správný uživatelský účet systému Windows jako přihlášení do databáze. Správný účet závisí na tom, zda jako webový server používáte ASP.NET Development Server nebo Internetovou informační službu. Správný uživatelský účet také závisí na operačním systému.
Pokud používáte ASP.NET Development Server (výchozí webový server používaný aplikací Visual Studio), aplikace se spustí v kontextu uživatelského účtu systému Windows. V takovém případě je třeba přidat uživatelský účet systému Windows jako přihlášení databázového serveru.
Pokud používáte Internetovou informační službu, je třeba přidat buď účet ASPNET, nebo účet NT AUTHORITY/NETWORK SERVICE jako přihlášení k databázovému serveru. Pokud používáte systém Windows XP, přidejte účet ASPNET jako přihlášení do databáze. Pokud používáte novější operační systém, například Windows Vista nebo Windows Server 2008, přidejte jako přihlášení do databáze účet NT AUTHORITY/NETWORK SERVICE.
Nový uživatelský účet můžete do databáze přidat pomocí aplikace Microsoft SQL Server Management Studio (viz obrázek 9).
**Obrázek 9 – Vytvoření nového přihlášení k serveru Microsoft SQL Server**

Po vytvoření požadované přihlášení, je třeba mapovat přihlášení do databáze uživatele s správné databázové role. Poklepejte na přihlášení a vyberte kartu Mapování uživatelů. Chcete-li například ověřit uživatele, musíte povolit\_databázovou roli aspnet Membership\_BasicAccess. Chcete-li vytvořit nové uživatele, je třeba\_povolit roli databáze Aspnet Membership\_FullAccess (viz obrázek 10).
**Obrázek 10 – Přidání rolí databáze aplikačních služeb**

#### <a name="summary"></a>Souhrn
V tomto kurzu jste se naučili používat ověřování pomocí formulářů při vytváření ASP.NET aplikace MVC. Nejprve jste se naučili vytvářet nové uživatele a role využitím nástroje pro správu webu. Dále jste se dozvěděli, jak pomocí atributu [Authorize] zabránit neoprávněným uživatelům v vyvolání akcí řadiče. Nakonec jste se dozvěděli, jak nakonfigurovat aplikaci MVC pro ukládání informací o uživatelích a rolích v produkční databázi.
> [!div class="step-by-step"]
> [Předchozí](preventing-javascript-injection-attacks-cs.md)
> [další](authenticating-users-with-windows-authentication-vb.md) |
package Algorithms;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
/**
* Created by Omeprazole on 2017/6/21.
*/
public class primeMST implements MST {
private boolean[] marked;
private Edge[] edgeTo;
private double[] distTo;
private TreeMap<Integer,Double> pq;
public primeMST(EdgeWeightedGraph G) {
marked = new boolean[G.V()];
edgeTo = new Edge[G.V()];
distTo = new double[G.V()];
pq = new TreeMap<Integer,Double>(
new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(pq.get(o1)>pq.get(o2)){
return 1;
}else if(pq.get(o1)<pq.get(o2)){
return -1;
}else{
return 0;
}
}
}
);
for(int i = 0;i<G.V();i++){
distTo[i] = Double.POSITIVE_INFINITY;
}
distTo[0] = 0;
pq.put(0,0.0);
while(!pq.isEmpty())
visit(G,pq.firstKey());
}
private void visit(EdgeWeightedGraph G,int v){
marked[v] = true;
for(Edge e : G.adj(v)){
int w = e.other(v);
if(marked[w]) continue;
if(e.getWeight()<distTo[w]){
distTo[w] = e.getWeight();
edgeTo[w] = e;
pq.put(w,distTo[w]);
}
}
}
@Override
public Iterable<Edge> edges(){
LinkedList<Edge> res = new LinkedList<>();
for(Edge e:edgeTo){
res.push(e);
}
return res;
}
@Override
public double weight(){
double weight = 0.0;
for(Edge e:edgeTo){
weight+=e.getWeight();
}
return weight;
}
public static void main(String[] args) {
String fileName = "data/tinyEWG.txt";
try{
InputStream in = new FileInputStream(new File(fileName));
Scanner scanner = new Scanner(in);
EdgeWeightedGraph G = new EdgeWeightedGraph(scanner);
primeMST mst = new primeMST(G);
System.out.print(mst.weight());
}catch (Exception e){
e.printStackTrace();
}
}
} |
import atexit
import base64
import getopt
import os
import signal
import sys
from datetime import datetime
import torch
from faster_whisper import WhisperModel
from flask import Flask, jsonify, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads' # Set the upload folder
app.config['MAX_CONTENT_PATH'] = 16 * 1024 * 1024 # 16 MB max file size
SUPPORTED_LANGUAGES = [
"Afrikaans", "Arabic", "Armenian", "Azerbaijani", "Belarusian", "Bosnian",
"Bulgarian", "Catalan", "Chinese", "Croatian", "Czech", "Danish", "Dutch",
"English", "Estonian", "Finnish", "French", "Galician", "German", "Greek",
"Hebrew", "Hindi", "Hungarian", "Icelandic", "Indonesian", "Italian",
"Japanese", "Kannada", "Kazakh", "Korean", "Latvian", "Lithuanian",
"Macedonian", "Malay", "Marathi", "Maori", "Nepali", "Norwegian", "Persian",
"Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Slovak",
"Slovenian", "Spanish", "Swahili", "Swedish", "Tagalog", "Tamil", "Thai",
"Turkish", "Ukrainian", "Urdu", "Vietnamese", "Welsh"
]
# ISO 639-1 Code
LANGUAGE_CODES = {
"Afrikaans" : "af",
"Arabic": "ar",
"Armenian": "hy",
"Azerbaijani": "az",
"Belarusian": "be",
"Bosnian": "bs",
"Bulgarian": "bg",
"Catalan": "ca",
"Chinese": "zh",
"Croatian": "co",
"Czech": "cs",
"Danish": "da",
"Dutch": "nl",
"English": "en",
"Estonian": "et",
"Finnish": "fi",
"French": "fr",
"Galician": "gl",
"German" : "de",
"Greek": "el",
"Hebrew": "he",
"Hindi": "hi",
"Hungarian": "hu",
"Icelandic": "is",
"Indonesian": "id",
"Italian": "it",
"Japanese": "ja",
"Kannada": "kn",
"Kazakh": "kk",
"Korean": "ko",
"Latvian": "lv",
"Lithuanian": "lt",
"Macedonian": "mk",
"Malay": "ms",
"Marathi": "mr",
"Maori": "mi",
"Nepali": "ne",
"Norwegian": "nn",
"Persian": "fa",
"Polish": "pl",
"Portuguese": "pt",
"Romanian": "rm",
"Russian": "ru",
"Serbian": "sr",
"Slovak": "sk",
"Slovenian": "sl",
"Spanish": "es",
"Swahili": "sw",
"Swedish": "sv",
"Tagalog": "tl",
"Tamil": "ta",
"Thai": "th",
"Turkish": "tr",
"Ukrainian": "uk",
"Urdu": "ur",
"Vietnamese": "vi",
"Welsh": "cy"
}
@app.route('/', methods=['GET'])
def home():
return jsonify({
"message": "Welcome to the Translation Service API!",
"endpoints": {
"/translate": "POST endpoint to translate an audio file. Optionally provide 'from_language'.",
"/transcribe": "POST endpoint to transcribe an audio file. Optionally provide 'from_language'.",
"/supportedLanguages": "GET endpoint to list supported languages or check if a specific language is supported."
}
})
def ensure_upload_folder_exists():
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
@app.route('/transcribe', methods=['POST'])
def transcribe():
from_language = request.args.get('from_language', 'English') # Default to English if not provided
if from_language not in SUPPORTED_LANGUAGES:
return jsonify({"error": "Invalid language"}), 400
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
audio_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(audio_path)
# Transcribe
result = model.transcribe(
audio_path,beam_size=5,
)
# Optionally remove the file after transcription
os.remove(audio_path)
return jsonify({"text": result["text"]})
else:
return jsonify({"error": "Invalid file type"}), 400
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in {'wav'}
@app.route('/translate', methods=['POST'])
def translate():
print(request)
from_language = request.args.get('from_language', 'English') # Default to English if not provided
if from_language not in SUPPORTED_LANGUAGES:
return jsonify({"error": "Invalid language"}), 400
# Check if the post request has the file part
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
audio_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(audio_path)
# Translate
result, info = model.transcribe(
audio_path,beam_size=5,
task="translate",
without_timestamps=True,
)
# Optionally remove the file after translation
os.remove(audio_path)
#Iterate over the result and append all the result.text to a text
text = " ".join(segment.text for segment in result)
print(text)
return jsonify({"text": text})
else:
return jsonify({"error": "Invalid file type"}), 400
@app.route('/supportedLanguages', methods=['GET'])
def supported_languages():
language = request.args.get('language')
if language:
return jsonify({"supported": language in SUPPORTED_LANGUAGES})
else:
return jsonify({"languages": SUPPORTED_LANGUAGES})
# Decodes base64 string to mp3 file and saves it to the disk
def decode_audio(data: str) -> str:
audio_data = base64.b64decode(data)
file_path = "audio-cache/audio" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".mp3"
with open(file_path, 'wb') as file:
file.write(audio_data)
return file_path
def handle_exit(*args):
# TODO: cleanup audio-cache
print("Shutting down")
sys.exit(0)
def get_model_version(argv):
model = 'large-v3'
opts, args = getopt.getopt(argv,"hm:",["model="])
for opt, arg in opts:
if opt == '-h':
print ('api.py -m [tiny|small|medium|large|large-v2|large-v3]')
sys.exit()
elif opt in ("-m", "--model"):
model = arg
return model
model = None
if __name__ == '__main__':
model_v = get_model_version(sys.argv[1:])
ensure_upload_folder_exists() # Ensure the uploads folder exists
# Add exit handler to clear audio-cache on shutdown
atexit.register(handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)
# Load model
on_gpu = torch.cuda.is_available()
print("Is CUDA available?", on_gpu,
"\nIf CUDA is not available, check installation instructions in README")
model = WhisperModel(model_v, device="cuda", compute_type="auto")
# Run the app
app.run(host='0.0.0.0', debug = False) |
import {
ILoadTransactionsRepository,
ILoadClientByIdRepository,
} from "@/data/protocols";
import { DbLoadTransactions } from "@/data/usecases";
import { ITransactionModel } from "@/domain/models";
import { mockTransaction } from "@/tests/domain/mocks/mock.transaction";
function makeLoadTransactionsRepository(): ILoadTransactionsRepository {
class LoadTransactionsRepositoryStub implements ILoadTransactionsRepository {
async load(id: string): Promise<ITransactionModel[]> {
return [mockTransaction()];
}
}
return new LoadTransactionsRepositoryStub();
}
function makeLoadClientByIdRepository(): ILoadClientByIdRepository {
class LoadClientByIdRepositoryStub implements ILoadClientByIdRepository {
async load(id: string): Promise<boolean> {
return true;
}
}
return new LoadClientByIdRepositoryStub();
}
type ISutTypes = {
sut: DbLoadTransactions;
loadTransactionsRepositoryStub: ILoadTransactionsRepository;
loadClientByIdRepositoryStub: ILoadClientByIdRepository;
};
function makeSut(): ISutTypes {
const loadTransactionsRepositoryStub = makeLoadTransactionsRepository();
const loadClientByIdRepositoryStub = makeLoadClientByIdRepository();
const sut = new DbLoadTransactions(
loadTransactionsRepositoryStub,
loadClientByIdRepositoryStub
);
return {
sut,
loadTransactionsRepositoryStub,
loadClientByIdRepositoryStub,
};
}
describe("DbLoadTransaction", () => {
test("should call LoadTransactionsRepository with correct values", async () => {
const { sut, loadTransactionsRepositoryStub } = makeSut();
const loadSpy = jest.spyOn(loadTransactionsRepositoryStub, "load");
await sut.load("any_id");
expect(loadSpy).toHaveBeenCalledWith("any_id");
});
test("should throw if LoadTransactionsRepository throw", async () => {
const { sut, loadTransactionsRepositoryStub } = makeSut();
jest
.spyOn(loadTransactionsRepositoryStub, "load")
.mockImplementationOnce(() => {
throw new Error();
});
const promise = sut.load("any_id");
expect(promise).rejects.toThrow();
});
test("should call LoadClientByIdRepository with correct values", async () => {
const { sut, loadClientByIdRepositoryStub } = makeSut();
const loadSpy = jest.spyOn(loadClientByIdRepositoryStub, "load");
await sut.load("any_id");
expect(loadSpy).toHaveBeenCalledWith("any_id");
});
test("should throw if LoadClientByIdRepository throw", async () => {
const { sut, loadClientByIdRepositoryStub } = makeSut();
jest
.spyOn(loadClientByIdRepositoryStub, "load")
.mockImplementationOnce(() => {
throw new Error();
});
const promise = sut.load("any_id");
expect(promise).rejects.toThrow();
});
test("should return false if the provided id does not exists on clients table", async () => {
const { sut, loadClientByIdRepositoryStub } = makeSut();
jest
.spyOn(loadClientByIdRepositoryStub, "load")
// eslint-disable-next-line no-promise-executor-return
.mockReturnValueOnce(new Promise((resolve) => resolve(false)));
const response = await sut.load("any_id");
expect(response).toBe(false);
});
test("should return an array of transactions on success", async () => {
const { sut } = makeSut();
const response = await sut.load("any_id");
expect(response).toEqual([mockTransaction()]);
});
}); |
package com.epam.hibernate.service;
import com.epam.hibernate.dto.trainee.request.TraineeRegisterRequest;
import com.epam.hibernate.dto.trainee.request.TraineeTrainingsRequest;
import com.epam.hibernate.dto.trainee.request.UpdateTraineeRequest;
import com.epam.hibernate.dto.trainee.request.UpdateTrainersListRequest;
import com.epam.hibernate.dto.trainee.response.*;
import com.epam.hibernate.dto.trainer.TrainerListInfo;
import com.epam.hibernate.dto.user.LoginDTO;
import com.epam.hibernate.entity.*;
import com.epam.hibernate.repository.TraineeRepository;
import com.epam.hibernate.repository.TrainerRepository;
import com.epam.hibernate.repository.UserRepository;
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.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import javax.naming.AuthenticationException;
import java.nio.file.AccessDeniedException;
import java.sql.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class TraineeServiceTest {
@Mock
private TraineeRepository traineeRepository;
@Mock
private UserRepository userRepository;
@Mock
private UserService userService;
@Mock
private TrainerRepository trainerRepository;
@InjectMocks
private TraineeService traineeService;
private Trainee createMockTrainee() {
Trainee mockTrainee = mock(Trainee.class);
User mockUser = mock(User.class);
when(mockTrainee.getUser()).thenReturn(mockUser);
return mockTrainee;
}
private Trainer createMockTrainer(){
Trainer mockTrainer = mock(Trainer.class);
User mockUser = mock(User.class);
when(mockUser.getActive()).thenReturn(true);
when(mockTrainer.getUser()).thenReturn(mockUser);
return mockTrainer;
}
private List<Trainer> createMockTrainerList() {
Trainer trainer = mock(Trainer.class);
when(trainer.getUser()).thenReturn(new User("John","Doe",true,RoleEnum.TRAINER));
return List.of(trainer);
}
private List<Training> createMockTrainingList() {
Training training = mock(Training.class);
when(training.getTrainingDate()).thenReturn(Date.valueOf("2024-10-10"));
when(training.getTrainingName()).thenReturn("test");
when(training.getTrainingDuration()).thenReturn(10);
when(training.getTrainingType()).thenReturn(new TrainingType());
when(training.getTrainer()).thenReturn(new Trainer(new TrainingType(TrainingTypeEnum.AGILITY), new User("John", "Doe", true, RoleEnum.TRAINEE)));
return List.of(training);
}
@Test
void createTraineeProfileOk() {
when(userRepository.usernameExists(any())).thenReturn(false);
when(traineeRepository.save(any(Trainee.class))).thenReturn(new Trainee());
TraineeRegisterRequest validRequest = new TraineeRegisterRequest("John", "Doe",
Date.valueOf("2001-10-10"), "123 Main St");
ResponseEntity<TraineeRegisterResponse> responseEntity = traineeService.createProfile(validRequest);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
TraineeRegisterResponse responseBody = responseEntity.getBody();
assertNotNull(responseBody);
assertNotNull(responseBody.getUsername());
assertNotNull(responseBody.getPassword());
}
@Test
void createTraineeProfileSameNameOk() {
when(userRepository.usernameExists(any())).thenReturn(true);
when(traineeRepository.save(any(Trainee.class))).thenReturn(new Trainee());
TraineeRegisterRequest validRequest = new TraineeRegisterRequest("John", "Doe",
Date.valueOf("2001-10-10"), "123 Main St");
ResponseEntity<TraineeRegisterResponse> responseEntity = traineeService.createProfile(validRequest);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
TraineeRegisterResponse responseBody = responseEntity.getBody();
assertNotNull(responseBody);
assertNotNull(responseBody.getUsername());
assertNotNull(responseBody.getPassword());
assertNotNull(responseBody);
assertNotNull(responseBody.getUsername());
assertNotNull(responseBody.getPassword());
assertEquals("John.Doe0", responseBody.getUsername());
}
@Test
void selectTraineeProfileOk() throws AuthenticationException {
when(userService.authenticate(any(LoginDTO.class))).thenReturn(null);
Trainee mockTrainee = createMockTrainee();
when(traineeRepository.selectByUsername(any(String.class))).thenReturn(mockTrainee);
LoginDTO loginDTO = new LoginDTO("admin", "admin");
ResponseEntity<TraineeProfileResponse> response = traineeService.selectCurrentTraineeProfile(
"John.Doe", loginDTO
);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
@Test
void updateTraineeProfileOk() throws AuthenticationException {
when(userService.authenticate(any(LoginDTO.class))).thenReturn(null);
Trainee mockTrainee = createMockTrainee();
when(traineeRepository.updateTrainee(any(String.class), any(), any(), any(), any(), any()))
.thenReturn(mockTrainee);
ResponseEntity<UpdateTraineeResponse> responseEntity = traineeService.updateTrainee(
"John.Doe", new UpdateTraineeRequest(
new LoginDTO("admin", "admin"), "James", "Smith",
null, null, true
));
assertEquals(200, responseEntity.getStatusCode().value());
}
@Test
void deleteTraineeOk() throws AuthenticationException, AccessDeniedException {
when(userService.authenticate(any(LoginDTO.class))).thenReturn(null);
when(userRepository.findByUsername(any())).thenReturn(new User(RoleEnum.ADMIN));
traineeService.deleteTrainee("John.Doe", new LoginDTO("admin", "admin"));
verify(userService, times(1)).authenticate(any(LoginDTO.class));
verify(traineeRepository, times(1)).deleteTrainee("John.Doe");
}
@Test
void getTrainingListOk() throws AuthenticationException {
when(userService.authenticate(any(LoginDTO.class))).thenReturn(null);
List<Training> mockTrainingList = createMockTrainingList();
when(traineeRepository.getTrainingList(anyString(), any(), any(), any(), any()))
.thenReturn(mockTrainingList);
TraineeTrainingsRequest request = new TraineeTrainingsRequest(
new LoginDTO("admin", "admin"), null, null, null, null
);
ResponseEntity<List<TraineeTrainingsResponse>> responseEntity = traineeService.getTrainingList("John.Doe", request);
assertEquals(200, responseEntity.getStatusCode().value());
}
@Test
void notAssignedTrainersListOk() throws AuthenticationException {
when(userService.authenticate(any(LoginDTO.class))).thenReturn(null);
Trainee mockTrainee = createMockTrainee();
when(traineeRepository.selectByUsername(any(String.class))).thenReturn(mockTrainee);
List<Trainer> mockTrainers = createMockTrainerList();
when(trainerRepository.getAllTrainers()).thenReturn(mockTrainers);
ResponseEntity<List<NotAssignedTrainer>> responseEntity = traineeService.notAssignedTrainersList("John.Doe", new LoginDTO("admin", "admin"));
assertEquals(200, responseEntity.getStatusCode().value());
}
@Test
void assignedTrainersListOk() throws AuthenticationException {
when(userService.authenticate(any(LoginDTO.class))).thenReturn(null);
Trainee mockTrainee = createMockTrainee();
when(traineeRepository.selectByUsername(any(String.class))).thenReturn(mockTrainee);
List<Trainer> mockTrainers = createMockTrainerList();
when(trainerRepository.getAllTrainers()).thenReturn(mockTrainers);
User currentUser = new User("admin", "admin", true, RoleEnum.ADMIN);
List<Trainer> assignedTrainers = traineeService.assignedTrainersList(currentUser, "John.Doe");
assertEquals(0, assignedTrainers.size());
}
@Test
void updateTrainersListOk() throws AuthenticationException {
when(userService.authenticate(any(LoginDTO.class))).thenReturn(null);
Trainee mockTrainee = createMockTrainee();
when(traineeRepository.selectByUsername(any(String.class))).thenReturn(mockTrainee);
Trainer mockTrainer = createMockTrainer();
when(trainerRepository.selectByUsername(any(String.class))).thenReturn(mockTrainer);
when(traineeRepository.save(any(Trainee.class))).thenReturn(new Trainee());
Set<String> trainersSet = new HashSet<>();
trainersSet.add("trainerUsername");
UpdateTrainersListRequest request = new UpdateTrainersListRequest(
new LoginDTO("John.Doe","password"),
trainersSet
);
request.setTrainers(trainersSet);
ResponseEntity<List<TrainerListInfo>> responseEntity = traineeService.updateTrainersList("John.Doe", request);
assertEquals(200, responseEntity.getStatusCode().value());
verify(trainerRepository, times(1)).selectByUsername("trainerUsername");
}
} |
import { FastifyReply, FastifyRequest } from 'fastify'
import { z } from 'zod'
import { makeEditPostUseCase } from '../factories/make-edit-post'
import { NotAllowedError } from '../../application/errors/not-allowed.error'
import { EntityNotFoundError } from '../../application/errors/entity-not-found.error'
const editPostBodySchema = z.object({
content: z.string(),
})
const editPostParamSchema = z.object({
id: z.string(),
})
export async function editPostController(request: FastifyRequest, reply: FastifyReply) {
const { content } = editPostBodySchema.parse(request.body)
const { id } = editPostParamSchema.parse(request.params)
const authorId = request.user!.id
const useCase = makeEditPostUseCase()
try {
const { post } = await useCase.execute({ id, authorId, content })
return reply.status(202).send({ post: post.toJson() })
} catch (error) {
if (error instanceof EntityNotFoundError)
return reply.status(400).send({ message: error.message })
if (error instanceof NotAllowedError)
return reply.status(401).send({ message: error.message })
return reply.status(500).send()
}
} |
/*
* Copyright 2013-2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.s3;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
/**
* An S3 object monitor watches a specific object in an S3 bucket and notifies a listener if that object changes.
*/
public class S3ObjectMonitor {
private final String s3Bucket;
private final String objectKey;
private final long maxObjectSize;
private final ScheduledExecutorService refreshExecutorService;
private final Duration refreshInterval;
private ScheduledFuture<?> refreshFuture;
private final AtomicReference<String> lastETag = new AtomicReference<>();
private final S3Client s3Client;
private static final Logger log = LoggerFactory.getLogger(S3ObjectMonitor.class);
public S3ObjectMonitor(
final AwsCredentialsProvider awsCredentialsProvider,
final String s3Region,
final String s3Bucket,
final String objectKey,
final long maxObjectSize,
final ScheduledExecutorService refreshExecutorService,
final Duration refreshInterval) {
this(S3Client.builder()
.region(Region.of(s3Region))
.credentialsProvider(awsCredentialsProvider)
.build(),
s3Bucket,
objectKey,
maxObjectSize,
refreshExecutorService,
refreshInterval);
}
@VisibleForTesting
S3ObjectMonitor(
final S3Client s3Client,
final String s3Bucket,
final String objectKey,
final long maxObjectSize,
final ScheduledExecutorService refreshExecutorService,
final Duration refreshInterval) {
this.s3Client = s3Client;
this.s3Bucket = s3Bucket;
this.objectKey = objectKey;
this.maxObjectSize = maxObjectSize;
this.refreshExecutorService = refreshExecutorService;
this.refreshInterval = refreshInterval;
}
public synchronized void start(final Consumer<InputStream> changeListener) {
if (refreshFuture != null) {
throw new RuntimeException("S3 object manager already started");
}
// Run the first request immediately/blocking, then start subsequent calls.
log.info("Initial request for s3://{}/{}", s3Bucket, objectKey);
refresh(changeListener);
refreshFuture = refreshExecutorService
.scheduleAtFixedRate(() -> refresh(changeListener), refreshInterval.toMillis(), refreshInterval.toMillis(),
TimeUnit.MILLISECONDS);
}
public synchronized void stop() {
if (refreshFuture != null) {
refreshFuture.cancel(true);
}
}
/**
* Immediately returns the monitored S3 object regardless of whether it has changed since it was last retrieved.
*
* @return the current version of the monitored S3 object. Caller should close() this upon completion.
* @throws IOException if the retrieved S3 object is larger than the configured maximum size
*/
@VisibleForTesting
ResponseInputStream<GetObjectResponse> getObject() throws IOException {
final ResponseInputStream<GetObjectResponse> response = s3Client.getObject(GetObjectRequest.builder()
.key(objectKey)
.bucket(s3Bucket)
.build());
lastETag.set(response.response().eTag());
if (response.response().contentLength() <= maxObjectSize) {
return response;
} else {
log.warn("Object at s3://{}/{} has a size of {} bytes, which exceeds the maximum allowed size of {} bytes",
s3Bucket, objectKey, response.response().contentLength(), maxObjectSize);
response.abort();
throw new IOException("S3 object too large");
}
}
/**
* Polls S3 for object metadata and notifies the listener provided at construction time if and only if the object has
* changed since the last call to {@link #getObject()} or {@code refresh()}.
*/
@VisibleForTesting
void refresh(final Consumer<InputStream> changeListener) {
try {
final HeadObjectResponse objectMetadata = s3Client.headObject(HeadObjectRequest.builder()
.bucket(s3Bucket)
.key(objectKey)
.build());
final String initialETag = lastETag.get();
final String refreshedETag = objectMetadata.eTag();
if (!StringUtils.equals(initialETag, refreshedETag) && lastETag.compareAndSet(initialETag, refreshedETag)) {
try (final ResponseInputStream<GetObjectResponse> response = getObject()) {
log.info("Object at s3://{}/{} has changed; new eTag is {} and object size is {} bytes",
s3Bucket, objectKey, response.response().eTag(), response.response().contentLength());
changeListener.accept(response);
}
}
} catch (final Exception e) {
log.warn("Failed to refresh monitored object", e);
}
}
} |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Loader\Configurator;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class CollectionConfigurator
{
use Traits\AddTrait;
use Traits\HostTrait;
use Traits\RouteTrait;
private RouteCollection $parent;
private ?CollectionConfigurator $parentConfigurator;
private ?array $parentPrefixes;
private string|array|null $host = null;
public function __construct(RouteCollection $parent, string $name, self $parentConfigurator = null, array $parentPrefixes = null)
{
$this->parent = $parent;
$this->name = $name;
$this->collection = new RouteCollection();
$this->route = new Route('');
$this->parentConfigurator = $parentConfigurator; // for GC control
$this->parentPrefixes = $parentPrefixes;
}
public function __sleep(): array
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
public function __destruct()
{
if (null === $this->prefixes) {
$this->collection->addPrefix($this->route->getPath());
}
if (null !== $this->host) {
$this->addHost($this->collection, $this->host);
}
$this->parent->addCollection($this->collection);
}
/**
* Creates a sub-collection.
*/
final public function collection(string $name = ''): self
{
return new self($this->collection, $this->name.$name, $this, $this->prefixes);
}
/**
* Sets the prefix to add to the path of all child routes.
*
* @param string|array $prefix the prefix, or the localized prefixes
*
* @return $this
*/
final public function prefix(string|array $prefix): static
{
if (\is_array($prefix)) {
if (null === $this->parentPrefixes) {
// no-op
} elseif ($missing = array_diff_key($this->parentPrefixes, $prefix)) {
throw new \LogicException(sprintf('Collection "%s" is missing prefixes for locale(s) "%s".', $this->name, implode('", "', array_keys($missing))));
} else {
foreach ($prefix as $locale => $localePrefix) {
if (!isset($this->parentPrefixes[$locale])) {
throw new \LogicException(sprintf('Collection "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $this->name, $locale));
}
$prefix[$locale] = $this->parentPrefixes[$locale].$localePrefix;
}
}
$this->prefixes = $prefix;
$this->route->setPath('/');
} else {
$this->prefixes = null;
$this->route->setPath($prefix);
}
return $this;
}
/**
* Sets the host to use for all child routes.
*
* @param string|array $host the host, or the localized hosts
*
* @return $this
*/
final public function host(string|array $host): static
{
$this->host = $host;
return $this;
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Grid Template for Bootstrap</title>
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<style>
.navbar-collapse{
width: 100%;
}
.navbar-nav{
width: 100%;
margin-left: 100px ;
}
.navbar-collapse a{
padding: 10px;
margin-left: 20px;
}
.carousel-inner img {
width: 100%;
height: 100%;
}
.carousel-item{
position: relative;
text-align: center;
width: 100%;
}
.carousel-item h4{
position: absolute;
top: 250px;
left: 700px;
color: black;
text-align: center;
font-weight: 700;
font-size: 30px;
}
.carousel-item p{
position: absolute;
top: 300px;
left: 300px;
color: black;
text-align: center;
}
.jumbotron h3{
padding: 20px 0 20px 0;
color: rgb(149, 145, 145);
}
.jumbotron {
margin-top: 200px;
text-align: center;
}
.footer-dark{
padding: 50px;
background-color: rgb(65, 129, 240);
}
.footer-dark li{
}
.footer-dark a{
list-style: none;
color: #fff;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<div class="navbar-brand">
<h1><img src="img/logo.jpg"/></h1>
</div>
</div>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" aria-current="page" href="./index.html">Trang chủ</a>
<a class="nav-link" href="./service.html">Dịch vụ</a>
<a class="nav-link" href="./about.html">Về chúng tôi</a>
<a class="nav-link" href="./faq.html">FAQ</a>
<a class="nav-link" href="./contact.html">Liên hệ</a>
</div>
</div>
</div>
</nav>
<hr/>
<div id="demo" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ul class="carousel-indicators">
<li data-target="#demo" data-slide-to="0" class="active"></li>
<li data-target="#demo" data-slide-to="1"></li>
<li data-target="#demo" data-slide-to="2"></li>
</ul>
<!-- The slideshow -->
<div class="carousel-inner">
<div class="carousel-item active">
<img src="./img/1.jpg" alt="Los Angeles" width="1100" height="500">
<h4>Điểm du lịch 1</h4>
<p>Đây là địa điểm du lịch 1, chi tiết về điểm du lịch này các bạn có thể có được bằng cách liên lạc với chúng tôi trực tiếp qua điện thoại hoặc email.</p>
</div>
<div class="carousel-item">
<img src="./img/2.jpg" alt="Chicago" width="1100" height="500">
<h4>Điểm du lịch 2</h4>
<p>Đây là địa điểm du lịch 2, chi tiết về điểm du lịch này các bạn có thể có được bằng cách liên lạc với chúng tôi trực tiếp qua điện thoại hoặc email.</p>
</div>
<div class="carousel-item">
<img src="./img/3.jpg" alt="New York" width="1100" height="500">
<h4>Điểm du lịch 3</h4>
<p>Đây là địa điểm du lịch 3, chi tiết về điểm du lịch này các bạn có thể có được bằng cách liên lạc với chúng tôi trực tiếp qua điện thoại hoặc email.</p>
</div>
</div>
<!-- Left and right controls -->
<a class="carousel-control-prev" href="#demo" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#demo" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
</div>
<div class="jumbotron jumbotron-fluid">
<h4>Hãy liên hệ với chúng tôi!</h4>
<p>Chúng tôi mong muốn lắng nghe từ bạn.</p>
<a href="#">Liên hệ</a>
</div>
</div>
<hr/>
<div class="footer-dark">
<footer>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-3 item">
<h3>Services</h3>
<ul>
<li><a href="#">Trang chủ</a></li>
<li><a href="#">Dịch vụ</a></li>
<li><a href="#">FAQ</a></li>
</ul>
</div>
<div class="col-sm-6 col-md-3 item">
<h3>About</h3>
<ul>
<li><a href="./contact.html">Liên hệ</a></li>
<li><a href="#">Về chúng tôi</a></li>
<li><a href="#">Thông tin</a></li>
</ul>
</div>
<div class="col-md-6 item text">
<h3> Công ty Du lịch Bụi.</h3>
<p>Praesent sed lobortis mi. Suspendisse vel placerat ligula. Vivamus ac sem lacus. Ut vehicula rhoncus elementum. Etiam quis tristique lectus. Aliquam in arcu eget velit pulvinar dictum vel in justo.</p>
</div>
</div>
</div>
</footer>
</div>
</body>
</html> |
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
"""
days is an array that has the days of the year that you want to travel on.
costs has the prices for a 1 day pass, 7 day pass, and a 30 day pass, respectively.
each pass lets you travel for that many days (all inclusive)
need the min cost to travel on every desired travel day.
some days will be best to buy 1 day pass, if you don't want to travel for another 30 days or something.
sometimes it might be better to buy a seven day pass, because you'll want to travel a few times within those 7 days, and buying 1 day passes would be more expensive.
[1,4,6,7,8,20]
[2,7,15]
1 7 30
[1,2,3,9]
[2,7,15]
1 7 30
DP, see all possible options
can decide to buy a 1 day ticket, 7, etc., and see what the cost is if you do each
need to know how long your pass let's you travel as you recurse downwards
i.e. if you bought a 7 day pass and recurse downards, you should know when that pass runs out/expires.
you could kind of skip to a certain day if you knew the indices
or if you add the day pass to the current day, you'll get the day that it expires on. that way, you won't have to add to the cost until the new day exceeds that final day
"""
pass_lens = [1, 7, 30]
memo = {}
def find_min(i, start_paying):
key = (i, start_paying)
if key in memo:
return memo[key]
if i >= len(days):
return 0
curr_day = days[i]
min_cost = float('inf')
for j in range(len(costs)):
cost = 0
if curr_day >= start_paying:
cost += costs[j]
cost += find_min(i + 1, curr_day + pass_lens[j])
else:
cost += find_min(i + 1, start_paying)
min_cost = min(min_cost, cost)
memo[key] = min_cost
return memo[key]
return find_min(0, 0) |
package main
import (
"container/heap"
"fmt"
"os"
"github.com/iSkytran/2023adventofcode/utilities"
)
// List of directions that can be added to coordinates.
var directions = []utilities.Coordinates{
{Row: -1, Col: 0},
{Row: 1, Col: 0},
{Row: 0, Col: -1},
{Row: 0, Col: 1},
}
// A state while exploring the grid taking into account location, direction, and
// number of straight steps.
type pathState struct {
loc utilities.Coordinates
direction utilities.Coordinates
steps int
}
// Convert a grid of runes to a grid of integers.
func intGrid(runeGrid *utilities.Grid[rune]) *utilities.Grid[int] {
grid := utilities.NewGrid[int]()
for _, row := range runeGrid.Data {
newRow := make([]int, 0)
for _, col := range row {
value := int(col - '0')
newRow = append(newRow, value)
}
grid.AppendRow(newRow)
}
return grid
}
// Compute the shortest path with constraints on how far in a straight line one can travel in the grid.
func dijkstra(grid *utilities.Grid[int], start utilities.Coordinates, end utilities.Coordinates, minLine int, maxLine int) int {
distance := make(map[pathState]int)
previous := make(map[pathState]pathState)
pq := new(utilities.MinPriorityQueue[pathState])
heap.Init(pq)
// Add start to queue.
startState := pathState{loc: start, direction: utilities.Coordinates{Row: 0, Col: 0}, steps: 0}
startElement := utilities.PriorityElement[pathState]{Value: startState, Priority: 0}
heap.Push(pq, startElement)
distance[startState] = 0
for pq.Len() != 0 {
// Visit next closest coordinate.
nextElement := heap.Pop(pq).(utilities.PriorityElement[pathState])
u := nextElement.Value
if u.steps+1 >= minLine && u.loc == end {
return nextElement.Priority
}
for _, direction := range directions {
// Disallow backtracking.
zeroCoord := utilities.Coordinates{Row: 0, Col: 0}
if direction.Add(u.direction) == zeroCoord {
continue
}
vOrigin := u.loc.Add(direction)
v := pathState{loc: vOrigin, direction: direction, steps: u.steps + 1}
if direction == u.direction {
// Cannot move more than maxLine times in the same direction.
if v.steps >= maxLine {
continue
}
} else {
if v.steps < minLine && u.direction != zeroCoord {
// Disallow turning before minLine. If not starting.
continue
}
// Made a turn. Reset step counter.
v.steps = 0
}
// Check v is in the grid.
if !grid.CoordInGrid(vOrigin) {
continue
}
// Total distance if v visited.
edgeWeight, _ := grid.GetByCoord(vOrigin)
altDist := distance[u] + edgeWeight
if currDist, found := distance[v]; !found || altDist < currDist {
// Found shorter path.
distance[v] = altDist
previous[v] = u
// Add v to queue.
vElement := utilities.PriorityElement[pathState]{Value: v, Priority: altDist}
heap.Push(pq, vElement)
}
}
}
// Couldn't find a path.
return -1
}
func part1(path string) {
grid := intGrid(utilities.GridFromFile(path))
start := utilities.Coordinates{Row: 0, Col: 0}
end := utilities.Coordinates{Row: grid.RowSize() - 1, Col: grid.ColSize() - 1}
distance := dijkstra(grid, start, end, 0, 3)
fmt.Printf("Heat Loss: %d\n", distance)
}
func part2(path string) {
grid := intGrid(utilities.GridFromFile(path))
start := utilities.Coordinates{Row: 0, Col: 0}
end := utilities.Coordinates{Row: grid.RowSize() - 1, Col: grid.ColSize() - 1}
distance := dijkstra(grid, start, end, 4, 10)
fmt.Printf("Heat Loss: %d\n", distance)
}
func main() {
// Input file.
path := os.Args[1]
part1(path)
part2(path)
} |
import UIKit
class PokemonDetailViewController: UIViewController {
@IBOutlet weak var gradientView: GradientView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var pokemonImageViewWidthContraint: NSLayoutConstraint!
@IBOutlet weak var pokemonImageViewHeigthContraint: NSLayoutConstraint!
@IBOutlet weak var pokemonImageViewVerticallyContraint: NSLayoutConstraint!
@IBOutlet weak var pokemonImageViewConstraintTop: NSLayoutConstraint!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var pokemonTypeView: PokemonTypeView!
@IBOutlet weak var backgroudView: DesignableView!
@IBOutlet var labelArray: [UILabel]!
@IBOutlet var progressArray: [UIProgressView]!
@IBOutlet weak var descriptionViewLabel: UILabel!
@IBOutlet weak var progressLabelHP: UILabel!
@IBOutlet weak var progressLabelSPD: UILabel!
@IBOutlet weak var progressLabelSTACK: UILabel!
@IBOutlet weak var progressLabelATK: UILabel!
@IBOutlet weak var progressLabelDEF: UILabel!
@IBOutlet weak var progressLabelSDEF: UILabel!
@IBOutlet weak var progressHP: UIProgressView!
@IBOutlet weak var progressSPD: UIProgressView!
@IBOutlet weak var progressSTACK: UIProgressView!
@IBOutlet weak var progressATK: UIProgressView!
@IBOutlet weak var progressDEF: UIProgressView!
@IBOutlet weak var progressSDEF: UIProgressView!
@IBAction func backAction(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
var pokemon : Pokemon?
let requestMaker = RequestMaker()
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityIdentifier = "detailsView"
self.initialConfig()
if let type = pokemon?.types.first {
self.pokemonTypeView.config(type: type)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.loadPokemonAnimation()
self.requestPokemon()
}
func requestPokemon(){
if let pokemon = self.pokemon {
requestMaker.make(withEndpoint: .details(query: pokemon.id)) {
(pokemon: Pokemon) in
print(pokemon)
self.pokemon = pokemon
self.animateImagePokemonToTop()
}
}
}
func animateImagePokemonToTop() {
DispatchQueue.main.async {
self.imageView.layer.removeAllAnimations()
self.pokemonImageViewVerticallyContraint.priority = UILayoutPriority(rawValue: 900)
self.pokemonImageViewConstraintTop.priority = UILayoutPriority(rawValue: 999)
self.pokemonImageViewHeigthContraint.constant = 100
self.pokemonImageViewWidthContraint.constant = 100
self.configProgress(statsArray: self.pokemon?.stats)
UIView.animate(withDuration: 0.5, animations: {
self.backgroudView.alpha = 1
self.imageView.alpha = 1
self.view.layoutIfNeeded()
}/*, completion: { (ok: Bool) in
self.configProgress(statsArray: self.pokemon?.stats)
})*/)
}
}
func loadPokemonAnimation() {
UIView.animate(withDuration: 0.5, delay: 0,
options: [.repeat, .autoreverse],
animations: {
self.imageView.alpha = 0.2
})
}
func initialConfig() {
if let pokemon = pokemon {
let color = pokemon.types.first?.color ?? .lightGray
self.gradientView.startColor = color
self.gradientView.endColor = color.lighter() ?? .white
self.imageView.loadImage(from: pokemon.image)
self.nameLabel.text = pokemon.name
self.descriptionViewLabel.text = pokemon.description
labelArray.forEach { label in label.textColor = color}
progressArray.forEach { label in label.configProgress(color: color) }
}
}
func configProgress(statsArray: [Stats]?) {
if let stats = self.pokemon?.stats {
stats.forEach { (stat) in
let name: String = stat.name.uppercased()
let value: Float = Float(stat.value)
switch name {
case "SPEED":
progressLabelSPD.text = String(format: "%03d", stat.value)
progressSPD.progress = Float(value/100)
case "SPECIAL-DEFENSE":
progressLabelSDEF.text = String(format: "%03d", stat.value)
progressSDEF.progress = Float(value/100)
case "SPECIAL-ATTACK":
progressLabelSTACK.text = String(format: "%03d", stat.value)
progressSTACK.progress = Float(value/100)
case "DEFENSE":
progressLabelDEF.text = String(format: "%03d", stat.value)
progressDEF.progress = Float(value/100)
case "ATTACK":
progressLabelATK.text = String(format: "%03d", stat.value)
progressATK.progress = Float(value/100)
case "HP":
progressLabelHP.text = String(format: "%03d", stat.value)
progressHP.progress = Float(value/100)
default:
return
}
}
}
}
} |
package com.dkit.oop.sd2.Server.DTOs;
import java.sql.Date;
public class Student {
private int id;
private String firstName;
private String lastName;
private Date birthDate;
private String studentEmail;
private String studentPhone;
private String address;
private int graduationYear;
private boolean hasPaidFullFee;
private double currentGPA;
private int courseId;
public Student() {
}
public Student(String firstName, String lastName, Date birthDate, String studentEmail, String studentPhone, String address, int graduationYear, boolean hasPaidFullFee, double currentGPA, int courseId) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.studentEmail = studentEmail;
this.studentPhone = studentPhone;
this.address = address;
this.graduationYear = graduationYear;
this.hasPaidFullFee = hasPaidFullFee;
this.currentGPA = currentGPA;
this.courseId = courseId;
}
public Student(int id, String firstName, String lastName, Date birthDate, String studentEmail, String studentPhone, String address, int graduationYear, boolean hasPaidFullFee, double currentGPA, int courseId) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.studentEmail = studentEmail;
this.studentPhone = studentPhone;
this.address = address;
this.graduationYear = graduationYear;
this.hasPaidFullFee = hasPaidFullFee;
this.currentGPA = currentGPA;
this.courseId = courseId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getStudentEmail() {
return studentEmail;
}
public void setStudentEmail(String studentEmail) {
this.studentEmail = studentEmail;
}
public String getStudentPhone() {
return studentPhone;
}
public void setStudentPhone(String studentPhone) {
this.studentPhone = studentPhone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getGraduationYear() {
return graduationYear;
}
public void setGraduationYear(int graduationYear) {
this.graduationYear = graduationYear;
}
public boolean isHasPaidFullFee() {
return hasPaidFullFee;
}
public void setHasPaidFullFee(boolean hasPaidFullFee) {
this.hasPaidFullFee = hasPaidFullFee;
}
public double getCurrentGPA() {
return currentGPA;
}
public void setCurrentGPA(double currentGPA) {
this.currentGPA = currentGPA;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", birthDate=" + birthDate +
", studentEmail='" + studentEmail + '\'' +
", studentPhone='" + studentPhone + '\'' +
", address='" + address + '\'' +
", graduationYear=" + graduationYear +
", hasPaidFullFee=" + hasPaidFullFee +
", currentGPA=" + currentGPA +
", courseId=" + courseId +
'}';
}
} |
<template>
<!-- <lightning-card title="Meeting Rooms">
<ul>
<template for:each={meetingRoomsInfo} for:item="room">
<li key={room.roomName} style="padding: 10px">
// show-room-info , passing true value from parent to child component
<c-meeting-room meeting-room-info={room} show-room-info></c-meeting-room>
</li>
</template>
</ul>
</lightning-card> -->
<!--Slot Examples-->
<!-- <lightning-card title="Meeting Rooms">
<ul>
<template for:each={meetingRoomsInfo} for:item="room">
<li key={room.roomName} style="padding: 10px">
<c-meeting-room show-room-info>
// slot is calling with name as attribute in parent component
<lightning-tile label={room.roomName} slot="roomInfo">
<p class="slds-truncate" title={room.roomCapacity}>Room Capacity:
{room.roomCapacity}</p>
</lightning-tile>
// Calling Unnamed Slot
<div>Additional markup will go in unnamed slot</div>
</c-meeting-room>
</li>
</template>
</ul>
</lightning-card> -->
<!-- Child to Parent Communication by using events-->
<lightning-card title="Meeting Rooms">
<lightning-layout>
<lightning-layout-item size="4" padding="around-small">
<ul>
<template for:each={meetingRoomsInfo} for:item="room">
<li key={room.roomName} style="padding: 10px">
<!-- One Way of Communicating to child component by using on + event name (ex:ontileclick)
<c-meeting-room meeting-room-info={room} show-room-info ontileclick={onTileSelectHandler}></c-meeting-room> -->
<!-- Second Way, the CC event handler can be define by time of component creation itself - it can be done by using js file (constructor)-->
<c-meeting-room meeting-room-info={room} show-room-info>
</c-meeting-room>
</li>
</template>
</ul>
</lightning-layout-item>
<lightning-layout-item size="4" padding="around-small">
<!-- selectedMeetingRoom - is a Property -->
You have Selected : {selectedMeetingRoom}
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template> |
//
// CharacterCell.swift
// Rick&Morty
//
// Created by Dani on 2/11/22.
//
import UIKit
import AlamofireImage
protocol CharacterCellDelegate {
func showPermissionAlert()
func showShareMenu(activityController: UIActivityViewController)
func showToast(text: String)
}
class CharacterCell: UICollectionViewCell {
// MARK: - Properties
var delegate: CharacterCellDelegate?
var character: Character?
// MARK: - IBOutlets
@IBOutlet weak var characterImage: UIImageView!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var viewStatus: UIView!
@IBOutlet weak var button: UIButton!
// MARK: - Life cycle
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
// MARK: - Functions
func setupUI() {
viewStatus.layer.cornerRadius = viewStatus.frame.width/2
button.showsMenuAsPrimaryAction = true
button.menu = configurePopUpMenu()
}
func display(this character: Character) {
self.character = character
guard let characterImageURL = URL(string: character.image) else { return }
characterImage.af.setImage(withURL: characterImageURL)
idLabel.text = "#\(character.id)"
nameLabel.text = character.name
switch character.status {
case "Alive":
viewStatus.backgroundColor = .green
case "Dead":
viewStatus.backgroundColor = .red
default:
viewStatus.backgroundColor = .orange
}
}
func configurePopUpMenu() -> UIMenu {
let usersItem = UIAction(title: "Download Image", image: UIImage(systemName: "square.and.arrow.down")) { (action) in
guard let image = self.characterImage.image else {
return
}
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
self.delegate?.showPermissionAlert()
}
let shareItem = UIAction(title: "Share URL", image: UIImage(systemName: "square.and.arrow.up")) { (action) in
let text = self.character?.image
let textToShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textToShare as [Any], applicationActivities: nil)
self.delegate?.showShareMenu(activityController: activityViewController)
}
let copyClipboard = UIAction(title: "Copy", image: UIImage(systemName: "doc.on.doc")) { (action) in
UIPasteboard.general.string = self.character?.name
self.delegate?.showToast(text: "Copy successfully")
}
return UIMenu(title: "Menu", options: .displayInline, children: [usersItem, shareItem, copyClipboard])
}
} |
/*
|--------------------------------------------------------------------------
| Routes
|--------------------------------------------------------------------------
|
| This file is dedicated for defining HTTP routes. A single file is enough
| for majority of projects, however you can define routes in different
| files and just make sure to import them inside this file. For example
|
| Define routes in following two files
| ├── start/routes/cart.ts
| ├── start/routes/customer.ts
|
| and then import them inside `start/routes.ts` as follows
|
| import './routes/cart'
| import './routes/customer'
|
*/
import Route from '@ioc:Adonis/Core/Route'
import packageJson from '../package.json'
import { cocktailUnitsRoute } from './routes/cocktailUnits'
import { ingredientUnitsRoute } from './routes/ingredientUnits'
Route.get('/', () => {
const { name, version } = packageJson
return { name, version }
})
Route.get('cocktails/units', cocktailUnitsRoute)
Route.get('ingredients/units', ingredientUnitsRoute)
Route.resource('techniques', 'TechniquesController').only(['index'])
Route.post('users/login', 'UsersController.login')
Route.post('users/logout', 'UsersController.logout').middleware('auth')
Route.put('users/update', 'UsersController.update').middleware('auth')
Route.resource('ingredients', 'IngredientsController')
.apiOnly()
.middleware({
create: ['auth'],
store: ['auth'],
edit: ['auth'],
update: ['auth'],
destroy: ['auth'],
})
Route.resource('cocktails', 'CocktailsController')
.apiOnly()
.middleware({
create: ['auth'],
store: ['auth'],
edit: ['auth'],
update: ['auth'],
destroy: ['auth'],
}) |
import { Formik } from "formik";
import configureStore from "redux-mock-store";
import ResourcePoolSelect from "./ResourcePoolSelect";
import type { RootState } from "app/store/root/types";
import {
resourcePool as resourcePoolFactory,
resourcePoolState as resourcePoolStateFactory,
rootState as rootStateFactory,
} from "testing/factories";
import { renderWithMockStore, screen } from "testing/utils";
const mockStore = configureStore<RootState>();
describe("ResourcePoolSelect", () => {
it("renders a list of all resource pools in state", () => {
const state = rootStateFactory({
resourcepool: resourcePoolStateFactory({
items: [
resourcePoolFactory({ id: 101, name: "Pool 1" }),
resourcePoolFactory({ id: 202, name: "Pool 2" }),
],
loaded: true,
}),
});
renderWithMockStore(
<Formik initialValues={{ pool: "" }} onSubmit={jest.fn()}>
<ResourcePoolSelect name="pool" />
</Formik>,
{ state }
);
const pools = screen.getAllByRole("option", { name: /Pool [1-2]/i });
expect(pools).toHaveLength(2);
expect(pools[0]).toHaveTextContent("Pool 1");
expect(pools[1]).toHaveTextContent("Pool 2");
});
it("dispatches action to fetch resource pools on load", () => {
const state = rootStateFactory();
const store = mockStore(state);
renderWithMockStore(
<Formik initialValues={{ pool: "" }} onSubmit={jest.fn()}>
<ResourcePoolSelect name="pool" />
</Formik>,
{ store }
);
expect(
store.getActions().some((action) => action.type === "resourcepool/fetch")
).toBe(true);
});
it("disables select if resource pools have not loaded", () => {
const state = rootStateFactory({
resourcepool: resourcePoolStateFactory({
loaded: false,
}),
});
renderWithMockStore(
<Formik initialValues={{ pool: "" }} onSubmit={jest.fn()}>
<ResourcePoolSelect name="pool" />
</Formik>,
{ state }
);
expect(screen.getByRole("combobox")).toBeDisabled();
});
}); |
import { CreateCarsRepositoryProps } from '@modules/cars/dtos/CarsInterfaceDTO'
import { CarRepositoryProps } from '../InterfaceCarRepository'
import { Car } from '@modules/cars/infra/typeorm/entities/Car'
export class CarsRepositoryInMemory implements CarRepositoryProps {
car: Car[] = []
async create({
brand,
category_id,
daily_rate,
description,
fine_amount,
license_plate,
name,
specifications,
id,
}: CreateCarsRepositoryProps): Promise<Car> {
const cars = new Car()
Object.assign(cars, {
brand,
category_id,
daily_rate,
description,
fine_amount,
license_plate,
name,
specifications,
id,
})
this.car.push(cars)
return cars
}
async listByLicensePlate(license_plate: string): Promise<Car | null> {
return this.car.find((car) => car.license_plate === license_plate)
}
async findAvailable(
brand?: string,
category_id?: string,
name?: string,
): Promise<Car[] | Car | null> {
return this.car.filter((car) => {
if (
car.available === true ||
(brand && car.brand === brand) ||
(category_id && car.category_id === category_id) ||
(name && car.name === name)
) {
return car
}
return null
})
}
async findById(car_id: string): Promise<Car> {
return this.car.find((car) => car.id === car_id)
}
async updateAvailable(car_id: string, available: boolean): Promise<void> {
const findIndex = this.car.findIndex((car) => car.id === car_id)
this.car[findIndex].available = available
}
} |
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Editor extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
Editor.hasMany(models.Category, {foreignKey: "editorId"});
}
}
Editor.init({
email: { type: DataTypes.STRING, allowNull: false, unique: true },
password: { type: DataTypes.STRING, allowNull: false },
fullName: { type: DataTypes.STRING, allowNull: false },
avatarPath: DataTypes.STRING,
isDeleted: { type: DataTypes.BOOLEAN, defaultValue: false },
isApproved: { type: DataTypes.BOOLEAN, defaultValue: false }
}, {
sequelize,
modelName: 'Editor',
});
return Editor;
}; |
<template>
<view class="recharge_popup_page">
<view class="px-4">
<view class="recharge_popup_title">
<text>{{ $t("user.wallet.deposit.title") }}</text>
</view>
<view class="recharge_list">
<scroll-view scroll-y class="scroll">
<u-skeleton
:loading="loading"
:animation="true"
bgColor="#FFF"
></u-skeleton>
<view
class="u-skeleton account_bank_item"
v-for="(item, index) in list"
:key="index"
>
<view class="account_sort fa-overflow">{{ item.bankName }}</view>
<view class="account_info flex_row">
<view class="left">
<view class="item_name">{{
$t("user.wallet.deposit.account")
}}</view>
<view>
{{ item.bankNumber }}
<u-image
@click="onCopy(item.bankNumber)"
src="https://btm-group.oss-cn-hangzhou.aliyuncs.com/resources/mobile/static/images/icon_copy.png"
class="ml-1"
width="24"
height="26"
></u-image>
</view>
<view class="item_name item_name1">{{
$t("user.wallet.deposit.bank-address")
}}</view>
<view>
{{ item.bankAddress }}
<u-image
@click="onCopy(item.bankAddress)"
src="https://btm-group.oss-cn-hangzhou.aliyuncs.com/resources/mobile/static/images/icon_copy.png"
class="ml-1"
width="24"
height="26"
></u-image>
</view>
</view>
<view class="right">
<view class="item_name">
{{ $t("user.wallet.deposit.swift-code") }}
</view>
<view>
{{ item.swiftCode }}
<u-image
@click="onCopy(item.swiftCode)"
src="https://btm-group.oss-cn-hangzhou.aliyuncs.com/resources/mobile/static/images/icon_copy.png"
class="ml-1"
width="24"
height="26"
></u-image>
</view>
<view class="item_name item_name1">
{{ $t("user.wallet.deposit.remark") }}
</view>
<view>
{{ item.remark }}
<u-image
@click="onCopy(item.remark)"
src="https://btm-group.oss-cn-hangzhou.aliyuncs.com/resources/mobile/static/images/icon_copy.png"
class="ml-1"
width="24"
height="26"
></u-image>
</view>
</view>
</view>
</view>
</scroll-view>
</view>
</view>
<view class="popup_bottom p-4">
<view class="confirm" @click="onConfirm">
{{ $t("user.wallet.deposit.button") }}
</view>
</view>
</view>
</template>
<script lang="ts" setup>
import usePageFrame from "../../mixins/page-frame";
import { ref, onMounted, defineEmits } from "vue";
import useWalletService from "../../service/wallet/walletService";
import type { DepositForm } from "../../service/wallet/model/walletModel";
import { isWeb, isAndroid, deviceType, isIOS } from "../../utils/platform";
import { DeviceType } from "../../types/enum";
const walletService = useWalletService();
const { onBack, t, $u, copy } = usePageFrame();
const loading = ref<boolean>(true);
const list = ref<Array<any>>([]);
const emit = defineEmits(["finished"]);
onMounted(async () => {
const result = await walletService.depositAccountList();
const data = result.data;
list.value = data;
loading.value = false;
});
const onCopy = (data: any) => {
copy(data);
};
const onConfirm = async () => {
// 0-PC 1-MOBILE(H5) 2-IOS 3-ANDROID
const params = {
channel:
deviceType === DeviceType.PC
? 0
: deviceType === DeviceType.PHONE && isWeb
? 1
: deviceType === DeviceType.PHONE && isAndroid
? 3
: deviceType === DeviceType.PHONE && isIOS
? 2
: 0,
} as DepositForm;
await walletService.deposit(params);
uni.showToast({
title: t("confirm.deposit.success"),
icon: "none",
mask: true,
});
emit("finished");
};
</script>
<style lang="scss" scoped>
.scroll {
height: 628rpx;
}
.recharge_popup_page {
background-color: #fff;
.recharge_popup_title {
text-align: center;
margin-bottom: 20rpx;
font-size: 40rpx;
font-weight: 600;
letter-spacing: 1.2rpx;
line-height: 100rpx;
image {
float: right;
top: 32rpx;
}
}
.recharge_list {
height: 628rpx;
.account_sort {
height: 80rpx;
background-color: rgba(0, 80, 179, 1);
color: #fff;
line-height: 80rpx;
padding-left: 32rpx;
}
.account_info {
background: rgba(79, 191, 255, 0.1);
padding: 40rpx 32rpx 32rpx;
justify-content: space-between;
font-size: 28rpx;
font-weight: 400;
color: rgba(0, 0, 0, 0.8);
line-height: 54rpx;
column-gap: 18rpx;
.left {
width: 50%;
}
.item_name {
font-size: 24rpx;
color: rgba(0, 0, 0, 0.5);
line-height: 34rpx;
}
.item_name1 {
margin-top: 30rpx;
}
}
}
}
.popup_bottom {
background-color: #fff;
border-top: 1rpx solid rgba(237, 237, 237, 1);
.confirm {
color: #ffffff;
line-height: 80rpx;
text-align: center;
background-color: rgba(0, 80, 179, 1);
}
}
.account_bank_item {
margin-bottom: 32rpx;
padding-bottom: 18rpx;
}
</style> |
import math
from random import random
class Matrix:
def __init__(self, rows, cols, initial_value=None):
assert rows > 0, "rows cannot be less than or equal to 0"
assert cols > 0, "cols cannot be less than or equal to 0"
self.rows = rows
self.cols = cols
self.stride = cols
self.values = [] if initial_value else [0 for _ in range(self.rows * self.cols)]
self.print_padding = 0
if initial_value:
assert len(initial_value) == rows, f"the initial value should have {rows} rows"
for r in range(rows):
assert len(initial_value[r]) == cols, f"the number of cols of your initial value should be equal to {cols}"
for v in initial_value[r]:
self.values.append(v)
def __sigmoid(self, x):
return 1.0 / (1.0 + math.exp(-x))
def rand(self):
for i in range(self.rows * self.cols):
self.values[i] = random()
def fill(self, x):
for i in range(self.rows * self.cols):
self.values[i] = x
def set(self, row, col, x):
assert row >= 0, "the row should be greater than or equal to 0"
assert col >= 0, "the col should be greater than or equal to 0"
assert row <= self.rows, "the row should be less than or equal to the total matrix rows"
assert col <= self.cols, "the col should be less than or equal to the total matrix cols"
self.values[row * self.stride + col] = x
def sum(self, matrix):
assert matrix.rows == self.rows, "to sum matrices the number of rows should be equal"
assert matrix.cols == self.cols, "to sum matrices the number of cols should be equal"
m = []
for i in range(self.rows * self.cols):
m.append(self.values[i] + matrix.values[i])
nm = Matrix(self.rows, self.cols)
nm.values = m
return nm
def apply_sigmoid(self):
for i in range(self.rows * self.cols):
self.values[i] = self.__sigmoid(self.values[i])
def row(self, row):
assert row >= 0, "the row should be greater than or equal to 0"
assert row <= self.rows - 1, "the row should be less than or equal to the number of rows that this matrix has - 1"
m = Matrix(1, self.cols);
m.values = self.values[row * self.stride:row * self.stride + self.stride]
return m
def at(self, r, c):
return self.values[self.stride * r + c]
def dot(self, matrix):
assert self.cols == matrix.rows, "to multiply matrices the number of cols of the first one should be equal to the number of rows of the second one"
def at(s, r, c):
return s * r + c
a = self
b = matrix
m = Matrix(a.rows, b.cols)
for row in range(a.rows):
for col in range(b.cols):
for i in range(a.cols):
m.values[at(m.stride, row, col)] += a.values[at(a.stride, row, i)] * b.values[at(b.stride, i, col)]
return m
def __str__(self):
padding = self.print_padding
self.print_padding = 0
string = (' ' * padding) + "[\n"
stride = 0
n = self.cols * self.rows
for i in range(n):
ident = stride == 0
if ident:
string += ' '
string += (' ' * padding) + str(self.values[i])
if stride == self.stride - 1 and i < n - 1:
stride = 0
string += '\n'
else:
stride += 1
string += '\n' + (' ' * padding) + "]"
return string |
import 'package:cercenatorul3000/Theme/colors.dart';
import 'package:cercenatorul3000/Widgets/custom_button.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class AlegeOrasul extends StatefulWidget {
final String projectId;
AlegeOrasul({required this.projectId});
@override
_AlegeOrasulState createState() => _AlegeOrasulState();
}
class _AlegeOrasulState extends State<AlegeOrasul> {
List<String> oraseSelectate = [];
List<String> orase = [];
@override
void initState() {
super.initState();
_getOrase();
}
Future<void> _getOrase() async {
QuerySnapshot oraseSnapshot = await FirebaseFirestore.instance
.collection('Judete')
.get();
for (QueryDocumentSnapshot judetDoc in oraseSnapshot.docs) {
QuerySnapshot oraseJudetSnapshot = await FirebaseFirestore.instance
.collection('Judete')
.doc(judetDoc.id)
.collection('Orase')
.get();
for (QueryDocumentSnapshot orasDoc in oraseJudetSnapshot.docs) {
setState(() {
orase.add(orasDoc.id);
});
}
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(vertical: 10),
child: Center(
child: Text(
oraseSelectate.join(', '),
style: TextStyle(fontSize: 18),
),
),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: AppColors.crimson, width: 2.0)),
),
),
SizedBox(height: 30),
Wrap(
spacing: 10.0,
runSpacing: 10.0,
children: orase.map((oras) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white, backgroundColor: AppColors.pink,
),
onPressed: () {
setState(() {
if (oraseSelectate.contains(oras)) {
oraseSelectate.remove(oras);
} else {
oraseSelectate.add(oras);
}
});
},
child: Text(
oras,
style: TextStyle(fontSize: 18),
),
);
}).toList(),
),
SizedBox(height: 50),
Align(
alignment: Alignment.center,
child: Container(
width: 150, // Setăm lățimea containerului la o valoare fixă
child: CustomButton(
onPressed: () => _salveazaOrasele(widget.projectId, oraseSelectate),
text: 'save',
),
),
),
],
);
}
void _salveazaOrasele(String projectId, List<String> selectedCities) {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
selectedCities.forEach((oras) {
_firestore.collection('Proiecte').doc(projectId).collection('Orase').add(
{'oras': oras},
);
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Orașele au fost salvate cu succes!')),
);
// Poți adăuga aici orice altă acțiune după salvarea orașelor, cum ar fi navigarea la o altă pagină sau actualizarea stării widget-ului.
}
} |
import React, { useState, useEffect } from 'react';
import { Grid, TextField, Button, Avatar, FormControl, Select, MenuItem, InputLabel } from '@material-ui/core';
import { customerDetails, updateCustomerDetails } from '../../api/customer';
import { caretakerDetails, updateCaretakerDetails } from '../../api/caretaker';
import FileBase from 'react-file-base64';
const inputStyle = {
width: '250px',
}
const Profile = ({ type }) => {
const [details, setDetails] = useState({});
const [newDetails, setNewDetails] = useState({});
const [edit, setEdit] = useState(false);
useEffect(() => {
if(type === "customer") {
const token = localStorage.getItem("customerToken");
const fetchDetails = async (token) => {
await customerDetails(token)
.then(res => {
// console.log(res.data.details);
setDetails(res.data.details);
setNewDetails(res.data.details);
})
.catch(err => {
console.log(err.message);
});
}
fetchDetails(token);
}
else {
const token = localStorage.getItem("caretakerToken");
const fetchDetails = async (token) => {
await caretakerDetails(token)
.then(res => {
setDetails(res.data.details);
setNewDetails(res.data.details);
// console.log(res.data.details);
})
.catch(err => {
console.log(err.message);
});
}
fetchDetails(token);
}
}, [type]);
const handleChange = (e) => {
setNewDetails({...newDetails, [e.target.name]: e.target.value});
}
const buttonClick = async () => {
if(edit) {
if(type === "customer") {
updateCustomer();
}
else {
console.log(newDetails);
updateCaretaker();
}
setEdit(false);
}
else {
setEdit(true);
}
}
const updateCustomer = async () => {
const token = localStorage.getItem("customerToken");
await updateCustomerDetails(token, newDetails)
.then(res => {
localStorage.setItem("customerPhoto", newDetails.photo);
})
.catch(err => {
console.log(err.message);
})
}
const updateCaretaker = async () => {
const token = localStorage.getItem("caretakerToken");
await updateCaretakerDetails(token, newDetails)
.then(res => {
localStorage.setItem("caretakerPhoto", newDetails.photo);
alert("Done");
})
.catch(err => {
console.log(err.message);
})
}
const cancelChanges = () => {
setNewDetails(details);
setEdit(false);
}
return (
<Grid container spacing={4} style={{marginTop: '20px'}}>
<Grid item xs={12} md={12} align='center'>
<Avatar style={{width: '200px', height: '200px'}} src={newDetails.photo}/>
{edit && <div>Upload image: <FileBase type="file" multiple={false} onDone={({base64}) => setNewDetails({...newDetails, photo: base64})}/></div>}
{edit && <Button variant="contained" color="primary" style={{marginTop: '10px'}} onClick={() => setNewDetails({...newDetails, photo: ''})}>Clear image</Button>}
{type === "caretaker" && <div style={{marginTop: '10px'}}><p>Rating: {newDetails.rating}</p></div>}
</Grid>
<Grid item container xs={12} md={12} align='center' spacing={2}>
<Grid item xs={12}>
<TextField variant="outlined" style={inputStyle} name="name" label="Name" value={newDetails.name} InputLabelProps={{shrink: true}} disabled onChange={handleChange}></TextField>
</Grid>
<Grid item xs={12}>
<TextField variant="outlined" style={inputStyle} name="age" label="Age" value={newDetails.age} InputLabelProps={{shrink: true}} disabled={!edit} onChange={handleChange}></TextField>
</Grid>
{type === "caretaker" && <Grid item xs={12}>
<TextField variant="outlined" style={inputStyle} name="phone" label="Phone" value={newDetails.phone} InputLabelProps={{shrink: true}} disabled={!edit} onChange={handleChange}></TextField>
</Grid>}
{type === "caretaker" && <Grid item xs={12}>
<TextField variant="outlined" style={inputStyle} name="charge" label="Charge" value={newDetails.charge} InputLabelProps={{shrink: true}} disabled={!edit} onChange={handleChange}></TextField>
</Grid>}
{type === "caretaker" && <Grid item xs={12}>
<FormControl variant='outlined' style={inputStyle} disabled={!edit}>
<InputLabel id='preferred-customer'>Preferred Customer</InputLabel>
<Select label='Preferred Customer' style={{textAlign: 'left'}} value={newDetails.preferredCustomer} labelId='preferred-customer' name='preferredCustomer' onChange={handleChange}>
<MenuItem value='any'>Any</MenuItem>
<MenuItem value='children'>Children</MenuItem>
<MenuItem value='adult'>Adult</MenuItem>
<MenuItem value='elderly'>Elderly</MenuItem>
</Select>
</FormControl>
</Grid>}
{type === "caretaker" && <Grid item xs={12}>
<FormControl variant='outlined' style={inputStyle} disabled={!edit}>
<InputLabel id='availability'>Availability</InputLabel>
<Select label='Preferred Customer' style={{textAlign: 'left'}} value={newDetails.availability} labelId='availability' name='availability' onChange={handleChange}>
<MenuItem value='available'>Available</MenuItem>
<MenuItem value='busy'>Busy</MenuItem>
</Select>
</FormControl>
</Grid>}
{type === "customer" && <Grid item xs={12}>
<TextField variant="outlined" style={inputStyle} name="phonePrimary" label="Primary phone" value={newDetails.phonePrimary} InputLabelProps={{shrink: true}} disabled={!edit} onChange={handleChange}></TextField>
</Grid>}
{type === "customer" && <Grid item xs={12}>
<TextField variant="outlined" style={inputStyle} name="phoneEmergency" label="Emergency phone" value={newDetails.phoneEmergency} InputLabelProps={{shrink: true}} disabled={!edit} onChange={handleChange}></TextField>
</Grid>}
<Grid item xs={12}>
<TextField multiline rows={4} style={inputStyle} name="address" variant="outlined" label="Address" value={newDetails.address} InputLabelProps={{shrink: true}} disabled={!edit} onChange={handleChange}></TextField>
</Grid>
<Grid item xs={12}>
<TextField multiline rows={4} style={inputStyle} name="aboutMe" variant="outlined" label="About Me" value={newDetails.aboutMe} InputLabelProps={{shrink: true}} disabled={!edit} onChange={handleChange}></TextField>
</Grid>
</Grid>
<Grid item xs={12} align='center'>
<Button variant='contained' color='primary' onClick={buttonClick}>{edit ? "Save" : "Edit"}</Button>
</Grid>
{edit && <Grid item xs={12} align='center'>
<Button variant='contained' color='primary' onClick={cancelChanges}>Cancel</Button>
</Grid>}
</Grid>
);
}
export default Profile; |
from tkinter import font
from turtle import color
from urllib.request import proxy_bypass
from sklearn.model_selection import RepeatedStratifiedKFold, GridSearchCV, train_test_split
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from xgboost import XGBClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from IPython import display
from PIL import Image
from sklearn.preprocessing import StandardScaler
from collections import Counter
from sklearn import preprocessing
from sklearn.pipeline import Pipeline
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import SGDRegressor
from sklearn.ensemble import BaggingRegressor, VotingRegressor
from sklearn.preprocessing import LabelEncoder
from sklearn import metrics
# Function to load dataset
def load_dataset(dataset_name, date_column=None):
if dataset_name == "deforestation":
data_path = input("Enter the file path for data.csv: ")
mun_path = input("Enter the file path for Counties.csv: ")
states_path = input("Enter the file path for states.csv: ")
df = pd.read_csv(data_path)
mun = pd.read_csv(mun_path, sep=';')
states = pd.read_csv(states_path)
return df, mun, states
file_path = input(f"Enter the file path for the {dataset_name} dataset: ")
if date_column:
parse_dates = [date_column]
data = pd.read_csv(file_path, parse_dates=parse_dates)
else:
data = pd.read_csv(file_path)
return data
choice = int(input(
"Enter your choice (1 for Water Quality, 2 for Air Quality, 3 for Deforestation, 4 for Climate Pattern): "))
# Water Quality Prediction
if choice == 1:
# Load the dataset
water_quality_data = load_dataset("water quality")
# ... (code for water quality prediction using 'water_quality_data')
print(water_quality_data.head())
print(water_quality_data.shape)
print(water_quality_data.isnull().sum())
water_quality_data.fillna(water_quality_data.mean(), inplace=True)
print(water_quality_data.isnull().sum())
print(water_quality_data.describe())
# Exploring the data
fig, axes = plt.subplots(figsize=(10, 7))
sns.heatmap(water_quality_data.corr(), annot=True,
cmap='gist_rainbow', ax=axes)
axes.set_title("Correlation Heatmap")
plt.show()
fig, axes = plt.subplots(figsize=(20, 7))
water_quality_data.boxplot(ax=axes)
axes.set_title("Boxplot")
plt.show()
print(water_quality_data['Solids'].describe())
print(water_quality_data.head())
print(water_quality_data.shape)
print(water_quality_data['Potability'].value_counts())
fig, axes = plt.subplots()
# Plot the countplot of Potability
sns.countplot(water_quality_data['Potability'], ax=axes)
axes.set_title("Countplot of Potability")
plt.show()
fig, axes = plt.subplots(figsize=(20, 15))
# Plot the histogram of variables
water_quality_data.hist(ax=axes)
# Set title and axis labels
axes.set_title("Histogram of Variables", color="black")
axes.set_xlabel("Variable")
axes.set_ylabel("Frequency")
plt.tight_layout() # Ensures proper spacing between subplots
plt.show()
fig = sns.pairplot(water_quality_data, hue="Potability")
fig.fig.suptitle("Pairplot of Variables")
plt.show()
fig, axes = plt.subplots()
sns.scatterplot(x=water_quality_data['ph'],
y=water_quality_data['Potability'], ax=axes)
axes.set_title("Scatterplot of pH vs. Potability")
plt.show()
# ...
x = water_quality_data.drop('Potability', axis=1) # input data
y = water_quality_data['Potability'] # target variable
x_train, x_test, y_train, y_test = train_test_split(
x, y, test_size=0.2, shuffle=True, random_state=404)
print(x_train)
print(y_train)
AB = DecisionTreeClassifier(
criterion='entropy', min_samples_split=9, splitter='best')
AB.fit(x_train, y_train) # Fit the model with training data
y_prediction = AB.predict(x_test)
print(accuracy_score(y_prediction, y_test) * 100)
print(confusion_matrix(y_test, y_prediction))
print(y_test.shape)
AB = DecisionTreeClassifier()
criterion = ["gini", "entropy"]
splitter = ["best", "random"]
min_samples_split = range(2, 10)
parameters = dict(criterion=criterion, splitter=splitter,
min_samples_split=min_samples_split)
cv = RepeatedStratifiedKFold(n_splits=5, random_state=250)
grid_search_cv_AB = GridSearchCV(
estimator=AB, param_grid=parameters, scoring='accuracy', cv=cv)
print(grid_search_cv_AB.fit(x_train, y_train))
print(grid_search_cv_AB.best_params_)
prediction_grid = grid_search_cv_AB.predict(x_test)
print(accuracy_score(prediction_grid, y_test) * 100)
print(confusion_matrix(y_test, prediction_grid))
knn = KNeighborsClassifier(metric='manhattan', n_neighbors=22)
knn.fit(x_train, y_train)
prediction_knn = knn.predict(x_test)
accuracy_knn = accuracy_score(y_test, prediction_knn) * 100
print('accuracy_score score:', accuracy_knn, '%')
print(confusion_matrix(prediction_grid, y_test))
# Air Quality Prediction
elif choice == 2:
# Load the dataset
# Load the dataset
air_quality_data = load_dataset("air quality", date_column="Date")
# Now you can use the air_quality_data DataFrame
print(air_quality_data.head())
# ... (code for air quality prediction using 'air_quality_data')
print(air_quality_data.shape)
fig, axes = plt.subplots(figsize=(10, 7))
# Plot the heatmap with missing values
sns.heatmap(air_quality_data.isnull(), yticklabels=False, cbar=False, cmap='viridis')
axes.set_title("Missing Values Heatmap")
plt.show()
plt.show()
print(air_quality_data .isnull().sum())
print((air_quality_data.isnull().sum() /
air_quality_data.shape[0] * 100).sort_values(ascending=False))
# #
print(air_quality_data.describe())
air_quality_data['Date'] = air_quality_data['Date'].apply(pd.to_datetime)
air_quality_data .set_index('Date', inplace=True)
print(air_quality_data.columns)
valid_columns = air_quality_data.columns[1:13]
air_quality_data.loc[:, valid_columns] = air_quality_data.groupby(
"City")[valid_columns].transform(lambda x: x.fillna(x.mean()))
print(air_quality_data)
fig, axes = plt.subplots(figsize=(10, 7))
# Plot the heatmap with missing values
sns.heatmap(air_quality_data.isnull(), yticklabels=False,
cbar=False, cmap='viridis')
axes.set_title("Missing Values Heatmap")
plt.show()
air_quality_data[valid_columns] = air_quality_data[valid_columns].fillna(
air_quality_data[valid_columns].mean())
print(air_quality_data)
# PM10 Sub-Index calculation
# PM10 Sub-Index calculation
def get_PM10_subindex(x):
if x <= 50:
return x
elif x > 50 and x <= 100:
return x
elif x > 100 and x <= 250:
return 100 + (x - 100) * 100 / 150
elif x > 250 and x <= 350:
return 200 + (x - 250)
elif x > 350 and x <= 430:
return 300 + (x - 350) * 100 / 80
elif x > 430:
return 400 + (x - 430) * 100 / 80
else:
return 0
air_quality_data["PM10_SubIndex"] = air_quality_data["PM10"].astype(int).apply(get_PM10_subindex)
# PM2.5 Sub-Index calculation
def get_PM25_subindex(x):
if x <= 30:
return x * 50 / 30
elif x > 30 and x <= 60:
return 50 + (x - 30) * 50 / 30
elif x > 60 and x <= 90:
return 100 + (x - 60) * 100 / 30
elif x > 90 and x <= 120:
return 200 + (x - 90) * 100 / 30
elif x > 120 and x <= 250:
return 300 + (x - 120) * 100 / 130
elif x > 250:
return 400 + (x - 250) * 100 / 130
else:
return 0
air_quality_data["PM2.5_SubIndex"] = pd.to_numeric(
air_quality_data["PM2.5"], errors="coerce").apply(get_PM25_subindex)
# SO2 Sub-Index calculation
def get_SO2_subindex(x):
if x <= 40:
return x * 50 / 40
elif x > 40 and x <= 80:
return 50 + (x - 40) * 50 / 40
elif x > 80 and x <= 380:
return 100 + (x - 80) * 100 / 300
elif x > 380 and x <= 800:
return 200 + (x - 380) * 100 / 420
elif x > 800 and x <= 1600:
return 300 + (x - 800) * 100 / 800
elif x > 1600:
return 400 + (x - 1600) * 100 / 800
else:
return 0
air_quality_data["SO2_SubIndex"] = air_quality_data["SO2"].astype(int).apply(get_SO2_subindex)
# NOx Sub-Index calculation
def get_NOx_subindex(x):
if x <= 40:
return x * 50 / 40
elif x > 40 and x <= 80:
return 50 + (x - 40) * 50 / 40
elif x > 80 and x <= 180:
return 100 + (x - 80) * 100 / 100
elif x > 180 and x <= 280:
return 200 + (x - 180) * 100 / 100
elif x > 280 and x <= 400:
return 300 + (x - 280) * 100 / 120
elif x > 400:
return 400 + (x - 400) * 100 / 120
else:
return 0
air_quality_data["NOx_SubIndex"] = air_quality_data["NOx"].astype(int).apply(get_NOx_subindex)
# NH3 Sub-Index calculation
def get_NH3_subindex(x):
if x <= 200:
return x * 50 / 200
elif x > 200 and x <= 400:
return 50 + (x - 200) * 50 / 200
elif x > 400 and x <= 800:
return 100 + (x - 400) * 100 / 400
elif x > 800 and x <= 1200:
return 200 + (x - 800) * 100 / 400
elif x > 1200 and x <= 1800:
return 300 + (x - 1200) * 100 / 600
elif x > 1800:
return 400 + (x - 1800) * 100 / 600
else:
return 0
air_quality_data["NH3_SubIndex"] = air_quality_data["NH3"].astype(int).apply(get_NH3_subindex)
# CO Sub-Index calculation
def get_CO_subindex(x):
if x <= 1:
return x * 50 / 1
elif x > 1 and x <= 2:
return 50 + (x - 1) * 50 / 1
elif x > 2 and x <= 10:
return 100 + (x - 2) * 100 / 8
elif x > 10 and x <= 17:
return 200 + (x - 10) * 100 / 7
elif x > 17 and x <= 34:
return 300 + (x - 17) * 100 / 17
elif x > 34:
return 400 + (x - 34) * 100 / 17
else:
return 0
air_quality_data["CO_SubIndex"] = air_quality_data["CO"].astype(int).apply(get_CO_subindex)
# O3 Sub-Index calculation
def get_O3_subindex(x):
if x <= 50:
return x * 50 / 50
elif x > 50 and x <= 100:
return 50 + (x - 50) * 50 / 50
elif x > 100 and x <= 168:
return 100 + (x - 100) * 100 / 68
elif x > 168 and x <= 208:
return 200 + (x - 168) * 100 / 40
elif x > 208 and x <= 748:
return 300 + (x - 208) * 100 / 540
elif x > 748:
return 400 + (x - 748) * 100 / 540
else:
return 0
air_quality_data["O3_SubIndex"] = air_quality_data["O3"].astype(int).apply(get_O3_subindex)
# Filling the Nan values of AQI column by taking maximum values out of sub-Indexes
air_quality_data["AQI"] = air_quality_data[["PM2.5_SubIndex", "PM10_SubIndex", "SO2_SubIndex",
"NOx_SubIndex", "NH3_SubIndex", "CO_SubIndex", "O3_SubIndex"]].max(axis=1)
print(air_quality_data)
fig, axes = plt.subplots(figsize=(10, 7))
# Plot the heatmap with missing values
sns.heatmap(air_quality_data.isnull(), yticklabels=False,
cbar=False, cmap='viridis')
axes.set_title("Missing Values Heatmap")
plt.show()
#AQI Bucket
display.Image("notebooks\__results___16_0.png", width=400, height=200)
# Load the image
image_path = "notebooks\__results___16_0.png"
image = Image.open(image_path)
# Display the image
image.show()
# calculating AQI bucket and filling the NAN value present
# AQI bucketing
def get_AQI_bucket(x):
if x <= 50:
return "Good"
elif x > 50 and x <= 100:
return "Satisfactory"
elif x > 100 and x <= 200:
return "Moderate"
elif x > 200 and x <= 300:
return "Poor"
elif x > 300 and x <= 400:
return "Very Poor"
elif x > 400:
return "Severe"
else:
return '0'
air_quality_data["AQI_Bucket"] = air_quality_data["AQI_Bucket"].fillna(
air_quality_data["AQI"].apply(lambda x: get_AQI_bucket(x)))
print(air_quality_data)
fig, axes = plt.subplots(figsize=(10, 7))
# Plot the heatmap with missing values
sns.heatmap(air_quality_data.isnull(), yticklabels=False,
cbar=False, cmap='viridis')
axes.set_title("Missing Values Heatmap")
plt.show()
air_quality_data_city_day = air_quality_data .copy()
print(air_quality_data.columns)
# Filter out non-numeric columns
numeric_columns = air_quality_data.select_dtypes(include=np.number)
# Plot the correlation heatmap
plt.figure(figsize=(12, 10))
sns.heatmap(numeric_columns.corr(), cmap='coolwarm', annot=True)
plt.show()
# Select the pollutants
pollutants = ['PM2.5', 'PM10', 'NO', 'NO2', 'NOx', 'NH3',
'CO', 'SO2', 'O3', 'Benzene', 'Toluene', 'Xylene']
air_quality_data_city_day = air_quality_data_city_day[pollutants]
# Plot the distribution of pollutants
print('Distribution of different pollutants in the last 5 years')
air_quality_data_city_day.plot(kind='line', figsize=(
18, 18), cmap='coolwarm', subplots=True, fontsize=10)
plt.show()
air_quality_data[['City', 'AQI']].groupby('City').mean().sort_values(
'AQI').plot(kind='bar', cmap='Blues_r', figsize=(8, 8))
plt.title('Average AQI in last 5 years')
plt.show()
final_air_quality_data = air_quality_data[['AQI', 'AQI_Bucket']].copy()
print(final_air_quality_data)
print(final_air_quality_data ['AQI_Bucket'].unique())
final_air_quality_data ['AQI_Bucket'] = final_air_quality_data ['AQI_Bucket'].map(
{'Good': 0, 'Satisfactory': 1, 'Moderate': 2, 'Poor': 3, 'Very Poor': 4, 'Severe': 5}).astype(int) # mapping numbers
print(final_air_quality_data.head())
# Predicting the values of AQI_Bucket w.r.t values of AQI using Random Forest Classifier
X = final_air_quality_data [['AQI']]
y = final_air_quality_data [['AQI_Bucket']]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = RandomForestClassifier(random_state=0).fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Enter the value of AQI:")
AQI = float(input("AQI : "))
output = clf.predict([[AQI]])
print(output)
# 0-->Good
# 1-->Satisfactory
# 2-->moderate
# 3-->poor
# 4-->Very poor
# 5-->Severe
print(accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))
# Deforestation Prediction
elif choice == 3:
# Load the dataset
df, mun, states = load_dataset("deforestation")
print(df.head())
# ... (code for deforestation prediction using 'deforestation_data')
def call(number):
"""This fuction will use the first two characters of a number
and return all the matches from the states["estados_id"] dataframe"""
num = str(number)[0:2]
num = int(num)
return states[states["estados_id"] == num]
def transform(air_quality_data):
"""It creates two lists with the name of the county and its state"""
munic = []
esta = []
for i in range(len(air_quality_data["id_municipio"])):
ind = mun[mun["Código Município Completo"] ==
air_quality_data["id_municipio"][i]]["Nome_Microrregião"].index[0]
nome_mun = mun[mun["Código Município Completo"] ==
air_quality_data["id_municipio"][i]]["Nome_Microrregião"][ind]
ind_es = mun[mun["Código Município Completo"] ==
air_quality_data["id_municipio"][i]]["Código Município Completo"][ind]
m = call(ind_es)["Estados"].index[0]
nome_est = call(ind_es)["Estados"][m]
munic.append(nome_mun)
esta.append(nome_est)
return munic, esta
def stats_year(air_quality_data, nome, Mean):
"""it returns the total sum of the nome column grouped
by the ano column"""
sum = air_quality_data[["ano", nome]].groupby(['ano']).sum()
media = sum[nome].mean()
vals = []
if Mean == False:
for k in sum[nome]:
vals.append(k)
else:
for k in sum[nome]:
vals.append(k/media)
return np.array(vals), sum.index
lista_mun, lista_est = transform(df) # lets add the new columns to our dataset
df["municipios"] = lista_mun
df["estados"] = lista_est
selected_columns = ["ano", "area", "desmatado", "floresta", "nuvem",
"nao_observado", "nao_floresta", "hidrografia", "estados", "municipios"]
new = df[selected_columns]
# Exclude non-numeric columns from the 'new' DataFrame
numeric_columns = new.select_dtypes(include=np.number).columns
new = new[numeric_columns]
corr = round(new.corr(), 2)
mask = np.triu(np.ones_like(corr, dtype=bool))
f, ax = plt.subplots(figsize=(9, 5))
# Plot the heatmap
sns.heatmap(corr, mask=mask, vmin=-1, vmax=1, annot=True)
ax.set_title("Correlation Heatmap")
plt.show()
lista1, anos1 = stats_year(df, "desmatado", True)
lista2, anos2 = stats_year(df, "floresta", True)
plt.figure(figsize=(9, 5))
plt.plot(list(anos1), lista1, "r", label="Deforestation Rate of Change")
plt.plot(list(anos2), lista2, "g", label="Forest Area Rate of Change")
plt.ylabel("Percentage %")
plt.legend()
anos = list(set(df["ano"]))
year = []
desmat = []
munic = []
esta = []
for ano in anos:
new = df[df["ano"] == ano]
new = new.sort_values(by=['desmatado'], ascending=False)
year.append(np.array(list(new.copy().iloc[0:10]["ano"])[:]))
desmat.append(np.array(list(new.copy().iloc[0:10]["desmatado"])[:]))
munic.append(np.array(list(new.copy().iloc[0:10]["municipios"])[:]))
esta.append(np.array(list(new.copy().iloc[0:10]["estados"])[:]))
dic = dict()
dic["ano"] = np.array(year).reshape(1, -1)[0]
dic["estado"] = np.array(esta).reshape(1, -1)[0]
dic["desmatado"] = np.array(desmat).reshape(1, -1)[0]
dic["municipio"] = np.array(munic).reshape(1, -1)[0]
novo = pd.DataFrame(dic)
print(novo)
muns = list(Counter(novo["municipio"]))
mat = []
for i in range(len(muns)):
data = df[df["municipios"] == muns[i]]
mat.append(stats_year(data, "desmatado", False)[0])
plt.figure(figsize=(15, 8))
for i in range(len(muns)):
if muns[i] == "São Félix do Xingu":
plt.plot(list(set(novo.ano)), mat[i])
plt.text(list(set(novo.ano))[-1]-4, mat[i]
[-1]-1000, str(muns[i]), fontsize=10)
elif muns[i] == "Arinos":
plt.plot(list(set(novo.ano)), mat[i])
plt.text(list(set(novo.ano))[-1]-4, mat[i][-1], str(muns[i]), fontsize=10)
else:
plt.plot(list(set(novo.ano)), mat[i])
plt.text(list(set(novo.ano))[-1], mat[i][-1], str(muns[i]), fontsize=10)
plt.ylabel("Deforestation (Km^2)", fontsize=20)
plt.show()
estd = list(Counter(df["estados"]))
mat = []
for i in range(len(estd)):
data = df[df["estados"] == estd[i]]
mat.append(stats_year(data, "desmatado", False)[0])
ano = []
est = []
for estado in estd:
for i in range(2000, 2022):
ano.append(i)
est.append(estado)
d = {}
d["ano"] = ano
d["estado"] = est
d["desmatado"] = np.array(mat).reshape(1, -1)[0]
X = pd.DataFrame(d)
labels = list(Counter(X["estado"]))
X["estado"] = LabelEncoder().fit_transform(X["estado"])
Y = X.pop("desmatado")
labels_encod = list(Counter(X["estado"]))
scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)
KN = KNeighborsRegressor()
bag = BaggingRegressor()
mod = GridSearchCV(estimator=KN,param_grid= {'n_neighbors':[1,2,3,4,5,6,7,8,9,10]},cv=2)
mod2 = GridSearchCV(estimator=bag,param_grid= {'n_estimators':[100,120,130,150,180]},cv=2)
mod3 = GridSearchCV(estimator=SGDRegressor(max_iter=1200,early_stopping=True),param_grid={'penalty': ["l1","l2"]} ,cv=2)
vot = VotingRegressor(estimators=[("kn",mod),("bag",mod2),("est",mod3)])
X_train, X_test, y_train, y_test = train_test_split(
X, Y, test_size=0.1, random_state=True)
vot.fit(X_train, y_train)
print(metrics.r2_score(y_test, vot.predict(X_test)))
m = []
for i in labels_encod:
for year in range(2022, 2024):
m.append({'ano': year, 'estado': i})
m_air_quality_data = pd.DataFrame(m)
pred = scaler.transform(m_air_quality_data[['ano', 'estado']])
predic = vot.predict(pred)
air_quality_data = pd.DataFrame(d)
ano = [i for i in range(2000, 2024)]
plt.figure(figsize=(15, 8))
c = 0
for i in labels:
dat = air_quality_data[air_quality_data["estado"] == i]
es = list(dat["desmatado"])
es.append(predic[c])
es.append(predic[c+1])
plt.plot(ano, es, label=i)
c += 2
plt.axvline(2021, color='k', linestyle='--')
plt.legend()
plt.xticks(ano, rotation=45)
plt.show()
# Climate Pattern Prediction
elif choice == 4:
# Load the dataset
climate_pattern_data = load_dataset("climate pattern")
print(climate_pattern_data.head())
print(climate_pattern_data.tail())
print(climate_pattern_data.info())
print(climate_pattern_data.isnull().sum())
climate_pattern_data['date'] = pd.to_datetime(climate_pattern_data['date'])
print(climate_pattern_data.nunique())
# Plot 1: Countplot of weather
plt.figure(figsize=(10, 5))
sns.set_theme()
sns.countplot(x='weather', data=climate_pattern_data, palette="ch:start=.2,rot=-.3")
plt.xlabel("weather", fontweight='bold', size=13)
plt.ylabel("Count", fontweight='bold', size=13)
plt.title("Count of Weather", fontweight='bold', size=15)
plt.show()
# Plot 2: Lineplot of temp_max
plt.figure(figsize=(18, 8))
sns.set_theme()
sns.lineplot(x='date', y='temp_max', data=climate_pattern_data)
plt.xlabel("Date", fontweight='bold', size=13)
plt.ylabel("Temp_Max", fontweight='bold', size=13)
plt.title("Lineplot of temp_max", fontweight='bold', size=15)
plt.show()
# Plot 3: Lineplot of temp_min
plt.figure(figsize=(18, 8))
sns.set_theme()
sns.lineplot(x='date', y='temp_min', data=climate_pattern_data)
plt.xlabel("Date", fontweight='bold', size=13)
plt.ylabel("Temp_Min", fontweight='bold', size=13)
plt.title("Lineplot of temp_min", fontweight='bold', size=15)
plt.show()
# Plot 4: Lineplot of wind
plt.figure(figsize=(18, 8))
sns.set_theme()
sns.lineplot(x='date', y='wind', data=climate_pattern_data)
plt.xlabel("Date", fontweight='bold', size=13)
plt.ylabel("wind", fontweight='bold', size=13)
plt.title("Lineplot of wind", fontweight='bold', size=15)
plt.show()
# Plot 5: Pairplot of weather vs. other numerical variables
sns.pairplot(climate_pattern_data.drop('date', axis=1), hue='weather', palette="hot")
plt.title("Pairplot of weather vs. other numerical variables",
fontweight='bold', size=10)
plt.show()
# Plot 6: Catplot of weather vs. temp_max
sns.catplot(x='weather', y='temp_max', data=climate_pattern_data, palette="hot")
plt.title("Catplot of weather vs. temp_max",
fontweight='bold', size=10)
plt.show()
# Plot 8: Catplot of weather vs. temp_min
sns.catplot(x='weather', y='temp_min', data=climate_pattern_data, palette="hot")
plt.title("Catplot of weather vs. temp_min",
fontweight='bold', size=10)
plt.show()
# Plot 9: Catplot of weather vs. wind
sns.catplot(x='weather', y='wind', data=climate_pattern_data, palette="hot")
plt.title("Catplot of weather vs. wind",
fontweight='bold', size=10)
plt.show()
# Plot 10: Catplot of weather vs. precipitation
sns.catplot(x='weather', y='precipitation', data=climate_pattern_data, palette="hot")
plt.title("Catplot of weather vs. precipitation",
fontweight='bold', size=10)
plt.show()
# Plot 11: Scatterplots of weather vs. numerical variables
fig, axes = plt.subplots(2, 2, figsize=(18, 10))
fig.suptitle('Price Range vs all numerical factor')
sns.scatterplot(ax=axes[0, 0], data=climate_pattern_data, x='weather', y='precipitation')
sns.scatterplot(ax=axes[0, 1], data=climate_pattern_data, x='weather', y='temp_max')
sns.scatterplot(ax=axes[1, 0], data=climate_pattern_data, x='weather', y='temp_min')
sns.scatterplot(ax=axes[1, 1], data=climate_pattern_data, x='weather', y='wind')
plt.show()
# Data preprocessing: Label encoding for the "weather" column
def LABEL_ENCODING(c1):
label_encoder = preprocessing.LabelEncoder()
climate_pattern_data[c1] = label_encoder.fit_transform(climate_pattern_data[c1])
climate_pattern_data[c1].unique()
LABEL_ENCODING("weather")
print(climate_pattern_data)
data = climate_pattern_data.drop('date', axis=1)
x = data.drop('weather', axis=1)
y = data['weather']
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
classifier = LogisticRegression(random_state=0)
print(classifier.fit(X_train, y_train))
y_pred = classifier.predict(X_test)
print(y_pred)
cm = confusion_matrix(y_test, y_pred)
print(cm)
sns.heatmap(cm, annot=True)
plt.show()
acc1 = accuracy_score(y_test, y_pred)
print(f"Accuracy score: {acc1}")
classifier = SVC(kernel='linear', random_state=0)
print(classifier.fit(X_train, y_train))
y_pred = classifier.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
acc2 = accuracy_score(y_test, y_pred)
print(f"Accuracy score: {acc2}")
classifier = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2)
print(classifier.fit(X_train, y_train))
y_pred = classifier.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
acc3 = accuracy_score(y_test, y_pred)
print(f"Accuracy score: {acc3}")
classifier = GaussianNB()
print(classifier.fit(X_train, y_train))
y_pred = classifier.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
acc4 = accuracy_score(y_test, y_pred)
print(f"Accuracy score : {acc4}")
classifier = DecisionTreeClassifier(criterion='entropy', random_state=0)
print(classifier.fit(X_train, y_train))
y_pred = classifier.predict(X_test)
print(y_pred)
cm = confusion_matrix(y_test, y_pred)
print(cm)
sns.heatmap(cm, annot=True)
plt.show()
acc5 = accuracy_score(y_test, y_pred)
print(f"Accuracy score: {acc5}")
forest = RandomForestClassifier(n_estimators=40, random_state=0)
forest.fit(X_train, y_train)
RandomForestClassifier(n_estimators=40, random_state=0)
y_pred = forest.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True)
print(classification_report(y_test, y_pred))
acc6 = forest.score(X_test, y_test)
print(acc6)
classifier = XGBClassifier()
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
acc7 = accuracy_score(y_test, y_pred)
print(acc7)
mylist = []
mylist2 = []
mylist.append(acc1)
mylist2.append("Logistic Regression")
mylist.append(acc2)
mylist2.append("SVM")
mylist.append(acc3)
mylist2.append("KNN")
mylist.append(acc4)
mylist2.append("Naive Bayes")
mylist.append(acc5)
mylist2.append("DTR")
mylist.append(acc6)
mylist2.append("RF")
mylist.append(acc7)
mylist2.append("XGBoost")
plt.rcParams['figure.figsize'] = 8, 6
sns.set_style("darkgrid")
plt.figure(figsize=(22, 8))
ax = sns.barplot(x=mylist2, y=mylist, palette="mako", saturation=1.5)
plt.xlabel("Classification Models", fontsize=20)
plt.ylabel("Accuracy", fontsize=20)
plt.title("Accuracy of different Classification Models", fontsize=20)
plt.xticks(fontsize=11, horizontalalignment='center', rotation=8)
plt.yticks(fontsize=13)
for p in ax.patches:
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
ax.annotate(f'{height:.2%}', (x + width/2, y + height * 1.02), ha='center', fontsize='x-large')
plt.tight_layout()
plt.show()
else:
print("Invalid choice. Please select a valid option (1, 2, 3, or 4).") |
<!DOCTYPE html>
<html>
<head>
<title>Sign in</title>
<link rel="stylesheet" href="kloudone.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+CDgftzFkZxlUqrnclFr6k5jc5r5l5uSc6nNn5IX9tF5F5F5F5" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="text-center mb-3">
<div class="hexagon">
<i class="bi bi-chat-dots-fill chat-icon"></i>
</div>
</div>
<h1 class="text-center">SIGN UP</h1>
<form id="signupForm">
<div class="mb-3">
<i class="fas fa-user"></i>
<label for="username" class="form-label">Username:</label>
<input type="text" class="form-control violet-textbox" id="username" name="username" required>
</div>
<div class="mb-3">
<i class="fas fa-envelope"></i>
<label for="signupEmail" class="form-label">Email:</label>
<input type="email" class="form-control violet-textbox" id="signupEmail" name="signupEmail" required>
</div>
<div class="mb-3">
<i class="fas fa-lock"></i>
<label for="signupPassword" class="form-label">Password:</label>
<input type="password" class="form-control violet-textbox" id="signupPassword" name="signupPassword" required>
</div>
<div class="mb-3">
<i class="fas fa-lock"></i>
<label for="retypePassword" class="form-label">Retype Password:</label>
<input type="password" class="form-control violet-textbox" id="retypePassword" name="retypePassword" required>
</div>
<button type="submit" class="btn btn-primary btn-block btn-sm">Sign Up</button>
<p class="mt-3 text-center">Already have an account? <a href="login.html">Sign In</a></p>
</form>
<div id="message"></div>
</div>
<style>
.violet-textbox {
width: 100%;
padding: 10px;
margin-bottom: 10px;
background-color: #8117F0; /* Violet background color */
color: #fff; /* White text color */
border: none;
border-radius: 3px;
}
/* Social media container styles */
.social-media-container {
display: small;
justify-content: center;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: center; /* Adjust top margin as needed */
}
/* Social media icon styles */
.social-media-icon {
margin: 0 15px; /* Adjust the spacing between icons as needed */
text-decoration: none; /* Remove underlines from anchor tags */
color: #333; /* Text color (adjust as needed) */
}
.hexagon {
position: relative;
width: 60px;
height: 60px;
background-color: purple;
clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
margin: 0 auto;
}
.chat-icon {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 24px;
}
/* Social media icon hover effect */
.social-media-icon:hover {
color: #1003c8;
}
/* Reduce the button size */
.btn-sm {
padding: 5px 10px; /* You can adjust the padding as needed */
font-size: 14px; /* You can adjust the font size as needed */
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
const signupForm = document.getElementById("signupForm");
const messageDiv = document.getElementById("message");
// Signup Form Submission
signupForm.addEventListener("submit", function (e) {
e.preventDefault();
const username = document.getElementById("username").value;
const signupEmail = document.getElementById("signupEmail").value;
const signupPassword = document.getElementById("signupPassword").value;
const retypePassword = document.getElementById("retypePassword").value;
// Validate password match
if (signupPassword !== retypePassword) {
messageDiv.innerText = "Passwords do not match. Please try again.";
return;
}
// Store user details (you can replace this with your preferred method)
const user = {
username,
email: signupEmail,
password: signupPassword
};
// You can save the user object to localStorage or send it to a server
// localStorage.setItem("user", JSON.stringify(user));
// Display success message
messageDiv.innerText = "Registration successful. Welcome, " + username + "!";
// Redirect to another screen (replace 'dashboard.html' with the desired URL)
window.location.replace("dashboard.html");
signupForm.reset();
});
});
</script>
</body>
</html> |
import { Box, Typography, useTheme, TextField } from "@mui/material";
import DashboardBox from "@/components/DashboardBox";
import PlaceCenter from "@/components/PlaceCenter";
import FlexBetween from "@/components/FlexBetween";
import { useEffect, useState } from "react";
import Columns from "@/components/Columns";
// import { ChatOpenAI } from "langchain/chat_models/openai";
// import { HumanChatMessage, SystemChatMessage } from "langchain/schema";
// const chat = new ChatOpenAI({ temperature: 0 });
type Props = {};
const AskAi = (props: Props) => {
const [queryInput, setQueryInput] = useState<string>("");
const [response, setResponse] = useState<any>(null);
const { palette } = useTheme();
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setQueryInput(event.target.value);
};
useEffect(() => {
//AI Model
async function query(data: any) {
const response = await fetch(
"https://api-inference.huggingface.co/models/google/flan-t5-base",
{
headers: {
Authorization: "Bearer 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",
},
method: "POST",
body: JSON.stringify(data),
}
);
const result = await response.json();
setResponse(result );
}
const context = ""; // Set the initial context here
if (queryInput !== "") {
const fullInput = `${context} ${queryInput}`; // Concatenate the context and query input
query({ inputs: fullInput });
}
}, [queryInput]);
//textfield color
const inputProps = {
style: {
backgroundColor: "#45444d",
color: palette.grey[100],
width: "80%",
borderRadius: "1rem",
boxShadow:
"rgba(0, 0, 0, 0.25) 0px 54px 55px, rgba(0, 0, 0, 0.12) 0px -12px 30px, rgba(0, 0, 0, 0.12) 0px 4px 6px, rgba(0, 0, 0, 0.17) 0px 12px 13px, rgba(0, 0, 0, 0.09) 0px -3px 5px",
}, // Specify the desired text color here
};
//label style
const inputLabelProps = {
style: { color: palette.grey[100], fontWeight: "bold" }, // Specify the desired label color here
};
return (
<DashboardBox height="100%">
<FlexBetween>
<Box margin="2rem">
<Typography variant="h3">Intelligent Financial Assistant</Typography>
<Typography variant="h6">
powered by a large language model for AI-Driven Chat Interactions
with the database
</Typography>
</Box>
</FlexBetween>
<Box height="100%">
<PlaceCenter>
<Typography variant="h2" color={palette.grey[300]}>
{response && <pre>{JSON.stringify(response)}</pre>}
</Typography>
<PlaceCenter marginLeft="15%" width="80%">
<TextField
fullWidth
label="Ask A.I"
id="fullWidth"
type="text"
value={queryInput}
onChange={handleInputChange}
InputProps={inputProps}
InputLabelProps={inputLabelProps}
/>
</PlaceCenter>
</PlaceCenter>
</Box>
</DashboardBox>
);
};
export default AskAi; |
import type { Equal, Expect } from './test-utils'
type PersonInfo = {
name: 'Tom'
age: 30
married: false
addr: {
home: '123456'
phone: '13111111111'
}
hobbies: ['sing', 'dance']
}
type ExpectedResult = {
name: string
age: number
married: boolean
addr: {
home: string
phone: string
}
hobbies: [string, string]
}
type cases = [
Expect<Equal<ToPrimitive<PersonInfo>, ExpectedResult>>,
]
type ToPrimitive<T extends Record<PropertyKey, any>> = {
[P in keyof T]: T[P] extends Record<PropertyKey, any> ? ToPrimitive<T[P]> : (T[P] extends any[] ? [ToPrimitive<T[P][number]>] : T[P] extends string ? string : T[P] extends number ? number : T[P] extends boolean ? boolean : never)
} |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Tax
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Tax class collection
*
* @category Mage
* @package Mage_Tax
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Tax_Model_Resource_Class_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
/**
* Resource initialization
*/
public function _construct()
{
$this->_init('tax/class');
}
/**
* Add class type filter to result
*
* @param int $classTypeId
* @return Mage_Tax_Model_Resource_Class_Collection
*/
public function setClassTypeFilter($classTypeId)
{
return $this->addFieldToFilter('main_table.class_type', $classTypeId);
}
/**
* Retrieve option array
*
* @return array
*/
public function toOptionArray()
{
return $this->_toOptionArray('class_id', 'class_name');
}
/**
* Retrieve option hash
*
* @return array
*/
public function toOptionHash()
{
return $this->_toOptionHash('class_id', 'class_name');
}
} |
import React from "react";
import { useState, useEffect } from "react";
function Expenses() {
const [dailyTotal, setDailyTotal] = useState<number>(0);
const [percentage, setPercentage] = useState<number>(0);
const [myBalance, setMyBalance] = useState<number>(0);
const [days] = useState<string[]>([
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
]);
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
useEffect(() => {
getDays(year, day);
getPercentage();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const getDays = (year: number, month: number) => {
return new Date(year, month, 0).getDate();
};
function getPercentage(): void {
const totalDaysOfMonth = getDays(year, month);
if (totalDaysOfMonth <= 31) {
const totalPercentage =
(dailyTotal * totalDaysOfMonth) / parseInt(totalDaysOfMonth.toFixed(2));
return setPercentage(totalPercentage);
}
}
function clearTotal() {
setDailyTotal(0);
const balance: any = document.getElementById("balance");
if (balance.value !== "") {
balance.value = "";
}
}
return (
<section className="expense-section">
<article className="expense-section__container">
<div className="expense-section__container__amount">
<h1>My Balance</h1>
<input
id="balance"
name="balance"
type="number"
placeholder="Enter Your Balance"
/>
<button type="button" onClick={clearTotal}>
Clear
</button>
</div>
<div className="expense-section__container__chartCard">
<h2>Spending in the last - 7 days</h2>
<div className="chart">
{days.map((day, dayIndex) => (
<label key={dayIndex}>{day}</label>
))}
</div>
<div className="total-card">
<div className="total-card__content">
<h3>Total this month</h3>
<span>{dailyTotal}</span>
</div>
<div className="total-card__percentage">
<span>{percentage}</span>
<h4>from last month</h4>
</div>
</div>
</div>
</article>
</section>
);
}
export default Expenses; |
import {Schema} from "prosemirror-model";
export const schema = new Schema({
nodes: {
doc: {
content: '(block | test)+',
},
paragraph: {
content: 'inline*',
group: 'block',
parseDOM: [{tag: "p"}],
toDOM() { return ['p', 0] }
},
heading: {
attrs: {level: {default: 1}},
content: 'inline*',
group: 'block',
toDOM(node) { return ['h' + node.attrs.level, 0] }
},
blockquote: {
content: 'inline*',
group: 'block',
toDOM() { return ['blockquote', {class: "editor-blockquote"}, 0] }
},
divider: {
group: 'test',
selectable: false,
toDOM() { return ['div', {class: "editor-divider"}, ['hr']] }
},
listItem: {
content: 'inline*',
group: 'block',
parseDOM: [{tag: 'li'}],
toDOM() { return ['li', 0] }
},
bulletList: {
content: '(listItem | bulletList)*',
group: 'block',
parseDOM: [{tag: 'ul'}],
toDOM() { return ['ul', {class: "editor-bulletList"}, 0] }
},
text: {
group: 'inline'
},
link: {
content: 'text*',
selectable: false,
attrs: {href: {default: ''}},
inline: true,
group: 'inline',
toDOM(node) { return ['a', {class: "editor-link", href: node.attrs.href, contentEditable: false}, 0]}
},
},
marks: {
inlineCode: {
toDOM() {return ["code", {class: "editor-inlineCode"}]}
},
}
}); |
<!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>哈希表实现</title>
</head>
<body>
<script>
// 封装哈希表类
function HashTable () {
// 属性
this.storage = [] //元素存放的地方
this.count = 0 //已存放的个数
this.limit = 7 //数组总容量
//加载因子 loadFactor
// 方法
// 哈希函数
HashTable.prototype.hashFunc = function (str, size) {
// 1.定义hashCode变量
var hashCode = 0
// 2.霍纳算法,来计算hashCode的值
// cats -> Unicode编码
for (let i = 0; i < str.length; i++) {
hashCode = 37 * hashCode + str.charCodeAt(i)
}
// 3.取余操作
var index = hashCode % size
return index
}
// 插入&修改操作
HashTable.prototype.put = function (key, value) {
// 1.根据key获取对应的index
var index = this.hashFunc(key, this.limit)
// 2.根据index取出对应的bucket
var bucket = this.storage[index]
// 3.判断该bucket是否为null
if (bucket == null) {
bucket = []
this.storage[index] = bucket
}
// 4.判断是否是修改数据
for (let i = 0; i < bucket.length; i++) {
var tuple = bucket[i]
if (tuple[0] == key) {
tuple[1] = value
return true
}
}
// 5.进行添加操作
bucket.push([key, value])
this.count += 1
// 6.判断是否需要扩容操作
if (this.count > this.limit * 0.75) {
var newSize = this.limit * 2
var newPrime = this.getPrime(newSize)
this.resize(newSize)
}
}
// 获取操作
HashTable.prototype.get = function (key) {
// 1.根据key获取对应的index
var index = this.hashFunc(key, this.limit)
// 2.根据index取出对应的bucket
var bucket = this.storage[index]
// 3.判断该bucket是否为null
if (bucket == null) {
return null
}
// 4.有bucket,那么就进行线性查找
for (let i = 0; i < bucket.length; i++) {
var tuple = bucket[i]
if (tuple[0] == key) {
return tuple[1]
}
}
// 5.依然没有找到,那么返回null
return null
}
// 删除操作
HashTable.prototype.remove = function (key) {
// 1.根据key获取对应的index
var index = this.hashFunc(key, this.limit)
// 2.根据index取出对应的bucket
var bucket = this.storage[index]
// 3.判断该bucket是否为null
if (bucket == null) {
return null
}
// 4.有bucket,那么就进行线性查找,并且删除
for (let i = 0; i < bucket.length; i++) {
var tuple = bucket[i]
if (tuple[0] == key) {
bucket.splice(i, 1)
this.count -= 1
// 缩小容量
if (this.limit > 7 && this.count < this.limit * 0.25) {
var newSize = Math.floor(this.limit / 2)
var newPrime = this.getPrime(newSize)
this.resize(newPrime)
}
return tuple[1]
}
}
// 5.依然没有找到,那么返回null
return null
}
// 其他方法
// 判断哈希表是否为空
HashTable.prototype.isEmpty = function () {
return this.count == 0
}
// 获取哈希表中元素的个数
HashTable.prototype.size = function () {
return this.count
}
// 哈希表扩容
HashTable.prototype.resize = function (newLimit) {
// 1.保存旧的数组内容
var oldStorage = this.storage
// 2.重置所有的属性
this.storage = []
this.count = 0
this.limit = newLimit
// 3.遍历oldStorage中所有的bucket
for (let i = 0; i < oldStorage.length; i++) {
// 3.1取出对应的bucket
var bucket = oldStorage[i]
// 3.2判断bucket是否为null
if (bucket == null) {
continue
}
// 3.3bucket中有数据,那么取出数据,重新插入
for (let j = 0; j < bucket.length; j++) {
this.put(tuple[0], tuple[1])
}
}
}
// 判断某个数字是否是质数
HashTable.prototype.isPrime = function (num) {
for (let i = 2; i < num; i++) {
if (num % i == 0) {
return false
}
}
return true
}
// 获取质数的方法
HashTable.prototype.getPrime = function (num) {
while (!this.isPrime(num)) {
num += 1
}
return num
}
}
var ht = new HashTable()
ht.put('wjq', '21')
ht.put('dcr', '50')
ht.put('wzq', '52')
ht.put('wyy', '21')
console.log(ht.get('dcr'))
ht.put('dcr', '18')
console.log(ht.get('dcr'))
ht.remove('dcr')
console.log(ht.get('dcr'))
</script>
</body>
</html> |
// Copyright (C) 2015 Michael Biggs. See the COPYING file at the top-level
// directory of this distribution and at http://shok.io/code/copyright.html
#ifndef _statik_test_Test_h_
#define _statik_test_Test_h_
#include "STLog.h"
#include "statik/Batch.h"
#include <boost/lexical_cast.hpp>
#include <string>
namespace statik_test {
class Result {
public:
Result()
: pass(0), expect_fail(0), fail(0), error(0) {
}
unsigned pass;
unsigned expect_fail;
unsigned fail;
unsigned error;
};
class Test {
public:
Test(const std::string& name)
: m_name(name) {}
virtual ~Test() {}
void Init();
void Run();
std::string Name() const { return m_name; }
const Result& GetResult() const { return m_result; }
protected:
virtual void init() {}
virtual void run() = 0;
void pass(const std::string& msg = "");
void fail(const std::string& msg = "");
bool test(bool t, const std::string& msg = "");
template <typename T>
bool test(T actual, T expected, const std::string& msg = "") {
return test(actual == expected, msg + " (actual: " + boost::lexical_cast<std::string>(actual) + " expected: " + boost::lexical_cast<std::string>(expected) + ")");
}
template <typename T>
bool qtest(T actual, T expected, const std::string& msg = "") {
return qtest(actual == expected, msg + " (actual: " + boost::lexical_cast<std::string>(actual) + " expected: " + boost::lexical_cast<std::string>(expected) + ")");
}
template <typename T>
bool test_not(T actual, T unexpected, const std::string& msg = "") {
return test(actual != unexpected, msg + " (actual: " + boost::lexical_cast<std::string>(actual) + " unexpected: " + boost::lexical_cast<std::string>(unexpected) + ")");
}
template <typename T>
bool qtest_not(T actual, T unexpected, const std::string& msg = "") {
return qtest(actual != unexpected, msg + " (actual: " + boost::lexical_cast<std::string>(actual) + " unexpected: " + boost::lexical_cast<std::string>(unexpected) + ")");
}
bool test(const statik::Batch& actual, const statik::Batch& expected, const std::string& msg = "");
// Quiet (no message if pass)
void qpass();
bool qtest(bool t, const std::string& msg = "");
private:
Result m_result;
const std::string m_name;
};
}
#endif // _statik_test_Test_h_ |
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Container from '@mui/material/Container';
import Link from '@mui/material/Link';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import * as React from 'react';
import { useNavigate } from 'react-router-dom';
import useLocalStorage from '@/hooks/useLocalStorage';
import { useAppDispatch } from '@/store';
import { loginUser } from '@/store/slices/account';
import { ILoginForm } from '@/utils/types/accounts';
import { showNotification } from '@/utils/notification';
import { CircularProgress } from '@mui/material';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from "yup";
function Copyright(props: any) {
return (
<Typography variant="body2" color="text.secondary" align="center" {...props}>
{'Copyright © '}
<Link color="inherit" href="https://chat.openai.com/chat">
My best friend
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}
const maxUsername = 24
const formSchema = yup.object({
username: yup.string().required().max(maxUsername)
.matches(/^[a-z0-9_]+$/, 'Username can only contain lowercase letters, and numbers')
.test('no-spaces', 'Username cannot contain spaces', (value) => !/\s/.test(value)),
secret: yup.string()
}).required();
export default function LoginPage() {
const dispatch = useAppDispatch()
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: yupResolver(formSchema)
})
const [user] = useLocalStorage<ILoginForm | null>('user', null)
const [isLoading, setIsLoading] = React.useState(false)
const navigate = useNavigate();
React.useEffect(() => {
if (user) navigate('/chat');
}, [navigate, user]);
const handleLogin = async (data: any) => {
setIsLoading(true)
dispatch(loginUser(data))
.then(() => setIsLoading(false))
.catch((error) => showNotification(JSON.stringify(error)))
};
return (
<Container component="main" maxWidth="xs">
<Box
flexDirection='column'
display='flex'
mt={8}
alignItems='center'
>
<Avatar sx={{ m: 1, bgcolor: 'primary' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<Box component="form" onSubmit={handleSubmit(handleLogin)} sx={{ mt: 1 }}>
<TextField
margin="normal"
fullWidth
label="username"
autoFocus
error={!!errors.username}
helperText={!!errors.username && errors.username.message}
{...register('username')}
/>
<TextField
margin="normal"
fullWidth
label="Your secret"
{...register('secret')}
/>
<Button
type="submit"
fullWidth
variant="contained"
disabled={isLoading}
sx={{ mt: 3, mb: 2 }}
>
{isLoading ?
<CircularProgress size={30} /> :
'Sign In'
}
</Button>
</Box>
</Box>
<Copyright sx={{ mt: 8, mb: 4 }} />
</Container>
);
} |
package com.cootek.presentation.sdk.utils;
import android.util.Log;
import com.cootek.presentation.service.PresentationSystem;
import java.util.HashSet;
public class BackgroundThreadManager {
private static final String TAG = "BackgroundThreadManager";
private static BackgroundThreadManager sIns = new BackgroundThreadManager();
/* access modifiers changed from: private */
public HashSet<String> mRunningThreads = new HashSet<>();
private BackgroundThreadManager() {
}
public static BackgroundThreadManager getIns() {
return sIns;
}
public synchronized boolean startDownloadThread(String str, Runnable runnable) {
boolean z;
z = false;
if (runnable != null) {
if (canStartThread(str)) {
doStartThread(str, runnable);
z = true;
}
}
if (PresentationSystem.DUMPINFO) {
Log.d(TAG, "startDownloadThread tag: " + str + " ret: " + z);
}
return z;
}
private boolean canStartThread(String str) {
if (str == null || this.mRunningThreads.contains(str)) {
return false;
}
return true;
}
private void doStartThread(final String str, final Runnable runnable) {
this.mRunningThreads.add(str);
try {
new Thread(new Runnable() {
public void run() {
runnable.run();
BackgroundThreadManager.this.mRunningThreads.remove(str);
if (PresentationSystem.DUMPINFO) {
Log.d(BackgroundThreadManager.TAG, "thread: " + str + " finished!");
}
}
}).start();
} catch (IllegalThreadStateException e) {
this.mRunningThreads.remove(str);
}
}
} |
import React, { memo, useEffect, useMemo, useRef, useState } from 'react';
import styles from './DynamicBlur.module.scss';
import { debounce } from '#src/utils/common';
import Fade from '#components/Animation/Fade/Fade';
import Image from '#components/Image/Image';
import type { ImageData } from '#types/playlist';
type Props = {
image: ImageData;
transitionTime?: number;
debounceTime?: number;
};
type ImageCursor = {
image: ImageData;
visible: boolean;
loading: boolean;
key: string;
};
const DynamicBlur = ({ image, transitionTime = 1, debounceTime = 350 }: Props): JSX.Element => {
const [images, setImages] = useState<ImageCursor[]>([]);
const keyRef = useRef(0);
const updateImage = useMemo(
() =>
debounce((image) => {
setImages((current) => [
{
image,
visible: true,
loading: true,
key: `key_${keyRef.current++}`,
},
...current,
]);
}, debounceTime),
[debounceTime],
);
useEffect(() => {
if (image) updateImage(image);
}, [updateImage, image]);
const handleClose = (key: string) => {
setImages((current) => current.filter((image) => image.key !== key));
};
const handleLoad = (key: string) => {
setImages((current) =>
current.map((image) => {
if (image.key === key) {
return { ...image, loading: false };
}
return { ...image, visible: false };
}),
);
};
return (
<div className={styles.dynamicBlur}>
{images.map((cursor) => (
<Fade
duration={transitionTime * 1000}
open={cursor.visible && !cursor.loading}
delay={cursor.visible ? 100 : 0}
key={cursor.key}
onCloseAnimationEnd={() => handleClose(cursor.key)}
keepMounted
>
<Image className={styles.image} image={cursor.image} onLoad={() => handleLoad(cursor.key)} width={1280} />
</Fade>
))}
</div>
);
};
export default memo(DynamicBlur); |
import { useState } from "react";
const Spotify = {
GetToken() {
const [accessToken, setAccessToken] = useState("");
const [expiresIn, setExpiresIn] = useState(0);
const initiateAuth = () => {
let clientId = process.env.REACT_APP_NOT_SECRET_CODE;
const redirectUri = "https://evdmjammmingapp.netlify.app/";
window.location = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
};
const extractAccessToken = () => {
const url = new URL(window.location.href.replace(/#/g, "?"));
let urlAccessToken = new URLSearchParams(url.search).get("access_token");
let urlExpiresIn = Number.parseInt(
new URLSearchParams(url.search).get("expires_in")
);
if (urlAccessToken && urlExpiresIn) {
setAccessToken(urlAccessToken);
setExpiresIn(Number(urlExpiresIn));
window.setTimeout(() => setAccessToken(""), expiresIn * 1000);
}
return urlAccessToken;
};
if (accessToken === "") {
let token = extractAccessToken();
if (!token) initiateAuth();
return { token };
}
return accessToken;
},
async search(accessToken, term) {
debugger;
let response = await fetch(
`https://api.spotify.com/v1/search?q=${term}&type=track`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
let data = await response.json();
if (!data.tracks) {
return [];
}
return data.tracks.items.map((track) => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri,
}));
},
async savePlaylist(accessToken, name, trackUris) {
let saved = false;
if (!name || !trackUris) {
return;
}
let userId;
await fetch("https://api.spotify.com/v1/me", {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
.then((response) => response.json())
.then(async (data) => {
userId = data.id;
console.log("Got user ID");
await fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
// body: '{\n "name": "New Playlist",\n "public": true\n}',
body: JSON.stringify({ name: name }),
})
.then((response) => response.json())
.then(async (data) => {
const playlistId = data.id;
saved = true;
await fetch(
`https://api.spotify.com/v1/playlists/${playlistId}/tracks`,
{
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
// body: '{\n "uris": [\n "string"\n ],\n "position": 0\n}',
body: JSON.stringify({ uris: trackUris }),
}
).then((response) => {
return true;
});
});
});
return saved;
},
};
export default Spotify; |
/**********************************************************************************
* $URL: https://source.etudes.org/svn/apps/coursemap/trunk/coursemap-impl/impl/src/java/org/etudes/coursemap/impl/CourseMapMapImpl.java $
* $Id: CourseMapMapImpl.java 9692 2014-12-26 21:57:29Z ggolden $
***********************************************************************************
*
* Copyright (c) 2010, 2011, 2012, 2014 Etudes, Inc.
*
* 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 org.etudes.coursemap.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.etudes.coursemap.api.CourseMapItem;
import org.etudes.coursemap.api.CourseMapItemAccessStatus;
import org.etudes.coursemap.api.CourseMapItemProgressStatus;
import org.etudes.coursemap.api.CourseMapItemType;
import org.etudes.coursemap.api.CourseMapMap;
import org.sakaiproject.util.StringUtil;
/**
* CourseMapServiceImpl implements CourseMapService
*/
public class CourseMapMapImpl implements CourseMapMap
{
/** Clear Block on Close setting. */
protected Boolean clearBlockOnClose = Boolean.FALSE;
/** The context for which this map was prepared. */
protected transient String context = null;
/** If the user is a guest in the site. */
protected transient Boolean guest = Boolean.FALSE;
/** The ordered items. **/
protected List<CourseMapItem> items = new ArrayList<CourseMapItem>();
/** Mastery level - percent between 0 and 100, or null for not set. */
protected Integer masteryPercent = null;
/** Set with the new item index order for a map reordering. */
protected transient String newOrder = null;
/** Set when the map is all populated and ready to use. */
protected transient boolean ready = false;
/** The user id for which this map was prepared. */
protected transient String userId = null;
/** Keep track of changes. */
transient boolean changed = false;
/**
* Construct
*
* @param contetx
* The context.
*/
public CourseMapMapImpl(String context, String userId)
{
this.context = context;
this.userId = userId;
}
/**
* {@inheritDoc}
*/
public void acceptAllPositioned()
{
for (CourseMapItem item : this.items)
{
item.setPositioned(Boolean.TRUE);
}
}
/**
* {@inheritDoc}
*/
public CourseMapItem addHeaderBefore(CourseMapItem item)
{
// Note: this is bad - won't support concurrent editing (adding headers) from different UIs. Really needs to be some sort of DB mediated thing... -ggolden
// id - scan the existing headers for the biggest id
long biggestId = 0;
for (CourseMapItem header : this.items)
{
if (header.getType() == CourseMapItemType.header)
{
try
{
long headerId = Long.parseLong(header.getId(), 16);
if (headerId > biggestId) biggestId = headerId;
}
catch (NumberFormatException e)
{
}
}
}
// use the next in sequence
// a new id - use the current time for the id
String id = Long.toHexString(biggestId + 1);
// create the item
CourseMapItem header = new CourseMapItemImpl(id, null);
// where to put the header
int pos = 0;
if (item != null)
{
pos = this.items.indexOf(item);
if (pos == -1) pos = 0;
}
// put in the map
this.items.add(pos, header);
((CourseMapItemImpl) header).map = this;
// the map has changed
this.setChanged();
// return the header
return header;
}
/**
* {@inheritDoc}
*/
public void applyNewOrder()
{
// if no new order set, nothing to do
if (this.newOrder == null) return;
// parse the numbers
String[] indexStrs = StringUtil.split(this.newOrder, " ");
int size = indexStrs.length;
// if we don't have one for each item, something has gone wrong
if (size != this.items.size()) return;
int[] indexes = new int[size];
for (int i = 0; i < size; i++)
{
try
{
indexes[i] = Integer.parseInt(indexStrs[i]);
}
catch (NumberFormatException e)
{
// this is not good
return;
}
}
// if the new order is just the old order (numbers from 0..size-1), then nothing to do
boolean changed = false;
for (int i = 0; i < size; i++)
{
if (indexes[i] != i)
{
changed = true;
break;
}
}
if (!changed) return;
// ok, we have work to do
this.setChanged();
// form a new list that has items in indexes order from the old list
List<CourseMapItem> newItems = new ArrayList<CourseMapItem>();
for (int i = 0; i < size; i++)
{
newItems.add(this.items.get(indexes[i]));
}
this.items = newItems;
}
/**
* {@inheritDoc}
*/
public Boolean getClearBlockOnClose()
{
return this.clearBlockOnClose;
}
/**
* {@inheritDoc}
*/
public String getContext()
{
return this.context;
}
/**
* {@inheritDoc}
*/
public Boolean getFullyPositioned()
{
for (CourseMapItem item : this.items)
{
if (!item.getPositioned()) return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* {@inheritDoc}
*/
public CourseMapItem getItem(String id)
{
for (CourseMapItem item : this.items)
{
if (item.getMapId().equals(id)) return item;
}
return null;
}
/**
* {@inheritDoc}
*/
public CourseMapItem getItem(String title, Integer appCode)
{
for (CourseMapItem item : this.items)
{
if (item.getType().getAppCode().equals(appCode) && item.getTitle().equals(title)) return item;
}
return null;
}
/**
* {@inheritDoc}
*/
public CourseMapItem getItemBlocked(String id, CourseMapItemType type)
{
CourseMapItem rv = null;
for (CourseMapItem i : this.items)
{
// is this the item?
if (i.getType().getAppCode().equals(type.getAppCode()) && i.getId().equals(id))
{
break;
}
// is this a valid blocker?
if ((i.getAccessStatus() != CourseMapItemAccessStatus.invalid) && i.getEffectiveBlocker())
{
// give up if not mastered
if (!i.getMastered())
{
rv = i;
break;
}
}
}
// if found, the item was not blocked
return rv;
}
/**
* {@inheritDoc}
*/
public List<CourseMapItem> getItems()
{
return this.items;
}
/**
* {@inheritDoc}
*/
public Float getMasteryLevel()
{
if (this.masteryPercent == null) return null;
// convert from integer 0..100 to float 0..1
return Float.valueOf((float) this.masteryPercent / 100f);
}
/**
* {@inheritDoc}
*/
public Integer getMasteryPercent()
{
if (this.masteryPercent == null) return null;
return this.masteryPercent;
}
/**
* {@inheritDoc}
*/
public String getMasteryPercentDisplay()
{
if (this.masteryPercent == null) return "0%";
return this.masteryPercent.toString() + "%";
}
/**
* {@inheritDoc}
*/
public String getNewOrder()
{
return this.newOrder;
}
/**
* {@inheritDoc}
*/
public Integer getNumItemsMissed()
{
int count = 0;
for (CourseMapItem item : this.items)
{
// skip survey items to hide their activity
if (item.getType() == CourseMapItemType.survey) continue;
if (item.getType() == CourseMapItemType.fce) continue;
if ((item.getProgressStatus() == CourseMapItemProgressStatus.missed)
|| (item.getProgressStatus() == CourseMapItemProgressStatus.missedNoSub)) count++;
}
return Integer.valueOf(count);
}
/**
* {@inheritDoc}
*/
public String getUserId()
{
return this.userId;
}
/**
* {@inheritDoc}
*/
public void mergeItems(List<CourseMapItem> mergeItems)
{
// for the second pass
List<CourseMapItem> pass2 = new ArrayList<CourseMapItem>();
// run through all the items for the first pass
for (CourseMapItem mergeItem : mergeItems)
{
// find the item in the map items by id and type's application code
CourseMapItem found = null;
for (CourseMapItem i : this.items)
{
if (i.getType().getAppCode().equals(mergeItem.getType().getAppCode()) && i.getId().equals(mergeItem.getId()))
{
// set the map item to match
// Note: the map already knows about this item, so is not changed
((CourseMapItemImpl) i).set(mergeItem);
// if the item's open date is different from the stored open date, mark the item as not positioned
if (Different.different(i.getOpen(), i.getPreviousOpen()))
{
i.setPositioned(Boolean.FALSE);
}
// Note: positioned or not, if we find the item we leave it in place
found = i;
break;
}
}
// if not found, and the item has an open date, save for the next pass
if (found == null)
{
// Note: this indicates a new item, so the map has changed
setChanged();
// new item, set the prevOpen to open
((CourseMapItemImpl) mergeItem).initPreviousOpen();
if (mergeItem.getOpen() != null)
{
pass2.add(mergeItem);
}
// if no date, add it to the map
else
{
// should we insert it at the beginning?
if (mergeItem.getType().getInsert())
{
this.items.add(0, mergeItem);
}
// otherwise append it to the end
else
{
this.items.add(mergeItem);
}
}
}
}
// process any left, with open dates, into their proper date position
for (CourseMapItem mergeItem : pass2)
{
boolean found = false;
for (CourseMapItem i : this.items)
{
if (i.getOpen() != null)
{
// if we find an item in the map after this one, insert before
if (i.getOpen().after(mergeItem.getOpen()))
{
this.items.add(this.items.indexOf(i), mergeItem);
found = true;
break;
}
}
}
// if the mergeItem has a date after all the items, add it after the last dated item
if (!found)
{
for (int index = this.items.size() - 1; index >= 0; index--)
{
if (this.items.get(index).getOpen() != null)
{
this.items.add(index + 1, mergeItem);
found = true;
break;
}
}
}
// if still not found, (i.e. all items in the map have no open date) add it right after the last item marked for front-insertion
if (!found)
{
for (int index = this.items.size() - 1; index >= 0; index--)
{
if (this.items.get(index).getType().getInsert())
{
this.items.add(index + 1, mergeItem);
found = true;
break;
}
}
}
// if still not found, there are no dated items, and no front-insert items, so just add it in the front
if (!found)
{
this.items.add(0, mergeItem);
}
}
}
/**
* {@inheritDoc} Note: this version has un-positioned items "float" - get re-inserted each time by the auto-rules
*/
public void mergeItemsFloaters(List<CourseMapItem> mergeItems)
{
// for the second pass
List<CourseMapItem> pass2 = new ArrayList<CourseMapItem>();
// run through all the items for the first pass
for (CourseMapItem mergeItem : mergeItems)
{
// find the item in the map items by id and type's application code
CourseMapItem found = null;
CourseMapItem remove = null;
for (CourseMapItem i : this.items)
{
if (i.getType().getAppCode().equals(mergeItem.getType().getAppCode()) && i.getId().equals(mergeItem.getId()))
{
// set the map item to match
// Note: the map already knows about this item, so is not changed
((CourseMapItemImpl) i).set(mergeItem);
// if the item is positioned, keep it in position
if (i.getPositioned())
{
found = i;
}
// otherwise if the item is not yet positioned, remove it from the map and process it as new (found remains null)
else
{
// i now has mergeItem plus the stored settings
mergeItem = i;
// mark it for removal from the items
remove = i;
}
break;
}
}
// if we need to remove the item from out items, do it here outside the for iteration
if (remove != null)
{
this.items.remove(remove);
}
// if not found, and the item has an open date, save for the next pass
if (found == null)
{
// Note: this indicates a new item, so the map has changed
setChanged();
if (mergeItem.getOpen() != null)
{
pass2.add(mergeItem);
}
// if no date, add it to the map
else
{
// should we insert it at the beginning?
if (mergeItem.getType().getInsert())
{
this.items.add(0, mergeItem);
}
// otherwise append it to the end
else
{
this.items.add(mergeItem);
}
}
}
}
// process any left, with open dates, into their proper date position
for (CourseMapItem mergeItem : pass2)
{
boolean found = false;
for (CourseMapItem i : this.items)
{
if (i.getOpen() != null)
{
// if we find an item in the map after this one, insert before
if (i.getOpen().after(mergeItem.getOpen()))
{
this.items.add(this.items.indexOf(i), mergeItem);
found = true;
break;
}
}
}
// if the mergeItem has a date after all the items, add it after the last dated item
if (!found)
{
for (int index = this.items.size() - 1; index >= 0; index--)
{
if (this.items.get(index).getOpen() != null)
{
this.items.add(index + 1, mergeItem);
found = true;
break;
}
}
}
// if still not found, (i.e. all items in the map have no open date) add it right after the last item marked for front-insertion
if (!found)
{
for (int index = this.items.size() - 1; index >= 0; index--)
{
if (this.items.get(index).getType().getInsert())
{
this.items.add(index + 1, mergeItem);
found = true;
break;
}
}
}
// if still not found, there are no dated items, and no front-insert items, so just add it in the front
if (!found)
{
this.items.add(0, mergeItem);
}
}
}
/**
* {@inheritDoc}
*/
public void reInsertUnPositioned()
{
// collect the not positioned items
List<CourseMapItem> unpositioned = new ArrayList<CourseMapItem>();
for (CourseMapItem i : this.items)
{
if (!i.getPositioned())
{
unpositioned.add(i);
}
}
// remove these from the map
this.items.removeAll(unpositioned);
// put them back in the map
mergeItems(unpositioned);
}
/**
* {@inheritDoc}
*/
public void removeHeader(CourseMapItem header)
{
// remove the item
this.items.remove(header);
// the map has changed
setChanged();
}
/**
* {@inheritDoc}
*/
public void setClearBlockOnClose(Boolean setting)
{
if (setting == null) setting = Boolean.FALSE;
// set only if different
if (!Different.different(setting, this.clearBlockOnClose)) return;
this.clearBlockOnClose = setting;
setChanged();
}
/**
* {@inheritDoc}
*/
public void setMasteryPercent(Integer percent)
{
// auto-range
if (percent != null)
{
if (percent < 0) percent = Integer.valueOf(0);
if (percent > 100) percent = Integer.valueOf(100);
}
// set only if different
if (!Different.different(percent, this.masteryPercent)) return;
this.masteryPercent = percent;
setChanged();
}
/**
* {@inheritDoc}
*/
public void setNewOrder(String newOrder)
{
this.newOrder = newOrder;
// no change yet...
}
/**
* Clear the changed flags.
*/
protected void clearChanged()
{
this.changed = false;
}
/**
* @return TRUE if the item has changed, FALSE if not.
*/
protected boolean getChanged()
{
return this.changed;
}
/**
* @return TRUE if the map's user is a guest in the site, FALSE if not.
*/
protected Boolean getIsGuest()
{
return this.guest;
}
/**
* Get the map ready to use, once fully populated.
*/
protected void init()
{
if (this.ready) return;
// trim items not populated
for (Iterator<CourseMapItem> i = this.items.iterator(); i.hasNext();)
{
CourseMapItem item = i.next();
// use a null title as an indicator - but don't drop any headers
if ((item.getType() != CourseMapItemType.header) && (item.getTitle() == null))
{
i.remove();
// Note: this item was in the map and is no longer, so the map has changed
setChanged();
}
// let the item know it is in this map
((CourseMapItemImpl) item).map = this;
}
this.ready = true;
}
/**
* Set the map has been changed.
*/
protected void setChanged()
{
this.changed = true;
}
/**
* Set the map as belonging to a guest.
*/
protected void setIsGuest()
{
this.guest = Boolean.TRUE;
}
} |
package bank.online.security;
import java.nio.charset.StandardCharsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import bank.online.security.jwt.AuthEntryPointJwt;
import bank.online.security.jwt.AuthTokenFilter;
import bank.online.security.services.UserDetailsServiceImpl;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public SpringTemplateEngine springTemplateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}
@Bean
public SpringResourceTemplateResolver htmlTemplateResolver() {
SpringResourceTemplateResolver pdfTemplateResolver = new SpringResourceTemplateResolver();
pdfTemplateResolver.setPrefix("classpath:/templates/");
pdfTemplateResolver.setSuffix(".html");
pdfTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
pdfTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return pdfTemplateResolver;
}
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/roles/**").permitAll()
.antMatchers("/user/**").permitAll()
.antMatchers("/joints/**").permitAll()
.antMatchers("/devises/**").permitAll()
.antMatchers("/reseau-paiements/**").permitAll()
.antMatchers("/carte-bancaires/**").permitAll()
.antMatchers("/credit-paiements/**").permitAll()
.antMatchers("/credits/**").permitAll()
.antMatchers("/ws/**").permitAll()
.antMatchers("/chiffre-affaires/**").permitAll()
.antMatchers("/notifications/**").permitAll()
.antMatchers("/chats/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
} |
import React, { createContext, useState } from "react";
export const AuthContext = createContext<{
isLoggedIn: boolean;
user?: {
id: number;
username: string;
profilePicture?: string;
};
setIsLoggedIn: (value: boolean) => void;
setUser: (
value: { id: number; username: string; profilePicture?: string } | null
) => void;
}>({
isLoggedIn: false,
user: null,
setIsLoggedIn: () => {},
setUser: () => {},
});
const AuthProvider: React.FC = ({ children }) => {
const [user, setUser] = useState<{
id: number;
username: string;
profilePicture?: string;
} | null>(null);
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<AuthContext.Provider value={{ isLoggedIn, user, setUser, setIsLoggedIn }}>
{children}
</AuthContext.Provider>
);
};
export default AuthProvider; |
# SHCの情報の認証と基準
SHCのフォーマットは発行元が認証可能な[JWS](https://datatracker.ietf.org/doc/html/rfc7515)
を実装しています。
使用の方法は、図での説明が[SHC生成過程](https://www.dxhealth.jp/blogs/%E5%AE%9F%E8%A3%85%E4%BE%8B/SHC%E7%94%9F%E6%88%90%E9%81%8E%E7%A8%8B) で表示されていますが、そのうちのデコードの部分を
下記に示していきます。
## ペイロードとヘッダ
QRCodeをデコードすると、中身はshc://のプロトコルの様な記入から始まります。
[IAMANA](https://www.iana.org/assignments/uri-schemes/prov/shc)
その次にQR Codeで情報を伝えられない量の情報が入っている場合はその何番目のQR Codeかという情報が
入っています。(こちらはDeprecatedになっています。)
その次に数が順列されます。例は下記の様なものtです。
```
shc:/56762909524320603460....
```
最後の "shc:/\<number\>"
これは [rfc7797#section-5.2](https://datatracker.ietf.org/doc/html/rfc7797#section-5.2)
に基づき、UTF-8のキャラクターを2Digitsづつで表した数字です。
これをUTF-8のキャラクターに変更すると、下記の様になります。
```
RUxMMTFXOifQ.KGJiFWI.OGZq1bUT
```
実際にはもう少し多いキャラクターになりますが、大きく二つのドットで分けられる3つのパートになります。
3つのパートが
<ヘッダ>.<ペイロード>.<参照ハッシュ>
となります。そのうち、ヘッダとペイロードはBase64のデコードし、そのバッファを
UTF-8 で エンコードし、JSONのフォーマットとして、パースできるようになります。
このフォーマットは(JWT-JSON Web Token)[https://www.w3.org/TR/vc-data-model/#jwt-encoding]
の仕様に基づいています。またこちらには日本語による[JWTの説明](https://tex2e.github.io/rfc-translater/html/rfc7519.html) 内容は(https://jwt.io/)[https://jwt.io/] のツールなどを使い、decodeできます。
がされています。
この中身は発行元のパブリックキーにより改ざんされていない証明書ということを確認できます。
パート1:ヘッダ(header)
パート2:ペイロード(payload)
パート3 :参照ハッシュ(Verify Signiture)
## 認証のプロセス
1. パート1のヘッダの中か"kid" を取得します。
2. パート2 のペイロードの中にISSが記入されています。
3. ステップ2を利用し、パブリックキーを取得します。
4. JOSELibraryを使用し、ステップ3で取得したJWSのパブリックキーを利用し、
改ざんされていないかチェックします。
## JWSのパブリックキーの取得
このセクションではどのようにパブリックキーを取得するかを説明します。
パート2のペイロードには Base64 でデコードし、UTF-8のキャラクターにエンコードすると、
発行元と発行元からパブリックキーを探すBase URLが *iss* が
入っています。
そこに ".well-known/jwks.json" を追加し、その中に、多目的に使用されている
発行済のパブリックキーのリストがあります。
~~~~
例で言うと日本のCovid18のワクチンのQRコードのヘッダのISSは現在、
https://vc.vrs.digital.go.jp/issuer となっています。
そこに、".well-known/jwks.json" を追加し、
https://vc.vrs.digital.go.jp/issuer/.well-known/jwks.json
~~~~
を取得します。
'keys'のフィールドから
```
"kty": "EC", "use": "sig", and "alg": "ES256"
```
にマッチし、また *kid* フィールドがステップ1の*kid*と同じパブリックキーをJOSEライブラリに
読み込ませます。ここでいうパブリックキーとは下記のようなJSONのオブジェクトです。
```
{
"kty": "EC",
"kid": "f1vhQP9oOZkityrguynQqB4aVh8u9xcf3wm4AFF4aVw",
"use": "sig",
"alg": "ES256",
"x5c": [
"MIIByjCCAXGgAwIBAg...=",
"MIIBlTCCATugAwIBA...=="
],
"crv": "P-256",
"x": "ViKBgZ0f3pQKv-tSz653HUtIzCS8TVSNu1Hwi0tKpSk",
"y": "01177apKXH2HgGfkn71ZPEljWk0Q2fcEzY2_XOfL_Zc"
}
```
パブリックキーを読み込ませた、JOSE ライブラリでJWKの <base64header>.<base64payload>.<verifykey>
を改ざんされていないか検証します。
実装の際には[各言語のJOSEライブラリ](#%E5%90%84%E8%A8%80%E8%AA%9E%E3%81%AEjose%E3%83%A9%E3%82%A4%E3%83%96%E3%83%A9%E3%83%AA)の項目各言語でライブラリが用意されています。
## VCIへの登録確認作業
前記の項目でSHCの発行元は認証できました。しかし、どの機関でもSHCは基準に従えば、発行できてしまいます。
まだ発行元が公式にVCI Directoryに登録されている発行元妥当ことを確認する必要があります。
payloadの中の iss の値を再び使用します。
最新の[VerifiedIssuer](https://github.com/the-commons-project/vci-directory/blob/main/vci-issuers.json)JSONを獲得し、その中の"participating_issuers"の中にissの値があるか確認します。
issがあれば、登録確認済みとなります。
## 各言語のJOSEライブラリ
### Java:
[Nimbus JOSE + JWT](https://connect2id.com/products/nimbus-jose-jwt) : A comprehensive library for working with JWT (JSON Web Tokens) and related specifications, including JWS verification.
### Ruby:
[ruby-jwt](https://github.com/potatosalad/ruby-jose/blob/master/docs/GettingStarted.md): A library that provides JWT and JWS support in Ruby. It allows you to verify JWS tokens and extract the payload.
### JavaScript:
[node-jose](https://github.com/cisco/node-jose) : A JavaScript implementation of the JSON Object Signing and Encryption (JOSE) for current web browsers and node.js-based servers. This library implements (wherever possible) all algorithms, formats, and options in JWS, JWE, JWK, and JWA and uses native cryptographic support (WebCrypto API or node.js' "crypto" module) where feasible.
[jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken): A widely used library for handling JWT and JWS in JavaScript. It provides functions to verify JWS tokens and extract the payload.
### Go:
[go-jose](https://github.com/go-jose/go-jose): A powerful library for working with JOSE standards in Go. It includes support for JWS verification and token validation.
### Python:
[PyJWT](https://github.com/jpadilla/pyjwt): A popular library for handling JWT in Python. It supports JWS verification and provides functions to extract the payload.
# Thank you!
この文章を制作するために御協力頂いた[MinaCare](https://www.minacare.co.jp/) Teamの方々, ありがとうございました。
# Reference
[spec.smarthealthfcards](https://spec.smarthealth.cards/) |
---
title: "5 Tactics to Spot - and Survive - a Devious Mimic in Phasmophobia!"
ShowToc: true
date: "2023-04-28"
author: "Anne Kidd"
---
*****
# 5 Tactics to Spot - and Survive - a Devious Mimic in Phasmophobia!
Phasmophobia is a unique and thrilling video game that places players in the shoes of ghost hunters tasked with investigating paranormal activity. One of the most challenging ghosts to face in the game is the Mimic. Mimics are mischievous apparitions that can take on the appearance of any object in the game. This includes furniture, doors, and even other players. In this article, we will explore five tactics to spot, and survive, a devious Mimic in Phasmophobia!
## Understanding Mimic Behavior
Before we dive into the tactics to spot and survive a Mimic in Phasmophobia, it's essential to understand their behavior. Mimics are highly unpredictable and can quickly shift between their ghost form and an object in the game. They cannot be detected by standard ghost-hunting equipment such as EMF readers and Thermometers. However, they do emit a faint humming noise that can be heard when they are near.
## 1. Keep an Ear out for Humming Sounds.
As mentioned earlier, Mimics emit a faint humming noise when they are near. It's vital to keep your ears open and listen for this sound. If you hear a humming noise that is not coming from your equipment, there's a good chance that a Mimic is close. You should also keep a close watch on your teammate's movements. If you notice someone who seems to be acting out of character or not interacting with the game environment, there is a chance they could be a Mimic in disguise.
## 2. Check Your Equipment
Although Mimics cannot be detected by standard equipment, they can still interact with the game environment. For instance, they can trigger motion sensors, trip wire sensors, and sound sensors. If you notice any of your equipment getting triggered without a clear reason, it's essential to investigate immediately. It's possible that a Mimic is playing games with you, and you should be ready for any surprises.
## 3. Experiment with Objects
One of the most challenging aspects of Mimics is their ability to take on the appearance of any object in the game. However, there are some ways to experiment with objects to see if they are a Mimic in disguise. For instance, if you shine your flashlight at an object, and it does not cast a shadow, there is a good chance that it is a Mimic. Additionally, if you toss an object and it disappears, it's safe to assume that it was a Mimic.
## 4. Stay Vigilant in Large Spaces
Mimics are highly unpredictable and dangerous in large spaces. They can quickly move from one object to another and keep you guessing. If you're in a large space, it's essential to keep a close eye on your environment and stay vigilant. If you notice any strange occurrences, investigate them immediately. You should also keep your equipment close at hand and use it to scan your surroundings for any abnormalities.
## 5. Work with Your Team
Finally, working with your team is crucial in surviving a Mimic encounter in Phasmophobia. Mimics can quickly overwhelm a lone player, so it's essential to have someone watching your back. Communicate with your teammates and coordinate your movements to maximize your chances of survival. If you notice any strange behavior, alert your team immediately, and work together to investigate.
In conclusion, Mimics are some of the most challenging ghosts to face in Phasmophobia. They are highly unpredictable and can quickly shift between their ghost form and an object in the game. However, by keeping your ears open, experimenting with objects, and staying vigilant in large spaces, you can increase your chances of surviving a Mimic encounter. Most importantly, work with your team, communicate effectively, and be ready for any surprises that come your way!
{{< youtube OA2VvVAhqho >}}
It can be quite difficult to find or identify a Mimic while playing Phasmophobia. As per the game’s description, it has the ability to copy the behaviour and trait of others and ghosts. This ability can make it really annoying to guess which ghost you are facing. Thankfully though this ghost also has several ways to let you identify itself. So in this guide let us take a look at how to identify and find a Mimic in Phasmophobia.
## How to Find & Identify a Mimic
The game tells you there are four pieces of evidence to find in order to identify a mimic in Phasmophobia. Three are given directly and one is hinted in its weakness, they are:
- Spirit Box: It allows you to talk to ghosts. This tool costs $50.
- Fingerprints: You need to use UV light to illuminate the area where you are looking for fingerprints for evidence.
- Orbs: You can use the video camera & tripods as well to look for any ghost orbs. Both of these tools’ combined cost is $75.
- Freezing Temperatures: You can identify if the area you are in has freezing temperatures using a thermometer. This tool costs $30. Although if you can’t buy a thermometer then you can also look out for your character’s breath.
Mimic is known for leaving a trail of ghost orbs behind. But the biggest giveaway here is its ability to mimic other ghosts, as the name suggests. So while playing normal mode you can use the above ways to identify a mimic. And as for the nightmare more it can leave any 3 of the above 4 pieces of evidence for you to identify.
### Things you should look out for when facing a Mimic
- Pieces of evidence: If you find any three of the evidence mentioned above then it is a Mimic.
- Behaviour: Mimic can copy the Behaviour of other ghosts but not their evidence. So if you are getting different behaviours then there is a high chance you are facing a Mimic.
That covers everything you should know to find and identify a Mimic in Phasmophobia. If you need other help with this game then check our guides on ghost types and how to use every item in the game. |
package com.lisboaworks.algafood.core.email;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
@Component
@Validated
@ConfigurationProperties("algafood.email")
@Getter
@Setter
public class EmailProperties {
@NotNull
private String sender;
@NotNull
private EmailSendingServiceImpl impl = EmailSendingServiceImpl.MOCK;
private Sandbox sandbox = new Sandbox();
@Getter
@Setter
public class Sandbox {
private String receiver;
}
public enum EmailSendingServiceImpl {
MOCK, SANDBOX, SMTP
}
} |
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local React = require(ReplicatedStorage.Packages.React)
local ReactRoblox = require(ReplicatedStorage.Packages.ReactRoblox)
local RoactSpring = require(ReplicatedStorage.Packages.RoactSpring)
local e = React.createElement
local function createUpdater(initialProps, initialDeps)
local test = {}
local function Test(_)
local springProps, update = React.useState({ initialProps, initialDeps })
test.update = function(newProps, newDeps)
update({ newProps, newDeps })
task.wait(0.1)
end
test.styles, test.api = RoactSpring.useSpring(springProps[1], springProps[2])
return nil
end
local root = ReactRoblox.createRoot(Instance.new("Folder"))
root:render(ReactRoblox.createPortal({
App = e(Test),
}, ReplicatedStorage))
task.wait()
while not root do
task.wait()
end
return test
end
return function()
describe("useSpring", function()
describe("when only a prop object is passed", function()
it("can animate supported data types", function()
local test = createUpdater({
number = 0,
udim = UDim.new(0, 0),
udim2 = UDim2.new(0, 0, 0, 0),
vector2 = Vector2.new(0, 0),
vector3 = Vector3.new(0, 0, 0),
color3 = Color3.fromRGB(0, 0, 0),
})
expect(test.styles.number:getValue()).to.equal(0)
expect(test.styles.udim:getValue()).to.equal(UDim.new(0, 0))
expect(test.styles.udim2:getValue()).to.equal(UDim2.new(0, 0, 0, 0))
expect(test.styles.vector2:getValue()).to.equal(Vector2.new(0, 0))
expect(test.styles.vector3:getValue()).to.equal(Vector3.new(0, 0, 0))
expect(test.styles.color3:getValue()).to.equal(Color3.fromRGB(0, 0, 0))
test.update({
number = 100,
udim = UDim.new(100, 200),
udim2 = UDim2.new(100, 200, 300, 400),
vector2 = Vector2.new(100, 200),
vector3 = Vector3.new(100, 200, 300),
color3 = Color3.fromRGB(255, 255, 255),
})
task.wait(1)
expect(test.styles.number:getValue()).to.be.near(100, 10)
expect(test.styles.udim:getValue().Scale).to.near(100, 10)
expect(test.styles.udim:getValue().Offset).to.near(200, 20)
expect(test.styles.udim2:getValue().X.Scale).to.near(100, 10)
expect(test.styles.udim2:getValue().X.Offset).to.near(200, 20)
expect(test.styles.udim2:getValue().Y.Scale).to.near(300, 30)
expect(test.styles.udim2:getValue().Y.Offset).to.near(400, 40)
expect(test.styles.vector2:getValue().X).to.be.near(100, 10)
expect(test.styles.vector2:getValue().Y).to.be.near(200, 20)
expect(test.styles.vector3:getValue().X).to.be.near(100, 10)
expect(test.styles.vector3:getValue().Y).to.be.near(200, 20)
expect(test.styles.vector3:getValue().Z).to.be.near(300, 30)
expect(test.styles.color3:getValue().R).to.be.near(1, 0.1)
expect(test.styles.color3:getValue().G).to.be.near(1, 0.1)
expect(test.styles.color3:getValue().B).to.be.near(1, 0.1)
end)
it("should set style instantly when immediate prop is passed", function()
local test = createUpdater({
x = 0,
immediate = true,
})
expect(test.styles.x:getValue()).to.equal(0)
test.update({ x = 1 })
expect(test.styles.x:getValue()).to.equal(1)
end)
end)
describe("when both a prop object and a deps array are passed", function()
it("should only update when deps change", function()
local test = createUpdater({
x = 0,
immediate = true,
}, { 1 })
expect(test.styles.x:getValue()).to.equal(0)
test.update({ x = 1 }, { 1 })
expect(test.styles.x:getValue()).to.equal(0)
test.update({ x = 1 }, { 2 })
expect(test.styles.x:getValue()).to.equal(1)
end)
end)
describe("when only a function is passed", function()
it("can animate supported data types", function()
local test = createUpdater(function()
return {
number = 0,
udim = UDim.new(0, 0),
udim2 = UDim2.new(0, 0, 0, 0),
vector2 = Vector2.new(0, 0),
vector3 = Vector3.new(0, 0, 0),
color3 = Color3.fromRGB(0, 0, 0),
}
end)
expect(test.styles.number:getValue()).to.equal(0)
expect(test.styles.udim:getValue()).to.equal(UDim.new(0, 0))
expect(test.styles.udim2:getValue()).to.equal(UDim2.new(0, 0, 0, 0))
expect(test.styles.vector2:getValue()).to.equal(Vector2.new(0, 0))
expect(test.styles.vector3:getValue()).to.equal(Vector3.new(0, 0, 0))
expect(test.styles.color3:getValue()).to.equal(Color3.fromRGB(0, 0, 0))
test.api
.start({
number = 100,
udim = UDim.new(100, 200),
udim2 = UDim2.new(100, 200, 300, 400),
vector2 = Vector2.new(100, 200),
vector3 = Vector3.new(100, 200, 300),
color3 = Color3.fromRGB(255, 255, 255),
config = { tension = 500 },
})
:await()
expect(test.styles.number:getValue()).to.equal(100)
expect(test.styles.udim:getValue()).to.equal(UDim.new(100, 200))
expect(test.styles.udim2:getValue()).to.equal(UDim2.new(100, 200, 300, 400))
expect(test.styles.vector2:getValue()).to.equal(Vector2.new(100, 200))
expect(test.styles.vector3:getValue()).to.equal(Vector3.new(100, 200, 300))
expect(test.styles.color3:getValue()).to.equal(Color3.fromRGB(255, 255, 255))
end)
it("should set style instantly when immediate prop is passed", function()
local test = createUpdater(function()
return { x = 0, immediate = true }
end)
expect(test.styles.x:getValue()).to.equal(0)
test.api.start({ x = 1 }):await()
expect(test.styles.x:getValue()).to.equal(1)
end)
it("should never update on render", function()
local test = createUpdater(function()
return { x = 0, immediate = true }
end)
expect(test.styles.x:getValue()).to.equal(0)
test.update(function()
return { x = 1 }
end)
expect(test.styles.x:getValue()).to.equal(0)
end)
end)
end)
end |
/* eslint-disable no-unused-vars */
/* eslint-disable comma-dangle */
// ** React Imports
// ** Third Party Components
import { User, X } from 'react-feather'
import { useState } from 'react'
// ** Reactstrap Imports
import {
Modal,
Input,
Label,
Button,
ModalHeader,
ModalBody,
InputGroup,
InputGroupText,
Form,
} from 'reactstrap'
// ** Styles
import '@styles/react/libs/flatpickr/flatpickr.scss'
import { testTypeService } from '../../../services/testTypeService'
import { useForm, Controller } from 'react-hook-form'
import { Slide, toast } from 'react-toastify'
// import MixTestType from "./MixTestType"
const defaultValues = {
code: '',
name: '',
basePrice: '',
getSampleAtHomePrice: '',
mix: [],
sum2: '2',
sum3: '3',
sum4: '4',
sum5: '5',
sum6: '6',
sum7: '7',
sum8: '8',
sum9: '9',
sum10: '10',
price2: null,
price3: null,
price4: null,
price5: null,
price6: null,
price7: null,
price8: null,
price9: null,
price10: null,
}
const AddNewModal = ({ open, handleModal, setRefreshTable }) => {
// ** State
// const [code, setCode] = useState()
// const [description, setDescription] = useState()
const [totalSumary, setTotalSumary] = useState([])
// ** Custom close btn
const CloseBtn = (
<X className='cursor-pointer' size={15} onClick={handleModal} />
)
const {
control,
handleSubmit,
formState: { errors },
} = useForm({ defaultValues })
// const mix = [
// {
// number: 2,
// price: 880000
// },
// {
// number: 2,
// price: 880000
// }
// ]
const add = () => {
setTotalSumary((prevState) => [...prevState, { sum: '', price: '' }])
}
const remove = () => {
setTotalSumary((prevState) => prevState.slice(0, -1))
}
// }
const onSubmit = (data) => {
const dataSend = {
code: data.code,
name: data.name,
price: parseFloat(data.basePrice),
getSampleAtHomePrice: parseFloat(data.getSampleAtHomePrice),
groupPrices: [],
}
if (data.price2 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum2),
price: parseFloat(data.price2),
})
}
if (data.price3 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum3),
price: parseFloat(data.price3),
})
}
if (data.price4 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum4),
price: parseFloat(data.price4),
})
}
if (data.price5 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum5),
price: parseFloat(data.price5),
})
}
if (data.price6 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum6),
price: parseFloat(data.price6),
})
}
if (data.price7 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum7),
price: parseFloat(data.price7),
})
}
if (data.price8 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum8),
price: parseFloat(data.price8),
})
}
if (data.price9 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum9),
price: parseFloat(data.price9),
})
}
if (data.price10 !== 0) {
dataSend.groupPrices.push({
quantity: parseFloat(data.sum10),
price: parseFloat(data.price10),
})
}
testTypeService
.create(dataSend)
.then((r) => {
handleModal()
setRefreshTable()
toast.success('Thêm mới loại xét nghiệm thành công !', {
position: 'top-right',
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
transition: Slide,
pauseOnHover: true,
draggable: true,
progress: undefined,
})
})
.catch((err) => {
toast.error('Thêm mới loại xét nghiệm thất bại!', {
position: 'top-right',
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
transition: Slide,
pauseOnHover: true,
draggable: true,
progress: undefined,
})
})
}
return (
<Modal
isOpen={open}
toggle={handleModal}
className='sidebar-lg'
modalClassName='modal-slide-in'
contentClassName='pt-0'
>
<ModalHeader
className='mb-1'
toggle={handleModal}
close={CloseBtn}
tag='div'
>
<h5 className='modal-title'>Thêm loại xét nghiệm</h5>
</ModalHeader>
<ModalBody className='flex-grow-1'>
<Form onSubmit={handleSubmit(onSubmit)}>
<div className='mb-1'>
<Label className='form-label' for='code'>
Mã code
</Label>
<InputGroup>
<InputGroupText>
<User size={15} />
</InputGroupText>
<Controller
rules={{
required: true,
}}
name='code'
control={control}
render={({ field }) => (
<Input
id='code'
placeholder='PCR'
invalid={errors.code && true}
{...field}
/>
)}
/>
{/*<Input id='full-name' placeholder='PCR' onChange={e => setCode(e.target.value)}/>*/}
</InputGroup>
</div>
<div className='mb-1'>
<Label className='form-label' for='name'>
Mô tả
</Label>
<InputGroup>
<InputGroupText>
<User size={15} />
</InputGroupText>
<Controller
rules={{
required: true,
}}
name='name'
control={control}
render={({ field }) => (
<Input
id='name'
placeholder='Realtime PCR'
invalid={errors.name && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<Label className='form-label' for='basePrice'>
Đơn giá
</Label>
<InputGroup>
<InputGroupText>
<User size={15} />
</InputGroupText>
<Controller
rules={{
required: true,
}}
name='basePrice'
control={control}
render={({ field }) => (
<Input
id='basePrice'
placeholder='500.000 VND'
invalid={errors.basePrice && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<Label className='form-label' for='getSampleAtHomePrice'>
Phí lấy mẫu tại nhà
</Label>
<InputGroup>
<InputGroupText>
<User size={15} />
</InputGroupText>
<Controller
rules={{
required: true,
}}
name='getSampleAtHomePrice'
control={control}
render={({ field }) => (
<Input
id='getSampleAtHomePrice'
placeholder='500.000 VND'
invalid={errors.getSampleAtHomePrice && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<div className='d-flex justify-content-between'>
<Label className='form-label me-1' for='basePrice'>
Giá gộp
</Label>
{/* <div>
<Button
className='me-1'
color='primary'
type='button'
size='sm'
onClick={add}
>
+
</Button>
<Button
className='me-1'
color='danger'
type='button'
size='sm'
onClick={remove}
>
-
</Button>
</div> */}
</div>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum2`}
control={control}
render={({ field }) => (
<Input
id={`sum2`}
placeholder='2'
invalid={errors.sum2 && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price2`}
control={control}
render={({ field }) => (
<Input
id={`price2`}
placeholder='200.000 VND'
invalid={errors.price2 && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum3`}
control={control}
render={({ field }) => (
<Input
id={`sum3`}
placeholder='3'
invalid={errors.sum3 && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price3`}
control={control}
render={({ field }) => (
<Input
id={`price3`}
placeholder='300.000 VND'
invalid={errors.sum3 && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum4`}
control={control}
render={({ field }) => (
<Input
id={`sum4`}
placeholder='4'
invalid={errors.sum4 && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price4`}
control={control}
render={({ field }) => (
<Input
id={`price4`}
placeholder='400.000 VND'
invalid={errors.price4 && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum5`}
control={control}
render={({ field }) => (
<Input
id={`sum5`}
placeholder='5'
invalid={errors.sum5 && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price5`}
control={control}
render={({ field }) => (
<Input
id={`price5`}
placeholder='500.000 VND'
invalid={errors.price5 && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum6`}
control={control}
render={({ field }) => (
<Input
id={`sum6`}
placeholder='6'
invalid={errors.sum6 && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price6`}
control={control}
render={({ field }) => (
<Input
id={`price6`}
placeholder='600.000 VND'
invalid={errors.code && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum7`}
control={control}
render={({ field }) => (
<Input
id={`sum7`}
placeholder='7'
invalid={errors.sum7 && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price7`}
control={control}
render={({ field }) => (
<Input
id={`price7`}
placeholder='700.000 VND'
invalid={errors.code && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum8`}
control={control}
render={({ field }) => (
<Input
id={`sum8`}
placeholder='8'
invalid={errors.code && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price8`}
control={control}
render={({ field }) => (
<Input
id={`price8`}
placeholder='800.000 VND'
invalid={errors.price8 && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum9`}
control={control}
render={({ field }) => (
<Input
id={`sum9`}
placeholder='9'
invalid={errors.code && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price9`}
control={control}
render={({ field }) => (
<Input
id={`price5`}
placeholder='900.000 VND'
invalid={errors.price9 && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div className='mb-1'>
<InputGroup>
<Controller
rules={
{
// required: true,
}
}
name={`sum10`}
control={control}
render={({ field }) => (
<Input
id={`sum10`}
placeholder='9'
invalid={errors.sum10 && true}
{...field}
/>
)}
/>
<Controller
rules={
{
// required: true,
}
}
name={`price10`}
control={control}
render={({ field }) => (
<Input
id={`price10`}
placeholder='1000.000 VND'
invalid={errors.code && true}
{...field}
/>
)}
/>
</InputGroup>
</div>
<div>{/*<MixTestType mixArr={mix}/>*/}</div>
<Button className='me-1' color='primary' type='submit'>
Xác nhận
</Button>
<Button color='secondary' onClick={handleModal} outline>
Hủy
</Button>
</Form>
</ModalBody>
</Modal>
)
}
export default AddNewModal |
#include "binary_trees.h"
/**
* heap_to_sorted_array - Converts a Binary Max Heap to a sorted array-integer.
*
* @heap: A pointer to the root node of the heap to convert.
* @size: An address to store the size of the array.
*
* Return: Sorted in descending order
*/
int *heap_to_sorted_array(heap_t *heap, size_t *size)
{
size_t heap_size;
int *list;
int extract_num, i = 0;
if (!heap)
return (NULL);
heap_size = binary_tree_size(heap);
*size = heap_size;
list = malloc(heap_size * sizeof(int));
if (!list)
return (NULL);
while (heap)
{
extract_num = heap_extract(&heap);
list[i] = extract_num;
i++;
}
return (list);
} |
## Introdução
Essa página tem como objetivo verificar os artefatos da Primeira Entrega do [grupo 8](https://requisitos-de-software.github.io/2024.1-Consumidor.gov/).
## Metodologia
Nessa página sobre a entrega 2 é possível se observar a verificação de todos os artefatos dessa mesma entrega sendo ele [Rich Picture](https://requisitos-de-software.github.io/2024.1-Consumidor.gov/Pr%C3%A9%20Rastreabilidade/rich-picture/). A verificação foi realizada utilizando a Tabela 1 como template.
<font size="3"><p style="text-align: center">Tabela 1: Template para verificação</p></font>
<center>
Critérios | Avaliação | Fonte
--|--|--
Pergunta para avaliação| Sim/Não/Incompleto| Página e livro de referência
</center>
#### Comentários
Os comentários relacionados a cada artefato serão detalhados aqui.
### Rich Picture
- Aqui é possível encontrar a origem do artefato verificado [Rich Picture](https://requisitos-de-software.github.io/2024.1-Consumidor.gov/Pr%C3%A9%20Rastreabilidade/rich-picture/).
<font size="3"><p style="text-align: center">Tabela 2: Verificação de Rich Picture</p></font>
Critérios | Sim/Não/Incompleto | Fonte
--------- | ------ | ------
1 - O Rich Picture identifica e expressa claramente os componentes vitais do problema ? | sim | <a id="RP1" href="#TEC1">p. 2</a>
2 - O Rich Picture utiliza imagens, figuras, palavras-chave e rótulos descritivos para contar uma história ? | sim | <a id="RP1" href="#TEC1">p. 2</a>
3 - O Rich Picture comunica quem está processando quais dados, para qual propósito, e os fluxos de informação dentro do sistema ? | sim | <a id="RP1" href="#TEC1">p. 2</a>
4 - Inclui uma declaração do problema no centro da página ? | incompleto | <a id="RP1" href="#TEC1">p. 3</a>
5 - Contém todas as palavras-chave relevantes ao redor da declaração do problema ? | sim | <a id="RP1" href="#TEC1">p. 3</a>
6 - Utiliza imagens e diagramas para representar conceitos e relacionamentos, evitando excesso de palavras ? | sim | <a id="RP1" href="#TEC1">p. 3</a>
7 - Identifica todos os atores no domínio do problema, com rótulos descritivos (e.g., Manager, Clerk)? | sim | <a id="RP1" href="#TEC1">p. 4</a>
8 - Identifica as operações que cada ator precisa realizar, representadas como círculos ou ovais com rótulos descritivos? | incompleto | <a id="RP1" href="#TEC1">p. 4</a>
9 - Identifica os requisitos de dados de cada operação, incluindo onde os dados serão armazenados e a direção do fluxo de dados entre atores, operações e armazenamentos? | Não | <a id="RP1" href="#TEC1">p. 4</a>
10 - Representa os armazenamentos de dados (e.g., tabelas do banco de dados, arquivos) como retângulos, com indicações do tipo de dados que contêm? | incompleto | <a id="RP1" href="#TEC1">p. 4</a>
11 - Utiliza setas para mostrar a direção do fluxo de dados ou informações entre atores, armazenamentos de dados e operações, com rótulos descritivos para a natureza dos dados ou informações? | incompleto | <a id="RP1" href="#TEC1">p. 4</a>
12 - Desenha a linha de delimitação do sistema para definir a área de responsabilidade, representada como uma linha circular (pode ser sólida ou tracejada)? | sim | <a id="RP1" href="#TEC1">p. 4</a>
13 - O Rich Picture mostra claramente o que está dentro da responsabilidade do sistema e o que está fora? | sim | <a id="RP1" href="#TEC1">p. 4</a>
14 - O Rich Picture comunica sua mensagem de forma eficaz, sendo compreensível para todos os membros da equipe e stakeholders? | incompleto | <a id="RP1" href="#TEC1">p. 5</a>
<font size="3"><p style="text-align: center">Fonte: [Amanda](https://github.com/acamposs) & [Bianca Castro](https://github.com/BiancaPatrocinio7)</p></font>
<center>
<a href="https://www.youtube.com/watch?v=kdfem2lYwrU" target="blanket"><strong>Vídeo 1</strong> - Verificação do Rich Picture</a>
<iframe width="560" height="315" src="https://www.youtube.com/embed/kdfem2lYwrU?si=acuI5RUfhHC6z2I7" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</center>
#### Comentários
1. a ambiguidade existente entre as nomeações da tabela de dados "empresas" e o ator "empresa"
2. Seria interessante adicionar uma descrição breve em todas as setas para indicar o fluxo dos dados e deixar o rich piicture ainda mais claro e objetivo
## Referências Bibliográficas
> <a id="RP1" href="#TEC1">1.</a> CTEC2402 - Software Development Project. Introducing Rich Pictures. Aprender 3. Distrito Federal. Disponível em: https://aprender3.unb.br/pluginfile.php/2844957/mod_resource/content/2/1_5145791542719414573.pdf. Acesso em: 10 jun. 2024.
## Histórico de Versões
| Versão | Data | Descrição | Autor(es) | Data da revisão | Revisor(es) |
| :--: | :--: | :--: | :--: | :--: | :--: |
|`1.0` | 10/06/2024 | Criação do documento. |[José Filipi](https://github.com/JoseFilipi) | 10/06/2024| |
import {
Table,
Model,
Column,
ForeignKey,
HasOne,
HasMany,
Default,
BelongsTo,
UpdatedAt,
CreatedAt,
Scopes,
DataType
} from 'sequelize-typescript'
import { Optional } from 'sequelize'
import User from './user.model'
import GroupRoster from './group-roster.model'
import GroupMessage from './group-message.model'
import GroupLastMessage from './group-last-message.model'
import FolderGroupRoster from './folder-group-roster.model'
import GroupMessageUnread from './group-message-unread.model'
import { defaultGroupChatAvatarImage } from '../../utils/constants'
export interface GroupAttributes {
id: string
creator_id: string
name: string
avatar: string
updated_at: Date
created_at: Date
}
export type GroupCreationAttributes = Optional<GroupAttributes, 'id' | 'updated_at' | 'created_at'>
@Scopes(() => ({
roster: ({}: any) => {
return {
include: [{
model: GroupRoster.scope([{ method: ['user', {}] }]),
as: 'roster'
}]
}
},
messages: ({ whereMessages }: any) => {
return {
include: [{
model: GroupMessage.scope([
{ method: ['author', {}] },
{ method: ['unread', {}] }
]),
as: 'messages',
where: whereMessages
}]
}
},
lastMessage: ({}: any) => {
return {
include: [{
model: GroupLastMessage.scope([{ method: ['message', {}] }]),
as: 'last_message'
}]
}
},
creator: ({}: any) => {
return {
include: [{
model: User.scope(['safe']),
as: 'creator'
}]
}
},
unreadMessages: ({}: any) => {
return {
include: [{
model: GroupMessageUnread.scope([{ method: ['message', {}] }]), as: 'unread_messages'
}]
}
}
}))
@Table({ tableName: 'groups' })
class Group extends Model<GroupAttributes, GroupCreationAttributes> {
@Default(DataType.UUIDV4)
@Column({ type: DataType.UUID, primaryKey: true })
declare id: string
@ForeignKey(() => User)
@Column({ type: DataType.UUID, primaryKey: true })
declare creator_id: string
@Column({ type: DataType.STRING })
declare name: string
@Default(defaultGroupChatAvatarImage)
@Column({ type: DataType.STRING })
declare avatar: string
@UpdatedAt
declare updated_at: Date
@CreatedAt
declare created_at: Date
// Associations
@BelongsTo(() => User)
declare creator: User
@HasMany(() => GroupRoster)
declare roster: GroupRoster[]
@HasMany(() => GroupMessage)
declare messages: GroupMessage[]
@HasOne(() => GroupLastMessage)
declare last_message: GroupLastMessage
@HasMany(() => GroupMessageUnread)
declare unread_messages: GroupMessageUnread[]
@HasMany(() => FolderGroupRoster)
declare folder_roster: FolderGroupRoster[]
}
export default Group |
import 'package:flutter/material.dart';
import 'package:metal_collector/bottom-navigation-custom-widget.dart';
import 'package:metal_collector/models/item-collection.dart';
import 'package:metal_collector/services/artist-service.dart';
import 'package:metal_collector/services/firebase-services/artist-firebase-services.dart';
import 'package:metal_collector/services/firebase-services/items-metal-collection-services.dart';
// Asegúrate de importar tus otros archivos y modelos necesarios aquí
import 'package:metal_collector/widgets/artist-basic-card-widget.dart';
class ItemCollectionScreen extends StatefulWidget {
@override
_ItemCollectionScreenState createState() => _ItemCollectionScreenState();
}
class _ItemCollectionScreenState extends State<ItemCollectionScreen> {
List<ItemCollection> allCollections = [];
List<ItemCollection> displayedCollections = [];
List<Artist> artists = [];
Artist? selectedArtist;
final serviceArtist = ArtistFirebaseService();
final serviceItemCollection = ItemMetalCollectorService();
List<String> _suggestions = [];
TextEditingController _controller = TextEditingController();
// void onTextChanged(String text) async {
// if (text.isNotEmpty) {
// var results = await serviceItemCollection.searchItems(text);
// setState(() {
// _suggestions =
// results.map((item) => item?.?.toString() ?? '').toList();
// });
// } else {
// setState(() {
// _suggestions = [];
// });
// }
// }
@override
void initState() {
super.initState();
fetchData();
}
Future<void> fetchData() async {
allCollections = await serviceItemCollection.fetchItems();
setState(() {
displayedCollections = List.from(allCollections);
});
}
void filterByArtist() {
// Tu lógica para filtrar por artista...
}
void clearFilter() {
// Tu lógica para limpiar el filtro...
}
deleteItem(String itemId) async {
// Aquí puedes añadir tu lógica para eliminar un ítem
await serviceItemCollection
.deleteItem(itemId); // Llama a tu servicio para eliminar el ítem
fetchData();
// Luego, actualiza el estado para reflejar la eliminación
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Item Collections")),
body: Column(
children: [
// Tu widget de Autocomplete y botón de limpiar filtro...
TextField(
controller: _controller,
// onChanged: onTextChanged,
onChanged: (String value) async {
allCollections = await serviceItemCollection.searchItems(value);
setState(() {
displayedCollections = List.from(allCollections);
});
}),
Expanded(
child: ListView.builder(
itemCount: displayedCollections.length,
itemBuilder: (context, index) {
final item = displayedCollections[index];
final artist = displayedCollections[index]
.artists; // Asegúrate de que esta línea obtenga correctamente el artista
return Card(
elevation: 4,
margin: EdgeInsets.all(8),
child: Column(
children: [
ListTile(
title: Text(item.name),
subtitle: Text(item.itemType),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () async => deleteItem(item
.itemId!), // Llama a deleteItem cuando se presione el ícono
),
),
if (artist != null)
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: ArtistCard(artist: artist),
),
],
),
);
},
),
),
],
),
bottomNavigationBar: BottomNavigationCustomWidgetPage(),
);
}
} |
import { Controller, Get, Post, Body, Param, Delete, Inject } from "@nestjs/common";
import { CreateProjectDto } from "./dto/create-project.dto";
import { CreateProjectUseCase } from "./use-cases/create-project.use-case";
import { ListProjectsUseCase } from "./use-cases/list-projects.use-case";
import { GetProjectUseCase } from "./use-cases/get-project.use-case";
import { DeleteProjectUseCase } from "./use-cases/delete-project.use-case";
import { StartProjectDto } from "./dto/start-project.dto";
import { StartProjectUseCase } from "./use-cases/start-project.use-case";
import { CancelProjectDto } from "./dto/cancel-project.dto";
import { CancelProjectUseCase } from "./use-cases/cancel-project.use-case";
@Controller("projects")
export class ProjectsController {
@Inject(CreateProjectUseCase)
private readonly createProjectUseCase: CreateProjectUseCase;
@Inject(ListProjectsUseCase)
private readonly listProjectsUseCase: ListProjectsUseCase;
@Inject(GetProjectUseCase)
private readonly getProjectUseCase: GetProjectUseCase;
@Inject(DeleteProjectUseCase)
private readonly deleteProjectUseCase: DeleteProjectUseCase;
@Inject(StartProjectUseCase)
private readonly startProjectUseCase: StartProjectUseCase;
@Inject(CancelProjectUseCase)
private readonly cancelProjectUseCase: CancelProjectUseCase;
constructor() {}
@Post()
create(@Body() createProjectDto: CreateProjectDto) {
return this.createProjectUseCase.execute(createProjectDto);
}
@Get()
findAll() {
return this.listProjectsUseCase.execute();
}
@Get(":id")
findOne(@Param("id") id: string) {
return this.getProjectUseCase.execute(id);
}
@Post(":id/start")
start(@Param("id") id: string, @Body() startProjectDto: StartProjectDto) {
return this.startProjectUseCase.execute(id, startProjectDto);
}
@Post(":id/cancel")
cancel(@Param("id") id: string, @Body() cancelProjectDto: CancelProjectDto) {
return this.cancelProjectUseCase.execute(id, cancelProjectDto);
}
@Delete(":id")
remove(@Param("id") id: string) {
return this.deleteProjectUseCase.execute(id);
}
} |
@*//-----------------------------------------------------------------------
// Copyright 2019 Sitecore Corporation A/S
// 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.
// -------------------------------------------------------------------------------------------*@
@using System.Web.Mvc.Html
@using Sitecore.XA.Foundation.MarkupDecorator.Extensions
@using Sitecore.XA.Foundation.SitecoreExtensions.Extensions
@using Sitecore.Commerce.XA.Foundation.Common.ExtensionMethods
@using Sitecore.Commerce.XA.Feature.Cart.Models
@using Sitecore.Mvc
@using ComponentDataSource = Sitecore.Commerce.XA.Feature.Cart.CartFeatureConstants.ShoppingCart.DataSourceFields;
@model ShoppingCartLinesRenderingModel
@{
var currentItem = Html.Sitecore().CurrentItem;
var productDetailsLabel = Html.Sitecore().Field(ComponentDataSource.ProductDetailsLabel, Html.Sitecore().CurrentItem, new { Parameters = new Sitecore.Collections.SafeDictionary<string> { { "title", @Model.ProductDetailsTooltip } } });
var unitPriceLabel = Html.Sitecore().Field(ComponentDataSource.UnitPriceLabel, Html.Sitecore().CurrentItem, new { Parameters = new Sitecore.Collections.SafeDictionary<string> { { "title", @Model.UnitPriceTooltip } } });
var quantityLabel = Html.Sitecore().Field(ComponentDataSource.QuantityLabel, Html.Sitecore().CurrentItem, new { Parameters = new Sitecore.Collections.SafeDictionary<string> { { "title", @Model.QuantityTooltip } } });
var totalLabel = Html.Sitecore().Field(ComponentDataSource.TotalLabel, Html.Sitecore().CurrentItem, new { Parameters = new Sitecore.Collections.SafeDictionary<string> { { "title", @Model.ProductTotalTooltip } } });
var discountLabel = currentItem[ComponentDataSource.DiscountLabel];
var savingsLabel = currentItem[ComponentDataSource.SavingLabel];
var deliveryLabel = currentItem[ComponentDataSource.DeliveryLabel];
var addressLabel = currentItem[ComponentDataSource.AddressLabel];
}
<div @Html.Sxa().Component("cxa-shoppingcartlines-component", Model.Attributes) data-cxa-component-class="CartLines" data-cxa-component-initialized="false" data-cxa-component-model="CartLinesViewModel" data-cxa-component-type="component">
@if (!String.IsNullOrWhiteSpace(Model.ErrorMessage))
{
<div class="error-message">
@Model.ErrorMessage
</div>
}
else
{
<div class="component-content" data-bind="with: cart">
<div class="shopping-cart-lines">
<table>
@if (Model.DisplayTableHeader)
{
<thead>
<tr>
<th colspan="2" title="@Model.ProductDetailsTooltip">@productDetailsLabel</th>
<th title="@Model.UnitPriceTooltip">@unitPriceLabel</th>
<th title="@Model.QuantityTooltip">@quantityLabel</th>
<th title="@Model.ProductTotalTooltip" class="total-header">@totalLabel</th>
<th class="delete-row"> </th>
</tr>
</thead>
}
<tbody data-bind="foreach: cartLines">
<tr>
<td class="shoppingcart-image">
<a data-bind="attr:{'href' : productUrl}"><img data-bind="attr: {src: image}" alt="" pid="image" /></a>
</td>
<td class="shoppingcart-info">
<a data-bind="attr:{'href' : productUrl}">
<h5 class="displayName" data-bind="text: displayName"></h5>
</a>
<div class="product-variant-information" data-bind="foreach: properties">
<div class="variant-information">
<span class="variant-label" data-bind="text: label"></span>
<span class="variant-value" data-bind="text: value"></span>
</div>
</div>
@if (Model.DisplayShippingInformation)
{
<p class="shoppingcart-delivery" data-bind="if: shippingMethodName">
<span>@deliveryLabel</span>
<span class="shippingMethodName" data-bind="text: shippingMethodName"></span>
</p>
<div class="shoppingcart-delivery" data-bind="if: address">
<span>@addressLabel</span>
<ul class="lineShippingAddress">
<li>
<span data-bind="text: address.Address1"></span>
<span data-bind="text: address.City"></span>
</li>
<li>
<span data-bind="text: address.State"></span>
<span data-bind="text: address.ZipPostalCode"></span>
</li>
<li>
<span data-bind="text: address.Country"></span>
</li>
</ul>
</div>
}
</td>
@if (Model.DisplayUnitPriceColumn)
{
<td class="shoppingcart-price">
<span class="price" data-bind="text: linePrice"></span>
<p data-bind="visible: discountOfferNames.length > 0">
<span>@discountLabel</span>
<span data-bind="text: discountOfferNames" class="shoppingcart-saving"></span>
</p>
</td>
}
@if (Model.DisplayQuantityColumn)
{
<td class="shoppingcart-quantity">
<div>
<button class="decrease" data-bind="event: { click: $parents[1].decreaseQuantity }, disable: $parents[1].quntityUpdating" style="display: none"></button>
<input class="quantity" min="1" type="number" placeholder="1" data-bind="event: { change: $parents[1].updateQuantity }, value: quantity, valueUpdate: 'input', fireChange:true, attr: {'data-ajax-lineitemid': externalCartLineId}, disable: $parents[1].quntityUpdating">
<button class="increase" data-bind="event: { click: $parents[1].increaseQuantity } , disable: $parents[1].quntityUpdating" style="display: none"></button>
</div>
</td>
}
<td class="shoppingcart-total">
<span class="total" data-bind="text: lineTotal"></span>
<p data-bind="visible: discountOfferNames.length > 0">
<span>@savingsLabel</span>
<span data-bind="text: lineItemDiscount" class="shoppingcart-total-saving"></span>
</p>
</td>
@if (Model.DisplayDeleteButtonColumn)
{
<td class="shoppingcart-delete">
<a class="remove-line" data-bind="attr: {'data-ajax-lineitemid': externalCartLineId}"><span data-bind="click: $parents[1].removeItem"></span></a>
<!-- HabitatHome customization -->
@if (Sitecore.Context.IsLoggedIn)
{
<button class="btn add-to-wishlist" data-bind="attr: {'data-ajax-lineitemid': externalCartLineId}, click: $parents[1].addItemToWishList, visible: sublines().length === 0">
<i class="fa"></i>
<span>Move to My Wish List</span>
</button>
}
<!-- end HabitatHome customization -->
</td>
}
</tr>
@if (Model.DisplaySubLines)
{
<!-- ko foreach: sublines -->
<tr class="subline-row">
<td colspan="3">
<div class="flex-container">
<div class="shoppingcart-image td">
<a data-bind="attr:{'href' : productUrl}"><img data-bind="attr: {src: image}" alt="" pid="image"/></a>
</div>
<div class="shoppingcart-info td">
<a data-bind="attr:{'href' : productUrl}">
<h5 class="displayName" data-bind="text: displayName"></h5>
</a>
<div class="product-variant-information" data-bind="foreach: properties">
<div class="variant-information">
<span class="variant-label" data-bind="text: label"></span>
<span class="variant-value" data-bind="text: value"></span>
</div>
</div>
</div>
</div>
</td>
<td colspan="1" class="shoppingcart-quantity td">
<text>@quantityLabel: </text> <lable class="quantity" data-bind="text: quantity"/>
</td>
<td colspan="2"></td>
</tr>
<!-- /ko -->
}
</tbody>
</table>
</div>
</div>
}
</div> |
<div class="register-container">
<form [formGroup]="form" class="register-form" (ngSubmit)="register()">
<div class="mb-3">
<h2 class="mb-2">Sign Up</h2>
<p>Already have an account? <a href="/login" class="ml-1">Sing In</a></p>
</div>
<div class="field mb-1">
<div class="control input-float">
<input type="text" class="input mt-4" name="username" formControlName="username" placeholder="Username"
required minlength="3" maxlength="10">
<label for="username"></label>
</div>
</div>
<ng-container *ngIf="form.get('username')?.touched">
<div class="form-label text-danger error-fix" *ngIf="form.get('username')?.errors?.['required']">Username is
required!</div>
<div class="form-label text-danger error-fix" *ngIf="form.get('username')?.errors?.['minlength']">Username
should have at least 3 characters!</div>
<div class="form-label text-danger error-fix" *ngIf="form.get('username')?.errors?.['maxlength']">Username
shouldn't have more than 10!
characters!</div>
</ng-container>
<div class="field mb-4">
<div class="control input-float">
<input type="text" class="input mt-4" name="city" formControlName="city" placeholder="City" required
minlength="3" maxlength="20">
<label for="city"></label>
</div>
</div>
<ng-container *ngIf="form.get('city')?.touched">
<div class="form-label text-danger error" *ngIf="form.get('city')?.errors?.['required']">City is required!
</div>
<div class="form-label text-danger error" *ngIf="form.get('city')?.errors?.['minlength']">City should have
at least 3 characters!</div>
<div class="form-label text-danger error" *ngIf="form.get('city')?.errors?.['maxlength']">City shouldn't
have more than 20!
characters!</div>
</ng-container>
<div class="field mb-1">
<div class="control input-float">
<input type="text" class="input" name="email" formControlName="email" placeholder="Email" required
pattern="^[a-zA-Z0-9\.-]{4,}@[a-z]+\.[a-z]+$">
<label for="email"></label>
</div>
</div>
<ng-container *ngIf="form.get('email')?.touched">
<div class="form-label text-danger error-fix" *ngIf="form.get('email')?.errors?.['required']">Email is
required!</div>
<div class="form-label text-danger error-fix" *ngIf="form.get('email')?.errors?.['invalidEmail']">Email
should be valid!</div>
</ng-container>
<div class="field mb-4">
<div class="control input-float">
<textarea class="input mt-4" type="text" placeholder="I'm good guy who loves computer games..."
name="personalInfo" formControlName="personalInfo" required minlength="10" maxlength="7000">
</textarea>
<label for="personalInfo"></label>
</div>
</div>
<ng-container *ngIf="form.get('personalInfo')?.touched">
<div class="form-label text-danger error" *ngIf="form.get('personalInfo')?.errors?.['required']">Personal
information is required!</div>
<div class="form-label text-danger error" *ngIf="form.get('personalInfo')?.errors?.['minlength']">Personal
information should have at least 10 characters!</div>
<div class="form-label text-danger error" *ngIf="form.get('personalInfo')?.errors?.['maxlength']">Personal
information cannot have more than 7000 characters!
characters!</div>
</ng-container>
<div class="field mb-4">
<div class="control input-float">
<input type="password" class="input" name="password" formControlName="password" placeholder="Password"
required minlength="3" maxlength="12">
<label for="password"></label>
</div>
</div>
<ng-container *ngIf="form.get('password')?.touched">
<div class="form-label text-danger error" *ngIf="form.get('password')?.errors?.['required']">Password is
required!</div>
<div class="form-label text-danger error" *ngIf="form.get('password')?.errors?.['minlength']">Password
should have more than 3
characters!</div>
<div class="form-label text-danger error" *ngIf="form.get('password')?.errors?.['maxlength']">Password
should have less 12
characters!</div>
</ng-container>
<div class="field mb-4">
<div class="control input-float">
<input type="password" class="input" name="rePassword" formControlName="rePassword"
placeholder="Repeat Password">
<label for="repeat-password"></label>
</div>
</div>
<ng-container *ngIf="form.get('rePassword')?.touched">
<div class="form-label text-danger error" *ngIf="form.get('rePassword')?.errors?.['required']">
Repeat-password is required!</div>
<div class="form-label text-danger error" *ngIf="form.get('rePassword')?.errors?.['invalidPasswords']">
Passwords must be equal!</div>
</ng-container>
<div class="field mb-4">
<div class="control input-float">
<input type="text" class="input" name="avatar" formControlName="avatar" placeholder="https://" required
pattern="^https?://.+">
<label for="avatar"></label>
</div>
</div>
<ng-container *ngIf="form.get('avatar')?.touched">
<div class="form-label text-danger error" *ngIf="form.get('avatar')?.errors?.['required']">Avatar is
required!</div>
<div class="form-label text-danger error" *ngIf="form.get('avatar')?.errors?.['pattern']">You must give a
URL!
characters!</div>
</ng-container>
<div>
<button class="btn-register mt-2 p-2">Sign Up</button>
</div>
</form>
</div> |
fn main() {
let mut user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com");
let user2 = User {
email: String::from("another@example.com"),
..user1
};
let mut black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
black.0 = 1;
let subject = AlwaysEqual;
let mut p = Point2 { x: 0, y: 0 };
let x = &mut p.x;
*x += 1;
println!("{}, {}", p.x, p.y);
}
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
fn build_user(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
struct AlwaysEqual;
struct Point2 {
x: i32,
y: i32,
} |
import { useEffect, useState} from 'react';
import { Link } from 'react-router-dom';
export default function Blog() {
const [articles, setArticles] = useState([]);
const [loading, setLoading] = useState(true);
/* Fetch the api */
useEffect(function () {
document.title = 'Blog';
async function getArticles() {
const request = await fetch(
'https://api.spaceflightnewsapi.net/v3/articles'
);
const response = await request.json();
setArticles(response);
// console.log(response);
setLoading(false);
}
getArticles();
}, []);
return (
<section className="section">
<h1 className="section-title">Blog Page</h1>
<p className="section-description">Berikut ini adalah tulisan-tulisan ku tapi boong</p>
{loading && (<i>Loading articles ... </i>)}
{!loading && (
<div className="articles">
{articles.map(function(article) {
return(
<article key={article.id} className="article">
<h2 className="article-title">
<Link to={`/blog/${article.id}`}>{article.title}></Link>
</h2>
<time className="article-time">
{new Date(article.publishedAt).toLocaleDateString()}
</time>
</article>
)
})}
</div>
)}
</section>
)
} |
; AutoHotkey script that enables you to use GPT3 in any input field on your computer
; -- Configuration --
#SingleInstance ; Allow only one instance of this script to be running.
; This is the hotkey used to autocomplete prompts
HOTKEY_AUTOCOMPLETE = #o ; Win+o
; This is the hotkey used to edit prompts
HOTKEY_INSTRUCT = #+o ; Win+shift+o
; Models settings
MODEL_AUTOCOMPLETE_ID := "gpt-3.5-turbo"
MODEL_AUTOCOMPLETE_MAX_TOKENS := 200
MODEL_AUTOCOMPLETE_TEMP := 0.8
MODEL_INSTRUCT_ID := "text-davinci-edit-001"
; -- Initialization --
; Dependencies
; WinHttpRequest: https://www.reddit.com/comments/mcjj4s
; cJson.ahk: https://github.com/G33kDude/cJson.ahk
#Include <Json>
http := WinHttpRequest()
I_Icon = GPT3-AHK.ico
IfExist, %I_Icon%
Menu, Tray, Icon, %I_Icon%
Hotkey, %HOTKEY_AUTOCOMPLETE%, AutocompleteFcn
Hotkey, %HOTKEY_INSTRUCT%, InstructFcn
OnExit("ExitFunc")
IfNotExist, settings.ini
{
InputBox, API_KEY, Please insert your OpenAI API key, API key, , 270, 145
IniWrite, %API_KEY%, settings.ini, OpenAI, API_KEY
}
Else
{
IniRead, API_KEY, settings.ini, OpenAI, API_KEY
}
Return
; -- Main commands --
; Edit the phrase
InstructFcn:
GetText(CutText, "Cut")
InputBox, UserInput, Text to edit "%CutText%", Enter an instruction, , 270, 145
if ErrorLevel {
PutText(CutText)
}else{
url := "https://api.openai.com/v1/edits"
body := {}
body.model := MODEL_INSTRUCT_ID ; ID of the model to use.
body.input := CutText ; The prompt to edit.
body.instruction := UserInput ; The instruction that tells how to edit the prompt
headers := {"Content-Type": "application/json", "Authorization": "Bearer " . API_KEY}
TrayTip, GPT3-AHK, Asking ChatGPT...
SetSystemCursor()
response := http.POST(url, JSON.Dump(body), headers, {Object:true, Encoding:"UTF-8"})
obj := JSON.Load(response.Text)
PutText(obj.choices[1].text, "")
RestoreCursors()
TrayTip
}
Return
; Auto-complete the phrase
AutocompleteFcn:
GetText(CopiedText, "Copy")
url := "https://api.openai.com/v1/chat/completions"
body := {}
body.model := MODEL_AUTOCOMPLETE_ID ; ID of the model to use.
body.messages := [{"role": "user", "content": CopiedText}] ; The prompt to generate completions for
body.max_tokens := MODEL_AUTOCOMPLETE_MAX_TOKENS ; The maximum number of tokens to generate in the completion.
body.temperature := MODEL_AUTOCOMPLETE_TEMP + 0 ; Sampling temperature to use
headers := {"Content-Type": "application/json", "Authorization": "Bearer " . API_KEY}
TrayTip, GPT3-AHK, Asking ChatGPT...
SetSystemCursor()
response := http.POST(url, JSON.Dump(body), headers, {Object:true, Encoding:"UTF-8"})
obj := JSON.Load(response.Text)
PutText(obj.choices[1].message.content, "AddSpace")
RestoreCursors()
TrayTip
Return
; -- Auxiliar functions --
; Copies the selected text to a variable while preserving the clipboard.
GetText(ByRef MyText = "", Option = "Copy")
{
SavedClip := ClipboardAll
Clipboard =
If (Option == "Copy")
{
Send ^c
}
Else If (Option == "Cut")
{
Send ^x
}
ClipWait 0.5
If ERRORLEVEL
{
Clipboard := SavedClip
MyText =
Return
}
MyText := Clipboard
Clipboard := SavedClip
Return MyText
}
; Send text from a variable while preserving the clipboard.
PutText(MyText, Option = "")
{
; Save clipboard and paste MyText
SavedClip := ClipboardAll
Clipboard =
Sleep 20
Clipboard := MyText
If (Option == "AddSpace")
{
Send {Right}
Send {Space}
}
Send ^v
Sleep 100
Clipboard := SavedClip
Return
}
; Change system cursor
SetSystemCursor()
{
Cursor = %A_ScriptDir%\GPT3-AHK.ani
CursorHandle := DllCall( "LoadCursorFromFile", Str,Cursor )
Cursors = 32512,32513,32514,32515,32516,32640,32641,32642,32643,32644,32645,32646,32648,32649,32650,32651
Loop, Parse, Cursors, `,
{
DllCall( "SetSystemCursor", Uint,CursorHandle, Int,A_Loopfield )
}
}
RestoreCursors()
{
DllCall( "SystemParametersInfo", UInt, 0x57, UInt,0, UInt,0, UInt,0 )
}
ExitFunc(ExitReason, ExitCode)
{
if ExitReason not in Logoff,Shutdown
{
RestoreCursors()
}
} |
class Queues
{
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
//Function to push an element into stack using two queues.
void push(int a)
{
q2.add(a);
while(!q1.isEmpty()){
q2.add(q1.remove());
}
while(!q2.isEmpty()){
q1.add(q2.remove());
}
}
//Function to pop an element from stack using two queues.
int pop()
{
return q1.isEmpty() ? -1 : q1.remove();
}
} |
---
title: manifest.json
description: Referensi API untuk berkas manifest.json.
---
# manifest.json
Tambahkan atau hasilkan berkas `manifest.(json|webmanifest)` yang sesuai dengan [Spesifikasi Manifest Web](https://developer.mozilla.org/docs/Web/Manifest) di **root** direktori `app` untuk memberikan informasi tentang aplikasi web Anda kepada browser.
## Berkas Manifest Statis
```json filename="app/manifest.json | app/manifest.webmanifest"
{
"name": "Aplikasi Next.js Saya",
"short_name": "Aplikasi Next.js",
"description": "Aplikasi yang dibangun dengan Next.js",
"start_url": "/"
// ...
}
```
## Hasilkan Berkas Manifest
Tambahkan berkas `manifest.js` atau `manifest.ts` yang mengembalikan objek [`Manifest`](#manifest-object).
```ts filename="app/manifest.ts" switcher
import { MetadataRoute } from 'next';
export default function manifest(): MetadataRoute.Manifest {
return {
name: 'Aplikasi Next.js',
short_name: 'Aplikasi Next.js',
description: 'Aplikasi Next.js',
start_url: '/',
display: 'standalone',
background_color: '#fff',
theme_color: '#fff',
icons: [
{
src: '/favicon.ico',
sizes: 'any',
type: 'image/x-icon',
},
],
};
}
```
```js filename="app/manifest.js" switcher
export default function manifest() {
return {
name: 'Aplikasi Next.js',
short_name: 'Aplikasi Next.js',
description: 'Aplikasi Next.js',
start_url: '/',
display: 'standalone',
background_color: '#fff',
theme_color: '#fff',
icons: [
{
src: '/favicon.ico',
sizes: 'any',
type: 'image/x-icon',
},
],
};
}
```
### Objek Manifest
Objek manifest mengandung daftar opsi yang luas yang mungkin diperbarui karena standar web yang baru. Untuk informasi tentang semua opsi saat ini, lihat tipe `MetadataRoute.Manifest` di editor kode Anda jika menggunakan [TypeScript](https://nextjs.org/docs/app/building-your-application/configuring/typescript#typescript-plugin) atau lihat [dokumentasi MDN](https://developer.mozilla.org/docs/Web/Manifest). |
# 第十二章:Spark SQL 在大规模应用程序架构中的应用
在本书中,我们从 Spark SQL 及其组件的基础知识开始,以及它在 Spark 应用程序中的作用。随后,我们提出了一系列关于其在各种类型应用程序中的使用的章节。作为 Spark SQL 的核心,DataFrame/Dataset API 和 Catalyst 优化器在所有基于 Spark 技术栈的应用程序中发挥关键作用,这并不奇怪。这些应用程序包括大规模机器学习、大规模图形和深度学习应用程序。此外,我们提出了基于 Spark SQL 的结构化流应用程序,这些应用程序作为连续应用程序在复杂环境中运行。在本章中,我们将探讨在现实世界应用程序中利用 Spark 模块和 Spark SQL 的应用程序架构。
更具体地,我们将涵盖大规模应用程序中的关键架构组件和模式,这些对架构师和设计师来说将作为特定用例的起点。我们将描述一些用于批处理、流处理应用程序和机器学习管道的主要处理模型的部署。这些处理模型的基础架构需要支持在一端到达高速的各种类型数据的大量数据,同时在另一端使输出数据可供分析工具、报告和建模软件使用。此外,我们将使用 Spark SQL 提供支持代码,用于监控、故障排除和收集/报告指标。
我们将在本章中涵盖以下主题:
+ 理解基于 Spark 的批处理和流处理架构
+ 理解 Lambda 和 Kappa 架构
+ 使用结构化流实现可扩展的流处理
+ 使用 Spark SQL 构建强大的 ETL 管道
+ 使用 Spark SQL 实现可扩展的监控解决方案
+ 部署 Spark 机器学习管道
+ 使用集群管理器:Mesos 和 Kubernetes
# 理解基于 Spark 的应用程序架构
Apache Spark 是一个新兴的平台,利用分布式存储和处理框架来支持规模化的查询、报告、分析和智能应用。Spark SQL 具有必要的功能,并支持所需的关键机制,以访问各种数据源和格式的数据,并为下游应用程序做准备,无论是低延迟的流数据还是高吞吐量的历史数据存储。下图显示了典型的基于 Spark 的批处理和流处理应用程序中包含这些要求的高级架构:

此外,随着组织开始在许多项目中采用大数据和 NoSQL 解决方案,仅由 RDBMS 组成的数据层不再被认为是现代企业应用程序所有用例的最佳选择。仅基于 RDBMS 的架构在下图所示的行业中迅速消失,以满足典型大数据应用程序的要求:

下图显示了一个更典型的场景,其中包含多种类型的数据存储。如今的应用程序使用多种数据存储类型,这些类型最适合特定的用例。根据应用程序使用数据的方式选择多种数据存储技术,称为多语言持久性。Spark SQL 在云端或本地部署中是这种和其他类似持久性策略的极好的实现者:

此外,我们观察到,现实世界中只有一小部分 ML 系统由 ML 代码组成(下图中最小的方框)。然而,围绕这些 ML 代码的基础设施是庞大且复杂的。在本章的后面,我们将使用 Spark SQL 来创建这些应用程序中的一些关键部分,包括可扩展的 ETL 管道和监控解决方案。随后,我们还将讨论机器学习管道的生产部署,以及使用 Mesos 和 Kubernetes 等集群管理器:

参考:“机器学习系统中的隐藏技术债务”,Google NIPS 2015
在下一节中,我们将讨论基于 Spark 的批处理和流处理架构中的关键概念和挑战。
# 使用 Apache Spark 进行批处理
通常,批处理是针对大量数据进行的,以创建批量视图,以支持特定查询和 MIS 报告功能,和/或应用可扩展的机器学习算法,如分类、聚类、协同过滤和分析应用。
由于批处理涉及的数据量较大,这些应用通常是长时间运行的作业,并且很容易延长到几个小时、几天或几周,例如,聚合查询,如每日访问者数量、网站的独立访问者和每周总销售额。
越来越多的人开始将 Apache Spark 作为大规模数据处理的引擎。它可以在内存中运行程序,比 Hadoop MapReduce 快 100 倍,或者在磁盘上快 10 倍。Spark 被迅速采用的一个重要原因是,它需要相似的编码来满足批处理和流处理的需求。
在下一节中,我们将介绍流处理的关键特征和概念。
# 使用 Apache Spark 进行流处理
大多数现代企业都在努力处理大量数据(以及相关数据的快速和无限增长),同时还需要低延迟的处理需求。此外,与传统的批处理 MIS 报告相比,从实时流数据中获得的近实时业务洞察力被赋予了更高的价值。与流处理系统相反,传统的批处理系统旨在处理一组有界数据的大量数据。这些系统在执行开始时就提供了它们所需的所有数据。随着输入数据的不断增长,这些批处理系统提供的结果很快就会过时。
通常,在流处理中,数据在触发所需处理之前不会在显著的时间段内收集。通常,传入的数据被移动到排队系统,例如 Apache Kafka 或 Amazon Kinesis。然后,流处理器访问这些数据,并对其执行某些计算以生成结果输出。典型的流处理管道创建增量视图,这些视图通常根据流入系统的增量数据进行更新。
增量视图通过**Serving Layer**提供,以支持查询和实时分析需求,如下图所示:

在流处理系统中有两种重要的时间类型:事件时间和处理时间。事件时间是事件实际发生的时间(在源头),而处理时间是事件在处理系统中被观察到的时间。事件时间通常嵌入在数据本身中,对于许多用例来说,这是您想要操作的时间。然而,从数据中提取事件时间,并处理延迟或乱序数据在流处理应用程序中可能会带来重大挑战。此外,由于资源限制、分布式处理模型等原因,事件时间和处理时间之间存在偏差。有许多用例需要按事件时间进行聚合;例如,在一个小时的窗口中系统错误的数量。
还可能存在其他问题;例如,在窗口功能中,我们需要确定是否已观察到给定事件时间的所有数据。这些系统需要设计成能够在不确定的环境中良好运行。例如,在 Spark 结构化流处理中,可以为数据流一致地定义基于事件时间的窗口聚合查询,因为它可以处理延迟到达的数据,并适当更新旧的聚合。
在处理大数据流应用程序时,容错性至关重要,例如,一个流处理作业可以统计到目前为止看到的所有元组的数量。在这里,每个元组可能代表用户活动的流,应用程序可能希望报告到目前为止看到的总活动。在这样的系统中,节点故障可能导致计数不准确,因为有未处理的元组(在失败的节点上)。
从这种情况中恢复的一个天真的方法是重新播放整个数据集。考虑到涉及的数据规模,这是一个昂贵的操作。检查点是一种常用的技术,用于避免重新处理整个数据集。在发生故障的情况下,应用程序数据状态将恢复到最后一个检查点,并且从那一点开始重新播放元组。为了防止 Spark Streaming 应用程序中的数据丢失,使用了**预写式日志**(**WAL**),在故障后可以从中重新播放数据。
在下一节中,我们将介绍 Lambda 架构,这是在 Spark 中心应用程序中实施的一种流行模式,因为它可以使用非常相似的代码满足批处理和流处理的要求。
# 理解 Lambda 架构
Lambda 架构模式试图结合批处理和流处理的优点。该模式由几个层组成:**批处理层**(在持久存储上摄取和处理数据,如 HDFS 和 S3),**速度层**(摄取和处理尚未被**批处理层**处理的流数据),以及**服务层**(将**批处理**和**速度层**的输出合并以呈现合并结果)。这是 Spark 环境中非常流行的架构,因为它可以支持**批处理**和**速度层**的实现,两者之间的代码差异很小。
给定的图表描述了 Lambda 架构作为批处理和流处理的组合:

下图显示了使用 AWS 云服务(**Amazon Kinesis**,**Amazon S3**存储,**Amazon EMR**,**Amazon DynamoDB**等)和 Spark 实现 Lambda 架构:

有关 AWS 实施 Lambda 架构的更多详细信息,请参阅[`d0.awsstatic.com/whitepapers/lambda-architecure-on-for-batch-aws.pdf`](https://d0.awsstatic.com/whitepapers/lambda-architecure-on-for-batch-aws.pdf)。
在下一节中,我们将讨论一个更简单的架构,称为 Kappa 架构,它完全放弃了**批处理层**,只在**速度层**中进行流处理。
# 理解 Kappa 架构
**Kappa 架构**比 Lambda 模式更简单,因为它只包括速度层和服务层。所有计算都作为流处理进行,不会对完整数据集进行批量重新计算。重新计算仅用于支持更改和新需求。
通常,传入的实时数据流在内存中进行处理,并持久化在数据库或 HDFS 中以支持查询,如下图所示:

Kappa 架构可以通过使用 Apache Spark 结合排队解决方案(如 Apache Kafka)来实现。如果数据保留时间限制在几天到几周,那么 Kafka 也可以用来保留数据一段有限的时间。
在接下来的几节中,我们将介绍一些使用 Apache Spark、Scala 和 Apache Kafka 的实际应用开发环境中非常有用的实践练习。我们将首先使用 Spark SQL 和结构化流来实现一些流式使用案例。
# 构建可扩展流处理应用的设计考虑
构建健壮的流处理应用是具有挑战性的。与流处理相关的典型复杂性包括以下内容:
+ **复杂数据**:多样化的数据格式和数据质量在流应用中带来了重大挑战。通常,数据以各种格式可用,如 JSON、CSV、AVRO 和二进制。此外,脏数据、延迟到达和乱序数据会使这类应用的设计变得极其复杂。
+ **复杂工作负载**:流应用需要支持多样化的应用需求,包括交互式查询、机器学习流水线等。
+ **复杂系统**:具有包括 Kafka、S3、Kinesis 等多样化存储系统,系统故障可能导致重大的重新处理或错误结果。
使用 Spark SQL 进行流处理可以快速、可扩展和容错。它提供了一套高级 API 来处理复杂数据和工作负载。例如,数据源 API 可以与许多存储系统和数据格式集成。
有关构建可扩展和容错的结构化流处理应用的详细覆盖范围,请参阅[`spark-summit.org/2017/events/easy-scalable-fault-tolerant-stream-processing-with-structured-streaming-in-apache-spark/`](https://spark-summit.org/2017/events/easy-scalable-fault-tolerant-stream-processing-with-structured-streaming-in-apache-spark/)。
流查询允许我们指定一个或多个数据源,使用 DataFrame/Dataset API 或 SQL 转换数据,并指定各种接收器来输出结果。内置支持多种数据源,如文件、Kafka 和套接字,如果需要,还可以组合多个数据源。
Spark SQL Catalyst 优化器可以找出增量执行转换的机制。查询被转换为一系列对新数据批次进行操作的增量执行计划。接收器接受每个批次的输出,并在事务上下文中完成更新。您还可以指定各种输出模式(**完整**、**更新**或**追加**)和触发器来控制何时输出结果。如果未指定触发器,则结果将持续更新。通过持久化检查点来管理给定查询的进度和故障后的重启。
选择适当的数据格式
有关结构化流内部的详细说明,请查看[`spark.apache.org/docs/latest/structured-streaming-programming-guide.html`](http://spark.apache.org/docs/latest/structured-streaming-programming-guide.html)。
Spark 结构化流使得流式分析变得简单,无需担心使流式工作的复杂底层机制。在这个模型中,输入可以被视为来自一个不断增长的追加表的数据。触发器指定了检查输入是否到达新数据的时间间隔,查询表示对输入进行的操作,如映射、过滤和减少。结果表示在每个触发间隔中更新的最终表(根据指定的查询操作)。
在下一节中,我们将讨论 Spark SQL 功能,这些功能可以帮助构建强大的 ETL 管道。
# 使用 Spark SQL 构建强大的 ETL 管道
ETL 管道在源数据上执行一系列转换,以生成经过清洗、结构化并准备好供后续处理组件使用的输出。需要应用在源数据上的转换将取决于数据的性质。输入或源数据可以是结构化的(关系型数据库,Parquet 等),半结构化的(CSV,JSON 等)或非结构化数据(文本,音频,视频等)。通过这样的管道处理后,数据就可以用于下游数据处理、建模、分析、报告等。
下图说明了一个应用架构,其中来自 Kafka 和其他来源(如应用程序和服务器日志)的输入数据在存储到企业数据存储之前经过清洗和转换(使用 ETL 管道)。这个数据存储最终可以供其他应用程序使用(通过 Kafka),支持交互式查询,将数据的子集或视图存储在服务数据库中,训练 ML 模型,支持报告应用程序等。
在下一节中,我们将介绍一些标准,可以帮助您选择适当的数据格式,以满足特定用例的要求。
正如缩写(ETL)所示,我们需要从各种来源检索数据(提取),转换数据以供下游使用(转换),并将其传输到不同的目的地(加载)。
在接下来的几节中,我们将使用 Spark SQL 功能来访问和处理各种数据源和数据格式,以实现 ETL 的目的。Spark SQL 灵活的 API,结合 Catalyst 优化器和 tungsten 执行引擎,使其非常适合构建端到端的 ETL 管道。
在下面的代码块中,我们提供了一个简单的单个 ETL 查询的框架,结合了所有三个(提取、转换和加载)功能。这些查询也可以扩展到执行包含来自多个来源和来源格式的数据的表之间的复杂连接:
```scala
spark.read.json("/source/path") //Extract
.filter(...) //Transform
.agg(...) //Transform
.write.mode("append") .parquet("/output/path") //Load
```
我们还可以对流数据执行滑动窗口操作。在这里,我们定义了对滑动窗口的聚合,其中我们对数据进行分组并计算适当的聚合(对于每个组)。
# 
在企业设置中,数据以许多不同的数据源和格式可用。Spark SQL 支持一组内置和第三方连接器。此外,我们还可以定义自定义数据源连接器。数据格式包括结构化、半结构化和非结构化格式,如纯文本、JSON、XML、CSV、关系型数据库记录、图像和视频。最近,Parquet、ORC 和 Avro 等大数据格式变得越来越受欢迎。一般来说,纯文本文件等非结构化格式更灵活,而 Parquet 和 AVRO 等结构化格式在存储和性能方面更有效率。
在结构化数据格式的情况下,数据具有严格的、明确定义的模式或结构。例如,列式数据格式使得从列中提取值更加高效。然而,这种严格性可能会使对模式或结构的更改变得具有挑战性。相比之下,非结构化数据源,如自由格式文本,不包含 CSV 或 TSV 文件中的标记或分隔符。这样的数据源通常需要一些关于数据的上下文;例如,你需要知道文件的内容包含来自博客的文本。
通常,我们需要许多转换和特征提取技术来解释不同的数据集。半结构化数据在记录级别上是结构化的,但不一定在所有记录上都是结构化的。因此,每个数据记录都包含相关的模式信息。
JSON 格式可能是半结构化数据最常见的例子。JSON 记录以人类可读的形式呈现,这对于开发和调试来说更加方便。然而,这些格式受到解析相关的开销的影响,通常不是支持特定查询功能的最佳选择。
通常,应用程序需要设计成能够跨越各种数据源和格式高效存储和处理数据。例如,当需要访问完整的数据行时,Avro 是一个很好的选择,就像在 ML 管道中访问特征的情况一样。在需要模式的灵活性的情况下,使用 JSON 可能是数据格式的最合适选择。此外,在数据没有固定模式的情况下,最好使用纯文本文件格式。
# ETL 管道中的数据转换
通常,诸如 JSON 之类的半结构化格式包含 struct、map 和 array 数据类型;例如,REST Web 服务的请求和/或响应负载包含具有嵌套字段和数组的 JSON 数据。
在这一部分,我们将展示基于 Spark SQL 的 Twitter 数据转换的示例。输入数据集是一个文件(`cache-0.json.gz`),其中包含了在 2012 年美国总统选举前三个月内收集的超过`1.7 亿`条推文中的`1 千万`条推文。这个文件可以从[`datahub.io/dataset/twitter-2012-presidential-election`](https://datahub.io/dataset/twitter-2012-presidential-election)下载。
在开始以下示例之前,按照第五章中描述的方式启动 Zookeeper 和 Kafka 代理。另外,创建一个名为 tweetsa 的新 Kafka 主题。我们从输入 JSON 数据集生成模式,如下所示。这个模式定义将在本节后面使用:
```scala
scala> val jsonDF = spark.read.json("file:///Users/aurobindosarkar/Downloads/cache-0-json")
scala> jsonDF.printSchema()
scala> val rawTweetsSchema = jsonDF.schema
scala> val jsonString = rawTweetsSchema.json
scala> val schema = DataType.fromJson(jsonString).asInstanceOf[StructType]
```
设置从 Kafka 主题(*tweetsa*)中读取流式推文,并使用上一步的模式解析 JSON 数据。
在这个声明中,我们通过`指定数据.*`来选择推文中的所有字段:
```scala
scala> val rawTweets = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("subscribe", "tweetsa").load()
scala> val parsedTweets = rawTweets.selectExpr("cast (value as string) as json").select(from_json($"json", schema).as("data")).select("data.*")
```
在你通过示例工作时,你需要反复使用以下命令将输入文件中包含的推文传输到 Kafka 主题中,如下所示:
```scala
Aurobindos-MacBook-Pro-2:kafka_2.11-0.10.2.1 aurobindosarkar$ bin/kafka-console-producer.sh --broker-list localhost:9092 --topic tweetsa < /Users/aurobindosarkar/Downloads/cache-0-json
```
考虑到输入文件的大小,这可能会导致您的计算机出现空间相关的问题。如果发生这种情况,请使用适当的 Kafka 命令来删除并重新创建主题(参考[`kafka.apache.org/0102/documentation.html`](https://kafka.apache.org/0102/documentation.html))。
在这里,我们重现了一个模式的部分,以帮助理解我们在接下来的几个示例中要处理的结构:

我们可以从 JSON 字符串中的嵌套列中选择特定字段。我们使用`.`(点)运算符来选择嵌套字段,如下所示:
```scala
scala> val selectFields = parsedTweets.select("place.country").where($"place.country".isNotNull)
```
接下来,我们将输出流写入屏幕以查看结果。您需要在每个转换之后执行以下语句,以查看和评估结果。此外,为了节省时间,您应该在看到足够的屏幕输出后执行`s5.stop()`。或者,您可以选择使用从原始输入文件中提取的较小数据集进行工作:
```scala
scala> val s5 = selectFields.writeStream.outputMode("append").format("console").start()
```

在下一个示例中,我们将使用星号(*)展平一个 struct 以选择 struct 中的所有子字段:
```scala
scala> val selectFields = parsedTweets.select("place.*").where($"place.country".isNotNull)
```
可以通过编写输出流来查看结果,如前面的示例所示:

我们可以使用 struct 函数创建一个新的 struct(用于嵌套列),如下面的代码片段所示。我们可以选择特定字段或字段来创建新的 struct。如果需要,我们还可以使用星号(*)嵌套所有列。
在这里,我们重现了此示例中使用的模式部分:

```scala
scala> val selectFields = parsedTweets.select(struct("place.country_code", "place.name") as 'locationInfo).where($"locationInfo.country_code".isNotNull)
```

在下一个示例中,我们使用`getItem()`选择单个数组(或映射)元素。在这里,我们正在操作模式的以下部分:

```scala
scala> val selectFields = parsedTweets.select($"entities.hashtags" as 'tags).select('tags.getItem(0) as 'x).select($"x.indices" as 'y).select($"y".getItem(0) as 'z).where($"z".isNotNull)
```

```scala
scala> val selectFields = parsedTweets.select($"entities.hashtags" as 'tags).select('tags.getItem(0) as 'x).select($"x.text" as 'y).where($"y".isNotNull)
```

我们可以使用`explode()`函数为数组中的每个元素创建新行,如所示。为了说明`explode()`的结果,我们首先展示包含数组的行,然后展示应用 explode 函数的结果:
```scala
scala> val selectFields = parsedTweets.select($"entities.hashtags.indices" as 'tags).select(explode('tags))
```
获得以下输出:

请注意,在应用 explode 函数后,为数组元素创建了单独的行:
```scala
scala> val selectFields = parsedTweets.select($"entities.hashtags.indices".getItem(0) as 'tags).select(explode('tags))
```
获得的输出如下:

Spark SQL 还具有诸如`to_json()`之类的函数,用于将`struct`转换为 JSON 字符串,以及`from_json()`,用于将 JSON 字符串转换为`struct`。这些函数对于从 Kafka 主题读取或写入非常有用。例如,如果“value”字段包含 JSON 字符串中的数据,则我们可以使用`from_json()`函数提取数据,转换数据,然后将其推送到不同的 Kafka 主题,并/或将其写入 Parquet 文件或服务数据库。
在以下示例中,我们使用`to_json()`函数将 struct 转换为 JSON 字符串:
```scala
scala> val selectFields = parsedTweets.select(struct($"entities.media.type" as 'x, $"entities.media.url" as 'y) as 'z).where($"z.x".isNotNull).select(to_json('z) as 'c)
```

我们可以使用`from_json()`函数将包含 JSON 数据的列转换为`struct`数据类型。此外,我们可以将前述结构展平为单独的列。我们在后面的部分中展示了使用此函数的示例。
有关转换函数的更详细覆盖范围,请参阅[`databricks.com/blog/2017/02/23/working-complex-data-formats-structured-streaming-apache-spark-2-1.html`](https://databricks.com/blog/2017/02/23/working-complex-data-formats-structured-streaming-apache-spark-2-1.html)。
# 解决 ETL 管道中的错误
ETL 任务通常被认为是复杂、昂贵、缓慢和容易出错的。在这里,我们将研究 ETL 过程中的典型挑战,以及 Spark SQL 功能如何帮助解决这些挑战。
Spark 可以自动从 JSON 文件中推断模式。例如,对于以下 JSON 数据,推断的模式包括基于内容的所有标签和数据类型。在这里,输入数据中所有元素的数据类型默认为长整型:
**test1.json**
```scala
{"a":1, "b":2, "c":3}
{"a":2, "d":5, "e":3}
{"d":1, "c":4, "f":6}
{"a":7, "b":8}
{"c":5, "e":4, "d":3}
{"f":3, "e":3, "d":4}
{"a":1, "b":2, "c":3, "f":3, "e":3, "d":4}
```
您可以打印模式以验证数据类型,如下所示:
```scala
scala> spark.read.json("file:///Users/aurobindosarkar/Downloads/test1.json").printSchema()
root
|-- a: long (nullable = true)
|-- b: long (nullable = true)
|-- c: long (nullable = true)
|-- d: long (nullable = true)
|-- e: long (nullable = true)
|-- f: long (nullable = true)
```
然而,在以下 JSON 数据中,如果第三行中的`e`的值和最后一行中的`b`的值被更改以包含分数,并且倒数第二行中的`f`的值被包含在引号中,那么推断的模式将更改`b`和`e`的数据类型为 double,`f`的数据类型为字符串:
```scala
{"a":1, "b":2, "c":3}
{"a":2, "d":5, "e":3}
{"d":1, "c":4, "f":6}
{"a":7, "b":8}
{"c":5, "e":4.5, "d":3}
{"f":"3", "e":3, "d":4}
{"a":1, "b":2.1, "c":3, "f":3, "e":3, "d":4}
scala> spark.read.json("file:///Users/aurobindosarkar/Downloads/test1.json").printSchema()
root
|-- a: long (nullable = true)
|-- b: double (nullable = true)
|-- c: long (nullable = true)
|-- d: long (nullable = true)
|-- e: double (nullable = true)
|-- f: string (nullable = true)
```
如果我们想要将特定结构或数据类型与元素关联起来,我们需要使用用户指定的模式。在下一个示例中,我们使用包含字段名称的标题的 CSV 文件。模式中的字段名称来自标题,并且用户定义的模式中指定的数据类型将用于它们,如下所示:
```scala
a,b,c,d,e,f
1,2,3,,,
2,,,5,3,
,,4,1,,,6
7,8,,,,f
,,5,3,4.5,
,,,4,3,"3"
1,2.1,3,3,3,4
scala> val schema = new StructType().add("a", "int").add("b", "double")
scala> spark.read.option("header", true).schema(schema).csv("file:///Users/aurobindosarkar/Downloads/test1.csv").show()
```
获取以下输出:

由于文件和数据损坏,ETL 管道中也可能出现问题。如果数据不是关键任务,并且损坏的文件可以安全地忽略,我们可以设置`config property spark.sql.files.ignoreCorruptFiles = true`。此设置允许 Spark 作业继续运行,即使遇到损坏的文件。请注意,成功读取的内容将继续返回。
在下一个示例中,第 4 行的`b`存在错误数据。我们仍然可以使用`PERMISSIVE`模式读取数据。在这种情况下,DataFrame 中会添加一个名为`_corrupt_record`的新列,并且损坏行的内容将出现在该列中,其余字段初始化为 null。我们可以通过查看该列中的数据来关注数据问题,并采取适当的措施来修复它们。通过设置`spark.sql.columnNameOfCorruptRecord`属性,我们可以配置损坏内容列的默认名称:
```scala
{"a":1, "b":2, "c":3}
{"a":2, "d":5, "e":3}
{"d":1, "c":4, "f":6}
{"a":7, "b":{}
{"c":5, "e":4.5, "d":3}
{"f":"3", "e":3, "d":4}
{"a":1, "b":2.1, "c":3, "f":3, "e":3, "d":4}
scala> spark.read.option("mode", "PERMISSIVE").option("columnNameOfCorruptRecord", "_corrupt_record").json("file:///Users/aurobindosarkar/Downloads/test1.json").show()
```

现在,我们使用`DROPMALFORMED`选项来删除所有格式不正确的记录。在这里,由于`b`的坏值,第四行被删除:
```scala
scala> spark.read.option("mode", "DROPMALFORMED").json("file:///Users/aurobindosarkar/Downloads/test1.json").show()
```

对于关键数据,我们可以使用`FAILFAST`选项,在遇到坏记录时立即失败。例如,在以下示例中,由于第四行中`b`的值,操作会抛出异常并立即退出:
```scala
{"a":1, "b":2, "c":3}
{"a":2, "d":5, "e":3}
{"d":1, "c":4, "f":6}
{"a":7, "b":$}
{"c":5, "e":4.5, "d":3}
{"f":"3", "e":3, "d":4}
{"a":1, "b":2.1, "c":3, "f":3, "e":3, "d":4}
scala> spark.read.option("mode", "FAILFAST").json("file:///Users/aurobindosarkar/Downloads/test1.json").show()
```
在下一个示例中,我们有一条跨越两行的记录;我们可以通过将`wholeFile`选项设置为 true 来读取此记录:
```scala
{"a":{"a1":2, "a2":8},
"b":5, "c":3}
scala> spark.read.option("wholeFile",true).option("mode", "PERMISSIVE").option("columnNameOfCorruptRecord", "_corrupt_record").json("file:///Users/aurobindosarkar/Downloads/testMultiLine.json").show()
+-----+---+---+
| a| b| c|
+-----+---+---+
|[2,8]| 5| 3|
+-----+---+---+
```
有关基于 Spark SQL 的 ETL 管道和路线图的更多详细信息,请访问[`spark-summit.org/2017/events/building-robust-etl-pipelines-with-apache-spark/`](https://spark-summit.org/2017/events/building-robust-etl-pipelines-with-apache-spark/)。
上述参考介绍了几个高阶 SQL 转换函数,DataframeWriter API 的新格式以及 Spark 2.2 和 2.3-Snapshot 中的统一`Create Table`(作为`Select`)构造。
Spark SQL 解决的其他要求包括可扩展性和使用结构化流进行持续 ETL。我们可以使用结构化流来使原始数据尽快可用作结构化数据,以进行分析、报告和决策,而不是产生通常与运行周期性批处理作业相关的几小时延迟。这种处理在应用程序中尤为重要,例如异常检测、欺诈检测等,时间至关重要。
在下一节中,我们将把重点转移到使用 Spark SQL 构建可扩展的监控解决方案。
# 实施可扩展的监控解决方案
为大规模部署构建可扩展的监控功能可能具有挑战性,因为每天可能捕获数十亿个数据点。此外,日志的数量和指标的数量可能难以管理,如果没有适当的具有流式处理和可视化支持的大数据平台。
从应用程序、服务器、网络设备等收集的大量日志被处理,以提供实时监控,帮助检测错误、警告、故障和其他问题。通常,各种守护程序、服务和工具用于收集/发送日志记录到监控系统。例如,以 JSON 格式的日志条目可以发送到 Kafka 队列或 Amazon Kinesis。然后,这些 JSON 记录可以存储在 S3 上作为文件和/或流式传输以实时分析(在 Lambda 架构实现中)。通常,会运行 ETL 管道来清理日志数据,将其转换为更结构化的形式,然后加载到 Parquet 文件或数据库中,以进行查询、警报和报告。
下图说明了一个使用**Spark Streaming Jobs**、**可扩展的时间序列数据库**(如 OpenTSDB 或 Graphite)和**可视化工具**(如 Grafana)的平台:

有关此解决方案的更多详细信息,请参阅[`spark-summit.org/2017/events/scalable-monitoring-using-apache-spark-and-friends/`](https://spark-summit.org/2017/events/scalable-monitoring-using-apache-spark-and-friends/)。
在由多个具有不同配置和版本、运行不同类型工作负载的 Spark 集群组成的大型分布式环境中,监控和故障排除问题是具有挑战性的任务。在这些环境中,可能会收到数十万条指标。此外,每秒生成数百 MB 的日志。这些指标需要被跟踪,日志需要被分析以发现异常、故障、错误、环境问题等,以支持警报和故障排除功能。
下图说明了一个基于 AWS 的数据管道,将所有指标和日志(结构化和非结构化)推送到 Kinesis。结构化流作业可以从 Kinesis 读取原始日志,并将数据保存为 S3 上的 Parquet 文件。
结构化流查询可以剥离已知的错误模式,并在观察到新的错误类型时提出适当的警报。其他 Spark 批处理和流处理应用程序可以使用这些 Parquet 文件进行额外处理,并将其结果输出为 S3 上的新 Parquet 文件:

在这种架构中,可能需要从非结构化日志中发现问题,以确定其范围、持续时间和影响。**原始日志**通常包含许多近似重复的错误消息。为了有效处理这些日志,我们需要对其进行规范化、去重和过滤已知的错误条件,以发现和揭示新的错误。
有关处理原始日志的管道的详细信息,请参阅[`spark-summit.org/2017/events/lessons-learned-from-managing-thousands-of-production-apache-spark-clusters-daily/`](https://spark-summit.org/2017/events/lessons-learned-from-managing-thousands-of-production-apache-spark-clusters-daily/)。
在本节中,我们将探讨 Spark SQL 和结构化流提供的一些功能,以创建可扩展的监控解决方案。
首先,使用 Kafka 包启动 Spark shell:
```scala
Aurobindos-MacBook-Pro-2:spark-2.2.0-bin-hadoop2.7 aurobindosarkar$ ./bin/spark-shell --packages org.apache.spark:spark-streaming-kafka-0-10_2.11:2.1.1,org.apache.spark:spark-sql-kafka-0-10_2.11:2.1.1 --driver-memory 12g
```
下载 1995 年 7 月的痕迹,其中包含了对佛罗里达州 NASA 肯尼迪航天中心 WWW 服务器的 HTTP 请求[`ita.ee.lbl.gov/html/contrib/NASA-HTTP.html`](http://ita.ee.lbl.gov/html/contrib/NASA-HTTP.html)。
在本章的实践练习中,导入以下包:
```scala
scala> import org.apache.spark.sql.types._
scala> import org.apache.spark.sql.functions._
scala> import spark.implicits._
scala> import org.apache.spark.sql.streaming._
```
接下来,为文件中的记录定义模式:
```scala
scala> val schema = new StructType().add("clientIpAddress", "string").add("rfc1413ClientIdentity", "string").add("remoteUser", "string").add("dateTime", "string").add("zone", "string").add("request","string").add("httpStatusCode", "string").add("bytesSent", "string").add("referer", "string").add("userAgent", "string")
```
为简单起见,我们将输入文件读取为以空格分隔的 CSV 文件,如下所示:
```scala
scala> val rawRecords = spark.readStream.option("header", false).schema(schema).option("sep", " ").format("csv").load("file:///Users/aurobindosarkar/Downloads/NASA")
scala> val ts = unix_timestamp(concat($"dateTime", lit(" "), $"zone"), "[dd/MMM/yyyy:HH:mm:ss Z]").cast("timestamp")
```
接下来,我们创建一个包含日志事件的 DataFrame。由于时间戳在前面的步骤中更改为本地时区(默认情况下),我们还在`original_dateTime`列中保留了带有时区信息的原始时间戳,如下所示:
```scala
scala> val logEvents = rawRecords.withColumn("ts", ts).withColumn("date", ts.cast(DateType)).select($"ts", $"date", $"clientIpAddress", concat($"dateTime", lit(" "), $"zone").as("original_dateTime"), $"request", $"httpStatusCode", $"bytesSent")
```
我们可以检查流式读取的结果,如下所示:
```scala
scala> val query = logEvents.writeStream.outputMode("append").format("console").start()
```

我们可以将流输入保存为 Parquet 文件,按日期分区以更有效地支持查询,如下所示:
```scala
scala> val streamingETLQuery = logEvents.writeStream.trigger(Trigger.ProcessingTime("2 minutes")).format("parquet").partitionBy("date").option("path", "file:///Users/aurobindosarkar/Downloads/NASALogs").option("checkpointLocation", "file:///Users/aurobindosarkar/Downloads/NASALogs/checkpoint/").start()
```
我们可以通过指定`latestFirst`选项来读取输入,以便最新的记录首先可用:
```scala
val rawCSV = spark.readStream.schema(schema).option("latestFirst", "true").option("maxFilesPerTrigger", "5").option("header", false).option("sep", " ").format("csv").load("file:///Users/aurobindosarkar/Downloads/NASA")
```
我们还可以按日期将输出以 JSON 格式输出,如下所示:
```scala
val streamingETLQuery = logEvents.writeStream.trigger(Trigger.ProcessingTime("2 minutes")).format("json").partitionBy("date").option("path", "file:///Users/aurobindosarkar/Downloads/NASALogs").option("checkpointLocation", "file:///Users/aurobindosarkar/Downloads/NASALogs/checkpoint/").start()
```
现在,我们展示了在流式 Spark 应用程序中使用 Kafka 进行输入和输出的示例。在这里,我们必须将格式参数指定为`kafka`,并指定 kafka 代理和主题:
```scala
scala> val kafkaQuery = logEvents.selectExpr("CAST(ts AS STRING) AS key", "to_json(struct(*)) AS value").writeStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("topic", "topica").option("checkpointLocation", "file:///Users/aurobindosarkar/Downloads/NASALogs/kafkacheckpoint/").start()
```
现在,我们正在从 Kafka 中读取 JSON 数据流。将起始偏移设置为最早以指定查询的起始点。这仅适用于启动新的流式查询时:
```scala
scala> val kafkaDF = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("subscribe", "topica").option("startingOffsets", "earliest").load()
```
我们可以按以下方式打印从 Kafka 读取的记录的模式:
```scala
scala> kafkaDF.printSchema()
root
|-- key: binary (nullable = true)
|-- value: binary (nullable = true)
|-- topic: string (nullable = true)
|-- partition: integer (nullable = true)
|-- offset: long (nullable = true)
|-- timestamp: timestamp (nullable = true)
|-- timestampType: integer (nullable = true)
```
接下来,我们定义输入记录的模式,如下所示:
```scala
scala> val kafkaSchema = new StructType().add("ts", "timestamp").add("date", "string").add("clientIpAddress", "string").add("rfc1413ClientIdentity", "string").add("remoteUser", "string").add("original_dateTime", "string").add("request", "string").add("httpStatusCode", "string").add("bytesSent", "string")
```
接下来,我们可以指定模式,如所示。星号`*`运算符用于选择`struct`中的所有`subfields`:
```scala
scala> val kafkaDF1 = kafkaDF.select(col("key").cast("string"), from_json(col("value").cast("string"), kafkaSchema).as("data")).select("data.*")
```
接下来,我们展示选择特定字段的示例。在这里,我们将`outputMode`设置为 append,以便只有追加到结果表的新行被写入外部存储。这仅适用于查询结果表中现有行不会发生变化的情况:
```scala
scala> val kafkaQuery1 = kafkaDF1.select($"ts", $"date", $"clientIpAddress", $"original_dateTime", $"request", $"httpStatusCode", $"bytesSent").writeStream.outputMode("append").format("console").start()
```

我们还可以指定`read`(而不是`readStream`)将记录读入常规 DataFrame 中:
```scala
scala> val kafkaDF2 = spark.read.format("kafka").option("kafka.bootstrap.servers","localhost:9092").option("subscribe", "topica").load().selectExpr("CAST(value AS STRING) as myvalue")
```
现在,我们可以对这个 DataFrame 执行所有标准的 DataFrame 操作;例如,我们创建一个表并查询它,如下所示:
```scala
scala> kafkaDF2.registerTempTable("topicData3")
scala> spark.sql("select myvalue from topicData3").take(3).foreach(println)
```

然后,我们从 Kafka 中读取记录并应用模式:
```scala
scala> val parsed = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("subscribe", "topica").option("startingOffsets", "earliest").load().select(from_json(col("value").cast("string"), kafkaSchema).alias("parsed_value"))
```
我们可以执行以下查询来检查记录的内容:
```scala
scala> val query = parsed.writeStream.outputMode("append").format("console").start()
```

我们可以从记录中选择所有字段,如下所示:
```scala
scala> val selectAllParsed = parsed.select("parsed_value.*")
```
我们还可以从 DataFrame 中选择感兴趣的特定字段:
```scala
scala> val selectFieldsParsed = selectAllParsed.select("ts", "clientIpAddress", "request", "httpStatusCode")
```
接下来,我们可以使用窗口操作,并为各种 HTTP 代码维护计数,如所示。在这里,我们将`outputMode`设置为`complete`,因为我们希望将整个更新后的结果表写入外部存储:
```scala
scala> val s1 = selectFieldsParsed.groupBy(window($"ts", "10 minutes", "5 minutes"), $"httpStatusCode").count().writeStream.outputMode("complete").format("console").start()
```

接下来,我们展示了另一个使用`groupBy`和计算各窗口中各种页面请求计数的示例。这可用于计算和报告访问类型指标中的热门页面:
```scala
scala> val s2 = selectFieldsParsed.groupBy(window($"ts", "10 minutes", "5 minutes"), $"request").count().writeStream.outputMode("complete").format("console").start()
```

请注意,前面提到的示例是有状态处理的实例。计数必须保存为触发器之间的分布式状态。每个触发器读取先前的状态并写入更新后的状态。此状态存储在内存中,并由持久的 WAL 支持,通常位于 HDFS 或 S3 存储上。这使得流式应用程序可以自动处理延迟到达的数据。保留此状态允许延迟数据更新旧窗口的计数。
然而,如果不丢弃旧窗口,状态的大小可能会无限增加。水印方法用于解决此问题。水印是预期数据延迟的移动阈值,以及何时丢弃旧状态。它落后于最大观察到的事件时间。水印之后的数据可能会延迟,但允许进入聚合,而水印之前的数据被认为是“太晚”,并被丢弃。此外,水印之前的窗口会自动删除,以限制系统需要维护的中间状态的数量。
在前一个查询中指定的水印在这里给出:
```scala
scala> val s4 = selectFieldsParsed.withWatermark("ts", "10 minutes").groupBy(window($"ts", "10 minutes", "5 minutes"), $"request").count().writeStream.outputMode("complete").format("console").start()
```
有关水印的更多详细信息,请参阅[`databricks.com/blog/2017/05/08/event-time-aggregation-watermarking-apache-sparks-structured-streaming.html`](https://databricks.com/blog/2017/05/08/event-time-aggregation-watermarking-apache-sparks-structured-streaming.html)。
在下一节中,我们将把重点转移到在生产环境中部署基于 Spark 的机器学习管道。
# 部署 Spark 机器学习管道
下图以概念级别说明了机器学习管道。然而,现实生活中的 ML 管道要复杂得多,有多个模型被训练、调整、组合等:

下图显示了典型机器学习应用程序的核心元素分为两部分:建模,包括模型训练,以及部署的模型(用于流数据以输出结果):

通常,数据科学家在 Python 和/或 R 中进行实验或建模工作。然后在部署到生产环境之前,他们的工作会在 Java/Scala 中重新实现。企业生产环境通常包括 Web 服务器、应用服务器、数据库、中间件等。将原型模型转换为生产就绪模型会导致额外的设计和开发工作,从而导致更新模型的推出延迟。
我们可以使用 Spark MLlib 2.x 模型序列化直接在生产环境中加载数据科学家保存的模型和管道(到磁盘)的模型文件。
在以下示例中(来源:[`spark.apache.org/docs/latest/ml-pipeline.html`](https://spark.apache.org/docs/latest/ml-pipeline.html)),我们将演示在 Python 中创建和保存 ML 管道(使用`pyspark` shell),然后在 Scala 环境中检索它。
启动`pyspark` shell 并执行以下 Python 语句序列:
```scala
>>> from pyspark.ml import Pipeline
>>> from pyspark.ml.classification import LogisticRegression
>>> from pyspark.ml.feature import HashingTF, Tokenizer
>>> training = spark.createDataFrame([
... (0, "a b c d e spark", 1.0),
... (1, "b d", 0.0),
... (2, "spark f g h", 1.0),
... (3, "hadoop mapreduce", 0.0)
... ], ["id", "text", "label"])
>>> tokenizer = Tokenizer(inputCol="text", outputCol="words")
>>> hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
>>> lr = LogisticRegression(maxIter=10, regParam=0.001)
>>> pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])
>>> model = pipeline.fit(training)
>>> model.save("file:///Users/aurobindosarkar/Downloads/spark-logistic-regression-model")
>>> quit()
```
启动 Spark shell 并执行以下 Scala 语句序列:
```scala
scala> import org.apache.spark.ml.{Pipeline, PipelineModel}
scala> import org.apache.spark.ml.classification.LogisticRegression
scala> import org.apache.spark.ml.feature.{HashingTF, Tokenizer}
scala> import org.apache.spark.ml.linalg.Vector
scala> import org.apache.spark.sql.Row
scala> val sameModel = PipelineModel.load("file:///Users/aurobindosarkar/Downloads/spark-logistic-regression-model")
```
接下来,我们创建一个`test`数据集,并通过 ML 管道运行它:
```scala
scala> val test = spark.createDataFrame(Seq(
| (4L, "spark i j k"),
| (5L, "l m n"),
| (6L, "spark hadoop spark"),
| (7L, "apache hadoop")
| )).toDF("id", "text")
```
在`test`数据集上运行模型的结果如下:
```scala
scala> sameModel.transform(test).select("id", "text", "probability", "prediction").collect().foreach { case Row(id: Long, text: String, prob: Vector, prediction: Double) => println(s"($id, $text) --> prob=$prob, prediction=$prediction")}
(4, spark i j k) --> prob=[0.15554371384424398,0.844456286155756], prediction=1.0
(5, l m n) --> prob=[0.8307077352111738,0.16929226478882617], prediction=0.0
(6, spark hadoop spark) --> prob=[0.06962184061952888,0.9303781593804711], prediction=1.0
(7, apache hadoop) --> prob=[0.9815183503510166,0.018481649648983405], prediction=0.0
```
保存的逻辑回归模型的关键参数被读入 DataFrame,如下面的代码块所示。在之前,当模型在`pyspark` shell 中保存时,这些参数被保存到与我们管道的最终阶段相关的子目录中的 Parquet 文件中:
```scala
scala> val df = spark.read.parquet("file:///Users/aurobindosarkar/Downloads/spark-logistic-regression-model/stages/2_LogisticRegression_4abda37bdde1ddf65ea0/data/part-00000-415bf215-207a-4a49-985e-190eaf7253a7-c000.snappy.parquet")
scala> df.show()
```
获得以下输出:

```scala
scala> df.collect.foreach(println)
```
输出如下:

有关如何将 ML 模型投入生产的更多详细信息,请参阅[`spark-summit.org/2017/events/how-to-productionize-your-machine-learning-models-using-apache-spark-mllib-2x/`](https://spark-summit.org/2017/events/how-to-productionize-your-machine-learning-models-using-apache-spark-mllib-2x/)。
# 了解典型 ML 部署环境中的挑战
ML 模型的生产部署环境可能非常多样化和复杂。例如,模型可能需要部署在 Web 应用程序、门户、实时和批处理系统中,以及作为 API 或 REST 服务,嵌入设备或大型遗留环境中。
此外,企业技术堆栈可以包括 Java 企业、C/C++、遗留主机环境、关系数据库等。与响应时间、吞吐量、可用性和正常运行时间相关的非功能性要求和客户 SLA 也可能差异很大。然而,在几乎所有情况下,我们的部署过程需要支持 A/B 测试、实验、模型性能评估,并且需要灵活和响应业务需求。
通常,从业者使用各种方法来对新模型或更新模型进行基准测试和逐步推出,以避免高风险、大规模的生产部署。
在下一节中,我们将探讨一些模型部署架构。
# 了解模型评分架构的类型
最简单的模型是使用 Spark(批处理)预计算模型结果,将结果保存到数据库,然后从数据库为 Web 和移动应用程序提供结果。许多大规模的推荐引擎和搜索引擎使用这种架构:

第二种模型评分架构使用 Spark Streaming 计算特征并运行预测算法。预测结果可以使用缓存解决方案(如 Redis)进行缓存,并可以通过 API 提供。其他应用程序可以使用这些 API 从部署的模型中获取预测结果。此选项在此图中有所说明:

在第三种架构模型中,我们可以仅使用 Spark 进行模型训练。然后将模型复制到生产环境中。例如,我们可以从 JSON 文件中加载逻辑回归模型的系数和截距。这种方法资源高效,并且会产生高性能的系统。在现有或复杂环境中部署也更加容易。
如图所示:

继续我们之前的例子,我们可以从 Parquet 文件中读取保存的模型参数,并将其转换为 JSON 格式,然后可以方便地导入到任何应用程序(在 Spark 环境内部或外部)并应用于新数据:
```scala
scala> spark.read.parquet("file:///Users/aurobindosarkar/Downloads/spark-logistic-regression-model/stages/2_LogisticRegression_4abda37bdde1ddf65ea0/data/part-00000-415bf215-207a-4a49-985e-190eaf7253a7-c000.snappy.parquet").write.mode("overwrite").json("file:///Users/aurobindosarkar/Downloads/lr-model-json")
```
我们可以使用标准操作系统命令显示截距、系数和其他关键参数,如下所示:
```scala
Aurobindos-MacBook-Pro-2:lr-model-json aurobindosarkar$ more part-00000-e2b14eb8-724d-4262-8ea5-7c23f846fed0-c000.json
```

随着模型变得越来越大和复杂,部署和提供服务可能会变得具有挑战性。模型可能无法很好地扩展,其资源需求可能变得非常昂贵。Databricks 和 Redis-ML 提供了部署训练模型的解决方案。
在 Redis-ML 解决方案中,模型直接应用于 Redis 环境中的新数据。
这可以以比在 Spark 环境中运行模型的价格更低的价格提供所需的整体性能、可伸缩性和可用性。
下图显示了 Redis-ML 作为服务引擎的使用情况(实现了先前描述的第三种模型评分架构模式):

在下一节中,我们将简要讨论在生产环境中使用 Mesos 和 Kubernetes 作为集群管理器。
# 使用集群管理器
在本节中,我们将在概念层面简要讨论 Mesos 和 Kubernetes。Spark 框架可以通过 Apache Mesos、YARN、Spark Standalone 或 Kubernetes 集群管理器进行部署,如下所示:

Mesos 可以实现数据的轻松扩展和复制,并且是异构工作负载的良好统一集群管理解决方案。
要从 Spark 使用 Mesos,Spark 二进制文件应该可以被 Mesos 访问,并且 Spark 驱动程序配置为连接到 Mesos。或者,您也可以在所有 Mesos 从属节点上安装 Spark 二进制文件。驱动程序创建作业,然后发出任务进行调度,而 Mesos 确定处理它们的机器。
Spark 可以在 Mesos 上以两种模式运行:粗粒度(默认)和细粒度(在 Spark 2.0.0 中已弃用)。在粗粒度模式下,每个 Spark 执行器都作为单个 Mesos 任务运行。这种模式具有显着较低的启动开销,但会为应用程序的持续时间保留 Mesos 资源。Mesos 还支持根据应用程序的统计数据调整执行器数量的动态分配。
下图说明了将 Mesos Master 和 Zookeeper 节点放置在一起的部署。Mesos Slave 和 Cassandra 节点也放置在一起,以获得更好的数据局部性。此外,Spark 二进制文件部署在所有工作节点上:

另一个新兴的 Spark 集群管理解决方案是 Kubernetes,它正在作为 Spark 的本机集群管理器进行开发。它是一个开源系统,可用于自动化容器化 Spark 应用程序的部署、扩展和管理。
下图描述了 Kubernetes 的高层视图。每个节点都包含一个名为 Kublet 的守护程序,它与 Master 节点通信。用户还可以与 Master 节点通信,以声明性地指定他们想要运行的内容。例如,用户可以请求运行特定数量的 Web 服务器实例。Master 将接受用户的请求并在节点上安排工作负载:

节点运行一个或多个 pod。Pod 是容器的更高级抽象,每个 pod 可以包含一组共同放置的容器。每个 pod 都有自己的 IP 地址,并且可以与其他节点中的 pod 进行通信。存储卷可以是本地的或网络附加的。这可以在下图中看到:

Kubernetes 促进不同类型的 Spark 工作负载之间的资源共享,以减少运营成本并提高基础设施利用率。此外,可以使用几个附加服务与 Spark 应用程序一起使用,包括日志记录、监视、安全性、容器间通信等。
有关在 Kubernetes 上使用 Spark 的更多详细信息,请访问[`github.com/apache-spark-on-k8s/spark`](https://github.com/apache-spark-on-k8s/spark)。
在下图中,虚线将 Kubernetes 与 Spark 分隔开。Spark Core 负责获取新的执行器、推送新的配置、移除执行器等。**Kubernetes 调度器后端**接受 Spark Core 的请求,并将其转换为 Kubernetes 可以理解的原语。此外,它处理所有资源请求和与 Kubernetes 的所有通信。
其他服务,如文件暂存服务器,可以使您的本地文件和 JAR 文件可用于 Spark 集群,Spark 洗牌服务可以存储动态分配资源的洗牌数据;例如,它可以实现弹性地改变特定阶段的执行器数量。您还可以扩展 Kubernetes API 以包括自定义或特定于应用程序的资源;例如,您可以创建仪表板来显示作业的进度。

Kubernetes 还提供了一些有用的管理功能,以帮助管理集群,例如 RBAC 和命名空间级别的资源配额、审计日志记录、监视节点、pod、集群级别的指标等。
# 总结
在本章中,我们介绍了几种基于 Spark SQL 的应用程序架构,用于构建高度可扩展的应用程序。我们探讨了批处理和流处理中的主要概念和挑战。我们讨论了 Spark SQL 的特性,可以帮助构建强大的 ETL 流水线。我们还介绍了一些构建可扩展监控应用程序的代码。此外,我们探讨了一种用于机器学习流水线的高效部署技术,以及使用 Mesos 和 Kubernetes 等集群管理器的一些基本概念。
总之,本书试图帮助您在 Spark SQL 和 Scala 方面建立坚实的基础。然而,仍然有许多领域可以深入探索,以建立更深入的专业知识。根据您的特定领域,数据的性质和问题可能差异很大,您解决问题的方法通常会涵盖本书中描述的一个或多个领域。然而,在所有情况下,都需要 EDA 和数据整理技能,而您练习得越多,就会变得越熟练。尝试下载并处理不同类型的数据,包括结构化、半结构化和非结构化数据。此外,阅读各章节中提到的参考资料,以深入了解其他数据科学从业者如何解决问题。参考 Apache Spark 网站获取软件的最新版本,并探索您可以在 ML 流水线中使用的其他机器学习算法。最后,诸如深度学习和基于成本的优化等主题在 Spark 中仍在不断发展,尝试跟上这些领域的发展,因为它们将是解决未来许多有趣问题的关键。 |
package datasources_test
import (
"fmt"
"testing"
acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/tfversion"
)
func TestAcc_Database(t *testing.T) {
databaseName := acc.TestClient().Ids.Alpha()
comment := random.Comment()
resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories,
TerraformVersionChecks: []tfversion.TerraformVersionCheck{
tfversion.RequireAbove(tfversion.Version1_5_0),
},
CheckDestroy: nil,
Steps: []resource.TestStep{
{
Config: database(databaseName, comment),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.snowflake_database.t", "name", databaseName),
resource.TestCheckResourceAttr("data.snowflake_database.t", "comment", comment),
resource.TestCheckResourceAttrSet("data.snowflake_database.t", "created_on"),
resource.TestCheckResourceAttrSet("data.snowflake_database.t", "owner"),
resource.TestCheckResourceAttrSet("data.snowflake_database.t", "retention_time"),
resource.TestCheckResourceAttrSet("data.snowflake_database.t", "is_current"),
resource.TestCheckResourceAttrSet("data.snowflake_database.t", "is_default"),
),
},
},
})
}
func database(databaseName, comment string) string {
return fmt.Sprintf(`
resource snowflake_database "test_database" {
name = "%v"
comment = "%v"
}
data snowflake_database "t" {
depends_on = [snowflake_database.test_database]
name = "%v"
}
`, databaseName, comment, databaseName)
} |
import React, { memo } from "react";
import {
OpaqueColorValue,
StyleSheet,
TouchableOpacityProps,
} from "react-native";
import { appRadius } from "../../utils";
import WrapIcon from "../WrapIcon";
import { AppText } from "../texts";
import ButtonWrapper from "./ButtonWrapper";
interface IIconWithLabelButton {
label: string;
iconName: string;
lblStyle?: object;
rootStyle?: object;
iconStyle?: object;
size?: number | undefined;
iconColor?: string | OpaqueColorValue;
}
const IconWithLabelButton = (
props: IIconWithLabelButton & TouchableOpacityProps
) => {
return (
<ButtonWrapper
onPress={props.onPress}
btnStyle={{ ...styles.rootStyle, ...props.rootStyle }}
>
<AppText
lblStyle={{ ...styles.lblStyle, ...props.lblStyle }}
label={props.label}
/>
<WrapIcon
size={props.size}
color={props.iconColor}
iconName={props.iconName}
rootStyle={{ ...styles.iconStyle, ...props.iconStyle }}
/>
</ButtonWrapper>
);
};
export default memo(IconWithLabelButton);
const styles = StyleSheet.create({
rootStyle: {
height: 45,
borderWidth: 0.5,
alignItems: "center",
justifyContent: "center",
borderRadius: appRadius.m,
flexDirection: "row-reverse",
},
lblStyle: {},
iconStyle: {
marginRight: 5,
},
}); |
import { useGraphQLHandler } from "~tests/helpers/useGraphQLHandler";
import { createIdentity } from "~tests/helpers/identity";
describe("get locked entry lock record", () => {
const {
lockEntryMutation,
getLockedEntryLockRecordQuery: creatorGetLockedEntryLockRecordQuery
} = useGraphQLHandler();
const { getLockedEntryLockRecordQuery } = useGraphQLHandler({
identity: createIdentity({
id: "anotherIdentityId",
displayName: "Another Identity",
type: "admin"
})
});
it("should return null for non existing lock record - getLockedEntryLockRecord", async () => {
const [response] = await getLockedEntryLockRecordQuery({
id: "nonExistingId",
type: "author"
});
expect(response).toMatchObject({
data: {
recordLocking: {
getLockedEntryLockRecord: {
data: null,
error: null
}
}
}
});
});
it("should return a record for a locked entry", async () => {
const [lockResult] = await lockEntryMutation({
id: "aTestId#0001",
type: "aTestType"
});
expect(lockResult).toMatchObject({
data: {
recordLocking: {
lockEntry: {
data: {
id: "aTestId"
},
error: null
}
}
}
});
const [shouldNotBeLockedResponse] = await creatorGetLockedEntryLockRecordQuery({
id: "aTestId#0001",
type: "author"
});
expect(shouldNotBeLockedResponse).toMatchObject({
data: {
recordLocking: {
getLockedEntryLockRecord: {
data: null,
error: null
}
}
}
});
const [shouldBeLockedResponse] = await getLockedEntryLockRecordQuery({
id: "aTestId#0001",
type: "author"
});
expect(shouldBeLockedResponse).toMatchObject({
data: {
recordLocking: {
getLockedEntryLockRecord: {
data: {
id: "aTestId"
},
error: null
}
}
}
});
});
}); |
<template>
<label v-if="label" class="mb-2 block">{{ label }}</label>
<select v-model="proxySelected"
:disabled="disabled"
class="h-9 w-full rounded bg-gray-150 border border-gray-300 py-1.5 px-3 text-sm focus:ring focus:ring-blue-200 outline-0 focus:bg-white focus:border-blue-300">
<slot></slot>
</select>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
emits: ['update:selected'],
props: {
selected: {
type: [Array, Boolean, Number, String, Object],
default: false,
},
error : {
type: Boolean,
default: false,
},
disabled: Boolean,
label: {
type: String,
required: false
}
},
computed: {
inputClasses() {
return this.error ? 'block w-full mt-1 text-sm border-red-600 dark:text-gray-300 dark:bg-gray-700 focus:border-red-400 focus:outline-none focus:shadow-outline-red form-input'
: 'block w-full mt-1 text-sm dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 form-select focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:focus:shadow-outline-gray';
},
proxySelected: {
get() {
return this.selected;
},
set(val) {
this.$emit("update:selected", val);
},
},
},
})
</script> |
import { useSelector } from "react-redux";
import avatar from "../../images/avatarold.jpg";
import insta from "../../images/insta.png";
import face from "../../images/face.png";
import github from "../../images/github.png";
import In from "../../images/in.png";
import CV from "../../Files/CV-Aren-Qochinyan.pdf";
import styles from "./Home.module.scss";
const Home = () => {
const darkTheme = useSelector(function (state) {
return state.darkTheme;
});
return (
<div
id="cont"
className={darkTheme ? styles.cont : `${styles.cont} ${styles.light}`}
>
<div className={styles.ovals}>
<div
className={
darkTheme ? styles.oval1 : `${styles.oval1} ${styles.bgBlack}`
}
></div>
<div
className={
darkTheme ? styles.oval2 : `${styles.oval2} ${styles.bgBlack}`
}
></div>
<div
className={
darkTheme ? styles.oval3 : `${styles.oval3} ${styles.bgBlack}`
}
></div>
</div>
<div className={styles.firstContent}>
<div className={styles.firstContentLeft}>
<span
className={
darkTheme ? styles.hi : `${styles.hi} ${styles.colBlack}`
}
>
Hi !
</span>{" "}
<br />
<span
className={
darkTheme
? styles.headNext
: `${styles.headNext} ${styles.colBlack}`
}
>
<b style={{ fontSize: "50px" }}>I</b>'m Aren
</span>
<br />
<a href={CV} download>
<button
className={styles.cvBut}
style={{
background: darkTheme ? "white" : "rgb(36,36,36)",
color: darkTheme ? "rgb(36,36,36)" : "white",
}}
>
Download CV
</button>
</a>
</div>
<div className={styles.firstContentRight}>
<img
style={{
borderRadius: darkTheme && "20px 0 20px 0",
padding: darkTheme && "20px 20px 0 0",
borderColor: darkTheme && "white",
}}
className={styles.avatar}
src={avatar}
/>
</div>
</div>
<div id="skills" className={`${styles.webContainer} ${styles.skills}`}>
<h1
className={
darkTheme
? `${styles.skillsHead}`
: `${styles.skillsHead} ${styles.colBlack}`
}
>
Skills
</h1>
<div className={styles.Skillscontent}>
<div
className={`${styles.col} ${styles.topSkill}`}
style={{ borderColor: darkTheme ? "white" : "rgb(36, 36, 36)" }}
>
<ul className={styles.skill}>
<li>
<span className={`${styles.expand} ${styles.html5}`}></span>
<em className={!darkTheme ? styles.colBlack : null}>HTML</em>
</li>
<li>
<span className={`${styles.expand} ${styles.css3}`}></span>
<em className={!darkTheme ? styles.colBlack : null}>CSS</em>
</li>
<li>
<span className={`${styles.expand} ${styles.figma}`}></span>
<em className={!darkTheme ? styles.colBlack : null}>Figma</em>
</li>
<li>
<span className={`${styles.expand} ${styles.js}`}></span>
<em className={!darkTheme ? styles.colBlack : null}>
JavaScript
</em>
</li>
<li>
<span className={`${styles.expand} ${styles.react}`}></span>
<em className={!darkTheme ? styles.colBlack : null}>React</em>
</li>
</ul>
</div>
<div className={styles.col}>
<ul className={styles.skill}>
<li>
<span
className={`${styles.expand} ${styles.git} ${styles.rightSkill}`}
></span>
<em className={!darkTheme ? styles.colBlack : null}>
Git / GitHub
</em>
</li>
<li>
<span
className={`${styles.expand} ${styles.ts} ${styles.rightSkill}`}
></span>
<em className={!darkTheme ? styles.colBlack : null}>
TypeScript
</em>
</li>
<li>
<span
className={`${styles.expand} ${styles.redux} ${styles.rightSkill}`}
></span>
<em className={!darkTheme ? styles.colBlack : null}>Redux</em>
</li>
</ul>
</div>
</div>
</div>
<div
id="contacts"
className={`${styles.webContainer} ${styles.contacts}`}
>
<h1
className={
darkTheme
? `${styles.skillsHead}`
: `${styles.skillsHead} ${styles.colBlack}`
}
>
Contacts
</h1>
<div className={styles.contactsCont}>
<a target="_blank" href="https://www.instagram.com/qochinyan.707/">
<img src={insta} alt="" />
</a>
<a target="_blank" href="https://www.facebook.com/qochh/">
<img src={face} alt="" />
</a>
<a target="_blank" href="https://www.github.com/qochinyan">
<img src={github} alt="" />
</a>
<a
target="_blank"
href="https://www.linkedin.com/in/aren-qochinyan-45b93924b/"
>
<img src={In} alt="" />
</a>
</div>
</div>
</div>
);
};
export default Home; |
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import Swal from 'sweetalert2';
import'./App.css'
const AddUserForm = ({ addUser }) => {
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required').min(6, 'Name must be at least 6 characters'),
email: Yup.string().required('Email is required').email('Invalid email format'),
phone: Yup.string().required('Phone number is required').matches(/^\d{10}$/, 'Invalid phone number'),
});
const initialValues = {
name: '',
email: '',
phone: '',
};
const handleSubmit = (values, { resetForm }) => {
addUser(values);
resetForm();
Swal.fire('Success!', 'User added successfully.', 'success');
};
return (
<div>
<h2 className='mt-2'>Create User</h2>
<div className='row justify-content-center '>
<div className='col sm-6 md-6 lg-6' >
<div className='card text-center p-2'>
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={handleSubmit}>
<Form>
<div className='card-title'>
<label htmlFor="name">Name</label>
<Field type="text" id="name" name="name" />
<ErrorMessage name="name" component="div" />
</div>
<div className='card-title '>
<label htmlFor="email">Email</label>
<Field type="email" id="email" name="email" />
<ErrorMessage name="email" component="div" />
</div>
<div className='card-title '>
<label htmlFor="phone">Phone</label>
<Field type="text" id="phone" name="phone" />
<ErrorMessage name="phone" component="div" />
</div>
<button className='btn btn-success btn-md'>Create</button>
</Form>
</Formik></div></div></div>
</div>
);
};
export default AddUserForm; |
/**
* @fileoverview Prevents jsx context provider values from taking values that
* will cause needless rerenders.
* @author Dylan Oshima
*/
'use strict';
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
// Recursively checks if an element is a construction.
// A construction is a variable that changes identity every render.
function isConstruction(node, callScope) {
switch (node.type) {
case 'Literal':
if (node.regex != null) {
return {type: 'regular expression', node};
}
return null;
case 'Identifier': {
const variableScoping = callScope.set.get(node.name);
if (variableScoping == null || variableScoping.defs == null) {
// If it's not in scope, we don't care.
return null; // Handled
}
// Gets the last variable identity
const variableDefs = variableScoping.defs;
const def = variableDefs[variableDefs.length - 1];
if (def != null
&& def.type !== 'Variable'
&& def.type !== 'FunctionName'
) {
// Parameter or an unusual pattern. Bail out.
return null; // Unhandled
}
if (def.node.type === 'FunctionDeclaration') {
return {type: 'function declaration', node: def.node, usage: node};
}
const init = def.node.init;
if (init == null) {
return null;
}
const initConstruction = isConstruction(init, callScope);
if (initConstruction == null) {
return null;
}
return {
type: initConstruction.type,
node: initConstruction.node,
usage: node
};
}
case 'ObjectExpression':
// Any object initialized inline will create a new identity
return {type: 'object', node};
case 'ArrayExpression':
return {type: 'array', node};
case 'ArrowFunctionExpression':
case 'FunctionExpression':
// Functions that are initialized inline will have a new identity
return {type: 'function expression', node};
case 'ClassExpression':
return {type: 'class expression', node};
case 'NewExpression':
// `const a = new SomeClass();` is a construction
return {type: 'new expression', node};
case 'ConditionalExpression':
return (isConstruction(node.consequent, callScope)
|| isConstruction(node.alternate, callScope)
);
case 'LogicalExpression':
return (isConstruction(node.left, callScope)
|| isConstruction(node.right, callScope)
);
case 'MemberExpression': {
const objConstruction = isConstruction(node.object, callScope);
if (objConstruction == null) {
return null;
}
return {
type: objConstruction.type,
node: objConstruction.node,
usage: node.object
};
}
case 'JSXFragment':
return {type: 'JSX fragment', node};
case 'JSXElement':
return {type: 'JSX element', node};
case 'AssignmentExpression': {
const construct = isConstruction(node.right);
if (construct != null) {
return {
type: 'assignment expression',
node: construct.node,
usage: node
};
}
return null;
}
case 'TypeCastExpression':
case 'TSAsExpression':
return isConstruction(node.expression);
default:
return null;
}
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Prevents JSX context provider values from taking values that will cause needless rerenders.',
category: 'Best Practices',
recommended: false,
url: docsUrl('jsx-no-constructed-context-values')
},
messages: {
withIdentifierMsg:
"The '{{variableName}}' {{type}} (at line {{nodeLine}}) passed as the value prop to the Context provider (at line {{usageLine}}) changes every render. To fix this consider wrapping it in a useMemo hook.",
withIdentifierMsgFunc:
"The '{{variableName}}' {{type}} (at line {{nodeLine}}) passed as the value prop to the Context provider (at line {{usageLine}}) changes every render. To fix this consider wrapping it in a useCallback hook.",
defaultMsg:
'The {{type}} passed as the value prop to the Context provider (at line {{nodeLine}}) changes every render. To fix this consider wrapping it in a useMemo hook.',
defaultMsgFunc:
'The {{type}} passed as the value prop to the Context provider (at line {{nodeLine}}) changes every render. To fix this consider wrapping it in a useCallback hook.'
}
},
create(context) {
return {
JSXOpeningElement(node) {
const openingElementName = node.name;
if (openingElementName.type !== 'JSXMemberExpression') {
// Has no member
return;
}
const isJsxContext = openingElementName.property.name === 'Provider';
if (!isJsxContext) {
// Member is not Provider
return;
}
// Contexts can take in more than just a value prop
// so we need to iterate through all of them
const jsxValueAttribute = node.attributes.find(
(attribute) => attribute.type === 'JSXAttribute' && attribute.name.name === 'value'
);
if (jsxValueAttribute == null) {
// No value prop was passed
return;
}
const valueNode = jsxValueAttribute.value;
if (valueNode.type !== 'JSXExpressionContainer') {
// value could be a literal
return;
}
const valueExpression = valueNode.expression;
const invocationScope = context.getScope();
// Check if the value prop is a construction
const constructInfo = isConstruction(valueExpression, invocationScope);
if (constructInfo == null) {
return;
}
// Report found error
const constructType = constructInfo.type;
const constructNode = constructInfo.node;
const constructUsage = constructInfo.usage;
const data = {
type: constructType, nodeLine: constructNode.loc.start.line
};
let messageId = 'defaultMsg';
// Variable passed to value prop
if (constructUsage != null) {
messageId = 'withIdentifierMsg';
data.usageLine = constructUsage.loc.start.line;
data.variableName = constructUsage.name;
}
// Type of expression
if (constructType === 'function expression'
|| constructType === 'function declaration'
) {
messageId += 'Func';
}
context.report({
node: constructNode,
messageId,
data
});
}
};
}
}; |
@extends('layouts.app') @section('content')<div class="content-header mt-5">
<div class="container-fluid text-center lead"><svg class="bi bi-person-circle" width="3em" height="3em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M13.468 12.37C12.758 11.226 11.195 10 8 10s-4.757 1.225-5.468 2.37A6.987 6.987 0 0 0 8 15a6.987 6.987 0 0 0 5.468-2.63z"/>
<path fill-rule="evenodd" d="M8 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/>
<path fill-rule="evenodd" d="M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1zM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8z"/>
</svg>
<h1 class="m-0 text-dark" x-text="okee"></h1>@if(session('created'))<div class="row">
<div class="col-12">
<div class="alert alert-success">Berhasil membuat user</div>
</div>
</div>@endif
</div>
</div>
<div class="content">
<div class="container lead">
<div class="row">
<div class="col-12 col-md-3 p-3 p-md-5"></div>
<div class="col-12 col-md-6 p-3 p-md-5">
<form method="post" action="{{ route('register') }}">
<div class="card-body">@if($errors->any())<div class="alert alert-danger">@foreach($errors->all() as
$error) - {{ $error }}<br>@endforeach</div>@endif
<div class="form-group"><label for="name"
x-text="namauser"></label><input id="name" placeholder="Masukkan user" type="text"
class="form-control @error('name') is-invalid @enderror" name="name"
value="{{ old('name') }}" required autocomplete="name" autofocus>
@error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="form-group"><label for="name"
x-text="emailuser"></label><input id="email" placeholder="Masukkan email" type="email"
class="form-control @error('email') is-invalid @enderror" name="email"
value="{{ old('email') }}" required autocomplete="email">
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="form-group"><label for="name"x-text="passuser"></label>
<input id="password" type="password" placeholder="Masukan password"
class="form-control @error('password') is-invalid @enderror" name="password"
required autocomplete="new-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="form-group"><label for="name"x-text="repassuser"></label>
<input id="password-confirm" placeholder="Masukkan konfirmasi password" type="password"
class="form-control" name="password_confirmation" required
autocomplete="new-password">
</div>
@csrf<button type="submit" class="btn btn-dark btn-lg btn-block">
Simpan
</button>
</form>
</div>
</div>
</div>
</div>@endsection |
<section class="container mt-2">
<div class="row d-flex align-items-center flex-wrap">
<!-- Inicio placeholder titulo-->
<p *ngIf="placeholder" class="fs-1 col-md-auto pe-0 me-3 text-center">
Loading...
</p>
<!-- Fim placeholder titulo-->
<!-- Inicio placeholder card-->
<div *ngIf="placeholder" class="container">
<div class="row">
<ngx-skeleton-loader class="overflow col-sm-4" animation="progress" count="1" [theme]="{
'height.px': 500,
'width.percent': 50,
'background-color': 'gray',
'margin-right.px' : 10,
'border-radius.px': 10
}"></ngx-skeleton-loader>
<ngx-skeleton-loader class="overflow col-sm-8" animation="progress" count="7" [theme]="{
'height.percent': 100,
'width.percent': 100,
'background-color': 'gray',
'margin-right.px' : 10,
'border-radius.px': 10
}"></ngx-skeleton-loader>
</div>
</div>
<!-- fim placeholder card-->
<p *ngIf="!placeholder" class="fs-1 col-md-auto pe-0 me-3 text-center text-white">
Anime<span class="text-color-skin">Infos</span>
</p>
<span class="col-md separador"></span>
</div>
</section>
<!-- left panel-->
<div *ngIf="!placeholder" class="d-md-flex align-items-start justify-content-center container">
<div class="flex-column col-md-4 justify-content-center text-center zoom">
<img [src]="singleAnime.images.webp.large_image_url" class="rounded mb-1 pointer" width="80%" [alt]="singleAnime.title" (click)="openModal()"/>
<p class="my-0">{{'Rating' | translate}}:</p>
<p class="my-0">{{singleAnime.rating || 'Unknown'}}</p>
</div>
<!-- right panel -->
<div class="d-flex flex-column align-items-stretch text-sm-start">
<section class="d-flex justify-content-between row">
<button class="switch-title" (click)="changeTitle(currentTitle)">
<img src="../../../../../assets/images/info/switch-name.webp" height="24px" alt="Change Title"
style="filter:invert()" />
</button>
<span class="fs-1 col-12 text-center text-color-skin mb-2">{{ currentTitle || 'N/A'}}</span>
<span class="text-muted fs-6 col-3">{{'Status' | translate}}:<p [ngClass]="{
'text-primary': singleAnime.status == 'Currently Airing',
'text-success': singleAnime.status == 'Finished Airing',
'text-danger': singleAnime.status == 'Not yet aired' }">
{{(singleAnime.status || 'N/A') | translate}}</p>
</span>
<span class="text-muted fs-6 col-3">{{'Episodes' | translate}}: <p>{{singleAnime.episodes || 'N/A'}}</p></span>
<span class="text-muted fs-6 col-3">{{'Year' | translate}}: <p>{{singleAnime.year || 'N/A'}}</p></span>
<span class="text-muted fs-6 col-3">{{'Studio' | translate}}: <p>{{singleAnime.studios[0].name || 'N/A'}}</p></span>
<span class="text-muted fs-6 col-md-auto">{{'Genres' | translate}}: <p *ngFor="let genres of singleAnime.genres"
class="mb-0">{{(genres.name || 'N/A') | translate}}</p></span>
<section class=" my-4 d-flex flex-wrap">
<a (click)="goToCrunchyRoll(singleAnime.title)" class="btn text-decoration-none text-white me-2 my-2"><img
class="me-1" src="../../../../assets/images/crunchyrol_ico.png" />CrunchyRoll</a>
<a (click)="goToFunimation(singleAnime.title)" class="btn text-decoration-none text-white me-2 my-2"><img
class="me-1" src="../../../../assets/images/funimation.ico" width="16px" height="16px" />Funimation</a>
<a *ngIf="singleAnime.trailer.url != null || singleAnime.trailer.url != ''" [href]="singleAnime.trailer.url"
class="btn text-decoration-none text-white w-auto my-2"><i class="fa fa-video-camera me-1 mb-1"
aria-hidden="true"></i>{{'Watch Trailer' | translate}}</a>
</section>
</section>
<span class="text-muted fs-6">{{'Synopsis' | translate}}:</span>
<p class="text-white overflow-auto">{{singleAnime.synopsis}}</p>
</div>
</div> |
import pytest
from tests._internal.mocks import DashCallbacksUtilMock
from pluto._internal.domain.model.expense import Expense
class TestDashCallbacksUtil:
def test_can_generate_last_twelve_months_list(self):
month_year_fmt = DashCallbacksUtilMock.month_year_fmt
expected_list = ['5/2023', '4/2023', '3/2023',
'2/2023', '1/2023', '12/2022',
'11/2022', '10/2022', '9/2022',
'8/2022', '7/2022', '6/2022']
expected_list.reverse()
assert expected_list == DashCallbacksUtilMock.get_last_twelve_months_str_list(month_year_fmt)
def test_can_get_total_of_expenses_per_month(self):
last_twelve_months = ['5/2023', '4/2023', '3/2023',
'2/2023', '1/2023', '12/2022',
'11/2022', '10/2022', '9/2022',
'8/2022', '7/2022', '6/2022']
last_twelve_months.reverse()
exp1_dict = {
'id': '1',
'user_id': '1',
'src': 'EPA',
'amount': 10,
'exp_date': '2023-01-01'
}
exp2_dict = {
'id': '2',
'user_id': '1',
'src': 'Padaria 24 horas',
'amount': 15,
'exp_date': '2023-02-01'
}
exp3_dict = {
'id': '3',
'user_id': '1',
'src': 'Farmácia',
'amount': 5,
'exp_date': '2023-03-01'
}
exp1 = Expense.from_complete_dict(exp1_dict)
exp2 = Expense.from_complete_dict(exp2_dict)
exp3 = Expense.from_complete_dict(exp3_dict)
exp_list = [exp1, exp2, exp3]
expected_expenses_per_month = {
'5/2023':0, '4/2023':0, '3/2023':5,
'2/2023':15, '1/2023':10, '12/2022':0,
'11/2022':0, '10/2022':0, '9/2022':0,
'8/2022':0, '7/2022':0, '6/2022':0
}
total_per_month = DashCallbacksUtilMock.total_amount_in_months(exp_list,
last_twelve_months
)
print(total_per_month)
print(expected_expenses_per_month)
assert total_per_month == expected_expenses_per_month
def test_invalid_url(self):
invalid_url = "/dash_entries".split('/')
assert DashCallbacksUtilMock.invalid_url(invalid_url)
invalid_url = '/dash_entries/'.split('/')
assert DashCallbacksUtilMock.invalid_url(invalid_url)
def test_not_invalid_url(self):
valid_url = '/dash_entries/daniel'.split('/')
assert not DashCallbacksUtilMock.invalid_url(valid_url) |
<template>
<div class="holder" id="app">
<div class="field __big">
<div class="table __long">
<div class="round">
<p class="title">Rounds:</p>
<p class="values">{{ round }}</p>
</div>
<div class="victories">
<p class="title">Victories:</p>
<p class="values">{{ victories }}</p>
</div>
<div class="losses">
<p class="title">Losses:</p>
<p class="values">{{ losses }}</p>
</div>
</div>
<img id="player" :src='playerItem' alt="">
<img id="indicator" :src='result' alt="">
<img id="enemy" :src='currentImage' alt="">
<div class="control __long">
<ButtonMy class="control-Btn start" v-show="showElementStart" @executeMethod="this.startGame()">
<p>start</p>
</ButtonMy>
<p class="timer" v-show="timerVisible">{{ timer }}</p>
<ButtonMy class="control-Btn reset" v-show="showElementReset" @executeMethod="this.resetFild()">
<p>reset</p>
</ButtonMy>
</div>
</div>
<ButtonMy id="paperBtn" @executeMethod="() => cardSelection('paper')" :disabled="!isButtonClickable">
<img class="btnImg" src="./assets/paper.png" alt="">
</ButtonMy>
<ButtonMy id="rockBtn" @executeMethod="() => cardSelection('rock')" :disabled="!isButtonClickable">
<img class="btnImg" src="./assets/rock.png" alt="">
</ButtonMy>
<ButtonMy id="shearsBtn" @executeMethod="() => cardSelection('shears')" :disabled="!isButtonClickable">
<img class="btnImg" src="./assets/shears.png" alt="">
</ButtonMy>
</div>
</template>
<script>
import ButtonMy from './components/ButtonMy.vue';
import arrow_back from './assets/arrow_back.png';
import arrow_forward from './assets/arrow_forward.png';
import equal from './assets/equal.png';
import paper from './assets/paper.png';
import rock from './assets/rock.png';
import shears from './assets/shears.png';
export default {
components: {
ButtonMy,
},
data(){
return {
playerItem: "",
enemyItem: "",
result: "",
currentImageKey: "",
intervalId: null,
showElementReset: false,
showElementStart: true,
isButtonClickable: false,
timerVisible: false,
round: 0,
victories: 0,
losses: 0,
timer: 0,
timeoutId: null,
intervalIdTimer: null,
cards: {
paper: paper,
rock: rock,
shears: shears,
},
indicators: {
arrow_back: arrow_back,
arrow_forward: arrow_forward,
equal: equal,
},
}
},
methods:{
gameCounter(){ // счетчик побед. записыват победы поражения в таблицу
if(this.result == this.indicators.arrow_back){
this.victories++;
} else if(this.result == this.indicators.arrow_forward){
this.losses++;
}
},
resetFild(){ // новый раунд. сбрасывает все до начальных значений
this.playerItem = "";
this.enemyItem = "";
this.result = "";
this.showElementReset = false;
this.showElementStart = true;
this.currentImageKey = '';
clearInterval(this.intervalIdTimer)
},
startAction(){ //начало хода игрока
this.timerVisible =true;
this.timer = 1;
this.intervalIdTimer = setInterval(() => { //запускает таймер
this.timer++
}, 1000)
this.timeoutId = setTimeout(() => { // таймер по истечению которого если игрок не сделал ход он проиграл
this.cardSelection(this.playerItem)
clearInterval(this.intervalIdTimer);
this.timerVisible = false;
}, 5000);
},
cardSelection(btn){ //ход игрока
this.opponentMove();
this.playerItem = this.cards[btn];
this.pause();
this.determiningTheWinner();
this.showElementReset = true;
this.isButtonClickable = false;
this.gameCounter()
clearTimeout(this.timeoutId);
clearInterval(this.intervalIdTimer);
this.timerVisible = false;
},
opponentMove(){ // выбор рандомного элемента противника
let keys = Object.keys(this.cards);
let randomKey = keys[Math.floor(Math.random() * keys.length)];
this.currentImageKey = randomKey;
this.enemyItem = this.cards[this.currentImageKey];
},
determiningTheWinner(){ //проверка результата хода
if (this.playerItem == this.enemyItem){
this.result = this.indicators.equal;
} else if (this.playerItem == this.cards.paper && this.enemyItem == this.cards.rock){
this.result = this.indicators.arrow_back;
} else if (this.playerItem == this.cards.rock && this.enemyItem == this.cards.shears){
this.result = this.indicators.arrow_back;
} else if (this.playerItem == this.cards.shears && this.enemyItem == this.cards.paper){
this.result = this.indicators.arrow_back;
} else {
this.result = this.indicators.arrow_forward;
}
},
nextElement(){ //метод с помощью которого выбирается следуйщий элемент из обьекта бля прокрутки картинки противника
let keys = Object.keys(this.cards);
const currentIndex = keys.indexOf(this.currentImageKey);
const nextIndex = (currentIndex + 1) % keys.length;
this.currentImageKey = keys[nextIndex];
},
pause(){ //останавливает интервал
clearInterval(this.intervalId);
},
startGame(){ //начинает игру
this.intervalId = setInterval(this.nextElement ,50); //прокрутка картинок проитвника
this.round++;
this.showElementStart = false;
this.isButtonClickable = true;
this.startAction()
},
},
computed: {
currentImage() { //присваевает картинку к айтеку хода противника
return this.enemyItem = this.cards[this.currentImageKey];
},
},
}
</script>
<style lang="scss" scoped>
.holder {
width: 500px;
height: 500px;
background: gray;
border-radius: 10%;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
align-items: center;
justify-items: center;
position: relative;
padding: 10%;
.field {
display: grid;
background-color: white;
width: 100%;
height: 100%;
border-radius: 10%;
padding: 10px;
align-items: center;
justify-content: space-around;
align-items: center;
justify-items: center;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
.control{
.timer{
color: black;
font-size: xx-large;
}
.control-Btn{
height: 50px;
display: flex;
align-items: center;
justify-content: center;
&.start{
background-color: darkgreen;
}
&.reset{
background-color: darkred;
}
}
}
.table{
display: flex;
justify-content: space-around;
align-items: flex-start;
width: 100%;
height: 100%;
.title{
color: black;
margin: 0;
font-size: x-large;
border-top: 2px solid black;
border-radius: 120px;
}
.values{
margin: 10px 0 0 0;
color: black;
border-bottom: 2px solid black;
border-radius: 120px;
height: 25px;
width: 120px;
}
}
}
.__big {
grid-column: span 3;
grid-row: span 2;
}
.__long {
grid-column: span 3;
grid-row: span 1;
}
}
</style> |
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap 3.3.7</title>
<link rel="shortcut icon" href="">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<!-- fontastic-->
<link href="https://file.myfontastic.com/fzWqxGRUY2qFPEtupQpRVH/icons.css" rel="stylesheet">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
132323231232132131264568464568
<!-- navbar-->
<nav class="navbar navbar-inverse navbar-full">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><i class="icon-life-ring"></i></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Jobs <span class="sr-only">(current)</span></a></li>
<li><a href="#">About</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Sign Up</a></li>
<li><a href="#">Log in</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- cover-->
<div class="cover">
<!--title-->
<div class="mainInfo wow fadeInDown">
<h1 class="coverH1 "><i class="icon-lightbulb"></i>Stressless Work</h1>
<h2 class="coverH2 ">The most easy work you never experience</h2>
<!--form -->
<form class="coverForm">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default btn-lg btnSpacing col-md-7">Let's Go</button>
<button type="submit" class="btn btn-default btn-lg btnSpacing col-md-4">LogIn</button>
<div class="clear"></div>
</div>
</form>
<br>
<!--downward Arrow-->
<div class="arrow wow pulse animated" data-wow-offset="10" data-wow-iteration="10">
<i class="icon-angle-double-down"></i>
</div>
</div>
</div>
<!-- break-->
<div class="break">e</div>
<!-- slider-->
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="img/slider/irina-219832.jpg" alt="...">
<div class="carousel-caption">
...
</div>
</div>
<div class="item">
<img src="img/slider/m0851-55542.jpg" alt="...">
<div class="carousel-caption">
...
</div>
</div>
<div class="item">
<img src="img/slider/omar-prestwich-247115.jpg" alt="...">
<div class="carousel-caption">
...
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!-- jobs-->
<div class="job">
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="img/jobs/allef-vinicius-178362.jpg" alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum illum earum sed deserunt nobis minima voluptate voluptatem velit praesentium officia, dicta tempore, itaque corporis repellendus libero quod accusamus possimus similique!</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="img/jobs/guilherme-cunha-222318.jpg" alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod quo autem tempore corporis ullam quam, suscipit asperiores officiis natus corrupti aliquam earum, quas eius laborum. Doloribus quidem reiciendis fugiat impedit.</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="img/jobs/igor-ovsyannykov-252347.jpg" alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur neque, recusandae numquam pariatur aperiam, optio alias doloremque repudiandae aut tempora itaque blanditiis ab tempore doloribus vel quasi, in quae? Dolores?</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="img/jobs/josefa-ndiaz-312261.jpg" alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem consequuntur ducimus nihil doloremque, asperiores distinctio omnis consectetur animi, quibusdam itaque minus dolorem. Explicabo ipsam eaque dolore, libero veritatis soluta porro.</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="img/jobs/ilya-pavlov-87472.jpg" alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia adipisci quae soluta asperiores iusto placeat debitis, beatae deserunt rerum eligendi, error et quisquam tempore illo ipsum repellendus vitae quibusdam consequuntur.</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="img/jobs/josefa-ndiaz-312261.jpg" alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. In a officia quia accusantium neque quam totam, provident eos odio doloremque consequatur odit, vel ratione. Optio id, reiciendis voluptatem architecto ut?</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
</div>
</div>
</div>
</div>
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
<!-- copyright-->
<div class="copyright">
<p>copyright © 2009 Joel Friedlander</p>
</div>
</div>
</div>
<!-- jquery-->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html> |
import { Backdrop, Badge, BottomNavigation, BottomNavigationAction, CircularProgress, Paper } from '@mui/material'
import React from 'react'
import { useSelector } from 'react-redux';
import { useRouter } from '@happysanta/router'
import { PAGE_MAIN, PAGE_PROPERTY, PAGE_BANK, PAGE_PROFILE } from '../routers';
import axios from '../axios.js'
import bridge from '@vkontakte/vk-bridge'
import HandshakeIcon from '@mui/icons-material/Handshake';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import MonetizationOnIcon from '@mui/icons-material/MonetizationOn';
let arr = [];
function BottomNav({ value }) {
const router = useRouter()
const debts = useSelector((state) => state.user.debts)
const greetings = useSelector((state) => state.user.greetings)
const user = useSelector((state) => state.user.user)
const [open, setOpen] = React.useState(false);
const save = async (data) => {
await axios.patch(`/auth/${user._id}`, data)
}
const handleChange = (event, newValue) => {
arr.push(newValue)
if (arr.length == 4) {
bridge.send('VKWebAppCheckNativeAds', { ad_format: 'interstitial' });
}
if (arr.length == 5) {
setOpen(true)
arr.length = 0
setTimeout(() => {
setOpen(false)
bridge.send('VKWebAppShowNativeAds', { ad_format: 'interstitial' })
.then((data) => {
if (data.result) {
console.log('Реклама показана');
save(user)
router.pushPage(newValue)
}
else
console.log('Ошибка при показе');
})
.catch((error) => { console.log(error); });
}, 1000)
} else {
save(user)
router.pushPage(newValue)
}
};
return (
<Paper sx={{ position: 'fixed', bottom: 0, left: 0, right: 0 }} elevation={3}>
<Backdrop
sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
open={open}
>
<CircularProgress color="inherit" />
</Backdrop>
<BottomNavigation
value={value}
onChange={handleChange}
>
<BottomNavigationAction label="Главная" value={PAGE_MAIN} icon={<MonetizationOnIcon />} />
<BottomNavigationAction label="Сделки" value={PAGE_PROPERTY} icon={<HandshakeIcon />} />
<BottomNavigationAction label="Банк" value={PAGE_BANK} icon={
<Badge color="secondary" variant="dot" invisible={!debts}>
<AccountBalanceIcon />
</Badge>
} />
<BottomNavigationAction label='Профиль' value={PAGE_PROFILE} icon={
<Badge color="secondary" variant="dot" invisible={!greetings}>
<AccountCircleIcon />
</Badge>
} />
</BottomNavigation>
</Paper>
)
}
export default BottomNav |
import { Link } from "react-router-dom";
import { FaBars, FaCartPlus } from "react-icons/fa";
import { useEffect, useState } from "react";
import Cookies from "js-cookie";
import { doc, collection, getDocs, getDoc } from "firebase/firestore";
import fireDB from "../fireConfig";
function Header() {
const token = Cookies.get("Token");
const uid = Cookies.get("id");
const [cartItems, setCartItems] = useState([]);
const [email, setEmail] = useState("");
const [cartNumber, setCartNumber] = useState();
const getEmail = async () => {
const userRef = doc(fireDB, "users", uid);
const docSnap = await getDoc(userRef);
const data = docSnap.data().email;
setEmail(data);
};
useEffect(() => {
getCartItems();
});
useEffect(() => {
getEmail();
}, []);
const logout = () => {
Cookies.remove("Token");
Cookies.remove("id");
window.location.reload();
};
const getCartItems = async () => {
try {
const itemArray = [];
const querySnapshot = await getDocs(
collection(fireDB, "cart", uid, "items")
);
querySnapshot.forEach((doc) => {
itemArray.push(doc.data());
});
const length = itemArray.length;
console.log(length);
setCartNumber(length);
} catch (error) {
console.log(error);
}
};
return (
<div className="header">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container-fluid ms-3 ">
<Link className="navbar-brand ms-5" to="/">
E-mart
</Link>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span>
<FaBars size={25} color="white" />
</span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ms-auto">
<li className="nav-item">
<Link
className="nav-link active"
aria-current="page"
to="/products"
>
Products
</Link>
</li>
<li className="nav-item">
{token ? (
<Link
className="nav-link active"
aria-current="page"
to="/orders"
>
{email.substring(0, email.length - 10)}
</Link>
) : (
<Link
className="nav-link active"
aria-current="page"
to="/login"
>
Login
</Link>
)}
</li>
<li className="nav-item">
{token ? (
<Link className="nav-link" to="/" onClick={logout}>
Logout
</Link>
) : (
""
)}
</li>
<li className="nav-item">
<Link className="nav-link" to="/cart">
<FaCartPlus /> {cartNumber}
</Link>
</li>
</ul>
</div>
</div>
</nav>
</div>
);
}
export default Header; |
import pandas as pd
import re
import nltk
import sklearn
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# Define the pipeline globally
pipeline = Pipeline([
('vectorizer', TfidfVectorizer()),
('classifier', LogisticRegression())
])
def preprocess_text(text: str) -> str:
"""
Preprocesses the text by removing special characters, converting to lowercase,
and lemmatizing the words.
Args:
text (str): The input text to be preprocessed.
Returns:
str: The preprocessed text.
"""
lemma = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))
msgs = re.sub('[^a-zA-Z]', ' ', text).lower().split() # removing special characters and converting to lowercase
msgs = [lemma.lemmatize(word) for word in msgs if word not in stop_words] # lemmatizing the words and removing stopwords
msgs = ' '.join(msgs) # joining the words again to form a sentence
return msgs
def train_and_evaluate_model(df: pd.DataFrame) -> float:
"""
Trains and evaluates a logistic regression model on the given dataframe.
Args:
df (pd.DataFrame): The input dataframe containing the dataset.
Returns:
float: The accuracy score of the model.
"""
df['Spam'] = pd.get_dummies(df['Category'], drop_first=True) # encoding the target variable
y = df['Spam'] # target variable
messages = df['Message'] # feature / input variable
corpus = [preprocess_text(i) for i in messages] # preprocessing the input text
x_train, x_test, y_train, y_test = train_test_split(corpus, y, test_size=0.2, random_state=42) # splitting the dataset into train and test
pipeline.fit(x_train, y_train)
pred = pipeline.predict(x_test)
acc_score = accuracy_score(y_test, pred)
return acc_score
# Reading the dataset:
df = pd.read_csv('spam.csv')
# Train and evaluate the model:
accuracy = train_and_evaluate_model(df)
print(f"Accuracy Score: {accuracy}")
# Reading the User email as input:
user_input = input("Enter your email: ")
user_email = preprocess_text(user_input)
prediction = pipeline.predict([user_email])
if prediction[0] == 0:
print("Your email is Not Spam")
else:
print("Your email is Spam! Hope you don't get it") |
import React, {Component} from 'react'
import { Text, View,Dimensions,StyleSheet } from 'react-native'
import {Constants,MapView,Location,Permissions} from "expo";
const window = Dimensions.get('window');
const {width,height}=window;
export default class MapScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
locationResult:null,
location:{
coords:{
latitude : -7.966,
longitude : 112.632
}
},
mapRegion:{
latitude : -7.966,
longitude : 112.632,
latitudeDelta: 0.0922,
longitudeDelta: 0.0922
}
};
};
componentWillMount(){
this._getLocationAsync();
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
this.setState({
errorMessage: 'Permission to access location was denied',
});
}
let location = await Location.getCurrentPositionAsync({});
this.setState({ location });
};
render() {
return (
<View style={styles.container}>
<MapView style={styles.map}
region={{
latitude: this.state.location.coords.latitude,
longitude: this.state.location.coords.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0922
}}
>
<MapView.Marker
coordinate={this.state.location.coords}
title="My Location"
description="Hello"
/>
</MapView>
<Text>{JSON.stringify(this.state.location)}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
map: {
alignSelf:'stretch',
height:window.height*0.8
},
paragraph: {
margin: 24,
fontSize: 18,
textAlign: 'center',
},
}); |
# Functions to output and edit C values for age-structured groups
# 1) get_param_C_age()
# 2) edit_param_C_age()
# 1) get_param_C_age -------------------------------------------------------
get_param_C_age = function(bio.prm, write.output = F, output.dir, out.name ){
bio.lines = readLines(bio.prm)
bio.lines.id = grep('^C_.*',bio.lines)
bio.lines.vals1 = bio.lines[bio.lines.id]
which.invert = grepl('_T15',bio.lines.vals1)
bio.lines.vals1 = bio.lines.vals1[!which.invert]
bio.lines.id = bio.lines.id[!which.invert]
group.names =unname(sapply(bio.lines.vals1,function(x) strsplit(x,'C_|\t10.00|\t| ')[[1]][2]))
max.age = max(as.numeric(sapply(bio.lines.vals1,function(x) strsplit(x,'C_|\t| ')[[1]][3])))
C.mat = matrix(NA, nrow = length(group.names),ncol = max.age)
colnames(C.mat) = paste0('C',1:max.age)
out.df = data.frame(C.mat)
out.df = cbind(data.frame(group = group.names),out.df)
for(i in 1:length(bio.lines.id)){
C.group = bio.lines[bio.lines.id[i] + 1 ]
C.split = strsplit(C.group,split = "\t| | ")[[1]]
if(length(C.split)>max.age){print(paste0(group.names[i],' has ',length(C.split)-10,' trailing tabs ',i))}
C.out = rep(NA,max.age)
C.out[1:length(C.split)] = C.split
out.df[i,2:ncol(out.df)] = C.out
}
if(write.output){
write.csv(out.df, file = paste0(output.dir,out.name,'.csv'),row.names = F)
}else{
return(out.df)
}
}
# edit_param_C_age ------------------------------------------------------
edit_param_C_age = function(bio.prm, new.C, overwrite = F,new.file.name,single.group = F, group.name = NA ){
#Get C_XXX bio.prm lines
bio.lines = readLines(bio.prm)
bio.lines.id = grep('^C_',bio.lines)
bio.lines.vals = bio.lines[bio.lines.id]
which.invert = grepl('_T15',bio.lines.vals)
bio.lines.vals = bio.lines.vals[!which.invert]
bio.lines.id = bio.lines.id[!which.invert]
group.names =unname(sapply(bio.lines.vals,function(x) strsplit(x,'C_|\t10.00|\t| ')[[1]][2]))
max.age = max(as.numeric(sapply(bio.lines.vals,function(x) strsplit(x,'C_|\t| ')[[1]][3])))
if(single.group){
ind = which(group.name == group.names)
new.C = new.C[!is.na(new.C)]
C.string = paste(new.C,collapse = '\t')
bio.lines[bio.lines.id[ind]+1] = C.string
}else{
for(i in 1:nrow(new.C)){
ind = which(group.names == new.C$group[i])
C.string = new.C[i,2:ncol(new.C)]
which.na = which(is.na(C.string))
if(length(which.na > 0)){C.string = C.string[-which.na]}
C.string = paste(C.string,collapse='\t')
bio.lines[bio.lines.id[ind]+1] = C.string
}
}
#overwrite or make copy of biology file
if(overwrite){
writeLines(bio.lines, con = bio.prm)
}else{
file.copy(bio.prm, new.file.name, overwrite = T)
writeLines(bio.lines, con = new.file.name )
}
}
# Example -----------------------------------------------------------------
# bio.prm = here::here('currentVersion','at_biology.prm')
# bio.orig = 'C:/Users/joseph.caracappa/Documents/Atlantis/Parameter_Files/at_biol_neus_v15_scaled_diet_20181126_3.prm'
# output.dir = 'C:/Users/joseph.caracappa/Documents/Atlantis/Obs_Hindcast/Diagnostic_Data/'
# out.name = 'New_Init_CatchTS_C_age'
# # new.C.df = read.csv(paste0(output.dir,'C_age_test_new.csv'),stringsAsFactors = F)
# # new.file.name = here::here('currentVersion','at_biology_test.prm')
#
# get_param_C_age(bio.prm=bio.prm, write.output = T,output.dir = output.dir, out.name = out.name)
# get_param_C_age(bio.prm=bio.orig, write.output = T,output.dir = output.dir, out.name = 'Orig_C_RM')
# new.C.df = read.csv(paste0(output.dir,'Reset_C_New_Init.csv'),stringsAsFactors = F)
# edit_param_C_age(bio.prm, new.C.df,overwrite = T) |
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/static-site-file-based-routing/">
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
body {
margin: 0;
padding: 0;
}
header nav {
display: flex;
gap: 1rem;
background-color: black;
color: white;
padding: 1rem;
}
nav a {
color: white;
text-decoration: none;
}
nav a:hover {
text-decoration: underline;
}
nav a[data-selected] {
text-decoration: underline;
color: rgb(184, 184, 184);
}
main {
margin: 0 auto;
max-width: 800px;
display: flex;
flex-direction: column;
}
img {
max-width: 100%;
}
</style>
<link rel="stylesheet" href="styles.css">
<title>Example</title>
</head>
<body>
<header>
<nav>
<a href="">Home</a>
<a href="dashboard/">Dashboard</a>
<a href="demo/">Demo</a>
<a href="faq/">FAQ</a>
</nav>
</header>
<main>
<slot></slot>
</main>
<script>
// Update the selected nav link
const links = document.querySelectorAll('nav a');
const baseHref = document.querySelector('base').getAttribute('href').split('/').join('');
const pathname = window.location.pathname.split('/').join('').replace(baseHref, '');
const currentPath = !pathname ? `/${baseHref}/` : `/${baseHref}/${pathname}/`;
for (const link of links) {
if (link.pathname === currentPath) {
link.setAttribute('data-selected', '');
}
}
</script>
</body>
</html> |
import { useEffect, useState } from "react";
const Category = () => {
const [categories, setCategories] = useState([]);
useEffect(() => {
fetch("category.json")
.then((res) => res.json())
.then((data) => setCategories(data));
}, []);
return (
<>
<div className="flex flex-col items-center">
<h1 className="mb-4 text-4xl font-bold">Job Category List</h1>
<p className="mb-8 text-base font-medium text-gray-500">
Explore thousands of job opportunities with all the information you
need. Its your future
</p>
</div>
<div className="mb-20 flex justify-center gap-x-8">
{categories.map((category) => (
<div
key={category.id}
className="rounded-lg border-2 bg-indigo-50 p-10"
>
<img className="mb-6" src={category.image} alt="accounts" />
<h1 className="mb-4 text-xl font-bold">{category.name}</h1>
<p className="text-base font-medium text-gray-500">
{category.jobs_count} Jobs available
</p>
</div>
))}
</div>
</>
);
};
export default Category; |
package jeecg.kxcomm.controller.contactm;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jeecg.kxcomm.entity.contactm.TbContractEntity;
import jeecg.kxcomm.entity.contactm.TbInventoryEntity;
import jeecg.kxcomm.entity.contactm.TbOrderEntity;
import jeecg.kxcomm.service.contactm.TbInventoryServiceI;
import jeecg.system.service.SystemService;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
* @Title: Controller
* @Description: 产品库存
* @author zhangdaihao
* @date 2013-10-22 11:08:57
* @version V1.0
*
*/
@Controller
@RequestMapping("/tbInventoryController")
public class TbInventoryController extends BaseController {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(TbInventoryController.class);
@Autowired
private TbInventoryServiceI tbInventoryService;
@Autowired
private SystemService systemService;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* 产品库存列表 页面跳转
*
* @return
*/
@RequestMapping(params = "tbInventory")
public ModelAndView tbInventory(HttpServletRequest request) {
return new ModelAndView("jeecg/kxcomm/contactm/tbInventoryList");
}
/**
* easyui AJAX请求数据
*
* @param request
* @param response
* @param dataGrid
* @param user
*/
@RequestMapping(params = "datagrid")
public void datagrid(TbInventoryEntity tbInventory,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
CriteriaQuery cq = new CriteriaQuery(TbInventoryEntity.class, dataGrid);
//查询条件组装器
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tbInventory);
this.tbInventoryService.getDataGridReturn(cq, true);
TagUtil.datagrid(response, dataGrid);
}
/**
* 删除产品库存
*
* @return
*/
@RequestMapping(params = "del")
@ResponseBody
public AjaxJson del(TbInventoryEntity tbInventory, HttpServletRequest request) {
AjaxJson j = new AjaxJson();
tbInventory = systemService.getEntity(TbInventoryEntity.class, tbInventory.getId());
message = "删除成功";
tbInventoryService.delete(tbInventory);
systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
j.setMsg(message);
return j;
}
/**
* 添加产品库存
*
* @param ids
* @return
*/
@RequestMapping(params = "save")
@ResponseBody
public AjaxJson save(TbInventoryEntity tbInventory, HttpServletRequest request) {
AjaxJson j = new AjaxJson();
if(tbInventory.getContractno()!=null && tbInventory.getContractno().equals("null")){
tbInventory.setContractno(null);
}
if(tbInventory.getKxorderno()!=null && tbInventory.getKxorderno().equals("null")){
tbInventory.setKxorderno(null);
}
if (StringUtil.isNotEmpty(tbInventory.getId())) {
message = "更新成功";
TbInventoryEntity t = tbInventoryService.get(TbInventoryEntity.class, tbInventory.getId());
try {
MyBeanUtils.copyBeanNotNull2Bean(tbInventory, t);
tbInventoryService.saveOrUpdate(t);
systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
} catch (Exception e) {
e.printStackTrace();
}
} else {
message = "添加成功";
tbInventoryService.save(tbInventory);
systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
}
return j;
}
/**
* 产品库存列表页面跳转
*
* @return
*/
@RequestMapping(params = "addorupdate")
public ModelAndView addorupdate(TbInventoryEntity tbInventory, HttpServletRequest req) {
List<TbContractEntity> contractList = systemService.getList(TbContractEntity.class);
req.setAttribute("contractList", contractList);
List<TbOrderEntity> orderList = systemService.getList(TbOrderEntity.class);
req.setAttribute("orderList", orderList);
if (StringUtil.isNotEmpty(tbInventory.getId())) {
tbInventory = tbInventoryService.getEntity(TbInventoryEntity.class, tbInventory.getId());
req.setAttribute("tbInventoryPage", tbInventory);
}
return new ModelAndView("jeecg/kxcomm/contactm/tbInventory");
}
} |
import { useEffect, useState } from 'react'
import { HashRouter, Route, Routes } from 'react-router-dom'
import './App.css'
import PokemonDetail from './components/PokemonDetail'
import Pokemons from './components/Pokemons'
import ProtectedRoutes from './components/ProtectedRoutes'
import UserInput from './components/UserInput'
function App() {
const [isLoading, setIsLoading] = useState(true);
useEffect(()=>{
setTimeout(() => {
setIsLoading(false);
}, 2500);
},[])
return (
<div className="App">
<HashRouter>
<Routes>
<Route path='/' element={<UserInput isLoading={isLoading} />} />
<Route element={<ProtectedRoutes />}>
<Route path='/pokemons' element={<Pokemons
/>} />
<Route path='/pokemons/:id' element={<PokemonDetail />} />
</Route>
</Routes>
</HashRouter>
</div>
)
}
export default App |
// Copyright (C) 2011 ~ 2018 Deepin Technology Co., Ltd.
// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: LGPL-3.0-or-later
#ifndef PLUGINSITEM_H
#define PLUGINSITEM_H
#include "dockitem.h"
#include "pluginsiteminterface.h"
class QGSettings;
class PluginsItem : public DockItem
{
Q_OBJECT
friend class QuickSettingController;
public:
~PluginsItem() override;
int itemSortKey() const;
void setItemSortKey(const int order) const;
void detachPluginWidget();
QString pluginName() const;
PluginsItemInterface::PluginSizePolicy pluginSizePolicy() const;
using DockItem::showContextMenu;
using DockItem::hidePopup;
ItemType itemType() const override;
QSize sizeHint() const override;
QWidget *centralWidget() const;
virtual void setDraging(bool bDrag) override;
PluginsItemInterface *pluginItem() const;
public slots:
void refreshIcon() override;
protected:
explicit PluginsItem(PluginsItemInterface *const pluginInter, const QString &itemKey, const QJsonObject &jsonData, QWidget *parent = nullptr);
private slots:
void onGSettingsChanged(const QString &key);
protected:
void mousePressEvent(QMouseEvent *e) override;
void mouseMoveEvent(QMouseEvent *e) override;
void mouseReleaseEvent(QMouseEvent *e) override;
void enterEvent(QEvent *event) override;
void leaveEvent(QEvent *event) override;
bool eventFilter(QObject *watched, QEvent *event) override;
void showEvent(QShowEvent *event) override;
void invokedMenuItem(const QString &itemId, const bool checked) override;
void showPopupWindow(QWidget *const content, const bool model = false) override;
const QString contextMenu() const override;
QWidget *popupTips() override;
void resizeEvent(QResizeEvent *event) override;
private:
void startDrag();
void mouseClicked();
bool checkGSettingsControl() const;
QString pluginApi() const;
private:
PluginsItemInterface *const m_pluginInter;
QWidget *m_centralWidget;
QJsonObject m_jsonData;
const QString m_itemKey;
bool m_dragging;
static QPoint MousePressPoint;
const QGSettings *m_gsettings;
};
#endif // PLUGINSITEM_H |
'use client';
import { Image } from '$components/image';
import { useHeaderFilled } from '$hooks/use-header-filled';
import { Box, Flex, Heading, Icon, SimpleGrid, Text } from '@chakra-ui/react';
import { useCallback, useState } from 'react';
import { PiCalendarBlank, PiMagnifyingGlassPlusFill } from 'react-icons/pi';
import { Fade } from '$components/animations/fade';
import { DefaultContainer } from '$components/default-container';
import 'yet-another-react-lightbox/styles.css';
import { PhotoLightbox } from './photo-lightbox';
export interface Photo {
title: string;
description: string;
createdAt: string;
updatedAt: string;
thumbnail: string;
images: string[];
}
export interface PhotoTemplateProps {
photo: Photo;
}
export function PhotoTemplate({ photo }: PhotoTemplateProps) {
useHeaderFilled(true);
const [currentImageIndex, setCurrentImage] = useState(0);
const [isLightboxOpen, setIsViewerOpen] = useState(false);
const openLightbox = useCallback((index: number) => {
setCurrentImage(index);
setIsViewerOpen(true);
}, []);
const closeLightbox = () => {
setCurrentImage(0);
setIsViewerOpen(false);
};
return (
<>
<Flex h="50px" w="full" display={{ base: 'block', lg: 'none' }} />
<Flex as={DefaultContainer} direction="column" w="full" py="16">
<Flex direction="column" mb="4">
<Fade delay={300}>
<Heading maxW="100%" fontSize="2xl" title={photo.title}>
{photo.title}
</Heading>
</Fade>
<Fade delay={500}>
<Text color="gray.500" mt="2">
{photo.description}
</Text>
</Fade>
<Fade delay={700}>
<Text
as="time"
color="gray700"
mb="2"
mt="4"
fontSize="md"
display="flex"
alignItems="center"
>
<Icon as={PiCalendarBlank} mr="1" /> {photo.createdAt}
</Text>
</Fade>
</Flex>
<SimpleGrid
w="full"
spacing={4}
minChildWidth={{ base: '220px', sm: '320px' }}
justifyItems="center"
>
{photo.images.map((image, index) => (
<Box
key={image}
as={Fade}
fraction={0}
delay={index > 2 ? 0 : 500 * (index + 1) * 0.5}
h={{ base: '320px', sm: '420px' }}
w="100%"
>
<Box
onClick={() => openLightbox(index)}
pos="relative"
h={{ base: '320px', sm: '420px' }}
w="full"
role="group"
cursor="pointer"
>
<Icon
as={PiMagnifyingGlassPlusFill}
pos="absolute"
top="50%"
left="50%"
transform="translate(-50%, -50%)"
zIndex="1"
color="white"
fontSize="6xl"
opacity="0"
transition="0.2s ease-in-out"
_groupHover={{
opacity: 1,
}}
/>
<Image
src={image}
alt={`Foto ${index} - ${photo.title}`}
pos="absolute"
top="0"
bottom="0"
left="0"
right="0"
w="full"
h="full"
objectFit="cover"
filter="auto"
transition="0.2s ease-in-out"
_groupHover={{
brightness: '0.5',
}}
/>
</Box>
</Box>
))}
</SimpleGrid>
<PhotoLightbox
images={photo.images}
isOpen={isLightboxOpen}
index={currentImageIndex}
onClose={closeLightbox}
/>
</Flex>
</>
);
} |
/*
* SonarQube
* Copyright (C) 2009-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission.index;
import com.google.common.collect.ImmutableList;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.sonar.db.DatabaseUtils.executeLargeInputs;
/**
* No streaming because of union of joins -> no need to use ResultSetIterator
*/
public class PermissionIndexerDao {
private enum RowKind {
USER, GROUP, ANYONE, NONE
}
private static final String SQL_TEMPLATE = "SELECT " +
" project_authorization.kind as kind, " +
" project_authorization.project as project, " +
" project_authorization.user_uuid as user_uuid, " +
" project_authorization.group_uuid as group_uuid, " +
" project_authorization.qualifier as qualifier " +
"FROM ( " +
// users
" SELECT '" + RowKind.USER + "' as kind," +
" c.uuid AS project, " +
" c.qualifier AS qualifier, " +
" user_roles.user_uuid AS user_uuid, " +
" NULL AS group_uuid " +
" FROM components c " +
" INNER JOIN user_roles ON user_roles.component_uuid = c.uuid AND user_roles.role = 'user' " +
" WHERE " +
" (c.qualifier = 'TRK' " +
" or c.qualifier = 'VW' " +
" or c.qualifier = 'APP') " +
" AND c.copy_component_uuid is NULL " +
" {projectsCondition} " +
" UNION " +
// groups
" SELECT '" + RowKind.GROUP + "' as kind," +
" c.uuid AS project, " +
" c.qualifier AS qualifier, " +
" NULL AS user_uuid, " +
" groups.uuid AS group_uuid " +
" FROM components c " +
" INNER JOIN group_roles ON group_roles.component_uuid = c.uuid AND group_roles.role = 'user' " +
" INNER JOIN groups ON groups.uuid = group_roles.group_uuid " +
" WHERE " +
" (c.qualifier = 'TRK' " +
" or c.qualifier = 'VW' " +
" or c.qualifier = 'APP') " +
" AND c.copy_component_uuid is NULL " +
" {projectsCondition} " +
" AND group_uuid IS NOT NULL " +
" UNION " +
// public projects are accessible to any one
" SELECT '" + RowKind.ANYONE + "' as kind," +
" c.uuid AS project, " +
" c.qualifier AS qualifier, " +
" NULL AS user_uuid, " +
" NULL AS group_uuid " +
" FROM components c " +
" WHERE " +
" (c.qualifier = 'TRK' " +
" or c.qualifier = 'VW' " +
" or c.qualifier = 'APP') " +
" AND c.copy_component_uuid is NULL " +
" AND c.private = ? " +
" {projectsCondition} " +
" UNION " +
// private project is returned when no authorization
" SELECT '" + RowKind.NONE + "' as kind," +
" c.uuid AS project, " +
" c.qualifier AS qualifier, " +
" NULL AS user_uuid, " +
" NULL AS group_uuid " +
" FROM components c " +
" WHERE " +
" (c.qualifier = 'TRK' " +
" or c.qualifier = 'VW' " +
" or c.qualifier = 'APP') " +
" AND c.copy_component_uuid is NULL " +
" AND c.private = ? " +
" {projectsCondition} " +
" ) project_authorization";
List<IndexPermissions> selectAll(DbClient dbClient, DbSession session) {
return doSelectByProjects(dbClient, session, Collections.emptyList());
}
public List<IndexPermissions> selectByUuids(DbClient dbClient, DbSession session, Collection<String> projectOrViewUuids) {
// we use a smaller partitionSize because the SQL_TEMPLATE contain 4x the list of project uuid.
// the MsSQL jdbc driver accept a maximum of 2100 prepareStatement parameter. To stay under the limit,
// we go with batch of 1000/2=500 project uuids, to stay under the limit (4x500 < 2100)
return executeLargeInputs(projectOrViewUuids, subProjectOrViewUuids -> doSelectByProjects(dbClient, session, subProjectOrViewUuids), i -> i / 2);
}
private static List<IndexPermissions> doSelectByProjects(DbClient dbClient, DbSession session, List<String> projectUuids) {
try {
Map<String, IndexPermissions> dtosByProjectUuid = new HashMap<>();
try (PreparedStatement stmt = createStatement(dbClient, session, projectUuids);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
processRow(rs, dtosByProjectUuid);
}
return ImmutableList.copyOf(dtosByProjectUuid.values());
}
} catch (SQLException e) {
throw new IllegalStateException("Fail to select authorizations", e);
}
}
private static PreparedStatement createStatement(DbClient dbClient, DbSession session, List<String> projectUuids) throws SQLException {
String sql;
if (projectUuids.isEmpty()) {
sql = StringUtils.replace(SQL_TEMPLATE, "{projectsCondition}", "");
} else {
sql = StringUtils.replace(SQL_TEMPLATE, "{projectsCondition}", " AND c.uuid in (" + repeat("?", ", ", projectUuids.size()) + ")");
}
PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql);
int index = 1;
// query for RowKind.USER
index = populateProjectUuidPlaceholders(stmt, projectUuids, index);
// query for RowKind.GROUP
index = populateProjectUuidPlaceholders(stmt, projectUuids, index);
// query for RowKind.ANYONE
index = setPrivateProjectPlaceHolder(stmt, index, false);
index = populateProjectUuidPlaceholders(stmt, projectUuids, index);
// query for RowKind.NONE
index = setPrivateProjectPlaceHolder(stmt, index, true);
populateProjectUuidPlaceholders(stmt, projectUuids, index);
return stmt;
}
private static int populateProjectUuidPlaceholders(PreparedStatement stmt, List<String> projectUuids, int index) throws SQLException {
int newIndex = index;
for (String projectUuid : projectUuids) {
stmt.setString(newIndex, projectUuid);
newIndex++;
}
return newIndex;
}
private static int setPrivateProjectPlaceHolder(PreparedStatement stmt, int index, boolean isPrivate) throws SQLException {
int newIndex = index;
stmt.setBoolean(newIndex, isPrivate);
newIndex++;
return newIndex;
}
private static void processRow(ResultSet rs, Map<String, IndexPermissions> dtosByProjectUuid) throws SQLException {
RowKind rowKind = RowKind.valueOf(rs.getString(1));
String projectUuid = rs.getString(2);
IndexPermissions dto = dtosByProjectUuid.get(projectUuid);
if (dto == null) {
String qualifier = rs.getString(5);
dto = new IndexPermissions(projectUuid, qualifier);
dtosByProjectUuid.put(projectUuid, dto);
}
switch (rowKind) {
case NONE:
break;
case USER:
dto.addUserUuid(rs.getString(3));
break;
case GROUP:
dto.addGroupUuid(rs.getString(4));
break;
case ANYONE:
dto.allowAnyone();
break;
}
}
} |
import SwiftUI
struct PopupNoticeWindowView: View {
var title: String
var message: String
var buttonText: String
@Binding var show: Bool
var body: some View {
GeometryReader { geo in
ZStack {
if show {
// PopUp background color
Color.black.opacity(show ? 0.8 : 0)
.edgesIgnoringSafeArea(.all)
// PopUp Window
VStack(alignment: .center, spacing: 0) {
Text(title)
.frame(maxWidth: .infinity)
.frame(height: 45, alignment: .center)
.font(Font.system(size: 23, weight: .semibold))
.foregroundColor(Color.white)
.background(Color(red: 0.3, green: 0.3, blue: 0.6))
Text(message)
.multilineTextAlignment(.leading)
.font(Font.system(size: 16, weight: .semibold))
.padding(EdgeInsets(top: 20, leading: 25, bottom: 20, trailing: 25))
.foregroundColor(Color.white)
Button(action: {
// Dismiss the PopUp
withAnimation(.linear(duration: 0.3)) {
show = false
}
}, label: {
Text(buttonText)
.frame(maxWidth: .infinity)
.frame(height: 54, alignment: .center)
.foregroundColor(Color.white)
.background(Color(red: 0.2, green: 0.2, blue: 0.2))
.font(Font.system(size: 23, weight: .semibold))
}).buttonStyle(PlainButtonStyle())
}
.frame(maxWidth: geo.size.width * 0.8)
.border(Color.white, width: 2)
.background(Color(red: 0.3, green: 0.3, blue: 0.3))
}
}
}
}
} |
import React, { useEffect, useState } from "react";
import { useTheme } from "../../Context/ThemeContext";
import styles from "./Content.module.css";
function Content() {
const { theme } = useTheme();
const [photos, setPhotos] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/photos?_limit=50")
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
setPhotos(data);
})
.catch((error) => {
console.error("Error fetching data:", error);
});
}, []);
return (
<div className={`${styles.content} ${theme}`}>
<h1 className={styles.heading1}>This is the content</h1>
<div className={styles.photo_list}>
<div className={styles.grid_container}>
{photos.map((photo) => (
<div key={photo.id} className={styles.grid_item}>
<img src={photo.thumbnailUrl} alt={photo.title} />
<p className={styles.title}>{photo.title}</p>
</div>
))}
</div>
</div>
</div>
);
}
export default Content; |
# frozen_string_literal: true
module Gitlab
module ErrorTracking
module Processor
class GrpcErrorProcessor < ::Raven::Processor
DEBUG_ERROR_STRING_REGEX = RE2('(.*) debug_error_string:(.*)')
def process(payload)
return payload if ::Feature.enabled?(:sentry_processors_before_send, default_enabled: :yaml)
self.class.process_first_exception_value(payload)
self.class.process_custom_fingerprint(payload)
payload
end
class << self
def call(event)
return event unless ::Feature.enabled?(:sentry_processors_before_send, default_enabled: :yaml)
process_first_exception_value(event)
process_custom_fingerprint(event)
event
end
# Sentry can report multiple exceptions in an event. Sanitize
# only the first one since that's what is used for grouping.
def process_first_exception_value(event_or_payload)
exceptions = exceptions(event_or_payload)
return unless exceptions.is_a?(Array)
exception = exceptions.first
return unless valid_exception?(exception)
exception_type, raw_message = type_and_value(exception)
return unless exception_type&.start_with?('GRPC::')
return unless raw_message.present?
message, debug_str = split_debug_error_string(raw_message)
set_new_values!(event_or_payload, exception, message, debug_str)
end
def process_custom_fingerprint(event)
fingerprint = fingerprint(event)
return event unless custom_grpc_fingerprint?(fingerprint)
message, _ = split_debug_error_string(fingerprint[1])
fingerprint[1] = message if message
end
private
def custom_grpc_fingerprint?(fingerprint)
fingerprint.is_a?(Array) && fingerprint.length == 2 && fingerprint[0].start_with?('GRPC::')
end
def split_debug_error_string(message)
return unless message
match = DEBUG_ERROR_STRING_REGEX.match(message)
return unless match
[match[1], match[2]]
end
# The below methods can be removed once we remove the
# sentry_processors_before_send feature flag, and we can
# assume we always have an Event object
def exceptions(event_or_payload)
case event_or_payload
when Raven::Event
# Better in new version, will be event_or_payload.exception.values
event_or_payload.instance_variable_get(:@interfaces)[:exception]&.values
when Hash
event_or_payload.dig(:exception, :values)
end
end
def valid_exception?(exception)
case exception
when Raven::SingleExceptionInterface
exception&.value
when Hash
true
else
false
end
end
def type_and_value(exception)
case exception
when Raven::SingleExceptionInterface
[exception.type, exception.value]
when Hash
exception.values_at(:type, :value)
end
end
def set_new_values!(event_or_payload, exception, message, debug_str)
case event_or_payload
when Raven::Event
# Worse in new version, no setter! Have to poke at the
# instance variable
exception.value = message if message
event_or_payload.extra[:grpc_debug_error_string] = debug_str if debug_str
when Hash
exception[:value] = message if message
extra = event_or_payload[:extra] || {}
extra[:grpc_debug_error_string] = debug_str if debug_str
end
end
def fingerprint(event_or_payload)
case event_or_payload
when Raven::Event
event_or_payload.fingerprint
when Hash
event_or_payload[:fingerprint]
end
end
end
end
end
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.