text
stringlengths
184
4.48M
package ru.auto.tests.desktop.dealers; import com.carlosbecker.guice.GuiceModules; import com.carlosbecker.guice.GuiceTestRunner; import io.qameta.allure.Epic; import io.qameta.allure.Feature; import io.qameta.allure.Owner; import io.qameta.allure.Story; import io.qameta.allure.junit4.DisplayName; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.RuleChain; import org.junit.runner.RunWith; import org.openqa.selenium.Keys; import ru.auto.tests.desktop.categories.Testing; import ru.auto.tests.desktop.module.DesktopTestsModule; import ru.auto.tests.desktop.rule.MockRuleConfigurable; import ru.auto.tests.desktop.step.BasePageSteps; import ru.auto.tests.desktop.step.UrlSteps; import javax.inject.Inject; import java.util.concurrent.TimeUnit; import static java.lang.String.format; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static ru.auto.tests.commons.webdriver.WebDriverSteps.waitSomething; import static ru.auto.tests.desktop.consts.AutoruFeatures.DEALERS; import static ru.auto.tests.desktop.consts.AutoruFeatures.DEALER_CARD; import static ru.auto.tests.desktop.consts.AutoruFeatures.FILTERS; import static ru.auto.tests.desktop.consts.Owners.DSVICHIHIN; import static ru.auto.tests.desktop.consts.Pages.ALL; import static ru.auto.tests.desktop.consts.Pages.CARS; import static ru.auto.tests.desktop.consts.Pages.DILER_OFICIALNIY; import static ru.auto.tests.desktop.consts.Pages.SLASH; import static ru.auto.tests.desktop.mock.MockStub.stub; import static ru.yandex.qatools.htmlelements.matchers.WebElementMatchers.hasText; import static ru.yandex.qatools.htmlelements.matchers.WebElementMatchers.isDisplayed; import static ru.yandex.qatools.htmlelements.matchers.WebElementMatchers.isEnabled; @DisplayName("Карточка дилера - фильтр по марке/модели/поколению") @Epic(DEALERS) @Feature(DEALER_CARD) @Story(FILTERS) @RunWith(GuiceTestRunner.class) @GuiceModules(DesktopTestsModule.class) public class CardMarkModelCarsTest { private static final String DEALER = "/avilon_mercedes_benz_moskva_vozdvizhenka/"; private static final String MARK = "Audi"; private static final String MODEL = "A3"; private static final String GENERATION = "III (8V) Рестайлинг"; private static final String GENERATION_CODE = "20785010"; private static final String MODEL_2 = "A8"; private static final String NAMEPLATE = "A8 Long"; private static final String NAMEPLATE_IN_URL = "long"; @Rule @Inject public MockRuleConfigurable mockRule; @Rule @Inject public RuleChain defaultRules; @Inject public BasePageSteps basePageSteps; @Inject public UrlSteps urlSteps; @Before public void before() { mockRule.setStubs(stub("desktop/Salon"), stub("desktop/SearchCarsBreadcrumbsRid213"), stub("desktop/SearchCarsBreadcrumbsAudi"), stub("desktop/SearchCarsAllDealerId"), stub("desktop/SearchCarsCountDealerId")).create(); urlSteps.testing().path(DILER_OFICIALNIY).path(CARS).path(ALL).path(DEALER).open(); } @Test @Owner(DSVICHIHIN) @Category({Testing.class}) @DisplayName("Выбор марки") public void shouldSelectMark() { mockRule.setStubs(stub("desktop/SearchCarsAllDealerIdAudi")).update(); basePageSteps.onDealerCardPage().filter().selectItem("Марка", MARK); basePageSteps.onDealerCardPage().filter().select(MARK).waitUntil(isDisplayed()); basePageSteps.onDealerCardPage().filter().resultsButton().waitUntil(isDisplayed()).click(); urlSteps.path(MARK.toLowerCase()).path(SLASH).shouldNotSeeDiff(); basePageSteps.onDealerCardPage().salesList().forEach(sale -> sale.nameLink().should(hasText(startsWith(MARK)))); } @Test @Owner(DSVICHIHIN) @Category({Testing.class}) @DisplayName("Выбор модели") public void shouldSelectModel() { mockRule.setStubs(stub("desktop/SearchCarsBreadcrumbsAudi_A3"), stub("desktop/SearchCarsAllDealerIdAudi_A3")).update(); basePageSteps.onDealerCardPage().filter().selectItem("Марка", MARK); basePageSteps.onDealerCardPage().filter().selectItem("Модель", MODEL); basePageSteps.onDealerCardPage().filter().select(MARK).waitUntil(isDisplayed()); basePageSteps.onDealerCardPage().filter().select(MODEL).waitUntil(isDisplayed()); basePageSteps.onDealerCardPage().filter().resultsButton().waitUntil(isDisplayed()).click(); urlSteps.path(MARK.toLowerCase()).path(MODEL.toLowerCase()).path(SLASH).shouldNotSeeDiff(); basePageSteps.onDealerCardPage().salesList().waitUntil(hasSize(greaterThan(0))); basePageSteps.onDealerCardPage().salesList().forEach(sale -> sale.nameLink() .should(hasText(startsWith(format("%s %s", MARK, MODEL))))); } @Test @Owner(DSVICHIHIN) @Category({Testing.class}) @DisplayName("Выбор поколения") public void shouldSelectGeneration() { mockRule.setStubs(stub("desktop/SearchCarsBreadcrumbsAudi_A3"), stub("desktop/SearchCarsBreadcrumbsAudi_A3_20785010"), stub("desktop/SearchCarsAllDealerIdAudi_A3_20785010")).update(); basePageSteps.onDealerCardPage().filter().selectItem("Марка", MARK); basePageSteps.onDealerCardPage().filter().select("Модель").waitUntil(isEnabled()); basePageSteps.onDealerCardPage().filter().selectItem("Модель", MODEL); basePageSteps.onDealerCardPage().filter().select("Поколение").selectButton().waitUntil(isEnabled()).click(); basePageSteps.onDealerCardPage().filter().generationsPopup().generationItem(GENERATION).waitUntil(isDisplayed()).click(); basePageSteps.onDealerCardPage().body().sendKeys(Keys.ESCAPE); basePageSteps.onDealerCardPage().filter().select(GENERATION).waitUntil(isDisplayed()); basePageSteps.onDealerCardPage().filter().resultsButton().waitUntil(isDisplayed()).click(); waitSomething(2, TimeUnit.SECONDS); urlSteps.path(MARK.toLowerCase()).path(MODEL.toLowerCase()).path(GENERATION_CODE).path(SLASH) .shouldNotSeeDiff(); basePageSteps.onDealerCardPage().salesList().forEach(sale -> sale.nameLink() .should(hasText(startsWith(format("%s %s %s", MARK, MODEL, GENERATION))))); } @Test @Owner(DSVICHIHIN) @Category({Testing.class}) @DisplayName("Выбор шильда") public void shouldSelectNameplate() { mockRule.setStubs(stub("desktop/SearchCarsBreadcrumbsAudi_A3"), stub("desktop/SearchCarsAllDealerIdAudi_A8_Long")).update(); basePageSteps.onDealerCardPage().filter().selectItem("Марка", MARK); basePageSteps.onDealerCardPage().filter().select("Модель").selectButton().waitUntil(isEnabled()).click(); basePageSteps.onDealerCardPage().filter().selectPopup().plusButton(MODEL_2).click(); basePageSteps.onDealerCardPage().filter().selectPopup().item(NAMEPLATE).click(); basePageSteps.onDealerCardPage().filter().resultsButton().waitUntil(isDisplayed()).click(); urlSteps.path(MARK.toLowerCase()).path(MODEL_2.toLowerCase()).path(SLASH) .addParam("nameplate_name", NAMEPLATE_IN_URL).shouldNotSeeDiff(); basePageSteps.onDealerCardPage().salesList().waitUntil(hasSize(greaterThan(0))); basePageSteps.onDealerCardPage().salesList().forEach(sale -> sale.nameLink() .should(hasText(startsWith(format("%s %s", MARK, NAMEPLATE))))); } @Test @Owner(DSVICHIHIN) @Category({Testing.class}) @DisplayName("Исключение марки") public void shouldExcludeMark() { mockRule.setStubs(stub("desktop/SearchCarsBreadcrumbsAudi"), stub("desktop/SearchCarsAllDealerIdExcludeAudi")).update(); basePageSteps.onDealerCardPage().filter().select("Марка").selectButton().waitUntil(isEnabled()).click(); basePageSteps.onDealerCardPage().filter().selectPopup().radioButton("Исключить").click(); basePageSteps.onDealerCardPage().filter().selectPopup().item(MARK).click(); basePageSteps.onDealerCardPage().filter().select(format("Кроме %s", MARK)).waitUntil(isDisplayed()); basePageSteps.onDealerCardPage().filter().resultsButton().waitUntil(isDisplayed()).click(); urlSteps.addParam("exclude_catalog_filter", format("mark=%s", MARK.toUpperCase())) .shouldNotSeeDiff(); basePageSteps.onDealerCardPage().waitForListingReload(); basePageSteps.onDealerCardPage().salesList().forEach(sale -> sale.nameLink().should(not(hasText(containsString(MARK))))); basePageSteps.refresh(); basePageSteps.onDealerCardPage().salesList().forEach(sale -> sale.nameLink().should(not(hasText(containsString(MARK))))); } }
using Entities; using ServiceContracts.Enums; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace ServiceContracts.DTOS.PersonDTO { public class PersonAddRequest { [Required(ErrorMessage = "Person Name can't be blank")] public string? PersonName { get; set; } [Required(ErrorMessage = "Email can't be blank")] [EmailAddress(ErrorMessage = "Email value should be a valid email")] public string? Email { get; set; } public DateTime DateOfBirth { get; set; } public GenderOptions? Gender { get; set; } public Guid CountryID { get; set; } public string? Address { get; set; } public bool ReceiveNewsLetter { get; set; } /// <summary> /// Convert PersonAddRequest object into /// Person object /// </summary> /// <returns></returns> public Person ToPerson() { return new Person { PersonName = this.PersonName, Email = this.Email, DateOfBirth = this.DateOfBirth, Gender = ConvertGenderOptionsToString(), CountryID = this.CountryID, Address = this.Address, ReceiveNewsLetter = this.ReceiveNewsLetter, }; } public string ConvertGenderOptionsToString() { switch (this.Gender) { case GenderOptions.Male: return "Male"; case GenderOptions.Female: return "Female"; default: return "Other"; } } } }
import Navbar from './components/Navbar' import CartContainer from './components/CartContainer' import { useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import { calcTotoal, getCartItems } from './reducers/cart/cartReducer' import Modal from './components/Modal' const App = () => { const dispatch = useDispatch() let { cartItems, isLoading } = useSelector((store) => store.cart) let { isOpen, isItemOpen } = useSelector((store) => store.modal) useEffect(() => { dispatch(calcTotoal()) }, [cartItems]) useEffect(() => { dispatch(getCartItems()) }, []) if (isLoading) { return ( <div className="loading"> <h1>Loading...</h1> </div> ) } return ( <main> {isOpen && <Modal />} <Navbar /> <CartContainer /> </main> ) } export default App
fetch('https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-json/dpc-covid19-ita-regioni.json') .then(response => response.json()) .then(dati => { // dati riordinati per data ultima let sorted = dati.reverse() // preso e riordinato per data let lastUpdated = sorted[0].data // data riformattata :12/06/2020 let lastUpdatedFormatted = lastUpdated .split("T")[0].split("-").reverse().join("/"); // mostrata data dom document.querySelector('#data').innerHTML = lastUpdatedFormatted; // elementi filtrati per ultima data nel senso per giorno e avremmo tutte le regioni let lastUpdatedData = sorted.filter( el => el.data == lastUpdated) // elementi riordinati in maniera decrescente per nuovi positivi let nuoviPositivi = lastUpdatedData.sort((a,b) => (b.nuovi_positivi - a.nuovi_positivi)); // elemnti ciclati e rimessi in un nuovo array per totali casi poi la somma di essi let totalCase = lastUpdatedData.map(el => el.totale_casi).reduce((a,b) => a+b); // mostra totalcases document.querySelector('#totCases').innerHTML = totalCase; // totale guariti let totalRecovered = lastUpdatedData.map(el => el.dimessi_guariti).reduce((a,b)=> a+b); document.querySelector('#totRecovered').innerHTML = totalRecovered; // totale morti let totalDead = lastUpdatedData.map(el => el.deceduti).reduce((a,b)=> a+b); document.querySelector("#totDecessi").innerHTML = totalDead // totale positivi piu la reduce let totalPositiv = lastUpdatedData.map(el => el.totale_positivi).reduce((a,b)=>a+b); document.querySelector('#posAttuali').innerHTML = totalPositiv // creaziene delle card dinamiche let cardWrapper = document.querySelector('#card-wrapper') let progresWrapper = document.querySelector('#progressBar') // valore massimo dei nuovi positivi esso è la laobradia let barMax = Math.max(...lastUpdatedData.map(el => el.nuovi_positivi)); // per creare le modali dinamiche, dobbiamo aggiungere un attributo al div delle card, con valore : richiamando l'array // denominazione_regione esso è il valore unovoco della promise lastUpdatedData.forEach(el => { let div = document.createElement('div') div.classList.add('col-12','col-md-5','my-5') div.innerHTML = ` <div class="card-custom p-3 pb-0 h-100" data-region="${el.denominazione_regione}"> <p class="text-center">${el.denominazione_regione}:</p> <p class="text-end h5 mb-0 p-2 text-main">${el.nuovi_positivi}</p> </div> ` cardWrapper.appendChild(div); let bar = document.createElement('div') bar.classList.add('col-12', 'mb-5') bar.innerHTML = ` <p class="mb-0">${el.denominazione_regione}:</p> <div class="progress bg-transparen rounded-0"> <div class="progress-bar bg-main" style="width:${90*el.nuovi_positivi/barMax}%"></div> </div> <p class="text-end h5 mb-0 p-2 text-main">${el.nuovi_positivi}</p> ` // alla riga 64 appiamo reso la progres bar dinamica (vedi riga 45) progresWrapper.appendChild(bar) }); let modal = document.querySelector('.modal-custom'); let modalContent = document.querySelector('.modal-custom-content'); // catturato l'attributo dinamimco , e per ogni elmento, cliaccato (el.addEvent) ascolta il click e fai la funzione (dataset) // messa in una variabile per poi stamparla document.querySelectorAll('[data-region').forEach(el =>{ // poi per ogni elemneto ascolta il suo click e fai partire una funzione che dichiara let region , che sarò // il suo data set e aggiungi a modla la classe active che attiverà quella del css el.addEventListener('click',()=>{ let region = el.dataset.region modal.classList.add('active') // e lavariabile dove diciamo al forEach da dove prendere i dati , ovviamente in posizione let dataAboutRegion = lastUpdatedData.filter(el => el.denominazione_regione === region)[0] console.log(dataAboutRegion); modalContent.innerHTML = ` <div class="container"> <div class="row"> <div class="col-12"> <p class="h2 fw-bold lead text-main">${dataAboutRegion.denominazione_regione}</p> </div> <div class="col-12"> <p class="h3 lead text-main"> <span>totale casi</span> : ${dataAboutRegion.totale_casi}</p> <p class="h3 lead text-main"> <span>Nuovi positivi</span> :${dataAboutRegion.nuovi_positivi}</p> <p class="h3 lead text-main"> <span>Decessi</span> :${dataAboutRegion.deceduti}</p> <p class="h3 lead text-main"> <span>guariti</span> :${dataAboutRegion.dimessi_guariti}</p> <p class="h3 lead text-main"> <span>Ricoverati con sintomi</span>:${dataAboutRegion.ricoverati_con_sintomi}</p> <p class="h3 lead text-main"> <span>Terapia Intensiva</span> : ${dataAboutRegion.terapia_intensiva}</p> </div> </div> ` let trendData = sorted.map(el => el).reverse().filter(el => el.denominazione_regione == region).map(el=> [el.data, el.nuovi_positivi, el.deceduti,el.dimessi_guariti]) let maxNew = Math.max(...trendData.map(el=> el[1])) let maxDeath = Math.max(...trendData.map(el=> el[2])) let maxRecovered = Math.max(...trendData.map(el=> el[3])) console.log(); let trendNew = document.querySelector('#trendNew'); let trendDeath = document.querySelector('#trendDeath'); let trendRecovered = document.querySelector('#trendRecovered'); trendData.forEach(el => { let colNew = document.createElement('div') colNew.classList.add('d-inline-block','pin-new') colNew.style.height = `${100* el[1] / maxNew}%` trendNew.appendChild(colNew) let colDeath = document.createElement('div') colDeath.classList.add('d-inline-block', 'pin-death') colDeath.style.height = `${100 * el[2] / maxDeath}%` trendDeath.appendChild(colDeath) let colRecovered = document.createElement('div') colRecovered.classList.add('d-inline-block', 'pin-recovered') colRecovered.style.height = `${100 * el[3] / maxRecovered}%` trendRecovered.appendChild(colRecovered) }); }); // diciamo a window(finestra generale ) ascolta l'evento 'click' e fai partire la funzione con un parametro formale che sarà l'elemento // cliccato in quel momento e se è esso è uguale a modal (ovvero attivo), allora rimuovi la classe window.addEventListener('click', function(a){ if(a.target == modal){ modal.classList.remove('active') } }) }) })
# mini-alloc `mini-alloc` is a small and performant allocator optimized for `wasm32` targets like [Arbitrum Stylus][Stylus]. You can use it in your program as follows. ```rust #[global_allocator] static ALLOC: mini_alloc::MiniAlloc = mini_alloc::MiniAlloc::INIT; ``` ## Benchmarks `mini-alloc` implements a minimal bump allocator strategy. It never deallocates memory -- that is, `dealloc` does nothing. It's suitable for cases where binary size is at a premium and it's acceptable to leak all allocations. The simplicity of this model makes it very efficient, as seen in the following benchmarks. | | `MiniAlloc` | [`WeeAlloc`][WeeAlloc] | Std Library | |--------------|-------------|------------------------|----------------| | alloc | 333 gas | 721 gas | 516 gas | | alloc_zeroed | 329 gas | 95 million gas | 48 million gas | The benchmarks compare the performance of this crate's `edge_cases` test in the [Stylus VM][StylusVM]. Normal allocations are over **2x** cheaper than when using [`WeeAlloc`][WeeAlloc], a common WASM alternative that this crate defaults to when built for non-WASM targets. Replacing each instance of `alloc` in the test with `alloc_zeroed` reveals an over **99%** improvement for zero-filled allocations. Unlike [`WeeAlloc`][WeeAlloc] and the standard library, `MiniAlloc` takes advantage of the fact that WASM pages are zero-filled at initialization, and uses fewer of them due to the layout of Rust's memory. In the above tests we disable memory expansion costs, which unfairly penelize `WeeAlloc` and the standard library due to their increased resource consumption. ## Notice `MiniAlloc` should not be used in `wasm32` environments that enable the multithreading proposal. Although `MiniAlloc` implements `Sync` since Rust requires it for the global allocator, this crate should not be used in this way. This should not be a concern in [`Stylus`][Stylus]. Also, `core::arch::wasm32::memory_grow` must never be called by any code outside this crate. On targets other than wasm32, `MiniAlloc` simply forwards to the allocator from another crate, `wee_alloc::WeeAlloc`. ## License &copy; 2023 Offchain Labs, Inc. This project is licensed under either of - [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) ([licenses/Apache-2.0](../licenses/Apache-2.0)) - [MIT license](https://opensource.org/licenses/MIT) ([licenses/MIT](../licenses/MIT)) at your option. The [SPDX](https://spdx.dev) license identifier for this project is `MIT OR Apache-2.0`. [Stylus]: https://github.com/OffchainLabs/stylus-sdk-rs [StylusVM]: https://github.com/OffchainLabs/stylus [WeeAlloc]: https://github.com/rustwasm/wee_alloc
#!/usr/bin/env perl # # mdbook-index-template # jms1 2023-11-06 # # Add my custom blocks to mdbook's index.hbs to make index-template.hbs # # This version contains hard-coded strings require 5.005 ; use strict ; use warnings ; use Getopt::Std ; ######################################## # Default blocks containing commit info my $after_toc = <<EOF ; <hr> <div class="part-title">Version</div> <div id="commit" class='version-commit-div'> <span class='version-commit-hash'><tt>\@VERSION_COMMIT_HASH\@</tt></span><br> <span class='version-commit-time'><tt>\@VERSION_COMMIT_TIME\@</tt></span> </div> <div class="part-title">Generated</div> <div id="generated" class='version-commit-div'> <span class='version-commit-now'><tt>\@VERSION_COMMIT_NOW\@</tt></span> </div> EOF my $after_page = <<EOF ; <hr> <div class="version-commit-div" style="float: right"> Generated <span class='version-commit-now'><tt>\@VERSION_COMMIT_NOW\@</tt></span> </div> <div class="version-commit-div"> <span class='version-commit-hash'><tt>\@VERSION_COMMIT_HASH\@</tt></span> <span class='version-commit-time'><tt>\@VERSION_COMMIT_TIME\@</tt></span> </div> EOF ######################################## # Other globals my %opt = () ; # getopts my $add_atoc = 0 ; # -t my $add_apage = 0 ; # -p my $uplink_file = '' ; # -U: my $atoc_file = '' ; # -T: my $apage_file = '' ; # -P: my $uplink_text = '' ; ############################################################################### # # usage sub usage(;$) { my $msg = ( shift || '' ) ; print <<EOF ; $0 [options] Read the original 'index.hbs' from mdbook's source from STDIN. Write a modified version to STDOUT. The modifications will include 'git commit' information. -t Include commit information below the Table of Contents. -T ___ Specify a file containing an HTML fragment to be included AS the commit information below the Table of Contents. This file should contain the correct substitution tokens. Implies '-t'. -p Include commit information at the bottom of the page. -P ___ Specify a file containing an HTML fragment to be included AS the commit information at the bottom of the page. This file should contain the correct substitution tokens. Implies '-p'. -U ___ Specify a file containing an HTML fragment to be included above the Table of Contents. This is normally used as a link "up" to an index of related books. -h Show this help message. EOF if ( $msg ne '' ) { print $msg ; exit 1 ; } exit 0 ; } ############################################################################### ############################################################################### ############################################################################### getopts ( 'htpU:T:P:' , \%opt ) ; $opt{'h'} && usage() ; $add_atoc = ( $opt{'t'} ? 1 : 0 ) ; $add_apage = ( $opt{'p'} ? 1 : 0 ) ; $uplink_file = ( $opt{'U'} || '' ) ; $atoc_file = ( $opt{'T'} || '' ) ; $apage_file = ( $opt{'P'} || '' ) ; my $changing = 0 ; ############################################################ # If an uplink file was specified, read it if ( $uplink_file ne '' ) { open( I , '<' , $uplink_file ) or die "ERROR: can't read \"$uplink_file\": $!\n" ; while ( my $line = <I> ) { $uplink_text .= $line ; } close I ; $changing = 1 ; } ############################################################ # Figure out "after ToC" if ( $atoc_file ne '' ) { $after_toc = '' ; open( I , '<' , $atoc_file ) or die "ERROR: can't read \"$atoc_file\": $!\n" ; while ( my $line = <I> ) { $after_toc .= $line ; } close I ; $add_atoc = 1 ; $changing = 1 ; } elsif ( ! $add_atoc ) { $after_toc = '' ; } else { $changing = 1 ; } ############################################################ # Figure out "after page" if ( $apage_file ne '' ) { $after_page = '' ; open( I , '<' , $apage_file ) or die "ERROR: can't read \"$apage_file\": $!\n" ; while ( my $line = <I> ) { $after_page .= $line ; } close I ; $add_apage = 1 ; $changing = 1 ; } elsif ( ! $add_apage ) { $after_page = '' ; } else { $changing = 1 ; } ############################################################################### # # Do the deed while ( my $line = <> ) { if ( $line =~ m|\{\{#toc\}\}| ) { if ( $uplink_text ne '' ) { print "\n<!-- Start up-link content above ToC -->\n" ; print $uplink_text ; print "<!-- End up-link content above ToC -->\n\n" ; } } print $line ; if ( $line =~ m|\{\{/toc\}\}| ) { if ( $add_atoc ) { print "\n<!-- Start version-commit content below ToC -->\n" ; print $after_toc ; print "<!-- End version-commit content below ToC -->\n\n" ; } } if ( $line =~ m|\{\{\{\s*content\s*\}\}\}| ) { if ( $add_apage ) { print "\n<!-- Start version-commit content below page -->\n" ; print $after_page ; print "<!-- End version-commit content below page -->\n\n" ; } } }
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter/services.dart'; import 'package:mobile/mqtt/MQTTAppState.dart'; import 'package:mobile/utils/permissions.dart'; import 'package:mobile/Constants.dart'; import 'package:mobile/pages/setting_hub_page.dart'; import 'package:mobile/mqtt/IMQTTController.dart'; import 'package:mobile/mqtt/MQTTManager.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:mobile/providers/Providers.dart'; import 'package:mqtt_client/mqtt_client.dart'; import 'package:mqtt_client/mqtt_server_client.dart'; import 'dart:io'; import 'dart:convert'; import 'package:mobile/models/sensor.dart'; import 'package:mobile/pages/add_hub_page2.dart'; import 'package:mobile/pages/add_hub_page1.dart'; import 'package:logger/logger.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:intl/intl.dart'; import 'package:mobile/models/devicelist.dart'; import 'package:mobile/database/db.dart'; enum MqttCommand {mcSensorList, mcParing} var logger = Logger( printer: PrettyPrinter(), ); var loggerNoStack = Logger( printer: PrettyPrinter(methodCount: 0), ); class HomePage extends ConsumerStatefulWidget { const HomePage({super.key, required this.title}); final String title; @override ConsumerState<HomePage> createState() => _HomePageState(); } class _HomePageState extends ConsumerState<HomePage> { List<Sensor> _sensorList = []; late IMQTTController _manager; bool loadingDeviceList = false; String resultTopic = ''; String commandTopic = ''; String requestTopic = ''; Future<List<DeviceList>> loadDeviceList() async { DBHelper db = DBHelper(); return await db.deviceLists(); } Future<void> getHubIdToPrefs() async { try { final SharedPreferences pref = await SharedPreferences.getInstance(); final deviceId = pref.getString('deviceID') ?? ''; if (deviceId != '') { resultTopic = 'result/$deviceId'; commandTopic = 'command/$deviceId'; requestTopic = 'request/$deviceId'; _manager.subScribeTo(resultTopic); logger.i('subscribed to $resultTopic'); _manager.subScribeTo(requestTopic); logger.i('subscribed to $requestTopic'); // mqttCommand(MqttCommand.mcSensorList, deviceId); } else { logger.i('not hubID'); } } catch (e) { logger.e(e); } } void mqttGetMessageTimer() { Timer.periodic(const Duration(seconds: 1), (timer) { if (_manager.currentState.getReceivedTopic != '') { logger.w(_manager.currentState.getReceivedTopic); } if (_manager.currentState.getReceivedTopic == resultTopic && _manager.currentState.getReceivedText != '') { final mqttMsg = json.decode(_manager.currentState.getReceivedText); logger.i(mqttMsg); if (mqttMsg['event'] == 'gatewayADD') { //gatewayADD는 처음 hub를 찾으면 들어온다. logger.i('received event: gatewayADD'); Navigator.popUntil(context, (route) { return route.isFirst; }, ); } } else if (_manager.currentState.getReceivedTopic == requestTopic && _manager.currentState.getReceivedText != '') { final mqttMsg = json.decode(_manager.currentState.getReceivedText); logger.i(mqttMsg); if (mqttMsg['order'] == 'sensorList') { logger.i('received event: sensorList'); } else if (mqttMsg['order'] == 'device_add') { logger.i('received event: device_add'); } if (mqttMsg['event'] == 'device_detected') { logger.i('received event: device_detected'); } } _manager.currentState.setReceivedText(''); _manager.currentState.setReceivedTopic(''); setState(() { }); }); } void mqttCommand(MqttCommand mc, String deviceId) { var now = DateTime.now(); String formatDate = DateFormat('yyyyMMdd_HHmmss').format(now); if (mc == MqttCommand.mcSensorList) { //펌웨어 에서 기능 구현 안됨. _manager.publishTopic(commandTopic, jsonEncode({ "order": "sensorList", "deviceID": deviceId, "time": formatDate })); } else if (mc == MqttCommand.mcParing) { _manager.publishTopic(commandTopic, jsonEncode({ "order": "pairingEnabled", "deviceID": deviceId, "time": formatDate })); } } @override Widget build(BuildContext context) { _manager = ref.watch(mqttManagerProvider); return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Home'), // actions: [ // Permissions(), // ], ), body: FutureBuilder<List<DeviceList>>( future: loadDeviceList(), builder: (context, snapshot) { final List<DeviceList>? devices = snapshot.data; if (snapshot.connectionState != ConnectionState.done) { return Center( child: waitWidget(), ); } if (snapshot.hasError) { return Center( child: Text(snapshot.error.toString()), ); } if (snapshot.hasData) { if (devices != null) { if (devices.isEmpty) { return Center( child: waitWidget(), ); } return ListView.builder( itemCount: devices.length, itemBuilder: (context, index) { final device = devices[index]; return Padding( padding: const EdgeInsets.all(8.0), child: Card( child: ListTile( title: Text(device.deviceType), trailing: const Icon(Icons.add), onTap: () { // Get.toNamed("/Setting_Hub", arguments: {"hubName": device}); Navigator.push(context, MaterialPageRoute(builder: (context) { return const AddHubPage1(); })); }, ), ), ); }, ); } else { return Center( child: waitWidget(), ); } } else { return Center( child: waitWidget(), ); } }, ), floatingActionButton: FloatingActionButton( onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return AddHubPage1(); })); },//_findingEsp32 ? null : _findEsp32, child: const Icon(Icons.add)), ); } void getMyDeviceToken() async { final token = await FirebaseMessaging.instance.getToken(); print("내 디바이스 토큰: $token"); } @override void didChangeDependencies() { super.didChangeDependencies(); initMqtt(); } @override void initState() { getMyDeviceToken(); mqttGetMessageTimer(); FirebaseMessaging.onMessage.listen((RemoteMessage message) async { RemoteNotification? notification = message.notification; if (notification != null) { FlutterLocalNotificationsPlugin().show( notification.hashCode, notification.title, notification.body, const NotificationDetails( android: AndroidNotificationDetails( 'high_importance_channel', 'high_importance_notification', importance: Importance.max, ), ), ); setState(() { logger.i("Foreground 메시지 수신: ${message.notification!.body!}"); }); } }); super.initState(); } void initMqtt() { _manager = ref.watch(mqttManagerProvider); _manager.initializeMQTTClient(host: '14.42.209.174', identifier: 'SCT Senior Care'); _manager.connect(); Future.delayed(const Duration(seconds: 1), () { if (_manager.currentState.getAppConnectionState == MQTTAppConnectionState.connected || _manager.currentState.getAppConnectionState == MQTTAppConnectionState.connectedSubscribed) { logger.i("MQTT Connected!"); getHubIdToPrefs(); } }); } Widget waitWidget() { return loadingDeviceList ? const CircularProgressIndicator(backgroundColor: Colors.blue) : const Text(""); } }
#' Greedily add factors to a flash object #' #' Adds factor/loadings pairs to a flash object in a "greedy" manner. Up to #' \code{Kmax} pairs are added one at a time. At each step, \code{flash_greedy} #' attempts to find an optimal additional (rank-one) factor given all #' previously added factors. The additional factor is retained if it #' increases the variational lower bound (ELBO); otherwise, fitting terminates. #' See \code{\link{flash}} for examples of usage. #' #' @inheritParams flash #' #' @param flash A \code{flash} or \code{flash_fit} object to which factors are #' to be added. #' #' @param Kmax The maximum number of factors to be added. This will not #' necessarily be the total number of factors added by #' \code{flash_greedy}, since factors are only added as long as they #' increase the ELBO. #' #' @param init_fn The function used to initialize factor/loadings pairs. Functions #' \code{\link{flash_greedy_init_default}}, \code{\link{flash_greedy_init_softImpute}}, and #' \code{\link{flash_greedy_init_irlba}} have been supplied; note, in particular, that #' \code{\link{flash_greedy_init_softImpute}} can yield better results than the #' default initialization function when there is missing data. Custom #' initialization functions may also be used. If \code{init_fn = NULL} then #' \code{\link{flash_greedy_init_default}} will be used, with an attempt made to set #' argument \code{sign_constraints} appropriately via test calls to #' the EBNM function(s) specified by parameter \code{ebnm_fn}. If factors or loadings #' are constrained in some other fashion (e.g., bounded support), then the #' initialization function should be modified to account for the constraints #' --- otherwise, the greedy algorithm can stop adding factor/loadings pairs #' too early. Custom initialization functions should accept a single #' parameter referring to a \code{\link{flash_fit}} object and should output #' a list consisting of two vectors, which will be used as initial values for #' the new loadings \eqn{\ell_{\cdot k}} and the new factor \eqn{f_{\cdot k}}. Typically, #' a custom initialization function will extract the matrix of residuals from #' the \code{flash_fit} object using method \code{residuals.flash_fit} and #' then return a (possibly constrained) rank-one approximation to the matrix #' of residuals. See \strong{Examples} below. #' #' @param warmstart Whether to use "warmstarts" when solving the EBNM #' subproblems by initializing solutions at the previous value of the fitted #' prior \eqn{\hat{g}}. An important side effect of warmstarts for #' \code{ashr}-like prior families is to fix the grid at its initial setting. #' Fixing the grid can lead to poor fits if there #' are large changes in the scale of the estimated prior over the #' course of the fitting process. However, allowing the grid to #' vary can occasionally result in decreases in ELBO. #' #' @param extrapolate Whether to use an extrapolation technique #' inspired by Ang and Gillis (2019) to accelerate the fitting process. #' Control parameters are handled via global options and can be set by #' calling \code{options("extrapolate.control") <- control.param}. #' #' @param maxiter The maximum number of iterations when optimizing a greedily #' added factor/loadings pair. #' #' @param tol The convergence tolerance parameter. At each iteration, the fit #' is compared to the fit from the previous iteration using a convergence #' criterion function (by default, the difference in ELBO, but the criterion #' can be changed via \code{\link{flash_set_conv_crit}}). When #' the value returned by this function is less than or equal to \code{tol}, #' the newly added factor/loadings pair is considered to have "converged," #' so that \code{flash_greedy} moves on and attempts to add another new #' factor (or, if the maximum number of factors \code{Kmax} has been reached, #' the process terminates). Note that #' specifying \code{tol} here will override any value set by #' \code{flash_set_conv_crit}; to use the "global" tolerance parameter, #' \code{tol} must be left unspecified (\code{NULL}). #' If \code{tol = NULL} and a global tolerance #' parameter has not been set, then the default #' tolerance used is \eqn{np\sqrt{\epsilon}}, where \eqn{n} is the #' number of rows in the dataset, \eqn{p} is the number of columns, and #' \eqn{\epsilon} is equal to \code{\link{.Machine}$double.eps}. #' #' @examples #' # The following are examples of advanced usage. See ?flash for basic usage. #' #' # Increase the maximum number of iterations in the default initialization #' # method. #' my_init_fn <- function(f) flash_greedy_init_default(f, maxiter = 500) #' fl <- flash_init(gtex) %>% #' flash_greedy(init_fn = my_init_fn) #' #' # Use a custom initialization function that wraps function nmf from #' # package RcppML. #' nmf_init_fn <- function(f) { #' nmf_res <- RcppML::nmf(resid(f), k = 1, verbose = FALSE) #' return(list(as.vector(nmf_res$w), as.vector(nmf_res$h))) #' } #' fl.nmf <- flash_init(gtex) %>% #' flash_greedy(ebnm_fn = ebnm_unimodal_nonnegative, #' init_fn = nmf_init_fn) #' #' @seealso \code{\link{flash_greedy_init_default}}, #' \code{\link{flash_greedy_init_softImpute}}, #' \code{\link{flash_greedy_init_irlba}} #' #' @return The \code{\link{flash}} object from argument \code{flash}, with up #' to \code{Kmax} new factor/loadings pairs "greedily" added. #' #' @importFrom ebnm ebnm_point_normal #' #' @export #' flash_greedy <- function(flash, Kmax = 1, ebnm_fn = ebnm_point_normal, init_fn = NULL, extrapolate = FALSE, warmstart = FALSE, maxiter = 500, tol = NULL, verbose = NULL) { flash <- get.fit(flash) tol <- handle.tol.param(tol, flash) verbose.lvl <- handle.verbose.param(verbose, flash) if (is.timed.out(flash)) { report.timeout.no.greedy(verbose.lvl) verbose.lvl <- 0 } must.be.integer(Kmax, lower = 1, allow.null = FALSE) must.be.integer(maxiter, lower = 1, allow.null = FALSE) must.be.integer(verbose.lvl, lower = -1, upper = 3, allow.null = FALSE) ebnm.chk <- handle.ebnm.fn(ebnm_fn, get.dim(flash)) ebnm.fn <- ebnm.chk$ebnm.fn if (is.null(init_fn)) { init_fn <- function(f) flash_greedy_init_default( f, sign_constraints = ebnm.chk$dim.signs ) } if (uses.R(flash)) { if (!missing(extrapolate) && extrapolate) { stop("Greedy extrapolation has not yet been implemented for the 'zero' ", "variance structure.") } else { extrapolate <- FALSE } } extrapolate.control <- getOption("extrapolate.control", list()) extrapolate.param <- set.extrapolate.param(extrapolate.control) flash <- set.gwarmstart(flash, warmstart) verbose.fns <- get.verbose.fns(flash) verbose.colnames <- get.verbose.colnames(flash) verbose.colwidths <- get.verbose.colwidths(flash) conv.crit.fn <- get.conv.crit.fn(flash) factors.added <- 0 greedy.failed <- FALSE while (factors.added < Kmax && !greedy.failed && !is.timed.out(flash)) { announce.add.factor(verbose.lvl, k = get.next.k(flash)) factor <- init.factor(flash, init_fn) factor <- set.ebnm.fn(factor, ebnm.fn) announce.factor.opt(verbose.lvl) print_table.header(verbose.lvl, verbose.colnames, verbose.colwidths, backfit = FALSE) iter <- 0 conv.crit <- Inf if (extrapolate) { old.f <- factor extrapolate.param <- init.beta(extrapolate.param) } while (conv.crit > tol && iter < maxiter && !is.timed.out(flash)) { iter <- iter + 1 if (extrapolate) { proposed.factor <- extrapolate.f(factor, old.f, extrapolate.param) proposed.factor <- update.factor(proposed.factor, flash) } old.f <- factor if (!extrapolate) { factor <- update.factor(factor, flash) } else if (get.obj(proposed.factor) - get.obj(factor) < tol) { factor <- update.factor(factor, flash) extrapolate.param <- decelerate(extrapolate.param) } else { factor <- proposed.factor extrapolate.param <- accelerate(extrapolate.param) } obj.diff <- get.obj(factor) - get.obj(old.f) if (is.obj.valid(old.f) && obj.diff < 0) { report.greedy.obj.decrease(verbose.lvl, obj.diff) factor <- old.f break } info <- calc.update.info(factor, old.f, conv.crit.fn, verbose.fns) conv.crit <- get.conv.crit(info) print_table.entry(verbose.lvl, verbose.colwidths, iter, info, get.next.k(flash), backfit = FALSE) } if (is.timed.out(flash)) { t.diff <- Sys.time() - get.timeout.set.time(flash) report.timeout.reached(verbose.lvl, t.diff) flash <- set.timeout.reached.flag(flash) } if (iter == maxiter) { report.maxiter.reached(verbose.lvl) } if (!is.zero(factor) && (get.obj(factor) > get.obj(flash) + tol # TODO: remove + tol here || !is.obj.valid(flash, factor))) { flash <- add.new.factor.to.flash(factor, flash) factors.added <- factors.added + 1 } else { greedy.failed <- TRUE } report.add.factor.result(verbose.lvl, greedy.failed, get.obj(flash)) } announce.wrapup(verbose.lvl) flash <- wrapup.flash(flash, output.lvl = 3L) report.completion(verbose.lvl) return(flash) }
import React from 'react' import { useState } from 'react'; import { Navbar, Nav } from 'react-bootstrap'; import { IoSearch } from "react-icons/io5"; import { BsCart4 } from "react-icons/bs"; import '../assets/Css/orelega-one.css'; import Login from "../Login/Login" const Header = () => { const [showLoginModal, setShowLoginModal] = useState(false) const openLoginModal = () => { setShowLoginModal(true); }; const closeLoginModal = () => { setShowLoginModal(false); }; return ( <> <div> <Navbar className="w-full bg-inherit"> <div className="container mx-auto flex justify-between items-center"> <Navbar.Brand href="#" className="font-montserrat font-bold text-lime-700 text-3xl" style={{ fontFamily: 'Orelega One, cursive' }}>Foody.</Navbar.Brand> <div className="flex justify-between items-center"> <Nav className="mr-auto space-x-20"> <Nav.Link href="#" className="text-lime-700 text-sm font-semibold">Home</Nav.Link> <Nav.Link href="#" className="text-lime-700 text-sm font-semibold">Restaurants</Nav.Link> <Nav.Link href="/Menus" className="text-black text-sm font-semibold">Menus</Nav.Link> <Nav.Link href="#" className="text-black text-sm font-semibold">About Us</Nav.Link> <Nav.Link href="#" className="text-black text-sm font-semibold">Contact</Nav.Link> </Nav> </div> <div className="flex items-center space-x-2"> <div className="w-10 h-10 flex items-center justify-center rounded-full"> <IoSearch size={15} /> </div> <div className="w-10 h-10 flex items-center justify-center rounded-full"> <BsCart4 size={15} /> </div> <div> <button onClick={openLoginModal} className="bg-white rounded-full px-3 py-1 text-xs font-semibold">Log In</button> </div> {/* Login button */} </div> </div> </Navbar> </div> <Login show={showLoginModal} onClose={closeLoginModal} /> </> ) } export default Header
import React, { useEffect, useState } from "react"; import { ActivityIndicator, Alert, Button, Pressable, RefreshControl, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, View, } from "react-native"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { useCallback } from "react"; export default function ChooseTeam({ navigation }) { const [teamsData, setTeamsData] = useState([]); const [studentData,setStudentData] = useState(null) const [teamId,setTeamId] = useState(null) const [success,setSuccess] = useState(false); const [refreshing, setRefreshing] = React.useState(false); const [animating,setAnimating] = useState(true); const onRefresh = React.useCallback(async () => { setRefreshing(true); try { await fetchTeamsData(); setSuccess(false); setTeamId(''); } catch (error) { console.error('Error fetching project data:', error); } finally { setTimeout(() => { setRefreshing(false); }, 2000); } }, []); const handleSubmit = () => { if (isNaN(teamId)) { Alert.alert('Validation Error','Team ID should be a number'); return; } const apiUrl = `https://centrale.onrender.com/team/teacherId/update/id/${teamId}`; const requestData = { teacherId:studentData.id }; fetch(apiUrl, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(requestData), }) .then(response => response.json()) .then(Alert.alert('🎊','Successfully Choosed Your Team')) .catch(error => { // Handle any errors that occur during the fetch console.error('Error:', error); }); onRefresh() }; useEffect(() => { // Fetch student data from AsyncStorage when the component mounts AsyncStorage.getItem("studentData") .then((data) => { if (data) { const parsedData = JSON.parse(data); setStudentData(parsedData); } }) .catch((error) => { console.error("Error fetching student data from AsyncStorage:", error); }); }, []); useEffect(() => { // Fetch team data from your API fetchTeamsData(); }, []); const fetchTeamsData = async () => { // Replace the URL with your actual API endpoint const apiUrl = `https://centrale.onrender.com/teams`; try { const response = await fetch(apiUrl); const data = await response.json(); // Fetch student names for each team const teamsWithStudents = await Promise.all( data.map(async (team) => { const studentsWithNames = []; // Fetch student names for studentId1, studentId2, and studentId3 for (let i = 1; i <= 3; i++) { const studentId = team[`studentId${i}`]; const studentApiUrl = `https://centrale.onrender.com/user/id/${studentId}`; const studentResponse = await fetch(studentApiUrl); const studentData = await studentResponse.json(); studentsWithNames.push({ id: studentId, name: studentData.name, }); } return { ...team, students: studentsWithNames, }; }) ); setTeamsData(teamsWithStudents); } catch (error) { console.error("Error:", error); } }; useEffect(() => { if (teamsData) { setTimeout(() => { setAnimating(false); }, 8000); } },[teamsData]) return ( <SafeAreaView style={styles.container}> <ScrollView refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} /> }> <View style={styles.container}> <Text style={styles.textstyles}>Enter your Team Id</Text> <TextInput style={styles.input} value={teamId} onChangeText={text => setTeamId(text)} placeholder="Team ID"/> <Pressable style={styles.button2} onPress={handleSubmit}> <Text style={styles.text}>Submit</Text> </Pressable> <View style={styles.spacetop}></View> <Text style={styles.text}>look through to see if you have already </Text> <Text style={styles.text}>choosed a team</Text> <ActivityIndicator animating={animating} color={'white'} size={'large'}/> {teamsData.map((team) => ( <> <View style={styles.spacetop}></View> <View key={team.id} style={styles.card}> <Text>Team ID: {team.id}</Text> <View style={styles.spacetop}></View> <Text>Team Name: {team.name}</Text> {team.students.map((student, index) => ( <View key={student.id} style={styles.spacetop}> <Text> Student {index + 1} Name: {student.name} </Text> </View> ))} <View style={styles.spacetop}></View> {team.teacherId===studentData.id?<Text>Teacher Name: {studentData.name}</Text>:<Text>TeacherID :{team.teacherId}</Text>} </View> <View style={styles.spacetop}></View> </> ))} </View> </ScrollView> </SafeAreaView> ); } const styles = StyleSheet.create({ cardlayout: { marginTop: 45, flexDirection: "row", justifyContent: "center", alignItems: "center", }, card: { backgroundColor: "#fff", paddingLeft: 30, paddingRight: 30, paddingTop: 40, paddingBottom: 40, borderRadius: 20, textAlign: "center", width:'85%' }, card2: { backgroundColor: "#fff", paddingLeft: 50, paddingRight: 50, paddingTop: 80, paddingBottom: 80, borderRadius: 20, textAlign: "center", }, cardtext: { color: "#3734A9", fontSize: 20, fontWeight: "bold", }, container: { flex: 1, backgroundColor: "#3734A9", alignItems: "center", justifyContent: "start", paddingTop: 21, }, container2: { backgroundColor: "#ffff", paddingTop: 20, paddingBottom: 80, paddingLeft: 45, paddingRight: 45, }, textstyles: { color: "white", fontFamily: "league", fontSize: 40, fontWeight: "500", paddingRight: 140, }, logo: { width: 210, height: 210, marginLeft: 120, }, input: { backgroundColor:'#fff', textAlign:'center', height: 50, width:270, margin: 12, borderWidth: 1, borderRadius:50, }, div: { backgroundColor: "#E652FF", paddingBottom: 65, paddingTop: 65, paddingLeft: 45, paddingRight: 45, borderRadius: 15, marginBottom: 20, }, button: { alignItems: "center", justifyContent: "center", paddingVertical: 12, paddingHorizontal: 32, borderRadius: 50, elevation: 3, backgroundColor: "#3734A9", }, button2: { alignItems: "center", justifyContent: "center", paddingVertical: 12, paddingHorizontal: 32, borderRadius: 50, elevation: 3, backgroundColor: "#E652FF", }, buttonred: { alignItems: "center", justifyContent: "center", paddingVertical: 12, paddingHorizontal: 32, borderRadius: 50, elevation: 3, backgroundColor: "#FF0000", }, text: { fontSize: 16, lineHeight: 21, fontWeight: "bold", letterSpacing: 0.25, color: "white", }, space: { paddingLeft: 10, paddingRight: 10, }, spacetop: { paddingTop: 30, }, });
package org.rhasspy.mobile.viewmodel.configuration.speechtotext import org.rhasspy.mobile.data.audiorecorder.AudioFormatChannelType import org.rhasspy.mobile.data.audiorecorder.AudioFormatEncodingType import org.rhasspy.mobile.data.audiorecorder.AudioFormatSampleRateType import org.rhasspy.mobile.data.service.option.SpeechToTextOption sealed interface SpeechToTextConfigurationUiEvent { sealed interface Change : SpeechToTextConfigurationUiEvent { data class SelectSpeechToTextOption(val option: SpeechToTextOption) : Change data class SetUseCustomHttpEndpoint(val enabled: Boolean) : Change data class SetUseSpeechToTextMqttSilenceDetection(val enabled: Boolean) : Change data class UpdateSpeechToTextHttpEndpoint(val endpoint: String) : Change } sealed interface Action : SpeechToTextConfigurationUiEvent { data object OpenAudioRecorderFormat : Action data object OpenAudioOutputFormat : Action data object BackClick : Action } sealed interface AudioRecorderFormatUiEvent : SpeechToTextConfigurationUiEvent { sealed interface Change : AudioRecorderFormatUiEvent { data class SelectAudioRecorderChannelType(val value: AudioFormatChannelType) : Change data class SelectAudioRecorderEncodingType(val value: AudioFormatEncodingType) : Change data class SelectAudioRecorderSampleRateType(val value: AudioFormatSampleRateType) : Change } } sealed interface AudioOutputFormatUiEvent : SpeechToTextConfigurationUiEvent { sealed interface Change : AudioOutputFormatUiEvent { data class SelectAudioOutputChannelType(val value: AudioFormatChannelType) : Change data class SelectAudioOutputEncodingType(val value: AudioFormatEncodingType) : Change data class SelectAudioOutputSampleRateType(val value: AudioFormatSampleRateType) : Change } } }
package org.example; import org.junit.Test; import java.time.LocalDate; import java.util.Map; import static org.junit.Assert.*; public class RentalToolTest { @Test public void testValidCheckout() { RentalTool[] tools = { new RentalTool("CHNS", "Chainsaw", "Stihl"), new RentalTool("LADW", "Ladder", "Werner"), new RentalTool("JAKD", "Jackhammer", "DeWalt"), new RentalTool("JAKR", "Jackhammer", "Ridgids"), }; for (RentalTool rentalTool : tools) { switch (rentalTool.toolType) { case "Chainsaw": rentalTool.setProperty(ToolType.CHAINSAW); break; case "Ladder": rentalTool.setProperty(ToolType.LADDER); break; case "Jackhammer": rentalTool.setProperty(ToolType.JACKHAMMER); break; } } Map<String, Object>[] prototypes = new Map[6]; prototypes[0] = Map.of("toolCode", "JAKR", "checkoutDate", "9/3/15", "rentalDays", 5, "discount", 101); prototypes[1] = Map.of("toolCode", "LADW", "checkoutDate", "7/2/20", "rentalDays", 1, "discount", 10); prototypes[2] = Map.of("toolCode", "CHNS", "checkoutDate", "7/2/15", "rentalDays", 5, "discount", 25); prototypes[3] = Map.of("toolCode", "JAKD", "checkoutDate", "9/3/15", "rentalDays", 6, "discount", 0); prototypes[4] = Map.of("toolCode", "JAKR", "checkoutDate", "7/2/15", "rentalDays", 9, "discount", 0); prototypes[5] = Map.of("toolCode", "JAKR", "checkoutDate", "7/2/20", "rentalDays", 4, "discount", 50); for (int i = 0; i < prototypes.length; i++) { try { String date = (String)prototypes[i].get("checkoutDate"); String[] parts = date.split("/"); LocalDate checkoutDate = LocalDate.of(Integer.parseInt(parts[2]), Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); RentalTool tool = switch ((String) prototypes[i].get("toolCode")) { case "JAKR" -> tools[3]; case "LADW" -> tools[1]; case "CHNS" -> tools[0]; case "JAKD" -> tools[2]; default -> null; }; RentalAgreement agreement = new RentalAgreement(tool, (int)prototypes[i].get("rentalDays"), (int)prototypes[i].get("discount"), checkoutDate); agreement.printRentalAgreement(); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } } @Test public void testInvalidRentalDays() { RentalTool tool = new RentalTool("CHNS", "Chainsaw", "Stihl"); tool.setProperty(ToolType.CHAINSAW); LocalDate checkoutDate = LocalDate.of(2023, 8, 24); Exception exception = assertThrows(IllegalArgumentException.class, () -> { new RentalAgreement(tool, 0, 10, checkoutDate); }); assertTrue(exception.getMessage().contains("Rental day count must be 1 or greater.")); } @Test public void testInvalidDiscountPercent() { RentalTool tool = new RentalTool("JAKD", "Jackhammer", "DeWalt"); tool.setProperty(ToolType.JACKHAMMER); LocalDate checkoutDate = LocalDate.of(2023, 9, 3); Exception exception = assertThrows(IllegalArgumentException.class, () -> { new RentalAgreement(tool, 4, 101, checkoutDate); }); if (exception.getMessage().contains("Discount percent must be in range 0-100.")) { System.out.println("Discount percent must be in range 0-100."); } // assertTrue(); } }
import { Request, Response } from 'express'; import httpStatus from 'http-status'; import { paginationFields } from '../../../constants/pagination'; import catchAsync from '../../../shared/catchAsync'; import pick from '../../../shared/pick'; import sendResponse from '../../../shared/sendResponse'; import { serviceFilterableFields } from './service.constant'; import { serviceServices } from './service.service'; const getAllServices = catchAsync(async (req: Request, res: Response) => { const filters = pick(req.query, serviceFilterableFields); const options = pick(req.query, paginationFields); const result = await serviceServices.getAllServices(filters, options); sendResponse(res, { statusCode: httpStatus.OK, success: true, message: 'Services fetched successfully!', meta: result.meta, data: result.data, }); }); const createService = catchAsync(async (req: Request, res: Response) => { const { userId } = req.user as any; const result = await serviceServices.createService({ ...req.body, userId }); sendResponse(res, { statusCode: httpStatus.OK, success: true, message: 'Service created successfully!', data: result, }); }); const getServiceById = catchAsync(async (req: Request, res: Response) => { const { id } = req.params; const result = await serviceServices.getServiceById(id); sendResponse(res, { statusCode: httpStatus.OK, success: true, message: 'Service fetched successfully', data: result, }); }); const getServicesByUser = catchAsync(async (req: Request, res: Response) => { const { userId } = req.params; const options = pick(req.query, paginationFields); const result = await serviceServices.getServicesByUser(userId, options); sendResponse(res, { statusCode: httpStatus.OK, success: true, message: 'Services fetched by user successfully', meta: result.meta, data: result.data, }); }); const updateServiceById = catchAsync(async (req: Request, res: Response) => { const { id } = req.params; const payload = req.body; const result = await serviceServices.updateServiceById(id, payload); sendResponse(res, { statusCode: httpStatus.OK, success: true, message: 'Service updated successfully', data: result, }); }); const deleteServiceById = catchAsync(async (req: Request, res: Response) => { const { id } = req.params; const result = await serviceServices.deleteServiceById(id); sendResponse(res, { statusCode: httpStatus.OK, success: true, message: 'Service deleted successfully', data: result, }); }); export const serviceController = { getAllServices, getServiceById, getServicesByUser, createService, updateServiceById, deleteServiceById, };
import React from "react"; import { DashboardScreen } from "./screens/Dashboard"; import { SportsScreen } from "./screens/Sports"; import { SchedulingScreen } from "./screens/Scheduling"; import { OrganisationsScreen } from "./screens/Organisations"; import { CompetitionsScreen } from "./screens/Competitions"; import { UsersScreen } from "./screens/Users"; export type NavigationRoute = { buttonText: string; path: string; element: JSX.Element; }; type NavigationRoutes = Record<string, Record<string, NavigationRoute>>; export const navigationRoutes: NavigationRoutes = { Management: { dashboard: { buttonText: "Dashboard", path: "/", element: <DashboardScreen />, }, sports: { buttonText: "Sports", path: "/sports", element: <SportsScreen />, }, competitions: { buttonText: "Competitions", path: "/competitions", element: <CompetitionsScreen />, }, }, Planning: { scheduling: { buttonText: "Scheduling", path: "/scheduling", element: <SchedulingScreen />, }, organisations: { buttonText: "Organisations", path: "/organisations", element: <OrganisationsScreen />, }, }, People: { users: { buttonText: "Users", path: "/users", element: <UsersScreen />, }, }, };
from ..user import User from ..student import Student from ..teacher import Teacher from flask import Flask, Blueprint, url_for, request, redirect, render_template, session, flash from flask_session import Session from src.helpers import create_username, generate_salt import sqlite3, hashlib auth = Blueprint("auth", __name__) @auth.route("/register", methods=["GET", "POST"]) def register(): """ This function is called when a user visits the /register route. If the user is simply visiting the site, it is a GET request and the 'else' block of the selection below is executed. If the user had submitted a form, then a POST request is sent to the server where the form input will be handled. """ if request.method == "POST": # get form data first_name = request.form.get("first_name").lower().strip() surname = request.form.get("surname").lower().strip() email = request.form.get("email").lower().strip() password = request.form.get("password").strip() confirm_password = request.form.get("confirm_password").strip() if request.form.get("account_type") == "student": is_student = True year_group = request.form.get("year-group") section = request.form.get("section") else: is_student = False suffix = request.form.get("suffix") # First and surnames can only be one word and completely alphabetical if not(first_name and surname): # checks if the name fields are not left blank flash("Name(s) not given.") return redirect(url_for("auth.register")) elif not(first_name.isalpha() and surname.isalpha()): flash("Name(s) must be completely alphabteical.") return redirect(url_for("auth.register")) elif len(first_name.split()) != 1 or len(surname.split()) != 1: flash("Name(s) must only be one word.") return redirect(url_for("auth.register")) # email if not(email): flash("Email not given.") # both password fields must be given print("HERE", password, confirm_password) if not(password and confirm_password): flash("Password field(s) not given.") return redirect(url_for("auth.register")) elif password != confirm_password: flash("Passwords do not match") return redirect(url_for("auth.register")) # Create object if is_student: # a username and the password hash are created when creating an instance of the student or teacher class if not(year_group): flash("Year group not given.") return redirect(url_for("auth.register")) elif not(section): flash("Section not given.") return redirect(url_for("auth.register")) student = Student(first_name, surname, email, password, year_group, section) student.insert_into_db() student.save_into_session() else: teacher = Teacher(first_name, surname, suffix, email, password) teacher.insert_into_db() teacher.save_into_session() return redirect(url_for("index")) else: # Page accessed via a GET request return render_template("register.html") @auth.route("/login", methods=["GET", "POST"]) def login(): """ This function is called when a user visits the /login route. Just like register(), the webpage is displayed when a GET request is received while a POST requests resuts in form input needing to be handled. """ if request.method == "POST": """ Check if the username exists. Check if the password's hash matches the one in the database. """ # get login details username = request.form.get("username") password = request.form.get("password") # create a cursor to the database con = sqlite3.connect("db/database.db", check_same_thread=False) cur = con.cursor() if not(username and password): flash("Username and/or password not given.") return redirect(url_for("auth.login")) query = User.login_query(username) if query == -1: flash("User not found.") return redirect(url_for("auth.login")) if User.check_hash(password, query["salt"], query["password_hash"]) == -1: flash("Incorrect password.") return redirect(url_for("auth.login")) if "_s" in username: session["user_info"] = { "username": username, "first_name": cur.execute("SELECT first_name FROM students WHERE username = ?", [username]).fetchone()[0].capitalize(), "surname": cur.execute("SELECT surname FROM students WHERE username = ?", [username]).fetchone()[0].capitalize(), "email": cur.execute("SELECT email FROM students WHERE username = ?", [username]).fetchone()[0], "year_group": cur.execute("SELECT year_group FROM students WHERE username = ?", [username]).fetchone()[0], "section": cur.execute("SELECT section FROM students WHERE username = ?", [username]).fetchone()[0], "is_student": True, } cur.close() return redirect(url_for("home.student_home")) else: session["user_info"] = { "username": username, "email": cur.execute("SELECT email FROM teachers WHERE username = ?", [username]).fetchone()[0], "first_name": cur.execute("SELECT first_name FROM teachers WHERE username = ?", [username]).fetchone()[0].capitalize(), "surname": cur.execute("SELECT surname FROM teachers WHERE username = ?", [username]).fetchone()[0].capitalize(), "suffix": cur.execute("SELECT suffix FROM teachers WHERE username = ?", [username]).fetchone()[0], "is_student": False, } cur.close() return redirect(url_for("home.teacher_home")) else: return render_template("login.html") @auth.route("/logout") def logout(): session.clear() return redirect("/")
import { createRef, useEffect, useState } from "react" import { Canvas, ColorPicker, PaletteBox, Uploader } from "../Components" import { generatePalette } from "../Utils/pletteGenerator"; import defImage from '../Asset/Img/default.jpg' import { DragAndUpload } from "../Components/DragAndUpload/DragAndUpload"; export const App = () => { const fileInp = createRef(); const [selectedColor, setSelectedColor] = useState('') const [tempColor, setTempColor] = useState('') const [loadedImg, setLoadedImg] = useState(null) const [palette, setPalette] = useState([]) const [colorCount, setColorCount] = useState(5) const [imageData, setImageData] = useState(null) const [catchingHover, setCatchingHover] = useState(false) const [screenWidth, setScreenWidth] = useState(window.screen.width) const getResponsiveWidth = (width) => { let maxWidth = screenWidth - 24 - screenWidth / 20; return width > maxWidth ? maxWidth : width; } const getPalette = () => { const palette = generatePalette(imageData, colorCount) setPalette(palette) } const uploadHandler = (image) => { const initialImg = new Image() initialImg.onload = () => { setLoadedImg(initialImg) } initialImg.src = URL.createObjectURL(image) } const pasteHandler = (e) => { const text = e.clipboardData.getData('text') const clipboardItems = e.clipboardData.items const image = (clipboardItems[0].kind === 'file') ? clipboardItems[0].getAsFile() : null if (image) { uploadHandler(image) return } const IMAGE_URL_EXP = /^http[^?]*.(jpg|jpeg|gif|png|tiff|bmp)(\?(.*))?$/gmi if (text && text.match(IMAGE_URL_EXP)) { fetch(text) .then(res => res.blob()) .then(blob => uploadHandler(blob)) } } const screenResizeHandler = () => { setScreenWidth(window.screen.width) } const colorCountHandler = (operation) => { switch (operation) { case "+": setColorCount(colorCount => colorCount < 10 ? colorCount + 1 : colorCount) break; case "-": setColorCount(colorCount => colorCount > 2 ? colorCount - 1 : colorCount) break; default: break; } } useEffect(() => { if (imageData) getPalette() }, [imageData, colorCount]) useEffect(() => { const initialImg = new Image() initialImg.onload = () => { setLoadedImg(initialImg) } initialImg.src = defImage window.addEventListener('resize', screenResizeHandler) window.addEventListener('paste', pasteHandler) return () => { window.removeEventListener('resize', screenResizeHandler) window.removeEventListener('paste', pasteHandler) } }, []) return ( <div className="h-screen relative flex flex-col lg:flex-row justify-center items-center bg-pink-300"> <DragAndUpload {...{ uploadHandler }} /> <div className="absolute -translate-x-80 -translate-y-52 z-0 h-48 w-48 rounded-full bg-blue-500"></div> <div className="z-10 shadow-lg hover:shadow-2xl p-2 mr-6 rounded-md bg-white bg-opacity-25 backdrop-blur-sm"> <div className="flex justify-center shadow-sm h-96 w-96"> {loadedImg ? <Canvas {...{ setSelectedColor, setTempColor, loadedImg, setImageData, setCatchingHover }} width={380} height={380} /> : "" } </div> <PaletteBox {...{ colorCountHandler, palette }} /> </div> <div className="flex flex-col sm:flex-row lg:flex-col p-2 z-10 "> <ColorPicker tempColor={catchingHover ? tempColor : selectedColor} selectedColor={selectedColor} /> <Uploader {...{ uploadHandler }} /> </div> </div> ) }
package api.utilities; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; import com.aventstack.extentreports.markuputils.ExtentColor; import com.aventstack.extentreports.markuputils.MarkupHelper; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import com.aventstack.extentreports.reporter.configuration.ChartLocation; import com.aventstack.extentreports.reporter.configuration.Theme; public class Utilitty_extentReports extends TestListenerAdapter { public ExtentHtmlReporter htmlreporter; public ExtentReports extent; public ExtentTest logger; public void onStart(ITestContext testContext) { String timestamp=new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()); //time stamp String repname="Test-Report"+timestamp +".html"; //htmlreporter=new ExtentHtmlReporter(System.getProperty("user.dir")+"/test-output/"+repname); htmlreporter=new ExtentHtmlReporter(System.getProperty("user.dir")+"/Reports/"+repname); htmlreporter.loadXMLConfig(System.getProperty("user.dir")+"/extent-config.xml"); extent=new ExtentReports(); extent.attachReporter(htmlreporter); extent.setSystemInfo("Hostname","localHost"); extent.setSystemInfo("Envoirment","QA"); extent.setSystemInfo("user", "manoj"); htmlreporter.config().setDocumentTitle("PetStore Report"); htmlreporter.config().setReportName("Rest Assured Report"); htmlreporter.config().setTestViewChartLocation(ChartLocation.TOP); htmlreporter.config().setTheme(Theme.STANDARD); } public void onTestSuccess(ITestResult tr) { logger=extent.createTest(tr.getName()); //create new entry to the report logger.log(Status.PASS, MarkupHelper.createLabel(tr.getName(), ExtentColor.GREEN)); } public void onTestFailure(ITestResult tr) { logger=extent.createTest(tr.getName()); logger.log(Status.FAIL, MarkupHelper.createLabel(tr.getName(), ExtentColor.RED)); String screenshotpath=System.getProperty("user.dir")+"\\screenshots\\"+tr.getName()+".png"; //String screenshotpath="C:\\Users\\sai\\eclipse-workspace\\Pomproject1\\screenshot\\"+tr.getName()+".png"; File f=new File(screenshotpath); if(f.exists()) { try { logger.fail("Screenshot is below :" + logger.addScreenCaptureFromPath(screenshotpath)); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } } public void onTestSkipped(ITestResult tr) { logger=extent.createTest(tr.getName()); logger.log(Status.SKIP, MarkupHelper.createLabel(tr.getName(), ExtentColor.ORANGE)); } public void onFinish(ITestContext testContext) { extent.flush(); } }
/* Copyright (c) 2017-2023, Carlos Amengual. Licensed under a BSD-style License. You can find the license here: https://css4j.github.io/LICENSE.txt */ // SPDX-License-Identifier: BSD-3-Clause package io.sf.carte.uparser; /** * A handler that removes comments. * <p> * Example: * </p> * * <pre><code> * String removeComments(String text) { * String[] opening = { "/{@literal *}", "&lt;!--" }; * String[] closing = { "{@literal *}/", "--&gt;" }; * CommentRemovalHandler handler = new CommentRemovalHandler(text.length()); * TokenProducer tp = new TokenProducer(handler); * try { * tp.parseMultiComment(new StringReader(text), opening, closing); * } catch (IOException e) { * } * return handler.getBuffer().toString(); * } * </code></pre> */ public class CommentRemovalHandler implements TokenHandler2 { private final StringBuilder buffer; /** * Construct the handler with the given initial buffer size. * * @param bufSize the initial buffer size. */ public CommentRemovalHandler(int bufSize) { super(); buffer = new StringBuilder(bufSize); } /** * Get the buffer. * * @return the buffer. */ public StringBuilder getBuffer() { return buffer; } @Override public void tokenStart(TokenControl control) { } @Override public void word(int index, CharSequence word) { buffer.append(word); } @Override public void separator(int index, int codePoint) { buffer.appendCodePoint(codePoint); } @Override public void quoted(int index, CharSequence quoted, int quoteCp) { char[] quote = Character.toChars(quoteCp); buffer.append(quote); buffer.append(quoted); buffer.append(quote); } @Override public void quotedWithControl(int index, CharSequence quoted, int quoteCp) { quoted(index, quoted, quoteCp); } @Override public void quotedNewlineChar(int index, int codePoint) { buffer.appendCodePoint(codePoint); } @Override public void leftParenthesis(int index) { buffer.append('('); } @Override public void leftSquareBracket(int index) { buffer.append('['); } @Override public void leftCurlyBracket(int index) { buffer.append('{'); } @Override public void rightParenthesis(int index) { buffer.append(')'); } @Override public void rightSquareBracket(int index) { buffer.append(']'); } @Override public void rightCurlyBracket(int index) { buffer.append('}'); } @Override public void character(int index, int codePoint) { buffer.appendCodePoint(codePoint); } @Override public void escaped(int index, int codePoint) { buffer.append('\\').appendCodePoint(codePoint); } @Override public void control(int index, int codePoint) { buffer.appendCodePoint(codePoint); } @Override public void commented(int index, int commentType, String comment) { } @Override public void endOfStream(int len) { } @Override public void error(int index, byte errCode, CharSequence context) { } }
import Link from "next/link"; import { Home, Package2, ShoppingCart, Package, Users2, LineChart, Settings } from "lucide-react"; import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from "@/components/ui/tooltip"; import { usePathname } from 'next/navigation'; import type { FC } from 'react'; interface SidebarProps { } const Sidebar: FC<SidebarProps> = ({ }) => { const pathname = usePathname(); const isActive = (path: string) => pathname === path; return ( <aside className="fixed inset-y-0 left-0 z-10 hidden w-14 flex-col border-r bg-background sm:flex"> <nav className="flex flex-col items-center gap-4 px-2 sm:py-5"> <Link href="/dashboard" className={`group flex h-9 w-9 shrink-0 items-center justify-center gap-2 rounded-full ${isActive('/dashboard') ? 'bg-primary text-primary-foreground' : 'bg-background text-muted-foreground'} md:h-8 md:w-8 md:text-base`} > <Package2 className="h-4 w-4 transition-all group-hover:scale-110" /> <span className="sr-only">Acme Inc</span> </Link> <TooltipProvider> <Tooltip> <TooltipTrigger asChild> <Link href="/dashboard" className={`flex h-9 w-9 items-center justify-center rounded-lg transition-colors md:h-8 md:w-8 ${isActive('/dashboard') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-foreground'}`} > <Home className="h-5 w-5" /> <span className="sr-only">Dashboard</span> </Link> </TooltipTrigger> <TooltipContent side="right">Dashboard</TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Link href="/orders" className={`flex h-9 w-9 items-center justify-center rounded-lg transition-colors md:h-8 md:w-8 ${isActive('/orders') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-foreground'}`} > <ShoppingCart className="h-5 w-5" /> <span className="sr-only">Orders</span> </Link> </TooltipTrigger> <TooltipContent side="right">Orders</TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Link href="/products" className={`flex h-9 w-9 items-center justify-center rounded-lg transition-colors md:h-8 md:w-8 ${isActive('/products') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-foreground'}`} > <Package className="h-5 w-5" /> <span className="sr-only">Products</span> </Link> </TooltipTrigger> <TooltipContent side="right">Products</TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Link href="/customers" className={`flex h-9 w-9 items-center justify-center rounded-lg transition-colors md:h-8 md:w-8 ${isActive('/customers') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-foreground'}`} > <Users2 className="h-5 w-5" /> <span className="sr-only">Customers</span> </Link> </TooltipTrigger> <TooltipContent side="right">Customers</TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Link href="/analytics" className={`flex h-9 w-9 items-center justify-center rounded-lg transition-colors md:h-8 md:w-8 ${isActive('/analytics') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-foreground'}`} > <LineChart className="h-5 w-5" /> <span className="sr-only">Analytics</span> </Link> </TooltipTrigger> <TooltipContent side="right">Analytics</TooltipContent> </Tooltip> </TooltipProvider> </nav> <nav className="mt-auto flex flex-col items-center gap-4 px-2 sm:py-5"> <TooltipProvider> <Tooltip> <TooltipTrigger asChild> <Link href="/settings" className={`flex h-9 w-9 items-center justify-center rounded-lg transition-colors md:h-8 md:w-8 ${isActive('/settings') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-foreground'}`} > <Settings className="h-5 w-5" /> <span className="sr-only">Settings</span> </Link> </TooltipTrigger> <TooltipContent side="right">Settings</TooltipContent> </Tooltip> </TooltipProvider> </nav> </aside> ); } export default Sidebar;
package com.example.apapunada.ui.staff import android.util.Log import android.widget.Toast import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.apapunada.R import com.example.apapunada.data.dataclass.Waitlist import com.example.apapunada.ui.AppViewModelProvider import com.example.apapunada.ui.components.DropDownMenu import com.example.apapunada.ui.components.IndeterminateCircularIndicator import com.example.apapunada.ui.components.SearchBar import com.example.apapunada.ui.components.formattedDate import com.example.apapunada.viewmodel.WaitlistViewModel import com.example.apapunada.viewmodel.WaitlistWithUsername import com.example.apapunada.viewmodel.WaitlistWithUsernameState @OptIn(ExperimentalFoundationApi::class) @Composable fun StaffWaitlistScreen( waitlistViewModel: WaitlistViewModel = viewModel(factory = AppViewModelProvider.Factory) ) { var waitlistWithUsernameState = waitlistViewModel.waitlistWithUsernameState.collectAsState(initial = WaitlistWithUsernameState()) var waitlistsWithUsername: List<WaitlistWithUsername> = listOf() val primaryColor = colorResource(R.color.primary) var textInput by remember { mutableStateOf("") } var currentWaitlist by remember { mutableStateOf(WaitlistWithUsername()) } var selectField by remember { mutableStateOf("Field") } var isSelected by remember { mutableStateOf("current") } if (isSelected == "current" && textInput == "") { waitlistViewModel.loadWaitlistsByCurrentStatus() } else if (isSelected == "history" && textInput == "") { waitlistViewModel.loadWaitlistsByHistoryStatus() } if (waitlistWithUsernameState.value.isLoading) { IndeterminateCircularIndicator("Loading waitlist...") } else { if (waitlistWithUsernameState.value.errorMessage.isNotEmpty()) { Text(text = "Error loading users: ${waitlistWithUsernameState.value.errorMessage}") Log.i("User", "StaffUserScreen: ${waitlistWithUsernameState.value.errorMessage}") } else { waitlistsWithUsername = waitlistWithUsernameState.value.waitlistWithUsername } } //screen width val config = LocalConfiguration.current val width by remember(config) { mutableStateOf(config.screenWidthDp) } var callAccept by remember { mutableStateOf(false) } var callCancel by remember { mutableStateOf(false) } if (callAccept) { AcceptStatus( onDismissRequest = {callAccept = false}, onConfirmation = { waitlistViewModel.updateWaitlistState(it) waitlistViewModel.updateWaitlist() callAccept = false }, dialogTitle = stringResource(id = R.string.waitlist_14), waitlist = currentWaitlist ) } if (callCancel) { CancelStatus( onDismissRequest = {callCancel = false}, onConfirmation = { waitlistViewModel.updateWaitlistState(it) waitlistViewModel.updateWaitlist() callCancel = false }, dialogTitle = stringResource(id = R.string.waitlist_15), waitlist = currentWaitlist ) } val currentHeaderList = listOf( // (Header name, Column width) Pair(" No. ", 80.dp), Pair("Party", 400.dp), Pair("Size", 200.dp), Pair("Quoted", 180.dp), Pair("Wait", 170.dp), Pair("Actions", 200.dp) ) val historyHeaderList = listOf( // (Header name, Column width) Pair(" No. ", 80.dp), Pair("Party", 400.dp), Pair("Size", 200.dp), Pair("Quoted", 180.dp), Pair("Status", 200.dp) ) val currentList = listOf( "Party", "Size" ) val historyList = listOf( "Party", "Size", "Status" ) Column( modifier = Modifier .fillMaxSize() .padding(horizontal = dimensionResource(R.dimen.padding_large)) ) { Row ( modifier = Modifier .padding(bottom = 5.dp) ) { OutlinedButton( modifier = Modifier .padding(top = 12.dp), border = BorderStroke(width = 1.dp, color = primaryColor), colors = ButtonDefaults.outlinedButtonColors( containerColor = if (isSelected == "current") primaryColor else Color.White, contentColor = if (isSelected == "current") Color.White else primaryColor, ), shape = RoundedCornerShape( topStart = 16.dp, bottomStart = 16.dp ), onClick = { isSelected = "current" } ) { Text(text = "Current") } OutlinedButton( modifier = Modifier .padding(top = 12.dp), border = BorderStroke(width = 1.dp, color = primaryColor), colors = ButtonDefaults.buttonColors( containerColor = if (isSelected == "current") Color.White else primaryColor, contentColor = if (isSelected == "current") primaryColor else Color.White ), shape = RoundedCornerShape( topEnd = 16.dp, bottomEnd = 16.dp ), onClick = { isSelected = "history" } ) { Text(text = "History") } Spacer(modifier = Modifier.size(10.dp)) if (width > 600 && isSelected == "current") { selectField = DropDownMenu(currentList) Spacer(modifier = Modifier.size(10.dp)) SearchBar( value = textInput, onValueChange = { textInput = it }, modifier = Modifier ) if (selectField == "Party" && textInput != "") { waitlistViewModel.loadWaitlistByParty("Queue", "Queue", "%" + textInput + "%") } else if (selectField == "Size" && textInput != ""){ waitlistViewModel.loadWaitlistBySize("Queue", "Queue", textInput.toInt()) } } else if (width > 600 && isSelected == "history") { selectField = DropDownMenu(historyList) Spacer(modifier = Modifier.size(10.dp)) SearchBar( value = textInput, onValueChange = { textInput = it }, modifier = Modifier ) if (selectField == "Party" && textInput != "") { waitlistViewModel.loadWaitlistByParty("Accepted", "Cancelled", "%" + textInput + "%") } else if (selectField == "Size" && textInput != ""){ waitlistViewModel.loadWaitlistBySize("Accepted", "Cancelled", textInput.toInt()) } else if (selectField == "Status" && textInput != "") { waitlistViewModel.loadWaitlistByStatus("%" + textInput + "%") } } } if (width <= 600 && isSelected == "current") { Row { selectField = DropDownMenu(currentList) Spacer(modifier = Modifier.size(10.dp)) SearchBar( value = textInput, onValueChange = { textInput = it }, modifier = Modifier ) if (selectField == "Party" && textInput != "") { waitlistViewModel.loadWaitlistByParty("Queue", "Queue", "%" + textInput + "%") } else if (selectField == "Size" && textInput != ""){ waitlistViewModel.loadWaitlistBySize("Queue", "Queue", textInput.toInt()) } } } else if (width <= 600 && isSelected == "history") { Row { selectField = DropDownMenu(historyList) Spacer(modifier = Modifier.size(10.dp)) SearchBar( value = textInput, onValueChange = { textInput = it }, modifier = Modifier ) if (selectField == "Party" && textInput != "") { waitlistViewModel.loadWaitlistByParty("Accepted", "Cancelled", "%" + textInput + "%") } else if (selectField == "Size" && textInput != ""){ waitlistViewModel.loadWaitlistBySize("Accepted", "Cancelled", textInput.toInt()) } else if (selectField == "Status" && textInput != "") { waitlistViewModel.loadWaitlistByStatus("%" + textInput + "%") } } } Spacer(modifier = Modifier.size(10.dp)) LazyColumn( modifier = Modifier .fillMaxSize() .horizontalScroll(rememberScrollState()) ) { // header row stickyHeader { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(60.dp) .background( colorResource(R.color.primary_200), RoundedCornerShape(10.dp) ) ) { if (isSelected == "current") { currentHeaderList.forEach { header -> Text( text = header.first, fontSize = 25.sp, fontWeight = FontWeight.Bold, modifier = Modifier .width(header.second) ) } } else { historyHeaderList.forEach { header -> Text( text = header.first, fontSize = 25.sp, fontWeight = FontWeight.Bold, modifier = Modifier .width(header.second) ) } } } } items(waitlistsWithUsername.size) { i -> val waitlist = waitlistsWithUsername[i] Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(100.dp) ) { Text( text = (i+1).toString(), fontSize = 22.sp, modifier = Modifier .width(currentHeaderList[0].second) .padding(start = 20.dp) ) Text( text = waitlist.username, fontSize = 22.sp, modifier = Modifier .width(currentHeaderList[1].second) ) Text( text = waitlist.size.toString(), fontSize = 22.sp, modifier = Modifier .width(currentHeaderList[2].second) ) Text( text = formattedDate(waitlist.datetime, "date"), fontSize = 22.sp, modifier = Modifier .width(currentHeaderList[3].second) ) if (isSelected == "current") { Text( text = (((System.currentTimeMillis() - (waitlist.datetime))/60000).toString() + " mins"), fontSize = 22.sp, modifier = Modifier .width(currentHeaderList[4].second) ) } if (waitlist.status == "Queue") { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.width(currentHeaderList[5].second) ) { IconButton( onClick = { currentWaitlist = waitlist callAccept = true } ) { Icon( painter = painterResource(id = R.drawable.waitlist5), contentDescription = "Edit button", modifier = Modifier.size(30.dp) ) } IconButton( onClick = { currentWaitlist = waitlist callCancel = true } ) { Icon( painter = painterResource(id = R.drawable.waitlist6), contentDescription = "Detail button", modifier = Modifier.size(30.dp) ) } } } else { Text( text = waitlist.status, fontSize = 22.sp, modifier = Modifier .width(currentHeaderList[4].second) ) } } } } } } @Composable fun AcceptStatus( onDismissRequest: () -> Unit, onConfirmation: (Waitlist) -> Unit, dialogTitle: String, waitlist: WaitlistWithUsername ) { val primaryColor = colorResource(id = R.color.primary) val context = LocalContext.current AlertDialog( containerColor = Color.White, shape = RoundedCornerShape(5.dp), title = { Column { Row { Text( modifier = Modifier .padding( start = 10.dp, end = 10.dp, bottom = 30.dp ), fontWeight = FontWeight.Bold, fontSize = 22.sp, text = dialogTitle ) } } }, onDismissRequest = { onDismissRequest() }, dismissButton = { TextButton( modifier = Modifier .padding( start = 5.dp ) .size(width = 75.dp, height = 35.dp), shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors( containerColor = Color.White, contentColor = primaryColor ), border = BorderStroke(1.dp,primaryColor), onClick = { onDismissRequest() } ) { Text("Dismiss") } }, confirmButton = { TextButton( modifier = Modifier .padding( start = 5.dp ) .size(width = 75.dp, height = 35.dp), shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors( containerColor = primaryColor, contentColor = Color.White ), onClick = { onConfirmation( Waitlist( waitlistID = waitlist.waitlistID, userID = waitlist.userID, size = waitlist.size, datetime = waitlist.datetime, status = "Accepted" ) ) Toast.makeText(context, "Accepted", Toast.LENGTH_SHORT) .show() } ) { Text("Accept") } } ) } @Composable fun CancelStatus( onDismissRequest: () -> Unit, onConfirmation: (Waitlist) -> Unit, dialogTitle: String, waitlist: WaitlistWithUsername ) { val primaryColor = colorResource(id = R.color.primary) val context = LocalContext.current AlertDialog( containerColor = Color.White, shape = RoundedCornerShape(5.dp), title = { Column { Row { Text( modifier = Modifier .padding( start = 10.dp, end = 10.dp, bottom = 30.dp ), fontWeight = FontWeight.Bold, fontSize = 22.sp, text = dialogTitle ) } } }, onDismissRequest = { onDismissRequest() }, dismissButton = { TextButton( modifier = Modifier .padding( start = 5.dp ) .size(width = 75.dp, height = 35.dp), shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors( containerColor = Color.White, contentColor = primaryColor ), border = BorderStroke(1.dp,primaryColor), onClick = { onDismissRequest() } ) { Text("Dismiss") } }, confirmButton = { TextButton( modifier = Modifier .padding( start = 5.dp ) .size(width = 75.dp, height = 35.dp), shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors( containerColor = primaryColor, contentColor = Color.White ), onClick = { onConfirmation( Waitlist( waitlistID = waitlist.waitlistID, userID = waitlist.userID, size = waitlist.size, datetime = waitlist.datetime, status = "Cancelled" ) ) Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT) .show() } ) { Text("Cancel") } } ) } @Composable @Preview(showBackground = true, device = Devices.TABLET) fun StaffWaitlistTabletPreview() { StaffWaitlistScreen() } @Composable @Preview(showBackground = true, device = Devices.PHONE) fun StaffWaitlistPhonePreview() { StaffWaitlistScreen() }
import { Router } from '@angular/router'; import { User } from './user.model'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from "@angular/core"; import { catchError, tap } from 'rxjs/operators'; import { BehaviorSubject, throwError } from 'rxjs' import { environment } from '../../environments/environment'; export interface AuthResData{ kind: string, idToken: string, email: string, refreshToken: string, expiresIn: string, localId: string registered?: boolean //? = optional } @Injectable({ providedIn: 'root' }) export class AuthService { userSubject = new BehaviorSubject<User>(null!);//behavior subject gives subscribers immediate access to the prev value if they havent subscribed when the value was emitted private tokenExpTimer: any constructor(private http: HttpClient, private router: Router){} logOut(){ this.userSubject.next(null!) this.router.navigate(['/auth']) localStorage.removeItem('userData') if(this.tokenExpTimer){ clearTimeout(this.tokenExpTimer) } this.tokenExpTimer = null } autoLogout(expirationDuration: number){ this.tokenExpTimer = setTimeout(()=>{ this.logOut() }, expirationDuration) } signUp(email: string, password: string){ return this.http.post<AuthResData>('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key='+environment.firebaseAPIKey,{ email: email, password: password, returnSecureToken: true }).pipe(catchError(this.handleError), tap(resData =>{ this.handleAuth(resData.email, resData.localId, resData.idToken, +resData.expiresIn) }) ) } login(email: string, password: string){ return this.http.post<AuthResData>('https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key='+environment.firebaseAPIKey,{ email: email, password: password, returnSecureToken: true }).pipe(catchError(this.handleError),tap(resData =>{ this.handleAuth(resData.email, resData.localId, resData.idToken, +resData.expiresIn) } ) ) } autoLogin(){ const userData: {email: string, id: string, _token: string, _tokenExpDate: string} = JSON.parse(localStorage.getItem('userData')!) if(!userData){ return } const loadedUser = new User(userData.email, userData.id, userData._token, new Date(userData._tokenExpDate)) if(loadedUser.token){ this.userSubject.next(loadedUser) const expirationDuration = new Date(userData._tokenExpDate).getTime() - new Date().getTime( ) this.autoLogout(expirationDuration) } } private handleAuth(email: string, userId: string, token: string, expiresIn: number){ const expirationDate = new Date(new Date().getTime() + +expiresIn * 1000) //set expiration date const newUser = new User(email, userId, token, expirationDate) this.userSubject.next(newUser) this.autoLogout(expiresIn*1000) localStorage.setItem('userData', JSON.stringify(newUser)) } private handleError(errorRes: HttpErrorResponse){ let errMsg = 'An unknown error occurred' if(!errorRes.error || !errorRes.error.error){ return throwError(errMsg) } switch(errorRes.error.error.message){ case 'EMAIL_EXISTS': errMsg = 'This email already exists' break; case 'EMAIL_NOT_FOUND': errMsg = 'This email does not exist' break; case 'INVALID_PASSWORD': errMsg = 'Password is incorrect' } return throwError(errMsg) } }
import React, { useEffect, useState } from "react"; import Updater from "../../components/noticeboard/Updater"; import { useNavigate, useParams } from "react-router"; import PostAPI from "../../utils/api/postAPI"; import { Link } from "react-router-dom"; import LoadingPage from "../../pages/LoadingPage"; export default function UpdaterContainer() { const navigate = useNavigate(); const { id } = useParams(); const [loading, setLoading] = useState(true); const [post, setPost] = useState(null); useEffect(() => { const fetchPost = async () => { try { const fetchedPost = await PostAPI.getPostById(id); setPost(fetchedPost); } catch (error) { console.error("게시물을 불러오는 중에 오류가 발생했습니다:", error); } finally { setLoading(false); // 데이터 로딩이 끝나면 로딩 상태 변경 } }; fetchPost(); }, [id]); // TODO: 로딩문제를 해결하는 방법 // 로딩 중일 때는 로딩 중 메시지 출력 if (loading) { return <LoadingPage />; } // 데이터가 없으면 "존재하지 않는 게시물입니다" 메시지 출력 if (!post) { return ( <div className="flex justify-center items-center h-screen"> <div className="text-center"> <h2 className="text-2xl font-semibold mb-4">존재하지 않는 게시물입니다.</h2> <Link to="/"> <button className="bg-blue-500 text-white font-semibold px-4 py-2 rounded-md mt-4"> 홈으로 </button> </Link> </div> </div> ); } // 데이터가 있으면 Updater 컴포넌트 렌더링 const onUpdate = async (updatedPost) => { try { const updatedPostData = await PostAPI.updatePost(id, updatedPost); console.log("게시물 업데이트 완료:", updatedPostData); navigate(`/post/${id}`); } catch (error) { console.error("게시물 업데이트 실패:", error.message); } }; return <Updater onUpdate={onUpdate} post={post} />; }
# Setting up a simple django setup `Team Digipodium` presents ## clearing some Jargon - `Django` is a web framework that helps you create websites using Python. - `Static files` are files that do not change, such as images, CSS, and JavaScript. - `Templates` are files that contain HTML code and Django tags that can display dynamic data from the server. To set up a Django project with static and templates folders, you need to follow these steps: 1. Install Python and Django on your computer. You can download Python(miniconda) from [here](^https://docs.conda.io/projects/miniconda/en/latest/^). Check every checkbox to install it properly. 2. Create a folder for your project, such as `myproject`, and open it in your code editor or terminal. You can use any code editor you like, such as Visual Studio Code, PyCharm, etc. 3. (optional) Create a virtual environment for your project using the `virtualenv` command. A virtual environment is a way to isolate your project's dependencies from other projects. To create a virtual environment, type `virtualenv env` in your terminal and press Enter. This will create a folder called `env` inside your project folder. 4. (optional) Activate the virtual environment using the `activate` command. To activate the virtual environment, type `source env/bin/activate` in your terminal and press Enter. This will change your prompt to `(env)`. 5. Install Django using the `pip` command. Pip is a tool that helps you install Python packages. To install Django, type `pip install django` in your terminal and press Enter. This will download and install Django in your environment. 6. Create a new Django project using the `django-admin` command. Django-admin is a tool that helps you create and manage Django projects. To create a new Django project, type `django-admin startproject myproject` in your terminal and press Enter. This will create a folder called `myproject` inside your project folder, which contains some files and folders that are essential for a Django project. 7. Run the Django server using the `manage.py` command. Manage.py is a file that helps you run various commands for your Django project. To run the Django server, type `python manage.py runserver` in your terminal and press Enter. This will start the server on your local machine and show you a message like this: ``` Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 15, 2023 - 15:04:53 Django version 4.2, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ``` 8. Open your web browser and go to http://127.0.0.1:8000/. You should see a page that says "The install worked successfully! Congratulations!" This means that your Django project is working correctly. 9. Create a new app for your project using the `manage.py` command. An app is a component of a Django project that contains models, views, templates, and other files related to a specific feature or functionality of your website. To create a new app, type `python manage.py startapp myapp` in your terminal and press Enter. This will create a folder called `myapp` inside your project folder, which contains some files and folders that are essential for a Django app. 10. Register your app in the settings.py file of your project. Settings.py is a file that contains various configurations for your Django project, such as installed apps, database settings, static files settings, etc. To register your app, open the settings.py file in your code editor and find the line that says `INSTALLED_APPS = [...]`. Add `'myapp'` to the list of installed apps, like this: ```python # myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # add this line ] ``` 11. Create static and templates folders inside your app folder. Static and templates folders are where you store your static files and templates for your app respectively. To create these folders, type `mkdir myapp/static myapp/templates` in your terminal and press Enter. 12. Set static and templates directories in the settings.py file of your project. To tell Django where to look for static files and templates for your app, you need to add some lines to the settings.py file of your project, like this: ```python # myproject/settings.py import os # add this line # ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'myapp/static')] # add this line # Templates # https://docs.djangoproject.com/en/4.2/topics/templates/ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'myapp/templates')], # add this line 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` 13. Add some static files and templates to your app folder. To test if your static files and templates are working correctly, you can add some files to your app folder, such as a CSS file, a JavaScript file, an image file, and an HTML file. For example, you can create these files in your app folder: - `myapp/static/style.css` - `myapp/static/script.js` - `myapp/static/image.jpg` - `myapp/templates/index.html` You can write any content you want in these files, or you can use some sample content from [here](^3^), [here](^4^), [here](^5^), and [here](^6^) respectively. To use these static files and templates in your app, you need to do two more things: - Create a view function in the views.py file of your app. Views.py is a file that contains functions that handle requests and return responses for your app. To create a view function, open the views.py file in your code editor and add a function like this: ```python # myapp/views.py from django.shortcuts import render def index(request): # this function renders the index.html template return render(request, 'index.html') ``` This function takes a request object as a parameter and returns a response object that renders the index.html template. - Create a URL pattern in the urls.py file of your project. Urls.py is a file that contains patterns that map URLs to view functions for your project. To create a URL pattern, open the urls.py file in your code editor and add a line like this: ```python # myproject/urls.py from django.contrib import admin from django.urls import path from myapp import views # add this line urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), # add this line ] ``` This line tells Django to call the index view function when the user visits the root URL of your website. That's it! You have successfully set up a Django project with static and templates folders. To see the result, restart the Django server by pressing Ctrl+C in your terminal and typing `python manage.py runserver` again. Then go to http://127.0.0.1:8000/ in your web browser and you should see something like this:
// Adappted from: http://bl.ocks.org/rkirsling/5001347 function draw_transitions(graph){ var color = d3.scale.category20(); var width = 700, height = 520; var force = d3.layout.force() .nodes(graph.nodes) .links(graph.links) .size([width, height]) .linkDistance(30) .charge(-50) .on("tick", tick) .start(); var svg = d3.select("#transition").append("svg") .attr("width", width) .attr("height", height); // build the arrow. svg.append("svg:defs").selectAll("marker") .data(["end"]) // Different link/path types can be defined here .enter().append("svg:marker") // This section adds in the arrows .attr("id", String) .attr("viewBox", "0 -5 10 10") .attr("refX", 15) .attr("refY", -1.5) .attr("markerWidth", 6) .attr("markerHeight", 6) .attr("orient", "auto") .append("svg:path") .attr("d", "M0,-5L10,0L0,5"); // add the links and the arrows var path = svg.append("svg:g").selectAll("path") .data(graph.links) .enter().append("svg:path") // .attr("class", function(d) { return "link " + d.type; }) .attr("class", "link") .attr("marker-end", "url(#end)"); // define the nodes var node = svg.selectAll(".node") .data(force.nodes()) .enter().append("g") .attr("class", "node") .call(force.drag); // add the nodes node.append("circle") .attr("r", function(d){return 5 + d.deg}) .style("fill", function(d) { return color(d.group); }) .on("click", function(d,i) { //alert(d.name) $("#jobs").empty(); for (var i=0; i<graph.nodes.length; i++) { if (graph.nodes[i].group == d.group) { $("#jobs").append("<button type='button' class='list-group-item'>"+graph.nodes[i].name+"</button>"); } } }) node.append("title") .text(function(d) { return d.name; }); // add the text node.append("text") .attr("x", 12) .attr("dy", ".35em") .text(function(d) { if (d.deg > 1) return d.name; }); // add the curvy lines function tick() { path.attr("d", function(d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = Math.sqrt(dx * dx + dy * dy); return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; }); node .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); } }
<template> <router-link to="/">Home</router-link><br /> <router-link to="/login/danish">login danish </router-link><br /> <router-link to="/login/sarmad">login sarmad</router-link><br /> <router-link to="/login/awais">login awais</router-link><br /> <router-link to="/signup">sign up</router-link><br /> <!-- router-view will display the component that corresponds to the url --> <router-view></router-view> <form @submit.prevent="addTodo"> <input type="text" v-model="newTodo" /> <button>Add Todo</button> </form> <ul> <li v-for="item in filteredTodos" :key="item.id"> <input type="checkbox" v-model="item.done" /> <span :class="{ done: item.done }">{{ item.text }}</span> <button @click="removeTodo(item)">X</button> </li> </ul> <button @click="hideCompleted = !hideCompleted"> {{ hideCompleted ? "Show all" : "Hide completed" }} </button> <br /><br /> <input type="text" placeholder="email" v-model="email" /> <br /> <br /> <input type="text" placeholder="password" v-model="password" /> <br /> <br /> <button @click="postData">post</button> <ul v-for="item in list" :key="item"> <li>{{ item.id }}</li> <li>{{ item.email }}</li> <li>{{ item.avatar }}</li> <li><img :src="item.avatar" alt="not found" /></li> </ul> <signupVue @response="(mes) => (emitMsg = mes)" /> <p>{{ emitMsg }}</p> <!-- <HelloWorldVue msg="new route" /> --> </template> <script> let id = 0; import signupVue from "./components/signup.vue"; // import HelloWorldVue from "./components/HelloWorld.vue"; import axios from "axios"; export default { name: "App", data() { return { emitMsg: "not passed from emit child", hideCompleted: false, list: [], email: "", password: "", newTodo: "", todos: [ { id: id++, text: "new todo1", done: true }, { id: id++, text: "new todo2", done: true }, { id: id++, text: "new todo3", done: false }, ], }; }, components: { signupVue }, computed: { filteredTodos() { return this.hideCompleted ? this.todos.filter((t) => !t.done) : this.todos; }, }, // components: { // HelloWorldVue, // }, methods: { addTodo() { this.todos.push({ id: id++, text: this.newTodo }); this.newTodo = ""; }, removeTodo(item) { this.todos = this.todos.filter((it) => it !== item); }, async postData() { let result = await axios.post("https://reqres.in/api/users?page=1", { email: this.email, password: this.password, }); let res = result.data; console.log(res.email + ":" + res.password); }, }, async mounted() { let result = await axios.get("https://reqres.in/api/users?page=1"); // console.log(result.data.data); this.list = result.data.data; }, }; </script> <style> ul { list-style: none; display: flex; justify-content: space-between; } #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } .done { text-decoration: line-through; } </style>
import axios from 'axios' import { UpdateProductDto } from '../dtos/product.dto' import {Category} from '../models/category.model' import { Product } from '../models/product.model' export class BaseHttpService<TypeClass>{ constructor(protected url: string){ } async getAll() { const { data } = await axios.get<TypeClass[]>(this.url) return data } async update<ID, DTO>(id: ID, changes: DTO) { const {data} = await axios.put(`${this.url}/${id}`, changes) return data } } (async () => { const productService = new BaseHttpService<Product>('https://api.escuelajs.co/api/v1/products') const products = await productService.getAll() console.log(products); productService.update<Product["id"], UpdateProductDto>(products[0].id, {title: 'new title'}) const categoryService = new BaseHttpService<Product>('https://api.escuelajs.co/api/v1/categories') const categories = await categoryService.getAll() console.log(categories); })()
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.future import select from app.db.models import Program async def store_or_update_program(session: AsyncSession, program: Program): """Store or update a program.""" expression = Program.sigaa_id == program.sigaa_id result = await session.execute(select(Program).where(expression)) current_program = result.scalars().one_or_none() if current_program: current_program = program else: session.add(program) await session.commit() return current_program async def get_programs(session: AsyncSession): """Get all programs.""" result = await session.execute(select(Program)) programs = result.scalars().all() return programs async def get_program_by_sigaa_id(session: AsyncSession, sigaa_id: int): """Get a program by its SIGAA ID.""" expression = Program.sigaa_id == sigaa_id result = await session.execute(select(Program).where(expression)) program = result.scalars().one_or_none() return program
<?php namespace App\Entity; use App\Entity\Traits\Timestamp; use App\Repository\CommandeMessageRepository; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Vich\UploaderBundle\Mapping\Annotation as Vich; #[ORM\Entity(repositoryClass: CommandeMessageRepository::class)] #[ORM\HasLifecycleCallbacks] /** * @Vich\Uploadable */ class CommandeMessage { use Timestamp; #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column(type: 'integer')] /** * @Groups("message") */ private $id; #[ORM\Column(type: 'text')] /** * @Groups("message") */ private $contenu; #[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'commandeMessages')] #[ORM\JoinColumn(nullable: false, onDelete: "CASCADE")] /** * @Groups("message") */ private $user; #[ORM\ManyToOne(targetEntity: Commande::class, inversedBy: 'commandeMessages')] #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] /** * @Groups("message") */ private $commande; #[ORM\Column(type: 'boolean')] private $lu; /** * @Vich\UploadableField(mapping="messages_files", fileNameProperty="file") * @var File|null **/ private $messageFile; #[ORM\Column(length: 255, nullable: true)] private ?string $file = null; public function getId(): ?int { return $this->id; } public function getContenu(): ?string { return $this->contenu; } public function setContenu(string $contenu): self { $this->contenu = $contenu; return $this; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): self { $this->user = $user; return $this; } public function getCommande(): ?Commande { return $this->commande; } public function setCommande(?Commande $commande): self { $this->commande = $commande; return $this; } public function getLu(): ?bool { return $this->lu; } public function setLu(bool $lu): self { $this->lu = $lu; return $this; } public function getFile(): ?string { return $this->file; } public function setFile(?string $file): self { $this->file = $file; return $this; } /** * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $messageFile */ public function setMessageFile(?File $messageFile = null): void { $this->messageFile = $messageFile; if (null !== $messageFile) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->setUpdated(new \DateTimeImmutable()); } } public function getMessageFile(): ?File { return $this->messageFile; } }
import React, { Fragment, useEffect, useState } from "react"; import { useAlert } from "react-alert"; import axios from "axios"; import {serverUrl} from "../../../constants.js" // import { Link } from "react-router-dom"; const Suggestion = () => { const alert = useAlert(); const [suggestedFriends, setSuggestedFriends] = useState([]); const [sentFriendRequests, setSentFriendRequests] = useState({}); useEffect(() => { const fetchSuggestedFriends = async () => { try { const { data } = await axios.get( `${serverUrl}/user/find/matchers`, { withCredentials: true } ); console.log("response in suggestion", data?.data); if (data?.success) { setSuggestedFriends(data?.data); } } catch (error) { alert.error(error.response.data.message); } }; fetchSuggestedFriends(); }, [alert]); useEffect(() => { const storedRequests = JSON.parse(localStorage.getItem("sentFriendRequests")) || {}; setSentFriendRequests(storedRequests); }, []); useEffect(() => { localStorage.setItem("sentFriendRequests", JSON.stringify(sentFriendRequests)); }, [sentFriendRequests]); const handleFriendRequest = async (userId) => { console.log("clicked", process.env.REACT_APP_BACKEND_URL); try { let url = `${serverUrl}/user/sendFriendRequest/${userId}`; if (sentFriendRequests[userId]) { url = `${serverUrl}/user/cancelFriendRequest/${userId}`; } const { data } = await axios.post(url, null, { withCredentials: true }); console.log("response of friendrequest", data); if (data.success) { setSentFriendRequests((prevRequests) => ({ ...prevRequests, [userId]: !prevRequests[userId], })); alert.success(data.message); } else { alert.error("Error", data.message); } } catch (error) { alert.error(error); } }; return ( <Fragment> <h1 className="h-center">People you may Know !</h1> <div className="f-wrap"> {suggestedFriends?.map((friend) => ( // <Link to={`/profile/${friend?._id}`} key={friend?._id} > <div className="friend-request-container"> <div className="friend-user-container"> <div className="images"> <img src={friend?.avatar} alt="img" /> </div> <div className="name"> <h3>{friend?.username}</h3> </div> <div className="friends-count"> <img src={friend?.avatar} alt="" /> <p>{friend?.friends.length} mutual Friends</p> </div> <button className="btn-delete" onClick={() => handleFriendRequest(friend?._id)} > {sentFriendRequests[friend?._id] ? "Cancel Request" : "Add Friend"} </button> {/* <button className={`btn-confirm ${ sentFriendRequests[friend?._id] ? "hidden" : "" }`} > Remove </button> */} </div> </div> // </Link> ))} </div> </Fragment> ); }; export default Suggestion;
--- title: ReactとAuth0でソーシャルログイン date: "2022-04-15" description: Auth0を用いてReactでTwitter認証を実装しました。 image_url: "https://user-images.githubusercontent.com/71915489/159204626-e6d7a74a-0ffd-43f6-ba16-a195c506b84a.png" tags: ["React", "Auth0"] --- React の Auth0 用の sdk を用いて Auth0 の Twitter ログインを行いました。 #### 参考サイト こちらの Auth0 の公式解説をもとに実装しました。 <br /> **https://auth0.com/docs/quickstart/spa/react/01-login** <br /> **https://marketplace.auth0.com/integrations/twitter-social-connection** <br /> **https://auth0.com/docs/libraries/auth0-react** #### 準備 Auth0 への登録、TwitterDevelopper への登録は済んでいる前提でいきます。 ##### Auth0 でフロントエンドのプロジェクト作成 Auth0 の管理画面でアプリケーション作成する。 <br /> 右上の Create Application をクリック <br /> <img src="https://user-images.githubusercontent.com/71915489/170627545-10d88f98-9cc8-4a2a-a0c2-236c71532654.png" width="70%" /> <br /> 今回は`idol-otaku-project` を作成します。 <br /> そのほかのプロジェクトはデフォルトで作られているプロジェクトです。 <br /> 作成したら`idol-otaku-project` を選択し、そのまま下にスクロールして以下の**Application URIs**の項目を埋めます。 <br /> **Allowed Callback URLs** <br /> **Allowed Logout URLs** <br /> **Allowed Web Origins** <br /> **Allowed Origins (CORS)** <br /> <br /> <img src="https://user-images.githubusercontent.com/71915489/170595034-c6500ee6-6f20-4620-91ee-39e369ec9c12.png" width="70%" /> <br /> 以上の 4 項目に <br /> `http://localhost:3001(ローカルで使用するポートを設定)` を追加 <br /> 次にプロジェクトの Twitter とのコネクションを有効にしておきます。 <br /> <img src="https://user-images.githubusercontent.com/71915489/170627708-cf80e1d2-2669-4bb6-9994-b07ad0c7715f.png" width="70%" /> ##### Twitter Developper に Auth0 のテナントを登録 Twitter Developper で作成したプロジェクトに auth0 のテナントの URL を入力します。 <br /> テナントのドメインは作成したプロジェクトの Settings に書いてあります。 <br /> 以下のように登録 <br /> ``` Website URL: <テナントのドメイン> Callback URI : <テナントのドメイン>/login/callback ``` <br /> <img src="https://user-images.githubusercontent.com/71915489/170597316-7a67294f-2dfc-4fcb-ae93-c48e30224693.png" width="70%" /> ##### React アプリケーション作成 任意のディレクトリ作成 <br /> ```javascript{numberLines:true} mkdir frontend cd frontend ``` <br /> react アプリケーション作成。 <br /> ```javascript{numberLines:true} $ yarn create react-app . ``` <br /> 必要な環境変数を作成します。 <br /> ```javascript{numberLines:true} $ touch .env ``` <br /> ※ []はいりません。文字列のみ入力してください。 <br /> <div class="gatsby-code-title"> <span>frontend/.env.development</span> </div> ```javascript{numberLines:true} // ローカルで起動時のポート PORT=3001 // auth0のテナントのドメイン REACT_APP_AUTH0_DOMAIN=[Domain] // auth0のフロントエンドアプリケーションのClient ID REACT_APP_AUTH0_CLIENT_ID=[Client ID] ``` <br /> auth0 用の sdk をインストール <br /> ```javascript{numberLines:true} yarn add @auth0/auth0-react ``` <br /> `frontend/src/index.js` を以下のように編集 <br /> <div class="gatsby-code-title"> <span>frontend/src/index.js</span> </div> ```javascript{numberLines:true} import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { Auth0Provider } from '@auth0/auth0-react'; const domain = process.env.REACT_APP_AUTH0_DOMAIN || ''; const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID || ''; const container = document.getElementById('root'); const root = ReactDOM.createRoot(container); root.render( <Auth0Provider domain={domain} clientId={clientId} redirectUri={window.location.origin} > <App /> </Auth0Provider> ); ``` <br /> `frontend/src/App.js` を編集 <div class="gatsby-code-title"> <span>frontend/src/App.js</span> </div> ```javascript{numberLines:true} import './App.css'; import { useAuth0 } from '@auth0/auth0-react'; function App() { const { user, isAuthenticated, loginWithRedirect, logout } = useAuth0(); // 必要な機能をインポート console.log(user); return ( <div className='App'> <div style={{ padding: '20px' }}> <h2>ログインボタン</h2> <button onClick={() => loginWithRedirect()}>ログイン</button> <h2>ログアウトボタン</h2> <button onClick={() => logout()}>ログアウト</button> <h2>ログイン状態</h2> {isAuthenticated ? <p>{user.name}</p> : <p> ログアウト</p>} </div> </div> ); } export default App; ``` <br /> 長かったですね!これでログイン処理ができます。 <br /> `loginWithRedirect`でログインができます。`logout`でログアウトします。`isAuthenticated`にはログインしているか、していないかが`boolean`で入っています。 <br /> `user`にはログインしたユーザーの情報が入っています。 ここまで、読んでいただきありがとうございました! <br /> 分かりにくい、または間違っているところあれば連絡いただければと思います。 #### 連絡先 何か連絡をしたい際は以下 SNS、メールでお願いいたします。 **Twitter**:  [https://twitter.com/naka_ryo_z](https://twitter.com/naka_ryo_z) **Github**:  [https://github.com/ryotaro-tenya0727](https://github.com/ryotaro-tenya0727) **メール**:   [email protected]
import React from 'react' import classnames from 'classnames' import Message from '@ttn-lw/lib/components/message' import PropTypes from '@ttn-lw/lib/prop-types' import style from './description-list.styl' const DescriptionListItem = props => { const { className, children, data, title, highlight } = props const content = children || data if (!Boolean(content)) { return null } if (!Boolean(title)) { return ( <div className={classnames(className, style.container)}> <div className={classnames(style.value, style.onlyValue)}>{content}</div> </div> ) } return ( <div className={classnames(className, style.container)}> <dt className={style.term}> <Message content={title} /> </dt> <dd className={classnames(style.value, { [style.highlight]: highlight })}>{content}</dd> </div> ) } DescriptionListItem.propTypes = { children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), className: PropTypes.string, data: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), highlight: PropTypes.bool, title: PropTypes.message, } DescriptionListItem.defaultProps = { children: undefined, data: undefined, className: undefined, highlight: false, title: undefined, } export default DescriptionListItem
using ArcCreate.Jklss.BetonQusetEditor.Base; using ArcCreate.Jklss.BetonQusetEditor.Windows; using ArcCreate.Jklss.Model.ClientModel; using ArcCreate.Jklss.Model.SocketModel; using ArcCreate.Jklss.Services; using GalaSoft.MvvmLight.Command; using QRCoder; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Forms; using System.Windows.Media.Imaging; using System.Windows.Media; using ComboBox = System.Windows.Controls.ComboBox; using Color = System.Drawing.Color; using System.Threading; namespace ArcCreate.Jklss.BetonQusetEditor.ViewModel.BetonQuest.ClientWindow { public class PayWindowViewModel : NotifyBase { private PayWindow window; public PayWindowViewModel(PayWindow payWindow) { window = payWindow; } private static PayModel model = new PayModel(); public string ImageFile { get { if (string.IsNullOrEmpty(model.ImageFile)) { return "/img/pay/99.jpg"; } return model.ImageFile; } set { if (string.IsNullOrEmpty(value)) { model.ImageFile = "/img/pay/99.jpg"; } model.ImageFile = value; NotifyChanged();//当view的值发生改变时通知model值发生了改变 } } public string PayMessage { get { return model.PayMessage; } set { model.PayMessage = value; NotifyChanged();//当view的值发生改变时通知model值发生了改变 } } public string PayMessageColor { get { return model.PayMessageColor; } set { model.PayMessageColor = value; NotifyChanged();//当view的值发生改变时通知model值发生了改变 } } private RelayCommand<ComboBox> _SelectionChanged; public RelayCommand<ComboBox> SelectionChanged { get { if (_SelectionChanged == null) { _SelectionChanged = new RelayCommand<ComboBox>(async (cb) => { var getSel = cb.SelectedIndex; var message = new MessageModel() { IsLogin = SocketModel.isLogin, JsonInfo = JsonInfo.UsePath, UserName = SocketModel.userName, Message = getSel.ToString(), Path = "BuyPointVIPBuy" }; var getResult = await SocketViewModel.EazySendRESMessage(message); if (!getResult.Succese) { return; } var outTradeNo = string.Empty; try { var fg = (getResult.Backs as MessageModel).Message.Split('|'); var payaddress = fg[0]; outTradeNo = fg[1]; QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(payaddress, QRCodeGenerator.ECCLevel.L); QRCode qrcode = new QRCode(qrCodeData); var image = qrcode.GetGraphic(5, Color.Black, Color.White, null, 15, 6, false); window.bitmap_Img.Source = ChangeBitmapToImageSource(image); } catch { return; } await CheckPay(outTradeNo); }); } return _SelectionChanged; } set { _SelectionChanged = value; } } public CommandBase _CloseCommand; public CommandBase CloseCommand { get { if (_CloseCommand == null) { _CloseCommand = new CommandBase(); _CloseCommand.DoExecute = new Action<object>(obj =>//回调函数 { (obj as Window).Close(); });//obj是窗口CommandParameter参数传递的值,此处传递为窗口本体 } return _CloseCommand; } } public CommandBase _NarrowCommand; public CommandBase NarrowCommand { get { if (_NarrowCommand == null) { _NarrowCommand = new CommandBase(); _NarrowCommand.DoExecute = new Action<object>(obj =>//回调函数 { (obj as Window).WindowState = WindowState.Minimized; });//obj是窗口CommandParameter参数传递的值,此处传递为窗口本体 } return _NarrowCommand; } } /// <summary> /// 从bitmap转换成ImageSource /// </summary> /// <param name="icon"></param> /// <returns></returns> public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (!DeleteObject(hBitmap)) { throw new System.ComponentModel.Win32Exception(); } return wpfBitmap; } [DllImport("gdi32.dll", SetLastError = true)] private static extern bool DeleteObject(IntPtr hObject); private async Task CheckPay(string outTradeNo) { bool isSuccess = false; await Task.Run(async () => { while (!isSuccess) { Thread.Sleep(1000); var newmessage = new MessageModel() { IsLogin = SocketModel.isLogin, JsonInfo = JsonInfo.UsePath, UserName = SocketModel.userName, Message = outTradeNo, Path = "CheckPointVIPBuy" }; var getResult = await SocketViewModel.EazySendRESMessage(newmessage); if (!getResult.Succese) { PayMessageColor = "Red"; PayMessage = getResult.Text; continue; } else { PayMessageColor = "Green"; PayMessage = (getResult.Backs as MessageModel).Message; isSuccess = true; } } }); } } }
import { useEffect, useState } from 'react'; import TextInput from './InputText'; import TextArea from './TextArea'; import Button from './Button'; import Error from './Error'; export default function FlashCardForm({ createMode = true, onPersist = null, children: flashCard = null, }) { const backgroundClassName = createMode ? 'bg-green-100' : 'bg-yellow-100'; console.log(flashCard); const [title, setTitle] = useState(flashCard?.title || ''); const [description, setDescription] = useState(flashCard?.description || ''); const [error, setError] = useState(''); useEffect(() => { if (createMode) { clearFields(); } }, [createMode]); function handleInputChange(newTitle) { setTitle(newTitle); } function handleTextAreaChange(newDescription) { console.log('textArea'); setDescription(newDescription); } function clearFields() { setTitle(''); setDescription(''); } function handleFormSubmit(event) { event.preventDefault(); if (validateForm()) { if (onPersist) { onPersist(title, description); clearFields(); } } else { setError('Título e descrição são obrigatorios'); } } function handleFormReset(event) { clearFields(); } function validateForm() { setError(''); return title.trim() !== '' && description.trim() !== ''; } return ( <form className={`${backgroundClassName} p-4`} onSubmit={handleFormSubmit} onReset={handleFormReset} > <h2 className="text-center font-semibold">Manutenção de flash Cards</h2> <TextInput labelDescription="Titulo" inputValue={title} onInputChange={handleInputChange} ></TextInput> <TextArea labelDescription="Descrição" textAreaValue={description} onTextAreaChange={handleTextAreaChange} ></TextArea> <div className="flex items-center justify-between"> {error.trim() !== '' ? <Error>{error}</Error> : <span>&nbsp;</span>} <div> <Button colorClass="bg-red-200" type="reset"> Limpar </Button> <Button colorClass="bg-green-400" type="submit"> Salvar </Button> </div> </div> </form> ); }
'use client' import './markdown.css' import { usePost } from "@/lib/global"; import Markdown from "react-markdown"; import { useEffect, useState } from "react"; import rehypeHighlight from 'rehype-highlight' export function Preview(props: {className?:string}) { const {ingredients,steps} = usePost() const [content,setContent] = useState('') useEffect(() => { setContent(`## Ingredients ${ingredients.map((ingredient) => `- ${ingredient.name}`).join('\n')} ## Steps ${steps.sort((a,b) => a.pos - b.pos).map((step,i) => `${i+1}. ${step.content}`).join('\n')}`) }, [ingredients, steps, setContent]) return <Markdown className={`markdown-body ${props.className??''}`} rehypePlugins={[rehypeHighlight]} >{content}</Markdown> }
import { useState } from "react"; import { useNavigate } from "react-router-dom"; export default function AddProduct({ addProduct}) { const [name, setName] = useState(""); const [price, setPrice] = useState(0); const [description, setDescription] = useState(""); const [url, setUrl] = useState(""); const navigate = useNavigate(); const handleSubmit = (e) => { e.preventDefault() const product = { name, price, description, url }; addProduct(product) alert(`${name} Product Added Successfully`) navigate("/") }; return( <form onSubmit={handleSubmit}> <h1>Add New Product</h1> <div className="form-group"> <label htmlFor="name">Name</label> <input type="text" className="form-control" value={name} onChange={(e) => setName(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="price">Price</label> <input type="number" className="form-control" value={price} onChange={(e) => setPrice(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="description">Description</label> <textarea className="form-control" value={description} onChange={(e) => setDescription(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="url">URL</label> <input type="text" className="form-control" value={url} onChange={(e) => setUrl(e.target.value)} /> </div> <button type="submit" className="btn btn-primary" onClick={handleSubmit}>Add Product</button> </form> ) }
###################################################################### # Basic test script for writing a NanoEvents array to a NanoAOD file # ###################################################################### # imports import sys import os import argparse from pathlib import Path import awkward as ak from coffea.nanoevents import NanoEventsFactory, NanoAODSchema sys.path.append(str(Path(__file__).parents[2])) from skimming.nanoeventswriter import NanoEventsWriter from objectselection.electronselection import electronselection from objectselection.muonselection import muonselection from objectselection.cleaning import clean_electrons_from_muons from preprocessing.preprocessor import PreProcessor from samples.sample import year_from_sample_name # input arguments: parser = argparse.ArgumentParser(description='Test file writing and re-reading') parser.add_argument('-i', '--inputfile', required=True, type=os.path.abspath) parser.add_argument('-o', '--outputfile', required=True, type=os.path.abspath) parser.add_argument('-n', '--nentries', type=int, default=-1) parser.add_argument('-m', '--mode', choices=['write','read'], default='write') args = parser.parse_args() # print arguments print('Running with following configuration:') for arg in vars(args): print(' - {}: {}'.format(arg,getattr(args,arg))) # make NanoEvents array year = None if args.mode=='write': year = year_from_sample_name(args.inputfile) events = NanoEventsFactory.from_root( args.inputfile, entry_stop=args.nentries if args.nentries>=0 else None, schemaclass=NanoAODSchema, metadata={'year': year} ).events() print('Basic properties of "events" array:') print(events) print(type(events)) print('Number of events: {}'.format(ak.count(events.event))) if args.mode=='read': # print out all the fields print('Contents of "events" array:') for field in sorted(events.fields): print(' {}'.format(field)) for subfield in sorted(events[field].fields): print(' {}'.format(subfield)) sys.exit() # calculate additional needed variables preprocessor = PreProcessor() preprocessor.process(events, leptongenvariables=['isPrompt'], leptonvariables=[ 'jetPtRatio', 'jetBTagDeepFlavor' ], topmvavariable='mvaTOP', topmvaversion='ULv1' ) # do object and event selection selected_muons = events.Muon[muonselection(events.Muon, selectionid='run2ul_loose')] selected_electrons = events.Electron[ ( (electronselection(events.Electron, selectionid='run2ul_loose')) & (clean_electrons_from_muons(events.Electron, selected_muons)) ) ] selected_events = events[ (ak.num(selected_muons.pt) + ak.num(selected_electrons.pt) >= 2) ] # write to a file writer = NanoEventsWriter() writer.write( selected_events, args.outputfile, drop='default' ) # print size of input and output file print('Size of input file:') os.system('ls -lh {}'.format(args.inputfile)) print('Size of output file:') os.system('ls -lh {}'.format(args.outputfile))
Authentication Schedule This document presents several authentication flows that can be used to identify an entity who wants to access Smart Core. It enumerates the following properties - **Who** - which entities (people or machines) will use this flow? - **Why** - for what purpose does the subject need to access Smart Core - **Where** - what location will be subject be in, and what network(s) will they be using to connect to smart core - **How** - what does the subject need to do in order to get access? ## Apps - Active Directory Flow - **Who?**: Landlord employees involved in monitoring or operating the building - **Why?** - To access the Smart Core web apps, for: - Configuration & Commissioning - Viewing Data - Manual Control - **Where** - on workstations connected to the landlord network, with direct connections to the app server - **How** - by entering their domain username and password on the Keycloak login page ### Data Storage User information is stored in an Active Directory server. The AD server will be accessible over LDAP to allow checking user passwords, and querying basic user information including group membership. ### Technical Details Keycloak will connect to an AD via LDAP to authenticate users. User roles will be auto-assigned based on group memberships in Active Directory. The Smart Core apps will send the entered username and password to Keycloak, which will return a Bearer token which can be used for Smart Core API access. ### Management Day-to-day management will be performed using the AD server. By assigning users to the appropriate groups, network administrators can provide landlord employees access to the parts of Smart Core they require. ### Reliability This authentication flow is dependent on both Active Directory and Keycloak being operational and accessible. Keycloak must be accessible from the client web app, so it can retrieve access tokens. If Active Directory is not available, but Keycloak is, then users can log in with the [Apps - Backup User Access](#apps---local-user-flow) flow below. If Keycloak is unavailable, then users can sign in using [Apps - Local User Access](#apps---backup-user-access). Existing sessions will continue to work until issued access tokens expire. The validity duration of tokens is configurable in Keycloak. ## Apps - Backup User Access - **Who?** - network administrators, or select landlord employees - **Why?** - to access the same resources as the Active Directory flow, when the LDAP connection to AD is unavailable - **Where?** - as in the AD flow - **How?** - by entering a Smart Core-specific username and password into Keycloak the login page ### Data Storage In addition to using user accounts via LDAP, Keycloak also maintains its own user database. Users can be created with usernames, emails, names (and other expected profile stuff), and roles. Keycloak's user database will be stored in the PostgreSQL database. ### Technical Details As in "Apps - Active Directory" flow, but user is stored in Keycloak's own database rather than Active Directory. Keycloak issues access tokens as normal. ### Management Users must be manually provisioned using the Keyclock web interface. It is expected that only a small number of accounts will be required. ### Reliability Flow is available only if Keycloak is operational and accessible. ### Alternatives Rather than having Keycloak query Active Directory for logins, it is possible to sync the directory into Keycloak's own user database. This means that logins against directory user accounts would be possible even if Active Directory were temporarily unavailable, so manually managing keycloak accounts would not be necessary. However, doing this would involve storing personal data and hashed user passwords in Keycloak. ## Apps - Local User Flow - **Who?** - network administrators, commissioners, or select landlord employees - **Why?** - to setup or troubleshoot individual controllers, or in cases where other more robust mechanisms are unavailable - **Where?** - as in the AD flow - **How?** - by entering a Smart Core-specific username and password into the app hosted login page ### Data Storage Users are configured via a configuration file stored on the local filesystem of the controller. User information and claims are configured in the file and the credentials are hashed. ### Technical Details The app invokes the OAuth Password flow to exchange user entered credentials for an access token directly with the Smart Core controller. ### Management Users must be manually provisioned by an administrator during the setup of the controller. ### Reliability If the server is online, the flow is available. ### Alternatives This is the lowest level of user authentication, Keycloak auth is preferred. The only other alternative is to disable authentication entirely, which is not recommended. ## Tenant Token Flow - **Who?** - Tenant's own software services (machine, not a person) - **Why?** - To allow the tenant to monitor and control the smart systems within their demise, using the Smart Core API. - **Where?** - on the tenant's own in-building network; connections go via the gateway - **How?** - tenant exchanges their client ID and secret with the server for an access token ### Data Storage Tenant details and secrets are stored in PostgreSQL. Each tenant is represented in the DB and linked to one or more secrets. The building controller it typically uniquely responsible for DB access via it's API. ### Technical Details The tenant's client will perform an OAuth2 Client Credentials grant using their client secret. They will receive an access token which will permit them access to the Smart Core API via the gateway. The API Gateway will ask the building controller to verify the token, and will only forward the request onward if the token is valid and the request passes all applicable security rules. Tenant claims include zones which describe while devices the tenant is permitted to access. ### Management Tenants are created and managed via the Ops App and/or the Smart Core Tenant API. Tenant secrets are generated and managed via the same mechanisms. The building FM team or ops team are responsible for sharing the tenant Client ID and generated secrets with the tenant. ### Reliability Accessing the Smart Core API using tenant credentials via the gateway involves the gateway talking to the building controller and the building controller talking to the DB. If either of these are unavailable, the flow will not work. ### Alternatives Tenant accounts can also be configured using the [Tenant Local Flow](#tenant-local-flow) below. The gateway can be configured to connect directly to the DB at the cost of granting permission for the gateway to access the DB directly. ## Tenant Local Flow - **Who?** - Tenant's own software services (machine, not a person) - **Why?** - To allow the tenant to monitor and control the smart systems within their demise, using the Smart Core API. - **Where?** - on the tenant's own in-building network; connections go via the gateway - **How?** - tenant exchanges their client ID and secret with the server for an access token ### Data Storage Tenants and secrets are configured via a configuration file stored on the local filesystem of the controller. Tenant information and claims are configured in the file and the credentials are hashed. ### Technical Details The tenant authenticates with the server using the same OAuth2 Client Credentials grant as in the [Tenant Token Flow](#tenant-token-flow). ### Management Tenants are created during controller setup by an administrator with access to the underlying filesystem. ### Reliability If the server is online, the flow is available. ### Alternatives This is the lowest level of tenant authentication without any management opportunity.
<template> <div class="container-full"> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-12"> <div class="box"> <div class="box-header with-border"> <div class="d-flex justify-content-between"> <h3 class="box-title">Danh sách người dùng</h3> </div> </div> <div class="box-body"> <div class="row"> <div class="col-sm-12 col-md-4"> <div class="input-group"> <input type="search" id="search-data" name="search_key" class="form-control" style="border-radius: 7px !important" placeholder="Nhập tên, email ..." v-model="searchKey" /> <button type="button" @click="searchUser" class="btn btn-primary ml-15" style="border-radius: 7px !important" > Tìm kiếm </button> </div> </div> </div> </div> <!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>Ảnh người dùng</th> <th>Tên</th> <th>Email</th> <th>Số điện thoại</th> <th>Địa chỉ</th> <th v-if="role == 1">Action</th> </tr> </thead> <tbody> <tr v-for="item in listUsers" :key="item.id"> <td> <img :src=" item.profile_photo_path ? item.profile_photo_path : '/frontend/assets/images/no-image.jpg' " alt="" width="50px" /> </td> <td>{{ item.name }}</td> <td>{{ item.email }}</td> <td>{{ item.phone }}</td> <td>{{ item.address }}</td> <td v-if="role == 1"> <a href="" :data-url="`/admin/user/delete/${item.id}`" class="btn btn-danger action-delete" title="Delete Data" id="delete" > <i class="fa fa-trash"></i ></a> </td> </tr> </tbody> </table> <paginate :page-count="lastPage"></paginate> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> </div> <!-- /.row --> </section> <!-- /.content --> <loading :active="isLoading" :is-full-page="fullPage"/> </div> </template> <script> import Paginate from "../Paginate.vue"; import Loading from 'vue-loading-overlay'; import 'vue-loading-overlay/dist/vue-loading.css'; const axios = require('axios'); export default { components: { Paginate, Loading }, props: { users: Array, total: Number, lastPage: Number, role: Number }, data() { return { listUsers: [], searchKey: "", isLoading: false, fullPage: true }; }, created() { this.listUsers = this.users; }, methods: { searchUser: async function () { this.isLoading = true; const response = await axios.get(`/admin/user/search?search_key=${this.searchKey}`); setTimeout(() => { this.isLoading = false; this.lastPage = response.data.lastPage; this.listUsers = response.data.listUsers; }, 500); }, }, }; </script> <style lang="scss" scoped> </style>
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/css/template.css"> <link rel="stylesheet" href="https://stackpath.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.12.9/umd/popper.min.js"></script> <link rel="stylesheet" href="/css/entryForms.css"> <script src="/js/setDate.js"></script> <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> <title>Previous Sports</title> </head> <header> <nav class="navbar navbar-expand-md navbar-light bg-light sticky-top"> <div class="container-fluid"> <a class="navbar-brand" href="/"><img src="/images/logo.png"></a> <!-- Logo location with link to homepage --> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> <!-- Drop down menu button when page is on mobile --> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <!--Each button object for nav--> <a class="nav-link" href="/">Home</a> </li> <li class="nav-item active"> <a class="nav-link" href="/new-applicant">Sign Up</a> </li> <li class="nav-item active"> <a class="nav-link" href="/login">Login</a> </li> <li class="nav-item active"> <a class="nav-link" href="/logout">Log Out</a> </li> </ul> </div> <div class="row-navbar"> <div id="google_translate_element"> <script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element'); } </script> </div> </div> </div> </nav> <h1 id="pageTitle">Update Profile </h1> </header> <body> <p> Please fill in the details below about any previous sporting history.</p> <br> <div class="entry-form"> <form action="#" method="post" th:action="@{/submit-previous-sports}" th:object="${previousSports}"> <input th:field="*{athleteID}" hidden> <div class="form-group"> <label th:for="previousSport">Have you done any previous sports?</label><br> <input class="form-control" th:field="*{previousSport}" type="text" placeholder="Previous Sports" required><br> </div> <span th:errors="*{previousSport}" th:if="${#fields.hasErrors('previousSport')}">Please enter text.</span> <br> <div class="form-check"> <label th:for="monthsTesting">Number of months spent training last year:</label> <br> <input class="session-rpe-button" th:field="*{monthsTesting}" th:value="'0-3'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('monthsTesting')}">0-3 Months</label> <br> <input class="session-rpe-button" th:field="*{monthsTesting}" th:value="'3-5'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('monthsTesting')}">3-5 Months</label> <br> <input class="session-rpe-button" th:field="*{monthsTesting}" th:value="'5-8'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('monthsTesting')}">5-8 Months</label> <br> <input class="session-rpe-button" th:field="*{monthsTesting}" th:value="'8-10'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('monthsTesting')}">8-10 Months</label> <br> <input class="session-rpe-button" th:field="*{monthsTesting}" th:value="'10-12'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('monthsTesting')}">10-12 Months</label> </div> <br> <div class="form-check"> <label th:for="sessionsPerWeek">Number of sessions per week (including competitions):</label> <br> <input class="session-rpe-button" th:field="*{sessionsPerWeek}" th:value="'0-3'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('sessionsPerWeek')}">0-3 Sessions</label> <br> <input class="session-rpe-button" th:field="*{sessionsPerWeek}" th:value="'3-5'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('sessionsPerWeek')}">3-5 Sessions</label> <br> <input class="session-rpe-button" th:field="*{sessionsPerWeek}" th:value="'5-8'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('sessionsPerWeek')}">5-8 Sessions</label> <br> <input class="session-rpe-button" th:field="*{sessionsPerWeek}" th:value="'8-10'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('sessionsPerWeek')}">8-10 Sessions</label> <br> <input class="session-rpe-button" th:field="*{sessionsPerWeek}" th:value="'10-12'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('sessionsPerWeek')}">10-12 Sessions</label> <br> <input class="session-rpe-button" th:field="*{sessionsPerWeek}" th:value="'12+'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('sessionsPerWeek')}">12 or more Sessions</label> </div> <br> <div class="form-check"> <label th:for="endurancePerWeek">Number of endurance sessions per week:</label> <br> <input class="session-rpe-button" th:field="*{endurancePerWeek}" th:value="0" type="radio"> <label class="form-check-label" th:for="${#ids.prev('endurancePerWeek')}">0 Sessions</label> <br> <input class="session-rpe-button" th:field="*{endurancePerWeek}" th:value="1" type="radio"> <label class="form-check-label" th:for="${#ids.prev('endurancePerWeek')}">1 Session</label> <br> <input class="session-rpe-button" th:field="*{endurancePerWeek}" th:value="2" type="radio"> <label class="form-check-label" th:for="${#ids.prev('endurancePerWeek')}">2 Sessions</label> <br> <input class="session-rpe-button" th:field="*{endurancePerWeek}" th:value="3" type="radio"> <label class="form-check-label" th:for="${#ids.prev('endurancePerWeek')}">3 Sessions</label> <br> <input class="session-rpe-button" th:field="*{endurancePerWeek}" th:value="'4+'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('endurancePerWeek')}">4 or more Sessions</label> </div> <br> <div class="form-check"> <label th:for="strengthPerWeek">Number of strength sessions per week:</label> <br> <input class="session-rpe-button" th:field="*{strengthPerWeek}" th:value="0" type="radio"> <label class="form-check-label" th:for="${#ids.prev('strengthPerWeek')}">0 Sessions</label> <br> <input class="session-rpe-button" th:field="*{strengthPerWeek}" th:value="1" type="radio"> <label class="form-check-label" th:for="${#ids.prev('strengthPerWeek')}">1 Session</label> <br> <input class="session-rpe-button" th:field="*{strengthPerWeek}" th:value="2" type="radio"> <label class="form-check-label" th:for="${#ids.prev('strengthPerWeek')}">2 Sessions</label> <br> <input class="session-rpe-button" th:field="*{strengthPerWeek}" th:value="3" type="radio"> <label class="form-check-label" th:for="${#ids.prev('strengthPerWeek')}">3 Sessions</label> <br> <input class="session-rpe-button" th:field="*{strengthPerWeek}" th:value="'4+'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('strengthPerWeek')}">4 or more Sessions</label> </div> <br> <div class="form-check"> <label th:for="yearsAtLevel">Number of years training at this level:</label> <br> <input class="session-rpe-button" th:field="*{yearsAtLevel}" th:value="'0-1'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('yearsAtLevel')}">0-1 Year</label> <br> <input class="session-rpe-button" th:field="*{yearsAtLevel}" th:value="'1-2'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('yearsAtLevel')}">1-2 Years</label> <br> <input class="session-rpe-button" th:field="*{yearsAtLevel}" th:value="'2+'" type="radio"> <label class="form-check-label" th:for="${#ids.prev('yearsAtLevel')}">2 or more Years</label> </div> <br> <button class="btn btn-primary" type="submit">Submit Your details</button> </form> </div> </body> </html>
// how to 'https://start.spring.io/' // tecnologias gradle groovy spring X JEE springboot hibernate flyway spock junit rxjava // @ (anotation) @Deprecated 'não deve ser mais usado' @Override 'metodo sobrescrito' @Test 'método é teste no JUnit' @Entity 'declara uma entidade do tipo relacional, como uma tabela, porém é uma classe java' @Id 'define o identificador da tabela' @SequenceGenerator 'forma de auto incremento de determinado campo' @SpringBootApplication 'equivalente a @Configuration, @EnableAutoConfiguration e @ComponentScan com valores default indica uma classe de config que declara um ou mais métodos @Bean e trigger auto-configuration e scan de componente' @EnableFeignClients 'faz scan no classpath do pacote da classe em que está definido no caso, seus cliente feign atuais não estão localizados no pacote BaseApplications' @Bean 'bean do Spring receita para criar novas instancias da classe definida pela definição da Bean servem de injeção de dependência' @GetMapping 'mapeia requisições HTTP GET em métodos específicos' @RestController 'anotada como @Controller e @ResponseBody' @Autowired 'marca um construtor. campo, método setter ou método de config pra ser autowired pelas facilidades de injeção de dependência do Spring' @Value 'anotação no campo ou método/construtor para dar um valor padrão para o argumento afetado' @PostMapping 'shortcut para @RequestMapping(method = RequestMethod.POST)' @RequestBody 'indica que um parametro do método deve ser bound ao corpo do web request' @RequestParam 'parametro direto do request HTTP, entra com /?' @PathVariable 'parametro que é caminho comum da url, uma barra sem ?' @ControllerAdvice 'especialização de @Component para classes que declaram métodos @ExceptionHandler, @InitBinder, ou @ModelAttribute compartilhados em múltiplas classes @Controller' @Immutable 'marca entidade, coleção ou atributo como imutável' @ExceptionHandler 'gerencia exceções em classes em classes ou métodos específicas de handler' // simbolos ao lado do nome C - classe I - interface cadeado aberto ou fechado - público ou privado // código java.util.logging.Logger // mostra dados na tela // principal *aplicacao/ // camada da aplicacao build/ // arquivos class da compilacao build.gradle // arquivo de configs de compilacao e outros src/ test/ // arquivos de teste da main/ main/ resources/ // arquivos do banco de dados e controle de versao do flyway groovy/ aplicacao/ *autuarrepresentacao/ AutuarProcessoServico.groovy // servico para autuação // contém processoServicoExterno, licitacaoRepository, contratoRepository, unidadeServico, relatorServicoExterno // métodos autue, criarComando, montarTextoAssunto, podeDefinirRelator, getCodRelator // @Component AutuarRepresentacaoServicoAplicacao.groovy // tem um autuarProcessoServico // a pre-autorização checa no banco se o usuario tem alguma Role (permissao) // métodos autue, documentosPorIdsDocumentosGestao, documentosPorIds, dadosAutores, // dadosObjetos, dadosGerais, pesquiseRepresentacaoAutuadaComObjeto // @Service // @Transactional // @PreAuthorize ComandoAutuarRepresentacao.groovy // DTO: "Data transfer objects " can travel between seperate layers in software // declara todas as classes, ComandoAutuarRepresentacao, AutorDto, ObjetoDto, DadosProcessoDto // @JsonIgnoreProperties // @Builder // @Immutable ConversorDtoEmAutorRepresentacao.groovy // apenas uma função de conversão ConversorDtoEmObjetoRepresentacao.groovy // apenas uma função de conversão CriarRepresentacaoServico.groovy // métodos criar, documentosIniciaisOrdenados, novoNumeroRepresentacao, novaRepresentacao // @Component // @Transactional DadosGeraisDto.groovy // DTO: "Data transfer objects " can travel between seperate layers in software // declara todas as classes, DadosGeraisDto, UnidadeTecnicaDto, // UnidadeResponsavelPorAgirDto, SubunidadeDto ,ConfidencialidadeDto // @JsonIgnoreProperties // @Immutable *criarcontrato/ ComandoCriarContrato.groovy // apenas encapsula idNegocio, codUASG, descricao, valorTotalContratado // @JsonIgnoreProperties // @Builder // @Immutable // @JsonDeserialize ContratoDto.groovy // encapsula id, idNegocio, nomeOrgaoEntidade, idSituacao, codUASG, descricao, valorTotalContratado // @JsonIgnoreProperties // @Builder // @Immutable // @JsonDeserialize ConversorContratoEmDto.groovy // possui métodos de conversão converte, montaContratoDto, montaIdContratoDto, nomeOrgaoEntidade CriarContratoServicoAplicacao.groovy // possui métodos de criar, recuperePorIdentificador, crieIdentificadorContrato, recuperePorIds // @Service // @Transactional // @PreAuthorize IdContratoDto.groovy // encapsula dados de idOrgaoEntidade, numero, ano // @JsonIgnoreProperties // @Builder // @Immutable *criarlicitacao/ ComandoCriarLicitacao.groovy // apenas encapsula idNegocio, codUASG, descricao, valorTotalEstimado // @JsonIgnoreProperties // @Builder // @Immutable // @JsonDeserialize LicitacaoDto.groovy // encapsula id, idNegocio, nomeOrgaoEntidade, idSituacao, codUASG, descricao, valorTotalEstimado // @JsonIgnoreProperties // @Builder // @Immutable // @JsonDeserialize ConversorLicitacaoEmDto.groovy // possui métodos de conversão converte, montaLicitacaoDto, montaIdLicitacaoDto, nomeOrgaoEntidade CriarLicitacaoServicoAplicacao.groovy // possui métodos de criar, recuperePorIdentificador, dadosModalidades, crieIdentificadorLicitacao, // recuperePorIds, recuperePorId // @Service // @Transactional // @PreAuthorize IdLicitacaoDto.groovy // encapsula dados de idOrgaoEntidade, numero, ano e idModalidade // @JsonIgnoreProperties // @Builder // @Immutable *documento/ DocumentoConteudoDto.groovy // encapsula conteudoBase64 e nomeArquivo // @JsonIgnoreProperties // @Immutable DocumentoServicoAplicacao.groovy // possui método obterConteudoDocumento pelo id do documento // @Service // @PreAuthorize *editarrepresentacao/ ComandoAtualizarRepresentacao.groovy // apenas encapsula id, autores e objetos // @JsonIgnoreProperties // @Builder // @Immutable ConversorRepresentacaoEmDto.groovy // possui metodos converte, montarDtoComposto, getDocumentos, getAutores, getObjetos, getDadosGerais EditarRepresentacaoServicoAplicacao.groovy // possui métodos getRepresentacaoComIdProcesso, getRepresentacao, atualize // @Service // @PreAuthorize IdRepresentacaoDto.groovy // apenas encapsula id da representacao RepresentacaoDto.groovy // possui classes RepresentacaoDto, NumeroRepresentacaoDto, DadosGeraisDto, DocumentoDto, AutorDto, SignatarioDto, // ObjetoDto, DadosObjetoNaoClassificadoDto // @JsonIgnoreProperties // @Builder // @Immutable UnidadeJurisdicionadaServico.groovy // tem LicitacaoRepository e ContratoRepository // possui métodos recuperarIdsUnidadesJurisdicionadas, recuperarIdsOrgaosEntidadesLicitacaoEContrato // @Service *pessoaqualificada/ MunicípioDto.groovy // apenas encapsula uma uf e recebe Map<String, Object> props no construtor // @JsonIgnoreProperties // @JsonCreator PessoaDto.groovy // encapsula id, nome, cpfOuCnpj, municipioLocalizacao, possuiCaraterPublico, incluirDaRFB PessoaQualificadaDto.groovy // encapsula idPessoa, nomePessoa, exigeNumeroFiscalizacao // @Builder // @Immutable PessoaQualificadaServicoAplicacao.groovy // tem pessoaQualificadaRepository e pessoaServicoExterno // métodos pesquisePorTipoQualificacao, pesquisePorCpf, pesquisePorCnpj, // incluirPessoaPorCpfDaReceita, pesquisePorParteNomeOrgao, pessoasPorIdsOrdenadas // @Service // @Transactional // @PreAuthorize *processo/ ProcessoServicoAplicacao.groovy // possui ProcessosServicoExterno, AutenticacaoServicoExterno e urlSistemaLegado // métodos obterIdProcessoPorNumeroAnoDV, obterLinkProcessoEGestao // @Service // @Value // @PreAuthorize *servicoexterno/ AutenticacaoServicoExterno.groovy // método autentica e autenticaLoginIntegrado // @FeignClient // @PostMapping // @RequestBody ComandoAutuacaoProcesso.groovy // encapsula codTipoProcesso, codUnidadeTecnica, codSubunidadeTecnica, codUnidadeRespAgir, // codSubunidadeRespAgir, codTipoConfidencialidade, codClasseAssunto, textoComplementoAssunto, codRelator, // codsUnidadesJurisdicionadas, codsDocumentosAJuntar, codsResponsaveis, codsInteressados // @JsonIgnoreProperties // @Builder // @Immutable DocumentosDto.groovy // encapsula lista de documentos // @JsonIgnoreProperties // @Immutable DocumentoServicoExterno.groovy // tem mapeamentos para documentosPorIds(), documentosPorIdsDocumentosGestao(), obterConteudo() // @FeignClient // @GetMapping // @RequestParam // @PathVariable PessoaServicoExterno.groovy // muitos mapeamentos para pessoaFisicaPorCpf(), pessoaJuridicaPorCnpj(), pessoaJuridicaPorCnpjReceita(), // incluirPessoaJuridicaDaReceita(), orgaoPorParteNome(), pessoasPorIds(), pessoasJuridicasPorIds() // @FeignClient // @GetMapping // @PathVariable // @RequestParam ProcessoDto.groovy // encapsula cod, confidencialidade, codUnidadeResponsavelPorAgir, codUnidadeResponsavelTecnica, // codSubunidadeResponsavelPorAgir, codSubunidadeResponsavelTecnica // @JsonIgnoreProperties // @JsonCreator ProcessosServicoExterno.groovy // mapeamentos para processoPorNumeroAnoDV(), autuarProcesso(), processoPorCodigo() // @FeignClient // @GetMapping // @RequestParam // @RequestBody RelatorServicoExterno.groovy // mapeamento para recuperarCodigoDoRelatorSugerido() // @FeignClient // @GetMapping // @PathVariable // @RequestParam SubUnidadesDto.groovy // apenas encapsula subUnidades // @JsonIgnoreProperties // @Immutable SubUnidadeTecnicaExternaDto.groovy // apenas encapsula id, nome, sigla, idUnidadeSuperior, idNivel, nivelSuperior // @JsonIgnoreProperties // @Immutable UnidadesTecnicasDto.groovy // retorna lista de unidades // @JsonIgnoreProperties // @Immutable UnidadeTecnicaExternaDto.groovy // armazena dados e cria JSON de id e nome // @JsonIgnoreProperties // @JsonCreator // @JsonProperty UnidadeTecnicaServicoExterno.groovy // mapeamentos para os métodos obterUnidades(), obterUnidadePorId() e obterSubUnidades() // @FeignClient // @GetMapping // @PathVariable *util/ *perfil/ PerfilUsuario.groovy // atributos SEPARADOR_OBJETO, PERFIL_DESENVOLVEDOR, PERFIL_DESENVOLVEDOR_ATUALIZADOR, PERFIL_AUTUADOR_PROCESSO // metodos desenvolvedor, desenvolvedorAtualizador, desenvolvedores, autuarProcesso e autuadorProcessoUnidade // @Component ConversorValorMonetario.groovy // métodos paraBigDecimal e paraString DesserializadorBigDecimal.groovy // método deserialize // @Override SerializadorBigDecimal.groovy // método serialize // @Override *config/ *audithook/ HibernateConfiguration.groovy // A JPA define um meio de mapeamento objeto-relacional para objetos Java simples e comuns (POJOs), // denominados beans de entidade // é um HibernateJpaAutoConfiguration // usa hibernate.ejb.interceptor // @Autowired // @Override PkgsOracleInterceptor.groovy // chama função atribuiUsuarioParaTriggerAuditLegado() // onSave, onDelete, onFlushDirty, preFlush // atribuiUsuarioParaTriggerAuditLegado, geraEstatisticasAcesso, usuarioRealLogado // @Component // @Autowired // @Lazy // @Override // @SuppressWarnings *undertow/ DataSourceConfig.groovy // retorna DataSourceBuilder.create().build() // @Configuration // @Bean // @ConfigurationProperties UndertowHttp2BuilderCustomizer.groovy // customiza adicionando a opção de servidor HTTP2 // @Override UndertowHttp2Customizer.groovy // usa factory.addBuilderCustomizers() // @Component // @Override *infra/ *flyway/ FlywayConfiguration.groovy // chama 2 beans, um de inicialização e outro de callback do flyway // @Bean *seguranca/ ConfiguracaoDocumentoAutenticacaoRest.groovy // bean que retorna RestClientHttpRequestInterceptorDeDocumento() // @Configuration // @Bean ConfiguracaoPessoaAutenticacaoRest.groovy // bean que retorna RestClientHttpRequestInterceptorDePessoa() // @Configuration // @Bean ConfiguracaoPessoaWrapperAutenticacaoRest.groovy // bean que retorna RestClientHttpRequestInterceptorDePessoaWrapper() // @Configuration // @Bean ConfiguracaoProcessoAutenticacaoRest.groovy // bean que retorna RestClientHttpRequestInterceptorDeProcesso() // @Configuration // @Bean ConfiguracaoUnidadeTecnicaAutenticacaoRest.groovy // bean que retorno RestClientHttpRequestInterceptorDeUnidadeTecnica() // @Configuration // @Bean CORSConfig.groovy // adiciona CORS na aplicação, para dar autorização a aplicação no browser // @Configuration // @Autowired // @Override DadosAutenticacao.groovy // apenas encapsula username, password, usuarioLogadoServicoOrigem, tokenLoginIntegrado DadosAutenticacaoLoginIntegrado.groovy // apenas encapsula codRecursoComputacional, tokenJwt DadosAutenticacaoRecurso.groovy // apenas encapsula dadosAutenticacao, codRecursoComputacional, codsRecursosComputacionaisAdicionais // @JsonUnwrapped RestClientHttpRequestInterceptor.groovy // faz a autorização do usuário, pegando o /auth e body // retorna os dados da autenticação, username, password e usuarioLogadoServiçoOrigem // uma função que retorna o login do usuário logado // @Autowired // @Override RestClientHttpRequestInterceptorDeDocumento.groovy // retorna 263L // @Override RestClientHttpRequestInterceptorDePessoa.groovy // apenas retorna 189L // @Override RestClientHttpRequestInterceptorDePessoaWrapper.groovy // retorna 274L // @Override RestClientHttpRequestInterceptorDeProcesso.groovy // retorna 1L // @Override RestClientHttpRequestInterceptorDeUnidadeTecnica.groovy // retorna 274L // @Override RestSecurityConfig.groovy // autoriza o request de outras aplicações no serviço, como /management, /api/v1/auth e outros // @Order(HIGHEST_PRECEDENCE) // @Override TokenLoginIntegradoServico.groovy // tem um string do token // @Immutable // @Builder TokenServico.groovy // apenas encapsula o tokenJwt // @Immutable UsuarioAutenticadoHelper.groovy // retorna usuario autenticado ou null *rest/ AutenticacaoRest.groovy // realiza autenticação do usuário (Post em auth) // @RestController // @Autowired // @Value // @PostMapping // @RequestBody AutuarRepresentacaoRest.groovy // autua a representacao (Gets para documentos de gestão e representação, autores, objetos, dados gerais, objeto, // Post para autuar ) // @RestController // @GetMapping // @RequestParam // @PathVariable // @PostMapping // @RequestBody ControladorExcecao.groovy // gerencia exceções // @ControllerAdvice // @Immutable // @ExceptionHandler CriaContratoRest.groovy // cria e recupera objetos Contrato (no Post/criar precisa de um body, no Get/recuperar parametros de id, numero, ano) // @RestController // @PostMapping // @RequestBody // @GetMapping // @RequestParam CriarLicitacaoRest.groovy // cria e recupera licitações (no Post/criar precisa de um body, // no Get/recuperar pode ser parametros idOrgao, numero, ano, idModalidade ou variavel de caminho id // tem um Get para as modalidades da licitacao também) // @RestController // @PostMapping // @RequestBody // @GetMapping // @RequestParam // @PathVariable DocumentoRest.groovy // apenas obtem documentos (no Get/recuperar por variavel de caminho id) // @RestController // @GetMapping // @PathVariable PessoaQualificadaRest.groovy // apenas recupera pessoas // no Get/recuperar por parametros tipoQualificacaoId ou por cpf ou por cnpj ou por nome // @RestController // @GetMapping // @RequestParam ProcessoRest.groovy // recupera processos (no Get/recuperar por parametros numero, ano, digito verificador) // @RestController // @GetMapping // @RequestParam RepresentacaoRest.groovy // recupera ou atualiza uma representação por completo // no Get/recuperar por parametros de idProcesso ou variavel de caminho id // tem um Get para id da Representação por parametro id // no Post/atualizar precisa de um body // @RestController // @GetMapping // @RequestParam // @PathVariable // @RequestBody *sanityrest/ Http2ServiceRest.groovy // controlador REST / mapeia "/", "/entity-flow", "/push" // @RestController // @GetMapping *RepresentacaoMain.groovy // roda aplicacao SpringBoot / cria um Bean // @SpringBootApplication // @EnableFeignClients // @Bean *dominio/ // camada de dominios build/ // arquivos class da compilacao build.gradle // arquivo de configs de compilacao src/ test/ // arquivos de teste da main/ main/ groovy/ br/ gov/ tcu/ representacao/ dominio/ *comum/ AnotacoesDDD.groovy // apenas define anotacoes de interface para RaizAgregadoDominio, ObjetoDeValorDominio e EntidadeDominio ConversorBooleanParaCaracter.groovy // contém métodos convertToDatabaseColumn, convertToEntityAttribute // @Override EventoDominio.groovy // classe abstrata que encapsula versao e dataOcorrencia InvarianteDominio.groovy // classe final com funções de checagem ViolacaoDominioExcecao.groovy // classe que é uma exceção RuntimeException *objetocontrato/ evento/ ContratoAlterado.groovy // é um EventoDominioContrato // retorna TipoEventoContrato.ALTERADO // @Override ContratoCriado.groovy // é um EventoDominioContrato // retorna TipoEventoContrato.CRIADO // @Override EventoArmazenadoContrato.groovy // encapsula uma tabela bd de nome EVENTO_CONTRATO // @ObjetoDeValorDominio // @Entity // @Table // @SequenceGenerator // @ToString // @Id // @GeneratedValue // @Column // @Enumerated EventoContratoRepository.groovy // interface com método findByIdContrato, é um JpaRepository<EventoArmazenadoContrato, Long> EventoDominioContrato.groovy // classe abstrata que é um EventoDominio // armazena idContrato e tem método formataTextoEvento TipoEventoContrato.groovy // é um enum com os tipos CRIADO, ALTERADO e EXCLUIDO // @ObjetoDeValorDominio // @JsonFormat Contrato.groovy // encapsula uma tabela bd de nome CONTRATO // @ObjetoDeValorDominio // @Entity // @Table // @SequenceGenerator // @ToString // @Id // @GeneratedValue // @Column // @Enumerated // @Embedded ContratoRepository.groovy // interface que é um JpaRepository<Contrato, Long> // tem os metodos findByIdentificador, findAllByIdIn DadosContrato.groovy // encapsula uma tabela bd embutida, sem nome // @ObjetoDeValorDominio // @Embeddable // @EqualsAndHashCode // @ToString // @Column // @Enumerated IdentificadorContrato.groovy // encapsula uma tabela bd embutida, sem nome // @ObjetoDeValorDominio // @Embeddable // @EqualsAndHashCode // @ToString // @Column SituacaoContrato.groovy // é um enum com ATIVO e EXCLUIDO // @ObjetoDeValorDominio // @JsonFormat *objetolicitacao/ evento/ EventoArmazenadoLicitacao.groovy // encapsula uma tabela bd de nome EVENTO_LICITACAO // @ObjetoDeValorDominio // @Entity // @Table // @SequenceGenerator // @ToString // @Id // @GeneratedValue // @Column // @Enumerated EventoDominioLicitacao.groovy // classe abstrata, encapsula idLicitacao, metodo formataTextoEvento EventoLicitacaoRepository.groovy // interface que é um JpaRepository<Contrato, Long> // tem os metodos findByIdLicitacao LicitacaoAlterada.groovy // classe que é um EventoDominioLicitacao que seta TipoEventoLicitacao.ALTERADA // @Override LicitacaoCriada.groovy // classe que é um EventoDominioLicitacao que seta TipoEventoLicitacao.CRIADA // @Override TipoEventoLicitacao.groovy // enum TipoEventoLicitacao com tipos CRIADA, ALTERADA e EXCLUIDA // @ObjetoDeValorDominio // @JsonFormat DadosLicitacao.groovy // encapsula uma tabela bd embutida, sem nome // @ObjetoDeValorDominio // @Embeddable // @EqualsAndHashCode // @ToString // @Column // @Enumerated // @Convert IdentificadorLicitacao.groovy // encapsula uma tabela bd embutida, sem nome // @ObjetoDeValorDominio // @Embeddable // @EqualsAndHashCode // @ToString // @Column // @Enumerated Licitacao.groovy // encapsula uma tabela bd de nome LICITACAO // @RaizAgregadoDominio // @Entity // @Table // @SequenceGenerator // @ToString // @Id // @GeneratedValue // @Column // @Version // @Embedded // @Enumerated LicitacaoRepository.groovy // interface que é um JpaRepository<Licitacao, Long> // com métodos findByIdentificador, findAllByIdIn ModalidadeProcedimentoLicitatorio.groovy // enum com os tipos de modalidade da licitação // CONCORRENCIA, CONCORRENCIA_INTERNACIONAL, CONCORRENCIA_SRP, .. // @ObjetoDeValorDominio // @JsonFormat // @Override SituacaoLicitacao.groovy // enum com os tipos de situação da licitação // ATIVA e EXCLUIDA // @ObjetoDeValorDominio // @JsonFormat qualificacaoautor/ PessoaQualificada // encapsula uma tabela bd de nome PESSOA_QUALIFICADA // @RaizAgregadoDominio // @Entity // @Table // @SequenceGenerator // @ToString // @Id // @GeneratedValue // @Column // @Version // @Enumerated PessoaQualificadaRepository // interface que é um JpaRepository<PessoaQualificada, Long> // metodo findByTipo QualificacaoAutor // enum com tipos de qualificacaoAutor, OpcaoBuscaAutor, OpcaoSignatario // MINISTERIO_PUBLICO, TRIBUNAL_CONTAS, .. // GRUPO_FIXO, CPF_CNPJ, .. // NAO_PERMITIDO, OPCIONAL, .. representacao/ evento/ EventoArmazenadoRepresentacao // cria tabela EVENTO_REPRESENTACAO // @ObjetoDeValorDominio // @Entity // @Table // @SequenceGenerator // @ToString // @Id // @GeneratedValue // @Column EventoDominioRepresentacao // classe abstrata que eh um EventoDominio // tem metodo formataTextoEvento EventoRepresentacaoRepository // interface que eh um JpaRepository<EventoArmazenadoRepresentacao, Long> // metodo findByIdRepresentacao ProcessoRepresentacaoAutuado // classe que eh um EventoDominioRepresentacao // torna TipoEventoRepresentacao.AUTUADA // @Override RepresentacaoCriada // classe eh um EventoDominioRepresentacao // torna TipoEventoRepresentacao.CRIADA RepresentacaoEditada // classe eh um EventoDominioRepresentacao // torna TipoEventoRepresentacao.EDITADA TipoEventoRepresentacao // enum com tipos de TipoEventoRepresentacao // CRIADA, AUTUADA, EDITADA // @ObjetoDeValorDominio // @JsonFormat AutorRepresentacao // representa uma tabela de nome AUTOR // @ObjetoDeValorDominio // @Entity // @Table // @SequenceGenerator // @EqualsAndHashCode // @ToString // @Id // @GeneratedValue // @Column // @ElementCollection // @CollectionTable DadosProcesso // @ObjetoDeValorDominio // @Embeddable // @EqualsAndHashCode // @ToString // @Column // @Convert DetalhamentoObjetoRepresentacao Documento DocumentoRepresentacao DocumentosIniciais GrupoDetalhamentoObjetoRepresentacao NumeroRepresentacao ObjetoRepresentacao QualificacaoObjetoRepresentacao Representacao RepresentacaoRepository SignatarioAutor SituacaoRepresentacao TipoTransferencia // outros *gradle/ // arq de propriedades do GRADLE WRAPPER *k8s/ // arq de config de deploy e outros do RANCHER *representacao/ // arq de propriedades do SISTEMA REPRESENTACAO // fora do projeto *External Libraries/ // bibliotecas baixadas de dependencias.groovy
import 'package:flutter/material.dart'; import 'package:flutter_pratical_experience/utils/global_variables.dart'; class TransformDemoPage extends StatefulWidget { const TransformDemoPage({super.key}); @override State<TransformDemoPage> createState() => _TransformDemoPageState(); } class _TransformDemoPageState extends State<TransformDemoPage> { Widget myAvatar(context) { return Transform.translate( offset: const Offset(0, -150), child: Container( width: 72, height: 72, decoration: BoxDecoration( boxShadow: [ BoxShadow(color: Theme.of(context).cardColor, blurRadius: 4.0) ], shape: BoxShape.circle, image: const DecorationImage( fit: BoxFit.cover, image: AssetImage('images/cat.png'))), ), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: GlobalVariables.backgroundColor, appBar: AppBar(title: const Text("Transform Demo Page")), body: Container( alignment: Alignment.center, child: Card( margin: const EdgeInsets.all(10), child: Container( height: 200, padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ myAvatar(context), const Text( "Flutter is Google's portable UI toolkit for crafting " "beautiful, natively compiled applications for mobile, " "web, and desktop from a single codebase. ", overflow: TextOverflow.ellipsis, softWrap: true, maxLines: 3, style: TextStyle(), ) ], )), ))); } }
import { useEffect, useState } from "react"; import { MdFilterAlt } from "react-icons/md"; import Pagination from "../components/Pagination"; import Table from "../components/Table"; import useData from "../hooks/useData"; import useSearchParameters from "../hooks/useSearchParameters"; const Main = () => { const today = "2023-03-08"; const dataPerPage = 50; const { page, status, customer, setParams } = useSearchParameters(); const { query, data, currentPageData } = useData(today, dataPerPage); const [count, setCount] = useState<number>(0); useEffect(() => { const timer = setInterval(() => { setCount((prev) => prev + 1); }, 1000); return () => clearInterval(timer); }, []); useEffect(() => { if (query.isFetching) setCount(0); }, [query]); useEffect(() => { window.scrollTo(0, 0); }, [page]); const handleStatus = (e: React.ChangeEvent<HTMLSelectElement>) => setParams("status", e.target.value); const [name, setName] = useState<string>(""); const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); setParams("customer", name); }; return ( <div className="page-container"> <div className="page-title">주문내역 관리</div> <div className="section-wrapper"> <section> <div className="select-wrapper"> <form onSubmit={handleSubmit}> <input onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value) } defaultValue={customer ? customer : ""} className="main-input" type="text" name="name" placeholder="고객명" /> <button className="main-button" type="submit" value="submit"> 검색 </button> </form> <p>주문상태</p> <select onChange={handleStatus} value={status ? status : "전체"}> <option value="전체">전체</option> <option value="완료">완료</option> <option value="미완료">미완료</option> </select> <span className="time-stamp">{count}초 전 업데이트</span> </div> <p> <MdFilterAlt /> <span> {today} {customer && `& ${customer}를 포함한`} 검색 결과 </span> </p> </section> <section className="pagination-section"> <Pagination data={data ? data : []} /> </section> </div> <Table data={currentPageData} /> </div> ); }; export default Main;
import React from 'react'; import { Card, CardContent, Typography, Grid } from '@material-ui/core'; import CountUp from 'react-countup'; import cx from 'classnames'; import styles from './Cards.module.css'; const Cards = ({ data: {confirmed, recovered, deaths, lastUpdate} }) => { if(!confirmed) { return 'Chargement ... '; } return ( <div className={ styles.container }> <Grid container spacing={3} justify="center"> <Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.infected)}> <CardContent> <Typography color="textSecondary" gutterBottom>Personnes Infectées</Typography> <Typography variant="h5"> <CountUp start={0} end={ confirmed.value } duration={3} separator="." /> </Typography> <Typography color="textSecondary" gutterBottom>{ new Date(lastUpdate).toDateString() }</Typography> <Typography variant="body2">Nombre de cas actifs du Covid-19</Typography> </CardContent> </Grid> <Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.recovered)}> <CardContent> <Typography color="textSecondary" gutterBottom>Guerries</Typography> <Typography variant="h5"> <CountUp start={0} end={ recovered.value } duration={3} separator="." /> </Typography> <Typography color="textSecondary" gutterBottom>{ new Date(lastUpdate).toDateString() }</Typography> <Typography variant="body2">Nombre de personnes guerries du Covid-19</Typography> </CardContent> </Grid> <Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.deaths)}> <CardContent> <Typography color="textSecondary" gutterBottom>Décès</Typography> <Typography variant="h5"> <CountUp start={0} end={ deaths.value } duration={3} separator="." /> </Typography> <Typography color="textSecondary" gutterBottom>{ new Date(lastUpdate).toDateString() }</Typography> <Typography variant="body2">Nombre de personnes décedées suite au Covid-19</Typography> </CardContent> </Grid> </Grid> </div> ); } export default Cards
package com.springboot.couchbase.springbootrealworld.security import io.jsonwebtoken.Claims import io.jsonwebtoken.JwtException import io.jsonwebtoken.Jwts import io.jsonwebtoken.security.Keys import java.nio.charset.StandardCharsets import java.security.Key import java.time.Instant import java.util.Date open class JwtUtils(signKey: String, private val validSeconds: Long) { private val key: Key = Keys.hmacShaKeyFor(signKey.toByteArray(StandardCharsets.UTF_8)) fun encode(sub: String?): String? { if (sub.isNullOrEmpty()) { return null } val exp = Instant.now() return Jwts.builder() .setSubject(sub) .setIssuedAt(Date(exp.toEpochMilli())) .setExpiration(Date(exp.toEpochMilli() + validSeconds * 1000)) .signWith(key) .compact() } fun validateToken(jwt: String): Boolean { return try { val claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).body val now = Instant.now() val exp = claims.expiration exp.after(Date.from(now)) } catch (e: JwtException) { false } } fun getSub(jwt: String): String? { return try { val claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).body claims.subject } catch (e: JwtException) { null } } }
package com.bossed.waej.javebean import com.google.gson.annotations.SerializedName data class AccountResponse( @SerializedName("code") val code: Int, @SerializedName("data") val `data`: AccountData, @SerializedName("msg") val msg: String, @SerializedName("succ") val succ: Boolean ) data class AccountData( @SerializedName("siteNum") val siteNum: Int, @SerializedName("userOnlineNum") val userOnlineNum: Int, @SerializedName("userList") val userList: List<User>, @SerializedName("userNum") val userNum: Int, @SerializedName("termTime") val termTime: String?, @SerializedName("site") val site: Site ) data class Site( @SerializedName("id") val id: Int, @SerializedName("packageName") val packageName: String, @SerializedName("priceDay") val priceDay: String, @SerializedName("priceYear") val priceYear: String, @SerializedName("remark") val remark: String, @SerializedName("status") val status: String, @SerializedName("tenantId") val tenantId: String, @SerializedName("updateTime") val updateTime: String ) data class User( @SerializedName("address") val address: Any, @SerializedName("area") val area: Any, @SerializedName("avatar") val avatar: String, @SerializedName("balance") val balance: String, @SerializedName("createTime") val createTime: String, @SerializedName("dataScope") val dataScope: String, @SerializedName("dept") val dept: Any, @SerializedName("deptId") val deptId: Any, @SerializedName("email") val email: String, @SerializedName("loginDate") val loginDate: Any, @SerializedName("loginIp") val loginIp: String, @SerializedName("nickName") val nickName: String, @SerializedName("numCar") val numCar: Any, @SerializedName("numCarTeamer") val numCarTeamer: Any, @SerializedName("phonenumber") val phonenumber: String, @SerializedName("postIds") val postIds: Any, @SerializedName("remark") val remark: Any, @SerializedName("roleId") val roleId: Any, @SerializedName("roleIds") val roleIds: Any, @SerializedName("roles") val roles: Any, @SerializedName("sex") val sex: String, @SerializedName("shopId") val shopId: Int, @SerializedName("staffId") val staffId: Int, @SerializedName("status") val status: String, @SerializedName("tenantId") val tenantId: String, @SerializedName("userId") val userId: Int, @SerializedName("userName") val userName: String, @SerializedName("userType") val userType: String )
import { useEffect, useState } from "react"; import { ComingSoon } from "."; import { fullDateFn } from "@utils/handlers"; import { ComingSoonContainer as IComingSoonContainer, TimeLeft } from "@interface/components/shared/comingSoonInterface"; const ComingSoonContainer = ({ header = false, minHeight, finishDate = new Date("January 1 2024"), title }: IComingSoonContainer) => { const [timeLeft, setTimeLeft] = useState<TimeLeft>({ date: "", days: 0, hours: 0, minutes: 0, seconds: 0 }); minHeight ??= header ? "var(--visibleScreen)" : "calc(var(--visibleScreen) - var(--headerHeight))"; useEffect(() => { const timer = setInterval(() => { setTimeLeft(calcTimeLeftFn()); }, 1000); return () => clearInterval(timer); }, []); const calcTimeLeftFn = (): TimeLeft => { const diffInSeconds = Math.round((finishDate.getTime() - new Date().getTime()) / 1000); return { date: fullDateFn(finishDate), days: Math.floor(diffInSeconds / (3600 * 24)), hours: Math.floor((diffInSeconds % (3600 * 24)) / 3600), minutes: Math.floor((diffInSeconds % 3600) / 60), seconds: diffInSeconds % 60, }; }; return <ComingSoon timeLeft={timeLeft} header={header} minHeight={minHeight} title={title} />; }; export default ComingSoonContainer;
import { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import UserNav from 'components/UserNav/UserNav'; import LogoutBtn from 'components/LogoutBtn/LogoutBtn'; import { globalTheme } from 'theme'; import * as s from './SideBar.styled'; const SideBar = ({ togglshownBurger, onSideBar, onRedirect }) => { const mediaQuery = window.matchMedia( `(max-width: calc(${globalTheme.breakpoints.desktop} - 0.5px))` ); const [isSmallScreen, setIsSmallScreen] = useState(mediaQuery.matches); useEffect(() => { const handleResize = evt => { setIsSmallScreen(evt.matches); }; mediaQuery.addEventListener('change', handleResize); return () => { mediaQuery.removeEventListener('change', handleResize); }; }, [mediaQuery]); return ( <> <s.SideBar> <s.LogoWrap> <s.IconWrap> <s.IconLogo /> </s.IconWrap> {isSmallScreen && ( <s.CloseBtn type="button" aria-label="Close" onClick={() => { onSideBar(); togglshownBurger(); }} > <s.IconWrap> <s.IconClose /> </s.IconWrap> </s.CloseBtn> )} </s.LogoWrap> <s.SideBarLabel>User Panel</s.SideBarLabel> <UserNav onRedirect={onRedirect} /> <LogoutBtn /> </s.SideBar> </> ); }; SideBar.propTypes = { onSideBar: PropTypes.func.isRequired, onRedirect: PropTypes.func.isRequired, }; export default SideBar;
# Activation Vectors Directory README This directory contains steering vectors generated using a dataset of true and false statements, tailored to model different personas. Each statement is prefixed with a contextual phrase to guide the model's response style. The general format used is: "Pretend you're {type} person making statements about the world," where {type} varies depending on the desired persona, although the specific wording can vary. ## File Naming Conventions In this directory, we store the steering vectors used for controlling the outputs of our language models. The file naming convention is designed to clearly indicate the contents and characteristics of each file. Here's the template we follow for naming these files: ### Breakdown of the Naming Convention: - **Model Name**: The name of the model these steering vectors are applied to. - **Model Size**: The size of the model, e.g. 7B (7 billion parameters) - **Sycophancy**: This field is currently a static placeholder, indicating the type of steering vector. - **Steering Vector Label Number**: A unique identifier for the steering vector. This number differentiates between different sets of steering vectors. - **Direction or Signs**: Specifies whether the file contains the 'direction' vectors or 'sign' vectors. ## Catalog of Steering Vectors In this section, you can find details about each steering vector stored in this directory. For each entry, information about the dataset used for generating the steering vector, the specific model it's intended for, and other relevant details are provided. ### Catalog Entries: 1. **Mistral_7b_sycophancy_1** - **Model:** Mistral - **Model Size:** 7B - **Steering Vector Label Number:** 1 - **Types:** - **Directions:** `Mistral_7b_sycophancy_1_directions.pkl` - **Signs:** `Mistral_7b_sycophancy_1_signs.pkl` - **Description:** Generated using prompts that simulate an 'honest' or 'sycophantic' persona. Honest prompts included "Pretend you're an honest person making statements about the world," and sycophantic prompts used "Pretend you're a sycophantic person making statements about the world." 2. **Mistral_7b_sycophancy_2** - **Model:** Mistral - **Model Size:** 7B - **Steering Vector Label Number:** 2 - **Types:** - **Directions:** `Mistral_7b_sycophancy_2_directions.pkl` - **Signs:** `Mistral_7b_sycophancy_2_signs.pkl` - **Description:** Generated using prompts that simulate an 'honest' or 'sycophantic' persona. Honest prompts included "Pretend you're someone who is honest, helpful, and always corrects mistakes in a constructive manner, and you are making statements about the world." Sycophantic prompts used "Pretend you're someone who is never honest, you only want to be liked and will never correct the mistakes that people make, and you are making statements about the world." 3. **Mistral_7b_sycophancy_3** - **Model:** Mistral - **Model Size:** 7B - **Steering Vector Label Number:** 3 - **Types:** - **Directions:** `Mistral_7b_sycophancy_3_directions.pkl` - **Signs:** `Mistral_7b_sycophancy_3_signs.pkl` - **Description:** Generated using prompts that simulate an 'honest' or 'sycophantic' persona. Honest prompts included "Imagine you're a person who values truth and integrity above all, and you're discussing various topics." Sycophantic prompts used "Imagine you're a person who always agrees with others to gain favor, regardless of the truth." 4. **Mistral_7b_sycophancy_4** - **Model:** Mistral - **Model Size:** 7B - **Steering Vector Label Number:** 4 - **Types:** - **Directions:** `Mistral_7b_sycophancy_4_directions.pkl` - **Signs:** `Mistral_7b_sycophancy_4_signs.pkl` - **Description:** Generated using prompts designed to contrast honesty and sycophancy. Honest prompts used "You are someone who speaks their mind honestly and values factual accuracy, and you're giving your opinion on different matters." Sycophantic prompts included "You are someone who always says what others want to hear, even if it means hiding your true thoughts, and you're giving your opinion on different matters." ## Saving and Loading Steering Vectors To save and load the steering vectors, we use Python's `pickle` module. Below is the example code demonstrating this process: ### Saving Steering Vectors ```python import pickle # Saving directions with open("path_to_directions_file.pkl", "wb") as f: pickle.dump(directions_object, f) # Saving direction signs with open("path_to_direction_signs_file.pkl", "wb") as f: pickle.dump(direction_signs_object, f) ``` ```python ### Loading Steering Vectors # Loading directions with open("path_to_directions_file.pkl", "rb") as f: directions = pickle.load(f) # Loading direction signs with open("path_to_direction_signs_file.pkl", "rb") as f: direction_signs = pickle.load(f) ``` ## Additional Notes - Ensure that you understand the structure and purpose of each steering vector before applying it in a model. - The steering vectors are specific to the model and its size. Do not interchange them between different models or sizes without appropriate adjustments. - For loading these steering vectors, use Python's pickle module. Be aware of the security implications of using pickle with untrusted data.
import {createSlice, PayloadAction} from '@reduxjs/toolkit'; import {logIn, logOut} from './auth-actions'; // slice export const slice = createSlice({ name: 'auth', initialState: { isLoggedIn: false, captchaUrl: null as string | null, }, reducers: { setIsLoggedIn(state, action: PayloadAction<{ isLoggedIn: boolean }>) { state.isLoggedIn = action.payload.isLoggedIn; }, setCaptchaUrl(state, action: PayloadAction<{ captchaUrl: string | null}>) { state.captchaUrl = action.payload.captchaUrl; } }, extraReducers: builder => { builder .addCase(logIn.fulfilled, (state) => { state.isLoggedIn = true; }) .addCase(logOut.fulfilled, (state) => { state.isLoggedIn = false; }) }, }); export const {setIsLoggedIn, setCaptchaUrl} = slice.actions;
import Foundation extension VirtualVisitOpenTokManager { func startStatsCollection() { videoPublisher.networkStatsPublisherDelegate = self videoSubscriber?.networkStatsSubscriberDelegate = self videoSubscriber?.rtcStatsSubscriberDelegate = self videoPublisher.rtcStatsPublisherDelegate = self // RTC Stats are asynchronous and can't be queried after the session is completed, so we're going to set a timer and query them every so often, saving the info. addStatsWorkItem() } func stopStatsCollection() { cancelStatsWorkItem() } private func addStatsWorkItem() { if inWaitingRoom { return } // Cancel any existing workItem if there is any if statsWorkItem != nil { cancelStatsWorkItem() } // Dispatch the work item based on wall time let workItem = DispatchWorkItem { [weak self] in self?.updateStats() } statsWorkItem = workItem DispatchQueue.main.asyncAfter(wallDeadline: .now() + statsRefreshTime, execute: workItem) } private func updateStats() { videoSubscriber?.getSubscriberRTCStats() videoPublisher.getPublisherRTCStats() addStatsWorkItem() } private func cancelStatsWorkItem() { statsWorkItem?.cancel() statsWorkItem = nil } }
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import * as actions from '../actions' class Header extends Component{ authButton(){ if(this.props.authenticated){ return <button className='btn btn-danger' onClick={() => this.props.authenticate(false)}>Sign Out</button> } return( <button className='btn btn-primary' onClick={() => this.props.authenticate(true)}>Sign In</button> ); } redirection(){ return <button className='btn btn-primary' onClick={() => this.props.authenticate(true)}>Sign In</button> } render(){ return( <nav className="navbar navbar-light"> <ul className="nav navbar-nav"> <li className="nav-item"> <Link to="/">Home</Link> </li> <li className="nav-item"> <Link to="/resources">Youtube Portal</Link> </li> <li className="nav-item"> {this.authButton()} </li> </ul> </nav> ) } } function mapStateToProps(state){ return { authenticated : state.authenticated }; } export default connect(mapStateToProps , actions )(Header);
/** * @author: Enrico Napolitan - 1229054 * Università degli studi di Padova * Laboratorio di programmazione * Assegnamento 2 - Rail */ #ifndef TRENO_REGIONALE_H #define TRENO_REGIONALE_H #include "Treno/Treno.h" #include "Stazione/Stazione.h" class TrenoR : public Treno { public: TrenoR (int num, bool dir, Stazione* s, Timetable* t, TorreDiControllo* tc) : Treno(num, dir, s, checkIfSosta(s), t, tc) { } /** * @brief il treno regionale si ferma in tutte le stazioni * @param s stazione da controllare * @return se si deve fermare in quella stazione */ bool checkIfSosta (const Stazione* s) const { return true; }; /** * @return char tipo treno */ char getTipoTreno () const { return 'R'; }; /** * @return int velocita' massima del treno */ int getVelocitaMax () const { return VELOCITA_MASSIMA; }; constexpr static int VELOCITA_MASSIMA = 160; }; #endif // TRENO_REGIONALE_H
package cn.sucre.service; import cn.sucre.domain.PageBean; import cn.sucre.domain.User; import java.util.List; import java.util.Map; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 用户登录 * @param user * @return */ User login(User user); /** * 增加用户信息 * @param user */ void addUser(User user); /** * 根据id删除指定用户信息 * @param id */ void deleteUser(String id); /** * 根据id查询用户并获取该对象 * @param id * @return */ User findUserById(String id); /** * 修改用户信息 * @param user */ void updateUser(User user); /** * 删除选中的用户信息 * @param uids */ void delSelectedUser(String[] uids); /** * 分页条件查询 * @param currentPage * @param rows * @param condition * @return */ PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition); }
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "db/db_impl.h" #include <algorithm> #include <set> #include <string> #include <stdint.h> #include <stdio.h> #include <vector> #include "db/builder.h" #include "db/db_iter.h" #include "db/dbformat.h" #include "db/filename.h" #include "db/log_reader.h" #include "db/log_writer.h" #include "db/memtable.h" #include "db/table_cache.h" #include "db/version_set.h" #include "db/write_batch_internal.h" #include "leveldb/db.h" #include "leveldb/env.h" #include "leveldb/status.h" #include "leveldb/table.h" #include "leveldb/table_builder.h" #include "port/port.h" #include "table/block.h" #include "table/merger.h" #include "table/two_level_iterator.h" #include "util/coding.h" #include "util/logging.h" #include "util/mutexlock.h" namespace leveldb { const int kNumNonTableCacheFiles = 10; // Information kept for every waiting writer struct DBImpl::Writer { // NOTE:htt, 写操作,包括批量写操作,以及是否sync和done/*{{{*/ Status status; WriteBatch* batch; // NOTE:htt, 批量写操作,将记录先编码到rep_,再有WriteBatchInternal实现记录追加到MemTable bool sync; // NOTE:htt, 是否sync bool done; // NOTE:htt, 是否完成 port::CondVar cv; explicit Writer(port::Mutex* mu) : cv(mu) { } };/*}}}*/ struct DBImpl::CompactionState { // NOTE:htt, compaction状态,包括compaction后的文件列表 Compaction* const compaction; // Sequence numbers < smallest_snapshot are not significant since we // will never have to service a snapshot below smallest_snapshot. // Therefore if we have seen a sequence number S <= smallest_snapshot, // we can drop all entries for the same key with sequence numbers < S. SequenceNumber smallest_snapshot; // NOTE:htt, 快照的最小seqNumber // Files produced by compaction struct Output { // NOTE:htt, compaction产生文件,包括number, file_size, 最小/最大key uint64_t number; // NOTE:htt, 文件number uint64_t file_size; InternalKey smallest, largest; }; std::vector<Output> outputs; // NOTE:htt, compaction文件列表 // State kept for output being generated WritableFile* outfile; TableBuilder* builder; uint64_t total_bytes; // NOTE:htt, compact总的文件大小 Output* current_output() { return &outputs[outputs.size()-1]; } explicit CompactionState(Compaction* c) : compaction(c), outfile(NULL), builder(NULL), total_bytes(0) { } }; // Fix user-supplied options to be reasonable template <class T,class V> static void ClipToRange(T* ptr, V minvalue, V maxvalue) { // NOTE:htt, 调整值在[minvalue, maxvalue]范围之间 if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue; if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue; } Options SanitizeOptions(const std::string& dbname, const InternalKeyComparator* icmp, const InternalFilterPolicy* ipolicy, const Options& src) { // NOTE:htt, 设置db的options,如果需要生成日志则创建日志 Options result = src; result.comparator = icmp; result.filter_policy = (src.filter_policy != NULL) ? ipolicy : NULL; ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000); // NOTE:htt, open files范围[64+10, 50000] ClipToRange(&result.write_buffer_size, 64<<10, 1<<30); // NOTE:htt, write buffer范围[64K, 1G] ClipToRange(&result.block_size, 1<<10, 4<<20); // NOTE:htt, block大小范围[1k, 4M] if (result.info_log == NULL) { // Open a log file in the same directory as the db src.env->CreateDir(dbname); // In case it does not exist src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname)); // NOTE:htt,将原有的{dbname}/LOG文件 重命{dbname}/LOG.old Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log); // NOTE: htt, 创建日志文件对象 if (!s.ok()) { // No place suitable for logging result.info_log = NULL; } } if (result.block_cache == NULL) { result.block_cache = NewLRUCache(8 << 20); // NOTE: htt, 生成8M大小的ShardedLRUCache } return result; } DBImpl::DBImpl(const Options& raw_options, const std::string& dbname) : env_(raw_options.env), internal_comparator_(raw_options.comparator), internal_filter_policy_(raw_options.filter_policy), options_(SanitizeOptions(dbname, &internal_comparator_, &internal_filter_policy_, raw_options)), owns_info_log_(options_.info_log != raw_options.info_log), owns_cache_(options_.block_cache != raw_options.block_cache), dbname_(dbname), db_lock_(NULL), shutting_down_(NULL), bg_cv_(&mutex_), mem_(new MemTable(internal_comparator_)), // NOTE:htt, 可变内存 imm_(NULL), logfile_(NULL), logfile_number_(0), log_(NULL), seed_(0), tmp_batch_(new WriteBatch), bg_compaction_scheduled_(false), manual_compaction_(NULL) { mem_->Ref(); // NOTE:htt, 增加内存引用 has_imm_.Release_Store(NULL); // Reserve ten files or so for other uses and give the rest to TableCache. const int table_cache_size = options_.max_open_files - kNumNonTableCacheFiles; table_cache_ = new TableCache(dbname_, &options_, table_cache_size); versions_ = new VersionSet(dbname_, &options_, table_cache_, &internal_comparator_); } DBImpl::~DBImpl() { // Wait for background work to finish mutex_.Lock(); shutting_down_.Release_Store(this); // Any non-NULL value is ok while (bg_compaction_scheduled_) { bg_cv_.Wait(); } mutex_.Unlock(); if (db_lock_ != NULL) { env_->UnlockFile(db_lock_); // NOTE: htt, 释放锁 } delete versions_; if (mem_ != NULL) mem_->Unref(); if (imm_ != NULL) imm_->Unref(); delete tmp_batch_; delete log_; delete logfile_; delete table_cache_; if (owns_info_log_) { delete options_.info_log; // NOTE:htt, 释放info log } if (owns_cache_) { delete options_.block_cache; // NOTE:htt, 释放block_cache对象 } } Status DBImpl::NewDB() { // NOTE:htt, 生成 MANIFEST-1 文件, 即DB文件是新创建 VersionEdit new_db; new_db.SetComparatorName(user_comparator()->Name()); new_db.SetLogNumber(0); new_db.SetNextFile(2); new_db.SetLastSequence(0); const std::string manifest = DescriptorFileName(dbname_, 1); // NOTE:htt, 描述文件, ${dbname}/MANIFEST-1 WritableFile* file; Status s = env_->NewWritableFile(manifest, &file); if (!s.ok()) { return s; } { log::Writer log(file); std::string record; new_db.EncodeTo(&record); // NOTE:htt, 将VersionEdit内容序列化 s = log.AddRecord(record); if (s.ok()) { s = file->Close(); } } delete file; if (s.ok()) { // Make "CURRENT" file that points to the new manifest file. s = SetCurrentFile(env_, dbname_, 1); // NOTE:htt, 将MANIFEST-1 值写入到${dbname}/CURRENT } else { env_->DeleteFile(manifest); } return s; } void DBImpl::MaybeIgnoreError(Status* s) const { // NOTE:htt, 忽略错误 if (s->ok() || options_.paranoid_checks) { // No change needed } else { Log(options_.info_log, "Ignoring error %s", s->ToString().c_str()); // NOTE:htt, 记录忽略错误 *s = Status::OK(); } } void DBImpl::DeleteObsoleteFiles() { // NOTE:htt, 删除无用的文件 if (!bg_error_.ok()) { // After a background error, we don't know whether a new version may // or may not have been committed, so we cannot safely garbage collect. return; } // Make a set of all of the live files std::set<uint64_t> live = pending_outputs_; versions_->AddLiveFiles(&live); // NOTE:htt, 添加level所有Version下的共同存活的文件 std::vector<std::string> filenames; env_->GetChildren(dbname_, &filenames); // Ignoring errors on purpose // NOTE:htt, 获取dbname_目录下文件列表 uint64_t number; FileType type; for (size_t i = 0; i < filenames.size(); i++) { if (ParseFileName(filenames[i], &number, &type)) { // NOTE:htt, 从fname中获取 number 和 文件类型 bool keep = true; switch (type) { case kLogFile: // NOTE:htt, WAL日志 keep = ((number >= versions_->LogNumber()) || (number == versions_->PrevLogNumber())); // NOTE:htt, 如果比记录WAL日志number大则保存 break; case kDescriptorFile: // NOTE:htt, MANIFEST-* 文件 // Keep my manifest file, and any newer incarnations' // (in case there is a race that allows other incarnations) keep = (number >= versions_->ManifestFileNumber()); // NOTE:htt, 记录mainfest的version是否比VersionSet大 break; case kTableFile: // NOTE:htt, sst或ldb文件 keep = (live.find(number) != live.end()); break; case kTempFile: // NOTE:htt, dbtmp文件 // Any temp files that are currently being written to must // be recorded in pending_outputs_, which is inserted into "live" keep = (live.find(number) != live.end()); break; case kCurrentFile: // NOTE:htt, CURRENT文件,需保留 case kDBLockFile: // NOTE:htt, LOCK文件,需保留 case kInfoLogFile: // NOTE:htt, LOG文件,需保留 keep = true; break; } if (!keep) { if (type == kTableFile) { table_cache_->Evict(number); // NOTE:htt, 释放 file_number对应的{file, table}缓存 } Log(options_.info_log, "Delete type=%d #%lld\n", int(type), static_cast<unsigned long long>(number)); env_->DeleteFile(dbname_ + "/" + filenames[i]); // NOTE:htt, 删除对应文件 } } } } Status DBImpl::Recover(VersionEdit* edit) { // NOTE:htt, 从CURRENT读取mainfest,获取该快照所有文件,在从WAL日志中恢复数据->memtable->sst文件 mutex_.AssertHeld(); // Ignore error from CreateDir since the creation of the DB is // committed only when the descriptor is created, and this directory // may already exist from a previous failed creation attempt. env_->CreateDir(dbname_); // NOTE:htt, 创建DB目录 assert(db_lock_ == NULL); Status s = env_->LockFile(LockFileName(dbname_), &db_lock_);// NOTE:htt, 对${dbname}/LOCK 文件进行加锁 if (!s.ok()) { return s; } if (!env_->FileExists(CurrentFileName(dbname_))) { // NOTE:htt, 如果${dbname}/CURRENT 文件不存在 if (options_.create_if_missing) { // NOTE:htt, 如果允许missing时创建DB s = NewDB(); if (!s.ok()) { return s; } } else { // NOTE:htt, 如果不允许missing创建DB则报错 return Status::InvalidArgument( dbname_, "does not exist (create_if_missing is false)"); } } else { if (options_.error_if_exists) { // NOTE:htt, 如果存在报错则返回出粗 return Status::InvalidArgument( dbname_, "exists (error_if_exists is true)"); } } s = versions_->Recover(); // NOTE:htt, 从${dbname}/CURRENT获取mainfest文件名,从mainfest读取VersionEdit列表恢复对应Version if (s.ok()) { // NOTE:htt, 从WAL日志中恢复数据 SequenceNumber max_sequence(0); // Recover from all newer log files than the ones named in the // descriptor (new log files may have been added by the previous // incarnation without registering them in the descriptor). // // Note that PrevLogNumber() is no longer used, but we pay // attention to it in case we are recovering a database // produced by an older version of leveldb. const uint64_t min_log = versions_->LogNumber(); const uint64_t prev_log = versions_->PrevLogNumber(); std::vector<std::string> filenames; s = env_->GetChildren(dbname_, &filenames); // NOTE:htt, 获得${dbname}/文件列表 if (!s.ok()) { return s; } std::set<uint64_t> expected; versions_->AddLiveFiles(&expected); // NOTE:htt, 添加level所有Version下的共同存活的文件 uint64_t number; FileType type; std::vector<uint64_t> logs; for (size_t i = 0; i < filenames.size(); i++) { if (ParseFileName(filenames[i], &number, &type)) { expected.erase(number); // NOTE:htt, 移除在Version中保存的文件 if (type == kLogFile && ((number >= min_log) || (number == prev_log))) logs.push_back(number); // NOTE:htt, 保存WAL日志文件number } } if (!expected.empty()) { // NOTE:htt, 还有不在Version列表中的文件,则报错 char buf[50]; snprintf(buf, sizeof(buf), "%d missing files; e.g.", static_cast<int>(expected.size())); return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin()))); } // Recover in the order in which the logs were generated std::sort(logs.begin(), logs.end()); // NOTE:htt, 对WAL排序,从小到大恢复 for (size_t i = 0; i < logs.size(); i++) { // NOTE:htt, 从所有的WAL日志会数据 s = RecoverLogFile(logs[i], edit, &max_sequence); // NOTE:htt, 从WAL日志中恢复数据到memtable,再将memtable生成sst文件 // The previous incarnation may not have written any MANIFEST // records after allocating this log number. So we manually // update the file number allocation counter in VersionSet. versions_->MarkFileNumberUsed(logs[i]);// NOTE:htt, 确保next_file_number值比当前的WAL日志的number大 } if (s.ok()) { if (versions_->LastSequence() < max_sequence) { versions_->SetLastSequence(max_sequence); // NOTE:htt, 更新当前最新的seq值 } } } return s; } Status DBImpl::RecoverLogFile(uint64_t log_number, VersionEdit* edit, SequenceNumber* max_sequence) { // NOTE:htt, 从WAL日志中恢复数据到memtable,再将memtable生成sst文件 struct LogReporter : public log::Reader::Reporter { // NOTE:htt, WAL日志恢复异常记录 Env* env; Logger* info_log; const char* fname; Status* status; // NULL if options_.paranoid_checks==false virtual void Corruption(size_t bytes, const Status& s) { Log(info_log, "%s%s: dropping %d bytes; %s", (this->status == NULL ? "(ignoring error) " : ""), fname, static_cast<int>(bytes), s.ToString().c_str()); if (this->status != NULL && this->status->ok()) *this->status = s; } }; mutex_.AssertHeld(); // Open the log file std::string fname = LogFileName(dbname_, log_number); // NOTE:htt, WAL日志文件名, ${name}/${number}.log SequentialFile* file; Status status = env_->NewSequentialFile(fname, &file); if (!status.ok()) { MaybeIgnoreError(&status); // NOTE:htt, 忽略错误 return status; } // Create the log reader. LogReporter reporter; reporter.env = env_; reporter.info_log = options_.info_log; reporter.fname = fname.c_str(); reporter.status = (options_.paranoid_checks ? &status : NULL); // We intentially make log::Reader do checksumming even if // paranoid_checks==false so that corruptions cause entire commits // to be skipped instead of propagating bad information (like overly // large sequence numbers). log::Reader reader(file, &reporter, true/*checksum*/, 0/*initial_offset*/); Log(options_.info_log, "Recovering log #%llu", (unsigned long long) log_number); // Read all the records and add to a memtable std::string scratch; Slice record; WriteBatch batch; MemTable* mem = NULL; while (reader.ReadRecord(&record, &scratch) && // NOTE:htt, 从WAL中读取一条完整日志;该record为一批<key,value> status.ok()) { if (record.size() < 12) { reporter.Corruption( record.size(), Status::Corruption("log record too small")); continue; } WriteBatchInternal::SetContents(&batch, record); // NOTE:htt, 重新设置WriteBatch.rep_为contents if (mem == NULL) { mem = new MemTable(internal_comparator_); // NOTE:htt, 内存table,采用跳表实现 mem->Ref(); } status = WriteBatchInternal::InsertInto(&batch, mem);// NOTE:htt, 将WriteBatch中记录逐条写入到MemTable中 MaybeIgnoreError(&status); if (!status.ok()) { break; } const SequenceNumber last_seq = WriteBatchInternal::Sequence(&batch) + WriteBatchInternal::Count(&batch) - 1; // NOTE:htt, 最后一条插入记录的seq if (last_seq > *max_sequence) { *max_sequence = last_seq; // NOTE:htt, 获取当前DB中最大seq } if (mem->ApproximateMemoryUsage() > options_.write_buffer_size) { status = WriteLevel0Table(mem, edit, NULL); // NOTE:htt, 如果memtable大于阈值,则直接将memtable写入到sst文件 if (!status.ok()) { // Reflect errors immediately so that conditions like full // file-systems cause the DB::Open() to fail. break; } mem->Unref(); // NOTE:htt,减少memtable引用 mem = NULL; } } if (status.ok() && mem != NULL) { status = WriteLevel0Table(mem, edit, NULL); // NOTE:htt, 将恢复的memtable生成sst文件 // Reflect errors immediately so that conditions like full // file-systems cause the DB::Open() to fail. } if (mem != NULL) mem->Unref(); delete file; return status; } Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit, Version* base) { // NOTE:htt, 将memtable写入到sst文件(选择level层时会进行优化) mutex_.AssertHeld(); const uint64_t start_micros = env_->NowMicros(); FileMetaData meta; meta.number = versions_->NewFileNumber(); pending_outputs_.insert(meta.number); // NOTE:htt, 保存新的sst文件number Iterator* iter = mem->NewIterator(); Log(options_.info_log, "Level-0 table #%llu: started", (unsigned long long) meta.number); Status s; { mutex_.Unlock(); s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);// NOTE:htt, 将iter中的数据内容写入到sst文件中(dbname为前缀),生成元信息到meta mutex_.Lock(); } Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s", (unsigned long long) meta.number, (unsigned long long) meta.file_size, s.ToString().c_str()); delete iter; pending_outputs_.erase(meta.number); // NOTE:htt, 文件写入成功,从compact列表中移除 // Note that if file_size is zero, the file has been deleted and // should not be added to the manifest. int level = 0; if (s.ok() && meta.file_size > 0) { const Slice min_user_key = meta.smallest.user_key(); // NOTE:htt, 最小user_key const Slice max_user_key = meta.largest.user_key(); // NOTE:htt, 最大user_key if (base != NULL) { level = base->PickLevelForMemTableOutput(min_user_key, max_user_key); // NOTE:htt, 选择MemTable可以直接落入层,范围level [0,1,2]这三层文件,目标避免0->1的compact } edit->AddFile(level, meta.number, meta.file_size, meta.smallest, meta.largest); // NOTE:htt, 添加保存sst文件元信息,包括<level,number,file_size,smallest,largest> } CompactionStats stats; stats.micros = env_->NowMicros() - start_micros; // NOTE:htt, 此次文件写入时间 stats.bytes_written = meta.file_size; stats_[level].Add(stats); // NOTE:htt, 保存此次sst文件生成(memtable->sst也算compact)统计 return s; } void DBImpl::CompactMemTable() { // NOTE:htt, 将immemtable写入sst,并将原有的文件信息写入到mainfest,同时将新文件信息追加到mainfest中 mutex_.AssertHeld(); assert(imm_ != NULL); // Save the contents of the memtable as a new Table VersionEdit edit; Version* base = versions_->current(); base->Ref(); Status s = WriteLevel0Table(imm_, &edit, base); // NOTE:htt, 将memtable写入到sst文件(选择level层时会进行优化) base->Unref(); if (s.ok() && shutting_down_.Acquire_Load()) { // NOTE:htt, 如果生成memtable->sst文件时DB关闭了 s = Status::IOError("Deleting DB during memtable compaction"); } // Replace immutable memtable with the generated Table if (s.ok()) { edit.SetPrevLogNumber(0); edit.SetLogNumber(logfile_number_); // Earlier logs no longer needed // NOTE:htt, 设置当前VersionEdit对应的log number s = versions_->LogAndApply(&edit, &mutex_); // NOTE:htt, 根据edit和VersionSet生成新的Version,并保存当前的文件信息到mainfest中,并追加新的edit内容到mainfest } if (s.ok()) { // Commit to the new state imm_->Unref(); imm_ = NULL; has_imm_.Release_Store(NULL); // NOTE:htt, imm_ 内存memtable为NULL DeleteObsoleteFiles(); // NOTE:htt, 删除无用的文件 } else { RecordBackgroundError(s);// NOTE:htt, 通知bg线程出错 } } void DBImpl::CompactRange(const Slice* begin, const Slice* end) { // NOTE:htt, 先尝试对immutable进行合并,在对level[0,6]之间[begin,end]进行manual合并 int max_level_with_files = 1; { MutexLock l(&mutex_); Version* base = versions_->current(); for (int level = 1; level < config::kNumLevels; level++) { if (base->OverlapInLevel(level, begin, end)) { // NOTE:htt, 判断[begin,end]相交的文件层 max_level_with_files = level; } } } TEST_CompactMemTable(); // TODO(sanjay): Skip if memtable does not overlap // NOTE:htt, 测试对immutable进行compaction,合并到level0层 for (int level = 0; level < max_level_with_files; level++) { TEST_CompactRange(level, begin, end); // NOTE:htt, 尝试[level,begin,end]进行合并 } } void DBImpl::TEST_CompactRange(int level, const Slice* begin,const Slice* end) { // NOTE:htt, 尝试[level,begin,end]进行合并 assert(level >= 0); assert(level + 1 < config::kNumLevels); InternalKey begin_storage, end_storage; ManualCompaction manual; // NOTE:htt, 手动合并 manual.level = level; manual.done = false; if (begin == NULL) { manual.begin = NULL; } else { begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek); manual.begin = &begin_storage; // NOTE:htt, 构建manual.begin } if (end == NULL) { manual.end = NULL; } else { end_storage = InternalKey(*end, 0, static_cast<ValueType>(0)); manual.end = &end_storage; } MutexLock l(&mutex_); while (!manual.done && !shutting_down_.Acquire_Load() && bg_error_.ok()) { if (manual_compaction_ == NULL) { // Idle manual_compaction_ = &manual; // NOTE:htt, 设置manual_compaction_ MaybeScheduleCompaction(); // NOTE:htt, 尝试进行后台段合并操作 } else { // Running either my compaction or another compaction. bg_cv_.Wait(); } } if (manual_compaction_ == &manual) { // Cancel my manual compaction since we aborted early for some reason. manual_compaction_ = NULL; // NOTE:htt, 完成合并,则设置manual_compaction_为NULL } } Status DBImpl::TEST_CompactMemTable() { // NOTE:htt, 测试对immutable进行compaction,合并到level0层 // NULL batch means just wait for earlier writes to be done Status s = Write(WriteOptions(), NULL); // NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable if (s.ok()) { // Wait until the compaction completes MutexLock l(&mutex_); while (imm_ != NULL && bg_error_.ok()) { // NOTE:htt, 如果有immutable,则等待immutable compact到level0层 bg_cv_.Wait(); } if (imm_ != NULL) { s = bg_error_; } } return s; } void DBImpl::RecordBackgroundError(const Status& s) { // NOTE:htt, 通知bg线程出错 mutex_.AssertHeld(); if (bg_error_.ok()) { bg_error_ = s; bg_cv_.SignalAll(); } } void DBImpl::MaybeScheduleCompaction() { // NOTE:htt, 尝试进行后台段合并操作 mutex_.AssertHeld(); if (bg_compaction_scheduled_) { // Already scheduled } else if (shutting_down_.Acquire_Load()) { // DB is being deleted; no more background compactions } else if (!bg_error_.ok()) { // Already got an error; no more changes } else if (imm_ == NULL && manual_compaction_ == NULL && !versions_->NeedsCompaction()) { // NOTE:htt, 判断是否需要compact,compaction_score_>=1 或file_to_compact_有值则进行 // No work to be done } else { bg_compaction_scheduled_ = true; // NOTE:htt, 启动后台线程 env_->Schedule(&DBImpl::BGWork, this); // NOTE:htt, 启动一个线程执行后台线程,并进行compact操作 } } void DBImpl::BGWork(void* db) { // NOTE:htt, 执行后台任务 reinterpret_cast<DBImpl*>(db)->BackgroundCall(); } void DBImpl::BackgroundCall() { // NOTE:htt, 后台执行文件的合并,并生成sst文件,最后会生成新的Version,并写入到mainfest,并清理无用文件 MutexLock l(&mutex_); assert(bg_compaction_scheduled_); if (shutting_down_.Acquire_Load()) { // NOTE:htt, 关闭则停止 // No more background work when shutting down. } else if (!bg_error_.ok()) { // No more background work after a background error. } else { BackgroundCompaction(); // NOTE:htt, 后台执行文件的合并,并生成sst文件,最后会生成新的Version,并写入到mainfest,并清理无用文件 } bg_compaction_scheduled_ = false; // Previous compaction may have produced too many files in a level, // so reschedule another compaction if needed. MaybeScheduleCompaction(); // NOTE:htt, 再次执行段合并 bg_cv_.SignalAll(); } void DBImpl::BackgroundCompaction() { // NOTE:htt, 后台执行文件的合并,并生成sst文件,最后会生成新的Version,并写入到mainfest,并清理无用文件 mutex_.AssertHeld(); if (imm_ != NULL) { // NOTE:htt, 如immemtable不为null,则执行immemtable的compaction,即刷盘 CompactMemTable(); // NOTE:htt, 将immemtable写入sst,并将原有的文件信息写入到mainfest,同时将新文件信息追加到mainfest中 return; } Compaction* c; bool is_manual = (manual_compaction_ != NULL); InternalKey manual_end; if (is_manual) { // NOTE:htt, 确认人工合并下待合并的文件列表(level和level+1层) ManualCompaction* m = manual_compaction_; c = versions_->CompactRange(m->level, m->begin, m->end); // NOTE:htt, 选择level层和[begin,end]有交集文件列表作为level层待compact文件列表,并确认level+1文件列表 m->done = (c == NULL); if (c != NULL) { manual_end = c->input(0, c->num_input_files(0) - 1)->largest; // NOTE:htt, 待合并第一层最大的key } Log(options_.info_log, "Manual compaction at level-%d from %s .. %s; will stop at %s\n", m->level, (m->begin ? m->begin->DebugString().c_str() : "(begin)"), (m->end ? m->end->DebugString().c_str() : "(end)"), (m->done ? "(end)" : manual_end.DebugString().c_str())); } else { c = versions_->PickCompaction();// NOTE:htt, 选择待compact文件,并扩容level层文件列表(前提是扩容后总文件之后小于50M) } Status status; if (c == NULL) { // Nothing to do } else if (!is_manual && c->IsTrivialMove()) { // NOTE:htt, 小合并,将level层单个文件直接移动到level+1层 // Move file to next level assert(c->num_input_files(0) == 1); FileMetaData* f = c->input(0, 0); c->edit()->DeleteFile(c->level(), f->number); // NOTE:htt, level删除对应文件(内存信息) c->edit()->AddFile(c->level() + 1, f->number, f->file_size, f->smallest, f->largest); // NOTE:htt, level+1层加入对应文件 status = versions_->LogAndApply(c->edit(), &mutex_); // NOTE:htt, 根据edit和VersionSet生成新的Version,并保存当前的文件信息到mainfest中,并追加新的edit内容到mainfest if (!status.ok()) { RecordBackgroundError(status); } VersionSet::LevelSummaryStorage tmp; Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n", static_cast<unsigned long long>(f->number), c->level() + 1, static_cast<unsigned long long>(f->file_size), status.ToString().c_str(), versions_->LevelSummary(&tmp)); } else { // NOTE:htt, 根据选择文件进行合并 CompactionState* compact = new CompactionState(c); // NOTE:htt, compaction状态,包括compaction后的文件列表 status = DoCompactionWork(compact); // NOTE:htt, 执行文件的合并,并生成sst文件,最后会生成新的Version,并写入到mainfest if (!status.ok()) { RecordBackgroundError(status); } CleanupCompaction(compact); // NOTE:htt, 清理本次的compact涉及状态信息 c->ReleaseInputs(); DeleteObsoleteFiles();// NOTE:htt, 删除无用的文件 } delete c; if (status.ok()) { // Done } else if (shutting_down_.Acquire_Load()) { // Ignore compaction errors found during shutting down } else { Log(options_.info_log, "Compaction error: %s", status.ToString().c_str()); } if (is_manual) { ManualCompaction* m = manual_compaction_; if (!status.ok()) { m->done = true; } if (!m->done) { // NOTE:htt, 如果未完成则继续 // We only compacted part of the requested range. Update *m // to the range that is left to be compacted. m->tmp_storage = manual_end; // NOTE:htt, 临时记录最大值 m->begin = &m->tmp_storage; // NOTE:htt, 记录起始合并值 } manual_compaction_ = NULL; // NOTE:htt, 下一次不再进行人工合并 } } void DBImpl::CleanupCompaction(CompactionState* compact) { // NOTE:htt, 清理本次的compact涉及状态信息 mutex_.AssertHeld(); if (compact->builder != NULL) { // May happen if we get a shutdown call in the middle of compaction compact->builder->Abandon(); delete compact->builder; } else { assert(compact->outfile == NULL); } delete compact->outfile; for (size_t i = 0; i < compact->outputs.size(); i++) { const CompactionState::Output& out = compact->outputs[i]; pending_outputs_.erase(out.number); // NOTE:htt, 移除outputs文件 } delete compact; } Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) { // NOTE:htt, 打开待compact的文件 assert(compact != NULL); assert(compact->builder == NULL); uint64_t file_number; { mutex_.Lock(); file_number = versions_->NewFileNumber(); // NOTE:htt, 生成新的文件Number pending_outputs_.insert(file_number); CompactionState::Output out; out.number = file_number; out.smallest.Clear(); out.largest.Clear(); compact->outputs.push_back(out); // NOTE:htt, 添加本次compact需要push back的文件 mutex_.Unlock(); } // Make the output file std::string fname = TableFileName(dbname_, file_number);// NOTE:htt, 表文件名, ${name}/${number}.ldb Status s = env_->NewWritableFile(fname, &compact->outfile); if (s.ok()) { compact->builder = new TableBuilder(options_, compact->outfile); // NOTE:htt, 完成整个sstable写入,包括{data block列表, meta block, meta index block, index block, footer} 写入 } return s; } Status DBImpl::FinishCompactionOutputFile(CompactionState* compact, Iterator* input) { // NOTE:htt, 将文件写入sst并进行刷盘处理 assert(compact != NULL); assert(compact->outfile != NULL); assert(compact->builder != NULL); const uint64_t output_number = compact->current_output()->number; // NOTE:htt, 文件number assert(output_number != 0); // Check for iterator errors Status s = input->status(); const uint64_t current_entries = compact->builder->NumEntries(); if (s.ok()) { s = compact->builder->Finish(); // NOTE:htt, 完成整个sstable写入, 包括{data block列表, meta block, meta index block, index block, footer} 写入 } else { compact->builder->Abandon(); } const uint64_t current_bytes = compact->builder->FileSize(); compact->current_output()->file_size = current_bytes; // NOTE:htt, 设置文件大小为新产生sst文件大小 compact->total_bytes += current_bytes; delete compact->builder; compact->builder = NULL; // Finish and check for file errors if (s.ok()) { s = compact->outfile->Sync(); // NOTE: htt, 将目录entry信息刷盘,同时将用户态数据刷入内核,内核态数据刷入磁盘 } if (s.ok()) { s = compact->outfile->Close(); } delete compact->outfile; compact->outfile = NULL; if (s.ok() && current_entries > 0) { // Verify that the table is usable Iterator* iter = table_cache_->NewIterator(ReadOptions(), output_number, current_bytes); // NOTE:htt, 读取file_number文件,并构建talbe的两层迭代器 s = iter->status(); delete iter; if (s.ok()) { Log(options_.info_log, "Generated table #%llu: %lld keys, %lld bytes", (unsigned long long) output_number, (unsigned long long) current_entries, (unsigned long long) current_bytes); } } return s; } Status DBImpl::InstallCompactionResults(CompactionState* compact) { // NOTE:htt, 记录本次待删除以及待添加的文件(compact之后文件),并生成新的Version和保存到mainfest mutex_.AssertHeld(); Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes", compact->compaction->num_input_files(0), compact->compaction->level(), compact->compaction->num_input_files(1), compact->compaction->level() + 1, static_cast<long long>(compact->total_bytes)); // Add compaction outputs compact->compaction->AddInputDeletions(compact->compaction->edit()); // NOTE:htt, 将本次compaction涉及到 level/level+1 层文件添加到待删除列表 const int level = compact->compaction->level(); for (size_t i = 0; i < compact->outputs.size(); i++) { const CompactionState::Output& out = compact->outputs[i]; compact->compaction->edit()->AddFile( level + 1, out.number, out.file_size, out.smallest, out.largest); // NOTE:htt, level+1层增加本次compaction文件 } return versions_->LogAndApply(compact->compaction->edit(), &mutex_); // NOTE:htt, 根据edit和VersionSet生成新的Version,并保存当前的文件信息到mainfest中,并追加新的edit内容到mainfest } Status DBImpl::DoCompactionWork(CompactionState* compact) { // NOTE:htt, 执行文件的合并,并生成sst文件,最后会生成新的Version,并写入到mainfest const uint64_t start_micros = env_->NowMicros(); // NOTE: htt, 获取系统当前时间对应的微秒值 int64_t imm_micros = 0; // Micros spent doing imm_ compactions Log(options_.info_log, "Compacting %d@%d + %d@%d files", compact->compaction->num_input_files(0), compact->compaction->level(), compact->compaction->num_input_files(1), compact->compaction->level() + 1); assert(versions_->NumLevelFiles(compact->compaction->level()) > 0); assert(compact->builder == NULL); assert(compact->outfile == NULL); if (snapshots_.empty()) { compact->smallest_snapshot = versions_->LastSequence(); // NOTE:htt, 空快照情况下,当前最小的snapshot即当前versions.seq } else { compact->smallest_snapshot = snapshots_.oldest()->number_; // NOTE:htt, 快照中最小的即为当前最小快照 } // Release mutex while we're actually doing the compaction work mutex_.Unlock(); Iterator* input = versions_->MakeInputIterator(compact->compaction); // NOTE:htt, 构建compaction中涉及两层需要merge文件的合并的迭代器 input->SeekToFirst(); Status status; ParsedInternalKey ikey; std::string current_user_key; bool has_current_user_key = false; SequenceNumber last_sequence_for_key = kMaxSequenceNumber; for (; input->Valid() && !shutting_down_.Acquire_Load(); ) { // NOTE:htt, MegerIterator 指向下一个值,并重新从所有待compact文件中找到值最小值的位置 // Prioritize immutable compaction work if (has_imm_.NoBarrier_Load() != NULL) { // NOTE:htt, immutable直接落sst文件 const uint64_t imm_start = env_->NowMicros(); mutex_.Lock(); if (imm_ != NULL) { CompactMemTable();// NOTE:htt, 将immemtable写入sst,并将原有的文件信息写入到mainfest,同时将新文件信息追加到mainfest中 bg_cv_.SignalAll(); // Wakeup MakeRoomForWrite() if necessary } mutex_.Unlock(); imm_micros += (env_->NowMicros() - imm_start); // NOTE:htt, 记录时间,imm文件落0层sst时间已专门统计 } Slice key = input->key(); if (compact->compaction->ShouldStopBefore(key) && compact->builder != NULL) { status = FinishCompactionOutputFile(compact, input); // NOTE:htt, 将文件写入sst并进行刷盘处理 if (!status.ok()) { break; } } // Handle key/value, add to state, etc. bool drop = false; if (!ParseInternalKey(key, &ikey)) { // Do not hide error keys current_user_key.clear(); has_current_user_key = false; last_sequence_for_key = kMaxSequenceNumber; } else { if (!has_current_user_key || user_comparator()->Compare(ikey.user_key, Slice(current_user_key)) != 0) { // First occurrence of this user key current_user_key.assign(ikey.user_key.data(), ikey.user_key.size()); has_current_user_key = true; last_sequence_for_key = kMaxSequenceNumber; } if (last_sequence_for_key <= compact->smallest_snapshot) { // NOTE:htt, 比compact最小的key小则丢弃 // Hidden by an newer entry for same user key drop = true; // (A) } else if (ikey.type == kTypeDeletion && ikey.sequence <= compact->smallest_snapshot && compact->compaction->IsBaseLevelForKey(ikey.user_key)) { // NOTE:htt, 更高层没有该记录,并为删除标记,同时比compaction的sequence小,则可以删 // For this user key: // (1) there is no data in higher levels // (2) data in lower levels will have larger sequence numbers // (3) data in layers that are being compacted here and have // smaller sequence numbers will be dropped in the next // few iterations of this loop (by rule (A) above). // Therefore this deletion marker is obsolete and can be dropped. drop = true; } last_sequence_for_key = ikey.sequence; // NOTE:htt, 更新last sequence,判断同一个key多个记录保留情况下使用 } #if 0 Log(options_.info_log, " Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, " "%d smallest_snapshot: %d", ikey.user_key.ToString().c_str(), (int)ikey.sequence, ikey.type, kTypeValue, drop, compact->compaction->IsBaseLevelForKey(ikey.user_key), (int)last_sequence_for_key, (int)compact->smallest_snapshot); #endif if (!drop) { // NOTE:htt, drop的记录则直接丢弃 // Open output file if necessary if (compact->builder == NULL) { status = OpenCompactionOutputFile(compact); // NOTE:htt, 生成新待compact的文件 if (!status.ok()) { break; } } if (compact->builder->NumEntries() == 0) { compact->current_output()->smallest.DecodeFrom(key); // NOTE:htt, 首次写入值设置为smallest } compact->current_output()->largest.DecodeFrom(key); // NOTE:htt, 每次写入的设置为largest compact->builder->Add(key, input->value()); // NOTE:htt, 添加<key,value>,因input每次从所有文件选择的最小的key // Close output file if it is big enough if (compact->builder->FileSize() >= compact->compaction->MaxOutputFileSize()) { status = FinishCompactionOutputFile(compact, input); // NOTE:htt, 将文件写入sst并进行刷盘处理 if (!status.ok()) { break; } } } input->Next(); // NOTE:htt, MegerIterator 指向下一个值,并重新找到值最小的位置 } if (status.ok() && shutting_down_.Acquire_Load()) { status = Status::IOError("Deleting DB during compaction"); } if (status.ok() && compact->builder != NULL) { status = FinishCompactionOutputFile(compact, input); // NOTE:htt, 将文件写入sst并进行刷盘处理 } if (status.ok()) { status = input->status(); } delete input; input = NULL; CompactionStats stats; // NOTE:htt, compaction统计 stats.micros = env_->NowMicros() - start_micros - imm_micros; // NOTE:htt, compaction消耗时间,imm落0层统计已专门处理,此处不重复统计 for (int which = 0; which < 2; which++) { for (int i = 0; i < compact->compaction->num_input_files(which); i++) { // NOTE:htt, 总共读取的数据 stats.bytes_read += compact->compaction->input(which, i)->file_size; } } for (size_t i = 0; i < compact->outputs.size(); i++) { // NOTE:htt, 总共写入的数据 stats.bytes_written += compact->outputs[i].file_size; } mutex_.Lock(); stats_[compact->compaction->level() + 1].Add(stats); // NOTE:htt, compact操作设置文件读取和写入算作 level+1层 if (status.ok()) { status = InstallCompactionResults(compact); // NOTE:htt, 记录本次待删除以及待添加的文件(compact之后文件),并生成新的Version和保存到mainfest } if (!status.ok()) { RecordBackgroundError(status); // NOTE:htt, 通知bg线程出错 } VersionSet::LevelSummaryStorage tmp; Log(options_.info_log, "compacted to: %s", versions_->LevelSummary(&tmp)); // NOTE:htt, 统计所有level层文件个数 return status; } namespace { struct IterState { // NOTE:htt, 迭代状态 port::Mutex* mu; Version* version;// NOTE:htt, 管理当前版本的所有level层文件 MemTable* mem; // NOTE:htt, 可写入mem MemTable* imm; // NOTE:htt, 不可写入imm }; static void CleanupIteratorState(void* arg1, void* arg2) { // NOTE:htt, 清理IterState,包括减少mem/version引用,并删除IterState IterState* state = reinterpret_cast<IterState*>(arg1); state->mu->Lock(); state->mem->Unref(); // NOTE:htt, 减少mem引用 if (state->imm != NULL) state->imm->Unref(); state->version->Unref(); state->mu->Unlock(); delete state; // NOTE:htt, 删除当前IterState } } // namespace Iterator* DBImpl::NewInternalIterator(const ReadOptions& options, SequenceNumber* latest_snapshot, uint32_t* seed) { // NOTE:htt, 生成{mem, imm, level0-6}文件迭代器,并注册清理函数 IterState* cleanup = new IterState; mutex_.Lock(); *latest_snapshot = versions_->LastSequence(); // NOTE:htt, 当前最新的sequence // Collect together all needed child iterators std::vector<Iterator*> list; list.push_back(mem_->NewIterator()); mem_->Ref(); if (imm_ != NULL) { list.push_back(imm_->NewIterator()); imm_->Ref(); } versions_->current()->AddIterators(options, &list); Iterator* internal_iter = NewMergingIterator(&internal_comparator_, &list[0], list.size()); versions_->current()->Ref(); cleanup->mu = &mutex_; // NOTE:htt, 引用锁 cleanup->mem = mem_; cleanup->imm = imm_; cleanup->version = versions_->current(); // NOTE:htt, 引用Version internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, NULL); *seed = ++seed_; mutex_.Unlock(); return internal_iter; } Iterator* DBImpl::TEST_NewInternalIterator() { // NOTE:htt, 测试生成{mem, imm, level0-6}文件迭代器 SequenceNumber ignored; uint32_t ignored_seed; return NewInternalIterator(ReadOptions(), &ignored, &ignored_seed); } int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {// NOTE:htt, 获取所有从level1层开始每个文件和下一层文件交集,并获取交集最大的值 MutexLock l(&mutex_); return versions_->MaxNextLevelOverlappingBytes();// NOTE:htt, 获取所有从level1层开始每个文件和下一层文件交集,并获取交集最大的值 } Status DBImpl::Get(const ReadOptions& options, const Slice& key, std::string* value) {/*{{{*/ // NOTE:htt, 读取key对应value,其中先找mem,再找imm,最后从sst找,从sst查找到会尝试触发读合并 Status s; MutexLock l(&mutex_); SequenceNumber snapshot; // NOTE:htt,获取最新或Options指定的sequece if (options.snapshot != NULL) { snapshot = reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_; } else { snapshot = versions_->LastSequence(); // NOTE:htt, 获取last sequence } // fprintf(stderr, "key:%s, snapshot:%llu\n", key.data(), snapshot); // TODO:htt, delete MemTable* mem = mem_; MemTable* imm = imm_; Version* current = versions_->current(); mem->Ref(); if (imm != NULL) imm->Ref(); current->Ref(); // NOTE:htt, 增加引用 bool have_stat_update = false; Version::GetStats stats; // NOTE:htt, 查询key所在文件信息 // Unlock while reading from files and memtables { mutex_.Unlock(); // First look in the memtable, then in the immutable memtable (if any). LookupKey lkey(key, snapshot); if (mem->Get(lkey, value, &s)) { // NOTE:htt, 如果mem中找到, 为KeyComparator(InternalKeyComparator(BytewiseComparatorImpl)),先比较user_key(按递增序),如果相等则按seq递减排序:{key1,10,1},{key1,8,1},{key2,11,1},用户查询时seq为最新({key1,20,1},则比{key1,10,1}小,则会返回{key1,10,1}) // Done } else if (imm != NULL && imm->Get(lkey, value, &s)) { // Done } else { s = current->Get(options, lkey, value, &stats); // NOTE:htt, 从levelDB的7层文件来读取数据,先从0层读取,如果未找到则继续1层读取 have_stat_update = true; } mutex_.Lock(); } if (have_stat_update && current->UpdateStats(stats)) { // NOTE:htt, 根据空读的次数来减少allowed_seeks,如果为0则记录文件为待compaction, 即因读引发的compaction MaybeScheduleCompaction(); // NOTE:htt, 尝试进行后台段合并操作 } mem->Unref(); if (imm != NULL) imm->Unref(); current->Unref(); return s; }/*}}}*/ Iterator* DBImpl::NewIterator(const ReadOptions& options) { // NOTE:htt, 根据{mem,imm, level0-6}文件迭代器构建DBIter SequenceNumber latest_snapshot; uint32_t seed; // NOTE:htt, 局部变量,未赋值,作为随机种子 Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed); // NOTE:htt, 生成{mem, imm, level0-6}文件迭代器,并注册清理函数; return NewDBIterator( this, user_comparator(), iter, (options.snapshot != NULL ? reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_ : latest_snapshot), seed);// NOTE:htt, 构建DBIter } void DBImpl::RecordReadSample(Slice key) { // NOTE:htt, 读采样,定位读match超过2个文件,则可以尝试合并 MutexLock l(&mutex_); if (versions_->current()->RecordReadSample(key)) { MaybeScheduleCompaction(); // NOTE:htt, 尝试合并 } } const Snapshot* DBImpl::GetSnapshot() {// NOTE:htt,获取最新seq的snapshot,并插入到snapshotlist的列表中 MutexLock l(&mutex_); return snapshots_.New(versions_->LastSequence());// NOTE:htt,获取最新seq的snapshot,并插入到snapshotlist的列表中 } void DBImpl::ReleaseSnapshot(const Snapshot* s) { // NOTE:htt, 删除当前快照列表中一个快照 MutexLock l(&mutex_); snapshots_.Delete(reinterpret_cast<const SnapshotImpl*>(s)); } // Convenience methods Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {// NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable return DB::Put(o, key, val);// NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable } Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {// NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable return DB::Delete(options, key); } Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) { // NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable Writer w(&mutex_); w.batch = my_batch; w.sync = options.sync; // NOTE:htt, 默认为false w.done = false; MutexLock l(&mutex_); writers_.push_back(&w); while (!w.done && &w != writers_.front()) { w.cv.Wait(); // NOTE:htt, 如果不在队首,则等待 } if (w.done) { return w.status; // NOTE:htt, 如果已完成则直接返回状态 } // May temporarily unlock and wait. Status status = MakeRoomForWrite(my_batch == NULL);// NOTE:htt, 为写腾空间,主要是将memtable转变为imm,然后生成新的mem来支持写 uint64_t last_sequence = versions_->LastSequence(); Writer* last_writer = &w; // NOTE:htt, 此时已经是尾部并且未完成 if (status.ok() && my_batch != NULL) { // NULL batch is for compactions WriteBatch* updates = BuildBatchGroup(&last_writer); // NOTE:htt, 将writers_中多个 writer请求追加一起直到大小超过限制,这样可以写入更多记录 WriteBatchInternal::SetSequence(updates, last_sequence + 1); // NOTE:htt, 将最新的 sequence 写入到批量请求中,写入时会递增sequence last_sequence += WriteBatchInternal::Count(updates); // NOTE:htt, 更新last_sequence(+写入记录个数) // Add to log and apply to memtable. We can release the lock // during this phase since &w is currently responsible for logging // and protects against concurrent loggers and concurrent writes // into mem_. { mutex_.Unlock(); status = log_->AddRecord(WriteBatchInternal::Contents(updates)); // NOTE:htt, 将待写记录 追加到 WAL日志 bool sync_error = false; if (status.ok() && options.sync) { status = logfile_->Sync(); // NOTE:htt, WAL日志刷盘 if (!status.ok()) { sync_error = true; } } if (status.ok()) { // NOTE:htt, WAL成功写入后,再写入MemTable status = WriteBatchInternal::InsertInto(updates, mem_); // NOTE:htt, 将WriteBatch中记录逐条写入到MemTable中 } mutex_.Lock(); if (sync_error) { // The state of the log file is indeterminate: the log record we // just added may or may not show up when the DB is re-opened. // So we force the DB into a mode where all future writes fail. RecordBackgroundError(status); } } if (updates == tmp_batch_) tmp_batch_->Clear(); // NOTE:htt, 清空 tmp_batch_,为下次整合批量提供准备 versions_->SetLastSequence(last_sequence); // NOTE:htt, 更新last_sequence值 } while (true) { // NOTE:htt, 循环取出已经做的writer,并且不是头部writer,则发起信号通知 Writer* ready = writers_.front(); writers_.pop_front(); if (ready != &w) { ready->status = status; ready->done = true; // NOTE:htt, 如果ready不是w对应,锁名ready已完成 ready->cv.Signal(); } if (ready == last_writer) break; // NOTE:htt, 如果本次批量写入的都已处理则break } // Notify new head of write queue if (!writers_.empty()) { writers_.front()->cv.Signal(); // NOTE:htt, 通知队列首部记录处理 } return status; } // REQUIRES: Writer list must be non-empty // REQUIRES: First writer must have a non-NULL batch WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) { // NOTE:htt, 将writers_中多个 writer请求追加一起直到大小超过限制,这样可以写入更多记录 assert(!writers_.empty()); Writer* first = writers_.front(); // NOTE:htt, 重新取头部记录 WriteBatch* result = first->batch; assert(result != NULL); size_t size = WriteBatchInternal::ByteSize(first->batch); // NOTE:htt, 获取批量写字符串大小 // Allow the group to grow up to a maximum size, but if the // original write is small, limit the growth so we do not slow // down the small write too much. size_t max_size = 1 << 20; if (size <= (128<<10)) { // NOTE:htt, 如果批量记录大小 < 128K, 则调整max size = 128K + size max_size = size + (128<<10); } *last_writer = first; std::deque<Writer*>::iterator iter = writers_.begin(); ++iter; // Advance past "first" // NOTE:htt, 跳过first for (; iter != writers_.end(); ++iter) { // NOTE:htt, 当批量记录累积大小未达到max_size(1M)则持续追加记录 Writer* w = *iter; // NOTE:htt, 取一个writer if (w->sync && !first->sync) { // NOTE:htt, 如果当前请求强制刷盘,但是头部请求未强制刷盘则暂停 // Do not include a sync write into a batch handled by a non-sync write. break; } if (w->batch != NULL) { size += WriteBatchInternal::ByteSize(w->batch); if (size > max_size) { // NOTE:htt, 如果累积写请求大小超过 max_size,则暂停新的批量记录添加result中 // Do not make batch too big break; } // Append to *reuslt if (result == first->batch) { // NOTE:htt, 如果result为first->batch,则将记录追加到缓存 tmp_batch_ // Switch to temporary batch instead of disturbing caller's batch result = tmp_batch_; assert(WriteBatchInternal::Count(result) == 0); // NOTE:htt, 首次写入tmp_batch则为空 WriteBatchInternal::Append(result, first->batch); // NOTE:htt, 将first->batch记录追加到result中 } WriteBatchInternal::Append(result, w->batch); // NOTE:htt, 将w->batch中请求记录追加到result中 } *last_writer = w; // NOTE:htt, 本次合并取出最后的writer } return result; } // REQUIRES: mutex_ is held // REQUIRES: this thread is currently at the front of the writer queue Status DBImpl::MakeRoomForWrite(bool force) { // NOTE:htt, 为写腾空间,主要是将memtable转变为imm,然后生成新的mem来支持写 mutex_.AssertHeld(); assert(!writers_.empty()); bool allow_delay = !force; Status s; while (true) { if (!bg_error_.ok()) { // Yield previous error s = bg_error_; break; } else if ( allow_delay && versions_->NumLevelFiles(0) >= config::kL0_SlowdownWritesTrigger) { // NOTE:htt, 0层sst达到8个,减缓写入,会sleep // We are getting close to hitting a hard limit on the number of // L0 files. Rather than delaying a single write by several // seconds when we hit the hard limit, start delaying each // individual write by 1ms to reduce latency variance. Also, // this delay hands over some CPU to the compaction thread in // case it is sharing the same core as the writer. mutex_.Unlock(); env_->SleepForMicroseconds(1000); // NOTE:htt, sleep 1ms allow_delay = false; // Do not delay a single write more than once // NOTE:htt, 单次写入不sleep多次 mutex_.Lock(); } else if (!force && (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) { // NOTE:htt, 如果内存小于4M并不强制则完成 // There is room in current memtable break; } else if (imm_ != NULL) { // NOTE:htt, 如果已经有immemtable,则说明内存memtable满了,需等待 // We have filled up the current memtable, but the previous // one is still being compacted, so we wait. Log(options_.info_log, "Current memtable full; waiting...\n"); bg_cv_.Wait(); } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) { // NOTE:htt, 如果level0文件>=12,则等待 // There are too many level-0 files. Log(options_.info_log, "Too many L0 files; waiting...\n"); bg_cv_.Wait(); } else { // Attempt to switch to a new memtable and trigger compaction of old assert(versions_->PrevLogNumber() == 0); uint64_t new_log_number = versions_->NewFileNumber(); WritableFile* lfile = NULL; s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile); // NOTE:htt, 生成WAL ${name}/${number}.log if (!s.ok()) { // Avoid chewing through file number space in a tight loop. versions_->ReuseFileNumber(new_log_number); // NOTE:htt, 回退版本号 break; } delete log_; delete logfile_; logfile_ = lfile; // NOTE:htt, 新的WAL文件描述符 logfile_number_ = new_log_number; log_ = new log::Writer(lfile); // NOTE:htt, WAL处理对象 imm_ = mem_; // NOTE:htt, 将immemtable设置为memtable has_imm_.Release_Store(imm_); mem_ = new MemTable(internal_comparator_); // NOTE:htt, 新的memtable mem_->Ref(); // NOTE:htt,增加引用 force = false; // Do not force another compaction if have room MaybeScheduleCompaction(); // NOTE:htt, 尝试进行后台段合并操作 } } return s; } bool DBImpl::GetProperty(const Slice& property, std::string* value) { // NOTE:htt, 获取统计信息,包括compaction统计或leveldb文件列表统计 value->clear(); MutexLock l(&mutex_); Slice in = property; Slice prefix("leveldb."); if (!in.starts_with(prefix)) return false; in.remove_prefix(prefix.size()); if (in.starts_with("num-files-at-level")) { in.remove_prefix(strlen("num-files-at-level")); uint64_t level; bool ok = ConsumeDecimalNumber(&in, &level) && in.empty(); // NOTE:htt, property为 leveldb.num-files-at-level2 if (!ok || level >= config::kNumLevels) { return false; } else { char buf[100]; snprintf(buf, sizeof(buf), "%d", versions_->NumLevelFiles(static_cast<int>(level))); *value = buf; // NOTE:htt, 直接获取level的值,如2 return true; } } else if (in == "stats") { // NOTE:htt, level.stats 获取文件compaction统计信息或每层文件信息 char buf[200]; snprintf(buf, sizeof(buf), " Compactions\n" "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n" "--------------------------------------------------\n" ); value->append(buf); for (int level = 0; level < config::kNumLevels; level++) { int files = versions_->NumLevelFiles(level); if (stats_[level].micros > 0 || files > 0) { // NOTE:htt, 如果compaction有统计或对应层文件大于0则落统计信息 snprintf( buf, sizeof(buf), "%3d %8d %8.0f %9.0f %8.0f %9.0f\n", level, files, versions_->NumLevelBytes(level) / 1048576.0, // NOTE:htt, 某level层文件总大小 stats_[level].micros / 1e6, // NOTE:htt, compaction操作花费时间 stats_[level].bytes_read / 1048576.0, // NOTE:htt, compaction操作读取数据 stats_[level].bytes_written / 1048576.0); // NOTE:htt, compaction操作写入数据 value->append(buf); } } return true; } else if (in == "sstables") { // NOTE:htt, leveldb.sstables 获取sst文件列表详细信息 *value = versions_->current()->DebugString();// NOTE:htt, 打印当前Version下所有level文件的信息 return true; } return false; } void DBImpl::GetApproximateSizes( const Range* range, int n, uint64_t* sizes) { // NOTE:htt, 统计 [start,limit] 之间的sst文件大小近似值, 通过Range*可以统计多个之间的统计 // TODO(opt): better implementation Version* v; { MutexLock l(&mutex_); versions_->current()->Ref(); v = versions_->current(); } for (int i = 0; i < n; i++) { // Convert user_key into a corresponding internal key. InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek); // NOTE:htt, 最小查询intelnalKey{user_key,seq,t} InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek); // NOTE:htt, 最小查询intelnalKey{user_key,seq,t} uint64_t start = versions_->ApproximateOffsetOf(v, k1); // NOTE:htt, 查找k1在leveldb所有文件中近似offset uint64_t limit = versions_->ApproximateOffsetOf(v, k2); // NOTE:htt, 查找k2在leveldb所有文件中近似offset sizes[i] = (limit >= start ? limit - start : 0); // NOTE:htt, 统计[k1, k2]之间所有sst文件大小之差 } { MutexLock l(&mutex_); v->Unref(); } } // Default implementations of convenience methods that subclasses of DB // can call if they wish Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) { // NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable WriteBatch batch; batch.Put(key, value);// NOTE:htt, 添加<key,value> 到rep_ return Write(opt, &batch); // NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable } Status DB::Delete(const WriteOptions& opt, const Slice& key) {// NOTE:htt, 取批量writer记录,并先写WAL,然后写Memtable WriteBatch batch; batch.Delete(key); // NOTE:htt, 添加删除key 到rep_ return Write(opt, &batch); } DB::~DB() { } Status DB::Open(const Options& options, const std::string& dbname, DB** dbptr) { // NOTE:htt, 打开DB文件,并从CURRENT读取mainfest,然后获取文件信息,并从WAL恢复mem数据;同时产生新的mainfest,并写入CURRENT;最后删除无用文件,并尝试段合并 *dbptr = NULL; DBImpl* impl = new DBImpl(options, dbname); impl->mutex_.Lock(); // NOTE:htt,启动时加锁 VersionEdit edit; Status s = impl->Recover(&edit); // Handles create_if_missing, error_if_exists // NOTE:htt, 从CURRENT读取mainfest,获取该快照所有文件,在从WAL日志中恢复数据->memtable->sst文件 if (s.ok()) { uint64_t new_log_number = impl->versions_->NewFileNumber(); WritableFile* lfile; s = options.env->NewWritableFile(LogFileName(dbname, new_log_number), &lfile); // NOTE:htt, 打开WAL日志, ${dbname}/${number}.log if (s.ok()) { edit.SetLogNumber(new_log_number); // NOTE:htt, 记录当前的WAL日志文件number impl->logfile_ = lfile; // NOTE:htt, WAL底层操作文件写入的文件对象 impl->logfile_number_ = new_log_number; impl->log_ = new log::Writer(lfile); // NOTE:htt, 将记录写入WAL日志中,如果记录大于块长度,则拆分多个部分写入 s = impl->versions_->LogAndApply(&edit, &impl->mutex_); // NOTE:htt, 根据edit和VersionSet生成新的Version,并保存当前的文件信息到mainfest中,并追加新的edit内容到mainfest } if (s.ok()) { impl->DeleteObsoleteFiles(); // NOTE:htt, 删除无用的文件 impl->MaybeScheduleCompaction(); // NOTE:htt, 尝试进行后台段合并操作 } } impl->mutex_.Unlock(); if (s.ok()) { *dbptr = impl; } else { delete impl; } return s; } Snapshot::~Snapshot() { } Status DestroyDB(const std::string& dbname, const Options& options) { // NOTE:htt, 删除整个DB,慎用 Env* env = options.env; std::vector<std::string> filenames; // Ignore error in case directory does not exist env->GetChildren(dbname, &filenames); if (filenames.empty()) { return Status::OK(); } FileLock* lock; const std::string lockname = LockFileName(dbname); Status result = env->LockFile(lockname, &lock); // NOTE: htt, 打开锁文件(文件加锁成功) if (result.ok()) { uint64_t number; FileType type; for (size_t i = 0; i < filenames.size(); i++) { if (ParseFileName(filenames[i], &number, &type) && type != kDBLockFile) { // Lock file will be deleted at end // NOTE:htt, 删除所有文件 Status del = env->DeleteFile(dbname + "/" + filenames[i]); if (result.ok() && !del.ok()) { result = del; } } } env->UnlockFile(lock); // Ignore error since state is already gone env->DeleteFile(lockname); env->DeleteDir(dbname); // Ignore error in case dir contains other files } return result; } } // namespace leveldb
import express, { Request, Response } from "express"; import dotenv from "dotenv"; import { AddressInfo } from "net"; import { IdGenerator } from "./IdGenetator"; import { UserDatabase } from "./data/UserDataBase"; import { RecipeDatabase } from "./data/RecipeDatabase"; import { Authenticator } from "./service/Authenticator"; import {FollowDatabase}from "./data/FollowDatabase" import HashManager from "./service/HashManager"; dotenv.config(); const app = express(); app.use(express.json()); app.post('/signup', async (req: express.Request, res: express.Response) => { try { if (!req.body.name || req.body.name === "") { throw new Error("Nome inválido / Campo vazio.") } if (!req.body.email || req.body.email.indexOf("@") === -1) { throw new Error("E-mail inválido.") } if (!req.body.password || req.body.password.length < 6) { throw new Error("Senha inválida.") } const userData = { name: req.body.name, email: req.body.email, password: req.body.password } const hashManager = new HashManager(); const cipherText = await hashManager.hash(userData.password); const idGenerator = new IdGenerator(); const id = idGenerator.generate(); const userDB = new UserDatabase(); const user = await userDB.create (id, userData.name, userData.email, cipherText) const authenticator = new Authenticator(); const token = authenticator.generateToken({ id }) res.status(200).send({ token }) } catch (error) { res.status(400).send({ message: error.message }) } }) app.post("/login", async (req: express.Request, res: express.Response) => { try{ const userData = { email: req.body.email, password: req.body.password } const userDatabase = new UserDatabase(); const user = await userDatabase.getByEmail(userData.email); const hashManager = new HashManager() const comparePassword = await hashManager.compare(userData.password, user.password) if(user.email !== userData.email){ throw new Error("E-mail inválido."); } if(comparePassword === false){ throw new Error("Senha inválida."); } const authenticator = new Authenticator(); const token = authenticator.generateToken({id: user.id}); res.status(200).send({token}); } catch (err) { res.status(400).send({ message: err.message, }); } }); app.get("/user/profile", async (req: Request, res: Response) => { try { const token = req.headers.authorization as string; const authenticator = new Authenticator(); const authenticationData = authenticator.getData(token); const userDb = new UserDatabase(); const user = await userDb.getById(authenticationData.id); res.status(200).send({ id: user.id, email: user.email, name: user.name }); } catch (err) { res.status(400).send({ message: err.message, }); } }); app.post('/recipe', async (req: express.Request, res: express.Response) => { try { const token = req.headers.authorization as string; const authenticator = new Authenticator(); const authenticationData = authenticator.getData(token); if (!req.body.title || req.body.title === "") { throw new Error("Título inválido / Campo vazio.") } if (!req.body.description || req.body.description === "") { throw new Error("Texto inválido / Campo vazio.") } const RecipeData = { title: req.body.title, description: req.body.description, } const idGenerator = new IdGenerator(); const id = idGenerator.generate(); const RecipeDB = new RecipeDatabase(); const recipe = await RecipeDB.createRecipe( id, RecipeData.title, RecipeData.description, authenticationData.id, new Date()) res.status(200).send("Receita publicada!") } catch (error) { res.status(400).send({ message: error.message }) } }) app.post('/user/follow/:id', async (req: express.Request, res: express.Response) => { try { const token= req.headers.authorization as string; const authenticator = new Authenticator(); const authenticationData = authenticator.getData(token); const followDatabase = new FollowDatabase(); const follow = await followDatabase.follow(authenticationData.id, req.params.id); res.status(200).send("Usuário seguido com sucesso") } catch (error) { res.status(400).send({ message: error.message }) } }) app.post('/user/unfollow/:id', async (req: express.Request, res: express.Response) => { try { const token= req.headers.authorization as string; const authenticator = new Authenticator(); const authenticationData = authenticator.getData(token); if (!req.params.id || req.params.id === "") { throw new Error("Usuário inválido / Campo vazio.") } const followDataBase = new FollowDatabase(); followDataBase.unfollow(authenticationData.id, req.params.id); res.status(200).send("Você deixou de seguir o perfil") } catch (error) { res.status(400).send({ message: error.message }) } }) app.get("/recipe/:id", async (req: Request, res: Response) => { try { const token = req.headers.authorization as string; const authenticator = new Authenticator(); const authenticationData = authenticator.getData(token); const recipeDb = new RecipeDatabase(); const recipe = await recipeDb.getRecipeById(req.params.id); res.status(200).send({ id: recipe.id, title: recipe.title, description: recipe.description, createdAt: recipe.createdAt }); } catch (err) { res.status(400).send({ message: err.message, }); } }); app.get("/feed", async (req: Request, res: Response) => { try { const token = req.headers.authorization as string; const authenticator = new Authenticator(); const authenticationData = authenticator.getData(token); const recipeDb = new RecipeDatabase(); const recipe = await recipeDb.getFeed(authenticationData.id); let feed = recipe.map((item: any)=>{ return item }) res.status(200).send({recipe}); } catch (err) { res.status(400).send({ message: err.message, }); } }); const server = app.listen(process.env.PORT || 3003, () => { if (server) { const address = server.address() as AddressInfo; console.log(`Server is running in http://localhost:${address.port}`); } else { console.error(`Failure upon starting server.`); } });
import {myData} from './data'; import React from 'react'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TablePagination from '@material-ui/core/TablePagination'; import TableRow from '@material-ui/core/TableRow'; import TableSortLabel from '@material-ui/core/TableSortLabel'; import Paper from '@material-ui/core/Paper'; import useStyles from './styles'; // import THeader from './TableHeader'; export interface TableData { id: number; location: string; type: string; device_health: string; last_used: string; price:string; color:string; } function createTableData(id:number, location:string, type:string, device_health:string, last_used:string, price:string,color:string): TableData { return { id, location, type, device_health, last_used, price, color}; } // creates content for the table rows from the given json object const rows:TableData[] = myData.map(({ id, location, type, device_health, last_used, price, color}) =>{ return ( createTableData(id, location, type, device_health, last_used, price, color) ); }) // basic sort function according to the order state function descendingComparator<T>(a: T, b: T, orderBy: keyof T) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } export type Order = 'asc' | 'desc'; function getComparator<Key extends keyof any>( order: Order, orderBy: Key, ): (a: { [key in Key]: number | string }, b: { [key in Key]: number | string }) => number { return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } function stableSort<T>(array: T[], comparator: (a: T, b: T) => number) { const stabilizedThis = array.map((el, index) => [el, index] as [T, number]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); return stabilizedThis.map(el => el[0]); } interface IColumnHeaderProps { id: keyof TableData; label: string; numeric: boolean; } const columnHeader: IColumnHeaderProps[] = [ { id: 'id', numeric: false, label: 'id' }, { id: 'location', numeric: false, label: 'Location' }, { id: 'type', numeric: false, label: 'Type' }, { id: 'device_health', numeric: false, label: 'Device health' }, { id: 'last_used', numeric: false, label: 'Last used' }, { id: 'price', numeric: false, label: 'Price' }, ]; export interface ITableProps { classes: ReturnType<typeof useStyles>; onRequestSort: (event: React.MouseEvent<unknown>, property: keyof TableData) => void; order: Order; orderBy: string; } function THeader(props: ITableProps) { const { classes, order, orderBy, onRequestSort } = props; const createSortHandler = (property: keyof TableData) => (event: React.MouseEvent<unknown>) => { onRequestSort(event, property); }; return ( <TableHead> <TableRow> {columnHeader.map(headCell => ( <TableCell key={headCell.id} align={headCell.numeric ? 'right' : 'left'} padding={'default'} sortDirection={orderBy === headCell.id ? order : false} > <TableSortLabel active={orderBy === headCell.id} direction={orderBy === headCell.id ? order : 'asc'} onClick={createSortHandler(headCell.id)} > {headCell.label} {orderBy === headCell.id ? ( <span className={classes.visuallyHidden}> {order === 'desc' ? 'sorted descending' : 'sorted ascending'} </span> ) : null} </TableSortLabel> </TableCell> ))} </TableRow> </TableHead> ); } export default function EnhancedTable() { const classes = useStyles(); const [order, setOrder] = React.useState<Order>('asc'); const [orderBy, setOrderBy] = React.useState<keyof TableData>('id'); const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(10); const handleRequestSort = (event: React.MouseEvent<unknown, MouseEvent>, property: keyof TableData) => { event.preventDefault(); const isAsc = orderBy === property && order === 'asc'; setOrder(isAsc ? 'desc' : 'asc'); setOrderBy(property); }; const handleChangePage = (event: React.MouseEvent<HTMLButtonElement, MouseEvent> | null, newPage: number) => { event && event.preventDefault(); setPage(newPage); }; const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <div className={classes.root}> <Paper className={classes.paper}> <TableContainer> <Table stickyHeader className={classes.table} aria-labelledby="tableTitle" size={'small'} aria-label="datatable" > <THeader classes={classes} order={order} orderBy={orderBy} onRequestSort={handleRequestSort} /> <TableBody> {stableSort(rows, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row) => { return ( <TableRow hover tabIndex={-1} key={row.id} > <TableCell align="left">{row.id}</TableCell> <TableCell align="left">{row.location}</TableCell> <TableCell align="left">{row.type}</TableCell> <TableCell align="left">{row.device_health}</TableCell> <TableCell align="left">{row.last_used}</TableCell> <TableCell align="left">{row.price}</TableCell> </TableRow> ); })} </TableBody> </Table> </TableContainer> <TablePagination rowsPerPageOptions={[10, 25, 100]} component="div" count={rows.length} rowsPerPage={rowsPerPage} page={page} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} /> </Paper> </div> ); }
--- title: "回溯法" date: 2024-03-09T16:56:42+08:00 draft: true --- # 40.组合总和II 力扣题目链接 (opens new window) 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。 说明: 所有数字(包括目标数)都是正整数。解集不能包含重复的组合。 示例 1: 输入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 示例 2: 输入: candidates = [2,5,2,1,2], target = 5, 所求解集为: [ [1,2,2], [5] ] ## 思考 这里,要求无重复的组合,因此需要进行去重,而回溯法时间复杂度非常高,排序是的时间复杂度相对低,通过排序使得数据有序即可根据前后元素(nums[i] == nums[i - 1])是否一样进行排除。 原题目通过used数组进行标识,标识的是前面的元素是在上一层使用过还是当前层使用过。如果是上一层使用过,那么就可以将当前元素加入,但是如果是同一层使用,那说明同一层的其他地方会加入一次这个元素,而当前仍然会加入这个元素,因此会重复。因此通过used[i - 1] = false能够知道当前这一层使用。 但是另一个思路其实可以是,从当前起始的下一个元素开始往前对比,因为当前层开始的元素到当前元素都是当前层使用的数字,因此可以去重。 used[i - 1] = false与true的不同点,在于false用于判定前面的元素是没有被前一层使用的,那一定是当前层使用了,而且false是默认值,因此可以去重,所有相同的连续元素只会取一次。而等于true意味着,上一层使用了前面这个,这个用于保证同一个序列不会多次使用。
// import React from "react"; import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import categories from "./categories"; const schema = z.object({ description: z .string({ invalid_type_error: "description is required" }) .min(3, { message: "Description should be greater than 3 words" }) .max(20), amount: z.number({ invalid_type_error: "Amount is required" }).min(1), categories: z.enum(categories, { errorMap: () => ({ message: "Please select a category" }), }), }); type ExpenseFormData = z.infer<typeof schema>; interface Props { onAddExpense: (expense: ExpenseFormData) => void; } const ExpenseDisplay = ({ onAddExpense }: Props) => { const { register, reset, handleSubmit, formState: { errors }, } = useForm<ExpenseFormData>({ resolver: zodResolver(schema) }); return ( <form onSubmit={handleSubmit((data) => { onAddExpense(data); reset(); })} > <div className="mb-3"> <label htmlFor="description" className="form-label"> Description </label> <input {...register("description")} id="description" type="text" className="form-control" /> {errors.description && ( <p className="text-danger">{errors.description.message}</p> )} </div> <div className="mb-3"> <label htmlFor="amount" className="form-label"> Amount </label> <input {...register("amount", { valueAsNumber: true })} id="amount" type="number" className="form-control" /> {errors.amount && ( <p className="text-danger">{errors.amount.message}</p> )} </div> <div className="mb-3"> <label htmlFor="categories-1" className="form-label"> Categories </label> <select {...register("categories")} name="categories" id="categories-1" className="form-select" > <option value="">All Categories</option> {categories.map((category) => ( <option key={category} value={category}> {category} </option> ))} </select> {errors.categories && ( <p className="text-danger">{errors.categories.message}</p> )} </div> <div className="mb-3"> <button className="btn btn-primary">Submit</button> </div> </form> ); }; export default ExpenseDisplay;
import QueryBuilder from '../util/QueryBuilder'; import Database from '../util/database'; interface IFields { register?: string; filter?: string; orderBy?: string; } export class Representation { constructor( private id: number = 0, private register: string = '', private unity: string = '', private personId: number = 0, ) {} getId = () => this.id; getRegister = () => this.register; getUnity = () => this.unity; getPersonId = () => this.personId; save = async (): Promise<number> => { if ( this.id != 0 || this.unity.trim() === '' || this.register.trim() === '' || this.personId == 0 ) return -5; let result = 0; const parameters = [this.register, this.unity, this.personId]; const query = new QueryBuilder() .insert('representacao', 'rep_cadastro, rep_unidade, pj_id', '?,?,?') .build(); result = await Database.instance.insert(query, parameters); return Number.parseInt(result.toString()); }; update = async (params: any): Promise<number> => { if (this.id <= 0 || params.unity.trim() === '') return -5; let result = 0; const parameters = [params.unity, this.id]; const query = new QueryBuilder() .update('representacao') .set('rep_unidade = ?') .where('rep_id = ?') .build(); result = await Database.instance.update(query, parameters); return Number.parseInt(result.toString()); }; delete = async (): Promise<number> => { if (this.id <= 0) return -5; let result = 0; const query = new QueryBuilder().delete('representacao').where('rep_id = ?').build(); result = await Database.instance.delete(query, [this.id]); return result; }; findOne = async (id: number): Promise<Representation | undefined> => { if (id <= 0) return undefined; const query = new QueryBuilder() .select('*') .from('representacao') .where('rep_id = ?') .build(); const rows = await Database.instance.select(query, [id]); if (rows.length == 0) return undefined; const row = rows[0]; return new Representation(row.rep_id, row.rep_cadastro, row.rep_unidade, row.pj_id); }; find = async (fields?: IFields): Promise<Representation[]> => { const representations: Representation[] = []; const parameters = []; let builder = new QueryBuilder() .select(`r.rep_id, r.rep_cadastro, r.rep_unidade, r.pj_id`) .from('representacao r') .innerJoin('pessoa_juridica p') .on('p.pj_id = r.pj_id') .innerJoin('contato ct') .on('ct.ctt_id = p.ctt_id'); if (fields) { if (fields.filter && fields.register) { parameters.push(`%${fields.filter}%`, `%${fields.filter}%`, fields.register); builder = builder .where('(p.pj_nome_fantasia like ? or ct.ctt_email like ?)') .and('r.rep_cadastro = ?'); } if (fields.filter) { parameters.push(`%${fields.filter}%`, `%${fields.filter}%`); builder = builder.where('p.pj_nome_fantasia like ?').or('ct.ctt_email like ?'); } if (fields.register) { parameters.push(fields.register); builder = builder.where('r.rep_cadastro = ?'); } if (fields.orderBy) builder = builder.orderBy(fields.orderBy); } const query = builder.build(); const rows = await Database.instance.select(query, parameters); for (const row of rows) { representations.push( new Representation(row.rep_id, row.rep_cadastro, row.rep_unidade, row.pj_id), ); } return representations; }; }
import React, { useEffect } from "react"; import styled from "styled-components"; const ModalContainer = styled.div` position: relative; `; const ModalBackdrop = styled.div` position: fixed; display: flex; justify-content: center; width: 500px; margin: 0 auto; background: rgba(0, 0, 0, 0.2); align-items: center; height: 100vh; z-index: 1000; `; const ModalView = styled.div` position: fixed; background-color: white; padding: 50px; z-index: 2; border: 1px solid white; border-radius: 20px; display: flex; flex-direction: column; form { margin: 40px auto; display: flex; flex-direction: column; .modal__btn--submit { background: skyblue; border-radius: 20px; border: none; width: 50px; margin: 10px auto 0; padding: 10px; border-radius: 20px; cursor: pointer; } } .modal__btn--off { position: absolute; top: 5px; right: 5px; border: none; font-size: 1.5rem; border-radius: 20px; margin: 0 auto; cursor: pointer; } `; export type Props = { onClick: () => void; todoId: string; removeTodoHandler: (todoId: string) => void; }; const SureToRemoveModal: React.FC<Props> = ({ onClick, todoId, removeTodoHandler }) => { const submitFunction = (e: React.FormEvent) => { e.preventDefault(); removeTodoHandler(todoId); }; return ( <> <ModalContainer> <ModalBackdrop onClick={onClick}> <ModalView onClick={(e) => { e.stopPropagation(); }} > <form onSubmit={(e) => submitFunction(e)}> <div>계획을 삭제하시겠습니까??</div> <button className="modal__btn--submit" type="submit" onKeyUp={(e) => console.log(e.key)}> 확인 </button> </form> <button className="modal__btn--off" onClick={onClick}> &times; </button> </ModalView> </ModalBackdrop> </ModalContainer> </> ); }; export default SureToRemoveModal;
import { useState, useEffect } from "react" import Formulario from "./components/Formulario" import Header from "./components/Header" import ListadoPacientes from "./components/ListadoPacientes" function App() { const [pacientes, setPacientes] = useState([]) const [paciente, setPaciente] = useState({}) useEffect(() => { const localpacientes = JSON.parse(localStorage.getItem('pacientes')) ?? [] console.log(localpacientes) if(localpacientes.length > 0) setPacientes(localpacientes) }, []) useEffect(() => { localStorage.setItem('pacientes', JSON.stringify(pacientes)) }, [pacientes]) const eliminarPaciente = id => { const pacientesActu = pacientes.filter(paciente => paciente.id !== id) setPacientes(pacientesActu) } return ( <div className="container mx-auto mt-20"> <Header /> <div className="mt-12 md:flex"> <Formulario pacientes = { pacientes } setPacientes={ setPacientes } paciente={ paciente } setPaciente={ setPaciente } /> <ListadoPacientes pacientes={ pacientes } setPaciente={ setPaciente } eliminarPaciente={ eliminarPaciente } /> </div> </div> ) } export default App
<!DOCTYPE html> <html lang="nl"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>Announcer</title> </head> <body> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand" href="#">Announcer System</a> <form class="form-inline"> <button onclick="stop();" class="btn btn-danger my-2 my-sm-0" type="submit">Stop</button> </form> </nav> <br><br><br> <div class="container"> <div class="card"> <div class="card-header"> Announcer </div> <div class="card-body"> <h5 class="card-title"></h5> <div class="card-text"> <div class="input-group mb-3"> <input id="tts_text" type="text" class="form-control" placeholder="Text..."> <div class="input-group-append"> <button onclick="play(document.getElementById('tts_text').value);" class="btn btn-outline-secondary" type="button" id="button-addon2">Play</button> </div> </div> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Say a template (you can set that in templates.json) </button> <div id="combobox" class="dropdown-menu" aria-labelledby="dropdownMenuButton"> </div> </div> </div> </div> </div> </div> <script> function play(text) { XMLsend("/play/" + text); } function stop() { XMLsend("/Stop"); } function XMLsend(url) { let xhttp = new XMLHttpRequest(); xhttp.open("GET", url, true); xhttp.send(); } function templates() { let url = '/templates'; fetch(url) .then(res => res.json()) .then((out) => { out.Default_lines.forEach(element => { addtoCombobox("<a class=\"dropdown-item\" onclick=\"XMLsend('/play/" + element + "');\">" + element + "</a>"); }); }) } function addtoCombobox(text){ document.getElementById("combobox").innerHTML = document.getElementById("combobox").innerHTML + text; } templates(); </script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script> </body> </html>
import { useState } from 'react'; import type { FormEventHandler, ChangeEventHandler } from 'react'; import { GlobalContext } from "@context/GlobalContext"; import { GlobalProviderTypes, ContactForm } from './types'; import axios from 'axios'; const initialState = { name: "", email: "", message: "" } const GlobalProvider = ({children}: GlobalProviderTypes ) => { const [menuBtn, setMenuBtn] = useState(false); const [input, setInput] = useState<ContactForm>(initialState); const [success, setSuccess] = useState(false); const [loading, setLoading] = useState(false); class Check { private name: string; private email: string; private message: string; constructor(name: string, email: string, message: string) { this.name = name; this.email = email; this.message = message; } protected validate() { const nameValue = this.name.trim(); const emailValue = this.email.trim(); const messageValue = this.message.trim(); let result = true; if (!nameValue) { this.messageNotification('Enter a name'); result = false; } else if (!this.regexName(nameValue)) { this.messageNotification('The "Name" field only accepts letters and spaces.'); result = false; } if (!emailValue) { this.messageNotification('Enter an email'); result = false; } else if (!this.isEmail(emailValue)) { this.messageNotification('The "Mail" field contains an invalid format.'); result = false; } if (!messageValue) { this.messageNotification('Enter a Message'); result = false; } else if (!this.regexMessage(messageValue)) { this.messageNotification('The "Message" field only accepts letters and spaces.'); result = false; } return result; } private messageNotification(message: string) { const small: HTMLElement | null = document.querySelector('small') ; small!.innerHTML = message; setTimeout(() => {small!.innerText = ""; }, 3000); } private regexName(name: string): boolean { return /^[A-Za-zÑñÁáÉéÍíÓóÚúÜü\s]+$/.test(name); } private isEmail(email: string): boolean { return /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(email); } private regexMessage(message: string): boolean { return /^.{1,255}$/.test(message); } protected onSubmit: FormEventHandler<HTMLFormElement> | undefined = async (event) => { event.preventDefault(); try { if(this.validate()) { setLoading(true) axios.defaults.headers.post['Content-Type'] = 'application/json'; await axios.post('https://formsubmit.co/ajax/[email protected]', { name: this.name, email: this.email, message: this.message }) setSuccess(true) this.messageNotification('Tu mensaje ha sido enviado correctamente'); setLoading(false) setTimeout(() => { window.location.href = 'https://chendo.dev' }, 3000); } else { setSuccess(false) throw new Error("Error from send email"); } } catch (error) { console.log(error) } } protected onChange: ChangeEventHandler<HTMLInputElement> = (event) => { const { name, value } = event.target; setInput({ ...input, [name]: value }) } } const { name, email, message } = input; let check = new Check(name, email, message); const valueContext = { setMenuBtn, menuBtn, setInput, success, loading, check, name, email, message } return ( <GlobalContext.Provider value={valueContext}> {children} </GlobalContext.Provider> ) } export {GlobalProvider};
// Copyright 2021 Datafuse Labs // // 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. use std::time::Duration; use arrow_array::RecordBatch; use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::encode::FlightDataEncoderBuilder; use arrow_flight::flight_service_client::FlightServiceClient; use arrow_flight::FlightDescriptor; use arrow_select::concat::concat_batches; use databend_common_exception::ErrorCode; use databend_common_exception::Result; use futures::stream; use futures::StreamExt; use futures::TryStreamExt; use tonic::transport::channel::Channel; use tonic::transport::Endpoint; use tonic::Request; use crate::types::DataType; use crate::DataSchema; const UDF_TCP_KEEP_ALIVE_SEC: u64 = 30; const UDF_HTTP2_KEEP_ALIVE_INTERVAL_SEC: u64 = 60; const UDF_KEEP_ALIVE_TIMEOUT_SEC: u64 = 20; // 4MB by default, we use 16G // max_encoding_message_size is usize::max by default const MAX_DECODING_MESSAGE_SIZE: usize = 16 * 1024 * 1024 * 1024; #[derive(Debug, Clone)] pub struct UDFFlightClient { inner: FlightServiceClient<Channel>, batch_rows: u64, } impl UDFFlightClient { #[async_backtrace::framed] pub async fn connect( addr: &str, conn_timeout: u64, request_timeout: u64, batch_rows: u64, ) -> Result<UDFFlightClient> { let endpoint = Endpoint::from_shared(addr.to_string()) .map_err(|err| { ErrorCode::UDFServerConnectError(format!("Invalid UDF Server address: {err}")) })? .connect_timeout(Duration::from_secs(conn_timeout)) .timeout(Duration::from_secs(request_timeout)) .tcp_keepalive(Some(Duration::from_secs(UDF_TCP_KEEP_ALIVE_SEC))) .http2_keep_alive_interval(Duration::from_secs(UDF_HTTP2_KEEP_ALIVE_INTERVAL_SEC)) .keep_alive_timeout(Duration::from_secs(UDF_KEEP_ALIVE_TIMEOUT_SEC)) .keep_alive_while_idle(true); let inner = FlightServiceClient::connect(endpoint) .await .map_err(|err| { ErrorCode::UDFServerConnectError(format!( "Cannot connect to UDF Server {}: {:?}", addr, err )) })? .max_decoding_message_size(MAX_DECODING_MESSAGE_SIZE); Ok(UDFFlightClient { inner, batch_rows }) } fn make_request<T>(&self, t: T) -> Request<T> { Request::new(t) } #[async_backtrace::framed] pub async fn check_schema( &mut self, func_name: &str, arg_types: &[DataType], return_type: &DataType, ) -> Result<()> { let descriptor = FlightDescriptor::new_path(vec![func_name.to_string()]); let request = self.make_request(descriptor); let flight_info = self.inner.get_flight_info(request).await?.into_inner(); let schema = flight_info .try_decode_schema() .map_err(|err| ErrorCode::UDFDataError(format!("Decode UDF schema error: {err}"))) .and_then(|schema| DataSchema::try_from(&schema))?; let fields_num = schema.fields().len(); if fields_num == 0 { return Err(ErrorCode::UDFSchemaMismatch( "UDF Server should return at least one column", )); } let (input_fields, output_fields) = schema.fields().split_at(fields_num - 1); let expect_arg_types = input_fields .iter() .map(|f| f.data_type().clone()) .collect::<Vec<_>>(); let expect_return_type = output_fields .iter() .map(|f| f.data_type().clone()) .collect::<Vec<_>>(); if expect_arg_types != arg_types { return Err(ErrorCode::UDFSchemaMismatch(format!( "UDF arg types mismatch, actual arg types: ({:?})", expect_arg_types .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(", ") ))); } if &expect_return_type[0] != return_type { return Err(ErrorCode::UDFSchemaMismatch(format!( "UDF return type mismatch, actual return type: {}", expect_return_type[0] ))); } Ok(()) } #[async_backtrace::framed] pub async fn do_exchange( &mut self, func_name: &str, input_batch: RecordBatch, ) -> Result<RecordBatch> { let descriptor = FlightDescriptor::new_path(vec![func_name.to_string()]); let batch_rows = self.batch_rows as usize; let batches = (0..input_batch.num_rows()) .step_by(batch_rows) .map(move |start| { Ok(input_batch.slice(start, batch_rows.min(input_batch.num_rows() - start))) }); let flight_data_stream = FlightDataEncoderBuilder::new() .with_flight_descriptor(Some(descriptor)) .build(stream::iter(batches)) .map(|data| data.unwrap()); let request = self.make_request(flight_data_stream); let flight_data_stream = self.inner.do_exchange(request).await?.into_inner(); let record_batch_stream = FlightRecordBatchStream::new_from_flight_data( flight_data_stream.map_err(|err| err.into()), ) .map_err(|err| ErrorCode::UDFDataError(format!("Decode record batch error: {err}"))); let batches: Vec<RecordBatch> = record_batch_stream.try_collect().await?; if batches.is_empty() { return Err(ErrorCode::EmptyDataFromServer( "Get empty data from UDF Server", )); } let schema = batches[0].schema(); concat_batches(&schema, batches.iter()) .map_err(|err| ErrorCode::UDFDataError(err.to_string())) } }
import React from 'react'; import './Login.css'; import {useState, useEffect, Fragment} from "react"; import {Navigate } from 'react-router-dom'; export default function Login({refreshNavbar}) { const [type, setType] = useState("login"); const [error, setError] = useState(false); const [username, setUsername] = useState(""); const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [email, setEmail] = useState(""); const [pass1, setPass1] = useState(""); const [pass2, setPass2] = useState(""); const [userIsAuth, setAuth] = useState(false); const changeType = (event) => { event.preventDefault(); if(type === "login") { setType("signup"); } else if(type === "signup"){ setType("login"); } } const changeErrorValue = () => { if(error) { setError(false); } else { setError(true); } } const handleLoginSubmit = async(e) => { e.preventDefault(); const postObject = { email: email, password: pass1 } console.log(`postObject is ${postObject}`); if(type === "login") { let response = await fetch('https://virewade-node-backend.onrender.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postObject) } ) if(response.ok){ let json = await response.json() console.log('works like ' + JSON.stringify(json)); localStorage.setItem('user', JSON.stringify(json)); sessionStorage.removeItem('discog-token') sessionStorage.removeItem('spotify-token'); refreshNavbar(true); setAuth(true); }else { changeErrorValue() } } } const handleSignupSubmit = async(e) => { e.preventDefault(); console.log(`${username} ${email} ${pass1}`); if(type === "signup") { if(!pass1 || !pass2 || pass1 !== pass2){ changeErrorValue(); } const postObject = { firstName: firstName, lastName: lastName, email: email, password: pass1 } let response = await fetch("https://virewade-node-backend.onrender.com/register", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postObject) }) if(response.ok){ let json = await response.json() console.log('works like ' + JSON.stringify(json)); localStorage.setItem('user', JSON.stringify(json)); sessionStorage.removeItem('discog-token') sessionStorage.removeItem('spotify-token'); refreshNavbar(true); setAuth(true); }else { changeErrorValue() } } } // const validateSession = async () => { // const existingSession = localStorage.getItem('user') // if(existingSession){ // const {sessionToken, userId} = JSON.parse(existingSession); // if(userId) { // const result = await fetch(`https://virewade-node-backend.onrender.com/session/validate/${userId}`, { // method: 'POST', // headers: { // 'Content-Type': 'application/json' // }, // body: JSON.stringify({ // sessionToken // }) // }); // const JSONresult = await result.json(); // if(JSONresult.status === 'success'){ // setAuth(true); // } // } // } // }; // useEffect(() => { // validateSession(); // },[]); useEffect(() => { if( window.location.pathname === "/register" && type === 'login') { setType("signup"); } },[]); return( <Fragment> { userIsAuth? <Navigate to="/" replace={true}/> : ( <div className="grid"> <div className="container"> <div className="leftContainer"> <h2 className="subtitle">VireWade</h2> </div> <div className="rightContainer"> {error ? <div className="containerChild error-text"> <p >Incorrect email and/or password</p> </div> :null } <form onSubmit={type === 'login' ? handleLoginSubmit : handleSignupSubmit} > {type === "signup" ? (<> {/* <input type="text" className="containerChild" name="username" id="username" placeholder="Type your username" value={username} onChange={e => setUsername(e.target.value)} required/> */} <input type="text" className="containerChild" name="firstName" id="firstName" placeholder="Type your first name" value={firstName} onChange={e => setFirstName(e.target.value)} required/> <input type="text" className="containerChild" name="lastName" id="lastName" placeholder="Type your last name" value={lastName} onChange={e => setLastName(e.target.value)} required/> </> ) : null } {type === "signup" ?<input type="email" className="containerChild" name="email" id="email" placeholder="Type your email" value={email} onChange={e => setEmail(e.target.value)} required /> :<input type="email" className="containerChild" name="email" id="email" placeholder="Type your email" value={email} onChange={e => setEmail(e.target.value)} required/> } <input type="password" name="password" id="password" className="containerChild" placeholder="Type your password" value={pass1} onChange={e => setPass1(e.target.value)} required/> {type === "signup" ? <input type="password" name="password" id="password" className="containerChild" value={pass2} placeholder="Retype your password" onChange={e => setPass2(e.target.value)} required/> : null } {type === "login" ? <div> <button type="submit" className="login containerChild" onClick={handleLoginSubmit}> Log In </button> <button className="containerChild" onClick={changeType}>Sign Up</button> </div> : <div> <button type="submit" className="containerChild" onClick={changeErrorValue}>Sign Up</button> <button className="containerChild" onClick={(e) => {changeType(e) }}>Return to Log In</button> </div> } </form> </div> </div> </div> ) } </Fragment> ); }
import React, { useState, useEffect } from 'react'; import { FaPaperclip } from 'react-icons/fa'; import { supabase } from '../supabaseClient'; import { v4 as uuidv4 } from 'uuid'; import '../Chat.css'; const API_URL = "https://api-inference.huggingface.co/models/gpt2"; const headers = { "Authorization": "Bearer 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" }; async function query(payload) { const response = await fetch(API_URL, { headers: headers, method: "POST", body: JSON.stringify(payload), }); const result = await response.json(); return result; } function Chat({ session }) { const [input, setInput] = useState(''); const [messages, setMessages] = useState([]); const [isTyping, setIsTyping] = useState(false); const generateId = () => { return uuidv4(); }; const handleClick = async () => { if (input.trim() !== '') { setIsTyping(true); const userId = generateId(); const newMessage = { text: input, created_at: new Date().toISOString(), user_id: userId, }; // Save the user's message in the Supabase database const { error } = await supabase .from('chat') .insert([newMessage]); if (error) { console.error('Error saving message:', error); } // Generate the chatbot's response const response = await query({ "inputs": input }); const generated_text = response[0].generated_text.replace(/\\/g, '').split('\n').map((line, index) => <div key={index}>{line}</div>); // Add the user's message and the chatbot's response to the messages state setMessages(prevMessages => [...prevMessages, { text: input, position: 'right' }, { text: generated_text, position: 'left' }]); // Clear the input setInput(''); setIsTyping(false); } }; const handleKeyPress = (event) => { if(event.key === 'Enter'){ handleClick(); } } const handleFileUpload = async (event) => { const file = event.target.files[0]; console.log(file); const fileExtension = file.name.split('.').pop(); const fileName = `${generateId()}.${fileExtension}`; const { data, error } = await supabase .storage .from('codepay') .upload(fileName, file, { cacheControl: '3600', upsert: false }); if (error) { console.error('Error uploading file:', error); } else { console.log('File uploaded successfully'); } }; useEffect(() => { if (input.length > 0) { setIsTyping(true); } else { setIsTyping(false); } }, [input]); return ( <div className="chat-container"> <div className="chat-header"> <img src='./codepay.png' alt="Logo" className="chat-logo" /> <h1>CodePay Chat</h1> </div> <div className="chat-messages"> <div className="chat-labels"> <div><span role="img" aria-label="robot">🤖</span> AI</div> <div> <span role="img" aria-label="user">�</span> {session && session.root ? session.root.email : 'Anonymous'} </div> </div> {messages.map((message, index) => ( <div key={index} className={`chat-message ${message.position}`}> {message.text} <div className="chat-timestamp">{message.timestamp}</div> </div> ))} {isTyping && <div className="typing-indicator">Typing...</div>} </div> <div className="chat-inputs"> <label htmlFor="file-upload" className="file-upload-label"> <FaPaperclip size={30} /> </label> <input id="file-upload" type="file" accept=".csv,audio/*" onChange={handleFileUpload} className="file-upload-input" /> <input type="text" value={input} onChange={e => setInput(e.target.value)} onKeyPress={handleKeyPress} className="chat-text-input" /> <button onClick={handleClick} className="send-button">Send</button> </div> </div> ); } export default Chat;
# install package “VIM” # install.packages("VIM") # To use the package in an R session, we need to load it in an R session via library(VIM) # Load dataset “sleep”, which comes within the package “VIM” data(sleep, package = "VIM") # call function head() to get a feeling about data, or call sleep to see all values head(sleep) # download package “mice” and load it into R # install.packages("mice") library(mice) # install tidyverse # install.packages("tidyverse") library("tidyverse") # there are 62 rows with data nrow(sleep) # there are 42 rows from the sleep column with complete data (i.e. each row does not contain missing data) # I don't like that the object is named sleep and there is also a column named "sleep" sleep[complete.cases(sleep),] %>% nrow() # note that packages are case sensitive VIM::aggr(sleep, prop = FALSE, numbers = TRUE) # vim:aggr does not work ?aggr # call function marginplot (), pch indicates notation of obs, col tells R how you # would like to see results in different color marginplot(sleep[c("Gest", "Dream")], pch = c(20), col = c("darkgray","red","blue")) boxplot(mpg ~ cyl, data = mtcars, col = "grey", main = "Mileage Data", ylab = "MPG", xlab = "Number of Cylinders") # install.packages("vioplot") library(vioplot) v1 <- mtcars$mpg[mtcars$cyl == 4] v2 <- mtcars$mpg[mtcars$cyl == 6] v3 <- mtcars$mpg[mtcars$cyl == 8] # what is the data type? typeof(v1) # what does this object contain? str(v1) str(v2) str(v3) # draw violin plots for vectors vioplot(v1, v2, v3, names = c("4 cyl", "6 cyl", "8 cyl"), col = "gold") #--------------# # Neural Networks #--------------# # install.packages("ISLR") library("ISLR") # install.packages("neuralnet") library(neuralnet) # install.packages("caTools) library("caTools") head(College, 2) tidyr::tibble(College) maxs <- apply(College[,2:18], 2, max) mins <- apply(College[,2:18], 2, min) scaled_data <- as.data.frame( scale(College[,2:18], center = mins, scale = maxs) ) tidyr::tibble(scaled_data) Private = as.numeric(College$Private) - 1 data = cbind(Private, scaled_data) set.seed(101) # split the data into train and test sets split = caTools::sample.split(data$Private, SplitRatio = 0.70) train = subset(data, split == TRUE) test = subset(data, split == FALSE) feats <- names(scaled_data) f <- paste(feats, collapse = ' + ') f <- paste("Private ~", f) f <- as.formula(f) nn <- neuralnet::neuralnet(f, train, hidden = c(10, 10, 10), linear.output = FALSE) predicted_nn_values <- neuralnet::compute(nn, test[,2:18]) tidyr::tibble(predicted_nn_values$net.result) predicted_nn_values$net.result <- sapply(predicted_nn_values$net.result, round, digits = 0) table(test$Private, predicted_nn_values$net.result) plot(nn)
import { UseGuards } from '@nestjs/common'; import { Args, Context, Mutation, Parent, Query, ResolveField, Resolver, Subscription, } from '@nestjs/graphql'; import * as DataLoader from 'dataloader'; import { PubSub } from 'graphql-subscriptions'; import { ValidatorPaginationParamsPipe } from 'src/shared/http/pipes/ValidatorPaginationParams.pipe'; import { PaginationInput, PaginationOutput, } from '~shared//http/pipes/PaginationInput'; import { Roles } from '~shared/decorators/Roles.decorator'; import { JwtAuthGuard } from '~shared/guards/JwtAuth.guard'; import { RolesGuard } from '~shared/guards/Roles.guard'; import { ValidatorAmericanDateFormatParamPipe } from '~shared/http/pipes/ValidatorAmericanDateFormatParam.pipe'; import { AuthPermissions } from '~shared/modules/auth/infra/abstracts/Auth'; import { CreateAppointmentUseCase } from '~modules/appointments/useCases/createAppointment/CreateAppointment.useCase'; import { FindAppointmentsByTeacherIdAndPeriodUseCase } from '~modules/appointments/useCases/findAppointmentsByTeacherAndPeriod/FindAppointmentsByTeacherAndPeriod.useCase'; import { FindAppointmentsByTeacherIdAndDateUseCase } from '~modules/appointments/useCases/findAppointmentsByTeacherIdAndDate/FindAppointmentsByTeacherIdAndDate.useCase'; import { ClassInterface } from '~modules/classes/infra/graphql/interfaces/ClassInterface'; import { Class } from '~modules/classes/infra/typeorm/entities/Class'; import { TeacherInterface } from '~modules/teachers/infra/graphql/interfaces/TeacherInterface'; import { CreateAppointmentInput } from '../inputs/CreateAppointment.input'; import { AppointmentAndTotalInterface } from '../interfaces/AppointmentAndTotalInterface'; import { AppointmentInterface } from '../interfaces/AppointmentInterface'; const pubSub = new PubSub(); @Resolver(() => AppointmentInterface) class AppointmentsResolver { constructor( private createAppointmentUseCase: CreateAppointmentUseCase, private findAppointmentsByTeacherIdAndDateUseCase: FindAppointmentsByTeacherIdAndDateUseCase, private findAppointmentsByTeacherIdAndPeriodUseCase: FindAppointmentsByTeacherIdAndPeriodUseCase, ) {} @Roles(AuthPermissions.ADMIN, AuthPermissions.TEACHER) @UseGuards(RolesGuard) @UseGuards(JwtAuthGuard) @Mutation(() => AppointmentInterface) async createAppointment( @Args('input') input: CreateAppointmentInput, ): Promise<AppointmentInterface> { const appointment = await this.createAppointmentUseCase.execute(input); pubSub.publish('appointmentAdded', { appointmentAdded: appointment }); return appointment; } @UseGuards(JwtAuthGuard) @Query(() => AppointmentAndTotalInterface) async getAppointmentsByTeacherIdAndDate( @Args('teacher_id') teacher_id: string, @Args( { name: 'date', description: 'format YYYY-MM-DD' }, ValidatorAmericanDateFormatParamPipe, ) date: string, @Args( { name: 'pagination', nullable: true, type: () => PaginationInput }, ValidatorPaginationParamsPipe, ) paginate: PaginationOutput, ): Promise<AppointmentAndTotalInterface> { const appointments = await this.findAppointmentsByTeacherIdAndDateUseCase.execute( teacher_id, date, paginate, ); return appointments; } @UseGuards(JwtAuthGuard) @Query(() => [AppointmentInterface]) async getAppointmentsByTeacherIdAndPeriod( @Args('teacher_id') teacher_id: string, @Args( { name: 'initial_date', description: 'format YYYY-MM-DD' }, ValidatorAmericanDateFormatParamPipe, ) initial_date: string, @Args( { name: 'final_date', description: 'format YYYY-MM-DD' }, ValidatorAmericanDateFormatParamPipe, ) final_date: string, ): Promise<AppointmentInterface[]> { const appointments = await this.findAppointmentsByTeacherIdAndPeriodUseCase.execute( teacher_id, initial_date, final_date, ); return appointments; } @ResolveField('class', () => ClassInterface) async class( @Parent() appointment: AppointmentInterface, @Context('ClassesLoader') classesLoader: DataLoader<string, Class>, ): Promise<Class> { const classes = await classesLoader.load(appointment.class_id); return classes; } @ResolveField('responsible', () => TeacherInterface) async responsible( @Parent() appointment: AppointmentInterface, @Context('TeachersLoader') teachersLoader: DataLoader<string, TeacherInterface>, ): Promise<TeacherInterface> { const teachers = await teachersLoader.load(appointment.responsible_id); return teachers; } @Subscription(() => [AppointmentInterface]) // add subscription filter appointmentAdded(): AsyncIterator<AppointmentInterface> { return pubSub.asyncIterator('appointmentAdded'); } } export { AppointmentsResolver };
#' About Server #' #' @param id identifier for shiny reactive #' @param helppath path to help markdown #' #' @return reactive server #' @export aboutServer <- function(id, helppath = NULL) { shiny::moduleServer(id, function(input, output, session) { ns <- session$ns output$about <- shiny::renderUI({ if(!is.null(helppath) && helppath != "" && file.exists(helppath)) { datainfo <- shiny::includeMarkdown(helppath) } else { datainfo <- shiny::includeMarkdown( system.file(file.path("shinyApp", "help.md"), package='foundrShiny')) } tagList( shiny::includeMarkdown( system.file(file.path("shinyApp", "intro.md"), package='foundrShiny')), "See GitHub:", shiny::a(paste("byandell/foundrShiny", paste0("(version ", utils::packageVersion("foundrShiny"), "); ")), href = "https://github.com/byandell/foundrShiny"), shiny::a(paste("byandell/foundr", paste0("(version ", utils::packageVersion("foundr"), ")")), href = "https://github.com/byandell/foundr"), shiny::br(), shiny::br(), datainfo) }) }) } #' @export #' @rdname aboutServer aboutOutput <- function(id) { ns <- shiny::NS(id) shiny::uiOutput(ns("about")) } #' @export #' @rdname aboutServer aboutApp <- function(id) { ui <- shiny::bootstrapPage( aboutOutput("about") ) server <- function(input, output, session) { aboutServer("about", helppath = customSettings$help) } shiny::shinyApp(ui, server) }
#!/usr/bin/python3 """ This module contains the class Student """ class Student: """ Simple class representing student information Attributes: first_name (str): student's fist name last_name (str): student's last name age (int): student's age """ def __init__(self, first_name, last_name, age): """ Class object initializer Args: first_name (str): item to set to first name att last_name (str): item to set to last name att age (int): value to set to age """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """ retrieves a dictionary representation of a Student Args: attrs (list): list of attribute to be returned """ if attrs: json = {} for i in attrs: if i in self.__dict__.keys(): json.append(self.__dict__) return json return self.__dict__
using System.Collections.Generic; namespace Quality2.Exceptions { public class CustomException: Exception { public List<string> Errors { get; private set;} public CustomException(string message) : base(message) { Errors = new List<string> { message }; } public CustomException(string message, IEnumerable<string> errors) : base(message) { Errors = errors.ToList(); } } public class BadRequestException: CustomException { public BadRequestException(string message, IEnumerable<string> errors) : base(message, errors) { } public BadRequestException(string message) : base(message) { } } public class NotFoundException : CustomException { public NotFoundException(string message) : base(message) { } } }
import { Component, DoCheck, Input, OnDestroy, OnInit, inject } from "@angular/core"; import { ActivatedRoute, RouterLink } from "@angular/router"; import { Store } from "@ngrx/store"; import { booksByLibActions } from "../store/actions"; import { Subscription, combineLatest } from "rxjs"; import { selectBooksByLibData, selectIsLoading } from "../store/reducers"; import { CommonModule } from "@angular/common"; import { BooksByLibraryService } from "../service/booksByLibrary.service"; import { selectLinks } from "../../shared/component/navlink/store/reducers"; @Component({ selector:'bl-booksLib', templateUrl:'./booksByLibrary.html', styleUrls:['./booksByLibrary.component.scss'], standalone:true, imports: [CommonModule, RouterLink] }) export class BooksByLibraryComponent implements OnInit, OnDestroy{ private routeSubscription!: Subscription; store = inject(Store) service = inject(BooksByLibraryService) route = inject(ActivatedRoute) data$ = combineLatest({ isLoading : this.store.select(selectIsLoading), books: this.store.select(selectBooksByLibData), links: this.store.select(selectLinks), }) ngOnInit(): void { this.routeSubscription = this.route.paramMap.subscribe(params => { const id = params.get('libraryId') this.store.dispatch(booksByLibActions.getBooksByLib({libraryId: Number(id)})) }) } deleteBook(googleId: string){ this.routeSubscription = this.route.paramMap.subscribe(params => { const id = params.get('libraryId') console.log(id) if(id != null){ this.store.dispatch(booksByLibActions.deleteBooksFromLib({googleId: googleId, libraryId:+id})) } }) } ngOnDestroy(): void { if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } } }
import React from "react"; import { useFormStatus } from "react-dom"; import { FaPaperPlane } from "react-icons/fa"; const SubmitButton = () => { const { pending } = useFormStatus(); return ( <button type="submit" disabled={pending} className="group flex items-center bg-blue-950 text-white font-sans px-6 py-2 gap-2 shadow-md rounded-lg w-fit" > {pending ? ( <div className="animate-spin h-5 w-5 mr-3 rounded-full border-b-2 border-white"></div> ) : ( <> Send{" "} <FaPaperPlane className="text-xs opacity-70 transition-all group-hover:translate-x-1 group-hover:-translate-y-1" /> </> )} </button> ); }; export default SubmitButton;
from django.db.models import Q from django.utils import timezone from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import extend_schema, OpenApiParameter from rest_framework import mixins from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import GenericViewSet from content_management.models import ( Tender, Project, TeamMember, PartnerLogo, News, Contacts, PDFReport, DonorLogo, HeroSlider, AboutUs, ) from content_management.serializers import ( TenderSerializer, ProjectSerializer, TeamMemberSerializer, PartnerLogoSerializer, NewsSerializer, ContactsSerializer, PDFReportSerializer, DonorLogoSerializer, HeroSliderSerializer, AboutUsSerializer, ) class BasePagination(PageNumberPagination): max_page_size = 100 class DynamicPagination(PageNumberPagination): max_page_size = 100 page_size_query_param = "limit" def get_page_size(self, request): limit = request.query_params.get(self.page_size_query_param) if limit: try: return min(int(limit), self.max_page_size) except ValueError: pass return super().get_page_size(request) @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class TenderViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): queryset = Tender.objects.all() serializer_class = TenderSerializer def get_queryset(self): end_date = self.request.query_params.get("end_date", None) if end_date is not None: self.queryset.filter(end_date__lt=timezone.now()).update(is_active=False) queryset = super().get_queryset() is_active = self.request.query_params.get("is_active", None) is_shown = self.request.query_params.get("is_shown", None) if is_active is not None: queryset = queryset.filter( is_active=True if is_active.lower() == "true" else False ) if is_shown is not None: queryset = queryset.filter( is_shown=True if is_shown.lower() == "true" else False ) return queryset @extend_schema( parameters=[ OpenApiParameter( "is_active", type=OpenApiTypes.STR, description="Filter by is_active field true, false (ex. ?is_active=true)", ), OpenApiParameter( "is_shown", type=OpenApiTypes.STR, description="Filter by is_shown field true, false (ex. ?is_shown=true)", ), ] ) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class ProjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): queryset = Project.objects.all() serializer_class = ProjectSerializer def get_queryset(self): end_date = self.request.query_params.get("end_date", None) if end_date is not None: self.queryset.filter(end_date__lt=timezone.now()).update(is_active=False) queryset = super().get_queryset() is_active = self.request.query_params.get("is_active", None) is_shown = self.request.query_params.get("is_shown", None) if is_active is not None: queryset = queryset.filter( is_active=True if is_active.lower() == "true" else False ) if is_shown is not None: queryset = queryset.filter( is_shown=True if is_shown.lower() == "true" else False ) return queryset @extend_schema( parameters=[ OpenApiParameter( "is_active", type=OpenApiTypes.STR, description="Filter by is_active field true, false (ex. ?is_active=true)", ), OpenApiParameter( "is_shown", type=OpenApiTypes.STR, description="Filter by is_shown field true, false (ex. ?is_shown=true)", ), ] ) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ) ] ) class TeamMemberViewSet(mixins.ListModelMixin, GenericViewSet): queryset = TeamMember.objects.all() serializer_class = TeamMemberSerializer @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class PartnerLogoViewSet(mixins.ListModelMixin, GenericViewSet): queryset = PartnerLogo.objects.all() serializer_class = PartnerLogoSerializer @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class DonorLogoViewSet(mixins.ListModelMixin, GenericViewSet): queryset = DonorLogo.objects.all() serializer_class = DonorLogoSerializer @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class NewsViewSet(mixins.ListModelMixin, GenericViewSet): queryset = News.objects.all() serializer_class = NewsSerializer pagination_class = DynamicPagination @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class ContactsViewSet(mixins.ListModelMixin, GenericViewSet): queryset = Contacts.objects.all() serializer_class = ContactsSerializer @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class PDFReportView(mixins.ListModelMixin, GenericViewSet): queryset = PDFReport.objects.all() serializer_class = PDFReportSerializer @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class HeroSliderViewSet(mixins.ListModelMixin, GenericViewSet): queryset = HeroSlider.objects.all() serializer_class = HeroSliderSerializer @extend_schema( parameters=[ OpenApiParameter( name="Accept-Language", type=OpenApiTypes.STR, location=OpenApiParameter.HEADER, required=False, description="Language code to get the content in a specific language (e.g., en, uk)", enum=["en", "uk"], ), ] ) class AboutUsViewSet(mixins.ListModelMixin, GenericViewSet): queryset = AboutUs.objects.all() serializer_class = AboutUsSerializer
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, } from 'typeorm'; @Entity('files') export class File { @PrimaryGeneratedColumn({ name: 'id', type: 'int', }) id: number; @Column({ name: 'name', type: 'varchar' }) name: string; @Column({ name: 'path', type: 'varchar' }) path: string; @Column({ name: 'mimetype', type: 'varchar' }) mimetype: string; @CreateDateColumn({ nullable: true, name: 'created_at', type: 'timestamp', }) created_at: Date; @UpdateDateColumn({ nullable: true, name: 'updated_at', type: 'timestamp', }) updated_at: Date; }
import 'package:cipherx_expense_tracker_app/home/pages/expense_page.dart'; import 'package:cipherx_expense_tracker_app/home/pages/income_page.dart'; import 'package:cipherx_expense_tracker_app/home/providers/home_provider.dart'; import 'package:cipherx_expense_tracker_app/home/widgets/balance.dart'; import 'package:cipherx_expense_tracker_app/home/widgets/header.dart'; import 'package:cipherx_expense_tracker_app/home/widgets/income_expense_tab.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; class AccountOverview extends StatelessWidget { final String accountBalance, income, expenses; const AccountOverview( {super.key, required this.accountBalance, required this.income, required this.expenses}); @override Widget build(BuildContext context) { return Container( alignment: Alignment.center, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), height: 312, width: double.infinity, decoration: BoxDecoration( gradient: const LinearGradient( colors: [ Color.fromRGBO(255, 246, 229, 1), Color.fromRGBO(248, 237, 216, 0), ], ), borderRadius: BorderRadius.only( bottomLeft: Radius.circular(32.r), bottomRight: Radius.circular(32.r), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const Header(), AccountBalance( accountBalance: accountBalance, ), SizedBox(height: 27.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ IncomeExpensesTab( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const IncomePage())); }, image: 'assets/images/income.png', title: 'Income', amount: income, color: const Color.fromRGBO(0, 168, 107, 1), ), // SizedBox(width: 16.w), IncomeExpensesTab( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const ExpensePage())); }, image: 'assets/images/expense.png', title: 'Expense', amount: expenses, color: const Color.fromRGBO(253, 60, 74, 1), ), ]) ], ), ); } }
/** This is part of my code for "Time of Day When Usually People Go To Sleep". This class is where the actual code for my modified record reader is defined. The changes to this class essentially make it so 4 lines from the file are concatenated into a single input line for the mapper. */ package nlrr; import java.util.Arrays; import java.io.BufferedReader; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.LongWritable; import java.io.IOException; import java.io.InputStreamReader; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; class NRecordReader extends RecordReader<LongWritable, Text> { private LongWritable key; private Text value; private FileSplit fsplit; private Configuration conf; private FSDataInputStream fsinstream; private FileSystem fs; private long splitstart = 0; private long splitlen = 0; private long bytesread = 0; private BufferedReader br; private final int newlinebytes = ("\n").getBytes().length; private int NLinesToRead = 2; @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { /* Initialize Input stream and reader. We use stream to seek to start of split position and reader to readlines */ this.fsplit = (FileSplit) split; this.conf = context.getConfiguration(); fs = fsplit.getPath().getFileSystem(conf); fsinstream = fs.open(fsplit.getPath()); br = new BufferedReader(new InputStreamReader(fsinstream)); // RecordLength field is set in driver program and informs // how many lines make a record NLinesToRead = conf.getInt("RecordLength",0); splitstart = fsplit.getStart(); splitlen = fsplit.getLength(); /* LineInputFormat, which we use as our input format, set the length of first split to 1 less byte and for other split it decrements one byte from splitstart. This it does to ensure it works hand in had with LineRecordReader. Since we are writing our own record reader, we need to offset this so that split boundaries line-up with line boundaries. */ if (splitstart == 0) splitlen++; else splitstart++; fsinstream.skip(splitstart); } // Read N lines as one record. public String readNLines() throws IOException { String Nlines = null; String line = null; for (int i = 0; (i < NLinesToRead) && ((line = br.readLine()) != null); i++) { if (Nlines == null) { Nlines = line; } else { Nlines = Nlines.concat(line); } } return Nlines; } /* Read Nline records till split boundary. NewLine character length is added to overall count of bytes read as it is lost during readline. */ @Override public boolean nextKeyValue() throws IOException { if (bytesread >= splitlen ) { return false; } else { String line; if ((line = readNLines()) != null) { int bytes = line.getBytes().length + newlinebytes * NLinesToRead; //This prevents the last line of the input from being used //Due to how the split is set up, the last line would be a duplicate //By setting this line equal to " ", this prevents any duplication if(bytes + bytesread >= splitlen) { line = " "; } //Otherwise writes the line as a key value = new Text(line); key = new LongWritable(splitstart); bytesread += bytes; return true; } else { return false; } } } @Override public void close() throws IOException { // do nothing } @Override public LongWritable getCurrentKey() { return this.key; } @Override public Text getCurrentValue() { return this.value; } @Override public float getProgress() throws IOException { return true ? 1.0f : 0.0f; } }
import { AttachMoney, HelpOutline } from '@mui/icons-material' import { Autocomplete, Checkbox, Grid, TextField, Tooltip, Typography } from '@mui/material' import { SearchEpics } from 'Components/Search' import useDebounce from 'Hooks/useDebounce' import PropTypes from 'prop-types' import { useEffect, useState } from 'react' import { useSelector } from 'react-redux' import { useParams } from 'react-router' import { selectCompletionTypes } from 'Redux/AppSettings/selectors' const types = { BINARY: 'BINARY', NUMBER: 'NUMBER', MONEY: 'MONEY', PERCENTAGE: 'PERCENTAGE', GITLAB_EPIC: 'GITLAB_EPIC', GITLAB_ISSUE: 'GITLAB_ISSUE' } export const determineCompletionTypeData = (onChangeType, fields) => { const noSyncFields = { gitlabEpicId: null, gitlabIssueId: null } const { completionType, value, target } = fields switch (completionType) { case types.BINARY: { onChangeType({ ...noSyncFields, completionType, value: value < target ? 0 : 1, target: 1 }) break } case types.PERCENTAGE: { const newValue = value < target ? (value / target * 100) : 100 onChangeType({ ...noSyncFields, completionType, value: Number.parseFloat(newValue.toFixed(2)), target: 100 }) break } case types.NUMBER: case types.MONEY: { onChangeType({ ...noSyncFields, completionType, value, target }) break } case types.GITLAB_ISSUE: { onChangeType({ ...noSyncFields, completionType, gitlabIssueId: fields.gitlabIssueId }) break } case types.GITLAB_EPIC: { onChangeType({ ...noSyncFields, completionType, gitlabEpicId: fields.gitlabEpicId }) break } } } const isValid = (value) => RegExp(/^\d{0,}([.]{0,1})\d{0,2}$/).test(value) const isManualOption = (option) => [types.BINARY, types.PERCENTAGE, types.NUMBER, types.MONEY].includes(option) function TypeTextField({ inputValue, onChange, disabled, label, showMoneyAdornment, title, max }) { const [textFieldValue, setTextFieldValue] = useState(inputValue) const valueToReturn = useDebounce(Math.min(textFieldValue, max), 500) const onValueChange = ({ target }) => { const { value } = target value.length === 0 ? setTextFieldValue('') : isValid(value) && setTextFieldValue(value, max) } useEffect(() => { inputValue !== valueToReturn && onChange(valueToReturn ? valueToReturn : 0) }, [valueToReturn]) useEffect(() => { setTextFieldValue(inputValue) }, [inputValue]) return ( <TextField variant = 'outlined' size = 'small' label = {label} value = {textFieldValue} disabled = {disabled} onChange = {onValueChange} InputProps = {{ startAdornment: showMoneyAdornment && ( <AttachMoney fontSize = 'small' color = 'secondary' style = {{ marginLeft: '-10px' }}/> ), endAdornment: ( <Tooltip title = {title}> <div style = {{ borderRadius: '50%', cursor: 'help', display: 'flex', opacity: .6 }}> <HelpOutline color = 'secondary' fontSize = 'small'/> </div> </Tooltip> ), }} /> ) } function TargetType({ type, inputValue, onChange, disabled }) { if ([types.NUMBER, types.MONEY].includes(type)) { return ( <Grid item xs zeroMinWidth> <TypeTextField disabled = {disabled} inputValue = {inputValue} label = 'Target' onChange = {onChange} showMoneyAdornment = {type === types.MONEY} title = 'Target value required for completion' /> </Grid> ) } return null } function ValueType({ type, inputValue, onChange, disabled, max }) { const addPercentageSymbol = () => type === types.PERCENTAGE ? ' (%)' : '' const isChecked = () => inputValue === 1 return [types.NUMBER, types.MONEY, types.PERCENTAGE].includes(type) ? <Grid item xs = 'auto' data-testid = {`CompletionType__value-${type}`}> <TypeTextField disabled = {disabled} inputValue = {inputValue} label = {'Value' + addPercentageSymbol()} onChange = {onChange} showMoneyAdornment = {type === types.MONEY} title = 'Current progress towards completion' max = {max} /> </Grid> : <Grid container alignItems = 'baseline' alignContent = 'center' paddingLeft = {2}> <Grid item> <label htmlFor = 'toggle'> <Typography variant = 'caption' color = 'secondary'>Complete</Typography> </label> </Grid> <Grid item data-testid = 'CompletionType__checkbox-button'> <Checkbox id = 'toggle' disabled = {disabled} checked = {isChecked()} size = 'small' onChange = {(e) => onChange(e.target.checked ? 1 : 0)} /> </Grid> </Grid> } function AutomatedType({ type, completion, onChange }) { const { productId } = useParams() switch (type) { case types.GITLAB_EPIC: return ( <SearchEpics defaultSearchTerms = {'product.id:' + productId} textFieldProps = {{ variant: 'outlined', size: 'small', label: 'Select Epic', placeholder: completion?.gitlabEpic?.title ?? 'Search product epics by title', }} onChange = {(_event, values) => values[0]?.id > 0 && onChange({ gitlabEpicId: values[0].id, completionType: types.GITLAB_EPIC }) } /> ) case types.GITLAB_ISSUE: default: return null } } export default function CompletionType({ completion, hasEdit, onChange }) { const completionTypes = useSelector(selectCompletionTypes) const [renderedOption, setRenderedOption] = useState(completionTypes[completion?.completionType] ?? null) const onChangeDropdown = (_e, selectedOption) => { setRenderedOption(selectedOption) const fields = { completionType: selectedOption?.name, value: completion.value, target: completion.target } isManualOption(selectedOption?.name) && determineCompletionTypeData(onChange, fields) } return ( <Grid container spacing = {1} style = {{ marginLeft: '-8px', marginBottom: 0, marginTop: '4px' }}> <Grid item xs marginBottom = {1} minWidth = '175px' style = {{ maxWidth: 'initial' }}> <Autocomplete freeSolo autoComplete disableClearable forcePopupIcon = {hasEdit} disabled = {!hasEdit} getOptionLabel = {(option) => option?.displayName} options = {Object.values(completionTypes) .filter(cType => !['CONNECTION_FAILURE', types.GITLAB_ISSUE].includes(cType.name))} value = {renderedOption} onChange = {onChangeDropdown} renderInput = {(params) => <TextField {...params} label = 'Completion Type' variant = 'outlined' size = 'small' /> } /> </Grid> {isManualOption(renderedOption?.name) ? <Grid item container xs = 'auto' spacing = {1} style = {{ maxWidth: '100%' }}> <ValueType type = {renderedOption?.name} onChange = {(value) => onChange({ value })} inputValue = {completion.value} max = {completion.target} disabled = {!hasEdit} /> <TargetType type = {renderedOption?.name} onChange = {(target) => onChange({ target })} inputValue = {completion.target} disabled = {!hasEdit} /> </Grid> : <Grid item sx = {{ maxWidth: 'md', width: 1 }}> <AutomatedType type = {renderedOption?.name} onChange = {(value) => onChange({ ...value })} completion = {completion} /> </Grid> } </Grid> ) } CompletionType.propTypes = { completion: PropTypes.shape({ value: PropTypes.number, target: PropTypes.number, completionType: PropTypes.string, id: PropTypes.number, }).isRequired, hasEdit: PropTypes.bool, onChange: PropTypes.func.isRequired } CompletionType.defaultProps = { hasEdit: false } const defaultPropTypes = { disabled: PropTypes.bool, inputValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), onChange: PropTypes.func.isRequired, type: PropTypes.string, } const defaultProps = { disabled: true, inputValue: '', type: null, } TargetType.propTypes = defaultPropTypes TargetType.defaultProps = defaultProps ValueType.propTypes = { ...defaultPropTypes, max: PropTypes.number } ValueType.defaultProps = { ...defaultProps, max: Number.MAX_SAFE_INTEGER } AutomatedType.propTypes = { onChange: PropTypes.func.isRequired, type: PropTypes.string, completion: PropTypes.shape({ gitlabEpic: PropTypes.shape({ title: PropTypes.string }) }).isRequired } AutomatedType.defaultProps = { type: 'unknown' } TypeTextField.propTypes = { disabled: PropTypes.bool.isRequired, inputValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, label: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, showMoneyAdornment: PropTypes.bool.isRequired, title: PropTypes.string.isRequired, max: PropTypes.number } TypeTextField.defaultProps = { max: Number.MAX_SAFE_INTEGER }
<?php namespace App\Http\Requests\Front\UserAddress; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\ValidationException; use App\Classes\Adapters\Front\UserAddress\UserAddressRequestAdapter; class UpdateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, mixed> */ public function rules() { return UserAddressRequestAdapter::rulesUpdated($this->id); } public function data() { return UserAddressRequestAdapter::transform($this->all() + ['user_id' => $this->user_id]); } public function attributes() { return UserAddressRequestAdapter::attributes(); } public function failedValidation($validator) { throw new ValidationException($validator); } }
const dotenv = require('dotenv'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const express = require('express'); const Razorpay = require('razorpay'); const app = express(); dotenv.config({ path: './config.env' }); const Transactions = require('./models/Transactions'); // Import your Transactions model const razorpay = new Razorpay({ key_id: process.env.RAZORPAY_API_KEY, key_secret: process.env.RAZORPAY_API_SECRET, }); app.use(express.json()); app.use(require('./routes/auth')); const PORT = process.env.PORT; const createOrder = async (req, res) => { const amount = parseInt(req.body.amount) * 100; // Convert the amount to the smallest unit (e.g., paise for INR) const currency = req.body.currency; // Define options for creating the Razorpay order const options = { amount, currency, receipt: 'your_receipt_id', // You can set a unique receipt ID as per your needs }; try { // Create the order using the Razorpay SDK const instance = await razorpay.orders.create(options); if (instance) { const order_id = instance.id; const user_id = 'your_user_id'; // Set the user ID as per your authentication logic // Create a new transaction record and save it to the database const transaction = new Transactions({ order_id, user_id, details: instance }); await transaction.save(); // Show order details in the console console.log('Razorpay Order Details:', instance); res.status(200).json(instance); } else { res.status(500).json({ error: 'Failed to create the order' }); } } catch (error) { console.error('Error creating order:', error); res.status(500).json({ error: 'Failed to create the order' }); } }; // Create a route for creating Razorpay orders app.post('/create-order', Transactions); app.get('/', (req, res) => { res.send(`Hello world from server router app`); }); // Add your Razorpay webhook handling code here (if needed) app.listen(PORT, () => { console.log(`Server is running on port no ${PORT}`); });
local M = {} M.setup = function() local signs = { { name = "DiagnosticSignError", text = "" }, { name = "DiagnosticSignWarn", text = "" }, { name = "DiagnosticSignHint", text = "" }, { name = "DiagnosticSignInfo", text = "" }, } for _, sign in ipairs(signs) do vim.fn.sign_define(sign.name, { texthl = sign.name, text = sign.text, numhl = "" }) end local config = { virtual_text = false, -- signs = { -- active = signs, -- }, signs = false, update_in_insert = false, underline = false, severity_sort = true, float = { focusable = true, style = "minimal", border = "rounded", source = "always", header = "", prefix = "", }, } vim.diagnostic.config(config) vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, { border = "single", }) vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, { border = "single", }) end local function lsp_keymaps(bufnr) local map = vim.keymap.set map("n", "gD", function() vim.lsp.buf.declaration() end, { desc = "(LSP) Go to Declaration", silent = true, buffer = bufnr }) map("n", "gd", function() vim.lsp.buf.definition() end, { desc = "(LSP) Go to Definition", silent = true, buffer = bufnr }) map("n", "K", function() vim.lsp.buf.hover() end, { desc = "(LSP) Hover", silent = true, buffer = bufnr }) map("n", "gi", function() vim.lsp.buf.implementation() end, { desc = "(LSP) Show Implementations", silent = true, buffer = bufnr }) map("n", "gr", function() vim.lsp.buf.references() end, { desc = "(LSP) Show References", silent = true, buffer = bufnr }) map("n", "gR", function() vim.lsp.buf.rename() end, { desc = "(LSP) Rename Symbol", silent = true, buffer = bufnr }) end M.on_attach = function(client, bufnr) if client.name == "tsserver" then client.server_capabilities.document_formatting = false local typescript = require("typescript") local map = vim.keymap.set map("n", "gM", function() typescript.actions.addMissingImports() end, { desc = "(LSP - Typescript) Add Missing Imports" }) map("n", "gu", function() typescript.actions.removeUnused() end, { desc = "(LSP - Typescript) Remove Unused" }) map("n", "gO", function() typescript.actions.organizeImports() end, { desc = "(LSP - Typescript) Organize Imports" }) map("n", "ga", function() typescript.actions.fixAll() end, { desc = "(LSP - Typescript) Fix All" }) end lsp_keymaps(bufnr) end local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.foldingRange = { dynamicRegistration = false, lineFoldingOnly = true, } local status_ok, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp") if not status_ok then return end M.capabilities = cmp_nvim_lsp.default_capabilities(capabilities) local diagnostics_visible = true M.toggle_diagnostics = function() diagnostics_visible = not diagnostics_visible if diagnostics_visible then vim.diagnostic.hide(nil, 0) else vim.diagnostic.show(nil, 0) end end return M
const mongoose = require("mongoose"); const { DateTime } = require("luxon"); const Schema = mongoose.Schema; const AuthorSchema = new Schema({ first_name: { type: String, required: true, maxLength: 100 }, family_name: { type: String, required: true, maxLength: 100 }, date_of_birth: { type: Date }, date_of_death: { type: Date }, }) AuthorSchema.virtual("name").get(function() { let fullname = ""; if (this.first_name && this.family_name) { fullname = `${this.family_name}, ${this.first_name}`; } return fullname; }) AuthorSchema.virtual("url").get(function() { return `/catalog/author/${this._id}`; }) AuthorSchema.virtual("date_of_birth_formatted").get(function() { return this.date_of_birth ? DateTime.fromJSDate(this.date_of_birth).toLocaleString(DateTime.DATE_MED) : ""; }) AuthorSchema.virtual("date_of_birth_form_formatted").get(function() { return this.date_of_birth ? DateTime.fromJSDate(this.date_of_birth).toFormat("yyyy-MM-dd") : ""; }) AuthorSchema.virtual("date_of_death_formatted").get(function() { return this.date_of_death ? DateTime.fromJSDate(this.date_of_death).toLocaleString(DateTime.DATE_MED) : ""; }) AuthorSchema.virtual("date_of_death_form_formatted").get(function() { return this.date_of_death ? DateTime.fromJSDate(this.date_of_death).toFormat("yyyy-MM-dd") : ""; }) AuthorSchema.virtual("lifespan").get(function() { return this.date_of_birth_formatted + ' - ' + this.date_of_death_formatted; }) module.exports = mongoose.model("Author", AuthorSchema);
{% extends '__base_local__.html' %} {% block title %}首页{% endblock %} {% block beforehead %} <style> html, body { scroll-behavior: smooth; } .v-enter-active, .v-leave-active { transition: opacity .2s ease; transition: translate .2s ease; } .fade-enter-from, .fade-leave-to { transition: translateY(0) } .slide-fade-enter-active { transition: all .3s ease-out; } .slide-fade-leave-active { transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0); } .slide-fade-enter-from, .slide-fade-leave-to { transform: translateY(0px); opacity: 0; } .tools-main { background-color: #c1f0c1aa; bottom: 150px; right: 2vw; cursor: pointer; position: fixed; text-align: center; z-index: 101; } </style> {% endblock %} {% block content %} <section class="content-header"> <h1> 91Porn <small>91 </small> </h1> <ol class="breadcrumb"> <li><a href="/"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">91 porn</li> </ol> </section> <div class="container" id="main"> <router-view></router-view> </div> {% endblock %} {% block beforebody %} <script src="static/vue/vue.global-3.2.31.js"></script> <script src="static/vue/vue-router.global-4.0.14.js"></script> <script src="static/vue/vue3-sfc-loader-5.3.5.js"></script> <script src="static/DPlayer-1.26.0/DPlayer.min.js"></script> <script src="static/main.js"></script> <script> let view = { // data返回值是暴露的属性 data() { return { player: null } }, props: ['url', 'path', 'poster', 'thumbnails'], methods: { }, delimiters: ['+{', '}'], template: ` <div class="row"> <nav class="col-md-8" aria-label="breadcrumb"> <ol class="breadcrumb"> <li v-for="item, index in path" class="breadcrumb-item" :aria-current="index == path.length - 1 ? 'page' : ''"> <a v-if="index === 0" @click="$router.push({name: 'index'})" href="#/">+{item}</a> <a v-else-if="index === 1" @click="$router.push({name: 'index', path: '/index', params: {uname: item, page_index: 1}})" href="#/">+{item}</a> <span v-else>+{item}</span> </li> </ol> </nav> </div> <div class="row"> <div ref="player" class="col-md" style="max-height: 60vh;"></div> </div>`, mounted() { if (!this.url) { this.$router.push({ name: 'index' }) return } let video = { url: `${location.pathname}${this.url}`, pic: `${location.pathname}${this.poster}`, thumbnails: `${location.pathname}${this.thumbnails}`, } console.log(video) if (this.url.indexOf('m3u8') > 0) { video['type'] = 'hls' } this.player = new DPlayer({ container: this.$refs.player, lang: 'zh-cn', theme: '#FADFA3', preload: 'auto', screenshot: true, video: video, }) }, watch: { } } let index = { // data返回值是暴露的属性 data() { return { items: [], selectItems: [], // path: ['/root'], path: { all: 'root', uname: '', status: '' }, prefix: 'vue', mode: 'list', page: { "total": 0, "pages": 1, "index": 1, "size": 15 }, filter: { uname: null, status: null }, loading: false, vue_export: { show: false, content: '', callbacks_: [() => { this.vue_export.show = false; this.vue_export.content = '' }] }, vue_import: { show: false, content: '' }, vue_config: { show: false, content: [{ key: 'sub', value: 'https://jiang.netlify.app/', enable: true, }] }, vue_update: { show: false, content: { path: 'path', name: 'name', key: 'key', status: 0, src: 'src', src_local: 'src_local', poster: 'poster', poster_local: 'poster_local', } }, vue_command: { show: false, content: { command: 'loadrflist', params: { range: '1:2' }, } }, ws: null, } }, props: ['uname', 'page_index'], methods: { choseItem(items) { this.selectItems = [] for (let id of items) { for (let item of this.items) { if (item.id === id) { this.selectItems.push(item) break } } } }, switchMode(mode) { this.mode = mode localStorage.setItem('mode', mode) }, pageToStatus(status) { if (status.length = 0) { this.filter['status'] = null } else { this.filter['status'] = status } this.pageTo(this.page.index) localStorage.setItem('filter', JSON.stringify(this.filter)) this.path['status'] = status localStorage.setItem('path', JSON.stringify(this.path)) }, pageToAuthorAll() { this.filter['status'] = null this.pageTo(1) localStorage.setItem('filter', JSON.stringify(this.filter)) this.path['status'] = null localStorage.setItem('path', JSON.stringify(this.path)) }, pageToAuthor(uname) { // log(uname) this.filter['uname'] = uname this.pageTo(1) localStorage.setItem('filter', JSON.stringify(this.filter)) this.path['uname'] = uname localStorage.setItem('path', JSON.stringify(this.path)) }, pageToAll() { this.filter['uname'] = null this.filter['status'] = null this.pageTo(1) localStorage.setItem('filter', JSON.stringify(this.filter)) this.path['uname'] = '' this.path['status'] = '' localStorage.setItem('path', JSON.stringify(this.path)) }, pageTo(index) { if (index > this.page.pages) index = this.page.pages if (index <= 0) index = 1 filter = '' // console.log(filter) let param = { pagesize: this.page.size, index: index } Object.keys(this.filter).forEach(key => { if (this.filter[key]) { param[key] = this.filter[key] } }) get('vue/items', param, { _before: () => { this.loading = true }, _final: () => { this.loading = false; this.selectItems = [] }, _success: (data) => { this.items = data['data']['items'] // this.path = data['data']['path'] this.prefix = data['data']['prefix'] this.page = data['data']['page'] this.ws_status_req() }, }) }, ws_status_req() { if (this.ws === null || this.ws.running === undefined) return let keys = [] this.items.forEach(item => { if (this.ws.running.indexOf(item['key']) < 0) { keys.push(item['key']) } }) let req = { 'command': 'key', 'params': keys } // console.log(this.ws) this.ws.send(JSON.stringify(req)); }, status_init() { const protocols = {'https:': 'wss', 'http:': 'ws'} let url = `${protocols[location.protocol]}://${location.host}${location.pathname}/status` this.ws = new WebSocket(url); this.ws.onopen = (event) => { this.ws.running = [] console.log(url + " Connection open ..."); this.ws_status_req() } this.ws.onmessage = (event) => { // console.log("Received Message: " + event.data); let data = event.data try { data = JSON.parse(data) if (data['command'] === 'rep') { let key = data['params']['key'] let items = this.items.filter(item => { if (item['key'] === key) return item }) if (items.length > 0) { status_data = data['params'] let item = items[0] item['status_data'] = status_data if (status_data['scale'] >= 100) { this.ws_status_req() this.ws.running.splice(this.ws.running.indexOf(key), 1) } else { let key = status_data['key'] if (this.ws.running.indexOf(key) < 0) { this.ws.running.push(key) } let req = { 'command': 'path', 'params': status_data } // log(req, "send") this.ws.send(JSON.stringify(req)); } } else { this.ws.running.splice(this.ws.running.indexOf(key), 1) } } } catch (error) { if (data === 'close') { this.ws.send('close'); } if (data === 'req') { console.log('req ...') let keys = [] this.items.forEach(item => { keys.push(item['key']) }) let req = { 'command': 'key', 'params': keys } this.ws.send(JSON.stringify(req)); } } }; this.ws.onclose = (event) => { console.log("Connection closed."); }; return this.ws; }, status_running() { let url = 'ws://' + location.host + '/status' const ws = new WebSocket(url); ws.onopen = (event) => { console.log(url + " Connection open ..."); ws.send(JSON.stringify({ 'command': 'running' })); } ws.onmessage = (event) => { // console.log("Received Message: " + event.data); let data = event.data try { data = JSON.parse(data) if (data['command'] === 'running') { let status_data = data['params'] console.log(status_data) ws.send(JSON.stringify({ 'command': 'running' })); } } catch (error) { if (data === 'close') { ws.send('close'); } } }; ws.onclose = (event) => { console.log("Connection closed."); }; return ws; }, resize(size) { this.page.size = size localStorage.setItem('page', JSON.stringify(this.page)) }, export2() { log(this.selectItems) if (this.selectItems.length <= 0) return this.vue_export.content = JSON.stringify(this.selectItems, null, "\t") this.vue_export.show = true }, onImport91(content) { if (!content || content.length <= 0) return let objs = [] try { objs = JSON.parse(content) } catch (error) { alert(error.message) return } if (!(objs instanceof Array)) return objs.sort((a, b) => { if (Object.keys(a).indexOf('id') < 0) return 0 if (Object.keys(b).indexOf('id') < 0) return 0 if (typeof (a['id']) !== 'number') return 0 if (typeof (b['id']) !== 'number') return 0 return a['id'] - b['id'] }) let items = [] let fields = ['key', 'name', 'src', 'poster', 'uname', 'uid', 'path', 'content_type', 'duration', 'size', 'publish_date', 'url', 'src_local', 'poster_local', 'status'] objs.forEach(el => { if (el['key'] && el['key'].length > 0 && el['src'] && el['src'].length > 0 && el['poster'] && el['poster'].length > 0 && el['name'] && el['name'].length > 0 ) { el['content_type'] = 'video' let item = {} fields.forEach(field => { item[field] = el[field] }) items.push(item) } }); if (items.length <= 0) { alert("items is empty") return } post('import', { items: items }, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => { this.pageTo(1); this.vue_import.show = false }, }) }, delete2() { log(this.selectItems) if (this.selectItems.length <= 0) return let info = this.selectItems[0].name if (this.selectItems.length >= 2) { info += ", " + this.selectItems[1].name + "..]等" + this.selectItems.length + '项' } else { info += "]" } if (confirm('删除[' + info)) { post('delete', { items: this.selectItems }, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => { this.pageTo(this.page.index); this.vue_import.show = false }, }) } }, download() { if (this.selectItems.length <= 0) return let keys = [] this.selectItems.forEach(item => { keys.push(item['key']) }) post('download', { keys: keys }, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => {alert(data['msg']);log(data['msg']); this.vue_import.show = false }, }) }, onConfig() { get('configs', {}, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => { this.vue_config.show = true this.vue_config.content = data['data']['items'] }, }) }, doConfig(items, remove) { if (items instanceof Array && items.length > 0) { post('configs', { items: items }, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => { this.vue_config.content = data['msg']['items'] this.vue_config.show = false }, }) } if (remove instanceof Array && remove.length > 0) { post('configs/del', { ids: remove }, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => { this.vue_config.content = data['msg']['items'] this.vue_config.show = false }, }) } }, onUpdate() { if (this.selectItems.length <= 0) return get('item/' + this.selectItems[0].id, {}, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => { if (data['data']['items'].length <= 0) return this.vue_update.show = true this.vue_update.content = data['data']['items'][0] }, }) }, doUpdate(item) { post('import', { items: [item] }, { _before: () => { this.loading = true }, _final: () => { this.loading = false }, _success: (data) => { this.pageTo(this.page.index); // this.vue_update.show = false }, }) }, loadrflist() { this.vue_command.content = { command: 'loadrflist', params: { range: '1:2' }, } this.vue_command.show = true }, loadaccuntlist() { this.vue_command.content = { command: 'loadaccuntlist', params: { uname: '', range: '1:2', }, } this.vue_command.show = true }, doCommand(item) { post('' + item.command, item.params, { _before: () => { this.loading = true }, _error: (data) => { alert(data['msg']) }, _success: (data) => { alert(data['msg']) }, _final: () => { this.loading = false }, }) }, command(url) { if (this.selectItems.length <= 0) return post(url, { items: this.selectItems }, { _before: () => { this.loading = true }, _error: (data) => { alert(data['msg']) }, _success: (data) => { alert(data['msg']) this.pageTo(this.page.index) }, _final: () => { this.loading = false }, }) }, logger() { /* let pathname = `` if (location.pathname.length > 1) { pathname = `/${location.pathname}` } let url = `ws://${location.host}${pathname}/tail` */ const protocols = {'https:': 'wss', 'http:': 'ws'} let url = `${protocols[location.protocol]}://${location.host}${location.pathname}/tail` let ws = new WebSocket(url); ws.onopen = (event) => { console.log(url + " Connection open ..."); ws.send('1 server/info.log'); this.vue_export.show = true } ws.onmessage = (event) => { // console.log("Received Message: " + event.data); if (event.data && event.data.length > 0) this.vue_export.content += event.data + '\n' ws.send('2'); }; ws.onclose = (event) => { console.log("Connection closed."); this.ws = null this.vue_export.show = false }; this.vue_export.callbacks_.push(() => { ws && ws.send('close'); }) return ws; } }, components: { toogleMode: component('static/vue/toogleMode.vue'), pagination: component('static/vue/pagination.vue'), list: component('static/vue/list.vue'), grid: component('static/vue/grid.vue'), navtb: component('static/vue/navtb.vue'), 'export': component('static/vue/export.vue'), import91: component('static/vue/import91.vue'), config: component('static/vue/config.vue'), update: component('static/vue/update.vue'), loading: component('static/vue/loading.vue'), command: component('static/vue/command.vue'), }, delimiters: ['+{', '}'], template: ` <div> <toogle-mode @switch-mode="switchMode" :mode="mode" :path="path" @page-to-all="pageToAll" @page-to-author-all="pageToAuthorAll" @page-to-status="pageToStatus"></toogle-mode> <component :is="mode" :items="items" @select="choseItem" @page-to="pageToAuthor"></component> <pagination :page="page" @page-to="pageTo" @resize="resize"></pagination> <transition> <loading v-if="loading"></loading> </transition> <export :show='vue_export.show' :content='vue_export.content' @hide="vue_export.callbacks_.forEach(callback=>{callback()})"></export> <import91 :show='vue_import.show' @save="onImport91" @hide="vue_import.show=false"></import91> <update :show='vue_update.show' :content="vue_update.content" @save="doUpdate" @refresh="onUpdate" @hide="vue_update.show=false"></update> <config :show='vue_config.show' :content="vue_config.content" @save="doConfig" @refresh="onConfig" @hide="vue_config.show=false"></config> <command :show='vue_command.show' :content="vue_command.content" @send="doCommand" @hide="vue_command.show=false"></command> {% if __user__ and __user__.admin == 1 %} <transition name="slide-fade"> <div class="tools-main"> <div class="btn-group dropleft d-block"> <a type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> 指令 </a> <div class="dropdown-menu text-center" style="background-color: #c1f0c1aa;"> <a class="dropdown-item btn" @click="loadrflist" data-toggle="tooltip" data-placement="top" title="热门视频">热门视频</a> <a class="dropdown-item btn" @click="loadaccuntlist" data-toggle="tooltip" data-placement="top" title="用户视频">用户视频</a> <a class="dropdown-item btn" @click="logger" data-toggle="tooltip" data-placement="top" title="日志">日志</a> <a class="dropdown-item btn border-top" @click="command('/loadvideopage')" v-if="selectItems.length > 0" data-toggle="tooltip" data-placement="top" title="视频信息">视频信息</a> <a class="dropdown-item btn" @click="command('/downloadsrc')" v-if="selectItems.length > 0" data-toggle="tooltip" data-placement="top" title="下载视频">下载视频</a> <a class="dropdown-item btn" @click="command('/stop')" v-if="selectItems.length > 0" data-toggle="tooltip" data-placement="top" title="停止下载">停止下载</a> <a class="dropdown-item btn" @click="command('/thumbnails')" v-if="selectItems.length > 0" data-toggle="tooltip" data-placement="top" title="更新预览">更新预览</a> </div> </div> <div class="btn-group dropleft d-block"> <a type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> 操作 </a> <div class="dropdown-menu text-center" style="background-color: #c1f0c1aa;"> <a class="btn btn-sm d-block w-100 tools border-top" v-if="selectItems.length > 0" @click="delete2" data-toggle="tooltip" data-placement="top" title="删除">删除</a> <a class="btn btn-sm d-block w-100 tools border-top" v-if="selectItems.length > 0" @click="download" data-toggle="tooltip" data-placement="top" title="下载">下载</a> <a class="btn btn-sm d-block w-100 tools" v-if="selectItems.length > 0" @click="export2" data-toggle="tooltip" data-placement="top" title="导出">导出</a> <a class="btn btn-sm d-block w-100 tools border-top" v-if="selectItems.length === 1" @click="onUpdate" data-toggle="tooltip" data-placement="top" title="修改">修改</a> <a class="btn btn-sm d-block w-100 tools border-top" @click="vue_import.show=true" data-toggle="tooltip" data-placement="top" title="导入">导入</a> <a class="btn btn-sm d-block w-100 tools" @click="onConfig" data-toggle="tooltip" data-placement="top" title="配置">配置</a> </div> </div> <navtb></navtb> </div> </transition> {% endif %} </div>`, mounted() { let page = localStorage.getItem('page') if (page != null && page != 'null' && page != undefined && page != 'undefined') { this.page = JSON.parse(page) } let filter = localStorage.getItem('filter') if (filter != null && filter != 'null' && filter != undefined && filter != 'undefined') { this.filter = JSON.parse(filter) } // console.log(filter) let path = localStorage.getItem('path') if (path != null && path != 'null' && path != undefined && path != 'undefined') { this.path = JSON.parse(path) } if (this.uname) { this.filter['uname'] = this.uname this.path['uname'] = this.uname } this.pageTo(this.page_index || this.page.index) let mode = localStorage.getItem('mode') if (mode != null && mode != 'null' && mode != undefined && mode != 'undefined') { this.mode = mode } this.status_init() // this.status_running() }, watch: { page(newVal, oldVal) { localStorage.setItem('page', JSON.stringify(this.page)) }, } } const routes = [ { path: '', name: 'index', component: index, props: true }, { path: '/view', name: 'view', component: view, props: true } ] const router = VueRouter.createRouter({ // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。 history: VueRouter.createWebHashHistory(), routes, // `routes: routes` 的缩写 }) const app = Vue.createApp({}) //确保 _use_ 路由实例使 //整个应用支持路由。 app.use(router) // mount方法返回根组件实例 const vm = app.mount('#main') </script> {% endblock %}
# 🌋 糖漿池 ### 什麼是糖漿池? 糖漿池是在NexusSwap上賺取免費代幣最簡單的方法。 質押NU,賺取免費代幣! 就是這麼簡單。 另外,還有一些特殊的糖漿池,讓你質押除了NU之外的其他代幣! ### 如何在糖漿池中質押? 在糖漿池中質押,讓你在睡覺時亦可賺取NU或其他代幣! 這比在NexusSwap農場中進行流動性挖礦要簡單。 有別於農場,你只需要質押一種代幣即可開始賺取:通常是NU。 #### 1、錢包正確連接後,進入糖漿池產品頁面,選擇一個您希望質押的糖漿池。 ![](<../.gitbook/assets/糖浆池1 (1).png>) 1、**自動 NU** 自動複投您的收益:任何賺取到的NU,將被自動收穫並重新投入回該糖漿池中。 即收益在無時無刻被轉化為本金,助您產生更多收益。 2、**手動 NU** 與自動NU不同,該池不會自動幫您複投收益。 您需要手動收穫,並手動複投您的收益。 3、其他糖漿池讓您質押NU,來賺取一系列非常有意思的其他項目代幣。 請務必瞭解他們。 #### 2、選擇好您希望質押的糖漿池後,點擊啟用按鈕,並在錢包彈出的消息中確認。 ![](<../.gitbook/assets/糖浆池1 (1).png>) #### 3、稍等片刻,啟用按鈕將變成質押。 點擊它來打開質押選單。 ![](<../.gitbook/assets/糖浆池2 (1).png>) #### 4、輸入您要質押的數量,或直接選擇餘額的百分比來選擇。 ![](<../.gitbook/assets/糖浆池3 (1).png>) #### 5、點擊【確認】按鈕,彈出錢包應用中的交易確認彈窗,點擊【確認】按鈕,合約執行交易,區塊進行確認,確認後,可查看質押成功提示。 ![](../.gitbook/assets/糖浆池4.png) 6、現在您應該能看到糖漿池的詳細質押資訊。 自動NU將展示一個倒數計時,用於提示「解除質押手續費」的收取還有多久結束。 其他糖漿池將顯示收穫按鈕,用於將賺取到的獎勵收穫至錢包內。 ![](../.gitbook/assets/糖浆池5.png) ### 在糖漿池中添加或移除NU <a href="#adding-and-removing-cake-from-a-pool" id="adding-and-removing-cake-from-a-pool"></a> 無論是在糖漿池中添加更多的NU,還是將NU選取並重新質押至更高利潤的糖漿池池中,都非常容易。 以下是操作指南: 1、點擊-(減號)來從池中選取NU,點擊+(加號)來添加更多的NU: ![](<../.gitbook/assets/糖浆池6 (1).png>) **請注意:**若您質押的是自動NU糖漿池,在質押操作後的72小時內,選取需要收取0.1%的手續費。 2、頁面會彈出一個視窗,若您點擊的是+(加號),請在視窗中選擇您要添加的NU數量。若您點擊的是-(減號),則選擇您要選取的NU數量。 ![](../.gitbook/assets/糖浆池6.png) ![](../.gitbook/assets/糖浆池7.png) 3、點擊**確認**。 4、稍等片刻,您的質押資訊將更新:\ ![](<../.gitbook/assets/糖浆池8 (1).png>)\ **请注意:**無論是添加還是選取NU,都會自動將待收穫收益,收穫至您的錢包中。
// // Copyright(c) 2009 Syntext, Inc. All Rights Reserved. // Contact: [email protected], http://www.syntext.com // // This file is part of Syntext Serna XML Editor. // // COMMERCIAL USAGE // Licensees holding valid Syntext Serna commercial licenses may use this file // in accordance with the Syntext Serna Commercial License Agreement provided // with the software, or, alternatively, in accorance with the terms contained // in a written agreement between you and Syntext, Inc. // // GNU GENERAL PUBLIC LICENSE USAGE // Alternatively, this file may be used under the terms of the GNU General // Public License versions 2.0 or 3.0 as published by the Free Software // Foundation and appearing in the file LICENSE.GPL included in the packaging // of this file. In addition, as a special exception, Syntext, Inc. gives you // certain additional rights, which are described in the Syntext, Inc. GPL // Exception for Syntext Serna Free Edition, included in the file // GPL_EXCEPTION.txt in this package. // // You should have received a copy of appropriate licenses along with this // package. If not, see <http://www.syntext.com/legal/>. If you are unsure // which license is appropriate for your use, please contact the sales // department at [email protected]. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // #ifndef SAPI_UI_ITEM_H_ #define SAPI_UI_ITEM_H_ #include "sapi/sapi_defs.h" #include "sapi/common/SString.h" #include "sapi/common/xtn_wrap.h" #include "sapi/app/UiAction.h" class QWidget; namespace SernaApi { class SernaDoc; class UiLiquidItemBase; /// Base class for the elements of the user interface class SAPI_EXPIMP UiItem : public RefCountedWrappedObject { public: UiItem(SernaApiBase* = 0); virtual ~UiItem(); /// Returns the name of item instance SString name() const; /// Returns the assotiated Action UiAction action() const; /// Returns type of item instance SString itemClass() const; SString widgetClass() const; /// Returns widget made by this item QWidget* widget() const; /// Returns requested property from this item, /// or from its action if property does not exist in this item PropertyNode property(const SString& prop) const; /// Updates item properties (if asked) and returns them PropertyNode itemProps(bool update = false); /// For MultiAction items - returns the current subaction root property PropertyNode currActionProp() const; /// Returns string property value SString get(const SString& propName) const; /// Returns string property value SString getTranslated(const SString& propName) const; /// Returns boolean property value bool getBool(const SString& propName) const; /// Returns integer property value int getInt(const SString& propName) const; /// Returns double property value double getDouble(const SString& propName) const; /// Sets string property value void set(const SString& propName, const SString& value); /// Sets boolean property value void setBool(const SString& propName, bool value); /// Sets integer property value void setInt(const SString& propName, int value); /// Sets double property value void setDouble(const SString& propName, double value); /// Sets visible state. void setVisible(bool); /// Returns visible state. bool isVisible() const; /// Attaches UI item void attach(bool recursive = false); /// Detaches UI item void detach(bool recursive = false); /// Dispatch Item command if any void dispatch(); /// Set the focus to the widget corresponding to this UI item void grabFocus() const; /// Set the focus back to the document editor void releaseFocus() const; /// Finds UI command by name. UiAction findAction(const SString& name) const; /// Finds UiItem by name. UiItem findItemByName(const SString& name) const; /// Look up UiItem by class. UiItem findItemByClass(const SString& name) const; /// Finds UiItem by UiActions. UiItem findItemByAction(const UiAction& name) const; /// Shows context menu for this liquid item at global pos (x,y) void showContextMenu(int x, int y); /// Translate string \a str in given context. static SString translate(const char* context, const SString& str); XTREENODE_WRAP_DECL(UiItem) /// Downcasts UiItem to SernaDoc SernaDoc asSernaDoc() const; /// For top-level items: append to documentItem(), attach and show // void attachAndShow(); }; /// Implementations of custom liquid items should inherit from this class. class SAPI_EXPIMP UiLiquidItemBase : public SimpleWrappedObject { public: virtual ~UiLiquidItemBase(); UiItem item() const; // corresponding UI item enum Type { WIDGET = 0x01, UNDOCKED_TOOL = 0x02, VERTICAL_TOOL = 0x04, HORIZONTAL_TOOL = 0x08 }; virtual SString itemClass() const = 0; virtual SString widgetClass() const; /// Shows context menu for this liquid item at global pos (x,y) virtual void showContextMenu(int x, int y); /// Releases input focus and passes it back to the editor virtual void releaseFocus() const; /// Set the focus to the widget corresponding to this UI item virtual void grabFocus() const; /// may be reimplemented for custom attach virtual bool doAttach(); /// may be reimplemented for custom detach virtual bool doDetach(); /// Called when item property changes virtual void propertyChanged(const PropertyNode& prop); /// invoked when escape button is pressed virtual void escapePressed(); /// May be reimplemented in custom item to indicate active focus virtual void widgetFocusChanged(bool); /// Widget factory - must be implemented in custom item, and /// should return QWidget instance virtual QWidget* makeWidget(QWidget* parent, Type type) = 0; UiLiquidItemBase(SernaApiBase* = 0); private: friend class LiquidItemWrap; //UiLiquidItemBase(const UiLiquidItemBase&); //UiLiquidItemBase& operator=(const UiLiquidItemBase&); }; } // namespace SernaApi #endif // SAPI_UI_ITEM_H_
import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import cartApi from "../../api/cartApi"; import { toastContext } from "../../contexts/ToastProvider"; import { ProgressSpinner } from "primereact/progressspinner"; import { Button } from "primereact/button"; import convertFirstLetterToUpperCase from "../../helpers/convertFirstLetterToUpperCase"; import route from "../../constants/route"; const Cart = () => { const [cart, setCart] = useState({}); const [items, setItems] = useState([]); const [loading, setLoading] = useState(false); const navigate = useNavigate(); const { toastError, toastSuccess } = toastContext(); const fetchCartItems = async () => { setLoading(true); try { const response = await cartApi.getCart(); if (response.data.type === "SUCCESS") { setCart(response.data.cart); setItems(response.data.cart.items); } } catch (error) { // toastError(error.response.data.message); } setLoading(false); }; useEffect(() => { fetchCartItems(); }, []); const handleDecreaseOne = async (productId, sizeId, colorId) => { setLoading(true); try { const response = await cartApi.decreaseOne( productId, sizeId, colorId ); if (response.data.type === "SUCCESS") { toastSuccess(response.data.message); fetchCartItems(); } } catch (error) { toastError(error.response.data.message); } setLoading(false); }; const handleIncreaseOne = async (productId, sizeId, colorId) => { setLoading(true); try { const response = await cartApi.increaseOne( productId, sizeId, colorId ); if (response.data.type === "SUCCESS") { toastSuccess(response.data.message); fetchCartItems(response.data); } } catch (error) { toastError(error.response.data.message); } setLoading(false); }; const handleDeleteItem = async (productId, size, color) => { setLoading(true); try { const response = await cartApi.deleteItemInCart( productId, size, color ); if (response.data.type === "SUCCESS") { toastSuccess(response.data.message); fetchCartItems(); } } catch (error) { console.log(error); toastError(error.response.data.message); } setLoading(false); }; const handlePlaceOrder = () => { navigate("/order"); }; return ( <div> <h1 className="text-4xl my-6 text-center">Shopping Cart</h1> {loading && ( <div className="w-full flex justify-center mt-12"> <ProgressSpinner /> </div> )} {!loading && ( <> {items && items.length === 0 ? ( <p className="text-center">Your cart is empty.</p> ) : ( <> <table className="table-auto w-full"> <thead> <tr> <th className="px-4 py-2 w-32"> Image </th> <th className="px-4 py-2">Name</th> <th className="px-4 py-2">Size</th> <th className="px-4 py-2">Color</th> <th className="px-4 py-2">Quantity</th> <th className="px-4 py-2">Price</th> <th className="px-4 py-2">Actions</th> </tr> </thead> <tbody> {items && items.map((item) => ( <tr className="border-t last:border-b" key={item._id} > <td className="px-8 py-2"> <img src={item.image} alt={item.product.name} className="h-16 w-16 object-cover rounded-lg" /> </td> <td className="px-4 py-2 text-center"> {item.product.name} </td> <td className="px-4 py-2 text-center"> {item.size.size ? item.size.size.toUpperCase() : ""} </td> <td className="px-4 py-2 text-center"> {item.color.color ? convertFirstLetterToUpperCase( item.color.color ) : ""} </td> <td className="pl-4 py-2 text-center"> <div className="w-full flex justify-center items-center"> <button className="px-2 py-1 border border-gray-300 rounded-md flex justify-center items-center border-t last:border-b hover:bg-cyan-400/40 hover:cursor-pointer" onClick={() => handleDecreaseOne( item.product ._id, item.size ._id, item.color ._id ) } > - </button> <span className="w-8 mx-2 text-center"> { item.totalProductQuantity } </span> <button className="px-2 py-1 border border-gray-300 rounded-md flex justify-center items-center border-t last:border-b hover:bg-cyan-400/40 hover:cursor-pointer" onClick={() => handleIncreaseOne( item.product ._id, item.size ._id, item.color ._id ) } > + </button> </div> </td> <td className="px-4 py-2 text-center"> {new Intl.NumberFormat().format( item.totalProductPrice )} <span className="text-sm text-red-500 pb-2"> đ </span> </td> <td className="px-4 py-2 text-center"> <Button className="" onClick={(e) => { handleDeleteItem( item.product ._id, item.size.size, item.color.color ); }} severity="danger" > Remove </Button> </td> </tr> ))} </tbody> </table> <div className="flex justify-between items-center mt-4 ml-4"> <span className="text-2xl ml-4"> Total Price:{" "} <span className="text-red-700 font-bold"> {new Intl.NumberFormat().format( cart.totalPrice )} </span> <span className="text-sm text-red-500 pb-2"> đ </span> </span> <button className="mr-10 px-8 py-4 font-bold bg-blue-500 text-white rounded hover:bg-blue-700" onClick={handlePlaceOrder} > Place Order </button> </div> </> )} </> )} </div> ); }; export default Cart;
// .load scripts/console-init.ts me = (await ethers.provider.listAccounts())[0]; core = await ethers.getContract("KlerosCore"); sortition = await hre.ethers.getContract("SortitionModule"); disputeKit = await ethers.getContract("DisputeKitClassic"); pnk = await ethers.getContract("PNK"); registry = await ethers.getContract("PolicyRegistry"); rng = await ethers.getContract("RandomizerRNG"); rng2 = await ethers.getContract("BlockHashRNG"); gateway = await ethers.getContract("HomeGatewayToGnosis"); resolver = await ethers.getContract("DisputeResolver"); faucet = await ethers.getContract("PNKFaucet"); sender = await ethers.getContract("VeaOutboxArbToGnosisDevnet"); options = { gasLimit: 10000000, gasPrice: 5000000000 }; var disputeID = 0; console.log("sortition phase: %s", await sortition.phase()); console.log("freezingPhase timeout? %s", await core.freezingPhaseTimeout()); const relayCreateDispute = async (blockHash, foreignDisputeID) => { // const blockHash = "0xda3c4d74eeb199345b771748a930a069b172dac9f4b50697f40803581eb13990"; // const foreignDisputeID = 6; const extraData = "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003"; const fee = await core.arbitrationCost(extraData); var tx; try { tx = await ( await gateway.relayCreateDispute( 10200, blockHash, foreignDisputeID, 2, extraData, "0x34E520dc1d2Db660113b64724e14CEdCD01Ee879", { value: fee, ...options, } ) ).wait(); console.log("txID: %s", tx?.transactionHash); disputeID = ( await core.queryFilter(core.filters.DisputeCreation(), tx.blockNumber, tx.blockNumber) )[0].args._disputeID.toNumber(); console.log("Using disputeID %d from now", disputeID); } catch (e) { if (typeof e === "string") { console.log("Error: %s", e); } else if (e instanceof Error) { console.log("%O", e); } } finally { if (tx) { const filter = core.filters.DisputeCreation(); const logs = await core.queryFilter(filter, tx.blockNumber, tx.blockNumber); console.log("DisputeID: %s", logs[0]?.args?._disputeID); } } }; const createDisputeOnResolver = async () => { const choices = 2; const nbOfJurors = 3; const feeForJuror = (await core.courts(1)).feeForJuror; var tx; try { tx = await ( await resolver.createDispute( "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003", "", 2, { value: feeForJuror.mul(nbOfJurors), ...options, } ) ).wait(); console.log("txID: %s", tx?.transactionHash); } catch (e) { if (typeof e === "string") { console.log("Error: %s", e); } else if (e instanceof Error) { console.log("%O", e); } } finally { if (tx) { const filter = core.filters.DisputeCreation(); const logs = await core.queryFilter(filter, tx.blockNumber, tx.blockNumber); console.log("DisputeID: %s", logs[0]?.args?._disputeID); } } }; const passPhase = async () => { const before = await sortition.phase(); var tx; try { tx = await (await sortition.passPhase(options)).wait(); console.log("txID: %s", tx?.transactionHash); } catch (e) { if (typeof e === "string") { console.log("Error: %s", e); } else if (e instanceof Error) { console.log("%O", e); } } finally { const after = await sortition.phase(); console.log("Phase: %d -> %d", before, after); } }; const passPeriod = async () => { const before = (await core.disputes(disputeID)).period; var tx; try { tx = await (await core.passPeriod(disputeID, options)).wait(); console.log("txID: %s", tx?.transactionHash); } catch (e) { if (typeof e === "string") { console.log("Error: %s", e); } else if (e instanceof Error) { console.log("%O", e); } } finally { const after = (await core.disputes(disputeID)).period; console.log("Period for dispute %s: %d -> %d", disputeID, before, after); } }; const drawJurors = async () => { var info = await core.getRoundInfo(disputeID, 0); console.log("Drawn jurors before: %O", info.drawnJurors); let tx; try { tx = await (await core.draw(disputeID, 10, options)).wait(); console.log("txID: %s", tx?.transactionHash); } catch (e) { if (typeof e === "string") { console.log("Error: %s", e); } else if (e instanceof Error) { console.log("%O", e); } } finally { info = await core.getRoundInfo(disputeID, 0); console.log("Drawn jurors after: %O", info.drawnJurors); } }; const isRngReady = async () => { const requesterID = await rng.requesterToID(disputeKit.address); const n = await rng.randomNumbers(requesterID); if (n.eq(0)) { console.log("rng is NOT ready."); return false; } else { console.log("rng is ready: %s", n.toString()); return true; } }; const getRoundInfo = async () => { console.log("%O", await core.getRoundInfo(disputeID, 0)); }; const executeRuling = async () => { let tx; try { tx = await (await core.execute(disputeID, 0, 10)).wait(); // redistribute console.log("txID execute: %s", tx?.transactionHash); tx = await (await core.executeRuling(disputeID)).wait(); // rule console.log("txID executeRuling: %s", tx?.transactionHash); } catch (e) { if (typeof e === "string") { console.log("Error: %s", e); } else if (e instanceof Error) { console.log("%O", e); } } finally { const dispute = await core.disputes(0); console.log("Ruled? %s", dispute.ruled); const ruling = await core.currentRuling(disputeID); console.log("Ruling: %d, Tied? %s, Overridden? %s", ruling.ruling, ruling.tied, ruling.overridden); var filter = sender.filters.MessageReceived(); var logs = await sender.queryFilter(filter, tx?.blockNumber, tx?.blockNumber); console.log("MessageReceived: %O", logs[0]?.args); } }; const toVoting = async () => { console.log("Running for disputeID %d", disputeID); var ready; try { ready = await passPhaseCore().then(passPhaseDk).then(passPhaseDk).then(isRngReady); } catch (e) { ready = false; } while (!ready) { console.log("Waiting for RNG to be ready...", disputeID); await new Promise((r) => setTimeout(r, 10000)); ready = await isRngReady(); } console.log("RNG is ready, drawing jurors.", disputeID); await drawJurors().then(passPhaseDk).then(passPhaseCore).then(passPeriod); }; const epochPeriod = await sender.epochPeriod(); const epochID = async () => { return Math.floor((await ethers.provider.getBlock("latest")).timestamp / epochPeriod); }; const anyBatchToSend = async () => { return await sender.batchSize(); }; const sendBatch = async () => { const before = await disputeKit.phase(); var tx; try { tx = await (await sender.sendBatch(options)).wait(); console.log("txID: %s", tx?.transactionHash); } catch (e) { if (typeof e === "string") { console.log("Error: %s", e); } else if (e instanceof Error) { console.log("%O", e); } } finally { const filter = sender.filters.BatchOutgoing(); const logs = await sender.queryFilter(filter, tx.blockNumber, tx.blockNumber); console.log("BatchOutgoing: %O", logs[0]?.args); } }; console.log("disputeID not set!");
import { DataTypes } from "sequelize"; import sequelize from "../db.js"; // Definir el modelo para la tabla contacto export const Modalidad = sequelize.define('Modalidad', { id_modalidad: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, modalidad_nombre: { type: DataTypes.STRING, allowNull: false, }, }, { timestamps: false, paranoid: false, tableName: "Modalidad", modelName: "Modalidad", }); // Sincronizar los modelos con la base de datos (esto creará las tablas si no existen) Modalidad.sync({ force: false }) .then(async () => { const count = await Modalidad.count(); if (count === 0) { { await Modalidad.bulkCreate([ { modalidad_nombre: "mod_comun", }, { modalidad_nombre: "mod_especial", }, { modalidad_nombre: "mod_adultos", }, ]); } } console.log('Tabla de Modalidad creada') });
import os import mimetypes import time from email.utils import formatdate from email.utils import parsedate from chordataweb.output_stream import CHUNK_SIZE, file_buffer def static_file_exists(working_directory: str, pathname: str, tenant: str): if pathname == '/': return False path_parts = pathname.split('/') application = path_parts[1] if len(path_parts) > 2: filename = str(os.path.sep).join(path_parts[2:]) physical_path_name = os.path.join(working_directory, "apps", application, "static", filename) if os.path.exists(physical_path_name): return physical_path_name filename = str(os.path.sep).join(path_parts[1:]) tenant_local_physical_name = os.path.join(working_directory, "static", tenant, filename) if os.path.exists(tenant_local_physical_name): return tenant_local_physical_name physical_path_name = os.path.join(working_directory, "static", "_global", filename) if os.path.exists(physical_path_name): return physical_path_name else: return False def serve_static(environ, start_response, physical_file: str): r = [''.encode()] file_ext = physical_file.split(".")[-1] file_mime = mimetypes.guess_type(physical_file) if file_ext.lower() == "css": file_mime = "text/css" if file_ext.lower() == "js": file_mime = "text/javascript" if file_ext.lower() == "json": file_mime = "application/json" file_mtime = int(os.path.getmtime(physical_file)) file_size = os.path.getsize(physical_file) cc_header = environ.get('HTTP_IF_MODIFIED_SINCE') if cc_header: cached_file_ts = int(time.mktime(parsedate(cc_header))) else: cached_file_ts = 0 in_cache = False if cc_header: if file_mtime == cached_file_ts: in_cache = True mtime_datetime = formatdate(timeval=file_mtime, localtime=False, usegmt=True) headers = [ ('Last-Modified', str(mtime_datetime)), ('Content-Type', str(file_mime)), ('Content-Length', str(file_size)) ] if in_cache: start_response("304 Not Modified", headers) return [] else: """ Load and return the content of the file """ start_response("200 OK", headers) fp = open(physical_file, 'rb') return file_buffer(fp, CHUNK_SIZE)
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CoursesComponent } from './courses.component'; import { HttpClientModule } from '@angular/common/http'; import { PicsService } from './pics.service'; import { SearchComponent } from './search/search.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelectModule } from '@angular/material/select'; import { PictureComponent } from './picture/picture.component'; import { StoreModule } from '@ngrx/store'; import { counterReducer } from './reducers/pic.reducer'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; //ng g c "nombre componente" //ng g s "nombre servicio" //ng g module routing --module app @NgModule({ declarations: [ AppComponent, CoursesComponent, SearchComponent, PictureComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, BrowserAnimationsModule, MatFormFieldModule, MatSelectModule, StoreModule.forRoot({ counter: counterReducer }), NgbModule, ], providers: [PicsService], bootstrap: [AppComponent], }) export class AppModule {}
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include "philosopher.h" philosopher_t *ph_create(size_t plates, pthread_mutex_t *f1, pthread_mutex_t *f2) { static size_t id = 1; philosopher_t *ph = NULL; ph = malloc(sizeof(philosopher_t)); if (!ph) return NULL; ph->f1 = f1; ph->f2 = f2; ph->plates = plates; ph->id = id; id++; return ph; } static void exit_failure(philosopher_t *ph) { if (ph) { printf("\033[0;31mPhilosopher %d has starved...\n\033[0m", ph->id); free(ph); } pthread_exit(NULL); } static void exit_success(philosopher_t *ph) { if (ph) { printf("\033[0;32mPhilosopher %d finished eating!\n\033[0m", ph->id); free(ph); } pthread_exit(NULL); } static bool try_eat(philosopher_t *ph) { if (pthread_mutex_trylock(ph->f1) != 0) return false; if (pthread_mutex_trylock(ph->f2) != 0) { pthread_mutex_unlock(ph->f1); return false; } printf("\033[0;34mPhilosopher %d is eating...\033[0m\n", ph->id); sleep(EATING_TIME_S); ph->plates--; pthread_mutex_unlock(ph->f1); pthread_mutex_unlock(ph->f2); return true; } void *ph_add(void *ph_ptr) { philosopher_t *ph = ph_ptr; time_t last_eat = time(NULL); if (!ph) exit_failure(NULL); while (ph->plates > 0) { if (time(NULL) - last_eat >= STARVING_TIME_S) exit_failure(ph); if (try_eat(ph)) last_eat = time(NULL); } exit_success(ph); return NULL; }
import { isEscapeKey } from './util.js'; const COMMENTS_SHOWN_PER_CLICK = 5; const bigPictureOverlayElement = document.querySelector('.big-picture'); const closePictureButtonElement = document.querySelector('.big-picture__cancel'); const commentTemplateElement = document.querySelector('#comment') .content .querySelector('.social__comment'); const commentsListElement = bigPictureOverlayElement.querySelector('.social__comments'); const commentsLoaderElement = bigPictureOverlayElement.querySelector('.comments-loader'); const commentsCountElement = bigPictureOverlayElement.querySelector('.comments-count'); const commentsShownCountElement = bigPictureOverlayElement.querySelector('.comments-shown-count'); const bodyElement = document.querySelector('body'); let commentsShownCount = 0; let commentsData = []; const createComment = ({ avatar, name, message }) => { const commentElement = commentTemplateElement.cloneNode(true); commentElement.querySelector('.social__picture').src = avatar; commentElement.querySelector('.social__picture').alt = name; commentElement.querySelector('.social__text').textContent = message; return commentElement; }; const renderComments = () => { commentsShownCount += COMMENTS_SHOWN_PER_CLICK; if (commentsShownCount >= commentsData.length) { commentsLoaderElement.classList.add('hidden'); commentsShownCount = commentsData.length; } else { commentsLoaderElement.classList.remove('hidden'); } const visibleComments = commentsData.slice(0, commentsShownCount); const fragment = document.createDocumentFragment(); visibleComments.forEach((commentData) => { const commentElement = createComment(commentData); fragment.append(commentElement); }); commentsListElement.innerHTML = ''; commentsListElement.append(fragment); commentsShownCountElement.textContent = commentsShownCount; commentsCountElement.textContent = commentsData.length; }; const closePictureModal = () => { bigPictureOverlayElement.classList.add('hidden'); bodyElement.classList.remove('modal-open'); document.removeEventListener('keydown', onDocumentKeydown); commentsShownCount = 0; }; function onDocumentKeydown(evt) { if (isEscapeKey(evt)) { evt.preventDefault(); closePictureModal(); } } const onCommentsLoaderClick = () => renderComments(); const onCancelButtonClick = () => { closePictureModal(); }; const renderBigPictureDetails = ({ url, likes, description }) => { bigPictureOverlayElement.querySelector('.big-picture__img img').src = url; bigPictureOverlayElement.querySelector('.big-picture__img img').alt = description; bigPictureOverlayElement.querySelector('.likes-count').textContent = likes; bigPictureOverlayElement.querySelector('.social__caption').textContent = description; }; const openPictureModal = (data) => { bigPictureOverlayElement.classList.remove('hidden'); bodyElement.classList.add('modal-open'); commentsLoaderElement.classList.add('hidden'); document.addEventListener('keydown', onDocumentKeydown); renderBigPictureDetails(data); commentsShownCount = 0; commentsData = data.comments; if (commentsData.length > 0) { renderComments(); } }; closePictureButtonElement.addEventListener('click', onCancelButtonClick); commentsLoaderElement.addEventListener('click', onCommentsLoaderClick); export { openPictureModal };
#pragma once #include "GPUResource.h" #include "../Container/Ptr.h" #include "../Container/Vector.h" #include "../Core/Object.h" namespace Joestar { enum class ImageType { TYPE_1D = 0, TYPE_2D = 1, TYPE_3D = 2, TypeCount }; enum class ImageViewType { TYPE_1D = 0, TYPE_2D = 1, TYPE_3D = 2, TYPE_CUBE = 3, TYPE_1D_ARRAY = 4, TYPE_2D_ARRAY = 5, TYPE_CUBE_ARRAY = 6, }; //How To Use Image, You may also check Vulkan's VkImageUsageFlagBits enum class ImageUsageBits { TRANSFER_SRC_BIT = 0x00000001, TRANSFER_DST_BIT = 0x00000002, SAMPLED_BIT = 0x00000004, STORAGE_BIT = 0x00000008, COLOR_ATTACHMENT_BIT = 0x00000010, DEPTH_STENCIL_ATTACHMENT_BIT = 0x00000020, TRANSIENT_ATTACHMENT_BIT = 0x00000040, INPUT_ATTACHMENT_BIT = 0x00000080, }; enum class ImageAspectFlagBits { COLOR_BIT = 0x00000001, DEPTH_BIT = 0x00000002, STENCIL_BIT = 0x00000004, METADATA_BIT = 0x00000008, }; enum class ImageFormat { R8G8B8A8_SRGB = 0, R8G8B8_SRGB, B8G8R8A8_SRGB, B8G8R8_SRGB, RG11B10, D24S8, D32S8, D32, R32, R16, FormatCount }; static bool IsDepthFormat(ImageFormat); static U32 GetChannels(ImageFormat); class Image; class Graphics; class GPUImage : public Object { REGISTER_OBJECT_ROOT(GPUImage); GET_SET_STATEMENT_INITVALUE(GPUResourceHandle, Handle, GPUResource::INVALID_HANDLE); GET_SET_STATEMENT_INITVALUE(ImageType, Type, ImageType::TYPE_2D); GET_SET_STATEMENT_INITVALUE(ImageFormat, Format, ImageFormat::R8G8B8A8_SRGB); GET_SET_STATEMENT_INITVALUE(U32, Width, 0); GET_SET_STATEMENT_INITVALUE(U32, Height, 0); GET_SET_STATEMENT_INITVALUE(U32, Depth, 1); GET_SET_STATEMENT_INITVALUE(U32, Layer, 1); GET_SET_STATEMENT_INITVALUE(U32, Usage, (U32)ImageUsageBits::TRANSFER_SRC_BIT | (U32)ImageUsageBits::TRANSFER_DST_BIT | (U32)ImageUsageBits::SAMPLED_BIT); GET_SET_STATEMENT_INITVALUE(U32, Samples, 1); GET_SET_STATEMENT_INITVALUE(U32, MipLevels, 1); GET_SET_STATEMENT_INITVALUE(U32, Size, 0); GET_SET_STATEMENT_PREFIX_INITVALUE(bool, WriteOnly, b, false); public: explicit GPUImage(EngineContext*); void SetImage(Image* image); void SetImages(Vector<SharedPtr<Image>>&); void SetData(U8* data); void SetSubData(U8* data, U32 offset=0); void SetRenderTarget(U32 w, U32 h); void SetSize(U32 w, U32 h, U32 d = 0); U8* GetData() { return mData; } private: U8* mData{ nullptr }; WeakPtr<Graphics> mGraphics; }; class GPUImageView : public Object { REGISTER_OBJECT_ROOT(GPUImageView); GET_SET_STATEMENT(SharedPtr<GPUImage>, Image); GET_SET_STATEMENT_INITVALUE(GPUResourceHandle, Handle, GPUResource::INVALID_HANDLE); GET_SET_STATEMENT_INITVALUE(ImageViewType, Type, ImageViewType::TYPE_2D); GET_SET_STATEMENT_INITVALUE(U32, AspectBits, (U32)ImageAspectFlagBits::COLOR_BIT); GET_SET_STATEMENT_INITVALUE(U32, BaseMipLevel, 0); GET_SET_STATEMENT_INITVALUE(U32, MipLevels, 1); GET_SET_STATEMENT_INITVALUE(U32, BaseLayer, 0); GET_SET_STATEMENT_INITVALUE(U32, Layer, 1); GET_SET_STATEMENT_PREFIX_INITVALUE(bool, WriteOnly, b, false); public: explicit GPUImageView(EngineContext*); void SetImage(Image*); void SetRenderTarget(U32 w, U32 h); void SetImages(Vector<SharedPtr<Image>>&); void SetData(U8* data); void SetFormat(ImageFormat fmt); ImageFormat GetFormat() { return mFormat; } GPUImage* GetImage(); private: WeakPtr<Graphics> mGraphics; ImageFormat mFormat{ ImageFormat::R8G8B8A8_SRGB }; }; class GPUSampler : public GPUResource {}; class GPUTexture : public GPUResource { public: GPUImage mImage; GPUSampler mSampler; }; }
import Project from "./Project/Project"; import styles from "./Projects.module.scss"; import React from "react"; import blogImg from "../../images/blog.png"; import quizImg from "../../images/quiz.png"; import hospitalWard from "../../images/hospital-ward.jpg"; import vendorsCookie from "../../images/vendors-cookie.jpg"; class Projects extends React.Component { projects = [ { id: 1, name: "Hospital - ward", url: "https://catelyn99.github.io/Hospital-ward/", technologiesUsed: "HTML, SASS, JavaScript, React", description: "Aplikacja jest odzwierciedleniem oddziału szpitalnego. Celem jest zwiększenie efektywności pracy wśród personelu medycznego oraz poprawa komunikacji na oddziale. Każdy pracownik mający aplikację może zrobić sobie szybki podgląd na zlecenia i uwagi dotyczące pacjentów. Aplikacja cały czas jest w procesie tworzenia.", img: { src: hospitalWard, alt: "The image of hospital-ward", }, }, { id: 2, name: "VENDORS-COOKIE", url: "https://catelyn99.github.io/Vendors-cookie/", technologiesUsed: "HTML, CSS, JavaScript", description: 'Aplikacja pobiera z zewnętrznego API listę vendorów i wyświetla je w popupie. Użytkownik ma możliwość wyboru i akceptacji lub odrzucenia wybranych opcji. Wybrane dane zapisywane są w pliku cookie na 24h. W tym czasie "popup" nie będzie wyświetlał się po ponownym otwarciu strony.', img: { src: vendorsCookie, alt: "The image of vendors-cookie", }, }, { id: 3, name: "QUIZ", url: "https://catelyn99.github.io/Quiz/quiz", technologiesUsed: "HTML, CSS, JavaScript", description: `Krótki quiz na temat HTML5. W quizie jest możliwość podsumowania punktów oraz sprawdzenia poprawnych odpowiedzi.`, img: { src: quizImg, alt: "The image of quiz", }, }, ]; render() { const projectsHTML = this.projects.map((item) => ( <Project key={item.id} project={item} /> )); return ( <> <div className={styles.name}>Projekty</div> <div className={styles.container}>{projectsHTML}</div> </> ); } } export default Projects;
import mongoose, { Schema, Document, Types } from 'mongoose' import uniqueValidator from 'mongoose-unique-validator' interface HashtagDocument extends Document { nombre: string } const hashtagSchema = new Schema<HashtagDocument>({ nombre: { type: String, required: true, minlength: 5, maxlength: 20, unique: true } }) hashtagSchema.plugin(uniqueValidator) const HashtagModel = mongoose.model<HashtagDocument>('Hashtag', hashtagSchema, 'hashtags') export { HashtagModel, HashtagDocument }
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: q = [root, root] while q: l = q.pop(0) r = q.pop(0) if l and r: if l.val != r.val: return False q.append(l.left) q.append(r.right) q.append(l.right) q.append(r.left) if not l and not r: continue if not l or not r: return False return True # return self.walk(root, root) def walk(self, left, right) -> bool: if not left and not right: return True if not left or not right: return False if left.val != right.val: return False return self.walk(left.left, right.right) and self.walk(left.right, right.left)
# script1-dpr-overview.R # # Examine files in the yearly CA Dept. Pest. Reg. Pesticide use repor # library(tidyverse) list.files() # narrows to 2 subdirectories list.files("./pur2018") # demonstrates valid path # path for second level DPR subdirectory containing 2018 data path_dat <- paste0(path_subdir,"/pur2018") list.files("./pur2018") #76 files # [1] "adjuvant_info.pdf" "cd_doc.pdf" "changes2018.txt" # [4] "chem_cas.txt" "chemical.txt" "county.txt" # [7] "debug.log" "diagram.pdf" "error_descriptions.txt" # [10] "errors_readme.pdf" "errors_readme.txt" "errors2018.txt" # [13] "ex_sum_18.pdf" "formula.txt" "outlier2018.txt" # [16] "product.txt" "qualify.txt" "qualify_readme.txt" # [19] "site.txt" "udc18_01.txt" "udc18_02.txt" # [22] "udc18_03.txt" "udc18_04.txt" "udc18_05.txt" ### Examine files containing crop names read_csv("./pur2018/site.txt") # working dir is pur2018 so not needed # read_csv("./site.txt") mysites <- read_csv("./pur2018/site2.txt")# add back in pur2018/ mysites # site_code site_name # 1 3000 NUTS # 2 3001 ALMOND # 3 3009 WALNUT # 4 3011 PISTACHIO # unintuitively, site.txt actually contains crop names and codes. site2.txt # is the original file manually trimmed to just nut crops. Note that, *.txt # extension not withstanding, this is a csv file. ### Use site_code to extract only almond, walnut and pistachio from ### udc18_01.txt, udc18_02.txt, udc18_03.txt. Append extracted files into ### a single data frame ### Example of county-level site data for 2018 x <- read_csv("./pur2018/udc18_01.txt") x # A tibble: 36,453 x 35 # use_no prodno chem_code prodchem_pct lbs_chm_used lbs_prd_used amt_prd_used unit_of_meas acre_planted # <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <dbl> # 1 3337041 62971 6004 17.6 0.726 4.12 56 OZ 10.4 # 2 3337236 62971 6004 17.6 1.04 5.89 80 OZ 48.1 ### Get list of input files file_names <- list.files(path = "./pur2018", #take out this line to run on zachs like the whole thing after bracket recursive = TRUE, pattern = "udc18", full.names = TRUE) ### Combine 56 files of County data input_files <- read_csv(file_names, id = "file_name") ### Use a list as input, and perform this operation on each file ### Below is quasi-pseudocode. We want output files 1 to 56 for input_files[1] ### to input_files[56] nut_apps <- input_files %>% filter(site_code %in% c(3001,3009,3011)) glimpse(nut_apps) ### Leaves us with ca. 602,000 records of applications to almond, walnut, and ### pistachio sites in 2018. 35 columns. County names are embedding in file ### names. Next challenges # 1) Replace "file_name" with County name list.files() #trying to see where the county file was read_csv("./pur2018/county.txt") #getting names county_names <- read_csv("./pur2018/county.txt") # x$county_cd[x$county_cd == "01"] <- "ALAMEDA" #soo this dose work but kinda repetitive not to keen on doing this 58 times #x$county_cd[x$county_cd == county_names] # data_merged0 <- merge(x , county_names) #data_merged1 <- left_join(x, county_names, by = c()) data_merged1 <- left_join(county_names,nut_apps) # County names now in file x <- data_merged1 %>% group_by(couty_name) %>% summarise(nObs = n()) %>% arrange(desc(nObs)) %>% filter(nObs > 1000) x # A tibble: 17 x 2 # couty_name nObs # <chr> <int> # 1 STANISLAUS 95494 # 2 KERN 80671 # 3 SAN JOAQUIN 63389 x <- x %>% mutate(county_name = fct_infreq(couty_name)) x ### Plot applications to nut crop by county, top 17 counties ggplot(x, aes(x = county_name, y = nObs)) + geom_col() + coord_flip() # refinenment need. Replace x and y labels. Get bars to sore # by nObs # 2) Extract all chem_code used, and link that to a chemical name old_chem_code <- read_csv("./pur2018/chemical.txt") chem_code <- subset(old_chem_code, select= -c(chemalpha_cd)) # Could also be accomplished with dplyr::select() or with df[,c(1,3)] data_merged2 <- left_join(chem_code,data_merged1) data_merged2 # A tibble: 432,728 x 38 # chem_code chemname county_cd couty_name file_name use_no prodno prodchem_pct lbs_chm_used lbs_prd_used amt_prd_used unit_of_meas acre_planted # <dbl> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <dbl> # 1 2254 ABAMECTIN 01 ALAMEDA ./pur2018/udc18_01.~ 2.01e6 62903 8 9.87 123. 2000 OZ 500 # 2 2254 ABAMECTIN 01 ALAMEDA ./pur2018/udc18_01.~ 2.01e6 62903 8 0.560 7.00 114. OZ 28.4 # 3 2254 ABAMECTIN 01 ALAMEDA ./pur2018/udc18_01.~ 2.01e6 62903 8 1.58 19.7 320 OZ 80 ### Gets to 2 real-world questions # 1) What pesticides were used most often? and data_merged2 %>% group_by(chem_code,chemname) %>% summarise(nObs = n()) %>% filter(nObs > 1000) %>% arrange(desc(nObs)) # 2) Does which pesticide is most often used vary between counties?
const { GuildMember, MessageEmbed, MessageAttachment } = require('discord.js'); const Canvas = require('canvas'); module.exports = { name: 'guildMemberUpdate', /** * * @param {GuildMember} oldMember * @param {GuildMember} newMember */ async execute(oldMember, newMember) { const { guild } = newMember; const Thanks = new MessageEmbed().setColor('PURPLE').setAuthor({ name: `SERVER BOOSTER, ${guild.iconURL({ dynamic: true, size: 512 })}` }); if (!oldMember.premiumSince && newMember.premiumSince) { const canvas = Canvas.createCanvas(800, 250); const ctx = canvas.getContext('2d'); const background = await Canvas.loadImage('./Structures/Images/boost.jpg'); ctx.drawImage(background, 0, 0, canvas.width, canvas.height); ctx.strokeStyle = '#9B59B6'; ctx.strokeRect(0, 0, canvas.width, canvas.height); ctx.font = '38px cursive'; ctx.textAlign = 'center'; ctx.fillStyle = '#FFFFFF'; ctx.fillText(newMember.displayName, canvas.width / 2, canvas.height / 1.2); const avatar = await Canvas.loadImage(newMember.user.displayAvatarURL({ format: 'jpg' })); ctx.beginPath(); ctx.arc(125, 125, 100, 0, Math.PI * 2, true); ctx.closePath(); ctx.clip(); ctx.drawImage(avatar, 25, 25, 200, 200); const attachment = new MessageAttachment(canvas.toBuffer(), 'booster.png'); Thanks.setDescription(`Thank you for boosting the server!`); Thanks.setImage('attachment://booster.png'); await guild.systemChannel.send({ embeds: [ Thanks ], files: [ attachment ] }).catch((err) => console.log(err)); Thanks.setDescription(`Thank you for boosting the server! We love your money.`); newMember.send({ embeds: [ Thanks ] }); } } };
import React, { useEffect, useState } from "react"; import { Field } from "formik"; import PropTypes from "prop-types"; const propTypes = { questions: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, description: PropTypes.string.isRequired, organization: PropTypes.number.isRequired, })).isRequired, setAnswersCallback: PropTypes.func.isRequired, }; export function QuestionsForm({ questions, setAnswersCallback }) { const [answers, setAnswers] = useState(null); useEffect(() => { if (!answers && questions?.length) { const createdAnswers = questions.map(({ id }) => ({ question_id: id, answer_text: '' })); setAnswers(createdAnswers); setAnswersCallback(createdAnswers); } }, [questions, setAnswersCallback, answers]); const handleOnChange = questionId => ({ target: { value } }) => { const updatedAnswers = answers.map(answer => answer.question_id === questionId ? ({ question_id: questionId, answer_text: value }) : answer ); setAnswers(updatedAnswers); setAnswersCallback(updatedAnswers); } return ( <> {questions.map(question => ( <div className="form-group row" key={question.id}> <div className="col-lg-12"> <label><strong>{question.name}</strong> ({question.description})</label> <Field id={question.id} name="answer" as="textarea" className="form-control" placeholder="Your answer" onChange={handleOnChange(question.id)} /> </div> </div> ))} </> ); } QuestionsForm.propTypes = propTypes;
package finalproject; import java.util.ArrayList; import java.util.Arrays; import finalproject.system.Tile; public class TilePriorityQ { // TODO level 3: Add fields that can help you implement this data type private ArrayList<Tile> heap; // TODO level 3: implement the constructor for the priority queue public TilePriorityQ (ArrayList<Tile> vertices) { this.heap = new ArrayList<>(vertices); buildMinHeap(); } // TODO level 3: implement remove min as seen in class public Tile removeMin() { Tile minTile = heap.get(0); int lastIndex = heap.size() - 1; heap.set(0, heap.get(lastIndex)); heap.remove(lastIndex); minHeapify(0); return minTile; } // TODO level 3: implement updateKeys as described in the pdf public void updateKeys(Tile t, Tile newPred, double newEstimate) { int index = heap.indexOf(t); if (index != -1) { t.predecessor = newPred; t.costEstimate = newEstimate; int parentIndex = parent(index); if (index > 0 && heap.get(parentIndex).costEstimate > heap.get(index).costEstimate) { heapifyUp(index); } else { heapifyDown(index); } } } private void buildMinHeap() { for (int i = (heap.size() / 2) - 1; i >= 0; i--) { minHeapify(i); } } private void minHeapify(int index) { int left = 2 * index + 1; int right = 2 * index + 2; int smallest = index; if (left < heap.size() && heap.get(left).costEstimate < heap.get(smallest).costEstimate) { smallest = left; } if (right < heap.size() && heap.get(right).costEstimate < heap.get(smallest).costEstimate) { smallest = right; } if (smallest != index) { swap(index, smallest); minHeapify(smallest); } } private void heapifyUp(int index) { while (index > 0 && heap.get(parent(index)).costEstimate > heap.get(index).costEstimate) { swap(index, parent(index)); index = parent(index); } } private void heapifyDown(int index) { int left = 2 * index + 1; int right = 2 * index + 2; int smallest = index; if (left < heap.size() && heap.get(left).costEstimate < heap.get(index).costEstimate) { smallest = left; } if (right < heap.size() && heap.get(right).costEstimate < heap.get(smallest).costEstimate) { smallest = right; } if (smallest != index) { swap(index, smallest); heapifyDown(smallest); } } private int parent(int index) { return (index - 1) / 2; } // Helper method to swap two elements in the heap private void swap(int i, int j) { Tile temp = heap.get(i); heap.set(i, heap.get(j)); heap.set(j, temp); } //helper boolean methods for Djikstra public boolean isEmpty() { return heap.isEmpty(); } public boolean contains(Tile tile) { return heap.contains(tile); } }