text
stringlengths
184
4.48M
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMatchTeamPivotTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('match_team', function (Blueprint $table) { $table->integer('match_id')->unsigned()->index(); $table->foreign('match_id')->references('id')->on('matches')->onDelete('cascade'); $table->integer('team_id')->unsigned()->index(); $table->boolean('is_home'); $table->boolean('is_winner'); $table->integer('super_goals'); $table->integer('goals'); $table->integer('behinds'); $table->integer('points'); $table->foreign('team_id')->references('id')->on('teams')->onDelete('cascade'); $table->primary(['match_id', 'team_id']); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('match_team'); } }
import Vue from 'vue'; import {Button} from '../components/common/Button'; import {PlayerInputModel} from '../models/PlayerInputModel'; import {Party} from '../components/Party'; import {TranslateMixin} from './TranslateMixin'; import {PartyName} from '../turmoil/parties/PartyName'; export const SelectPartyToSendDelegate = Vue.component('select-party-to-send-delegate', { props: { playerinput: { type: Object as () => PlayerInputModel, }, onsave: { type: Function as unknown as () => (out: Array<Array<string>>) => void, }, showsave: { type: Boolean, }, showtitle: { type: Boolean, }, }, data: function() { return { selectedParty: undefined as string | undefined, }; }, components: {Button, Party}, mixins: [TranslateMixin], methods: { saveData: function() { const result: string[][] = []; result.push([]); if (this.selectedParty !== undefined) { result[0].push(this.selectedParty); } this.onsave(result); }, isDominant: function(partyName: PartyName): boolean { return partyName === this.playerinput.turmoil?.dominant; }, partyAvailableToSelect: function(partyName: PartyName): boolean { if (this.playerinput.availableParties === undefined) { return false; } else { return this.playerinput.availableParties.includes(partyName); } }, }, template: ` <div class="wf-component wf-component--select-party"> <div v-if="showtitle === true" class="nofloat wf-component-title">{{ $t(playerinput.title) }}</div> <div class="wf-component--list-party"> <label v-for="party in playerinput.turmoil.parties" :key="party.name"> <input type="radio" v-model="selectedParty" :value="party.name" v-if="partyAvailableToSelect(party.name)"/> <party :party="party" :isDominant="isDominant(party.name)" :isAvailable="partyAvailableToSelect(party.name)"/> </label> </div> <div v-if="showsave === true" class="nofloat"> <Button :onClick="saveData" :title="playerinput.buttonLabel" /> </div> </div> `, });
--- permalink: nas-audit/display-connections-external-fpolicy-servers-task.html sidebar: sidebar keywords: display, information, connections, external fpolicy servers summary: 您可以显示有关与集群或指定 Storage Virtual Machine ( SVM )的外部 FPolicy 服务器( FPolicy 服务器)连接的状态信息。此信息可帮助您确定连接了哪些 FPolicy 服务器。 --- = 显示有关连接到外部 FPolicy 服务器的信息 :allow-uri-read: [role="lead"] 您可以显示有关与集群或指定 Storage Virtual Machine ( SVM )的外部 FPolicy 服务器( FPolicy 服务器)连接的状态信息。此信息可帮助您确定连接了哪些 FPolicy 服务器。 .关于此任务 如果未指定任何参数,则此命令将显示以下信息: * SVM name * Node name * FPolicy policy name * FPolicy 服务器 IP 地址 * FPolicy 服务器状态 * FPolicy 服务器类型 除了显示有关集群或特定 SVM 上的 FPolicy 连接的信息之外,您还可以使用命令参数按其他条件筛选命令的输出。 您可以指定 `-instance` 用于显示有关列出策略的详细信息的参数。或者、您也可以使用 `-fields` 参数、以便在命令输出中仅显示指示的字段。您可以输入 `?` 之后 `-fields` 用于确定可以使用哪些字段的参数。 .步骤 . 使用相应的命令显示有关节点与 FPolicy 服务器之间连接状态的筛选信息: + [cols="35,65"] |=== | 要显示有关 FPolicy 服务器的连接状态信息 ... | 输入 ... a| 您指定的 a| `vserver fpolicy show-engine -server IP_address` a| 指定的 SVM a| `vserver fpolicy show-engine -vserver vserver_name` a| 附加了指定策略的 a| `vserver fpolicy show-engine -policy-name policy_name` a| 指定的服务器状态 a| `vserver fpolicy show-engine -server-status status` 服务器状态可以是以下状态之一: ** `connected` ** `disconnected` ** `connecting` ** `disconnecting` a| 指定类型 a| `vserver fpolicy show-engine -server-type type` FPolicy 服务器类型可以是以下类型之一: ** `primary` ** `secondary` a| 已因指定原因断开连接的 a| `vserver fpolicy show-engine -disconnect-reason text` 断开连接的原因可能有多种。以下是断开连接的常见原因: ** `Disconnect command received from CLI.` ** `Error encountered while parsing notification response from FPolicy server.` ** `FPolicy Handshake failed.` ** `SSL handshake failed.` ** `TCP Connection to FPolicy server failed.` ** `The screen response message received from the FPolicy server is not valid.` |=== .示例 此示例显示了有关 SVM vs1.example.com 上 FPolicy 服务器的外部引擎连接的信息: [listing] ---- cluster1::> vserver fpolicy show-engine -vserver vs1.example.com FPolicy Server- Server- Vserver Policy Node Server status type --------------- --------- ------------ ------------- ------------- --------- vs1.example.com policy1 node1 10.1.1.2 connected primary vs1.example.com policy1 node1 10.1.1.3 disconnected primary vs1.example.com policy1 node2 10.1.1.2 connected primary vs1.example.com policy1 node2 10.1.1.3 disconnected primary ---- 此示例仅显示有关已连接 FPolicy 服务器的信息: [listing] ---- cluster1::> vserver fpolicy show-engine -fields server -server-status connected node vserver policy-name server ---------- --------------- ----------- ------- node1 vs1.example.com policy1 10.1.1.2 node2 vs1.example.com policy1 10.1.1.2 ----
//This class represents a box with a width, height, and depth. //The variable grade is a measure of the thickness of the cardboard //used to construct the box. public class Box2 { private int width, height, depth, grade; // class constructor public Box2(int width, int height, int depth, int grade) { this.width = width; this.height = height; this.depth = depth; this.grade = grade; } // Two boxes should be considered equivalent if their volume is // the same and they are constructed out of the same grade of cardboard. // returns true if they are equivalent and false otherwise public boolean equals(Box2 b) { return this.getVolume() == b.getVolume() && this.grade == b.grade; } // If this Box is larger than the argument Box b // then return this Box - otherwise return b public Box2 larger(Box2 b) { if (b.getVolume() > this.getVolume()) { return b; } return this; } // Simple getter methods public int getGrade() { return grade; } public int getVolume() { return width * height * depth * grade; } public int getWidth() { return width; } public double getHeight() { return height; } public int getDepth() { return depth; } }
/* * Original Author -> Harry Yang (taketoday@foxmail.com) https://taketoday.cn * Copyright © TODAY & 2017 - 2022 All Rights Reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see [http://www.gnu.org/licenses/] */ package cn.taketoday.beans.factory.xml; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.List; import cn.taketoday.beans.factory.config.BeanDefinition; import cn.taketoday.beans.factory.config.TypedStringValue; import cn.taketoday.beans.factory.parsing.AliasDefinition; import cn.taketoday.beans.factory.parsing.BeanComponentDefinition; import cn.taketoday.beans.factory.parsing.ComponentDefinition; import cn.taketoday.beans.factory.parsing.ImportDefinition; import cn.taketoday.beans.factory.parsing.PassThroughSourceExtractor; import cn.taketoday.beans.factory.support.StandardBeanFactory; import cn.taketoday.beans.testfixture.beans.CollectingReaderEventListener; import cn.taketoday.core.io.ClassPathResource; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop * @author Juergen Hoeller */ @SuppressWarnings("rawtypes") public class EventPublicationTests { private final StandardBeanFactory beanFactory = new StandardBeanFactory(); private final CollectingReaderEventListener eventListener = new CollectingReaderEventListener(); @BeforeEach public void setUp() throws Exception { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.setEventListener(this.eventListener); reader.setSourceExtractor(new PassThroughSourceExtractor()); reader.loadBeanDefinitions(new ClassPathResource("beanEvents.xml", getClass())); } @Test public void defaultsEventReceived() throws Exception { List defaultsList = this.eventListener.getDefaults(); boolean condition2 = !defaultsList.isEmpty(); assertThat(condition2).isTrue(); boolean condition1 = defaultsList.get(0) instanceof DocumentDefaultsDefinition; assertThat(condition1).isTrue(); DocumentDefaultsDefinition defaults = (DocumentDefaultsDefinition) defaultsList.get(0); assertThat(defaults.getLazyInit()).isEqualTo("true"); assertThat(defaults.getAutowire()).isEqualTo("constructor"); assertThat(defaults.getInitMethod()).isEqualTo("myInit"); assertThat(defaults.getDestroyMethod()).isEqualTo("myDestroy"); assertThat(defaults.getMerge()).isEqualTo("true"); boolean condition = defaults.getSource() instanceof Element; assertThat(condition).isTrue(); } @Test public void beanEventReceived() throws Exception { ComponentDefinition componentDefinition1 = this.eventListener.getComponentDefinition("testBean"); boolean condition3 = componentDefinition1 instanceof BeanComponentDefinition; assertThat(condition3).isTrue(); assertThat(componentDefinition1.getBeanDefinitions().length).isEqualTo(1); BeanDefinition beanDefinition1 = componentDefinition1.getBeanDefinitions()[0]; assertThat(beanDefinition1.getConstructorArgumentValues().getGenericArgumentValue(String.class).getValue()).isEqualTo(new TypedStringValue("Rob Harrop")); assertThat(componentDefinition1.getBeanReferences().length).isEqualTo(1); assertThat(componentDefinition1.getBeanReferences()[0].getBeanName()).isEqualTo("testBean2"); assertThat(componentDefinition1.getInnerBeanDefinitions().length).isEqualTo(1); BeanDefinition innerBd1 = componentDefinition1.getInnerBeanDefinitions()[0]; assertThat(innerBd1.getConstructorArgumentValues().getGenericArgumentValue(String.class).getValue()).isEqualTo(new TypedStringValue("ACME")); boolean condition2 = componentDefinition1.getSource() instanceof Element; assertThat(condition2).isTrue(); ComponentDefinition componentDefinition2 = this.eventListener.getComponentDefinition("testBean2"); boolean condition1 = componentDefinition2 instanceof BeanComponentDefinition; assertThat(condition1).isTrue(); assertThat(componentDefinition1.getBeanDefinitions().length).isEqualTo(1); BeanDefinition beanDefinition2 = componentDefinition2.getBeanDefinitions()[0]; assertThat(beanDefinition2.getPropertyValues().getPropertyValue("name")).isEqualTo(new TypedStringValue("Juergen Hoeller")); assertThat(componentDefinition2.getBeanReferences().length).isEqualTo(0); assertThat(componentDefinition2.getInnerBeanDefinitions().length).isEqualTo(1); BeanDefinition innerBd2 = componentDefinition2.getInnerBeanDefinitions()[0]; assertThat(innerBd2.getPropertyValues().getPropertyValue("name")).isEqualTo(new TypedStringValue("Eva Schallmeiner")); boolean condition = componentDefinition2.getSource() instanceof Element; assertThat(condition).isTrue(); } @Test public void aliasEventReceived() throws Exception { List aliases = this.eventListener.getAliases("testBean"); assertThat(aliases.size()).isEqualTo(2); AliasDefinition aliasDefinition1 = (AliasDefinition) aliases.get(0); assertThat(aliasDefinition1.getAlias()).isEqualTo("testBeanAlias1"); boolean condition1 = aliasDefinition1.getSource() instanceof Element; assertThat(condition1).isTrue(); AliasDefinition aliasDefinition2 = (AliasDefinition) aliases.get(1); assertThat(aliasDefinition2.getAlias()).isEqualTo("testBeanAlias2"); boolean condition = aliasDefinition2.getSource() instanceof Element; assertThat(condition).isTrue(); } @Test public void importEventReceived() throws Exception { List imports = this.eventListener.getImports(); assertThat(imports.size()).isEqualTo(1); ImportDefinition importDefinition = (ImportDefinition) imports.get(0); assertThat(importDefinition.getImportedResource()).isEqualTo("beanEventsImported.xml"); boolean condition = importDefinition.getSource() instanceof Element; assertThat(condition).isTrue(); } }
--- title: LiquidCrystal_I2C layout: ardbiblio --- # LiquidCrystal_I2C Traducció de <https://github.com/mrkaleArduinoLib/LiquidCrystal_I2C> #### **Contingut** - [Introducció](#introducció) - [Crèdits](#crèdits) - [Dependencia](#dependencia) - [Interfície](#interfície) ## Introducció És la reimplementació de la biblioteca LCD Arduino estàndard, configurada per a funcionar amb pantalles LCD compatibles amb HD44780 en paral·lel i interconnectada a través d’un extensor serie I2C PCF8574 xinés. ## Crèdits La reimplementació s’ha inspirat i el crèdit és per a: - Mario H. <atmega@xs4all.nl> LiquidCrystal_I2C V2.0 - Murray R. Van Luyn <vanluynm@iinet.net.au> modificacions per a placa convertidora china I2C ## Dependencia La classe de biblioteca amplia la biblioteca del sistema Print i inclou els següents arxius d’encapçalat del sistema. - **inttypes.h:** conversions de tipus sencer. Aquest arxiu d’encapçalat inclou les definicions d’enters d’ample exacte i les amplia amb funcions addicionals proporcionades per la implementació. - **Print.h:** Clase base que proporciona `print()` y `println()`. - **Wire.h:** biblioteca TWI/I2C para Arduino & Wiring. ## Interfície Algunes de les funcions enumerades provenen de Arduino [LCD API 1.0](http://playground.arduino.cc/Code/LCDAPI), algunes d’elles són específiques per a aquesta biblioteca. És possible utilitzar funcions de la biblioteca del sistema [Print](https://github.com/mrkaleArduinoLib/LiquidCrystal_I2C#dependency), que s’amplia amb LiquidCrystal_I2C. - **Inicialització** [LiquidCrystal_I2C()](#liquidcrystal-i2c) [begin()](#begin) [init()](#init) [clear()](#clear) [home()](#home) - **Impressió** [print()](#print) [write()](#write) - **Controls de pantalla** [noDisplay()](#nodisplay) [off()](#nodisplay) [display()](#display) [on()](#display) [scrollDisplayLeft()](#scrolldisplayleft) [scrollDisplayRight()](#scrolldisplayright) [leftToRight()](#lefttoright) [rightToLeft()](#righttoleft) [noAutoscroll()](#noautoscroll) [autoscroll()](#autoscroll) [noBacklight()](#nobacklight) [backlight()](#backlight) [setBacklight()](#setbacklight) - **Manipulació del cursor** [noCursor()](#nocursor) [cursor_off()](#cursor_off) [cursor()](#cursor) [cursor_on()](#cursor_on) [noBlink()](#noblink) [blink_off()](#blink_off) [blink()](#vlink) [blink_on()](#blink_on) [setCursor()](#setcursor) - **Grafics** [init_bargraph()](#init_bargraph) [draw_horizontal_graph()](#draw_horizontal_graph) [draw_vertical_graph()](#draw_vertical_graph) - **Utilitats** [createChar()](#createchar) [load_custom_character()](#load_custom_character) [command()](#command) --- ### LiquidCrystal-I2C() #### Descripció Constructor de l’objecte que controla una pantalla LCD. Defineix la direcció de la pantalla LCD i la seua geometria. - Es poden connectar més pantalles LCD al mateix bus I2C si estan configurades per maquinari per a diferents direccions. - Per a cadascuna de les pantalles LCD, ha de crear-se un objecte independent. - Quan la pantalla s’encén, es configura de la següent manera: - Neteja la pantalla - Conjunt de funcions: - DL = 1; Dades de la interfície de 8 bits - N = 0; Pantalla d’una línia - F = 0; Tipus de lletra de caràcters de 5x8 punts - Control d’encesa/apagada de la pantalla: - D = 0; Pantalla apagada - C = 0; Cursor apagat - B = 0; Parpellejant apagat - Configuració del mode d’entrada: - I/D = 1; Augmenta en 1 - S = 0; No shift Tingueu en compte, però, que el restabliment de l’Arduino no reinicia la pantalla LCD, de manera que no podem suposar que es troba en aquest estat quan comença un esbós (i es crida al constructor). #### Sintaxi `LiquidCrystal_I2C ObjecteLCD(uint8_t addr, uint8_t cols, uint8_t rows);` #### Paràmetres - **ObjecteLCD**: Objecte que controla el LCD que es comunica en una direcció - **addr**: direcció I2C de la pantalla LCD predefinides per l’extensor de sèrie. - _Valors vàlids_: byte sense signe - _Valor predeterminat_: cap - _Valors habituals_: - 0x3F per a LCD 2004 amb 20 columnes i 4 files. - 0x27 per a LCD 1602 amb 16 columnes i 2 files. - **cols**: nombre de caràcters en una fila definit per la construcció de la pantalla LCD. - _Valors vàlids_: byte sense signe - _Valor predeterminat_: cap - _Valors habituals_: 20, 16, 8 - **rows**: nombre de files en la pantalla LCD definit per la construcció de la pantalla LCD. - _Valors vàlids_: byte sense signe - _Valor predeterminat_: cap - _Valors habituals_: 4, 2, 1 #### Retorn - **Objecte LCD**: Objecte que controla el LCD que es comunica en una direcció definida. #### Exemple `lcd = LiquidCrystal_I2C(0x27, 16, 2);` --- ### begin() #### Descripció Inicialitza la pantalla LCD amb els seus paràmetres geomètrics específics. #### Sintaxi `lcd.begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS);` #### Paràmetres - **cols**: nombre de caràcters en una fila definit per la construcció de la pantalla LCD. - _Valors vàlids_: byte sense signe - _Valor predeterminat_: cap - _Valors habituals_: 20, 16, 8 - **rows**: nombre de files en la pantalla LCD definit per la construcció de la pantalla LCD. - _Valors vàlids_: byte sense signe - _Valor predeterminat_: cap - _Valors habituals_: 4, 2, 1 - **charsize**: Geometria del caràcter de la pantalla LCD definida per una constant de biblioteca. - _Valors vàlids_: byte sense signe LCD_5x8DOTS, LCD_5x10DOT - _Valor predeterminat_: LCD_5x8DOTS #### Retorn - Cap #### Veure també [LiquidCrystal_I2C()](#liquidcrystal-i2c) [init()](#init) [Tornar a interfície](#interfície) --- ### init() #### Descripció inicialitza la pantalla amb els valors posats en el [constructor](#LiquidCrystal_I2C), neteja la pantalla i col·loca el cursor a la cantonada superior esquerra de la pantalla, és a dir, en la posició inicial 0,0. És una funció contenidora per a la funció [???](<#begin()>) amb la inicialització anterior de la biblioteca Wire. #### Sintaxi `lcd.init();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [LiquidCrystal_I2C()](#liquidcrystal-i2c) - [begin()](#begin) - [Tornar a interfície](#interfície) --- ### clear() #### Descripció Funció per a netejar tota la pantalla LCD o només una part d’una fila. - L’ús de la funció sense cap paràmetre esborra tota la pantalla. - Per a esborrar tota la fila, useu la funció només amb el primer paràmetre. - Les funcions col·loquen el cursor en la columna **i** fila d’inici després d’esborrar, és a dir, després de cridar sense paràmetres a la posició inicial (0, 0), o després de cridar amb paràmetres als inicis del segment de fila esborrat. #### Sintaxi `lcd.clear();` `lcd.clear(uint8_t rowStart, uint8_t colStart = 0, uint8_t colCnt = 255);` #### Paràmetres - **rowStart**: Número d’una fila que s’esborrarà comptant des de 0. - Valors vàlids: byte sense signe de 0 a (files - 1) del constructor - Valor predeterminat: cap - **colStart**: Número d’ordre del primer caràcter en una fila buidada comptant des de 0, des d’on comença el segment buidat. - Valors vàlids: byte sense signe de 0 a (cols - 1) del constructor - Valor predeterminat: 0 (inici d’una fila) - **colCnt**: Nombre de caràcters esborrats en una fila clara. - Valors vàlids: byte 0 sense signe a les columnes del constructor - Valor predeterminat: 255, però limitat internament a (cols – colStart) #### Retorn - Cap #### Veure també - [LiquidCrystal_I2C()](#liquidcrystal-i2c) - [Tornar a interfície](#interfície) --- ### home() #### Descripció Col·loca el cursor en la posició inicial (0, 0) i deixa els caràcters mostrats. #### Sintaxi `lcd.home();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [LiquidCrystal_I2C()](#liquidcrystal-i2c) - [clear()](#clear) - [Tornar a interfície](#interfície) --- ### print() #### Descripció Imprimeix text o números en la pantalla LCD. És una funció heretada del sistema principal. La funció està sobrecarregada i actua segons la mena de dades de les dades d’entrada a imprimir. #### Sintaxi `lcd.print(char|byte|int|long|string data, int base);` #### Paràmetres - **data**: Cadena o número que ha d’imprimir-se en la pantalla LCD des de la posició actual del cursor. - Valors vàlids: arbitrari - Valor predeterminat: cap - **base**: Base opcional en la qual imprimir números. - Valors vàlids: integer en forma de constants de preprocessador - BIN: base binària 2 - DEC: base decimal 10 - OCT: base octal 8 - HEX base hexadecimal 16 - Valor predeterminat: string #### Retorn - **ProcessBytes:** Nombre de bytes impresos correctament. #### Exemple ```Arduino lcd = LiquidCrystal_I2C(0x27, 16, 2); void setup() { lcd.print("Hello, world!"); lcd.setCursor(0, 1); lcd.print(128, HEX); } void loop() {} ``` _>Hello, world!_ _>80_ #### Veure també - [LiquidCrystal_I2C()](#liquidcrystal-i2c) - [write()](#write) - [setCursor()](#setCursor) - [Tornar a interfície](#interfície) --- ### write() #### Descripció Escriu un valor en la pantalla. #### Sintaxi `lcd.write(uint8_t value);` #### Paràmetres - **value**: Valor que s’ha d’escriure en la pantalla LCD en l’adreça configurada anteriorment. - Valors vàlids: byte sense signe - Valor predeterminat: cap #### Retorn - **ProcessBytes**: nombre de bytes processats correctament; sempre 1. #### Veure també - [LiquidCrystal_I2C()](#liquidcrystal-i2c) - [print()](#print) - [command()](#command) - [Tornar a interfície](#interfície) --- ### noDisplay() #### Descripció Apaga la pantalla ràpidament. Si la pantalla no té una opció per a encendre la pantalla, la funció simplement encén la llum de fons. #### Sintaxi `lcd.noDisplay();` `lcd.off();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [Display()](#display) - [Tornar a interfície](#interfície) --- ### display() #### Descripció Encén la pantalla ràpidament. Si la pantalla no té una opció per a apagar la pantalla, la funció simplement apaga la llum de fons. #### Sintaxi `lcd.display();` `lcd.on();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [noDisplay()](#nodisplay) - [Tornar a interfície](#interfície) --- ### scrollDisplayLeft() ### Descripció Desplaça el text de la pantalla cap a l’esquerra sense canviar la RAM. La funció desplaça el búfer complet de 40 caràcters. Si imprimeix 40 caràcters en una fila i comença a desplaçar-se, obtindrà un bàner en moviment continu en una fila, especialment en un 1602 LCD. ### Sintaxi `lcd.scrollDisplayLeft();` ### Paràmetres - Cap ### Retorn - Cap ### Veure també - [scrollDisplayRight()](#scrolldisplayright) - [Tornar a interfície](#interfície) --- ### scrollDisplayRight() #### Descripció Desplaça el text de la pantalla cap a la dreta sense canviar la RAM. La funció desplaça el búfer complet de 40 caràcters. Si imprimeix 40 caràcters en una fila i comença a desplaçar-se, obtindrà un bàner en moviment continu en una fila, especialment en un 1602 LCD. #### Sintaxi `lcd.scrollDisplayRight();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [scrollDisplayLeft()](#scrolldisplayleft) - [Tornar a interfície](#interfície) --- ### leftToRight() #### Descripció Estableix el flux de text d’esquerra a dreta com és normal per als idiomes llatins. #### Sintaxi `lcd.leftToRight();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [rightToLeft()](#rightoleft) - [Tornar a interfície](#interfície) --- ### rightToLeft() #### Descripció Estableix el flux de text de dreta a esquerra com és normal en els idiomes àrabs. #### Sintaxi `lcd.rightToLeft();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [leftToRight()](#leftyoright) - [Tornar a interfície](#interfície) --- ### noAutoscroll() #### Descripció Justifica el text del cursor a l’esquerra. #### Sintaxi `lcd.noAutoscroll();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [autoscroll()](#autoscroll) - [Tornar a interfície](#interfície) --- ### autoscroll() #### Descripció Justifica el text del cursor a la dreta. #### Sintaxi `lcd.autoscroll();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [noAutoscroll()](#noautoscroll) - [Tornar a interfície](#interfície) --- ### noBacklight() #### Descripció Apaga la llum de fons #### Sintaxi `lcd.noBacklight();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [backlight()](#backlight) - [Tornar a interfície](#interfície) --- ### backlight() #### Descripció Apaga la llum de fons #### Sintaxi `lcd.noBacklight();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [noBacklight()](#nobacklight) - [Tornar a interfície](#interfície) --- ### noCursor() #### Descripció Apaga el cursor de bloc. #### Sintaxi `lcd.noCursor();` `lcd.cursor_off();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [cursor()](#cursor) - [Tornar a interfície](#interfície) --- ### cursor() #### Descripció Encén el cursor de bloc. #### Sintaxi `lcd.Cursor();` `lcd.cursor_on();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [noCursor()](#nocursor) - [Tornar a interfície](#interfície) --- ### noBlink() #### Descripció Apaga el cursor de subratllat parpadejant. #### Sintaxi `lcd.noBlink();` `lcd.blink_off();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [blink()](#blink) - [Tornar a interfície](#interfície) --- ### blink() #### Descripció Encén el cursor de subratllat parpadejant. #### Sintaxi `lcd.blink();` `lcd.blink_on();` #### Paràmetres - Cap #### Retorn - Cap #### Veure també - [noBlink()](#noblink) - [Tornar a interfície](#interfície) --- ### setCursor() #### Descripció Posiciona el cursor en les coordenades indicades #### Sintaxi `lcd.setCursor(uint8_t col, uint8_t row);` #### Paràmetres - **col**: Número d’una columna on se situarà el cursor comptant des de 0. - Valors vàlids: byte sense signe 0 a cols - 1 del constructor - Valor predeterminat: cap - **row**: Número d’una fila on se situarà el cursor comptant des de 0. - Valors vàlids: byte sense signe 0 a files - 1 del constructor - Valor predeterminat: cap #### Retorn - Cap #### Veure també - [home()](#home) - [Tornar a interfície](#interfície) --- ### init_bargraph() #### Descripció Inicialitza un gràfic de barres particular. La funció crea un conjunt de caràcters personalitzats per a mostrar gràfics de barres. Alguns dels primers caràcters personalitzats actuals (5 o 8) se sobreescriuran segons la mena de gràfic. #### Sintaxi `lcd.init_bargraph(uint8_t graphtype);` #### Paràmetres - **graphtype**: tipus de gràfic. - Valors vàlids: enter sense signe - LCDI2C_VERTICAL_BAR_GRAPH: reescriu els 8 caràcters personalitzats - LCDI2C_HORITZONTAL_BAR_GRAPH: reescriu els primers 5 caràcters personalitzats - LCDI2C_HORITZONTAL_LINE_GRAPH: reescriu els primers 5 caràcters personalitzats - Valor predeterminat: cap #### Retorn - ResultCode: codi numèric que determina el processament de la inicialització. - 0: èxit - 1: error, p. ex., Tipus de gràfic no reconegut #### Veure també - [draw_horizontal_graph()](#draw_horizontal_graph) - [draw_vertical_graph()](#draw_vertical_graph) - [Tornar a interfície](#interfície) --- ### draw_horizontal_graph() #### Descripció Mostra un gràfic horitzontal des de la posició desitjada del cursor amb el valor d’entrada. - El gràfic de barres es compon eventualment de caràcters rectangulars complets sòlids, excepte el caràcter final amb barres verticals reduïdes. El valor del gràfic de barres es mostra com un nombre equivalent de canonades en el segment del gràfic. - El gràfic de línies es compon d’una canonada que travessa una fila de LCD. El valor del gràfic de barres es mostra com una canonada en la posició de punt equivalent en el segment del gràfic. - La funció està sobrecarregada per la mena de dades d’un valor de gràfic mostrat, la qual cosa determina la seua forma. - El valor zero del gràfic es mostra com la canonada de l’extrem esquerre en el segment del gràfic degut al recompte des de 0, de manera que el gràfic sempre mostra alguna cosa. #### Sintaxi `lcd.draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end);` `lcd.draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint16_t percentage);` `lcd.draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, float ratio);` #### Paràmetres - **row**: Posició de fila del segment de gràfic comptant des de 0 fins al nombre físic de files. - Valors vàlids: sencer no negatiu 0 a files - 1 del constructor - Valor predeterminat: cap - **col**: Posició de la columna del segment del gràfic comptant des de 0 nombre físic de columnes en una fila. - Valors vàlids: sencer no negatiu 0 a cols - 1 del constructor - Valor predeterminat: cap - **len**: Longitud d’un segment de gràfic en caràcters limitada a les columnes físiques restants des de la posició de la columna inicial. - Valors vàlids: sencer no negatiu 0 a cols - col del constructor - Valor predeterminat: cap - **píxel_col_end**: Valor mostrat en canonades (punts horitzontals) comptant des de 0 fins al nombre de canonades del segment del gràfic. Un esbós ha de calcular el nombre de canonades de segment per a assigne un valor d’aplicació al valor mostrat. - Valors vàlids: sencer no negatiu de 0 a 5 \* len - Valor predeterminat: cap - **percentatge**: valor mostrat en percentatge de la longitud d’un segment de gràfic. El valor acceptat s’arredoneix a un enter per cent. - Valors vàlids: sencer no negatiu de 0 a 100 - Valor predeterminat: cap - **ràtio**: valor mostrat com un fragment de la longitud d’un segment de gràfic. - Valors vàlids: decimal no negatiu de 0 a 1. - Valor predeterminat: cap #### Retorn - Cap #### Veure també - [init_bargraph()](#init_bargraph) - [draw_vertical_graph()](#draw_vertical_graph) - [Tornar a interfície](#interfície) --- ### draw_vertical_graph() #### Descripció Mostra la barra vertical des de la posició desitjada del cursor amb el valor d’entrada. - El gràfic de barres es compon eventualment de caràcters rectangulars complets sòlids, excepte el caràcter final amb guions horitzontals reduïts. El valor del gràfic de barres es mostra com un nombre equivalent de guions en el segment del gràfic. - La funció està sobrecarregada per la mena de dades d’un valor de gràfic mostrat, la qual cosa determina la seua forma. #### Sintaxi `lcd.draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_row_end);` `lcd.draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint16_t percentage);` `lcd.draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, float ratio);` #### Paràmetres - **row**: Posició de fila del segment de gràfic comptant des de 0 fins al nombre físic de files. - Valors vàlids: sencer no negatiu 0 a files - 1 del constructor - Valor predeterminat: cap - **col**: Posició de la columna del segment del gràfic comptant des de 0 nombre físic de columnes en una fila. - Valors vàlids: sencer no negatiu 0 a cols - 1 del constructor - Valor predeterminat: cap - **len**: Longitud d’un segment de gràfic en caràcters limitada a les columnes físiques restants des de la posició de la columna inicial. - Valors vàlids: sencer no negatiu 0 a cols - col del constructor - Valor predeterminat: cap - **píxel_col_end**: Valor mostrat en canonades (punts horitzontals) comptant des de 0 fins al nombre de canonades del segment del gràfic. Un esbós ha de calcular el nombre de canonades de segment per a assigne un valor d’aplicació al valor mostrat. - Valors vàlids: sencer no negatiu de 0 a 5 \* len - Valor predeterminat: cap - **percentatge**: valor mostrat en percentatge de la longitud d’un segment de gràfic. El valor acceptat s’arredoneix a un enter per cent. - Valors vàlids: sencer no negatiu de 0 a 100 - Valor predeterminat: cap - **ràtio**: valor mostrat com un fragment de la longitud d’un segment de gràfic. - Valors vàlids: decimal no negatiu de 0 a 1. - Valor predeterminat: cap #### Retorn - Cap #### Veure també - [init_bargraph()](#init_bargraph) - [draw_horizontal_graph()](#draw_horizontal_graph) - [Tornar a interfície](#interfície) --- ### createChar() #### Descripció Ompli les primeres 8 ubicacions de RAM del generador de caràcters (CGRAM) amb caràcters personalitzats. #### Sintaxi `lcd.createChar(uint8_t, uint8_t[]);` `lcd.load_custom_character(uint8_t char_num, uint8_t *rows);` #### Paràmetres - **char_num**: posició d’un caràcter personalitzat en CGRAM per a caràcters personalitzats. - Valors vàlids: 0 - 7 - Valor predeterminat: cap - **uint8_t \[\]**: matriu de definicions de caràcters personalitzats. - Valors vàlids: patrons de bytes de fila de caràcters des de la part superior del char. - Longitud de matriu de 8 bytes per a caràcters de 5x8. - Longitud de la matriu 10 bytes per a 5x10 caràcters. - Valor predeterminat: cap - **\*rows**: punter a la matriu de definicions de caràcters personalitzats. #### Retorn - Cap #### Veure també - [init_bargraph()](#init_bargraph) - [Tornar a interfície](#interfície) --- ### command() #### Descripció Envia un comando a la pantalla. És útil per a comandos no compatibles amb la biblioteca. #### Sintaxi `lcd.command(uint8_t value);` #### Paràmetres - **valor**: codi de comando que ha d’enviar-se a la pantalla LCD. - Valors vàlids: byte sense signe - Valor predeterminat: cap #### Retorn - Cap #### Veure també - [write()](#write) - [Tornar a interfície](#interfície)
`timescale 1ns/10ps module neg_tb; reg PCout, Zlowout, MDRout, R2out, R3out; // add any other signals to see in your simulation reg MARin, Zlowin, PCin, MDRin, IRin, Yin; reg IncPC, Read, NEG, R1in, R2in, R3in; reg clock, clear; reg [31:0] Mdatain; parameter Default = 4'b0000, Reg_load1a = 4'b0001, Reg_load1b = 4'b0010, Reg_load2a = 4'b0011, Reg_load2b = 4'b0100, Reg_load3a = 4'b0101, Reg_load3b = 4'b0110, T0 = 4'b0111, T1 = 4'b1000, T2 = 4'b1001, T3 = 4'b1010, T4 = 4'b1011, T5 = 4'b1100; reg [3:0] Present_state = Default; DataPath DUT(.clock(clock), .clear(clear), .R1in(R1in), .R2in(R2in), .R3in(R3in), .R2out(R2out), .R3out(R3out), .MDRin(MDRin), .MARin(MARin), .PCin(PCin), .MD_read(Read), .Zlowin(Zlowin), .Zlowout(Zlowout), .IncPC(IncPC), .Yin(Yin), .IRin(IRin), .Mdatain(Mdatain), .MDRout(MDRout)); // add test logic here initial begin clock = 0; clear = 0; forever #10 clock = ~ clock; end always @(posedge clock) // finite state machine; if clock rising-edge begin case (Present_state) Default : #40 Present_state = Reg_load1a; Reg_load1a : #40 Present_state = Reg_load1b; Reg_load1b : #40 Present_state = Reg_load2a; Reg_load2a : #40 Present_state = Reg_load2b; Reg_load2b : #40 Present_state = Reg_load3a; Reg_load3a : #40 Present_state = Reg_load3b; Reg_load3b : #40 Present_state = T0; T0 : #40 Present_state = T1; T1 : #40 Present_state = T2; T2 : #40 Present_state = T3; T3 : #40 Present_state = T4; T4 : #40 Present_state = T5; endcase end always @(Present_state) // do the required job in each state begin case (Present_state) // assert the required signals in each clock cycle Default: begin PCout <= 0; Zlowout <= 0; MDRout <= 0; // initialize the signals R2out <= 0; R3out <= 0; MARin <= 0; Zlowin <= 0; PCin <=0; MDRin <= 0; IRin <= 0; Yin <= 0; IncPC <= 0; Read <= 0; NEG <= 0; R1in <= 0; R2in <= 0; R3in <= 0; Mdatain <= 32'h00000000; end //------------------------------------------------------------ Reg_load1a: begin Mdatain <= 32'h00000006; //sends data to MDMux Read = 0; MDRin = 0; // does nothing #10 Read <= 1; MDRin <= 1; //sets BusMuxInMDR to Mdatain #15 Read <= 0; MDRin <= 0; //read selects Busmux out, MDRin disables MDR end Reg_load1b: begin #10 MDRout <= 1; R2in <= 1; //MDRout = 1 sets BusMuxOut to BusMuxInMDR aka Mdatain //R2in = 1 enables R2in, sets BMInR2 to BusMuxOut #15 MDRout <= 0; R2in <= 0; //MDRout dissables bus change, R2in dissables register R2 change end //------------------------------------------------------------ Reg_load2a: begin Mdatain <= 32'h00000014; #10 Read <= 1; MDRin <= 1; #15 Read <= 0; MDRin <= 0; //puts Mdatain to BusMuxInMDR end Reg_load2b: begin #10 MDRout <= 1; R3in <= 1; #15 MDRout <= 0; R3in <= 0; // initialize R3 with the value $14 //puts BusMuxInMDR to BusMuxOut to Register 3 (BMInR3) end //------------------------------------------------------------ Reg_load3a: begin Mdatain <= 32'h00000018; #10 Read <= 1; MDRin <= 1; #15 Read <= 0; MDRin <= 0; //puts Mdatain to BusMuxInMDR end Reg_load3b: begin #10 MDRout <= 1; R1in <= 1; #15 MDRout <= 0; R1in <= 0; // initialize R1 with the value $18 //puts BusMuxInMDR to BusMuxOut to Register 1 (BMInR1) end //------------------------------------------------------------ T0: begin // see if you need to de-assert these signals #10 PCout <= 1; MARin <= 1; IncPC <= 1; Zlowin <= 1; #15 PCout <= 0; MARin <= 0; IncPC <= 0; Zlowin <= 0; end T1: begin #10 Zlowout <= 1; PCin <= 1; Read <= 1; MDRin <= 1; Mdatain <= 4'b0010; // opcode for “NEG R2” #15 Zlowout <= 0; PCin <= 0; Read <= 0; MDRin <= 0; end T2: begin #10 MDRout <= 1; IRin <= 1; //transfers MDR contents to IR reg #15 MDRout <= 0; IRin <= 0; end T3: begin #10 R2out <= 1; Yin <= 1; //transfers R2 contents to Y reg #15 R2out <= 0; Yin <= 0; end T4: begin #10 R3out <= 1; NEG <= 1; Zlowin <= 1; //transfers R3 to bus, does OR, Z takes in OR result #15 R3out <= 0; NEG <= 0; Zlowin <= 0; end T5: begin #10 Zlowout <= 1; R1in <= 1; //transfers zlow contents into R1 #15 Zlowout <= 0; R1in <= 0; end endcase end endmodule
doctype html html(lang='en') head meta(charset='utf-8') title Office Shop meta(name='viewport', content='width=device-width, initial-scale=1.0') meta(name='description', content='') meta(name='author', content='') // Bootstrap styles link(href='assets/css/bootstrap.css', rel='stylesheet') // Customize styles link(href='style.css', rel='stylesheet') style(type='text/css'). .my-alert { overflow: hidden; position: fixed; /* Set to fixed position */ top: 0; /* set position at the top of the page */ right: auto; } // font awesome styles link(href='assets/font-awesome/css/font-awesome.css', rel='stylesheet') //if IE 7 link(href='css/font-awesome-ie7.min.css', rel='stylesheet') //if lt IE 9 script(src='http://html5shim.googlecode.com/svn/trunk/html5.js') // Favicons link(rel='shortcut icon', href='assets/ico/favicon.ico') body //Lower Header Section .container #gototop include ./navbar.jade // Body Section .row #sidebar.span3 .well.well-small ul.nav.nav-list each cat in data.cats li a(href="/category/#{cat.id}/1/*?page=1") span.icon-chevron-right #{cat.name} .span9 .well.np #myCarousel.carousel.slide.homCar .carousel-inner each item, index in data.cats if index == 0 .item.active img(style='width:100%; height:320px', src='/images/#{item.img}') .carousel-caption h4 #{item.name} else .item img(style='width:100%; height:320px', src='/images/#{item.img}') .carousel-caption h4 #{item.name} a.left.carousel-control(href='#myCarousel', data-slide='prev') ‹ a.right.carousel-control(href='#myCarousel', data-slide='next') › //New Products .well.well-small h3 New Products hr.soften .row-fluid #newProductCar.carousel.slide .carousel-inner .item.active ul.thumbnails each prod, index in data.eight if index < 4 li.span3 .thumbnail img(style="height:150px" src='#{prod.img}') .item ul.thumbnails each prod, index in data.eight if index >= 4 li.span3 .thumbnail img(style="height:150px" src='#{prod.img}') a.left.carousel-control(href='#newProductCar', data-slide='prev') ‹ a.right.carousel-control(href='#newProductCar', data-slide='next') › .row-fluid ul.thumbnails each prod in data.three li.span4 .thumbnail img(style="height:250px" src='#{prod.img}') .caption.cntr p #{prod.name} p strong $#{prod.price} .actionList br.clr div.alert.alert-success.pull-right.my-alert(id='ver-alert' style='width:40%; height:24px; display:none; padding: 5px;') strong A Verification message has been sent to your email div.alert.alert-success.pull-right.my-alert(id='info-alert' style='width:40%; height:24px; display:none; padding: 5px;') strong Your profile information has been successfuly changed div.alert.alert-success.pull-right.my-alert(id='pass-alert' style='width:40%; height:24px; display:none; padding: 5px;') strong Your password has been successfuly changed div.alert.alert-success.pull-right.my-alert(id='GRM-alert' style='width:40%; height:24px; display:none; padding: 5px;') strong A mail with your password has been sent, please change it as soon as possible div.alert.alert-danger.pull-right.my-alert(id='GARM-alert' style='width:40%; height:24px; display:none; padding: 5px;') strong Already registered with this email div.alert.alert-success.pull-right.my-alert(id='fpe-alert' style='width:40%; height:24px; display:none; padding: 5px;') strong A link to change your password has been sent to your email // Placed at the end of the document so the pages load faster script(src='assets/js/jquery.js') script(src='assets/js/bootstrap.min.js') script(src='assets/js/jquery.easing-1.3.min.js') script(src='assets/js/jquery.scrollTo-1.4.3.1-min.js') script(src='assets/js/shop.js') script. //make link with black bg $('#nav-home').parent().addClass('active'); function showAlert(id){ $(id).show(); //- $('.my-alert').hide(); } function addTrailingZeros(number) { // todo use this func return parseFloat(Math.round(number * 100) / 100).toFixed(2); }, if data.pc script. $(document).ready(function(){ let alert = $('#pass-alert'); alert.show(); setTimeout(() => {alert.hide();}, 2000); }); if data.pi script. $(document).ready(function(){ let alert = $('#info-alert'); alert.show(); setTimeout(() => {alert.hide();}, 2000); }); if data.reg script. $(document).ready(function(){ let alert = $('#ver-alert'); alert.show(); setTimeout(() => {alert.hide();}, 2000); }); if data.GRM script. $(document).ready(function(){ let alert = $('#GRM-alert'); alert.show(); setTimeout(() => {alert.hide();}, 4000); }); if data.GARM script. $(document).ready(function(){ let alert = $('#GARM-alert'); alert.show(); setTimeout(() => {alert.hide();}, 3000); }); if data.fpe script. $(document).ready(function(){ let alert = $('#fpe-alert'); alert.show(); setTimeout(() => {alert.hide();}, 3000); });
package xyz.xzaslxr.guidance; import edu.berkeley.cs.jqf.fuzz.guidance.Guidance; import edu.berkeley.cs.jqf.fuzz.guidance.GuidanceException; import edu.berkeley.cs.jqf.fuzz.guidance.Result; import edu.berkeley.cs.jqf.fuzz.guidance.TimeoutException; import edu.berkeley.cs.jqf.fuzz.util.Coverage; import edu.berkeley.cs.jqf.fuzz.util.ICoverage; import edu.berkeley.cs.jqf.fuzz.util.IOUtils; import edu.berkeley.cs.jqf.instrument.tracing.events.TraceEvent; import org.eclipse.collections.api.iterator.IntIterator; import org.eclipse.collections.api.list.primitive.IntList; import org.eclipse.collections.impl.set.mutable.primitive.IntHashSet; import xyz.xzaslxr.fuzzing.FuzzException; import xyz.xzaslxr.utils.coverage.ChainsCoverage; import xyz.xzaslxr.utils.setting.ChainPaths; import xyz.xzaslxr.utils.setting.ReadChainPathsConfigure; import java.io.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; /** * A guidance that performs chains-coverage-guided fuzzing using two coverage maps, * one for total coverage and one for chains coverage. * @author fe1w0 * <p> This class learn from the <a href="https://github.com/rohanpadhye/JQF/wiki/The-Guidance-interface">jqf-wiki: The Guidance interface</a> * and ZestGuidance * </p> */ public class ChainsCoverageGuidance implements Guidance { // ---------- Primary Parameter ---------- /** * A pseudo-random number generator for generating fresh values. * <p> * 预先的随机数字生成器,用于后续的变量随机。 * </p> */ protected Random random; /** The name of the test for display purposes. * <p> * 被Fuzzing的函数名 * </p> * */ protected String testName; // ---------- Algorithm Parameters ---------- /** The max amount of time to run for, in milliseconds * <p>允许允许的最多时间,单位为秒</p> */ protected long maxDurationMillis; /** The number of trials completed. * 当前有多少尝试完成 * */ protected long numTrials = 0; protected long numValid = 0; /** The max number of trials to run * 设置的最多尝试次数 * */ protected long maxTrials; /** Time since this guidance instance was created. * <p> * ChainsCG 实例被创建的时间。 * </p> * */ protected Date startTime = new Date(); /** Whether to stop/exit once a crash is found. * <p> * 当被测试的产生奔溃时,是否停止或退出 * </p> * */ protected boolean EXIT_ON_CRASH = Boolean.getBoolean("jqf.ei.EXIT_ON_CRASH"); /** The set of unique failures found so far. * <p> * 到目前为止,发现的独特错误 * </p> * */ protected Set<String> uniqueFailures = new HashSet<>(); public int failures; // ---------- Fuzzing Input and Coverage ---------- protected String chainsConfigPath; protected Map<Integer, String> chainPaths = new ConcurrentHashMap<>(); /** validityFuzzing -- if true then save valid inputs that increase valid * coverage */ protected boolean validityFuzzing; /** * Number of saved inputs. * * This is usually the same as savedInputs.size(), * but we do not really save inputs in TOTALLY_RANDOM mode. */ protected int numSavedInputs = 0; /** Coverage statistics for a single run. */ protected ICoverage runCoverage = new ChainsCoverage(); protected ICoverage totalCoverage = new Coverage(); protected ICoverage validCoverage = new Coverage(); protected ICoverage chainsCoverage = new ChainsCoverage(); protected int maxCoverage = 0; protected int maxChainsCoverage = 0; protected Map<Object, Input> responsibleInputs = new HashMap<>(totalCoverage.size()); /** Set of saved inputs to fuzz. */ protected ArrayList<Input> savedInputs = new ArrayList<>(); /** Queue of seeds to fuzz. * <p> * seedInputs 只表示,一开始从SeedFile中生成PUT的Input * </p> */ protected Deque<Input> seedInputs = new ArrayDeque<>(); /** * Current input that's running -- valid after getInput() and before * handleResult(). */ protected Input<?> currentInput; /** * currentParentInputIdx 用于当 seedInput 为空,从非空的savedInput获取前父输入,以此构建新的 currentInput */ protected int currentParentInputIdx = 0; /** * 为当前父输入生成的子输入个数 */ protected int numChildrenGeneratedForCurrentParentInput = 0; // --------- Debug and Logging --------- /** Number of conditional jumps since last run was started. */ protected long branchCount = 0; /** * Number of cycles completed, i.e. how many times we've reset currentParentInputIdx to 0. */ protected int cyclesCompleted = 0; /** Number of favored inputs in the last cycle. */ protected long numFavoredLastCycle = 0; /** * 存储debug信息 */ public static File logFile; /** Whether to print log statements to stderr (debug option; manually edit). */ public static boolean verbose = true; /** The directory where fuzzing results are produced. */ protected final File outputDirectory; /** The directory where interesting inputs are saved. */ protected File savedCorpusDirectory; /** The directory where saved inputs are saved. */ protected File savedFailuresDirectory; /** * The directory where all generated inputs are logged in sub-directories (if * enabled). */ protected File allInputsDirectory; // ---------- Thread Handling ---------- /** The first thread in the application, which usually runs the test method. * * */ protected Thread firstThread; /** * Whether the application has more than one thread running coverage-instrumented code * <p> * 需要修改,需要改成新的coverage-instrumented, 记录的信息不再是 basic block 的 hashcode, * 而是其函数名。 * </p> * */ protected boolean multiThreaded = false; // ------------- FUZZING HEURISTICS ------------ /** Whether to save only valid inputs **/ protected static final boolean SAVE_ONLY_VALID = Boolean.getBoolean("jqf.ei.SAVE_ONLY_VALID"); /** Max input size to generate. */ protected static final int MAX_INPUT_SIZE = Integer.getInteger("jqf.ei.MAX_INPUT_SIZE", 10240); /** * Whether to generate EOFs when we run out of bytes in the input, instead of * randomly generating new bytes. **/ protected static final boolean GENERATE_EOF_WHEN_OUT = Boolean.getBoolean("jqf.ei.GENERATE_EOF_WHEN_OUT"); /** Baseline number of mutated children to produce from a given parent input. * <p> * Baseline: 从ParentInput中生成ChildrenInput的数量 * </p> * */ protected static final int NUM_CHILDREN_BASELINE = 50; /** * Multiplication factor for number of children to produce for favored inputs. */ protected static final int NUM_CHILDREN_MULTIPLIER_FAVORED = 20; /** Mean number of mutations to perform in each round. */ protected static final double MEAN_MUTATION_COUNT = 8.0; /** Mean number of contiguous bytes to mutate in each mutation. */ protected static final double MEAN_MUTATION_SIZE = 4.0; // Bytes /** * Whether to save inputs that only add new coverage bits (but no new * responsibilities). */ protected static final boolean DISABLE_SAVE_NEW_COUNTS = Boolean.getBoolean("jqf.ei.DISABLE_SAVE_NEW_COUNTS"); /** * Whether to steal responsibility from old inputs (this increases computation * cost). */ protected static final boolean STEAL_RESPONSIBILITY = Boolean.getBoolean("jqf.ei.STEAL_RESPONSIBILITY"); // ------------- TIMEOUT HANDLING ------------ private long singleRunTimeoutMillis; private Date runStart; // -------- Initialization -------- public ChainsCoverageGuidance(String testName, Duration duration, Long trials, File outputDirectory, File seedInputDir, Random sourceOfRandomness, String chainsConfigPath) throws IOException{ this(testName, duration, trials, outputDirectory, IOUtils.resolveInputFileOrDirectory(seedInputDir), sourceOfRandomness, chainsConfigPath); } public ChainsCoverageGuidance(String testName, Duration duration, Long trials, File outputDirectory, File[] seedInputFiles, Random sourceOfRandomness, String chainsConfigPath) throws IOException { this(testName, duration, trials, outputDirectory, sourceOfRandomness, chainsConfigPath); if (seedInputFiles != null) { for (File seedInputFile : seedInputFiles) { seedInputs.add(new SeedInput(seedInputFile)); } } } public ChainsCoverageGuidance(String testName, Duration duration, Long trials, File outputDirectory, Random sourceOfRandomness, String chainsConfigPath) throws IOException { this.random = sourceOfRandomness; this.testName = testName; this.maxDurationMillis = duration != null ? duration.toMillis() : Long.MAX_VALUE; this.maxTrials = trials != null ? trials : Long.MAX_VALUE; this.outputDirectory = outputDirectory; this.validityFuzzing = !Boolean.getBoolean("jqf.ei.DISABLE_VALIDITY_FUZZING"); this.chainsConfigPath = chainsConfigPath; ReadChainPathsConfigure reader = new ReadChainPathsConfigure(); ChainPaths tmpChainPaths = reader.readConfiguration(chainsConfigPath, new ChainPaths()); // prepare chainsPaths for (String path: tmpChainPaths.getPaths()) { this.chainPaths.put(path.hashCode(), path); } runCoverage = new ChainsCoverage(chainPaths); prepareOutputDirectory(); String timeout = System.getProperty("jqf.ei.TIMEOUT"); if (timeout != null && !timeout.isEmpty()) { try { // Interpret the timeout as milliseconds (just like `afl-fuzz -t`) this.singleRunTimeoutMillis = Long.parseLong(timeout); } catch (NumberFormatException e1) { throw new IllegalArgumentException("Invalid timeout duration: " + timeout); } } } /** * Todo: 需要自定义修改 * @throws IOException */ private void prepareOutputDirectory() throws IOException { // Create the output directory if it does not exist IOUtils.createDirectory(outputDirectory); // Name files and directories after AFL this.savedCorpusDirectory = IOUtils.createDirectory(outputDirectory, "corpus"); this.savedFailuresDirectory = IOUtils.createDirectory(outputDirectory, "failures"); this.logFile = new File(outputDirectory, "fuzz.log"); logFile.delete(); for (File file : savedCorpusDirectory.listFiles()) { file.delete(); } for (File file : savedFailuresDirectory.listFiles()) { file.delete(); } } // -------- Basic Method -------- /** * 检查是否有新的输入: * <p>参考: * edu.berkeley.cs.jqf.fuzz.ei.ZestGuidance#hasInput() * </p> * @return boolean */ @Override public boolean hasInput() { Date now = new Date(); long elapsedMilliseconds = now.getTime() - startTime.getTime(); if (EXIT_ON_CRASH && !uniqueFailures.isEmpty()) { // exit return false; } if (elapsedMilliseconds < maxDurationMillis && numTrials < maxTrials) { return true; } else { displayStats(true); infoLog("failures: %d", failures); infoLog("numTrials: %s", numTrials); if (failures != 0 ) { infoLog("effectiveness: %d", numTrials/failures); } return false; } } // --------- JQF Basic Frame --------- /** * 得到新的程序输入 * <p>参考: * edu.berkeley.cs.jqf.fuzz.ei.ZestGuidance#getInput() * </p> * @return java.io.InputStream */ @Override public InputStream getInput() throws IllegalStateException, GuidanceException { // 参考 ZestGuidance 代码,需要考虑到 多线程的问题 conditionallySynchronize(multiThreaded, () -> { // 初始化 runCoverage.clear(); // Choose an input to execute based on state of queues if (!seedInputs.isEmpty()) { // 当 seedInputs 非空时,表示保存有效的种子 // First, if we have some specific seeds, use those // 优先使用 seedInputs 前面的流量 // seedInputs 只会在此处进行消耗 currentInput = seedInputs.removeFirst(); } else if (savedInputs.isEmpty()) { //当 savedInputs 和 seedInput 都为空时 // If no seeds given try to start with something random if (numTrials > 100_000) { throw new GuidanceException("Too many trials; " + "likely all assumption violations"); } // Make fresh input using either list or maps infoLog("Spawning new input from thin air"); // 创建一个全新的inputs队列 currentInput = createFreshInput(); } else { // 当 seedInputs 为空,savedInputs 为非空 // The number of children to produce is determined by how much of the coverage // pool this parent input hits // 当前的新input内容受到之前父input的覆盖率所决定 Input currentParentInput = savedInputs.get(currentParentInputIdx); int targetNumChildren = getTargetChildrenForParent(currentParentInput); // 超出当前的基线,需要刷新 numChildrenGeneratedForCurrentParentInput if (numChildrenGeneratedForCurrentParentInput >= targetNumChildren) { // Select the next saved input to fuzz currentParentInputIdx = (currentParentInputIdx + 1) % savedInputs.size(); // Count cycles if (currentParentInputIdx == 0) { completeCycle(); } numChildrenGeneratedForCurrentParentInput = 0; } Input parent = savedInputs.get(currentParentInputIdx); // Fuzz it to get a new input currentInput = parent.fuzz(random); infoLog("Mutating input: %s", parent.desc + "\tnewInput: " + currentInput.desc); // numChildrenGeneratedForCurrentParentInput 自增 numChildrenGeneratedForCurrentParentInput++; // 细节: // 第一次执行时,原 Zest 算法不会产生新的runStart this.runStart = new Date(); // handleEvent时,会 ++this.branchCount this.branchCount = 0; } }); return createParameterStream(); } /** * 注册处理Event的函数 * <p>⚠️ 需要注意: generateCallBack 在 JQF中的 执行顺序上优于 handleResult</p> * @param thread the thread whose events to handle * @return Consumer<TraceEvent> */ @Override public Consumer<TraceEvent> generateCallBack(Thread thread) { if (firstThread == null) { firstThread = thread; } else if (firstThread != thread) { multiThreaded = true; } return this::handleEvent; } /** * * @param result the result of the fuzzing trial * @param error the error thrown during the trial, or <code>null</code> */ @Override public void handleResult(Result result, Throwable error) throws GuidanceException { conditionallySynchronize(multiThreaded, () -> { // Stop timeout handling this.runStart = null; // Increment run count this.numTrials++; boolean valid = result == Result.SUCCESS; if (valid) { this.numValid++; } // 当前trial为成功,或者该trial中忽视 if (result == Result.SUCCESS || (result == Result.INVALID && !SAVE_ONLY_VALID)) { IntHashSet responsibilities = computeResponsibilities(valid); List<String> savingCriteriaSatisfied = checkSavingCriteriaSatisfied(result); boolean toSave = !savingCriteriaSatisfied.isEmpty(); if (toSave) { String why = String.join(" ", savingCriteriaSatisfied); // Todo: 理解 gc 的作用 currentInput.gc(); // Save input to queue and to disk final String reason = why; GuidanceException.wrap(() -> saveCurrentInput(responsibilities, reason)); } } else if (result == Result.FAILURE || result == Result.TIMEOUT) { // 需要注意的是: // 区别 FuzzException 和 其他 Exception 的区别 String msg = error.getMessage(); // Get the root cause of the failure Throwable rootCause = error; while (rootCause.getCause() != null) { rootCause = rootCause.getCause(); } if (rootCause instanceof FuzzException) { failures++; } // Attempt to add this to the set of unique failures if (uniqueFailures.add(failureDigest(rootCause.getStackTrace()))) { // Trim input (remove unused keys) currentInput.gc(); // Save crash to disk int crashIdx = uniqueFailures.size() - 1; String saveFileName = String.format("id_%06d", crashIdx); File saveFile = new File(savedFailuresDirectory, saveFileName); GuidanceException.wrap(() -> writeCurrentInputToFile(saveFile)); infoLog("%s", "Found crash: " + error.getClass() + " - " + (msg != null ? msg : "")); String how = currentInput.desc; String why = result == Result.FAILURE ? "+crash" : "+hang"; infoLog("Saved - %s %s %s", saveFile.getPath(), how, why); } } }); } // -------- Handle Events -------- /** * Handles a trace event generated during test execution. * <p>handleEvent: 处理Event的过程中,会对 totalCoverage 等信息进行更新</p> * * Not used by FastNonCollidingCoverage, which does not allocate an * instance of TraceEvent at each branch probe execution. * * @param e the trace event to be handled */ protected void handleEvent(TraceEvent e) { conditionallySynchronize(multiThreaded, () -> { // Collect totalCoverage and ChainsCoverage ((ChainsCoverage) runCoverage).handleEvent(e); // Check for possible timeouts every so often // 只有当开启 单线程时间设置 和 存在启动时间时, // 才会对 this.branchCount 进行自增计算 if (this.singleRunTimeoutMillis > 0 && this.runStart != null && (++this.branchCount) % 10_000 == 0) { long elapsed = new Date().getTime() - runStart.getTime(); if (elapsed > this.singleRunTimeoutMillis) { throw new TimeoutException(elapsed, this.singleRunTimeoutMillis); } } }); } // ------- Handle Result ------- /** * return: * <p> * (runCoverage - (totalCoverage + validCoverage) + coveredChainsMethod) * </p> * * @param valid * @return IntHashSet */ protected IntHashSet computeResponsibilities(boolean valid) { IntHashSet result = new IntHashSet(); // newValidCoverage 中保存着之前 totalCoverage中没有的新的edges信息 IntList newCoverage = runCoverage.computeNewCoverage(totalCoverage); if (!newCoverage.isEmpty()) { result.addAll(newCoverage); } // 如果当前result为有效的,则同样更新validCoverage if (valid) { IntList newValidCoverage = runCoverage.computeNewCoverage(validCoverage); if (!newValidCoverage.isEmpty()) { result.addAll(newValidCoverage); } } // 计算当前 runCoverage 中覆盖了哪些新的 ChainsPath IntList newChainsCoverage = ((ChainsCoverage)runCoverage).computeNewCoveredChainsPath(chainsCoverage); if (!newChainsCoverage.isEmpty()) { result.addAll(newChainsCoverage); } // Todo: 理解 STEAL_RESPONSIBILITY 的作用,暂时先删除 return result; } /** * 返回更新的原因 * @param result * @return */ protected List<String> checkSavingCriteriaSatisfied(Result result) { // Coverage Before // 之前,TotalCoverage的Edges数量 int nonZeroBefore = totalCoverage.getNonZeroCount(); // 之前,ValidCoverage的Edges数量 int validNonZeroBefore = validCoverage.getNonZeroCount(); boolean coverageBitsUpdated = totalCoverage.updateBits(runCoverage); if (result == Result.SUCCESS) { validCoverage.updateBits(runCoverage); } // Todo: 添加 chainsCoverage.updateBits // 当发现新的且有效的chainCoverage时,刷新chainsCoverage boolean chainsCoverageBitsUpdate = ((ChainsCoverage)chainsCoverage).updateChainsBits((ChainsCoverage) runCoverage); // Coverage after int nonZeroAfter = totalCoverage.getNonZeroCount(); if (nonZeroAfter > maxCoverage) { maxCoverage = nonZeroAfter; } int validNonZeroAfter = validCoverage.getNonZeroCount(); // Possibly save input List<String> reasonsToSave = new ArrayList<>(); if (!DISABLE_SAVE_NEW_COUNTS && coverageBitsUpdated) { reasonsToSave.add("+count"); } // Save if new total coverage found if (nonZeroAfter > nonZeroBefore) { reasonsToSave.add("+cov"); } if (chainsCoverageBitsUpdate) { reasonsToSave.add("+newChains"); } // Save if new valid coverage is found if (this.validityFuzzing && validNonZeroAfter > validNonZeroBefore) { reasonsToSave.add("+valid"); } return reasonsToSave; } // -------- Stats -------- /** * 展示Fuzzing的现状 * @param force */ private void displayStats(boolean force) { } // -------- Generate Input Part ------- /** * 生成用于 generators 的 InputStream * @return InputStream */ protected InputStream createParameterStream() { return new InputStream() { int bytesRead = 0; @Override public int read() throws IOException { // LinearInput 线性输入 assert currentInput instanceof LinearInput : "ChainsCoverageGuidance should only mutate LinearInput(s)"; // For linear inputs, get with key = bytesRead (which is then incremented) LinearInput linearInput = (LinearInput) currentInput; // Attempt to get a value from the list, or else generate a random value int ret = linearInput.getOrGenerateFresh(bytesRead++, random); infoLog("read(%d) = %d", bytesRead, ret); return ret; } }; } /** * 因为seedInput和savedInput都为空,需要产生一个全新的输入 * @return Input<?> */ protected Input<?> createFreshInput() { return new LinearInput(); } /** * 计算该父输入最多有多少子输入。 */ protected int getTargetChildrenForParent(Input parentInput) { int target = NUM_CHILDREN_BASELINE; // nonZeroCoverage: 覆盖中非空的元素数 if (maxCoverage > 0) { target = (NUM_CHILDREN_BASELINE * parentInput.nonZeroCoverage) / maxCoverage; } // isFavored的父输入,至少有一个没空覆盖元素 if (parentInput.isFavored()) { target = target * NUM_CHILDREN_MULTIPLIER_FAVORED; } return target; } protected void saveCurrentInput(IntHashSet responsibilities, String why) throws IOException { // First, save to disk (note: we issue IDs to everyone, but only write to disk // if valid) int newInputIdx = numSavedInputs++; String saveFileName = String.format("id_%06d", newInputIdx); String how = currentInput.desc; File saveFile = new File(savedCorpusDirectory, saveFileName); writeCurrentInputToFile(saveFile); infoLog("Saved - %s %s %s", saveFile.getPath(), how, why); // Second, save to queue savedInputs.add(currentInput); // Third, store basic book-keeping data currentInput.id = newInputIdx; currentInput.saveFile = saveFile; currentInput.coverage = runCoverage.copy(); currentInput.nonZeroCoverage = runCoverage.getNonZeroCount(); currentInput.offspring = 0; savedInputs.get(currentParentInputIdx).offspring += 1; // Fourth, assume responsibility for branches currentInput.responsibilities = responsibilities; if (!responsibilities.isEmpty()) { currentInput.setFavored(); } IntIterator iter = responsibilities.intIterator(); while (iter.hasNext()) { int b = iter.next(); // If there is an old input that is responsible, // subsume it Input oldResponsible = responsibleInputs.get(b); if (oldResponsible != null) { // 刷新责任对象,由新的responsibleInput来负责这个b oldResponsible.responsibilities.remove(b); infoLog("-- Stealing responsibility for %s from input %d", b, oldResponsible.id); } else { infoLog("-- Assuming new responsibility for %s", b); } // We are now responsible responsibleInputs.put(b, currentInput); } } protected void writeCurrentInputToFile(File saveFile) throws IOException { try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile))) { for (Integer b : currentInput) { assert (b >= 0 && b < 256); out.write(b); } } } // --------- Handle Exception ------ private static MessageDigest sha1; private static String failureDigest(StackTraceElement[] stackTrace) { if (sha1 == null) { try { sha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new GuidanceException(e); } } byte[] bytes = sha1.digest(Arrays.deepToString(stackTrace).getBytes()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16) .substring(1)); } return sb.toString(); } // -------- Multi thread Part ------- /** * Conditionally run a method using synchronization. * This is used to handle multithreaded fuzzing. * <p>Taking from JQF source code, ZestGuidance.</p> * <p>当 cond 为真时,以当前对象为锁,只有一个线程可以同时执行 task 中的代码。当 cond 为假时,多个线程可以同时执行 task 中的代码,没有同步限制。</p> */ protected void conditionallySynchronize(boolean cond, Runnable task) { if (cond) { synchronized (this) { task.run(); } } else { task.run(); } } /** * Handles the end of fuzzing cycle (i.e., having gone through the entire queue) * <p> * * </p> */ protected void completeCycle() { // Increment cycle count // 循环计数++ cyclesCompleted++; infoLog("\n# Cycle " + cyclesCompleted + " completed."); // Go over all inputs and do a sanity check (plus log) infoLog("Here is a list of favored inputs:"); int sumResponsibilities = 0; numFavoredLastCycle = 0; for (Input input : savedInputs) { if (input.isFavored()) { int responsibleFor = input.responsibilities.size(); infoLog("Input %d is responsible for %d branches", input.id, responsibleFor); sumResponsibilities += responsibleFor; numFavoredLastCycle++; } } int totalCoverageCount = totalCoverage.getNonZeroCount() + ((ChainsCoverage)chainsCoverage).getNonZeroChainsCount(); // int totalCoverageCount = totalCoverage.getNonZeroCount(); infoLog("Total %d branches covered", totalCoverageCount); if (sumResponsibilities != totalCoverageCount) { if (multiThreaded) { infoLog("Warning: other threads are adding coverage between test executions"); } else { throw new AssertionError("Responsibility mismatch"); } } // Break log after cycle infoLog("\n\n\n"); } // -------- Debug and Log -------- /* Writes a line of text to the log file. */ public static void infoLog(String str, Object... args) { if (verbose) { String line = String.format(str, args); if (logFile != null) { appendLineToFile(logFile, line); } else { System.err.println(line); } } } public static void appendLineToFile(File logFile, String line) { try (PrintWriter printWriter = new PrintWriter(new FileWriter(logFile, true))){ printWriter.println(line); } catch (IOException e) { throw new RuntimeException(e); } } // Output Information public ICoverage getTotalCoverage() { return totalCoverage; } }
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:test_pt_seru/presentation/components/widgets/widgets.components.dart'; class LocationField extends StatelessWidget { final Future<List<String>> Function(int, String)? items; final List<String>? selectedItems; final List<bool>? errors; final void Function(int, String)? onChange; final void Function(int)? onClear; const LocationField({ super.key, this.items, this.selectedItems, this.errors, this.onChange, this.onClear, }); List<String> get _labels => [ "Province", "City/Regency", "District", "Sub-district", ]; List<Widget> get _fields => List.generate( _labels.length, (i) => DropdownField( items: items != null ? (item) => items!(i, item) : null, selectedItem: selectedItems![i], labelText: _labels[i], error: errors![i], onChange: (str) => onChange!(i, str!), onClear: () => onClear!(i), ), ); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(horizontal: 24.w), child: Column( children: [ SizedBox(height: 8.h), _fields[0], SizedBox(height: 16.h), _fields[1], SizedBox(height: 16.h), _fields[2], SizedBox(height: 16.h), _fields[3], ], ), ); } }
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import {Component, ChangeDetectionStrategy, Input, ViewChild, Output, EventEmitter, ElementRef} from '@angular/core'; import {ContentChange, QuillEditorComponent} from 'ngx-quill'; import {defaultTextEditorOptions} from '../../../modal/text-editor/text-editor.utils'; import {FullscreenDropdownDirective} from '../../../dropdown/fullscreen/fullscreen-dropdown.directive'; import {ModalData} from '../../../../core/model/modal-data'; import {isMacOS} from '../../../utils/system.utils'; import {textContainsOnlyBrTags} from '../../../utils/string.utils'; import {keyboardEventCode, KeyCode} from '../../../key-code'; @Component({ selector: 'rich-text-dropdown', templateUrl: './rich-text-dropdown.component.html', styleUrls: ['./rich-text-dropdown.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RichTextDropdownComponent extends FullscreenDropdownDirective { @Input() public modalData: ModalData; @Input() public readonly = false; @Input() public content: string; @Input() public maxLength: number; @Input() public minLength: number; @Input() public origin: ElementRef | HTMLElement; @Output() public save = new EventEmitter<string>(); @Output() public cancel = new EventEmitter(); @Output() public dataChange = new EventEmitter<ModalData>(); @ViewChild(QuillEditorComponent) public quillEditorComponent: QuillEditorComponent; public readonly defaultOptions = defaultTextEditorOptions; public readonly macOS = isMacOS(); public valid = true; private keyboardEventListener = (event: KeyboardEvent) => { const code = keyboardEventCode(event); if (this.isOpen() && this.valid && code === KeyCode.Enter && (event.metaKey || event.ctrlKey)) { this.onSave(); } }; public contentChanged(event: ContentChange) { this.checkValid(event.text); } private checkValid(text: string) { const filterText = text.replace('\n', '').trim(); let newValid = true; if (this.minLength) { newValid = filterText.length >= this.minLength; } if (this.maxLength) { newValid = newValid && filterText.length <= this.maxLength; } if (newValid !== this.valid) { this.valid = newValid; } } public focusEditor(editor: any) { setTimeout(() => { editor.setSelection({index: Number.MAX_SAFE_INTEGER, length: 1}); editor.scrollingContainer.scrollTop = Number.MAX_SAFE_INTEGER; }, 200); } public onCancel() { this.close(); this.cancel.emit(); } public onSave() { this.close(); if (!this.readonly) { this.save.emit(this.getSaveContent()); } } private getSaveContent(): string { return textContainsOnlyBrTags(this.content) ? null : this.content; } public onEditorMouseDown(event: MouseEvent) { const target = <HTMLElement>event.target; if (!target?.classList.contains('ql-toolbar')) { event.stopPropagation(); } } public open() { super.open(); document.addEventListener('keydown', this.keyboardEventListener, {capture: true}); } public close() { super.close(); document.removeEventListener('keydown', this.keyboardEventListener, {capture: true}); } }
<?php /* * phpcs:disable WordPress.Security.NonceVerification.Recommended * phpcs:disable WordPress.Security.NonceVerification.Missing * phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized: */ use RT\ThePostGrid\Helpers\Fns; $current_post_id = ''; if ( ! empty( $_GET['pid'] ) ) { $current_post_id = absint( $_GET['pid'] ); } $current_post = get_post( $current_post_id ); ?> <div id="tpg-postbox" class="tpg-postbox"> <form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="new_post" name="new_post" class="new-post edit-post-form" method="post"> <input type="hidden" name="action" value="tpg_post_update"/> <input type="hidden" name="post_id" value="<?php echo esc_attr( $current_post_id ); ?>"/> <input type="hidden" name="post_status" value="<?php echo esc_attr( $current_post->post_status ); ?>"/> <input type="hidden" name="uid" value="<?php echo esc_attr( get_current_user_id() ); ?>"/> <div class="tpg-form-container"> <div class="form-item"> <label for="title"><?php esc_attr_e( 'Title', 'the-post-grid' ); ?><span>*</span></label> <input type="text" id="title" tabindex="1" size="20" name="title" value="<?php echo esc_attr( $current_post->post_title ); ?>" required/> </div> <div class="form-item form-content-area"> <label for="content"><?php esc_attr_e( 'Content', 'the-post-grid' ); ?></label> <?php $content = $current_post->post_content; if ( isset( $_POST['submit'] ) && ! empty( $_POST['content'] ) ) { $content = wp_kses_post( wp_unslash( $_POST['content'] ) ); } $editor_settings = [ 'textarea_name' => 'content', 'textarea_rows' => 30, 'media_buttons' => true, ]; wp_editor( $content, 'user-editor', $editor_settings ); ?> </div> <div class="form-item"> <label for="excerpt"><?php esc_html_e( 'Excerpt', 'the-post-grid' ); ?></label> <textarea type="textarea" id="excerpt" name="excerpt" rows="2"><?php echo esc_attr( $current_post->post_excerpt ); ?></textarea> </div> <div class="form-item"> <label for="tpg-category"><?php esc_html_e( 'Category', 'the-post-grid' ); ?></label> <div class="cat-list"> <?php $cat_lists = get_the_terms( $current_post_id, 'category' ); $cat_terms_string = wp_list_pluck( $cat_lists, 'term_id' ); $post_cats = get_terms( [ 'taxonomy' => 'category', 'hide_empty' => false, ] ); ?> <select id="tpg-category" class="postform" name="post_category[]" multiple> <option value="" selected disabled></option> <?php foreach ( $post_cats as $p_cat ) { if ( in_array( $p_cat->term_id, $cat_terms_string ) ) { echo '<option value="' . esc_attr( $p_cat->term_id ) . '" selected="selected">' . esc_html( $p_cat->name ) . '</option>'; } else { echo '<option value="' . esc_attr( $p_cat->term_id ) . '">' . esc_html( $p_cat->name ) . '</option>'; } } ?> </select> </div> </div> <?php $post_tags = get_the_terms( $current_post_id, 'post_tag' ); $post_tags_val = join( ', ', wp_list_pluck( $post_tags, 'name' ) ); ?> <div class="form-item"> <label for="new_tpg_tags"><?php esc_html_e( 'Tags', 'the-post-grid' ); ?></label> <div class="new_tpg_tags"> <div class="tpg-tags-input"> <input type="text" value="<?php echo esc_attr( $post_tags_val ); ?>" name="post_tags" id="new_tpg_tags" autocomplete="off"/> </div> <input type="hidden" id="rtpg_post_tag" name="rtpg_post_tag"> </div> </div> <div class="form-item" id="tpg-featured-image"> <?php if ( current_user_can( 'upload_files' ) ) { ?> <label class="custom-file-upload"> <input id="tpg-feature-image" type="file"/> <input name="tpg_feature_image" type="hidden" id="tpg-feature-image-id" value=""/> <svg width="18" height="14" viewBox="0 0 18 14" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M15.909 11.7727H16.2272C16.7541 11.7727 17.1818 11.3454 17.1818 10.8182V0.954545C17.1818 0.427318 16.7541 0 16.2272 0H3.49996C2.97273 0 2.54541 0.427318 2.54541 0.954545V1.27273H15.909V11.7727Z" fill="#6DA4E7"/> <path d="M14 2.22726H0.954545C0.427636 2.22726 0 2.65458 0 3.18181V13.0454C0 13.5727 0.427636 14 0.954545 14H14C14.5269 14 14.9545 13.5727 14.9545 13.0454V3.18181C14.9545 2.65458 14.5269 2.22726 14 2.22726ZM13.6818 12.0909H1.27273V10.8182L5.72727 6.36363L8.75 9.38636L10.5 7.63636L13.6818 10.8182V12.0909Z" fill="#006FFF"/> </svg> <?php esc_html_e( 'Set Featured Image', 'the-post-grid' ); ?> </label> <div class="featured-image-container tpg-image-preview"> <?php echo get_the_post_thumbnail( $current_post_id, 'thumbnail' ); ?> </div> <?php } else { ?> <label class="thumb-file-upload"> <input id="tpg-feature-image2" type="file" name="tpg-feature-image2" accept="image/png, image/gif, image/jpeg"/> </label> <?php } ?> </div> <?php wp_nonce_field( 'tpg-frontend-post' ); ?> <div class="form-item"> <input type="submit" value="<?php echo esc_attr__( 'Save Post', 'the-post-grid' ); ?>" tabindex="6" id="submit" name="submit"/> </div> </div> </form> <?php if ( ! empty( $_GET['status'] ) ) : ?> <?php Fns::status_message( sanitize_text_field( wp_unslash( $_GET['status'] ) ) ); ?> <?php endif; ?> </div>
import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart'; class ChatPage2 extends StatefulWidget { final BluetoothDevice server; const ChatPage2({required this.server}); @override _ChatPage2 createState() => new _ChatPage2(); } class _Message { int whom; var text; _Message(this.whom, this.text); } class _ChatPage2 extends State<ChatPage2> { static final clientID = 0; BluetoothConnection? connection; List<_Message> messages = List<_Message>.empty(growable: true); String _messageBuffer = ''; final TextEditingController textEditingController = new TextEditingController(); final ScrollController listScrollController = new ScrollController(); bool isConnecting = true; bool get isConnected => (connection?.isConnected ?? false); bool isDisconnecting = false; @override void initState() { super.initState(); BluetoothConnection.toAddress(widget.server.address).then((_connection) { print('Connected to the device'); connection = _connection; setState(() { isConnecting = false; isDisconnecting = false; }); connection!.input!.listen(_onDataReceived).onDone(() { if (isDisconnecting) { print('Disconnecting locally!'); } else { print('Disconnected remotely!'); } if (this.mounted) { setState(() {}); } }); }).catchError((error) { print('Cannot connect, exception occured'); print(error); }); } @override void dispose() { // Avoid memory leak (`setState` after dispose) and disconnect if (isConnected) { isDisconnecting = true; connection?.dispose(); connection = null; } super.dispose(); } @override Widget build(BuildContext context) { final List<Row> list = messages.map((_message) { return Row( children: <Widget>[ Container( child: Text( (text) { return text == '/shrug' ? '¯\\_(ツ)_/¯' : text; }(_message.text.trim()), style: TextStyle(color: Colors.white)), padding: EdgeInsets.all(12.0), margin: EdgeInsets.only(bottom: 8.0, left: 8.0, right: 8.0), width: 222.0, decoration: BoxDecoration( color: _message.whom == clientID ? Colors.blueAccent : Colors.grey, borderRadius: BorderRadius.circular(7.0)), ), ], mainAxisAlignment: _message.whom == clientID ? MainAxisAlignment.end : MainAxisAlignment.start, ); }).toList(); final serverName = widget.server.name ?? "Unknown"; return Scaffold( backgroundColor: Colors.grey, appBar: AppBar( backgroundColor: Colors.black87, title: (isConnecting ? Text('正在嘗試連接至 ' + serverName + '...') : isConnected ? Text(serverName + '連接中 ') : Text('已斷線 '))), body: SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Flexible( child: Container( margin: const EdgeInsets.only(left: 16.0), child: Column( children: [ ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.black87), fixedSize: MaterialStateProperty.all(Size(150, 40))), onPressed: isConnected ? () => _sendMessage('n11p') : null, child: Text('沖水', style: TextStyle(fontSize: 19, color: Colors.white)), ), ], ), ), ), ], ) ], ), ), ); } void _onDataReceived(Uint8List data) { // Allocate buffer for parsed data int backspacesCounter = 0; data.forEach((byte) { if (byte == 8 || byte == 127) { backspacesCounter++; } }); Uint8List buffer = Uint8List(data.length - backspacesCounter); int bufferIndex = buffer.length; // Apply backspace control character backspacesCounter = 0; for (int i = data.length - 1; i >= 0; i--) { if (data[i] == 8 || data[i] == 127) { backspacesCounter++; } else { if (backspacesCounter > 0) { backspacesCounter--; } else { buffer[--bufferIndex] = data[i]; } } } // Create message if there is new line character String dataString = String.fromCharCodes(buffer); int index = buffer.indexOf(13); if (~index != 0) { setState(() { messages.add( _Message( 1, backspacesCounter > 0 ? _messageBuffer.substring( 0, _messageBuffer.length - backspacesCounter) : _messageBuffer + dataString.substring(0, index), ), ); _messageBuffer = dataString.substring(index); }); } else { _messageBuffer = (backspacesCounter > 0 ? _messageBuffer.substring( 0, _messageBuffer.length - backspacesCounter) : _messageBuffer + dataString); } } void _sendMessage(String text) async { text = text.trim(); textEditingController.clear(); if (text.length > 0) { try { connection!.output.add(Uint8List.fromList(utf8.encode(text))); await connection!.output.allSent; setState(() { messages.add(_Message(clientID, text)); }); } catch (e) { // Ignore error, but notify state setState(() { print(e); }); } } } }
from fastapi import FastAPI, status from fastapi.middleware.cors import CORSMiddleware import uvicorn from log import logger from config import global_settings from tasks import apscheduler_tasks from user.routers.crud import router as user_crud_router from user.routers.actions import router as user_actions_router from auth.router import router as auth_router from company.routers.crud import router as company_crud_router from company.routers.actions import router as company_actions_router from quiz.routers.quiz import router as quiz_crud_router from quiz.routers.question import router as question_crud_router app = FastAPI() origins = [ "http://localhost:5000", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.on_event("startup") async def startup_event(): logger.info("App startup...") apscheduler_tasks.scheduler.start() @app.on_event("shutdown") async def shutdown_event(): logger.info("App shutdown...") @app.get("/") async def health_check(): return { "status_code": status.HTTP_200_OK, "detail": "ok", "result": "working" } app.include_router(auth_router, tags=["Auth"]) app.include_router(user_crud_router, tags=["User"]) app.include_router(user_actions_router, tags=["User actions"]) app.include_router(company_crud_router, tags=["Company"]) app.include_router(company_actions_router, tags=["Company actions"]) app.include_router(quiz_crud_router, tags=["Quiz"]) app.include_router(question_crud_router, tags=["Question"]) if __name__ == "__main__": uvicorn.run( 'main:app', reload=True, host=global_settings.host, port=global_settings.port )
package stream.input; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.crypto.Cipher; import logic.FSPasswordHash; import logic.FileElement; /** * Class specialized for Decrypt and reconstruct a file via {@link #deryptFile}, extends the {@link #InputCore} class. * Reconstruct a file with all the encrypted parts * @author Meschio * */ public class InputDecrypt extends InputCore{ /** * The BufferedOutputStream where to write the reconstructed file */ private BufferedOutputStream fileOutputStream; /** * cipher element used for write via {@link #writeBytes}, * and manipulated via {@link #crypt} */ private Cipher cipher; /** * FSPasswordHash element to handle the decrypt stuff */ private FSPasswordHash crypt; /** * Constructor of InputCrypt, call the super constructor of {@link #InputCore}, * @param srcPath * @param data * @throws IOException */ public InputDecrypt(String srcPath, FileElement data) throws IOException{ super(srcPath,data); } /** * Specialized get method of OutputSplit, return the {@link #fileOutputStream}. * Used by {@link #writeParts} */ protected OutputStream getOutputStream(){ return fileOutputStream; } /** * Specialized set method of OutputSplit, set the {@link #fileOutputStream}. * Used by {@link #writeParts} */ protected void setOutputStream(String srcPathOut) throws FileNotFoundException{ fileOutputStream = new BufferedOutputStream(new FileOutputStream(srcPathOut + File.separator + headerInfo.getFileNamePure() + headerInfo.getFileExtension())); } /** * decryptFile Function for reconstruct the file from its crypted parts * Will perform the action only if {@link #successfulFlag} is set to true, * otherwise will update the {@link #data} status to "Error" * @throws IOException */ public void decryptFile(String password) throws Exception { if(isSuccessful()==true){//check all previous operation in stream core crypt = new FSPasswordHash(password); this.cipher = crypt.getDecryptChiper(); writeParts(); } else { data.setStatus("Error"); } } /** * @Override method of writeBytes in {@link #StreamCore} to handle the decrypt write */ @Override protected void writeBytes(OutputStream outputStream, long part) throws Exception { if(isSuccessful() == true){ fileProgress.incColumnBar();//update the progress of the element byte[] buffer = new byte[(int) part]; if(stream.read(buffer) >=0){ byte[] crypt = cipher.update(buffer); outputStream.write(crypt); } } } /** * Specialized start set operation of cycle in {@link #writeParts} * */ protected void handleMethodStartOperation(int partIndex){ //nothing to do for crypt } /** * Specialized end set operation of cycle in {@link #writeParts} * */ protected void handleMethodEndOperation() throws IOException{ //nothing to do for crypt } }
import { Provide } from '@midwayjs/decorator'; import { makeHttpRequest } from '@midwayjs/core'; import { WeatherInfo } from '../interface'; import { WeatherEmptyDataError } from '../error/weather.error'; // 这里使用 @Provide 装饰器修饰类,便于后续 Controller 注入该类 @Provide() export class WeatherService { async getWeather(cityId: string): Promise<WeatherInfo> { if (!cityId) { throw new WeatherEmptyDataError(); } try { // makeHttpRequest 方法是 Midway 内置的 http 请求方法 const result = await makeHttpRequest( //城市天气信息来自于中国中央气象台 API `http://www.weather.com.cn/data/sk/${cityId}.html`, { dataType: 'json', } ); if (result.status === 200) { console.log('result.data', result.data); return result.data; } } catch (error) { throw new WeatherEmptyDataError(error); } } }
# Copyright (C) 2009 Greenbone Networks GmbH # Some text descriptions might be excerpted from (a) referenced # source(s), and are Copyright (C) by the respective right holder(s). # # SPDX-License-Identifier: GPL-2.0-or-later # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. if(description) { script_oid("1.3.6.1.4.1.25623.1.0.63680"); script_cve_id("CVE-2008-4316"); script_tag(name:"creation_date", value:"2009-03-31 17:20:21 +0000 (Tue, 31 Mar 2009)"); script_version("2023-04-03T10:19:49+0000"); script_tag(name:"last_modification", value:"2023-04-03 10:19:49 +0000 (Mon, 03 Apr 2023)"); script_tag(name:"cvss_base", value:"4.6"); script_tag(name:"cvss_base_vector", value:"AV:L/AC:L/Au:N/C:P/I:P/A:P"); script_name("Debian: Security Advisory (DSA-1747)"); script_category(ACT_GATHER_INFO); script_copyright("Copyright (C) 2009 Greenbone Networks GmbH"); script_family("Debian Local Security Checks"); script_dependencies("gather-package-list.nasl"); script_mandatory_keys("ssh/login/debian_linux", "ssh/login/packages", re:"ssh/login/release=DEB(4|5)"); script_xref(name:"Advisory-ID", value:"DSA-1747"); script_xref(name:"URL", value:"https://www.debian.org/security/2009/dsa-1747"); script_xref(name:"URL", value:"https://security-tracker.debian.org/tracker/DSA-1747"); script_tag(name:"summary", value:"The remote host is missing an update for the Debian 'glib2.0' package(s) announced via the DSA-1747 advisory."); script_tag(name:"vuldetect", value:"Checks if a vulnerable package version is present on the target host."); script_tag(name:"insight", value:"Diego Petteno discovered that glib2.0, the GLib library of C routines, handles large strings insecurely via its Base64 encoding functions. This could possible lead to the execution of arbitrary code. For the stable distribution (lenny), this problem has been fixed in version 2.16.6-1+lenny1. For the oldstable distribution (etch), this problem has been fixed in version 2.12.4-2+etch1. For the testing distribution (squeeze), this problem will be fixed soon. For the unstable distribution (sid), this problem has been fixed in version 2.20.0-1. We recommend that you upgrade your glib2.0 packages."); script_tag(name:"affected", value:"'glib2.0' package(s) on Debian 4, Debian 5."); script_tag(name:"solution", value:"Please install the updated package(s)."); script_tag(name:"solution_type", value:"VendorFix"); script_tag(name:"qod_type", value:"package"); exit(0); } include("revisions-lib.inc"); include("pkg-lib-deb.inc"); release = dpkg_get_ssh_release(); if(!release) exit(0); res = ""; report = ""; if(release == "DEB4") { if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-0-dbg", ver:"2.12.4-2+etch1", rls:"DEB4"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-0", ver:"2.12.4-2+etch1", rls:"DEB4"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-data", ver:"2.12.4-2+etch1", rls:"DEB4"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-dev", ver:"2.12.4-2+etch1", rls:"DEB4"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-doc", ver:"2.12.4-2+etch1", rls:"DEB4"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-udeb", ver:"2.12.4-2+etch1", rls:"DEB4"))) { report += res; } if(report != "") { security_message(data:report); } else if(__pkg_match) { exit(99); } exit(0); } if(release == "DEB5") { if(!isnull(res = isdpkgvuln(pkg:"libgio-fam", ver:"2.16.6-1+lenny1", rls:"DEB5"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-0-dbg", ver:"2.16.6-1+lenny1", rls:"DEB5"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-0", ver:"2.16.6-1+lenny1", rls:"DEB5"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-data", ver:"2.16.6-1+lenny1", rls:"DEB5"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-dev", ver:"2.16.6-1+lenny1", rls:"DEB5"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-doc", ver:"2.16.6-1+lenny1", rls:"DEB5"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libglib2.0-udeb", ver:"2.16.6-1+lenny1", rls:"DEB5"))) { report += res; } if(report != "") { security_message(data:report); } else if(__pkg_match) { exit(99); } exit(0); } exit(0);
--- title: "Dijkstra's Algorithm" tags: - Algorithms - Graphs --- # Dijkstra's Algorithm ## 1. Problem Statement Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. - NOTE : If graph is a **DAG**, then simply do [[topo-sort|Topological Sort]] and store the vertices in a stack. Then pop the vertices from the stack and update the distances of the adjacent vertices. - This is because to calculate shortest path of any node, we need to calculate the shortest path of all the nodes that come before it. Thus, this automatically calls for topological sorting. ## 2. Solution - **NOTE:** Dijkstra’s Algorithm is not valid for negative weights or negative cycles. - A negative cycle is a cycle whose edges are such that the sum of their weights is a negative value. - Difference between using `sets` and `priority_queues` is that in `sets` we can check if there exists a pair with the same node but a greater distance than the current distance. - This is not possible in `priority_queues` as we cannot erase a particular element from the queue. Thus, we need to push the same node with a smaller distance and the `priority_queue` will automatically sort it. - We can use `queues` also but it will be slower than the above two methods. ### 2.1 Using Sets ```cpp vector <int> dijkstra(int V, vector<vector<int>> adj[], int src) { // Create a set for storing the nodes as a pair {dist,node} set<pair<int,int>> st; // Initialising dist list with a large number to // indicate the nodes are unvisited initially. // This list contains distance from source to the nodes. vector<int> dist(V, 1e9); st.insert({0, src}); // Source initialised with dist=0 dist[src] = 0; // Now, erase the minimum distance node first from the set // and traverse for all its adjacent nodes. while(!st.empty()) { auto it = *(st.begin()); int node = it.second; int dis = it.first; st.erase(it); // Check for all adjacent nodes of the erased // element whether the prev dist is larger than current or not. for(auto it : adj[node]) { int adjNode = it[0]; int edgW = it[1]; if(dis + edgW < dist[adjNode]) { // erase if it was visited previously at // a greater cost. if(dist[adjNode] != 1e9) st.erase({dist[adjNode], adjNode}); // If current distance is smaller, // push it into the queue dist[adjNode] = dis + edgW; st.insert({dist[adjNode], adjNode}); } } } return dist; } ``` ### 2.2 Using Priority Queues ```cpp vector<int> dijkstra(int V, vector<vector<int>> adj[], int S) { // Create a p.q. for storing the nodes as a pair {dist,node} priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // This list contains distance from source to the nodes. vector<int> distTo(V, INT_MAX); // Source initialised with dist=0. distTo[S] = 0; pq.push({0, S}); // Now, pop the minimum distance node first from the min-heap // and traverse for all its adjacent nodes. while (!pq.empty()) { int node = pq.top().second; int dis = pq.top().first; pq.pop(); // Check for all adjacent nodes of the popped out // element whether the prev dist is larger than current or not. for (auto it : adj[node]) { int v = it[0]; int w = it[1]; if (dis + w < distTo[v]) { distTo[v] = dis + w; // If current distance is smaller, // push it into the queue. pq.push({dis + w, v}); } } } return distTo; } ``` ## 3. Complexity - Time Complexity --> $O(E*logV)$ - Space Complexity --> $O(V)$ [//begin]: # "Autogenerated link references for markdown compatibility" [topo-sort|Topological Sort]: topo-sort "Topological Sort" [//end]: # "Autogenerated link references"
package org.lt.project.service; import org.apache.commons.io.input.Tailer; import org.apache.commons.io.input.TailerListener; import org.lt.project.core.result.ErrorResult; import org.lt.project.core.result.Result; import org.lt.project.core.result.SuccessResult; import org.lt.project.entity.SuspectIPEntity; import org.springframework.stereotype.Service; import java.io.File; import java.time.Duration; import java.util.concurrent.Executor; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.concurrent.Executors.newSingleThreadExecutor; @Service public class LogListenerService extends LogListenerAdapter { private SuspectIpService suspectIpService; private final Pattern pattern; private Pattern accessPattern; private Tailer tailer; private boolean isServiceRunning = false; public LogListenerService(SuspectIpService suspectIpService) { this.suspectIpService=suspectIpService; String patternString = ".*access forbidden by rule.*client: ([^,]+).*host: ([^,]+).*"; pattern = Pattern.compile(patternString, Pattern.MULTILINE); } public Result startService(){ try{ if(isServiceRunning){ return new ErrorResult("Servis zaten çalışıyor."); } String logFilePath="src/main/resources/error.log"; File logFile = new File(logFilePath); TailerListener tailerListener = this; tailer = Tailer.builder() .setFile(logFile) .setTailerListener(tailerListener) .setStartThread(false) .setDelayDuration(Duration.ofSeconds(2)) .get(); Executor executor = newSingleThreadExecutor(); executor.execute(tailer); isServiceRunning=true; return new SuccessResult("Başarılya başlatıldı"); }catch (Exception e){ return new ErrorResult("Başlatılırken bir hata oluştu. "+e.getMessage()); } } public Result stopService(){ try{ if(isServiceRunning){ tailer.close(); return new SuccessResult("Başarıyla durduruldu."); }else { return new ErrorResult("Zaten başlatılmadı."); } }catch (Exception e){ return new ErrorResult("Durdurulurken bir hata oluştu. "+e.getMessage()); } } @Override public void handle(String line) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { String ip = matcher.group(1); String host = matcher.group(2); Integer accessForbiddenNumber = getAccessForbiddenNumber(line); System.out.println(ip); suspectIpService.saveSuspectIp(new SuspectIPEntity(ip, host, accessForbiddenNumber)); } } private Integer getAccessForbiddenNumber(String line) { String accessPatternString = ".*\\*(\\d+) access forbidden by rule.*"; accessPattern = Pattern.compile(accessPatternString); Matcher accessMatcher = accessPattern.matcher(line); if (accessMatcher.matches()) { return Integer.valueOf(accessMatcher.group(1)); } return -1; } }
//Abstraction Typescript abstract class Character { public name: string; public damage: number; public attackSpeed: number; constructor(name: string, damage: number, speed: number) { this.name = name; this.damage = damage; this.attackSpeed = speed; } public abstract damagePerSecond(): number; } class Goblin extends Character { constructor(name: string, damage: number, speed: number) { super(name, damage, speed); } public damagePerSecond(): any { console.log("Name: " + this.name + " " + "\n" + "damagePerSecond: " + this.damage * this.attackSpeed); } } class Goblin1 extends Character { constructor(name: string, damage: number, speed: number) { super(name, damage, speed); } public damagePerSecond(): any { console.log("Name: " + this.name + " " + "\n" + "damagePerSecond: " + this.damage / this.attackSpeed); } } // let c = new Character('ABC', 123, 123);//Cannot create an instance of an abstract class // Character.damagePerSecond(); let g = new Goblin('ABC', 123, 123); g.damagePerSecond(); let g1 = new Goblin1('ABC', 123, 123); g1.damagePerSecond();
<template> <div class="content"> <div class="content-top"> <el-input class="searchClass" v-model="keyword" @input="handleSearchKey" placeholder="搜索周边" :suffix-icon="Search" /> </div> <div class="search-box"> <var-tabs elevation color="#fff" active-color="#fff" inactive-color="black" v-model:active="active" > <var-tab :key="index" v-for="(item, index) in state.searchList">{{ item.label }}</var-tab> </var-tabs> <div class="icon"> <svg-icon name="jihe" color="grey" width="22px" height="22px" ></svg-icon> </div> <!-- <div class="search-item" > {{ item.label }} </div> --> </div> <div class="map-content"> <Map /> </div> </div> </template> <script setup> import { ref, reactive } from "vue"; import Map from "@/components/map.vue"; import SvgIcon from "@/components/svg.vue"; import { Search } from "@element-plus/icons-vue"; const active = ref(0); const keyword = ref(""); //搜索项 const state = reactive({ searchList: [ { label: "景点", id: 1, }, { label: "停车场", id: 2, }, { label: "卫生间", id: 3, }, { label: "公园", id: 4, }, { label: "商店", id: 5, }, { label: "停车场", id: 6, }, { label: "餐饮", id: 7, }, { label: "母婴室", id: 8, }, { label: "售票处", id: 9, }, { label: "出入口", id: 10, }, ], }); /** * 搜索周边 */ const handleSearchKey = (keyword) => { // 创建搜索请求对象 var request = { keyWord: keyword, level: 12, mapBound: "116.02524,39.83833,116.65592,39.99185", queryType: 2, start: 0, count: 10, }; // 将搜索请求对象转换为 Base64 编码的 JSON 字符串 var postStr = JSON.stringify(request); // 发送搜索请求 fetch( "http://api.tianditu.gov.cn/v2/search?postStr=" + postStr + "&type=query" + "&tk=f5c6e3cb59fa2c5c10a4279fa232d65c" ) .then(function (response) { return response.json(); }) .then(function (data) { // 将搜索结果添加到地图上 for (var i = 0; i < data.pois.length; i++) { var poi = data.pois[i]; var marker = new T.Marker(new T.LngLat(poi.lonlat)); var infoWindow = new T.InfoWindow(); infoWindow.setLngLat(new T.LngLat(116.404, 39.915)); // infoWindow.setLatLng(new T.LngLat(poi.lonlat)) infoWindow.setContent(poi.name + "<br>" + poi.address); marker.addEventListener("click", function () { if (poi.lonlat) { window.map.openInfoWindow(infoWindow, marker); } }); window.map.addOverLay(marker); } }) .catch(function (error) { console.error(error); }); }; </script> <style lang="less" scoped> .content { width: 100%; height: 100vh; .content-top { height: 30px; margin-bottom: 20px; :deep(.searchClass) { border-radius: 20px; border: none !important; background: #f7f8fb; .el-input__wrapper { height: 36px; line-height: 36px; border: none; box-shadow: none; color: #6ca7f8; background-color: transparent; } } } .search-box { width: 100%; height: 35px; display: flex; overflow-x: auto; margin-bottom: 20px; :deep(.var-tabs) { width: calc(100% - 40px); flex: 1; height: 100%; padding: 2px 0; box-shadow: none; .var-tab--active { background: #008efa; height: 90%; border-radius: 20px; } } .icon { width: 30px; display: flex; justify-content: center; align-items: center; } } .map-content { height: calc(100% - 150px); } } </style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@800&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css" /> <link rel="stylesheet" href="styles/styles.css" /> <title>Web Studio</title> </head> <body> <header class="header"> <div class="container main-nav"> <nav class="header-nav"> <a href="" class="header-logo logo"> <span>Web</span>Studio </a> <ul class="header-list list"> <li class="header-item item"> <a href="index.html" class="header-link link active" data-activated-link >Studio</a > </li> <li class="header-item item"> <a href="portfolio.html" class="header-link link">Portfolio</a> </li> <li class="header-item item"> <a href="#" class="header-link link">Contacts</a> </li> </ul> </nav> <address class="header-address"> <ul class="header-address-list list"> <li class="address-item item"> <a href="mailto:info@devstudio.com" class="header-link link active-link" >info@devstudio.com</a > </li> <li class="address-item item"> <a href="tel:+110001111111" class="header-link link active-link" >+11 (000) 111-11-11</a > </li> </ul> </address> </div> </header> <main> <!--Section Hero--> <section class="hero"> <div class="hero-wrapper container"> <h1 class="hero-title">Effective Solutions for Your Business</h1> <button type="button" class="hero-button btn" data-modal-open> Order Service </button> </div> </section> <!--/Section Hero--> <!--Qualities--> <section class="qualities section no-padding"> <div class="container"> <h2 class="visually-hidden">Qualities</h2> <ul class="qualities-list list"> <li class="qualities-item"> <div class="qualities-icon-box"> <svg class="qualities-icon" width="64" height="64"> <use href="images/symbol-defs.svg#icon-Group"></use> </svg> </div> <h3 class="qualities-subtitle subtitle">Strategy</h3> <p class="qualities-description description"> Our goal is to identify the business problem to walk away with the perfect and creative solution. </p> </li> <li class="qualities-item"> <div class="qualities-icon-box"> <svg class="qualities-icon" width="64" height="64"> <use href="images/symbol-defs.svg#icon-clock"></use> </svg> </div> <h3 class="qualities-subtitle subtitle">Punctuality</h3> <p class="qualities-description description"> Bring the key message to the brand's audience for the best price within the shortest possible time. </p> </li> <li class="qualities-item"> <div class="qualities-icon-box"> <svg class="qualities-icon" width="64" height="64"> <use href="images/symbol-defs.svg#icon-diagram"></use> </svg> </div> <h3 class="qualities-subtitle subtitle">Diligence</h3> <p class="qualities-description description"> Research and confirm brands that present the strongest digital growth opportunities and minimize risk. </p> </li> <li class="qualities-item"> <div class="qualities-icon-box"> <svg class="qualities-icon" width="64" height="64"> <use href="images/symbol-defs.svg#icon-astronaut"></use> </svg> </div> <h3 class="qualities-subtitle subtitle">Technologies</h3> <p class="qualities-description description"> Design practice focused on digital experiences. We bring forth a deep passion for problem-solving. </p> </li> </ul> </div> </section> <!--/Qualities--> <!--What are we doing?--> <section class="domain section"> <div class="container"> <h2 class="domain-title title">What are we doing</h2> <ul class="domain-list list"> <li class="domain-item"> <img src="./images/work.jpg" alt="desktop" width="360" height="300" /> </li> <li class="domain-item"> <img src="./images/work-2.jpg" alt="app on the screen" width="360" height="300" /> </li> <li class="domain-item"> <img src="./images/work-3.jpg" alt="app in mobile phone and laptop" width="360" height="300" /> </li> </ul> </div> </section> <!--/What are we doing?--> <!--Section Team--> <section class="team section"> <div class="container"> <h2 class="team-title title">Our Team</h2> <ul class="team-list list"> <li class="team-item"> <img src="./images/team.jpg" alt="team-member" width="264" height="260" /> <div class="team-content"> <h3 class="team-subtitle subtitle">Mark Guerrero</h3> <p class="team-description description">Product Designer</p> <ul class="social-list list"> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-instagram" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-facebook" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-linkedin" ></use> </svg> </a> </li> </ul> </div> </li> <li class="team-item"> <img src="./images/team-2.jpg" alt="team-member" width="264" height="260" /> <div class="team-content"> <h3 class="team-subtitle subtitle">Tom Ford</h3> <p class="team-description description">Frontend Developer</p> <ul class="social-list list"> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-instagram" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-facebook" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-linkedin" ></use> </svg> </a> </li> </ul> </div> </li> <li class="team-item"> <img src="./images/team-3.jpg" alt="team-member" width="264" height="260" /> <div class="team-content"> <h3 class="team-subtitle subtitle">Camila Garcia</h3> <p class="team-description description">Marketing</p> <ul class="social-list list"> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-instagram" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-facebook" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-linkedin" ></use> </svg> </a> </li> </ul> </div> </li> <li class="team-item"> <img src="./images/team-4.jpg" alt="team-member" width="264" height="260" /> <div class="team-content"> <h3 class="team-subtitle subtitle">Daniel Wilson</h3> <p class="team-description description">UI Designer</p> <ul class="social-list list"> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-instagram" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-facebook" ></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link"> <svg class="social-list-icon" width="16" height="16"> <use href="./images/symbol-defs.svg#icon-linkedin" ></use> </svg> </a> </li> </ul> </div> </li> </ul> </div> </section> <!--/Section Team--> <!--Customers--> <section class="customers section"> <div class="container"> <h2 class="customers-title title">Customers</h2> <ul class="customers-list list"> <li class="customers-item"> <a href="" class="customers-link"> <svg class="customers-list-icon" width="104" height="56"> <use href="./images/symbol-defs.svg#icon-Logo-1"></use> </svg> </a> </li> <li class="customers-item"> <a href="" class="customers-link"> <svg class="customers-list-icon" width="104" height="56"> <use href="./images/symbol-defs.svg#icon-Logo-2"></use> </svg> </a> </li> <li class="customers-item"> <a href="" class="customers-link"> <svg class="customers-list-icon" width="104" height="56"> <use href="./images/symbol-defs.svg#icon-Logo-3"></use> </svg> </a> </li> <li class="customers-item"> <a href="" class="customers-link"> <svg class="customers-list-icon" width="104" height="56"> <use href="./images/symbol-defs.svg#icon-Logo-4"></use> </svg> </a> </li> <li class="customers-item"> <a href="" class="customers-link"> <svg class="customers-list-icon" width="104" height="56"> <use href="./images/symbol-defs.svg#icon-Logo-5"></use> </svg> </a> </li> <li class="customers-item"> <a href="" class="customers-link"> <svg class="customers-list-icon" width="104" height="56"> <use href="./images/symbol-defs.svg#icon-Logo-6"></use> </svg> </a> </li> </ul> </div> </section> <!--/Customers--> </main> <footer class="footer"> <div class="footer-container container"> <div class="footer-info"> <a href="/" class="footer-logo logo"> <span>Web</span> Studio </a> <p class="footer-description description"> Increase the flow of customers and sales for your business with digital marketing & growth solutions. </p> </div> <div class="footer-social"> <h4 class="footer-social-title">Social media</h4> <ul class="footer-social-list list"> <li class="social-list-item"> <a href="" class="social-list-link footer-social-link"> <svg class="social-list-icon" width="24" height="24"> <use href="./images/symbol-defs.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link footer-social-link"> <svg class="social-list-icon" width="24" height="24"> <use href="./images/symbol-defs.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link footer-social-link"> <svg class="social-list-icon" width="24" height="24"> <use href="./images/symbol-defs.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a href="" class="social-list-link footer-social-link"> <svg class="social-list-icon" width="24" height="24"> <use href="./images/symbol-defs.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </div> </footer> <div class="overlay is-hidden" data-modal> <div class="modal"> <button class="modal-close" type="button" data-modal-close> <svg class="modal-cross" width="8" height="8"> <use href="./images/symbol-defs.svg#icon-close-black"></use> </svg> </button> </div> </div> <!-- <script src="./js/modal.js"></script> --> <script src="./js/modal.js"></script> </body> </html>
document.addEventListener("DOMContentLoaded", function () { const dynamicForm = document.getElementById("dynamicForm"); const numFieldsSelect = document.getElementById("numFields"); const inputContainer = document.getElementById("inputContainer"); numFieldsSelect.addEventListener("change", function () { const numFields = parseInt(numFieldsSelect.value); generateInputFields(numFields); }); dynamicForm.addEventListener("submit", function (e) { e.preventDefault(); // Prevent form submission if (validateForm()) { dynamicForm.submit(); } }); function generateInputFields(numFields) { inputContainer.innerHTML = ""; for (let i = 1; i <= numFields; i++) { const input = document.createElement("input"); input.type = "text"; input.name = `field${i}`; input.placeholder = `Field ${i}`; inputContainer.appendChild(input); } } function validateForm() { const inputs = inputContainer.querySelectorAll("input"); for (const input of inputs) { if (input.value.trim() === "") { alert("Please fill in all fields."); return false; } } return true; } });
// // RideDetailViewModel.swift // Edvora_Test // // Created by Rahul Chaturvedi on 19/03/22. // import Foundation struct Item { var title: String var value: String } class RideDetailViewModel { var ride: Ride init(ride: Ride) { self.ride = ride } func getDetailStacks() -> [Item] { let detailStacks = [Item(title: "Ride ID", value: "\(ride.id)"), Item(title: "Origin Station", value: "\(ride.origin_station_code)"), Item(title: "Date", value: ride.formattedDate), Item(title: "Distance", value: "\(ride.distance ?? 0) Km"), Item(title: "State", value: "\(ride.state)"), Item(title: "City", value: "\(ride.city)"), Item(title: "Station Path", value: "\(ride.station_path.toPrint)")] return detailStacks } }
import 'dart:developer' as devtools show log; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'firebase_options.dart'; import 'state/auth/providers/is_logged_in_provider.dart'; import 'state/providers/is_loading_provider.dart'; import 'views/components/loading/loading_screen.dart'; import 'views/login/login_view.dart'; import 'views/main/main_view.dart'; extension Log on Object { void log() => devtools.log(toString()); } void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp( const ProviderScope( child: MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( brightness: Brightness.dark, primarySwatch: Colors.blue, ), themeMode: ThemeMode.dark, darkTheme: ThemeData( brightness: Brightness.dark, primarySwatch: Colors.blueGrey, indicatorColor: Colors.blueGrey, ), home: Consumer( builder: (context, ref, child) { final isLoggedIn = ref.watch(isLoggedInProvider); ref.listen<bool>(isLoadingProvider, (_, isLoading) { isLoading ? LoadingScreen.instance.show(context: context) : LoadingScreen.instance.hide(); }); return isLoggedIn ? const MainView() : const LoginView(); }, ), ); } }
import { List, ListItem, Typography, TextField, Button, Link, } from '@material-ui/core'; import axios from 'axios'; import { useRouter } from 'next/router'; import { getError } from '../utils/error'; import React, { useContext, useEffect } from 'react'; import Layout from '../components/Layout'; import { Store } from '../utils/Store'; import useStyles from '../utils/styles'; import Cookies from 'js-cookie'; import { Controller, useForm } from 'react-hook-form'; import { useSnackbar } from 'notistack'; export default function Register() { const { handleSubmit, control, formState: { errors }, } = useForm(); const { enqueueSnackbar, closeSnackbar } = useSnackbar(); const router = useRouter(); const { redirect } = router.query; const { state, dispatch } = useContext(Store); const { userInfo } = state; useEffect(() => { if (userInfo) { router.push('/'); } }, [router, userInfo]); const classes = useStyles(); const submitHandler = async ({ name, email, password, confirmPassword }) => { closeSnackbar(); if (password !== confirmPassword) { enqueueSnackbar('Senhas não são iguais ', { variant: 'error' }); return; } try { const { data } = await axios.post('/api/users/registro', { name, email, password, }); dispatch({ type: 'USER_LOGIN', payload: data }); Cookies.set('userInfo, data'); router.push(redirect || '/'); } catch (err) { enqueueSnackbar(getError(err), { variant: 'error' }); } }; return ( <Layout title="Registro"> <form onSubmit={handleSubmit(submitHandler)} className={classes.form}> <Typography align="center" component="h1" className={classes.registerTitle} > Registro </Typography> <List> <ListItem> <Controller name="name" control={control} defaultValue="" rules={{ required: true, minLength: 2, }} render={({ field }) => ( <TextField variant="outlined" fullWidth id="name" label="Nome" inputProps={{ type: 'name' }} error={Boolean(errors.name)} helperText={ errors.name ? errors.name.type === 'minLength' ? 'O nome precisa ter mais de um caractere' : 'Insira seu nome' : '' } {...field} ></TextField> )} ></Controller> </ListItem> <ListItem> <Controller name="email" control={control} defaultValue="" rules={{ required: true, pattern: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/, }} render={({ field }) => ( <TextField variant="outlined" fullWidth id="email" label="Email" inputProps={{ type: 'email' }} error={Boolean(errors.email)} helperText={ errors.email ? errors.email.type === 'pattern' ? 'O email não é válido' : 'Insira seu email' : '' } {...field} ></TextField> )} ></Controller> </ListItem> <ListItem> <Controller name="password" control={control} defaultValue="" rules={{ required: true, minLength: 8, }} render={({ field }) => ( <TextField variant="outlined" fullWidth id="password" label="Senha" inputProps={{ type: 'password' }} error={Boolean(errors.password)} helperText={ errors.password ? errors.password.type === 'minLength' ? 'A senha precisa ter no mínimo 8 caracteres' : 'Insira sua senha' : '' } {...field} ></TextField> )} ></Controller> </ListItem> <ListItem> <Controller name="confirmPassword" control={control} defaultValue="" rules={{ required: true, minLength: 8, }} render={({ field }) => ( <TextField variant="outlined" fullWidth id="confirmPassword" label="Confirmar senha" inputProps={{ type: 'password' }} error={Boolean(errors.confirmPassword)} helperText={ errors.confirmPassword ? errors.confirmPassword.type === 'minLength' ? 'Confirmar senha precisa ter no mínimo 8 caracteres' : 'Insira a confirmação de senha' : '' } {...field} ></TextField> )} ></Controller> </ListItem> <ListItem> <Button className={classes.ctaProduct} variant="contained" type="submit" fullWidth color="primary" > Registrar </Button> </ListItem> <ListItem> Já tem uma conta?&nbsp; <Link href={`/login?redirect=${redirect || '/'}`}>Logue aqui</Link> </ListItem> </List> </form> </Layout> ); }
// @flow import type {AST, Environment, MutableAsset} from '@parcel/types'; import PostHTML from 'posthtml'; // A list of all attributes that may produce a dependency // Based on https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes const ATTRS = { src: [ 'script', 'img', 'audio', 'video', 'source', 'track', 'iframe', 'embed', 'amp-img', ], // Using href with <script> is described here: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/script href: ['link', 'a', 'use', 'script'], srcset: ['img', 'source'], imagesrcset: ['link'], poster: ['video'], 'xlink:href': ['use', 'image', 'script'], content: ['meta'], data: ['object'], }; // A list of metadata that should produce a dependency // Based on: // - http://schema.org/ // - http://ogp.me // - https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/markup // - https://msdn.microsoft.com/en-us/library/dn255024.aspx // - https://vk.com/dev/publications const META = { property: [ 'og:image', 'og:image:url', 'og:image:secure_url', 'og:audio', 'og:audio:secure_url', 'og:video', 'og:video:secure_url', 'vk:image', ], name: [ 'twitter:image', 'msapplication-square150x150logo', 'msapplication-square310x310logo', 'msapplication-square70x70logo', 'msapplication-wide310x150logo', 'msapplication-TileImage', 'msapplication-config', ], itemprop: [ 'image', 'logo', 'screenshot', 'thumbnailUrl', 'contentUrl', 'downloadUrl', ], }; // Options to be passed to `addDependency` for certain tags + attributes const OPTIONS = { a: { href: {isEntry: true}, }, iframe: { src: {isEntry: true}, }, link(attrs) { if (attrs.rel === 'stylesheet') { return { // Keep in the same bundle group as the HTML. isAsync: false, isEntry: false, isIsolated: true, }; } }, script(attrs, env: Environment) { return { // Keep in the same bundle group as the HTML. isAsync: false, isEntry: false, isIsolated: true, env: { outputFormat: attrs.type === 'module' && env.shouldScopeHoist ? 'esmodule' : undefined, }, }; }, }; function collectSrcSetDependencies(asset, srcset, opts) { let newSources = []; for (const source of srcset.split(',')) { let pair = source.trim().split(' '); if (pair.length === 0) { continue; } pair[0] = asset.addURLDependency(pair[0], opts); newSources.push(pair.join(' ')); } return newSources.join(','); } function getAttrDepHandler(attr) { if (attr === 'srcset' || attr === 'imagesrcset') { return collectSrcSetDependencies; } return (asset, src, opts) => asset.addURLDependency(src, opts); } export default function collectDependencies( asset: MutableAsset, ast: AST, ): boolean { let isDirty = false; let hasScripts = false; PostHTML().walk.call(ast.program, node => { let {tag, attrs} = node; if (!attrs) { return node; } if (tag === 'meta') { if ( !Object.keys(attrs).some(attr => { let values = META[attr]; return ( values && values.includes(attrs[attr]) && attrs.content !== '' && !(attrs.name === 'msapplication-config' && attrs.content === 'none') ); }) ) { return node; } } if ( tag === 'link' && (attrs.rel === 'canonical' || attrs.rel === 'manifest') && attrs.href ) { attrs.href = asset.addURLDependency(attrs.href, { isEntry: true, }); isDirty = true; return node; } for (let attr in attrs) { // Check for virtual paths if (tag === 'a' && attrs[attr].lastIndexOf('.') < 1) { continue; } // Check for id references if (attrs[attr][0] === '#') { continue; } let elements = ATTRS[attr]; if (elements && elements.includes(node.tag)) { let depHandler = getAttrDepHandler(attr); let depOptionsHandler = OPTIONS[node.tag]; let depOptions = typeof depOptionsHandler === 'function' ? depOptionsHandler(attrs, asset.env) : depOptionsHandler && depOptionsHandler[attr]; attrs[attr] = depHandler(asset, attrs[attr], depOptions); isDirty = true; if (node.tag === 'script') { hasScripts = true; } } } if (isDirty) { asset.setAST(ast); } return node; }); return hasScripts; }
## 뉴스 내용 요약 및 중복제거 from openai import OpenAI import snowflake.connector from snowflake.connector.pandas_tools import pd_writer from snowflake.connector.pandas_tools import write_pandas import os import pandas as pd def summary_api(): # db 접근 ## 접속 인자 snow_conn = snowflake.connector.connect( user=os.getenv('user'), password=os.getenv('password'), account=os.getenv('account'), role=os.getenv('role'), warehouse=os.getenv('warehouse'), database=os.getenv('database'), schema=os.getenv('schema') ) snowCur = snow_conn.cursor() ## query 세팅(수정) query = '''Select "검색어", "아이디", "제목", "내용", "발행일", "요약" From NEWS.CRAWLING_DATA.NAVER_NEWS;''' ## query 조회 snowCur.execute(query) data = snowCur.fetchall() columns = [desc[0] for desc in snowCur.description] df = pd.DataFrame(data, columns=columns) # 요약 ## openai 접속정보 openai_api_key = st.secrets.OPENAI_API_KEY client = OpenAI(api_key=openai_api_key) ## init prompt prompt = ''' 뉴스를 읽고 mask를 채워줘. [뉴스] {content} [요약문] 서론 : mask 본론 : mask 결론 : mask ''' ## summary ids = df["아이디"].to_list() df["요약"] = "" summary_to_id = {} ## (수정) for id in ids: messages = [] messages.append({"role":"system", "content": "당신은 주어진 틀에 맞춰 뉴스를 요약해주는 챗봇입니다. user가 뉴스를 입력하면 mask에 정보를 입력해주세요."}) content = df[df["아이디"] == id]["내용"].values[0] input_prompt = prompt.format(content=content) messages.append({"role":"user", "content": input_prompt}) response = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages) response.choices[0] msg = response.choices[0].message.content # 문자열을 줄바꿈 문자로 분리 sections = msg.split('\n') # 각 섹션에서 내용만 추출 try: extracted_contents = ' '.join([section.split(' : ')[1] for section in sections if section]) except: extracted_contents = msg df.loc[df['아이디'] == id, '요약'] = extracted_contents print(len(df), "개의 요약문을 입력하였습니다.") df['내용'] = df['내용'].apply(lambda x: x.replace('\n','.').replace('..', '.')) df['요약'] = df['요약'].apply(lambda x: x.replace('\n','.').replace('..', '.')) write_pandas(snow_conn, df, 'NAVER_NEWS', auto_create_table=False, overwrite=True) snow_conn.close() return df df = summary_api()
# TABLEAU DE BORD SODECOTON - CAMEROUN V01 -2020. Auteur : Samuel Talle #--chargemement des librairies-------------------------------------------- library(shiny) library(shinydashboard) library(RMariaDB) library("DBI") library(RODBC) library(lattice) library(ggplot2) library(tidyverse) library(dplyr) require(gridExtra) library(DT) library(plotly) library(waterfalls) library(RODBCext) library(pivottabler) library(rpivotTable) theme_set(theme_bw()) library(shinyjs) library(scales) library(lubridate) library(rAmCharts4) library(rAmCharts) library(reactable) #library(shinydashboardPlus) #library(shinyscreenshot) #---Connection la BD-------------------------------------------------------------------- #cn <- odbcDriverConnect(connection="Driver={SQL Server};server=10.100.2.26;Port=1433;database=DWH_Coton;uid=SA;pwd=Sdcc@2021;") cn <- odbcDriverConnect(connection="Driver={SQL Server};server=DI-LPTP-16;Port=1433;database=DWH_Coton;uid=SA;pwd=Damico5089@;") #------------------------------------------------------------------------------------------ #---Verification des MAJ de la base de donnees---------------------------------------- check_for_update <- function() { sqlQuery(cn, "SELECT MAX(timestamp) FROM [FactProduction]") } #-------------------------------------------------------------------------------- #---Obtention des jeux de donnees-------------------------------------------------------------- get_dataProjet <- function() { sqlQuery(cn, " select d.Year as Periode, d.DayOfWeek, d.MonthName, d.Date DateOpe, d.Month, realName, fisrtName, pr.name Projet, NiveauAvancement, RespectDelai, t.IdTechnicienSK, t.Name from FaitProjet p left join DimDate d on d.IdDateSK=p.IdDateSK left join DimTechnicien t on t.IdTechnicienSK=p.IdTechnicienSK left join DimProjet pr on pr.idProjetSK=p.idProjetSK where RealEndDate is null " ) } get_dataHuilerie <- function() { sqlQuery(cn, " select d.Year as Periode, d.DayOfWeek, d.MonthName, d.Date DateOpe, d.Month, h.CodeUsine, h.NomUsine Usine, q.ChefQuart, t.Libelle Equipe, q.NomQuart Quart, p.GraineRecepKG, p.EcartKG, p.GraineMoKG, p.AlibetProduitSac, p.Farine21ProduitSac, CoqueIncorporeKG, CoqueChaudiereKG, HuileNProduitLT, HuileNMOLT, HuileRaffineLT, NbCartonDiamaorU, -- on calcule tous les kpis case when GraineMoKG = 0 then 0.0 else (HuileNProduitLT / GraineMoKG) * 100 end as TauxHnGr, case when GraineMoKG = 0 then 0.0 else ((p.AlibetProduitSac + p.Farine21ProduitSac) / GraineMoKG) * 100 end as TauxTtxGr from FaitHlProduction p left join DimDate d on d.IdDateSK=p.IdDateSK left join DimQuart q on q.IdQuartSK=p.IdQuartSK left join DimTranche_horaire t on t.IdTrancheSK=p.IdTrancheSK left join DimUsinehuilerie h on h.IdUsineSK=p.IdUsineSK " ) } get_dataProduction <- function() { sqlQuery(cn, " select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, e.IdUsine, e.Libelle Usine, c.ChefDeQuart,c.Libelle Equipe,d.Libelle Quart, a.NbBalles,a.PoidsBrut,a.PoidsNet,a.PoidsBrut-a.PoidsNet Ecart_Poids, KwhReseau,TempsEgreneuse1,TempsEgreneuse2,TempsEgreneuse3,TempsEgreneuse4,a.NbEgreneuses,a.NbScies, a.TempsCondenseur from FactProduction a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimQuartEgrenage c on c.IdQuartEgrenageSK=a.IdQuartEgrenageSK left join DimQuartPeriode d on d.IdQuartPeriode=a.IdQuartPeriodeSK left join DimUsine e on e.IdUsineSK=a.IdUsineSK " ) } get_dataProductionUsine <- function() { sqlQuery(cn, " select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, e.IdUsine, e.Libelle Usine, a.PdsCgEgrene,a.PdsGraineHuileries,a.PdsSemences,a.PdsGraines,a.NbSacGraines, a.PdsFibreCourtes,NbSacFibreCourtes,a.TempEgreneuse,a.NbScies from FactProductionJour a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimUsine e on e.IdUsineSK=a.IdUsineSK " ) } get_dataEvacuation <- function() { sqlQuery(cn, " select a.IdUsine,DateBordereauLivraison,DateProduction, b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, e.IdUsine, e.Libelle Usine, Transporteur,Chauffeur, 1 NbBalles,PoidsBrut,a.PoidsNet, DATEDIFF(DAY,DateProduction,DateBordereauLivraison) delai from T_Evacuation a left join DimDate b on b.Date=a.DateBordereauLivraison left join DimUsine e on e.IdUsineSK=a.IdUsine " ) } ' get_dataClassement <- function() { sqlQuery(cn, " select top 2000 b.Year as Periode,b.DayOfWeek,b.MonthName,b.Date DateOpe, b.Month, c.IdVarietes,c.Libelle Variete, d.IdClasse,d.Libelle Classe, e.IdNatureCotons,e.Libelle NatureCoton, f.IdUsine,f.Libelle Usine, g.IdSoies,g.Libelle Soie, g.Longueur LongueurSoie, a.PoidsBrut,a.PoidsNet from FactClassement a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimVarietes c on c.IdVarietesSK=a.IdVarietesSK left join DimClasse d on d.IdClasseSK=a.IdClasseSK left join DimNatureCotons e on e.IdNatureCotonsSK=a.IdNatureCotonsSK left join DimUsine f on f.IdUsineSK=a.IdUsineSK left join DimSoies g on g.IdSoiesSK=a.IdSoiesSK where b.Year=2018 " ) } ' VYear<-2020 VIdUsune<-"0" VIdHuilerie<-"1" VMonth<-1 VMonthPrec<-0 nb<-0 value1G<-0 VCodeSociete<<-'Sodecoton' get_dataIncident_By_Direction <- function() { req<- " select di.Name, count(idTickets) Nombre from FaitIncident i left join DimDate d on d.IdDateSK=i.IdDateSK left join DimDirection di on di.idDirectionSK = i.idDirectionSK where d.Year= cast(? as varchar) and d.Month=cast(? as varchar) group by di.Name order by Nombre desc " myvalue<-data.frame(VYear, VMonth) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataIncident_By_Site <- function() { req<- " select top 5 s.Name, count(idTickets) Nombre from FaitIncident i left join DimDate d on d.IdDateSK=i.IdDateSK left join DimSite s on s.idSiteSk=i.idSiteSk where d.Year= cast(? as varchar) and d.Month=cast(? as varchar) group by s.Name order by Nombre desc " myvalue<-data.frame(VYear, VMonth) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataIncident <- function() { req<- " select d.Year as Periode, d.DayOfWeek, d.MonthName, d.Date DateOpe, d.Month, realName, fisrtName, c.name Categorie, s.name Site, di.name Direction, idTickets Tickets from FaitIncident i left join DimDate d on d.IdDateSK=i.IdDateSK left join DimTechnicien t on t.IdTechnicienSK=i.IdTechnicienSK left join DimCategorieInfo c on c.IdCategorieSK=i.IdCategorieSK left join DimSite s on s.idSiteSk=i.idSiteSk left join DimStatut st on st.idStatutSK = i.idStatutSK left join DimDirection di on di.idDirectionSK = i.idDirectionSK where d.Year= cast(? as varchar) and d.Month=cast(? as varchar) " myvalue<-data.frame(VYear, VMonth) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataIncidentRapport <- function() { req<- " select c.name Categorie, s.name Site, di.name Direction, count(*) Nombre from FaitIncident i left join DimDate d on d.IdDateSK=i.IdDateSK left join DimTechnicien t on t.IdTechnicienSK=i.IdTechnicienSK left join DimCategorieInfo c on c.IdCategorieSK=i.IdCategorieSK left join DimSite s on s.idSiteSk=i.idSiteSk left join DimStatut st on st.idStatutSK = i.idStatutSK left join DimDirection di on di.idDirectionSK = i.idDirectionSK where d.Year= cast(? as varchar) group by c.name , s.name , di.name order by c.name " myvalue<-data.frame(VYear) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataProjetParam <- function() { req<- " select d.Year as Periode, d.DayOfWeek, d.MonthName, d.Date DateOpe, d.Month, realName, fisrtName, pr.name LeProjet, NiveauAvancement, RespectDelai, t.IdTechnicienSK, t.Name from FaitProjet p left join DimDate d on d.IdDateSK=p.IdDateSK left join DimTechnicien t on t.IdTechnicienSK=p.IdTechnicienSK left join DimProjet pr on pr.idProjetSK=p.idProjetSK where d.Year= cast(? as varchar) " myvalue<-data.frame(VYear) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_EvolProjetParam <- function() { req<- " select pr.name Projet, t.Name, NiveauAvancement, RespectDelai from FaitProjet p left join DimDate d on d.IdDateSK=p.IdDateSK left join DimTechnicien t on t.IdTechnicienSK=p.IdTechnicienSK left join DimProjet pr on pr.idProjetSK=p.idProjetSK where d.Year= cast(? as varchar) order by d.Year , d.DayOfWeek, d.MonthName " myvalue<-data.frame(VYear) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataConsommable <- function() { req<- " select d.Year as Periode, d.DayOfWeek, d.MonthName, d.Date DateOpe, d.Month, s.name Site, di.name Direction, Nombre from FaitConsommableInfo c left join DimDate d on d.IdDateSK=c.IdDateSK left join DimSite s on s.idSiteSk=c.idSiteSk left join DimDirection di on di.idDirectionSK=c.idDirectionSK where d.Year= cast(? as varchar) and d.Month=cast(? as varchar) " myvalue<-data.frame(VYear, VMonth) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataConsommableRapport <- function() { req<- " select s.name Site, di.name Direction, sum(Nombre) Nombre from FaitConsommableInfo c left join DimDate d on d.IdDateSK=c.IdDateSK left join DimSite s on s.idSiteSk=c.idSiteSk left join DimDirection di on di.idDirectionSK=c.idDirectionSK where d.Year= cast(? as varchar) group by s.name, di.name " myvalue<-data.frame(VYear) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataSatisfaction <- function() { req<- " select d.Year as Periode, d.DayOfWeek, d.MonthName, d.Date DateOpe, d.Month, realName, fisrtName, s.name Site, c.Name, Poids , Satisfaction, case when(satisfaction <> -1) then satisfaction else 0 end Votant, case when(satisfaction = -1) then 1 else 0 end NonVotant from FaitSatisfaction sa left join DimDate d on d.IdDateSK=sa.IdDateSK left join DimTechnicien t on t.IdTechnicienSK=sa.IdTechnicienSK left join DimSite s on s.idSiteSk=sa.idSiteSk left join DimCategorieInfo c on c.idCategorieSK = sa.idCategorieSK where d.Year= cast(? as varchar) and d.Month=cast(? as varchar) " myvalue<-data.frame(VYear, VMonth) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataHuilerie_param <- function() { req<-" select d.Year as Periode, d.DayOfWeek, d.MonthName, day(d.date) Jour, d.Date DateOpe, d.Month, h.CodeUsine, h.NomUsine Usine, q.ChefQuart, t.Libelle Equipe, q.NomQuart Quart, p.GraineRecepKG, p.EcartKG, p.GraineMoKG, p.AlibetProduitSac, p.Farine21ProduitSac, p.AlibetProduitSac + p.Farine21ProduitSac as Tourteau, CoqueIncorporeKG, CoqueChaudiereKG, HuileNProduitLT, HuileNMOLT, HuileRaffineLT, NbCartonDiamaorU, -- on calcule tous les kpis case when GraineMoKG = 0 then 0.0 else (HuileNProduitLT / GraineMoKG) * 100 end as TauxHnGr, case when GraineMoKG = 0 then 0.0 else ((p.AlibetProduitSac + p.Farine21ProduitSac) / GraineMoKG) * 100 end as TauxTtxGr from FaitHlProduction p left join DimDate d on d.IdDateSK=p.IdDateSK left join DimQuart q on q.IdQuartSK=p.IdQuartSK left join DimTranche_horaire t on t.IdTrancheSK=p.IdTrancheSK left join DimUsinehuilerie h on h.IdUsineSK=p.IdUsineSK where d.Year= cast(? as varchar) and d.Month=cast(? as varchar) and h.CodeUsine = cast(? as varchar) order by q.NomQuart " myvalue<-data.frame(VYear, VMonth, VIdHuilerie) sqlExecute(cn, req, myvalue, fetch=TRUE) } get_dataClassement <- function() { #Obtention des donnees req<-"select b.Year as Periode,b.DayOfWeek,b.MonthName,b.Date DateOpe, b.Month, c.IdVarietes,c.Libelle Variete, d.IdClasse,d.Libelle Classe,d.Qualite, e.IdNatureCotons,e.Libelle NatureCoton, f.IdUsine,f.Libelle Usine, g.IdSoies,g.Libelle Soie, g.Longueur LongueurSoie, h.IdAvaries,h.Libelle Avaries, a.PoidsBrut,a.PoidsNet from FactClassement a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimVarietes c on c.IdVarietesSK=a.IdVarietesSK left join DimClasse d on d.IdClasseSK=a.IdClasseSK left join DimNatureCotons e on e.IdNatureCotonsSK=a.IdNatureCotonsSK left join DimUsine f on f.IdUsineSK=a.IdUsineSK left join DimSoies g on g.IdSoiesSK=a.IdSoiesSK left join DimAvaries h on h.IdAvariesSK=a.IdAvariesSK where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) and f.IdUsine = cast(? as varchar) " myvalue<-data.frame(VYear,VMonth,VIdUsine) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataPanne <- function() { #Obtention des donnees req<-"select b.Year as Periode,b.DayOfWeek,b.MonthName,b.Date DateOpe, b.Month, c.IdUsine,c.Libelle Usine, d.Id_type,d.Libelle_type TypePanne, a.NbPanne, case when a.DureePanne<0 then -a.DureePanne else a.DureePanne end as DureePanne, clasification_machi from FactPanne a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimUsine c on c.IdUsineSK=a.IdUsineSK left join DimTypePanne d on d.IdTypePanneSK=a.IdTypePanneSK where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) and c.IdUsine = cast(? as varchar) " myvalue<-data.frame(VYear,VMonth,VIdUsine) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataPanneCumul <- function() { #Obtention des donnees req<-"select b.Year as Periode,b.DayOfWeek,b.MonthName,b.Date DateOpe, b.Month, c.IdUsine,c.Libelle Usine, d.Id_type,d.Libelle_type TypePanne, a.NbPanne, case when a.DureePanne<0 then -a.DureePanne else a.DureePanne end as DureePanne, clasification_machi from FactPanne a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimUsine c on c.IdUsineSK=a.IdUsineSK left join DimTypePanne d on d.IdTypePanneSK=a.IdTypePanneSK where b.Year= cast(? as varchar) and b.Month<=cast(? as varchar) and c.IdUsine = cast(? as varchar) " myvalue<-data.frame(VYear,VMonth,VIdUsine) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataPanneCumul12Mois <- function() { #Obtention des donnees req<-"select b.Year as Periode,b.DayOfWeek,b.MonthName,b.Date DateOpe, b.Month, c.IdUsine,c.Libelle Usine, d.Id_type,d.Libelle_type TypePanne, a.NbPanne, case when a.DureePanne<0 then -a.DureePanne else a.DureePanne end as DureePanne, clasification_machi from FactPanne a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimUsine c on c.IdUsineSK=a.IdUsineSK left join DimTypePanne d on d.IdTypePanneSK=a.IdTypePanneSK where b.Year= cast(? as varchar) and c.IdUsine = cast(? as varchar) " myvalue<-data.frame(VYear,VIdUsine) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataEffectif <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbEffectif,a.NbPermanent, a.NbSaisonnier,a.NbLocaux,a.NbExpat,a.NbTemporaire,a.NbGardien,d.VALL as Direction, a.NbFonctAffecte,a.NbFonctDetache,a.NbCadre,a.NbAgm,a.NbEmp, case when DATEDIFF(year,dtna,SYSDATETIME()) <=20 then 1 else 0 end as de0a20An, case when DATEDIFF(year,dtna,SYSDATETIME()) >=21 and DATEDIFF(year,dtna,SYSDATETIME()) <=30 then 1 else 0 end as de21a30An, case when DATEDIFF(year,dtna,SYSDATETIME()) >=31 and DATEDIFF(year,dtna,SYSDATETIME()) <=40 then 1 else 0 end as de31a40An, case when DATEDIFF(year,dtna,SYSDATETIME()) >=41 and DATEDIFF(year,dtna,SYSDATETIME()) <=50 then 1 else 0 end as de41a50An, case when DATEDIFF(year,dtna,SYSDATETIME()) >=51 and DATEDIFF(year,dtna,SYSDATETIME()) <=60 then 1 else 0 end as de51a60An, case when DATEDIFF(year,dtna,SYSDATETIME()) >=61 and DATEDIFF(year,dtna,SYSDATETIME()) <=70 then 1 else 0 end as de61a70An, case when DATEDIFF(year,dtna,SYSDATETIME()) >=71 then 1 else 0 end as plus70An, DATEDIFF(year,dtna,SYSDATETIME()) as Age, e.VALL as MotifDepart, DATEDIFF(year,dtes,SYSDATETIME()) as Anc from FactEffectif a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 left join stg_RHFNOM e on e.cacc=c.MTFR and d.ctab='23' and d.nume=1 where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataEffectifCumul <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbEffectif, a.NbPermanent,a.NbSaisonnier,a.NbLocaux,a.NbExpat,a.NbTemporaire,a.NbGardien, d.VALL as Direction, a.NbFonctAffecte,a.NbFonctDetache,a.NbCadre,a.NbAgm,a.NbEmp from FactEffectif a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 where b.Year= cast(? as varchar) and b.Month<=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataDepart <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbDepart,a.NbPermanent, a.NbSaisonnier,a.NbTemporaire,a.NbGardien, d.VALL as Direction, e.VALL as MotifDepart from FactDepart a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 left join stg_RHFNOM e on e.cacc=c.MTFR and e.ctab='23' and e.nume=1 where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataDepartCumul <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbDepart,a.NbPermanent, a.NbSaisonnier,a.NbTemporaire,a.NbGardien, d.VALL as Direction, e.VALL as MotifDepart from FactDepart a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 left join stg_RHFNOM e on e.cacc=c.MTFR and e.ctab='23' and e.nume=1 where b.Year= cast(? as varchar) and b.Month<=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataRecrutement <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbRecrutement,a.NbPermanent, a.NbSaisonnier,a.NbTemporaire,a.NbGardien, d.VALL as Direction from FactRecrutement a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataRecrutementCumul <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbRecrutement,a.NbPermanent, a.NbSaisonnier,a.NbTemporaire,a.NbGardien, d.VALL as Direction from FactRecrutement a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 where b.Year= cast(? as varchar) and b.Month<=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataStock <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.codart,c.LIBART1,c.LIBART2, a.Qte,a.Montant from FactStock a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimArticle c on c.IdArticleSK=a.IdIdArticleSK where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) and c.UNISTO='L' " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataStockCumul <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.codart,c.LIBART1,c.LIBART2, a.Qte,a.Montant from FactStock a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimArticle c on c.IdArticleSK=a.IdIdArticleSK where b.Year= cast(? as varchar) and b.Month<=cast(? as varchar) and c.UNISTO='L' " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataAchat <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NumCpt,c.NUMTIE,c.NOMFOU, a.NbCde,a.NbCdeCFA,a.NbCdeEURO,a.NbCdeUSD, a.MontantCdeCFA,a.MontantCdeEURO,a.MontantCdeUSD from FactAchat a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimFournisseur c on c.IdFournisseurSK=a.IdFournisseurSK where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataAchatCumul <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NumCpt,c.NUMTIE,c.NOMFOU, a.NbCde,a.NbCdeCFA,a.NbCdeEURO,a.NbCdeUSD, a.MontantCdeCFA,a.MontantCdeEURO,a.MontantCdeUSD from FactAchat a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimFournisseur c on c.IdFournisseurSK=a.IdFournisseurSK where b.Year= cast(? as varchar) and b.Month<=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataUtilisateur <- function() { #Obtention des donnees req<-"select CodeUtilisateur, NomUtilisateur,MotPasse, a.ProfilUtilisateur from Utilisateur a " #myvalue<-data.frame(VCodeSociete) sqlExecute(cn, req, fetch=TRUE) } get_dataMission <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbMission,a.NbjourMission, d.VALL as Direction, a.MontantMission from FactMission a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 left join stg_RHFNOM e on e.cacc=c.MTFR and d.ctab='23' and d.nume=1 where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataMissionCumul <- function() { req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, c.NMAT,c.NIV1,c.NIV2,c.NIV3,c.CLAS, c.NOM,PREN,SEXE,c.SITF,c.CAT,c.ECH,c.GRAD,c.FONC, a.NbMission,a.NbjourMission, d.VALL as Direction, a.MontantMission from FactMission a left join DimDate b on b.IdDateSK=a.IdDateSK left join DimEmploye c on c.IdEmployeSK=a.IdEmployeSK left join stg_RHFNOM d on d.cacc=c.niv1 and d.ctab='1' and d.nume=1 left join stg_RHFNOM e on e.cacc=c.MTFR and d.ctab='23' and d.nume=1 where b.Year= cast(? as varchar) and b.Month<=cast(? as varchar) " myvalue<-data.frame(VYear,VMonth) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataFacture <- function() { V_year<-VYear V_Month<-VMonth req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, a.NbFacture,a.PoidsNet,a.NbBalle from FactFacture a left join DimDate b on b.IdDateSK=a.IdDateSK where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) " myvalue<-data.frame(V_year,V_Month) #myvalue<-data.frame(Year,input$Month) sqlExecute(cn, req,myvalue, fetch=TRUE) } get_dataFactureDef <- function() { V_Year<-VYear V_Month<-VMonth req<-" select b.Year as Periode,b.DayOfWeek,b.MonthName, b.Date DateOpe, b.Month, dt_factur_def, nm_negoci, li_pays, rf_contrats_sdcc, rf_contrats_negoci, references_instru, rf_bl, dt_bl, recolte, type as typeF, pu_euro, li_incote, nb_balle, montant_contrat, montant_tot_fact_def, rf_factur_def from stg_v_facture_definitive a INNER join DimDate b ON CONVERT(varchar,b.Date,23) = CONVERT(varchar,a.dt_factur_def,23) where b.Year= cast(? as varchar) and b.Month=cast(? as varchar) " myvalue<-data.frame(V_Year,V_Month) sqlExecute(cn, req,myvalue, fetch=TRUE) } #---Fermeture de la connexion bd----------------------------------------------------------------- close_connection <- function() { odbcClose(cn) } jsCode <- 'shinyjs.winprint = function(){ window.print(); }' #---Dashboard header carrying the title of the dashboard--------------------- header <- dashboardHeader(title = "TABLEAU DE BORD - SODECOTON") #Sidebar content of the dashboard sidebar <- dashboardSidebar( useShinyjs(html = FALSE), extendShinyjs(text = jsCode, functions = c("winprint")), shinyjs::hidden( div(id = "Sidebar", sidebarMenu( menuItem("Source - SODECOTON ", tabName = "dashboard", icon = icon("dashboard")), menuItem("SELECTION PARAMETRES",badgeColor = "green"), selectInput("Year","Annee",choices=c(2017,2018,2019, 2020,2021,2022,2023),selected = 2020), selectInput("Month","Mois",choices=NULL), selectInput("Usine","Usine",choices=NULL), selectInput("Huilerie","Huilerie",choices=NULL), actionButton("ScreenDownload", "Telecharger") ) )) ) #--------Synthese------------------------------------------------------------- frow1Synhese <- fluidRow( valueBoxOutput("value1Synthese",width = 2) ,valueBoxOutput("value4Synthese",width = 2) #,valueBoxOutput("value4",width = 2) #,valueBoxOutput("value5",width = 2) #,valueBoxOutput("value12",width = 2) #,valueBoxOutput("value10",width = 2) ) #---------------------------------------------------------------------------- #--------------------------UI Huilerie--------------------------------------- frowH1 <- fluidRow( valueBoxOutput("TauxHnGr", width = 2) ,valueBoxOutput("TauxTxGr", width = 2) ,valueBoxOutput("ProductiviteDiamaor", width = 2) ) frowH2 <- fluidRow( valueBoxOutput("QteGraineRecep", width = 2) ,valueBoxOutput("QteGraineMO", width = 2) ,valueBoxOutput("NbSacsTotal", width = 2) ,valueBoxOutput("QteHuileNProduitLT", width = 2) ) frowH3 <- fluidRow( box(width = 6, title = "EVOLUTION DES RECEPTION DES GRAINES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChart4Output("CourbeReceptionGraine", height = "290px") ), box(width = 6, title = "RECEPTION DES GRAINES PAR TRANCHE HORAIRE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("RecepGraineByTranche",height = "290px") ), ) frowH4 <- fluidRow( box(width = 6, title = "EVALUATION DES MISES EN OEUVRE PAR QUART" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("MoByQuart", height = "290px") ), box(width = 6, title = "EVALUATION DES MISES EN OEUVRE PAR TRANCHE HORAIRE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("MoByTranche",height = "290px") ), ) frowH5 <- fluidRow( box(width = 6, title = "PRODUCTION DU TOURTEAU PAR QUART" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("TtxByQuart", height = "290px") ), box(width = 6, title = "PRODUCTION DE L'HUILE NEUTRE PAR QUART" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("HnByQuart",height = "290px") ), ) #---------------FIN UI Huilerie-------------------------------------------- #----------------UI Informatique------------------------------------------- PremiereLigne_Informatique <- fluidRow( valueBoxOutput("NombreIncident", width = 2) ,valueBoxOutput("NombreProjet", width = 2) ,valueBoxOutput("QuantiteConsommable", width = 2) ) DeuxiemeLigne_Informatique <- fluidRow( valueBoxOutput("TauxRespectDelaiProjet", width = 2) ,valueBoxOutput("TauxSatisfactionUtilisateur", width = 2) ,valueBoxOutput("TauxParticipation", width = 2) ,valueBoxOutput("TauxDisponibiliteService", width = 2) ,valueBoxOutput("TauxDisponibiliteServeur", width = 2) ,valueBoxOutput("NombreChangement", width = 2) ) TroisiemeLigne_Informatique <- fluidRow( box(width = 6, title = "RAPPORT ANNUEL SUR L'EVOLUTION DES PROJETS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,reactableOutput("TabEvolutionProjet", height = "290px", width = "100%") ), box(width = 6, title = "RAPPORT ANNUEL SUR L'AFFECTATION DE CONSOMMABLES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,reactableOutput("TabRapportConsommable", height = "290px", width = "100%") ) ) QuatriemeLigne_Informatique <- fluidRow( box(width = 6, title = "RAPPORT ANNUEL SUR LES INCIDENTS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,reactableOutput("TabRapportIncident", height = "350px", width = "100%") ), box(width = 6, title = "INCIDENTS ANNUEL PAR DIRECTION" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("INCIDENTSANNUELBYDIRECTION", height = "350px", width = "100%") ) ) CinquiemeLigne_Informatique <- fluidRow( box(width = 6, title = "INCIDENTS MENSUEL PAR DIRECTION" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("INCIDENTSMENSUELBYDIRECTION", height = "350px", width = "100%") ), box(width = 6, title = "INCIDENTS PAR SITE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,amChartsOutput("INCIDENTSBYSITE", height = "350px", width = "100%") ) ) #----------------FIN UI Informatique------------------------------------------- frow1 <- fluidRow( valueBoxOutput("value1",width = 2) ,valueBoxOutput("value2",width = 2) ,valueBoxOutput("value4",width = 2) ,valueBoxOutput("value5",width = 2) ,valueBoxOutput("value12",width = 2) ,valueBoxOutput("value10",width = 2) ) frow2 <- fluidRow( box(width = 6, title = "POIDS MOYENS DES BALLE (KG) PAR EQUIPE - MOIS M vs M-1" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabBallesCompare",height = "290px",width = "80%") ), box(width = 6, title = "PERFORMANCE DES EQUIPES" ,status = "primary" ,solidHeader = TRUE ,collapsible = FALSE ,plotlyOutput("GNbBallesEquipes", height = "290px") )#, #selectInput("Nature","Nature",choices = c("Poids Moyen","Rendement Fibre","Egrene Moy/J")) ) frow3 <- fluidRow( box(width = 6, title = "RENDEMENT FIBRE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GRendementFibre", height = "290px") ), box(width = 6,height=10, title = "RENDEMENT JOURNALIER - CG et FIBRES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabRendement",height = "290px",width = "80%") ), ) frow4 <- fluidRow( valueBoxOutput("value3",width = 2), valueBoxOutput("value6",width = 2), valueBoxOutput("value7",width = 2), valueBoxOutput("value8",width = 2), valueBoxOutput("value9",width = 2), valueBoxOutput("value11",width = 2) ) frow5 <- fluidRow( valueBoxOutput("value7",width = 2) ) frow6 <- fluidRow( valueBoxOutput("value13",width = 2), valueBoxOutput("value14",width = 2), valueBoxOutput("value15",width = 2), valueBoxOutput("value16",width = 2), valueBoxOutput("value17",width = 2), valueBoxOutput("value18",width = 2) ) frow7 <- fluidRow( box(width = 4, title = "TAUX FIBRE PAR CATEGORIE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabtauxFibre",height = "290px",width = "100%") ), #box(width = 6, # title = "PERFORMANCE DES EQUIPES" # ,status = "primary" # ,solidHeader = TRUE # ,collapsible = FALSE # ,plotlyOutput("GTauxFibreSoie", height = "290px") #)#, box(width = 3, title = "TAUX FIBRE PAR CATEGORIE (%)" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GTauxFibreCategorie", height = "300px") ), box(width = 5, title = "TONNAGE FIBRE JOURNALIER / CATEGORIE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GTauxFibreCategorie2", height = "300px") ) ) frow8 <- fluidRow( valueBoxOutput("value19",width = 4), valueBoxOutput("value20",width = 4), valueBoxOutput("value21",width = 4) ) frow9 <- fluidRow( box(width = 6, title = "TAUX FIBRES / SOIES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("LongueurSoie",height = "290px",width = "80%") ), box(width = 6, title = "TAUX FIBRES / VARIETES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabtauxFibreVariete",height = "290px",width = "80%") ) ) frow10 <- fluidRow( box(width = 12, title = "CLASSEMENT - JOURNALIER" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabclassementJour",height = "290px",width = "80%") ) ) frow11 <- fluidRow( valueBoxOutput("value22",width = 3), valueBoxOutput("value30",width = 3), valueBoxOutput("value31",width = 2), valueBoxOutput("value32",width = 2), valueBoxOutput("value33",width = 2) #valueBoxOutput("value23",width = 3), #valueBoxOutput("value24",width = 3), #valueBoxOutput("value25",width = 3) ) frow12 <- fluidRow( #--Cumul Annuel valueBoxOutput("value26",width = 3), valueBoxOutput("value34",width = 3), valueBoxOutput("value35",width = 2), valueBoxOutput("value36",width = 2), valueBoxOutput("value37",width = 2) #valueBoxOutput("value27",width = 3), #valueBoxOutput("value28",width = 3), #valueBoxOutput("value29",width = 3) ) frow12b <- fluidRow( valueBoxOutput("value48",width = 3), valueBoxOutput("value49",width = 3), valueBoxOutput("value50",width = 2), valueBoxOutput("value51",width = 2), valueBoxOutput("value52",width = 2) ) frow13 <- fluidRow( box(width = 6, title = "EVOLUTION DES EFFECTIFS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GEvolutionEffectif", height = "290px") ), box(width = 6,height=10, title = "EVOLUTION DES EFFECTIFS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabEffectif",height = "290px",width = "100%") ) ) frow14 <- fluidRow( #box(width = 5, # title = "REPARTITION DES EFFECTIFS" # ,status = "primary" # ,solidHeader = TRUE # ,collapsible = TRUE # ,plotlyOutput("GEffectifparSexe", height = "290px") #), box(width = 3, title = "EFFECTIFS PAR CATEGORIES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabEffectifCatSocio",height = "320px",width = "100%") ), box(width = 9, title = "REPARTITION DES EFFECTIFS DU MOIS PAR DIRECTION" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabEffectifParDirection",height = "320px",width = "100%") ) ) frow15 <- fluidRow( box(width = 6, title = "EVOLUTION MENSUELLE DES EFFECTIFS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabEffectifParClasse",height = "290px",width = "100%") ), box(width = 6, title = "EVOLUTION MENSUELLE DES EFFECTIFS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GEvolutionClasseEffectif", height = "290px") ) ) frow15b <- fluidRow( box(width = 4, title = "Effectifs des permanents par age" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GPyramideAgeSexePermanent", height = "400px") ), box(width = 4, title = "Effectifs des Saisonniers par age" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GPyramideAgeSexeSaisonnier", height = "400px") ), box(width = 4, title = "Effectifs des temporaire par age" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GPyramideAgeSexeTemporaraire", height = "400px") ) ) frow15c <- fluidRow( box(width = 4, title = "Effectifs des permanents par Ancienneté" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GPyramideAncSexePermanent", height = "400px") ), box(width = 4, title = "Effectifs des Saisonniers par Ancienneté" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GPyramideAncSexeSaisonnier", height = "400px") ), box(width = 4, title = "Effectifs des temporaire par Ancienneté" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GPyramideAncSexeTemporaraire", height = "400px") ) ) frow16 <- fluidRow( box( rpivotTableOutput("MatriceEffectif") ) ) frow17 <- fluidRow( valueBoxOutput("value38",width = 3), valueBoxOutput("value39",width = 3), valueBoxOutput("value40",width = 2), valueBoxOutput("value41",width = 2), valueBoxOutput("value42",width = 2) ) frow18 <- fluidRow( box(width = 7, title = "REPARTITION DES DEPARTS PAR DIRECTION" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabDepartParDirection",height = "290px",width = "90%") ), box(width = 5, title = "EVOLUTION MENSUELLE DES DEPARTS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabDepartParClasse",height = "290px",width = "80%") ) ) frow18b <- fluidRow( box(width = 6, title = "DEPARTS DU MOIS - REPARTITION PAR MOTIF" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabDepartParMotif",height = "290px",width = "90%") ), box(width = 6, title = "DEPARTS CUMUL ANNUEL- REPARTITION PAR MOTIF" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabDepartParMotifCumul",height = "290px",width = "90%") ) ) frow19 <- fluidRow( valueBoxOutput("value43",width = 3), valueBoxOutput("value44",width = 3), valueBoxOutput("value45",width = 2), valueBoxOutput("value46",width = 2), valueBoxOutput("value47",width = 2) ) frow20 <- fluidRow( box(width = 7, title = "REPARTITION DES RECRUTEMENTS PAR DIRECTION" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabRecrutementParDirection",height = "290px",width = "90%") ), box(width = 5, title = "EVOLUTION MENSUELLE DES RECRUTEMENTS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabRecrutementParClasse",height = "290px",width = "80%") ) ) frow21 <- fluidRow( #valueBoxOutput("value53",width = 3), valueBoxOutput("value53Vte",width = 3), valueBoxOutput("value53VtePoidsNet",width = 3), valueBoxOutput("value53VteNbBalle",width = 3), valueBoxOutput("value53VteMontant",width = 3) ) frow21c <- fluidRow( valueBoxOutput("value53NbContrat",width = 3), valueBoxOutput("value53NbClient",width = 3), valueBoxOutput("value53PUMin",width = 3), valueBoxOutput("value53PUMax",width = 3) ) frow21a <- fluidRow( box(width = 6, title = "REPARTITION DES MONTANTS PAR TYPE DE FIBRE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabtauxVente",height = "290px",width = "90%") ), box(width = 6, title = "REPARTITION MONTANTS PAR TYPE DE FIBRE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GTauxVenteParType", height = "300px") ) ) frow21b <- fluidRow( box(width = 6, title = "REPARTITION DES MONTANTs PAR CLIENT" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabtauxVenteParClient",height = "290px",width = "90%") ), box(width = 6, title = "REPARTITION MONTANTS PAR CLIENT" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GTauxVenteParClient", height = "300px") ) ) frow22 <- fluidRow( box(width = 7,height = "270px", h3("Evolution mensuelle Qte Stock (Litre)"), pivottablerOutput("MatriceStock2") ) #pivottablerOutput("ConsultationMvtSaisie_test") #box(width = 6, # title = "EVOLUTION QUANTITE ET MONTANT PAR PRODUIT" # ,status = "primary" # ,solidHeader = TRUE # ,collapsible = TRUE # ,tableOutput("TabStockEvolution2") #) ) frow23 <- fluidRow( box(width = 4, title = "QUANTITE ET MONTANT PAR PRODUIT" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabQteMontantParProduit",height = "290px",width = "90%") ) ) frow24 <- fluidRow( valueBoxOutput("value55",width = 3), valueBoxOutput("value56",width = 1), valueBoxOutput("value57",width = 1), valueBoxOutput("value58",width = 3), valueBoxOutput("value59",width = 2), valueBoxOutput("value60",width = 2) ) frow25 <- fluidRow( valueBoxOutput("value61",width = 3), valueBoxOutput("value62",width = 1), valueBoxOutput("value63",width = 1), valueBoxOutput("value64",width = 3), valueBoxOutput("value65",width = 2), valueBoxOutput("value66",width = 2) ) frow26 <- fluidRow( box(width = 6, title = "EVOLUTION MENSUELLE NOMBRE DE COMMANDES CRÉES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabCdeEvolution",height = "290px",width = "100%") ), box(width = 6, title = "EVOLUTION MENSUELLE NOMBRE DE COMMANDES CRÉES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GEvolutionNbCde", height = "290px") ) ) frow27 <- fluidRow( box(width = 6, title = "EVOLUTION MENSUELLE DES MONTANS DE COMMANDES CRÉES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabMonantCdeEvolution",height = "290px",width = "100%") ), box(width = 6, title = "EVOLUTION MENSUELLE DES MONTANS DE COMMANDES CRÉES" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GEvolutionCdeMontant", height = "290px") ) ) frow28 <- fluidRow( #box(width = 6, # title = "EVOLUTION MENSUELLE DES MONTANS DE COMMANDES CRÉES" # ,status = "primary" # ,solidHeader = TRUE # ,collapsible = TRUE # ,DTOutput("TabMonantCdeEvolution",height = "290px",width = "100%") #), box(width = 6, title = "MONTANT DES COMMANDES PAR DATE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GMontantCdeParDate", height = "290px") ), box(width = 6, title = "MONTANT DES COMMANDES PAR FOURNISSEUR" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GMontantCdeParFsseur", height = "290px") ) ) frow29 <- fluidRow( box(width = 8, title = "REPARTITION DES EFFECTIFS PAR TRANCHE D'AGE" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabEffectifParAge",height = "290px",width = "90%") ), box(width = 1, h4("choisir une plage d'age pour les effectifs"), numericInput("AgeDebut","Age debut",value = 0,width = "150px"), numericInput("AgeFin","Age fin",value = 0,width = "150px"), ), box(width = 3, title = "REPARTITION DES EFFECTIFS PAR TRANCHE D'AGE", status = "primary", DTOutput("TabEffectifParAge2",height = "200px",width = "90%") ) #box(width = 5, # title = "EVOLUTION MENSUELLE DES RECRUTEMENTS" # ,status = "primary" # ,solidHeader = TRUE # ,collapsible = TRUE # ,DTOutput("TabRecrutementParClasse",height = "290px",width = "80%") #) ) frow30 <- fluidRow( valueBoxOutput("value67",width = 4), valueBoxOutput("value68",width = 4), valueBoxOutput("value69",width = 4)#, #valueBoxOutput("value70",width = 3) ) frow31 <- fluidRow( box(width = 5, title = "EVOLUTION MENSUELLE DES MISSIONS" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabMissionParMois",height = "290px",width = "90%") ), box(width = 7, title = "CUMUL ANNUEL DES MISSIONS PAR DIRECTION" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabMissionParDirection",height = "290px",width = "100%") ) ) frow32 <- fluidRow( box(width = 8, title = "COUTS DES MISSIONS PAR DIRECTION" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GMissionParDirection", height = "400px") ), box(width = 4, title = "EVOLUTION JOURNALIERE DES FRAIS MISSION " ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GEvolutionMissionParMois", height = "400px") ) ) frow33 <- fluidRow( valueBoxOutput("value71",width = 3), valueBoxOutput("value72",width = 3), valueBoxOutput("value73",width = 3), valueBoxOutput("value74",width = 3) ) frow100 <- fluidRow( #valueBoxOutput("value100",width = 3), #valueBoxOutput("value101",width = 3), valueBoxOutput("value102",width = 2), valueBoxOutput("value103",width = 2), valueBoxOutput("value104",width = 2), valueBoxOutput("value105",width = 2), valueBoxOutput("value106",width = 2), valueBoxOutput("value107",width = 2) ) frow102 <- fluidRow( box(width = 4, title = "RUBRIQUE DES TEMPS (Heures)" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabTemps2",height = "200px",width = "90%") ), box(width = 4, title = "RUBRIQUE DES TEMPS (Heures)" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabTemps3",height = "200px",width = "90%") ), box(width = 4, title = "RUBRIQUE DES TEMPS (Heures)" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabTemps4",height = "200px",width = "90%") ) ) frow101 <- fluidRow( box(width = 3, title = "EVOLUTION MENSUELLE TEMPS NET (Heures)" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,DTOutput("TabTempsNetEvolution",height = "290px",width = "90%") ), box(width = 8, title = "EVOLUTION MENSUELLE TEMPS NET (Heures)" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GEvolutionTempsNetParMois", height = "290px") ) ) frow34 <- fluidRow( box(width = 8, title = "NOMBRE DE PANNES PAR TYPE DE PANNE - CUMUL ANNUEL" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GPanneParType", height = "400px") ), box(width = 4, title = "EVOLUTION JOURNALIERE DE NOMBRE DE PANNES " ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotlyOutput("GEvolutionPannesParMois", height = "400px") ) ) frow35 <- fluidRow( box(width = 6,height = "600px", h3("Evolution mensuelle nombre de pannes"), pivottablerOutput("MatricePanne") ), box(width = 6,height = "600px", h3("Evolution mensuelle duree des pannes (en Heures)"), pivottablerOutput("MatriceDureePanne") ) ) # combine the two fluid rows to make the body body <- dashboardBody( #actionButton("ScreenDownload", "Telecharger"), tabsetPanel( tabPanel(tags$h3("SODECOTON - SUIVI DES INDICATEURS DE PERFORMANCES"), tags$h4("veuillez vous connecter"), tags$br(), value = 1, br(), div(id = "Connexion", textInput("username", "Username"), passwordInput("password", label = "Password"), actionButton("login", "Login",class = "btn-primary"), textOutput("pwd") ), br(), br(), img(src="Sodecoton.jpg",height="5%", width="40%") ), id = "tabselected", type = "pills" ) ) #completing the ui part with dashboardPage ui <- dashboardPage(title = 'TABLEAUX DE BORD DE LA SODECOTON', header, sidebar, body, skin='red') Server <- function(input, output, session) { # Run every 30 seconds dataf_production = reactive({ invalidateLater(900000,session) input$Year input$Usine input$Month get_dataProduction() } ) dataf_productionUsine = reactive({ invalidateLater(900000,session) input$Year input$Usine input$Month get_dataProductionUsine() } ) dataf_evacuation = reactive({ invalidateLater(900000,session) input$Year input$Usine input$Month get_dataEvacuation() } ) dataf_classement = reactive({ invalidateLater(900000,session) input$Year input$Usine input$Month get_dataClassement() } ) dataf_Panne = reactive({ invalidateLater(900000,session) input$Year input$Usine input$Month get_dataPanne() } ) dataf_PanneCumul = reactive({ invalidateLater(900000,session) input$Year input$Usine input$Month get_dataPanneCumul() } ) dataf_PanneCumul12Mois = reactive({ invalidateLater(900000,session) input$Year input$Usine input$Month get_dataPanneCumul12Mois() } ) dataf_Effectif = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataEffectif() } ) dataf_EffectifCumul = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataEffectifCumul() } ) dataf_Depart = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataDepart() } ) dataf_DepartCumul = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataDepartCumul() } ) dataf_Recrutement = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataRecrutement() } ) dataf_RecrutementCumul = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataRecrutementCumul() } ) dataf_Stock = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataStock() } ) dataf_StockCumul = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataStockCumul() } ) dataf_Achat = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataAchat() } ) dataf_AchatCumul = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataAchatCumul() } ) dataf_Mission = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataMission() } ) dataf_MissionCumul = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataMissionCumul() } ) dataf_facture = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataFacture() } ) dataf_factureDef = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataFactureDef() } ) #---get data for huilerie------------ dataf_Huilerie = reactive({ invalidateLater(900000,session) input$Year input$Huilerie input$Month get_dataHuilerie() }) dataf_Huilerie_param = reactive({ invalidateLater(900000,session) input$Year input$Huilerie input$Month get_dataHuilerie_param() }) #--------All datas get for Huilerie---------- #---get data for Informatique------------ dataf_Incident_param = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataIncident() }) dataf_dataIncidentRapport_param = reactive({ invalidateLater(900000,session) input$Year get_dataIncidentRapport() }) dataf_getProjet = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataProjet() }) dataf_Projet_param = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataProjetParam() }) dataf_Evol_Projet_param = reactive({ invalidateLater(900000,session) input$Year get_EvolProjetParam() }) dataf_Consommable_param = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataConsommable() }) dataf_dataConsommableRapport_param = reactive({ invalidateLater(900000,session) input$Year get_dataConsommableRapport() }) dataf_Satisfaction_param = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataSatisfaction() }) dataf_dataIncident_By_Direction = reactive({ invalidateLater(900000,session) input$Year input$Month get_dataIncident_By_Direction() }) dataf_dataIncident_By_Site = reactive({ invalidateLater(900000,session) input$Year input$Month dataf_dataIncident_By_Site() }) #--------All datas get for Informatique---------- #--- On recupere toutes les huileries-------- reqHuilerie<- sqlQuery(cn," select ' ' CodeUsine,' ' NomUsine UNION ALL select CodeUsine, NomUsine from DimUsineHuilerie " ) #----- On charge le combo des huileries------------- choicesHuilerie = setNames(reqHuilerie$CodeUsine,reqHuilerie$NomUsine) updateSelectInput(session, 'Huilerie', choices=choicesHuilerie, selected = 1) reqUsine<- sqlQuery(cn," select ' ' IdUsine,' ' NomUsine UNION ALL select IdUsine,Libelle from DimUsine " ) reqMois<- sqlQuery(cn," SELECT distinct Month,MonthName FROM [DimDate] order by Month " ) choicesUsine = setNames(reqUsine$IdUsine,reqUsine$NomUsine) updateSelectInput(session,'Usine',choices=choicesUsine,selected = 5) choicesMois = setNames(reqMois$Month,reqMois$MonthName) updateSelectInput(session,'Month',choices=choicesMois,selected = 5) user_vec <- c("user" = "user", "stalle" = "coton2020" ) #----On capture tous les changements de valeurs dans la liste deroulante sur les huileries----- observeEvent(input$Huilerie, { VIdHuilerie <<-input$Huilerie }) observeEvent(input$Year, { VYear<<-input$Year #runjs('Shiny.setInputValue("Usine", " ", {priority: "event"});') }) observeEvent(input$Usine, { VIdUsine<<-input$Usine }) observeEvent(input$Month, { VMonth<<-input$Month VMonthPrec<<-as.numeric(VMonth)-1 VMonthPrec<-as.character(VMonthPrec) }) observeEvent(input$tabselected, { if (input$tabselected == "RESSOURCES H." | input$tabselected == "VENTES & STOCKS" | input$tabselected=="ACHATS & FINANCES" | input$tabselected=="SYNTHESE" ) { shinyjs::hide("Usine") shinyjs::hide("Huilerie") }else if (input$tabselected == "HUILERIES"){ shinyjs::hide("Usine") shinyjs::show("Huilerie") } else{ shinyjs::show("Usine") shinyjs::hide("Huilerie") } }) observeEvent(input$login, { Vusername<<-input$username req<-"select * from utilisateur where CodeUtilisateur like cast(? as varchar) and MotPasse like cast(? as varchar)" myvalue<-data.frame(Vusername,input$password) user<-sqlExecute(cn, req, myvalue,fetch=TRUE) nb<-nrow(user) #if(nb!=0){ # alert("Mot de passe incorectxxx!"); #alert(names(user_vec[1])) #if (str_to_lower(input$username) %in% names(user_vec)) if (nb!=0) { if (input$password == user$MotPasse) { shinyjs::show(id = "Sidebar") shinyjs::hide(id = "Connexion") output$report <- downloadHandler( filename = "report.html", content = function(file) { tempReport <- file.path(tempdir(), "report.Rmd") file.copy("report.Rmd", tempReport, overwrite = TRUE) params <- list(a = value1G, b=input$Year, c=input$Month) rmarkdown::render(tempReport, output_file = file, params = params, envir = new.env(parent = globalenv()) ) } ) #--------------SYNTHESE--------------------------------------------- output$value1Synthese <- renderValueBox({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & Month==input$Month) Valeur1 <- sum(dataf_productionUsine$PdsCgEgrene)/1000 #value1G<<-Valeur1 valueBox(formatC(Valeur1,digits = 0,format ="f",big.mark=' ' ),'TonnageCgEgrene(t)',color = "green") }) output$value4Synthese <- renderValueBox({ dataf_production<-dataf_production()[complete.cases(dataf_production()$NbBalles),] dataf_production<-dataf_production %>% filter(Periode == input$Year & Month==input$Month) Valeur4 <- sum(dataf_production$NbBalles) valueBox(formatC(Valeur4,digits = 0,format ="f",big.mark=' ' ),'Nombre de Balls',color = "green") }) #------------------------------------------------------------------- #---------------Chargement des widgets HUILERIES--------------------------- #---------Premiere ligne page huileries : Ligne des Kpis------ #-- Kpi Taux Rendement huile neutre / graine output$TauxHnGr<-renderValueBox({ dataf_Huilerie<-get_dataHuilerie()[complete.cases(get_dataHuilerie()$HuileNProduitLT),] dataf_Huilerie<-dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) QteHuileNProduite<-sum(dataf_Huilerie$HuileNProduitLT) QteGraineMoKG<-sum(dataf_Huilerie$GraineMoKG) TauxHnGr<<-0 if(QteGraineMoKG != 0){ TauxHnGr = (QteHuileNProduite / QteGraineMoKG) * 100 } valueBox(formatC(TauxHnGr, digits = 2, format ="f",big.mark=' ' ), 'Rend. HN sur Graine(%)', color = "green") }) #-- Kpi Taux Rendement Tourteau / graine output$TauxTxGr<-renderValueBox({ dataf_Huilerie<-get_dataHuilerie()[complete.cases(get_dataHuilerie()$AlibetProduitSac),] dataf_Huilerie<-dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) QteAlibetProduitSac<-sum(dataf_Huilerie$AlibetProduitSac) QteFarine21ProduitSac<-sum(dataf_Huilerie$Farine21ProduitSac) QteGraineMoKG <- sum(dataf_Huilerie$GraineMoKG) TauxTxGr<<-0 if(QteGraineMoKG != 0){ TauxTxGr = ( (QteAlibetProduitSac + QteFarine21ProduitSac) / QteGraineMoKG) * 100 } valueBox(formatC(TauxTxGr, digits = 2, format ="f", big.mark=' ' ), 'Rend. Tourteaux sur Graine(%)', color = "green") }) #-- Kpi Productivite Diamaor output$ProductiviteDiamaor<-renderValueBox({ dataf_Huilerie<- get_dataHuilerie()[complete.cases(get_dataHuilerie()$NbCartonDiamaorU),] dataf_Huilerie<-dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) ProductiviteDiamaor<-sum(dataf_Huilerie$NbCartonDiamaorU) valueBox(formatC(ProductiviteDiamaor, digits = 0, format ="f", big.mark=' ' ), 'Productivite Diamaor(U)', color = "green") }) #---------Deuxieme ligne page huileries : Ligne des autres mesures utiles------------- #---- Mesure : Graine Receptionnee output$QteGraineRecep <- renderValueBox({ dataf_Huilerie <- get_dataHuilerie()[complete.cases(get_dataHuilerie()$GraineRecepKG),] dataf_Huilerie <- dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) QteGraineRecep <- sum(dataf_Huilerie$GraineRecepKG) / 1000 QteGraineRecepG<<-QteGraineRecep valueBox(formatC(QteGraineRecep, digits = 2, format ="f",big.mark=' ' ), 'Graine Receptionnee(T)', color = "yellow") }) #---- Mesure : Graine Mise en oeuvre output$QteGraineMO <- renderValueBox({ dataf_Huilerie <- get_dataHuilerie()[complete.cases(get_dataHuilerie()$GraineMoKG),] dataf_Huilerie <- dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) QteGraineMO <- sum(dataf_Huilerie$GraineMoKG) / 1000 valueBox(formatC(QteGraineMO, digits = 2, format ="f", big.mark=' ' ), 'Graine M.O.(T)', color = "yellow") }) #---- Mesure : Nombre de Sacs de tourteaux output$NbSacsTotal <- renderValueBox({ dataf_Huilerie <- get_dataHuilerie()[complete.cases(get_dataHuilerie()$AlibetProduitSac),] dataf_Huilerie <- dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) QteAlibetProduitSac <- sum(dataf_Huilerie$AlibetProduitSac) dataf_Huilerie <- get_dataHuilerie()[complete.cases(get_dataHuilerie()$Farine21ProduitSac),] dataf_Huilerie <- dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) NbSacFarine21 <- sum(dataf_Huilerie$Farine21ProduitSac) NbSacsTotal<<-QteAlibetProduitSac + NbSacFarine21 valueBox(formatC(NbSacsTotal, digits = 0, format ="f", big.mark=' ' ), 'Sacs de tourteaux(U)', color = "yellow") }) #---- Mesure : Huile neutre produite output$QteHuileNProduitLT <- renderValueBox({ dataf_Huilerie <- dataf_Huilerie_param()[complete.cases(get_dataHuilerie()$HuileNProduitLT),] dataf_Huilerie <- dataf_Huilerie %>% filter(Periode == input$Year & CodeUsine == input$Huilerie & Month==input$Month) QteHuileNProduitLT <- sum(dataf_Huilerie$HuileNProduitLT) valueBox(formatC(QteHuileNProduitLT, digits = 2, format ="f", big.mark=' ' ), 'Huile neutre produite(L)', color = "yellow") }) #----------DIAGRAMME EVOLUTION DES RECEPTIONS DE GRAINE------------ output$CourbeReceptionGraine <- renderAmChart4({ dataf_Huilerie_<-dataf_Huilerie_param()[complete.cases(dataf_Huilerie_param()),] dataf_Huilerie_<-dataf_Huilerie_ %>% group_by(Jour) %>% summarize(GraineRecepKG=sum(GraineRecepKG)) dat <- data.frame( Jour = dataf_Huilerie_$Jour, Quantite = dataf_Huilerie_$GraineRecepKG ) amLineChart(data = dat, data2 = NULL, xValue = "Jour", yValues = "Quantite", draggable = TRUE) }) ##----------Comparaison des receptions par tranche_horaire-------------- output$RecepGraineByTranche <- renderAmCharts({ dataf_Huilerie_<-dataf_Huilerie_param()[complete.cases(dataf_Huilerie_param()),] dataf_Huilerie_<-dataf_Huilerie_ %>% group_by(Equipe) %>% summarize(GraineRecepKG=sum(GraineRecepKG)) dat <- data.frame( Equipe = dataf_Huilerie_$Equipe, Quantite = dataf_Huilerie_$GraineRecepKG ) amBarplot(x = "Equipe", y = "Quantite", data = dat, depth = 15, labelRotation = -45) }) ##----------Evaluation des mises en oeuvre par quart-------------- output$MoByQuart <- renderAmCharts({ dataf_Huilerie_<-dataf_Huilerie_param()[complete.cases(dataf_Huilerie_param()),] dataf_Huilerie_<-dataf_Huilerie_ %>% group_by(Quart) %>% summarize(GraineMoKG=sum(GraineMoKG)) dat <- data.frame( Quart = dataf_Huilerie_$Quart, Quantite = dataf_Huilerie_$GraineMoKG ) amBarplot(x = "Quart", y = "Quantite", data = dat, depth = 20, labelRotation = -45, legend = TRUE) }) ##----------Evaluation des mises en oeuvre par tranche horaire-------------- output$MoByTranche <- renderAmCharts({ datef_huilerie_p<-dataf_Huilerie_param()[complete.cases(dataf_Huilerie_param()),] datef_huilerie_p<-datef_huilerie_p %>% group_by(Equipe) %>% summarize(GraineMoKG=sum(GraineMoKG) / 1000) dat <- data.frame( label = datef_huilerie_p$Equipe, value = datef_huilerie_p$GraineMoKG ) amPie(data = dat, depth = 30, legend = TRUE) }) ##----------PRODUCTION TOURTEAU PAR QUART output$TtxByQuart <- renderAmCharts({ datef_huilerie_p<-dataf_Huilerie_param()[complete.cases(dataf_Huilerie_param()),] datef_huilerie_p<-datef_huilerie_p %>% group_by(Quart) %>% summarize(Tourteau=sum(Tourteau) * 60) dat <- data.frame( label = datef_huilerie_p$Quart, value = datef_huilerie_p$Tourteau ) amPie(data = dat, depth = 30, legend = TRUE) }) ##----------PRODUCTION DE L'HUILE NEUTRE PAR QUART output$HnByQuart <- renderAmCharts({ datef_huilerie_p<-dataf_Huilerie_param()[complete.cases(dataf_Huilerie_param()),] datef_huilerie_p<-datef_huilerie_p %>% group_by(Quart) %>% summarize(HuileNProduitLT=sum(HuileNProduitLT)) dat <- data.frame( label = datef_huilerie_p$Quart, value = datef_huilerie_p$HuileNProduitLT ) amPie(data = dat, depth = 30, legend = TRUE) }) #---------------FIN Chargement des widgets HUILERIES----------------------- #---------------Chargement des widgets INFORMATIQUE----------------------- #---------Premiere ligne page Informatique : Ligne des Kpis------ #-- Kpi Nombre d'incident output$NombreIncident<-renderValueBox({ dataf_Incident<-dataf_Incident_param() NombreIncident_<-length(dataf_Incident$Tickets) valueBox(formatC(NombreIncident_, digits = 0, format ="f",big.mark=' ' ), 'Incident(s) declare(s)', color = "green") }) #-- Kpi Nombre de projets output$NombreProjet<-renderValueBox({ dataf_Projet<-dataf_Projet_param() #dataf_getProjet() dataf_Projet<- dataf_Projet %>% filter(Periode == input$Year & Month==input$Month) NombreProjet_<-length(dataf_Projet$Projet) valueBox(formatC(NombreProjet_, digits = 0, format ="f",big.mark=' ' ), 'Projets cree(s)', color = "green") }) #-- Kpi Quantite de consommables output$QuantiteConsommable<-renderValueBox({ dataf_Consommable<-dataf_Consommable_param() dataf_Consommable<- dataf_Consommable %>% filter(Periode == input$Year & Month==input$Month) QteConsommable_<-sum(dataf_Consommable$Nombre) valueBox(formatC(QteConsommable_, digits = 0, format ="f",big.mark=' ' ), 'Consommable(s) affecte(s)', color = "green") }) #-- Kpi TauxRespectDelaiProjet output$TauxRespectDelaiProjet<-renderValueBox({ dataf_Projet<-dataf_Projet_param() TauxRespectDelai_<-mean(dataf_Projet$RespectDelai) valueBox(formatC(TauxRespectDelai_, digits = 2, format ="f",big.mark=' ' ), 'Taux-respect-delai-projets(%)', color = "black") }) #-- Kpi TauxSatisfactionUtilisateur output$TauxSatisfactionUtilisateur<-renderValueBox({ dataf_Satisfaction<-dataf_Satisfaction_param() data_votant<-dataf_Satisfaction %>% filter(Votant != 0) #Calcul de la somme des notes NoteTotal <- sum(data_votant$Votant) #Calcul du taux de satisfaction TauxSatis <- ((NoteTotal) / sum(data_votant$Poids)) * 100 valueBox(formatC(TauxSatis, digits = 2, format ="f",big.mark=' ' ), 'Taux de satisfaction(%)', color = "black") }) #-- Kpi TauxParticipation output$TauxParticipation<-renderValueBox({ dataf_Satisfaction<-dataf_Satisfaction_param() data_votant<-dataf_Satisfaction %>% filter(Votant != 0) #Calcul du taux de participation TauxParticipation <- (length(data_votant$Votant) / length(dataf_Satisfaction$Votant)) * 100 valueBox(formatC(TauxParticipation, digits = 2, format ="f",big.mark=' ' ), 'Taux de participation(%)', color = "black") }) #-- Kpi TauxDisponibiliteService output$TauxDisponibiliteService<-renderValueBox({ valueBox(formatC(0, digits = 2, format ="f",big.mark=' ' ), 'Taux-Disponibilite-Services(%)', color = "red") }) #-- Kpi TauxDisponibiliteServeur output$TauxDisponibiliteServeur<-renderValueBox({ valueBox(formatC(0, digits = 2, format ="f",big.mark=' ' ), 'Taux-Disponibilite-Serveurs(%)', color = "red") }) #-- Kpi NombreChangement output$NombreChangement<-renderValueBox({ valueBox(formatC(0, digits = 0, format ="f",big.mark=' ' ), 'Nombre de changement', color = "red") }) #----EVOLUTION ANNUEL DES PROJETS------------- output$TabEvolutionProjet <- renderReactable({ dataf_Projet<-dataf_Evol_Projet_param() reactable(dataf_Projet, selection = "multiple", onClick = "select", sortable = TRUE, searchable = TRUE, defaultPageSize = 2, resizable = TRUE ) }) #----RAPPORT ANNUEL SUR LES AFECTATIONS DE CONSOMMABLE------------- output$TabRapportConsommable <- renderReactable({ dataf_Consommable_rapport<-dataf_dataConsommableRapport_param() reactable(dataf_Consommable_rapport, selection = "multiple", onClick = "select", sortable = TRUE, searchable = TRUE, defaultPageSize = 2, resizable = TRUE ) }) #----RAPPORT ANNUEL SUR LES INCIDENTS ------------- output$TabRapportIncident <- renderReactable({ dataf_Incident_rapport<-dataf_dataIncidentRapport_param() reactable(dataf_Incident_rapport, selection = "multiple", onClick = "select", sortable = TRUE, searchable = TRUE, defaultPageSize = 4, resizable = TRUE ,groupBy = "Categorie", columns = list( Site = colDef(aggregate = "frequency"), Direction = colDef(aggregate = "frequency"), Nombre = colDef(aggregate = "sum") ) ) }) #---INCIDENT ANNUEL PAR DIRECTION---------- output$INCIDENTSANNUELBYDIRECTION <- renderAmCharts({ dataf_dataIncident_By_Categories<-dataf_dataIncidentRapport_param()[complete.cases(dataf_dataIncidentRapport_param()),] dataf_dataIncident_By_Categories<-dataf_dataIncident_By_Categories %>% group_by(Direction) %>% summarize(Nombre=sum(Nombre)) dat <- data.frame( Name = dataf_dataIncident_By_Categories$Direction, Quantite = dataf_dataIncident_By_Categories$Nombre ) amBarplot(x = "Name", y = "Quantite", data = dat, depth = 20, labelRotation = -45, legend = TRUE) }) #---INCIDENT MENSUEL PAR DIRECTIONS---------- output$INCIDENTSMENSUELBYDIRECTION <- renderAmCharts({ dataf_dataIncident_By_Direction<-dataf_dataIncident_By_Direction()[complete.cases(dataf_dataIncident_By_Direction()),] dataf_dataIncident_By_Direction<-dataf_dataIncident_By_Direction %>% group_by(Name) %>% summarize(Nombre=sum(Nombre)) dat <- data.frame( Name = dataf_dataIncident_By_Direction$Name, Quantite = dataf_dataIncident_By_Direction$Nombre ) amBarplot(x = "Name", y = "Quantite", data = dat, depth = 20, labelRotation = -45, legend = TRUE) }) #---------------FIN Chargement des widgets INFORMATIQUE----------------------- #creating the valueBoxOutput content output$value1 <- renderValueBox({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] #dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur1 <- sum(dataf_productionUsine$PdsCgEgrene)/1000 value1G<<-Valeur1 valueBox(formatC(Valeur1,digits = 0,format ="f",big.mark=' ' ),'TonnageCgEgrene(t)',color = "green") }) output$value2 <- renderValueBox({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur2 <- sum(dataf_productionUsine$PdsFibreCourtes)/1000 valueBox(formatC(Valeur2,digits = 0,format ="f",big.mark=' ' ),'TonnageFibreCourte(t)',color = "green") }) output$value3 <- renderValueBox({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur3a <- sum(dataf_productionUsine$PdsCgEgrene) dataf_production<-dataf_production()[complete.cases(dataf_production()$PoidsNet),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur3b <- sum(dataf_production$PoidsNet) Valeur3=(Valeur3b/Valeur3a)*100 valueBox(formatC(Valeur3,digits = 2,format ="f",big.mark=' ' ),'Rendement fibre(%)',color = "black") }) #creating the valueBoxOutput content output$value4 <- renderValueBox({ dataf_production<-dataf_production()[complete.cases(dataf_production()$NbBalles),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur4 <- sum(dataf_production$NbBalles) valueBox(formatC(Valeur4,digits = 0,format ="f",big.mark=' ' ),'Nombre de Balls',color = "green") }) output$value5 <- renderValueBox({ dataf_production<-dataf_production()[complete.cases(dataf_production()$PoidsNet),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur5 <- sum(dataf_production$PoidsNet)/1000 valueBox(formatC(Valeur5,digits = 0,format ="f",big.mark=' ' ),'TonnageBalles Net (t)',color = "green") }) output$value6 <- renderValueBox({ dataf_production<-dataf_production()[complete.cases(dataf_production()$PoidsNet),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur6 <- sum(dataf_production$PoidsNet)/sum(dataf_production$NbBalles) valueBox(formatC(Valeur6,digits = 2,format ="f",big.mark=' ' ),'PoidsMoyen Balles (Kg)',color = "black") }) output$value7 <- renderValueBox({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur7 <- sum(dataf_productionUsine$PdsCgEgrene)/nrow(dataf_productionUsine)/1000 valueBox(formatC(Valeur7,digits = 0,format ="f",big.mark=' ' ),'Egrené moyen par jour(t)',color = "black") }) output$value8 <- renderValueBox({ dataf_production<-dataf_production()[complete.cases(dataf_production()$PoidsNet),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur8<- sum(dataf_production$KwhReseau)/(sum(dataf_production$PoidsNet)/1000) valueBox(formatC(Valeur8,digits = 0,format ="f",big.mark=' ' ),'Kwh Conso./t de fibre',color = "black") }) output$value9 <- renderValueBox({ dataf_production<-dataf_production() dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur9 <- sum(dataf_production$TempsEgreneuse1+dataf_production$TempsEgreneuse2+dataf_production$TempsEgreneuse3+dataf_production$TempsEgreneuse4) valueBox(formatC(Valeur9,digits = 0,format ="f",big.mark=' ' ),'Fonct.Egreneuse (H)',color = "black") }) output$value10 <- renderValueBox({ dataf_production<-dataf_production()[complete.cases(dataf_production()$NbEgreneuses),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) #Valeur10 <- sum(dataf_production$NbScies)/nrow(dataf_production) Valeur10 <- max(dataf_production$NbScies) valueBox(formatC(Valeur10,digits = 0,format ="f",big.mark=' ' ),'Nbre de scies',color = "purple") }) output$value11 <- renderValueBox({ #dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] #dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) #Valeur11a <- sum(dataf_productionUsine$PdsFibreCourtes) dataf_production<-dataf_production()[complete.cases(dataf_production()$NbEgreneuses),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur11a <- sum(dataf_production$PoidsNet) Valeur11b <- max(dataf_production$NbScies) Valeur11c <- sum(dataf_production$TempsEgreneuse1+dataf_production$TempsEgreneuse2+dataf_production$TempsEgreneuse3+dataf_production$TempsEgreneuse4) Valeur11 = Valeur11a/(Valeur11b*Valeur11c) valueBox(formatC(Valeur11,digits = 2,format ="f",big.mark=' ' ),'Vitesse egrenage (Ksh)',color = "black") }) output$value12 <- renderValueBox({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur12 <- nrow(dataf_productionUsine) valueBox(formatC(Valeur12,digits = 0,format ="f",big.mark=' ' ),'Nbre de Jours Egrenage',color = "green") }) output$TabBallesCompare = renderDT({ dataf_production<-dataf_production() dataf_production<-dataf_production()[complete.cases(dataf_production()$NbBalles),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine) dataf_production<-dataf_production%>% group_by(Equipe) %>% summarize( #NbBalles_Mois= sum((NbBalles[Month==VMonth])), PoidsMoy_Mois= sum((PoidsNet[Month==input$Month]))/sum((NbBalles[Month==input$Month])), #NbBalles_MoisPrec= sum((NbBalles[Month== VMonthPrec])), PoidsMoy_MoisPrec= sum((PoidsNet[Month==as.character(as.numeric(input$Month)-1)] ))/sum((NbBalles[Month==as.character(as.numeric(input$Month)-1)])) ) dataf_production$variation_PoidsMoy<-dataf_production$PoidsMoy_Mois-dataf_production$PoidsMoy_MoisPrec dataf_production$PoidsMoy_Mois<-formatC(dataf_production$PoidsMoy_Mois,digits = 1,format ="f",big.mark=',' ) dataf_production$PoidsMoy_MoisPrec<-formatC(dataf_production$PoidsMoy_MoisPrec,digits = 1,format ="f",big.mark=',' ) dataf_production$variation_PoidsMoy<-formatC(dataf_production$variation_PoidsMoy,digits = 1,format ="f",big.mark=',' ) datatable(dataf_production, rownames = FALSE) }) output$GNbBalles <- renderPlotly({ dataf_production<-dataf_production() dataf_production<-dataf_production()[complete.cases(dataf_production()$Ecart_Poids),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) if(nrow(dataf_production)>0){ p<-ggplot(dataf_production,aes(x=DateOpe))+ geom_line(aes(y=NbBalles,col="NbBalles"), alpha = 0.6, size = 0.9) + labs(x = "Date", y = "Nombre de Balles", title = "Evolution Journaliere Nombre de balles")+ scale_color_manual(values = c( 'NbBalles' = 'green' ) )+ labs(color = '')+ theme_minimal() ggplotly(p) } } ) output$GNbBallesQuart <- renderPlotly({ dataf_production<-dataf_production() dataf_production<-dataf_production()[complete.cases(dataf_production()$Ecart_Poids),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) if(nrow(dataf_production)>0){ p<-ggplot(dataf_production, aes(x = DateOpe, y = NbBalles)) + geom_line(aes(color = Quart, linetype = Quart), #alpha = 0.6, size = 0.5 ) + labs(x = "Date", y = "Nombre de Balles", title = "Nombre de balles par Quart")+ #scale_color_manual(values = c("darkred", "steelblue","blue"))+ labs(color = '')+ theme_minimal() ggplotly(p) } } ) output$GNbBallesEquipe <- renderPlotly({ dataf_production<-dataf_production() dataf_production<-dataf_production()[complete.cases(dataf_production()$Ecart_Poids),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) if(nrow(dataf_production)>0){ p<-ggplot(dataf_production, aes(x = DateOpe, y = NbBalles)) + geom_line(aes(color = Equipe, linetype = Equipe), #alpha = 0.6, size = 0.5 ) + labs(x = "Date", y = "Nombre de Balles", title = "Nombre de balles par Equipe")+ #scale_color_manual(values = c("darkred", "steelblue","blue"))+ labs(color = '')+ theme_minimal() ggplotly(p) } } ) output$GNbBallesEquipes <- renderPlotly({ dataf_production<-dataf_production() dataf_production<-dataf_production()[complete.cases(dataf_production()$Ecart_Poids),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) dataf_production<-dataf_production %>% group_by(Equipe,Quart) %>% summarize(TotalBalles=sum(NbBalles)) if(nrow(dataf_production)>0){ p<-ggplot(data=dataf_production, aes(x = Equipe, y = TotalBalles, fill = Quart)) + geom_bar(stat = "identity")+ labs(x = "Equipe", y = "Nombre de Balles", title = "Nombre de balles par Equipe et par Quart")+ theme_minimal() ggplotly(p) } } ) output$TabBalles = renderDT({ dataf_production<-dataf_production() dataf_production<-dataf_production()[complete.cases(dataf_production()$Ecart_Poids),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) dataf_production<-head(dataf_production[order(-dataf_production$NbBalles),],5) dataf_production<-dataf_production[,c("DateOpe","DayOfWeek","Equipe","Quart","NbBalles")] datatable(dataf_production, rownames = FALSE) }) output$TabRendement = renderDT({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] #dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) dataf_productionUsine<-dataf_productionUsine[,c("DateOpe","PdsCgEgrene","PdsFibreCourtes","PdsGraines")] dataf_productionUsine$DateOpe<-format(dataf_productionUsine$DateOpe,"%b %d %Y") dataf_productionUsine$PoidsNet<-0 dataf_production<-dataf_production()[complete.cases(dataf_production()$PoidsNet),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) #dataf_production<-dataf_production %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) dataf_production<-dataf_production[,c("DateOpe","PoidsNet")] dataf_production$DateOpe<-format(dataf_production$DateOpe,"%b %d %Y") dataf_production$PdsCgEgrene<-0 dataf_production$PdsFibreCourtes<-0 dataf_production$PdsGraines<-0 dataf_production<-rbind(dataf_production,dataf_productionUsine) dataf_production<-dataf_production %>% group_by(DateOpe) %>% summarize(PdsCgEgrene=sum(PdsCgEgrene),TonnageFibre=sum(PoidsNet),PdsGraines=sum(PdsGraines), PdsFibreCourtes=sum(PdsFibreCourtes), RendementFibre=100*sum(PoidsNet)/sum(PdsCgEgrene) ) #dataf_productionUsine$RendementFibre<-100*dataf_productionUsine$PdsFibreCourtes/dataf_productionUsine$PdsCgEgrene dataf_production$RendementFibre<-formatC(dataf_production$RendementFibre,digits = 2,format ="f",big.mark=',',width = 2) names(dataf_production)<-c("DateOpe","CgEgrene(kg)","NetFibre(Kg)","Graines(Kg)", "Dechet(kg)", "%Fibre") datatable(dataf_production, rownames = FALSE,selection = 'single', options=list( pageLength = 5, lengthMenu = c(5), autoWidth = FALSE )) }) output$GRendementFibre <- renderPlotly({ dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) dataf_productionUsine<-dataf_productionUsine %>% group_by(DateOpe) %>% summarize(PdsCgEgrene=sum(PdsCgEgrene),PoidsNet=sum(0) ) dataf_production<-dataf_production()[complete.cases(dataf_production()$PoidsNet),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) dataf_production<-dataf_production %>% group_by(DateOpe) %>% summarize(PdsCgEgrene=sum(0),PoidsNet=sum(PoidsNet) ) dataf_productionUsine<-rbind(dataf_productionUsine,dataf_production) dataf_productionUsine<-dataf_productionUsine %>% bind_rows(.id = "location") %>% group_by(DateOpe) %>% summarize(TonnageFibre=100*sum(PoidsNet)/sum(PdsCgEgrene) ) dataf_productionUsine['Objectif'] = 43 if(nrow(dataf_productionUsine)>0){ p<-ggplot(data=dataf_productionUsine) + geom_line(aes(x=DateOpe,y=TonnageFibre),color='red') + geom_line(aes(x=DateOpe,y=Objectif),color='blue') + ylab('Values')+xlab('date') #p<-ggplot(data=dataf_productionUsine, aes(x = DateOpe, y = TonnageFibre)) + # geom_line(size = 0.5 # ) + # labs(x = "DateProduction", # y = "Evolution Rendement fibre(%))", # title = "Rendement Fibre(%)")+ # theme_minimal() #ggplotly(p) } } ) #----------------- CLASSEMENT -------------------------------------------------------------- output$TabclassementJour = renderDT({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] dataf_classement$TonnageFibre <- dataf_classement$PoidsNet/1000 dataf_classement$NbBalles<-1 dataf_classement$TonFibre_HautGamme<- ifelse(dataf_classement$Qualite=="Haut de gamme",dataf_classement$PoidsNet/1000,0) dataf_classement$TonFibre_Reference<- ifelse(dataf_classement$Qualite=="Fibre de référence",dataf_classement$PoidsNet/1000,0) dataf_classement$TonFibre_MoyGamme<- ifelse(dataf_classement$Qualite=="Moyenne gamme",dataf_classement$PoidsNet/1000,0) dataf_classement$TonFibre_BasGamme<- ifelse(dataf_classement$Qualite=="Bas gamme",dataf_classement$PoidsNet/1000,0) dataf_classement$NbBalle_Avarie<- ifelse(!is.na(dataf_classement$IdAvaries),1,0) dataf_classement$Tonnage_Avarie<- ifelse(!is.na(dataf_classement$IdAvaries),dataf_classement$PoidsNet/1000,0) dataf_classement$DateOpe<-format(dataf_classement$DateOpe,"%b %d %Y") ' Valeur14 <- nrow(dataf_classement) dataf_productionUsine<-dataf_productionUsine()[complete.cases(dataf_productionUsine()$PdsCgEgrene),] #dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) dataf_productionUsine<-dataf_productionUsine %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) dataf_productionUsine<-dataf_productionUsine[,c("DateOpe","PdsCgEgrene","PdsFibreCourtes","PdsGraines")] dataf_productionUsine$DateOpe<-format(dataf_productionUsine$DateOpe,"%b %d %Y") dataf_productionUsine$PoidsNet<-0 dataf_production<-dataf_production()[complete.cases(dataf_production()$PoidsNet),] dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) #dataf_production<-dataf_production %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) dataf_production<-dataf_production[,c("DateOpe","PoidsNet")] dataf_production$DateOpe<-format(dataf_production$DateOpe,"%b %d %Y") dataf_production$PdsCgEgrene<-0 dataf_production$PdsFibreCourtes<-0 dataf_production$PdsGraines<-0 dataf_production<-rbind(dataf_production,dataf_productionUsine) ' dataf_classement<-dataf_classement %>% group_by(DateOpe) %>% summarize(TonnageFibre=sum(TonnageFibre), NbBalles=sum(NbBalles), TonFibre_HautGamme=sum(TonFibre_HautGamme), TonFibre_Reference=sum(TonFibre_Reference), TonFibre_MoyGamme=sum(TonFibre_MoyGamme), TonFibre_BasGamme=sum(TonFibre_BasGamme), NbBalle_Avarie=sum(NbBalle_Avarie), Tonnage_Avarie=sum(Tonnage_Avarie) ) dataf_classement$TonnageFibre<-formatC(dataf_classement$TonnageFibre,digits = 2,format ="f",big.mark=',',width = 2) dataf_classement$TonFibre_Reference<-formatC(dataf_classement$TonFibre_Reference,digits = 2,format ="f",big.mark=',',width = 2) dataf_classement$TonFibre_HautGamme<-formatC(dataf_classement$TonFibre_HautGamme,digits = 2,format ="f",big.mark=',',width = 2) dataf_classement$TonFibre_MoyGamme<-formatC(dataf_classement$TonFibre_MoyGamme,digits = 2,format ="f",big.mark=',',width = 2) dataf_classement$TonFibre_BasGamme<-formatC(dataf_classement$TonFibre_BasGamme,digits = 2,format ="f",big.mark=',',width = 2) dataf_classement$Tonnage_Avarie<-formatC(dataf_classement$Tonnage_Avarie,digits = 2,format ="f",big.mark=',',width = 2) #names(dataf_production)<-c("DateOpe","CgEgrene(kg)","NetFibre(Kg)","Graines(Kg)", "Dechet(kg)", "%Fibre") datatable(dataf_classement, rownames = FALSE,selection = 'single', options=list( pageLength = 5, lengthMenu = c(5), autoWidth = FALSE )) }) output$value13 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] Valeur13 <- sum(dataf_classement$PoidsNet)/1000 valueBox(formatC(Valeur13,digits = 0,format ="f",big.mark=' ' ),'TonnageFibre(t)',color = "green") }) output$value14 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] Valeur14 <- nrow(dataf_classement) valueBox(formatC(Valeur14,digits = 0,format ="f",big.mark=' ' ),'Nombre de balles',color = "green") }) output$value15 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] dataf_classement<-dataf_classement %>% filter(Qualite == 'Haut de gamme') Valeur15 <- sum(dataf_classement$PoidsNet)/1000 valueBox(formatC(Valeur15,digits = 0,format ="f",big.mark=' ' ),'Ton. fibre Haut gamme(t)',color = "green") }) output$value16 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] dataf_classement<-dataf_classement %>% filter(Qualite == 'Fibre de référence') Valeur16 <- sum(dataf_classement$PoidsNet)/1000 valueBox(formatC(Valeur16,digits = 0,format ="f",big.mark=' ' ),'Ton. fibre Référence(t)',color = "green") }) output$value17 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] dataf_classement<-dataf_classement %>% filter(Qualite == 'Moyenne gamme') Valeur17 <- sum(dataf_classement$PoidsNet)/1000 valueBox(formatC(Valeur17,digits = 0,format ="f",big.mark=' ' ),'Ton. Moyenne gamme(t)',color = "green") }) output$value18 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] dataf_classement<-dataf_classement %>% filter(Qualite == 'Bas gamme') Valeur18 <- sum(dataf_classement$PoidsNet)/1000 valueBox(formatC(Valeur18,digits = 0,format ="f",big.mark=' ' ),'Ton. Bas gamme(t)',color = "green") }) output$value19 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$IdAvaries),] Valeur19 <- sum(dataf_classement$PoidsNet)/1000 valueBox(formatC(Valeur19,digits = 0,format ="f",big.mark=' ' ),'Tonnage AVARIES(t)',color = "black") }) output$value20 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$IdAvaries),] Valeur20 <- nrow(dataf_classement) valueBox(formatC(Valeur20,digits = 0,format ="f",big.mark=' ' ),'Nombre de balles AVARIES',color = "black") }) output$value21 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$IdAvaries),] Valeur21a <- nrow(dataf_classement) dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] Valeur21b <- nrow(dataf_classement) Valeur21<-(Valeur21a/Valeur21b)*100 valueBox(formatC(Valeur21,digits = 3,format ="f",big.mark='.' ),'Taux de balles AVARIES(%)',color = "red") }) output$TabtauxFibre = renderDT({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] #dataf_classement<-dataf_classement %>% filter(Periode == input$Year & IdUsine==input$Usine & as.numeric(Month)==as.numeric(input$Month)) dataf_classement<-dataf_classement %>% group_by(Classe) %>% summarize(#TonBrut=sum(PoidsBrut)/1000, TonNet=sum(PoidsNet)/1000 ) VTotalFibre <-sum(dataf_classement$TonNet) dataf_classement$TauxFibre<-(dataf_classement$TonNet/VTotalFibre)*100 dataf_classement$TauxFibre <-formatC(dataf_classement$TauxFibre,digits = 3,format ="f",big.mark=' ' ) #dataf_classement$TonBrut <-formatC(dataf_classement$TonBrut,digits = 2,format ="f",big.mark=' ' ) dataf_classement$TonNet <-formatC(dataf_classement$TonNet,digits = 2,format ="f",big.mark=' ' ) names(dataf_classement)<-c("Classe","TonnageNet(t)","Taux(%)") datatable(dataf_classement, rownames = FALSE, options=list( pageLength = 5, lengthMenu = c(5), autoWidth = FALSE) ) }) output$LongueurSoie = renderDT({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] #dataf_classement<-dataf_classement %>% filter(Periode == input$Year & IdUsine==input$Usine & as.numeric(Month)==as.numeric(input$Month)) dataf_classement<-dataf_classement %>% group_by(Soie) %>% summarize(#TonBrut=sum(PoidsBrut)/1000, TonNet=sum(PoidsNet)/1000 ) VTotalFibre <-sum(dataf_classement$TonNet) #dataf_classement$Totol<- sum(dataf_classement$PoidsNet) dataf_classement$Taux<-(dataf_classement$TonNet/VTotalFibre)*100 dataf_classement$Taux <-formatC(dataf_classement$Taux,digits = 3,format ="f",big.mark=',' ) #dataf_classement$TonBrut <-formatC(dataf_classement$TonBrut,digits = 2,format ="f",big.mark=' ' ) dataf_classement$TonNet <-formatC(dataf_classement$TonNet,digits = 2,format ="f",big.mark=' ' ) names(dataf_classement)<-c("Soie","TonnageNet","Taux(%)") datatable(dataf_classement, rownames = FALSE) }) output$TabtauxFibreSoie = renderDT({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] #dataf_classement<-dataf_classement %>% filter(Periode == input$Year & IdUsine==input$Usine & as.numeric(Month)==as.numeric(input$Month)) dataf_classement<-dataf_classement %>% group_by(Variete) %>% summarize(TonBrut=sum(PoidsBrut)/1000,TonNet=sum(PoidsNet)/1000 ) VTotalFibre <-sum(dataf_classement$TonNet) dataf_classement$TauxFibre<-(dataf_classement$TonNet/VTotalFibre)*100 dataf_classement$TauxFibre <-formatC(dataf_classement$TauxFibre,digits = 3,format ="f",big.mark=' ' ) dataf_classement$TonBrut <-formatC(dataf_classement$TonBrut,digits = 2,format ="f",big.mark=' ' ) dataf_classement$TonNet <-formatC(dataf_classement$TonNet,digits = 2,format ="f",big.mark=' ' ) datatable(dataf_classement, rownames = FALSE) }) output$GTauxFibreCategorie <- renderPlotly({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] #dataf_classement<-dataf_classement %>% filter(Periode == input$Year & IdUsine==input$Usine & as.numeric(Month)==as.numeric(input$Month)) dataf_classement<-dataf_classement %>% group_by(Classe) %>% summarize(TonBrut=sum(PoidsBrut)/1000,TonNet=sum(PoidsNet)/1000 ) VTotalFibre <-sum(dataf_classement$TonNet) dataf_classement$TauxFibre<-(dataf_classement$TonNet/VTotalFibre)*100 dataf_classement<-arrange(dataf_classement,-TauxFibre) dataf_classement = dataf_classement %>% mutate_if(is.factor, fct_explicit_na, na_level = "NA") dataf_classement$Classe <- with(dataf_classement, reorder(Classe, -TauxFibre)) p<- ggplot(data=dataf_classement, aes(x = reorder(Classe, TauxFibre), y = TauxFibre, fill = Classe)) + geom_bar(stat = "identity")+ coord_flip()+ labs(x = "Classe", y = "Taux(%)" )+ theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) #theme_minimal() ggplotly(p) } ) output$GTauxFibreCategorie2 <- renderPlotly({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] dataf_classement<-dataf_classement %>% group_by(DateOpe,Qualite) %>% summarize(TonNet=sum(PoidsNet)/1000 ) #VTotalFibre <-sum(dataf_classement$TonNet) #dataf_classement$TauxFibre<-dataf_classement$TonNet/VTotalFibre if(nrow(dataf_classement)>0){ p<-ggplot(data=dataf_classement) + geom_line(aes(x=DateOpe,y=TonNet,color=Qualite)) + #geom_line(aes(x=DateOpe,y=Objectif),color='blue') + ylab('Tonnage(t)')+xlab('date') } ggplotly(p) } ) output$TabtauxFibreVariete = renderDT({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] #dataf_classement<-dataf_classement %>% filter(Periode == input$Year & IdUsine==input$Usine & as.numeric(Month)==as.numeric(input$Month)) dataf_classement<-dataf_classement %>% group_by(Variete) %>% summarize(#TonBrut=sum(PoidsBrut)/1000, TonNet=sum(PoidsNet)/1000 ) VTotalFibre <-sum(dataf_classement$TonNet) dataf_classement$TauxFibre<-(dataf_classement$TonNet/VTotalFibre)*100 dataf_classement$TauxFibre <-formatC(dataf_classement$TauxFibre,digits = 3,format ="f",big.mark=' ' ) #dataf_classement$TonBrut <-formatC(dataf_classement$TonBrut,digits = 2,format ="f",big.mark=' ' ) dataf_classement$TonNet <-formatC(dataf_classement$TonNet,digits = 2,format ="f",big.mark=' ' ) names(dataf_classement)<-c("Variete","TonnageNet","Taux(%)") datatable(dataf_classement, rownames = FALSE) }) output$GTauxFibreSoie <- renderPlotly({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] #dataf_classement<-dataf_classement %>% filter(Periode == input$Year & IdUsine==input$Usine & as.numeric(Month)==as.numeric(input$Month)) dataf_classement<-dataf_classement %>% group_by(Soie) %>% summarize(TonBrut=sum(PoidsBrut)/1000,TonNet=sum(PoidsNet)/1000 ) VTotalFibre <-sum(dataf_classement$TonNet) dataf_classement$TauxFibre<-(dataf_classement$TonNet/VTotalFibre)*100 ggplot(dataf_classement, aes(x = 3, y = TauxFibre, fill = Soie)) + geom_bar(stat = "identity", color = "white") + #labs(title = "Ventes par Type de Client")+ #coord_polar(theta = "y", start = 0)+ geom_text(aes(y = TauxFibre, label = paste0(TauxFibre, " (", scales::percent(TauxFibre / sum(TauxFibre)), ")")), color = "black", #position = position_dodge(width = 1), #vjust = -2, #size = 5 )+ #scale_fill_manual(values = mycols) + theme_void()+ theme( plot.title = element_text(color="black", size=16, face="bold.italic"))#+ #xlim(0.5, 2.5) } ) #----------------- MAINTENANCE -------------------------------------------------------------- output$value71 <- renderValueBox({ dataf_Panne<-dataf_Panne() Valeur71 <- sum(dataf_Panne$NbPanne) valueBox(formatC(Valeur71,digits = 0,format ="f",big.mark=' ' ),'Nbre de pannes du Mois',color = "black") }) output$value72 <- renderValueBox({ dataf_Panne<-dataf_Panne() Valeur72 <- sum(dataf_Panne$DureePanne)/60 valueBox(formatC(Valeur72,digits = 0,format ="f",big.mark=' ' ),'Duree de pannes du Mois (Heures) ',color = "yellow") }) output$value73 <- renderValueBox({ dataf_PanneCumul<-dataf_PanneCumul() Valeur73 <- sum(dataf_PanneCumul$NbPanne) valueBox(formatC(Valeur73,digits = 0,format ="f",big.mark=' ' ),'Cumul annuel Nbre de pannes',color = "black") }) output$value74 <- renderValueBox({ dataf_PanneCumul<-dataf_PanneCumul() Valeur74 <- sum(dataf_PanneCumul$DureePanne)/60 valueBox(formatC(Valeur74,digits = 0,format ="f",big.mark=' ' ),'Cumul annuel Duree pannes (Heures) ',color = "yellow") }) output$value100 <- renderValueBox({ dataf_production<-dataf_production() dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine & Month==input$Month) Valeur100 <- sum(dataf_production$TempsCondenseur) valueBox(formatC(Valeur100,digits = 2,format ="f",big.mark=' ' ),'TempsCondenseur Mois (H)',color = "black") }) output$value101 <- renderValueBox({ dataf_Panne<-dataf_Panne() Valeur101 <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 valueBox(formatC(Valeur101,digits = 2,format ="f",big.mark=' ' ),'Heure Cadence Mois (H)',color = "yellow") }) output$value102 <- renderValueBox({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur102a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur102b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur102c<-Valeur102a-Valeur102b #temps de fonctionnement Valeur102d <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 #Heure cadence Valeur102<-Valeur102c-Valeur102d #Temps Net valueBox(formatC(Valeur102,digits = 2,format ="f",big.mark=' ' ),'Temps Net Mois (H)',color = "green") }) output$TabTempsNetEvolution = renderDT({ dataf_production<-dataf_production() dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine #& Month<=input$Month ) dataf_production<-dataf_production %>% group_by(MonthName,Month) %>% summarize(Temps=sum(TempsCondenseur) ) dataf_PanneCumul<-dataf_PanneCumul() dataf_PanneCumul<-dataf_PanneCumul[dataf_PanneCumul$clasification_machi=="cadence",] dataf_PanneCumul<-dataf_PanneCumul %>% group_by(MonthName,Month) %>% summarize(Temps=-sum(DureePanne)/60 ) dataf_production<-rbind(dataf_production,dataf_PanneCumul) dataf_production<-dataf_production %>% group_by(MonthName,Month) %>% summarize(TempsNet=sum(Temps) ) names(dataf_production)<-c("Mois","Month","TempsNet") dataf_production <- dataf_production[order(dataf_production$Month),c("Mois","TempsNet")] dataf_production$TempsNet<- formatC(dataf_production$TempsNet,digits = 2,format ="f",big.mark=' ' ) names(dataf_production)<-c("Mois","TempsNet(H)") datatable(dataf_production, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$GEvolutionTempsNetParMois <- renderPlotly({ dataf_production<-dataf_production() dataf_production<-dataf_production %>% filter(Periode == input$Year & IdUsine==input$Usine #& Month<=input$Month ) dataf_production<-dataf_production %>% group_by(MonthName,Month) %>% summarize(Temps=sum(TempsCondenseur) ) dataf_PanneCumul<-dataf_PanneCumul() dataf_PanneCumul<-dataf_PanneCumul[dataf_PanneCumul$clasification_machi=="cadence",] dataf_PanneCumul<-dataf_PanneCumul %>% group_by(MonthName,Month) %>% summarize(Temps=-sum(DureePanne)/60 ) dataf_production<-rbind(dataf_production,dataf_PanneCumul) dataf_production<-dataf_production %>% group_by(MonthName,Month) %>% summarize(TempsNet=sum(Temps) ) names(dataf_production)<-c("Mois","Month","TempsNet") #dataf_production <- dataf_production[order(dataf_production$Month),c("Mois","TempsNet")] #dataf_production$TempsNet<- formatC(dataf_production$TempsNet,digits = 2,format ="f",big.mark=' ' ) #names(dataf_production)<-c("Mois","TempsNet(H)") #p<-ggplot(data=dataf_production, aes(x = Equipe, y = TotalBalles, fill = Quart)) + # geom_bar(stat = "identity")+ # labs(x = "Equipe", # y = "Nombre de Balles", # title = "Nombre de balles par Equipe et par Quart")+ # theme_minimal() #ggplotly(p) p<- ggplot(data=dataf_production, aes(x = reorder(Mois, Month), y = TempsNet, fill = Mois)) + geom_bar(stat = "identity")+ #coord_flip()+ labs(x = "Mois", y = "TempsNet" )#+ #theme(axis.title.y=element_blank(), # axis.text.y=element_blank(), # axis.ticks.y=element_blank()) #theme_minimal() ggplotly(p) } ) output$value103 <- renderValueBox({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) value103<-100*(days_in_month(Vdate)*24-(sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60))/(days_in_month(Vdate)*24) valueBox(formatC(value103,digits = 2,format ="f",big.mark=' ' ),'Taux rendement Economique(%)',color = "blue") }) output$value104 <- renderValueBox({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur104a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur104b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur104c<-Valeur104a-Valeur104b #temps de fonctionnement Valeur104<-(Valeur104c/Valeur104a)*100 #Taux de disponibilite operationnelle valueBox(formatC(Valeur104,digits = 2,format ="f",big.mark=' ' ),'Taux de dispo Operationnelle(%)',color = "blue") }) output$value105 <- renderValueBox({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur105a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur105b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur105c<-Valeur105a-Valeur105b #temps de fonctionnement Valeur105d <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 #Heure cadence Valeur105e<-Valeur105c-Valeur105d #Temps Net value105<- (Valeur105e/Valeur105c)*100 valueBox(formatC(value105,digits = 2,format ="f",big.mark=' ' ),'Taux de performance(%)',color = "blue") }) output$value106 <- renderValueBox({ dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] Valeur106a <- sum(dataf_classement$PoidsNet)/1000 # tonnage fibre dataf_classement<-dataf_classement %>% filter(Qualite == 'Haut de gamme') Valeur106b <- sum(dataf_classement$PoidsNet)/1000 # Tonnage fibre haut de gamme Valeur106<- (Valeur106b/Valeur106a)*100 valueBox(formatC(Valeur106,digits = 2,format ="f",big.mark=' ' ),'Taux de Qualité (%)',color = "blue") }) output$value107 <- renderValueBox({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur104a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur104b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur104c<-Valeur104a-Valeur104b #temps de fonctionnement Valeur104<-(Valeur104c/Valeur104a) #Taux de disponibilite operationnelle Valeur105a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur105b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur105c<-Valeur105a-Valeur105b #temps de fonctionnement Valeur105d <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 #Heure cadence Valeur105e<-Valeur105c-Valeur105d #Temps Net valeur105<- (Valeur105e/Valeur105c) #Taux de Performance dataf_classement<-dataf_classement() dataf_classement<-dataf_classement()[complete.cases(dataf_classement()$PoidsNet),] Valeur106a <- sum(dataf_classement$PoidsNet)/1000 # tonnage fibre dataf_classement<-dataf_classement %>% filter(Qualite == 'Haut de gamme') Valeur106b <- sum(dataf_classement$PoidsNet)/1000 # Tonnage fibre haut de gamme Valeur106<- (Valeur106b/Valeur106a) #TAux de Qualite Valeur107<-Valeur104*valeur105*Valeur106 *100 valueBox(formatC(Valeur107,digits = 2,format ="f",big.mark=' ' ),'taux rendement synthetique (%)',color = "blue") }) output$TabTemps = renderDT({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur102a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur102b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur102b1 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene"),]$DureePanne)/60 #heure Exogene Valeur102b2 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("machine"),]$DureePanne)/60 #heure Machine Valeur102b3 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("fabrication"),]$DureePanne)/60 #heure Fabrication Valeur102c<-Valeur102a-Valeur102b #temps de fonctionnement Valeur102d <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 #Heure cadence Valeur102<-Valeur102c-Valeur102d #Temps Net Valeur102e<-days_in_month(Vdate)*24#Temps Total Valeur102f <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("maintenance"),]$DureePanne)/60 #heure Maintenance Valeur102g <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("chomer"),]$DureePanne)/60 #heure Chomer Valeur102h<-Valeur102e-Valeur102g #Temps Ouverture TempsOuverture<-data.frame("Temps Ouverture",Valeur102h) names(TempsOuverture)<-c("Rubrique","Temps(H)") TempsChomer<-data.frame("Temps Chomé",Valeur102g) names(TempsChomer)<-c("Rubrique","Temps(H)") TempsMaintenance<-data.frame("Temps Maintenance",Valeur102f) names(TempsMaintenance)<-c("Rubrique","Temps(H)") TempsTotal<-data.frame("Temps Total",Valeur102e) names(TempsTotal)<-c("Rubrique","Temps(H)") TempsCadence<-data.frame("Temps Cadences",Valeur102d) names(TempsCadence)<-c("Rubrique","Temps(H)") TempsRequis<-data.frame("Temps Requis",Valeur102a) names(TempsRequis)<-c("Rubrique","Temps(H)") TempsExogen<-data.frame("Temps Exogene",Valeur102b1) names(TempsExogen)<-c("Rubrique","Temps(H)") TempsMachine<-data.frame("Temps Machine",Valeur102b2) names(TempsMachine)<-c("Rubrique","Temps(H)") TempsFabrication<-data.frame("Temps Fabrication",Valeur102b3) names(TempsFabrication)<-c("Rubrique","Temps(H)") TempsFonctionnement<-data.frame("Temps Fonctionnement",Valeur102c) names(TempsFonctionnement)<-c("Rubrique","Temps(H)") TempsNet<-data.frame("Temps Net",Valeur102) names(TempsNet)<-c("Rubrique","Temps(H)") dataf_Temps<-rbind(TempsChomer,TempsFabrication,TempsCadence,TempsMaintenance,TempsExogen,TempsMachine, TempsTotal,TempsOuverture,TempsRequis,TempsFonctionnement,TempsNet ) dataf_Temps$"Temps(H)"<-formatC(dataf_Temps$"Temps(H)",digits = 2,format ="f",big.mark=' ' ) datatable(dataf_Temps, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 11, lengthMenu = c(11), autoWidth = FALSE )) }) output$TabTemps2 = renderDT({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur102a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur102b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur102b1 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene"),]$DureePanne)/60 #heure Exogene Valeur102b2 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("machine"),]$DureePanne)/60 #heure Machine Valeur102b3 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("fabrication"),]$DureePanne)/60 #heure Fabrication Valeur102c<-Valeur102a-Valeur102b #temps de fonctionnement Valeur102d <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 #Heure cadence Valeur102<-Valeur102c-Valeur102d #Temps Net Valeur102e<-days_in_month(Vdate)*24#Temps Total Valeur102f <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("maintenance"),]$DureePanne)/60 #heure Maintenance Valeur102g <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("chomer"),]$DureePanne)/60 #heure Chomer Valeur102h<-Valeur102e-Valeur102g #Temps Ouverture TempsOuverture<-data.frame("Temps Ouverture",Valeur102h) names(TempsOuverture)<-c("Rubrique","Temps(H)") TempsChomer<-data.frame("Temps Chomé",Valeur102g) names(TempsChomer)<-c("Rubrique","Temps(H)") TempsMaintenance<-data.frame("Temps Maintenance",Valeur102f) names(TempsMaintenance)<-c("Rubrique","Temps(H)") TempsTotal<-data.frame("Temps Total",Valeur102e) names(TempsTotal)<-c("Rubrique","Temps(H)") TempsCadence<-data.frame("Temps Cadences",Valeur102d) names(TempsCadence)<-c("Rubrique","Temps(H)") TempsRequis<-data.frame("Temps Requis",Valeur102a) names(TempsRequis)<-c("Rubrique","Temps(H)") TempsExogen<-data.frame("Temps Exogene",Valeur102b1) names(TempsExogen)<-c("Rubrique","Temps(H)") TempsMachine<-data.frame("Temps Machine",Valeur102b2) names(TempsMachine)<-c("Rubrique","Temps(H)") TempsFabrication<-data.frame("Temps Fabrication",Valeur102b3) names(TempsFabrication)<-c("Rubrique","Temps(H)") TempsFonctionnement<-data.frame("Temps Fonctionnement",Valeur102c) names(TempsFonctionnement)<-c("Rubrique","Temps(H)") TempsNet<-data.frame("Temps Net",Valeur102) names(TempsNet)<-c("Rubrique","Temps(H)") dataf_Temps<-rbind(TempsChomer,TempsFabrication,TempsCadence,TempsMaintenance ) dataf_Temps$"Temps(H)"<-formatC(dataf_Temps$"Temps(H)",digits = 2,format ="f",big.mark=' ' ) datatable(dataf_Temps, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 11, lengthMenu = c(11), autoWidth = FALSE )) }) output$TabTemps3 = renderDT({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur102a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur102b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur102b1 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene"),]$DureePanne)/60 #heure Exogene Valeur102b2 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("machine"),]$DureePanne)/60 #heure Machine Valeur102b3 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("fabrication"),]$DureePanne)/60 #heure Fabrication Valeur102c<-Valeur102a-Valeur102b #temps de fonctionnement Valeur102d <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 #Heure cadence Valeur102<-Valeur102c-Valeur102d #Temps Net Valeur102e<-days_in_month(Vdate)*24#Temps Total Valeur102f <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("maintenance"),]$DureePanne)/60 #heure Maintenance Valeur102g <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("chomer"),]$DureePanne)/60 #heure Chomer Valeur102h<-Valeur102e-Valeur102g #Temps Ouverture TempsOuverture<-data.frame("Temps Ouverture",Valeur102h) names(TempsOuverture)<-c("Rubrique","Temps(H)") TempsChomer<-data.frame("Temps Chomé",Valeur102g) names(TempsChomer)<-c("Rubrique","Temps(H)") TempsMaintenance<-data.frame("Temps Maintenance",Valeur102f) names(TempsMaintenance)<-c("Rubrique","Temps(H)") TempsTotal<-data.frame("Temps Total",Valeur102e) names(TempsTotal)<-c("Rubrique","Temps(H)") TempsCadence<-data.frame("Temps Cadences",Valeur102d) names(TempsCadence)<-c("Rubrique","Temps(H)") TempsRequis<-data.frame("Temps Requis",Valeur102a) names(TempsRequis)<-c("Rubrique","Temps(H)") TempsExogen<-data.frame("Temps Exogene",Valeur102b1) names(TempsExogen)<-c("Rubrique","Temps(H)") TempsMachine<-data.frame("Temps Machine",Valeur102b2) names(TempsMachine)<-c("Rubrique","Temps(H)") TempsFabrication<-data.frame("Temps Fabrication",Valeur102b3) names(TempsFabrication)<-c("Rubrique","Temps(H)") TempsFonctionnement<-data.frame("Temps Fonctionnement",Valeur102c) names(TempsFonctionnement)<-c("Rubrique","Temps(H)") TempsNet<-data.frame("Temps Net",Valeur102) names(TempsNet)<-c("Rubrique","Temps(H)") dataf_Temps<-rbind(TempsExogen,TempsMachine, TempsTotal,TempsOuverture ) dataf_Temps$"Temps(H)"<-formatC(dataf_Temps$"Temps(H)",digits = 2,format ="f",big.mark=' ' ) datatable(dataf_Temps, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 11, lengthMenu = c(11), autoWidth = FALSE )) }) output$TabTemps4 = renderDT({ dataf_Panne<-dataf_Panne() Vdate<-as.Date(paste(VYear,'/',VMonth,'/','01',sep = "")) Valeur102a<-days_in_month(Vdate)*24-sum(dataf_Panne[dataf_Panne$clasification_machi=="chomer",]$DureePanne)/60-sum(dataf_Panne[dataf_Panne$clasification_machi=="maintenance",]$DureePanne)/60 #Temps requis Valeur102b <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene","machine","fabrication"),]$DureePanne)/60 #heure Exogene, Machine et Fabrication Valeur102b1 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("exogene"),]$DureePanne)/60 #heure Exogene Valeur102b2 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("machine"),]$DureePanne)/60 #heure Machine Valeur102b3 <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("fabrication"),]$DureePanne)/60 #heure Fabrication Valeur102c<-Valeur102a-Valeur102b #temps de fonctionnement Valeur102d <- sum(dataf_Panne[dataf_Panne$clasification_machi=="cadence",]$DureePanne)/60 #Heure cadence Valeur102<-Valeur102c-Valeur102d #Temps Net Valeur102e<-days_in_month(Vdate)*24#Temps Total Valeur102f <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("maintenance"),]$DureePanne)/60 #heure Maintenance Valeur102g <- sum(dataf_Panne[dataf_Panne$clasification_mach %in% c("chomer"),]$DureePanne)/60 #heure Chomer Valeur102h<-Valeur102e-Valeur102g #Temps Ouverture TempsOuverture<-data.frame("Temps Ouverture",Valeur102h) names(TempsOuverture)<-c("Rubrique","Temps(H)") TempsChomer<-data.frame("Temps Chomé",Valeur102g) names(TempsChomer)<-c("Rubrique","Temps(H)") TempsMaintenance<-data.frame("Temps Maintenance",Valeur102f) names(TempsMaintenance)<-c("Rubrique","Temps(H)") TempsTotal<-data.frame("Temps Total",Valeur102e) names(TempsTotal)<-c("Rubrique","Temps(H)") TempsCadence<-data.frame("Temps Cadences",Valeur102d) names(TempsCadence)<-c("Rubrique","Temps(H)") TempsRequis<-data.frame("Temps Requis",Valeur102a) names(TempsRequis)<-c("Rubrique","Temps(H)") TempsExogen<-data.frame("Temps Exogene",Valeur102b1) names(TempsExogen)<-c("Rubrique","Temps(H)") TempsMachine<-data.frame("Temps Machine",Valeur102b2) names(TempsMachine)<-c("Rubrique","Temps(H)") TempsFabrication<-data.frame("Temps Fabrication",Valeur102b3) names(TempsFabrication)<-c("Rubrique","Temps(H)") TempsFonctionnement<-data.frame("Temps Fonctionnement",Valeur102c) names(TempsFonctionnement)<-c("Rubrique","Temps(H)") TempsNet<-data.frame("Temps Net",Valeur102) names(TempsNet)<-c("Rubrique","Temps(H)") dataf_Temps<-rbind(TempsExogen,TempsMachine, TempsTotal,TempsOuverture ) dataf_Temps<-rbind(TempsOuverture,TempsRequis,TempsFonctionnement,TempsNet ) dataf_Temps$"Temps(H)"<-formatC(dataf_Temps$"Temps(H)",digits = 2,format ="f",big.mark=' ' ) datatable(dataf_Temps, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 11, lengthMenu = c(11), autoWidth = FALSE )) }) output$GPanneParType <- renderPlotly({ dataf_PanneCumul<-dataf_PanneCumul() dataf_PanneCumul<-dataf_PanneCumul()[complete.cases(dataf_PanneCumul()$NbPanne),] dataf_PanneCumul<-dataf_PanneCumul %>% group_by(TypePanne) %>% summarize(NbPanne=sum(NbPanne) ) dataf_PanneCumul<-arrange(dataf_PanneCumul,-NbPanne) dataf_PanneCumul = dataf_PanneCumul %>% mutate_if(is.factor, fct_explicit_na, na_level = "NA") dataf_PanneCumul$TypePanne <- with(dataf_PanneCumul, reorder(TypePanne, -NbPanne)) p<- ggplot(data=dataf_PanneCumul, aes(x = reorder(TypePanne, NbPanne), y = NbPanne, fill = TypePanne)) + geom_bar(stat = "identity")+ coord_flip()+ labs(x = "TypePanne", y = "Nbre de Pannes" )+ theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) #theme_minimal() ggplotly(p) } ) output$GEvolutionPannesParMois <- renderPlotly({ dataf_PanneCumul<-dataf_PanneCumul() dataf_PanneCumul<-dataf_PanneCumul %>% group_by(DateOpe) %>% summarize(NbPanne=sum(NbPanne) ) if(nrow(dataf_PanneCumul)>0){ p<-ggplot(data=dataf_PanneCumul,aes(x = DateOpe)) + geom_line(aes(y=NbPanne)) + ylab('Nbre de Pannes')+xlab('Date') } } ) output$MatricePanne <- renderPivottabler({ dataf_PanneCumul<-dataf_PanneCumul() dataf_PanneCumul$Libelle<-"Mois" dataf_PanneCumul<-dataf_PanneCumul[,c("Month","MonthName","TypePanne","NbPanne","Libelle")] dataf_PanneCumul <- dataf_PanneCumul[order(dataf_PanneCumul$Month),c("Month","MonthName","TypePanne","NbPanne","Libelle")] pt <- PivotTable$new() pt$addData(dataf_PanneCumul) pt$addColumnDataGroups("Libelle",addTotal=TRUE) pt$addColumnDataGroups("Month",addTotal=FALSE) pt$addColumnDataGroups("MonthName",addTotal=FALSE) pt$addRowDataGroups("TypePanne",outlineTotal=list(groupStyleDeclarations=list(color="blue"))) pt$defineCalculation(calculationName="NbPanne", summariseExpression="sum(NbPanne)") pt$renderPivot() pivottabler(pt) } ) output$MatricePanneClassif <- renderPivottabler({ dataf_PanneCumul<-dataf_PanneCumul12Mois() dataf_PanneCumul$Libelle<-"Mois" dataf_PanneCumul<-dataf_PanneCumul[,c("Month","MonthName","clasification_machi","NbPanne","Libelle")] dataf_PanneCumul <- dataf_PanneCumul[order(dataf_PanneCumul$Month),c("Month","MonthName","clasification_machi","NbPanne","Libelle")] pt <- PivotTable$new() pt$addData(dataf_PanneCumul) pt$addColumnDataGroups("Libelle",addTotal=TRUE) pt$addColumnDataGroups("Month",addTotal=FALSE) pt$addColumnDataGroups("MonthName",addTotal=FALSE) pt$addRowDataGroups("clasification_machi",outlineTotal=list(groupStyleDeclarations=list(color="blue"))) pt$defineCalculation(calculationName="NbPanne", summariseExpression="sum(NbPanne)") pt$renderPivot() pivottabler(pt) } ) output$MatriceDureePanne <- renderPivottabler({ dataf_PanneCumul<-dataf_PanneCumul() dataf_PanneCumul$Libelle<-"Mois" dataf_PanneCumul<-dataf_PanneCumul[,c("Month","MonthName","TypePanne","DureePanne","Libelle")] dataf_PanneCumul <- dataf_PanneCumul[order(dataf_PanneCumul$Month),c("Month","MonthName","TypePanne","DureePanne","Libelle")] pt <- PivotTable$new() pt$addData(dataf_PanneCumul) pt$addColumnDataGroups("Libelle",addTotal=TRUE) pt$addColumnDataGroups("Month",addTotal=FALSE) pt$addColumnDataGroups("MonthName",addTotal=FALSE) pt$addRowDataGroups("TypePanne",outlineTotal=list(groupStyleDeclarations=list(color="blue"))) pt$defineCalculation(calculationName="DureePanne", summariseExpression="round(sum(DureePanne)/60,digits=1)") pt$renderPivot() pivottabler(pt) } ) #----------------- RESSOURCES HUMAINES -------------------------------------------------------------- output$value22 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() Valeur22 <- sum(dataf_Effectif$NbEffectif) valueBox(formatC(Valeur22,digits = 0,format ="f",big.mark=' ' ),'Effectif du Mois',color = "black") }) output$value23 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() dataf_Effectif<-dataf_Effectif %>% filter(SEXE == 'M') Valeur23 <- sum(dataf_Effectif$NbEffectif) valueBox(formatC(Valeur23,digits = 0,format ="f",big.mark=' ' ),'HOMMES',color = "blue") }) output$value24 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() dataf_Effectif<-dataf_Effectif %>% filter(SEXE != 'M') Valeur24 <- sum(dataf_Effectif$NbEffectif) valueBox(formatC(Valeur24,digits = 0,format ="f",big.mark=' ' ),'FEMMES',color = "black") }) output$value25 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() Valeur25a <- sum(dataf_Effectif$NbEffectif) dataf_Effectif<-dataf_Effectif %>% filter(SEXE != 'M') Valeur25b <- sum(dataf_Effectif$NbEffectif) valeur25<-(Valeur25b/Valeur25a)*100 valueBox(formatC(valeur25,digits = 2,format ="f",big.mark=' ' ),'%FEMMES',color = "orange") }) output$value26 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbEffectif=sum(NbEffectif) ) Valeur26 <- mean(dataf_EffectifCumul$NbEffectif) valueBox(formatC(Valeur26,digits = 0,format ="f",big.mark=' ' ),'CumulAn Moy. Effectif',color = "black") }) output$value27 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% filter(SEXE == 'M') dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbEffectif=sum(NbEffectif) ) Valeur27 <- mean(dataf_EffectifCumul$NbEffectif) valueBox(formatC(Valeur27,digits = 0,format ="f",big.mark=' ' ),'Cumul An - HOMMES',color = "blue") }) output$value28 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% filter(SEXE != 'M') dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbEffectif=sum(NbEffectif) ) Valeur28 <- mean(dataf_EffectifCumul$NbEffectif) valueBox(formatC(Valeur28,digits = 0,format ="f",big.mark=' ' ),'Cumul An - FEMMES',color = "black") }) output$value29 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumulTotal<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbEffectif=sum(NbEffectif) ) Valeur29b <- mean(dataf_EffectifCumulTotal$NbEffectif) dataf_EffectifCumulFemme<-dataf_EffectifCumul %>% filter(SEXE != 'M') dataf_EffectifCumulFemme<-dataf_EffectifCumulFemme %>% group_by(MonthName) %>% summarize(NbEffectif=sum(NbEffectif) ) Valeur29a <- mean(dataf_EffectifCumulFemme$NbEffectif) valeur29<-(Valeur29a/Valeur29b)*100 valueBox(formatC(valeur29,digits = 2,format ="f",big.mark=' ' ),'% Cumul An. FEMMES.',color = "orange") }) output$value30 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() Valeur30 <- sum(dataf_Effectif$NbPermanent) valueBox(formatC(Valeur30,digits = 0,format ="f",big.mark=' ' ),'Permanents du Mois',color = "blue") }) output$value31 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() Valeur31 <- sum(dataf_Effectif$NbSaisonnier) valueBox(formatC(Valeur31,digits = 0,format ="f",big.mark=' ' ),'Saisonniers du Mois',color = "red") }) output$value32 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() Valeur32 <- sum(dataf_Effectif$NbTemporaire) valueBox(formatC(Valeur32,digits = 0,format ="f",big.mark=' ' ),'Temporaires du Mois',color = "yellow") }) output$value33 <- renderValueBox({ dataf_Effectif<-dataf_Effectif() Valeur33 <- sum(dataf_Effectif$NbGardien) valueBox(formatC(Valeur33,digits = 0,format ="f",big.mark=' ' ),'Gardiens du Mois',color = "green") }) output$value34 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbPermanent=sum(NbPermanent) ) Valeur34 <- mean(dataf_EffectifCumul$NbPermanent) valueBox(formatC(Valeur34,digits = 0,format ="f",big.mark=' ' ),'CumulAn Moy. Permanents ',color = "blue") }) output$value35 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbSaisonnier=sum(NbSaisonnier) ) Valeur35 <- mean(dataf_EffectifCumul$NbSaisonnier) valueBox(formatC(Valeur35,digits = 0,format ="f",big.mark=' ' ),'CumulAn Moy.',color = "red") }) output$value36 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbTemporaire=sum(NbTemporaire) ) Valeur36 <- mean(dataf_EffectifCumul$NbTemporaire) valueBox(formatC(Valeur36,digits = 0,format ="f",big.mark=' ' ),'CumulAn Moy.',color = "yellow") }) output$value37 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName) %>% summarize(NbGardien=sum(NbGardien) ) Valeur37 <- mean(dataf_EffectifCumul$NbGardien) valueBox(formatC(Valeur37,digits = 0,format ="f",big.mark=' ' ),'CumulAn Moy. Gardiens',color = "green") }) output$GEvolutionEffectif <- renderPlotly({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(DateOpe) %>% summarize(TotalEffectif=sum(NbEffectif), Homme=sum( ifelse( SEXE == "M", NbEffectif, 0 ),na.rm = TRUE), Femme=sum( ifelse( SEXE != "M", NbEffectif, 0 ),na.rm = TRUE) ) #dataf_productionUsine['Objectif'] = 43 if(nrow(dataf_EffectifCumul)>0){ p<-ggplot(data=dataf_EffectifCumul,aes(x = DateOpe)) + geom_line(aes(y=TotalEffectif,colour ="TotalEffectif")) + geom_line(aes(y=Homme,colour ="Homme")) + geom_line(aes(y=Femme,colour ="Femme")) + scale_colour_manual("", breaks = c("TotalEffectif", "Homme", "Femme"), values = c("green", "blue", "black"))+ ylab('Effectif')+xlab('date') } } ) output$GPyramideAge <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbEffectif!=0,],aes(Age))+ geom_histogram(binwidth = 1,color='red',fill='pink',alpha=0.4)+ #geom_histogram(binwidth = 1,aes(fill=..count..))+ ylab('Effectif')+xlab('Age') } } ) output$GPyramideAgeSexeTotal <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbEffectif!=0,],aes(Age))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Age') } } ) output$GPyramideAgeSexeSaisonnier <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbSaisonnier!=0,],aes(Age))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Age') } } ) output$GPyramideAgeSexePermanent <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbPermanent!=0,],aes(Age))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Age') } } ) output$GPyramideAgeSexeTemporaraire <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbTemporaire!=0,],aes(Age))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Age') } } ) #--- output$GPyramideAncSexeTotal <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbEffectif!=0,],aes(Anc))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Anciennete') } } ) output$GPyramideAncSexeSaisonnier <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbSaisonnier!=0,],aes(Anc))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Anciennete') } } ) output$GPyramideAncSexePermanent <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbPermanent!=0,],aes(Anc))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Anciennete') } } ) output$GPyramideAncSexeTemporaraire <- renderPlotly({ dataf_Effectif<-dataf_Effectif() if(nrow(dataf_Effectif)>0){ ggplot(dataf_Effectif[dataf_Effectif$NbTemporaire!=0,],aes(Anc))+ geom_histogram(binwidth = 1,aes(fill=SEXE))+ ylab('Effectif')+xlab('Anciennete') } } ) #--- output$GEvolutionClasseEffectif <- renderPlotly({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(DateOpe) %>% summarize(TotalEffectif=sum(NbEffectif), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire), Gardiens=sum(NbGardien) ) if(nrow(dataf_EffectifCumul)>0){ p<-ggplot(data=dataf_EffectifCumul,aes(x = DateOpe)) + geom_line(aes(y=TotalEffectif,colour ="TotalEffectif")) + geom_line(aes(y=Permanents,colour ="Permanents")) + geom_line(aes(y=Saisonniers,colour ="Saisonniers")) + geom_line(aes(y=Temporaires,colour ="Temporaires")) + geom_line(aes(y=Gardiens,colour ="Gardiens")) + scale_colour_manual("", breaks = c("TotalEffectif", "Permanents", "Saisonniers","Temporaires","Gardiens"), values = c("black", "blue", "red","yellow","green"))+ ylab('Effectif')+xlab('date') } } ) output$GEffectifparSexe <- renderPlotly({ dataf_Effectif<-dataf_Effectif() EffectifTotal<-dataf_Effectif %>% group_by(SEXE) %>% summarize(Effectif=sum(NbEffectif) ) EffectifTotal$Classe<-"Total" EffectifPermanent<-dataf_Effectif %>% group_by(SEXE) %>% summarize(Effectif=sum(NbPermanent) ) EffectifPermanent$Classe<-"Permanents" EffectifSaisonnier<-dataf_Effectif %>% group_by(SEXE) %>% summarize(Effectif=sum(NbSaisonnier) ) EffectifSaisonnier$Classe<-"Saisonniers" EffectifTemporaire<-dataf_Effectif %>% group_by(SEXE) %>% summarize(Effectif=sum(NbTemporaire) ) EffectifTemporaire$Classe<-"Temporaires" EffectifGardien<-dataf_Effectif %>% group_by(SEXE) %>% summarize(Effectif=sum(NbGardien) ) EffectifGardien$Classe<-"Gardiens" dataf_Effectif<-rbind(EffectifTotal, EffectifPermanent, EffectifSaisonnier, EffectifTemporaire, EffectifGardien ) names(dataf_Effectif)<-c("SEXE","Effectif","Classe") if(nrow(dataf_Effectif)>0){ p<-ggplot(data=dataf_Effectif, aes(x = Classe , y = Effectif,fill=SEXE)) + geom_bar(stat = "identity")+ labs(x = "Classe", y = "Effectif", title = "Effectif Mensuel par classe de salariés et par sexe")+ theme_minimal() ggplotly(p) } } ) output$TabEffectif = renderDT({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName,Month) %>% summarize(TotalEffectif=sum(NbEffectif), Homme=sum( ifelse( SEXE == "M", NbEffectif, 0 ),na.rm = TRUE), Femme=sum( ifelse( SEXE != "M", NbEffectif, 0 ),na.rm = TRUE), Ratio=sum( ifelse( SEXE != "M", NbEffectif, 0 ),na.rm = TRUE)*100/sum(NbEffectif) ) dataf_EffectifCumul$Ratio<-formatC(dataf_EffectifCumul$Ratio,digits = 2,format ="f",big.mark=',',width = 2) names(dataf_EffectifCumul)<-c("Mois","Month","TotalEffectif","Homme","Femme","%Femme") dataf_EffectifCumul <- dataf_EffectifCumul[order(dataf_EffectifCumul$Month),c("Mois","Homme","Femme","TotalEffectif","%Femme")] datatable(dataf_EffectifCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$TabEffectifParClasse = renderDT({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% group_by(MonthName,Month) %>% summarize(TotalEffectif=sum(NbEffectif), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire), Gardiens=sum(NbGardien) ) names(dataf_EffectifCumul)<-c("Mois","Month","TotalEffectif","Permanents","Saisonniers","Temporaires","Gardiens") dataf_EffectifCumul <- dataf_EffectifCumul[order(dataf_EffectifCumul$Month),c("Mois","TotalEffectif","Permanents","Saisonniers","Temporaires","Gardiens")] datatable(dataf_EffectifCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$TabEffectifParDirection = renderDT({ dataf_Effectif<-dataf_Effectif() dataf_Effectif<-dataf_Effectif %>% group_by(Direction) %>% summarize(TotalEffectif=sum(NbEffectif), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire), Gardiens=sum(NbGardien) ) datatable(dataf_Effectif, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 9, lengthMenu = c(9), autoWidth = FALSE )) }) output$TabEffectifCatSocio = renderDT({ dataf_Effectif<-dataf_Effectif() EffectifCadre<-data.frame("Cadres",sum(dataf_Effectif$NbCadre)) names(EffectifCadre)<-c("CateSocio","Effectif") EffectifAgm<-data.frame("Agents de Maitrise",sum(dataf_Effectif$NbAgm)) names(EffectifAgm)<-c("CateSocio","Effectif") EffectifEmp<-data.frame("Employés & Ouvriers",sum(dataf_Effectif$NbEmp)) names(EffectifEmp)<-c("CateSocio","Effectif") EffectifFoncAffecte<-data.frame("Fonctionnaires Affectés",sum(dataf_Effectif$NbFonctAffecte)) names(EffectifFoncAffecte)<-c("CateSocio","Effectif") EffectifFoncDetache<-data.frame("Fonctionnaires Détachés",sum(dataf_Effectif$NbFonctDetache)) names(EffectifFoncDetache)<-c("CateSocio","Effectif") EffectifHomme<-data.frame("Hommes",sum( (dataf_Effectif %>% filter(SEXE == 'M'))$NbEffectif)) names(EffectifHomme)<-c("CateSocio","Effectif") EffectifFemme<-data.frame("Femmes",sum( (dataf_Effectif %>% filter(SEXE != 'M'))$NbEffectif)) names(EffectifFemme)<-c("CateSocio","Effectif") EffectifExpat<-data.frame("Expatriés",sum(dataf_Effectif$NbExpat)) names(EffectifExpat)<-c("CateSocio","Effectif") EffectifLocaux<-data.frame("Locaux",sum(dataf_Effectif$NbLocaux)) names(EffectifLocaux)<-c("CateSocio","Effectif") dataf_Effectif<-rbind(EffectifCadre,EffectifAgm,EffectifEmp,EffectifFoncAffecte,EffectifFoncDetache,EffectifHomme,EffectifFemme,EffectifExpat,EffectifLocaux) datatable(dataf_Effectif, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 9, lengthMenu = c(9), autoWidth = FALSE )) }) output$MatriceEffectif <- renderRpivotTable( rpivotTable::rpivotTable( rows = c("MonthName"), #cols=c("CAT"), vals = c("NbEffectif","NbPermanent"), aggregatorName = "Sum", exclusions = "totals", rendererName ="Table",width="50%", height="550px", { data <- dataf_EffectifCumul() data<-data[,c("SEXE","Direction","MonthName","NbEffectif","NbPermanent")] data })) output$value38 <- renderValueBox({ dataf_Depart<-dataf_Depart() Valeur38 <- sum(dataf_Depart$NbDepart) valueBox(formatC(Valeur38,digits = 0,format ="f",big.mark=' ' ),'Total Departs-Mois',color = "black") }) output$value39 <- renderValueBox({ dataf_Depart<-dataf_Depart() Valeur39 <- sum(dataf_Depart$NbPermanent) valueBox(formatC(Valeur39,digits = 0,format ="f",big.mark=' ' ),'Permanents',color = "blue") }) output$value40 <- renderValueBox({ dataf_Depart<-dataf_Depart() Valeur40 <- sum(dataf_Depart$NbSaisonnier) valueBox(formatC(Valeur40,digits = 0,format ="f",big.mark=' ' ),'Saisonniers',color = "red") }) output$value41 <- renderValueBox({ dataf_Depart<-dataf_Depart() Valeur41 <- sum(dataf_Depart$NbTemporaire) valueBox(formatC(Valeur41,digits = 0,format ="f",big.mark=' ' ),'Temporaires',color = "yellow") }) output$value42 <- renderValueBox({ dataf_Depart<-dataf_Depart() Valeur42 <- sum(dataf_Depart$NbGardien) valueBox(formatC(Valeur42,digits = 0,format ="f",big.mark=' ' ),'Gardiens',color = "green") }) output$TabDepartParClasse = renderDT({ dataf_DepartCumul<-dataf_DepartCumul() dataf_DepartCumul<-dataf_DepartCumul %>% group_by(MonthName,Month) %>% summarize(TotalDepart=sum(NbDepart), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire), Gardiens=sum(NbGardien) ) names(dataf_DepartCumul)<-c("Mois","Month","Total","Perm.","Saiso.","Tempo.","Gardiens") dataf_DepartCumul <- dataf_DepartCumul[order(dataf_DepartCumul$Month),c("Mois","Total","Perm.","Saiso.","Tempo.","Gardiens")] datatable(dataf_DepartCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), columnDefs = list(list(width = '10px', targets = c(1,3))), autoWidth = TRUE )) }) output$TabDepartParDirection = renderDT({ dataf_Depart<-dataf_Depart() dataf_Depart<-dataf_Depart %>% group_by(Direction) %>% summarize(Total=sum(NbDepart), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire), Gardiens=sum(NbGardien) ) datatable(dataf_Depart, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 5, lengthMenu = c(5), autoWidth = FALSE )) }) output$TabDepartParMotif = renderDT({ dataf_Depart<-dataf_Depart() dataf_Depart<-dataf_Depart %>% group_by(MotifDepart) %>% summarize(Total=sum(NbDepart), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire)#, #Gardiens=sum(NbGardien) ) datatable(dataf_Depart, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 7, lengthMenu = c(7), autoWidth = FALSE )) }) output$TabDepartParMotifCumul = renderDT({ dataf_DepartCumul<-dataf_DepartCumul() dataf_DepartCumul<-dataf_DepartCumul %>% group_by(MotifDepart) %>% summarize(Total=sum(NbDepart), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire)#, #Gardiens=sum(NbGardien) ) datatable(dataf_DepartCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$value43 <- renderValueBox({ dataf_Recrutement<-dataf_Recrutement() Valeur43 <- sum(dataf_Recrutement$NbRecrutement) valueBox(formatC(Valeur43,digits = 0,format ="f",big.mark=' ' ),'Total Recrutement-Mois',color = "black") }) output$value44 <- renderValueBox({ dataf_Recrutement<-dataf_Recrutement() Valeur44 <- sum(dataf_Recrutement$NbPermanent) valueBox(formatC(Valeur44,digits = 0,format ="f",big.mark=' ' ),'Permanents',color = "blue") }) output$value45 <- renderValueBox({ dataf_Recrutement<-dataf_Recrutement() Valeur45 <- sum(dataf_Recrutement$NbSaisonnier) valueBox(formatC(Valeur45,digits = 0,format ="f",big.mark=' ' ),'Saisonniers',color = "red") }) output$value46 <- renderValueBox({ dataf_Recrutement<-dataf_Recrutement() Valeur46 <- sum(dataf_Recrutement$NbTemporaire) valueBox(formatC(Valeur46,digits = 0,format ="f",big.mark=' ' ),'Temporaires',color = "yellow") }) output$value47 <- renderValueBox({ dataf_Recrutement<-dataf_Recrutement() Valeur47 <- sum(dataf_Recrutement$NbGardien) valueBox(formatC(Valeur47,digits = 0,format ="f",big.mark=' ' ),'Gardiens',color = "green") }) output$TabRecrutementParClasse = renderDT({ dataf_RecrutementCumul<-dataf_RecrutementCumul() dataf_RecrutementCumul<-dataf_RecrutementCumul %>% group_by(MonthName,Month) %>% summarize(TotalRecrutement=sum(NbRecrutement), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire), Gardiens=sum(NbGardien) ) names(dataf_RecrutementCumul)<-c("Mois","Month","Total","Perm.","Saiso.","Tempo.","Gardiens") dataf_RecrutementCumul <- dataf_RecrutementCumul[order(dataf_RecrutementCumul$Month),c("Mois","Total","Perm.","Saiso.","Tempo.","Gardiens")] datatable(dataf_RecrutementCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 5, lengthMenu = c(5), autoWidth = TRUE )) }) output$TabRecrutementParDirection = renderDT({ dataf_Recrutement<-dataf_Recrutement() dataf_Recrutement<-dataf_Recrutement %>% group_by(Direction) %>% summarize(Total=sum(NbRecrutement), Permanents=sum(NbPermanent), Saisonniers=sum(NbSaisonnier), Temporaires=sum(NbTemporaire), Gardiens=sum(NbGardien) ) datatable(dataf_Recrutement, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$value48 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% filter(Month == VMonthPrec) valeur48<-sum(dataf_EffectifCumul$NbEffectif) valueBox(formatC(valeur48,digits = 0,format ="f",big.mark=' ' ),'Effectif-Mois Prec.',color = "black") }) output$value49 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% filter(Month == VMonthPrec) valeur49<-sum(dataf_EffectifCumul$NbPermanent) valueBox(formatC(valeur49,digits = 0,format ="f",big.mark=' ' ),'Permanents-Mois Prec.',color = "blue") }) output$value50 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% filter(Month == VMonthPrec) valeur50<-sum(dataf_EffectifCumul$NbSaisonnier) valueBox(formatC(valeur50,digits = 0,format ="f",big.mark=' ' ),'Saisonniers-Mois Prec.',color = "red") }) output$value51 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% filter(Month == VMonthPrec) valeur51<-sum(dataf_EffectifCumul$NbTemporaire) valueBox(formatC(valeur51,digits = 0,format ="f",big.mark=' ' ),'Temporaires-Mois Prec.',color = "yellow") }) output$value52 <- renderValueBox({ dataf_EffectifCumul<-dataf_EffectifCumul() dataf_EffectifCumul<-dataf_EffectifCumul %>% filter(Month == VMonthPrec) valeur52<-sum(dataf_EffectifCumul$NbGardien) valueBox(formatC(valeur52,digits = 0,format ="f",big.mark=' ' ),'Gardiens-Mois Prec.',color = "green") }) output$TabEffectifParAge = renderDT({ dataf_Effectif<-dataf_Effectif() dataf_Effectif<-dataf_Effectif[dataf_Effectif$NbEffectif>0,] dataf_Effectif<-dataf_Effectif %>% group_by(Direction) %>% summarize(K=sum(de0a20An), A=sum(de21a30An), B=sum(de31a40An), C=sum(de41a50An), D=sum(de51a60An), E=sum(de61a70An), G=sum(plus70An) ) names(dataf_Effectif)<-c("Direction","0-20ans","21-30ans","31-40ans","41-50ans","51-60ans","61-70ans","+70ans") #dataf_Effectif <- dataf_Effectif[order(dataf_EffectifCumul$Month),c("Mois","TotalEffectif","Permanents","Saisonniers","Temporaires","Gardiens")] datatable(dataf_Effectif, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$TabEffectifParAge2 = renderDT({ dataf_Effectif<-dataf_Effectif() dataf_Effectif<-dataf_Effectif[dataf_Effectif$NbEffectif>0,] dataf_Effectif<-dataf_Effectif %>% filter(Age >= input$AgeDebut & Age <= input$AgeFin) dataf_Effectif<-dataf_Effectif %>% group_by(Direction) %>% summarize(Effectif=sum(de0a20An + de21a30An + de31a40An + de41a50An + de51a60An + de61a70An + plus70An ) ) datatable(dataf_Effectif, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 4, lengthMenu = c(4), autoWidth = FALSE )) }) output$value67 <- renderValueBox({ dataf_Mission<-dataf_Mission() Valeur67 <- sum(dataf_Mission$NbMission) valueBox(formatC(Valeur67,digits = 0,format ="f",big.mark=' ' ),'Nbre de Missions du Mois',color = "black") }) output$value68 <- renderValueBox({ dataf_Mission<-dataf_Mission() Valeur68 <- sum(dataf_Mission$NbjourMission) valueBox(formatC(Valeur68,digits = 0,format ="f",big.mark=' ' ),'Jours Misssion du Mois',color = "yellow") }) output$value69 <- renderValueBox({ dataf_Mission<-dataf_Mission() Valeur69 <- sum(dataf_Mission$MontantMission) valueBox(formatC(Valeur69,digits = 0,format ="f",big.mark=' ' ),'Montant Mois (FCFA)',color = "green") }) output$value70 <- renderValueBox({ dataf_Mission<-dataf_Mission() Valeur70 <- sum(dataf_Mission$MontantMission)/sum(dataf_Mission$NbjourMission) valueBox(formatC(Valeur70,digits = 0,format ="f",big.mark=' ' ),'Cout Moy. Jour Mission du Mois (FCFA)',color = "blue") }) output$TabMissionParMois = renderDT({ dataf_MissionCumul<-dataf_MissionCumul() dataf_MissionCumul<-dataf_MissionCumul %>% group_by(MonthName,Month) %>% summarize(NbMissions=sum(NbMission), NbjourMission=sum(NbjourMission), MontantMission=sum(MontantMission)#, #CoutMoyJour=sum(MontantMission)/sum(NbjourMission) ) dataf_MissionCumul$MontantMission<-formatC(dataf_MissionCumul$MontantMission,digits = 0,format ="f",big.mark=' ',width = 2) #dataf_MissionCumul$CoutMoyJour<-formatC(dataf_MissionCumul$CoutMoyJour,digits = 0,format ="f",big.mark=' ',width = 2) names(dataf_MissionCumul)<-c("Mois","Month","NbMissions","Nbjours","Montant(CFA)"#,"CoutJour(CFA)" ) dataf_MissionCumul <- dataf_MissionCumul[order(dataf_MissionCumul$Month),c("Mois","NbMissions","Nbjours","Montant(CFA)"#,"CoutJour(CFA)" )] datatable(dataf_MissionCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$TabMissionParDirection = renderDT({ dataf_MissionCumul<-dataf_MissionCumul() dataf_MissionCumul<-dataf_MissionCumul %>% group_by(Direction) %>% summarize(NbMissions=sum(NbMission), NbjourMission=sum(NbjourMission), MontantMission=sum(MontantMission)#, #CoutMoyJour=sum(MontantMission)/sum(NbjourMission) ) dataf_MissionCumul$MontantMission<-formatC(dataf_MissionCumul$MontantMission,digits = 0,format ="f",big.mark=' ',width = 2) #dataf_MissionCumul$CoutMoyJour<-formatC(dataf_MissionCumul$CoutMoyJour,digits = 0,format ="f",big.mark=' ',width = 2) names(dataf_MissionCumul)<-c("Direction","NbMissions","Nbjours","Montant(CFA)"#,"CoutJour(CFA)" ) datatable(dataf_MissionCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$GMissionParDirection <- renderPlotly({ dataf_MissionCumul<-dataf_MissionCumul() dataf_MissionCumul<-dataf_MissionCumul()[complete.cases(dataf_MissionCumul()$MontantMission),] dataf_MissionCumul<-dataf_MissionCumul %>% group_by(Direction) %>% summarize(MontantMission=sum(MontantMission)/1000000 ) dataf_MissionCumul<-arrange(dataf_MissionCumul,-MontantMission) dataf_MissionCumul = dataf_MissionCumul %>% mutate_if(is.factor, fct_explicit_na, na_level = "NA") dataf_MissionCumul$Direction <- with(dataf_MissionCumul, reorder(Direction, -MontantMission)) p<- ggplot(data=dataf_MissionCumul, aes(x = reorder(Direction, MontantMission), y = MontantMission, fill = Direction)) + geom_bar(stat = "identity")+ coord_flip()+ labs(x = "Direction", y = "Montant(MillionsFCFA)" )+ theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) #theme_minimal() ggplotly(p) } ) output$GEvolutionMissionParMois <- renderPlotly({ dataf_MissionCumul<-dataf_MissionCumul() dataf_MissionCumul<-dataf_MissionCumul %>% group_by(DateOpe) %>% summarize(MontantMission=sum(MontantMission)/1000, CoutMoyJour=sum(MontantMission)/sum(NbjourMission)/1000 ) if(nrow(dataf_MissionCumul)>0){ p<-ggplot(data=dataf_MissionCumul,aes(x = DateOpe)) + geom_line(aes(y=MontantMission)) +#,colour ="MontantMission")) + #geom_line(aes(y=CoutMoyJour,colour ="CoutMoyJour")) + scale_colour_manual("", # breaks = c("MontantMission", "CoutMoyJour" # ), # values = c("black", "green"))+ ylab('Montant(kfca)')+xlab('Date') } } ) #----------------- STock HUILERIE -------------------------------------------------------------- output$value53 <- renderValueBox({ dataf_Stock<-dataf_Stock() nb<-nrow(dataf_Stock) if(nb!=0){ valeur53<-sum(dataf_Stock$Qte) }else{ valeur53<-0 } valueBox(formatC(valeur53,digits = 0,format ="f",big.mark=' ' ),'QteStock (Litre)',color = "black") }) output$value54 <- renderValueBox({ dataf_Stock<-dataf_Stock() nb<-nrow(dataf_Stock) if(nb!=0){ valeur54<-sum(dataf_Stock$Qte) }else{ valeur54<-0 } valueBox(formatC(valeur54,digits = 0,format ="f",big.mark=' ' ),'Moantant (FCFA)',color = "green") }) output$TabQteMontantParProduit = renderDT({ dataf_Stock<-dataf_Stock() dataf_Stock<-dataf_Stock %>% group_by(LIBART1) %>% summarize(Qte=sum(Qte), Montant=sum(Montant) ) names(dataf_Stock)<-c("Article","Qte(L)","Montant(FCFA)") datatable(dataf_Stock, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 5, lengthMenu = c(5), autoWidth = FALSE )) }) output$TabStockEvolution = renderDT({ dataf_StockCumul<-dataf_StockCumul() dataf_StockCumul<-dataf_StockCumul %>% group_by(MonthName,Month,LIBART1) %>% summarize(Qte=sum(Qte), Montant=sum(Montant) ) names(dataf_StockCumul)<-c("Mois","Month","Article","Qte(L)","Montant(FCFA)") dataf_StockCumul <- dataf_StockCumul[order(dataf_StockCumul$Month),c("Mois","Article","Qte(L)","Montant(FCFA)")] datatable(dataf_StockCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 5, lengthMenu = c(5), autoWidth = TRUE )) }) output$MatriceStock <- renderRpivotTable( rpivotTable::rpivotTable( rows = c("Month","MonthName"), cols=c("LIBART1"), vals = c("Qte","Montant"), aggregatorName = "Sum", rendererName ="Table", { data <- dataf_StockCumul() data }, autoWidth = FALSE, exclusions=list( Class = list( "Totals")), subtotals =TRUE ) ) output$MatriceStock2 <- renderPivottabler({ dataf_StockCumul<-dataf_StockCumul() dataf_StockCumul$Libelle<-"Mois" dataf_StockCumul<-dataf_StockCumul[,c("Month","MonthName","LIBART1","Qte","Libelle")] dataf_StockCumul <- dataf_StockCumul[order(dataf_StockCumul$Month),c("Month","MonthName","LIBART1","Qte","Libelle")] pt <- PivotTable$new() pt$addData(dataf_StockCumul) pt$addColumnDataGroups("Libelle",addTotal=FALSE) pt$addColumnDataGroups("Month",addTotal=FALSE) pt$addColumnDataGroups("MonthName",addTotal=FALSE) pt$addRowDataGroups("LIBART1",outlineTotal=list(groupStyleDeclarations=list(color="blue"))) pt$defineCalculation(calculationName="Qte", summariseExpression="sum(Qte)") pt$renderPivot() pivottabler(pt) } ) output$TabStockEvolution2 = renderPrint({ dataf_Stock <- dataf_StockCumul() dataf_Stock<-xtabs(Qte~LIBART1+MonthName,dataf_Stock) } ) output$value53Vte <- renderValueBox({ dataf_facture<-dataf_facture() nb<-nrow(dataf_facture) if(nb!=0){ valeur53Vte<-sum(dataf_facture$NbFacture) }else{ valeur53Vte<-0 } valueBox(formatC(valeur53Vte,digits = 0,format ="f",big.mark=' ' ),'Nbre Factures',color = "black") }) output$value53VtePoidsNet <- renderValueBox({ dataf_facture<-dataf_facture() nb<-nrow(dataf_facture) if(nb!=0){ valeur53VtePoidsNet<-sum(dataf_facture$PoidsNet) }else{ valeur53VtePoidsNet<-0 } valueBox(formatC(valeur53VtePoidsNet,digits = 0,format ="f",big.mark=' ' ),'Poids Net(Kg)',color = "black") }) output$value53VteNbBalle <- renderValueBox({ dataf_facture<-dataf_facture() nb<-nrow(dataf_facture) if(nb!=0){ valeur53VteNbBalle<-sum(dataf_facture$NbBalle) }else{ valeur53VteNbBalle<-0 } valueBox(formatC(valeur53VteNbBalle,digits = 0,format ="f",big.mark=' ' ),'Nbre Balles',color = "black") }) output$value53VteMontant <- renderValueBox({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0){ valeur53VteMontant<-sum(as.numeric(dataf_facture$montant_tot_fact_def)) }else{ valeur53VteMontant<-0 } valueBox(formatC(valeur53VteMontant,digits = 0,format ="f",big.mark=' ' ),'Montant (Euro)',color = "black") }) output$value53NbContrat <- renderValueBox({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0){ valeur53NbContrat<-nrow(as.data.frame(unique(dataf_facture$rf_contrats_sdcc))) }else{ valeur53NbContrat<-0 } valueBox(formatC(valeur53NbContrat,digits = 0,format ="f",big.mark=' ' ),'Nbre de contrats',color = "green") }) output$value53NbClient <- renderValueBox({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0){ valeur53NbClient<-nrow(as.data.frame(unique(dataf_facture$nm_negoci))) }else{ valeur53NbClient<-0 } valueBox(formatC(valeur53NbClient,digits = 0,format ="f",big.mark=' ' ),'Nbre de clients',color = "green") }) output$value53PUMin <- renderValueBox({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0){ valeur53PUMin<-min(as.character(dataf_facture$pu_euro)) }else{ valeur53PUMin<-0 } valueBox(formatC(valeur53PUMin,digits = 4,format ="f",big.mark=' ' ),'PU. Minimum(Euro)',color = "green") }) output$value53PUMax <- renderValueBox({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0){ valeur53PUMax<-max(as.character(dataf_facture$pu_euro)) }else{ valeur53PUMax<-0 } valueBox(formatC(valeur53PUMax,digits = 4,format ="f",big.mark=' ' ),'PU. Maximum(Euro)',color = "green") }) output$TabtauxVente = renderDT({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0) { #dataf_facture<-dataf_facture()[complete.cases(dataf_facture()$montant_tot_fact_def),] dataf_facture<-dataf_facture %>% group_by(typeF) %>% summarize( Nb_balle=sum(nb_balle), Montant=sum(montant_tot_fact_def) ) VTotal <-sum(dataf_facture$Montant) dataf_facture$Pourc<-(dataf_facture$Montant/VTotal)*100 dataf_facture$Pourc <-formatC(dataf_facture$Pourc,digits = 3,format ="f",big.mark=' ' ) #dataf_classement$TonBrut <-formatC(dataf_classement$TonBrut,digits = 2,format ="f",big.mark=' ' ) #dataf_facture$TonNet <-formatC(dataf_classement$TonNet,digits = 2,format ="f",big.mark=' ' ) names(dataf_facture)<-c("Type","NbBalles","Montant(Euro)","Pourc(%)") datatable(dataf_facture, rownames = FALSE, options=list( pageLength = 5, lengthMenu = c(5), autoWidth = FALSE) ) } }) output$TabtauxVenteParClient = renderDT({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0) { #dataf_facture<-dataf_facture()[complete.cases(dataf_facture()$montant_tot_fact_def),] dataf_facture<-dataf_facture %>% group_by(nm_negoci) %>% summarize( Nb_balle=sum(nb_balle), Montant=sum(montant_tot_fact_def) ) VTotal <-sum(dataf_facture$Montant) dataf_facture$Pourc<-(dataf_facture$Montant/VTotal)*100 dataf_facture$Pourc <-formatC(dataf_facture$Pourc,digits = 3,format ="f",big.mark=' ' ) names(dataf_facture)<-c("Client","NbBalles","Montant(Euro)","Pourc(%)") datatable(dataf_facture, rownames = FALSE, options=list( pageLength = 5, lengthMenu = c(5), autoWidth = FALSE) ) } }) output$GTauxVenteParType <- renderPlotly({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0) { dataf_facture<-dataf_facture %>% group_by(typeF,li_pays) %>% summarize( Montant=sum(montant_tot_fact_def)/1000 ) VTotal <-sum(dataf_facture$Montant) dataf_facture$Pourc<-(dataf_facture$Montant/VTotal)*100 dataf_facture<-arrange(dataf_facture,-Pourc) dataf_facture = dataf_facture %>% mutate_if(is.factor, fct_explicit_na, na_level = "NA") dataf_facture$typeF <- with(dataf_facture, reorder(typeF, -Montant)) p<- ggplot(data=dataf_facture, aes(x = reorder(typeF, Montant), y = Montant, fill = li_pays)) + geom_bar(stat = "identity")+ coord_flip()+ labs(x = ".", y = "Montant(KEuro)" )#+ #theme(axis.title.y=element_blank(), # axis.text.y=element_blank(), # axis.ticks.y=element_blank()) #theme_minimal() ggplotly(p) } } ) output$GTauxVenteParClient <- renderPlotly({ dataf_facture<-dataf_factureDef() nb<-nrow(dataf_facture) if(nb!=0) { dataf_facture<-dataf_facture %>% group_by(nm_negoci,li_pays) %>% summarize( Montant=sum(montant_tot_fact_def)/1000 ) VTotal <-sum(dataf_facture$Montant) dataf_facture$Pourc<-(dataf_facture$Montant/VTotal)*100 dataf_facture<-arrange(dataf_facture,-Pourc) dataf_facture = dataf_facture %>% mutate_if(is.factor, fct_explicit_na, na_level = "NA") dataf_facture$nm_negoci <- with(dataf_facture, reorder(nm_negoci, -Montant)) p<- ggplot(data=dataf_facture, aes(x = reorder(nm_negoci, Montant), y = Montant, fill = li_pays)) + geom_bar(stat = "identity")+ coord_flip()+ labs(x = ".", y = "Montant(KEuro)" ) ggplotly(p) } } ) #----------------- ACHATS FINANCES -------------------------------------------------------------- output$value55 <- renderValueBox({ dataf_Achat<-dataf_Achat() nb<-nrow(dataf_Achat) if(nb!=0){ valeur55<-sum(dataf_Achat$NbCde) }else{ valeur55<-0 } valueBox(formatC(valeur55,digits = 0,format ="f",big.mark=' ' ),'Nb Total Cdes',color = "black") }) output$value56 <- renderValueBox({ dataf_Achat<-dataf_Achat() nb<-nrow(dataf_Achat) if(nb!=0){ valeur56<-sum(dataf_Achat$NbCdeCFA) }else{ valeur56<-0 } valueBox(formatC(valeur56,digits = 0,format ="f",big.mark=' ' ),'Cdes Locales',color = "green") }) output$value57 <- renderValueBox({ dataf_Achat<-dataf_Achat() nb<-nrow(dataf_Achat) if(nb!=0){ valeur57<-sum(dataf_Achat$NbCdeEURO+dataf_Achat$NbCdeUSD) }else{ valeur57<-0 } valueBox(formatC(valeur57,digits = 0,format ="f",big.mark=' ' ),'Cdes Imports',color = "yellow") }) output$value58 <- renderValueBox({ dataf_Achat<-dataf_Achat() nb<-nrow(dataf_Achat) if(nb!=0){ valeur58<-sum(dataf_Achat$MontantCdeCFA) }else{ valeur58<-0 } valueBox(formatC(valeur58,digits = 0,format ="f",big.mark=' ' ),'Montant Cdes Locales(CFA)',color = "green") }) output$value59 <- renderValueBox({ dataf_Achat<-dataf_Achat() nb<-nrow(dataf_Achat) if(nb!=0){ valeur59<-sum(dataf_Achat$MontantCdeEURO) }else{ valeur59<-0 } valueBox(formatC(valeur59,digits = 0,format ="f",big.mark=' ' ),'Montant Cdes imports(Euro)',color = "yellow") }) output$value60 <- renderValueBox({ dataf_Achat<-dataf_Achat() nb<-nrow(dataf_Achat) if(nb!=0){ valeur60<-sum(dataf_Achat$MontantCdeUSD) }else{ valeur60<-0 } valueBox(formatC(valeur60,digits = 0,format ="f",big.mark=' ' ),'Montant Cdes imports(USD)',color = "blue") }) output$value61 <- renderValueBox({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% filter(Month == VMonthPrec) valeur61<-sum(dataf_AchatCumul$NbCde) valueBox(formatC(valeur61,digits = 0,format ="f",big.mark=' ' ),'Total Cdes-Mois Prec.',color = "black") }) output$value62 <- renderValueBox({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% filter(Month == VMonthPrec) valeur62<-sum(dataf_AchatCumul$NbCdeCFA) valueBox(formatC(valeur62,digits = 0,format ="f",big.mark=' ' ),'Locales -Mois Prec.',color = "green") }) output$value63 <- renderValueBox({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% filter(Month == VMonthPrec) valeur63<-sum(dataf_AchatCumul$NbCdeEURO+dataf_AchatCumul$NbCdeUSD) valueBox(formatC(valeur63,digits = 0,format ="f",big.mark=' ' ),'Imports -Mois Prec.',color = "yellow") }) output$value64 <- renderValueBox({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% filter(Month == VMonthPrec) valeur64<-sum(dataf_AchatCumul$MontantCdeCFA) valueBox(formatC(valeur64,digits = 0,format ="f",big.mark=' ' ),'Locales(CFA) -Mois Prec.',color = "green") }) output$value65 <- renderValueBox({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% filter(Month == VMonthPrec) valeur65<-sum(dataf_AchatCumul$MontantCdeEURO) valueBox(formatC(valeur65,digits = 0,format ="f",big.mark=' ' ),'Import(Euro) -Mois Prec.',color = "yellow") }) output$value66 <- renderValueBox({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% filter(Month == VMonthPrec) valeur66<-sum(dataf_AchatCumul$MontantCdeUSD) valueBox(formatC(valeur66,digits = 0,format ="f",big.mark=' ' ),'Import(USD) -Mois Prec.',color = "blue") }) output$GEvolutionNbCde <- renderPlotly({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% group_by(DateOpe) %>% summarize(TotalCdes=sum(NbCde), CdesLocales=sum(NbCdeCFA), CdesImpot_euro=sum(NbCdeEURO), CdesImpot_USD=sum(NbCdeUSD) ) if(nrow(dataf_AchatCumul)>0){ p<-ggplot(data=dataf_AchatCumul,aes(x = DateOpe)) + geom_line(aes(y=TotalCdes,colour ="TotalCdes")) + geom_line(aes(y=CdesLocales,colour ="CdesLocales")) + geom_line(aes(y=CdesImpot_euro,colour ="CdesImpot_euro")) + geom_line(aes(y=CdesImpot_USD,colour ="CdesImpot_USD")) + scale_colour_manual("", breaks = c("TotalCdes", "CdesLocales", "CdesImpot_euro","CdesImpot_USD"), values = c("black", "blue","yellow","green"))+ ylab('Nbre Cdes')+xlab('date') } } ) output$TabCdeEvolution = renderDT({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% group_by(MonthName,Month) %>% summarize(TotalCdes=sum(NbCde), CdesLocales=sum(NbCdeCFA), CdesImpot_euro=sum(NbCdeEURO), CdesImpot_USD=sum(NbCdeUSD) ) names(dataf_AchatCumul)<-c("Mois","Month","TotalCdes","CdesLocales","CdesImpot_euro","CdesImpot_USD") dataf_AchatCumul <- dataf_AchatCumul[order(dataf_AchatCumul$Month),c("Mois","TotalCdes","CdesLocales","CdesImpot_euro","CdesImpot_USD")] datatable(dataf_AchatCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$GEvolutionCdeMontant <- renderPlotly({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% group_by(DateOpe) %>% summarize( MontantCFA=sum(MontantCdeCFA), MontantEURO=sum(MontantCdeEURO), MontantUSD=sum(MontantCdeUSD) ) if(nrow(dataf_AchatCumul)>0){ p<-ggplot(data=dataf_AchatCumul,aes(x = DateOpe)) + geom_line(aes(y=MontantCFA,colour ="MontantCFA")) + geom_line(aes(y=MontantEURO,colour ="MontantEURO")) + geom_line(aes(y=MontantUSD,colour ="MontantUSD")) + scale_colour_manual("", breaks = c("MontantCFA", "MontantEURO", "MontantUSD"), values = c("blue","yellow","green"))+ ylab('Montant')+xlab('date') } } ) output$TabMonantCdeEvolution = renderDT({ dataf_AchatCumul<-dataf_AchatCumul() dataf_AchatCumul<-dataf_AchatCumul %>% group_by(MonthName,Month) %>% summarize( MontantCFA=sum(MontantCdeCFA), MontantEURO=sum(MontantCdeEURO), MontantUSD=sum(MontantCdeUSD) ) dataf_AchatCumul$MontantCFA<- formatC(dataf_AchatCumul$MontantCFA,digits = 0,format ="f",big.mark=' ' ) dataf_AchatCumul$MontantEURO<- formatC(dataf_AchatCumul$MontantEURO,digits = 0,format ="f",big.mark=' ' ) dataf_AchatCumul$MontantUSD<- formatC(dataf_AchatCumul$MontantUSD,digits = 0,format ="f",big.mark=' ' ) names(dataf_AchatCumul)<-c("Mois","Month","MontantCFA","MontantEURO","MontantUSD") dataf_AchatCumul <- dataf_AchatCumul[order(dataf_AchatCumul$Month),c("Mois","MontantCFA","MontantEURO","MontantUSD")] datatable(dataf_AchatCumul, rownames = FALSE,selection = 'single', options=list( dom = 'tp', pageLength = 6, lengthMenu = c(6), autoWidth = FALSE )) }) output$GMontantCdeParFsseur <- renderPlotly({ dataf_Achat<-dataf_Achat() if(nrow(dataf_Achat)>0){ dataf_Achat<-dataf_Achat %>% group_by(NOMFOU) %>% summarize(TotalCde=sum(MontantCdeCFA)/1000000) dataf_Achat<-head(arrange(dataf_Achat,-TotalCde),10) # top 10 des produits dataf_Achat = dataf_Achat %>% mutate_if(is.factor, fct_explicit_na, na_level = "NA") dataf_Achat$NOMFOU <- with(dataf_Achat, reorder(NOMFOU, -TotalCde)) p<- ggplot(data=dataf_Achat, aes(x = reorder(NOMFOU, TotalCde), y = TotalCde, fill = NOMFOU)) + geom_bar(stat = "identity")+ coord_flip()+ labs(x = "Fournisseur", y = "MontantCde (Millions CFA)", title = "TOP 10 - Montant en Millions FCFA")+ theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) #scale_x_discrete(labels = comma) #theme_minimal() ggplotly(p) } } ) output$GMontantCdeParDate <- renderPlotly({ dataf_Achat<-dataf_Achat() if(nrow(dataf_Achat)>0){ dataf_Achat<-dataf_Achat %>% group_by(DateOpe) %>% summarize(TotalCde=sum(MontantCdeCFA)/1000000) dataf_Achat<-head(arrange(dataf_Achat,-TotalCde),10) # top 10 des produits dataf_Achat = dataf_Achat %>% mutate_if(is.factor, fct_explicit_na, na_level = "NA") dataf_Achat$DateOpe <- with(dataf_Achat, reorder(DateOpe, -TotalCde)) p<- ggplot(data=dataf_Achat, aes(x = reorder(DateOpe, TotalCde), y = TotalCde, fill = DateOpe)) + geom_bar(stat = "identity")+ coord_flip()+ labs(x = "DateCde", y = "MontantCde (Millions CFA)", title = "TOP 10 - Montant en Millions FCFA")+ theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) #scale_x_discrete(labels = comma) #theme_minimal() ggplotly(p) } } ) dataf_Utilisateur= reactive({ input$updateUtilisateurP input$deleteUtilisateurP input$insertUtilisateurP get_dataUtilisateur() } ) output$Utilisateur = renderDT({ updateTextInput(session,"CodeUtilisateurP",value="") updateTextInput(session,"NomUtilisateurP",value="") dataf_Utilisateur<-dataf_Utilisateur() datatable(dataf_Utilisateur, rownames = FALSE,selection = 'single', options=list( pageLength = 10, lengthMenu = c(10), columnDefs = list(list(visible=FALSE, targets=c(2))) ) ) } ) outputOptions(output,'Utilisateur', priority=-100) observe({ if(!is.null(input$Utilisateur_rows_selected)){ updatevalue=dataf_Utilisateur()[input$Utilisateur_rows_selected,] updateTextInput(session,"CodeUtilisateurP",value=updatevalue$CodeUtilisateur) updateTextInput(session,"CodeProfil",value=updatevalue$ProfilUtilisateur) updateTextInput(session,"NomUtilisateurP",value=updatevalue$NomUtilisateur) updateTextInput(session,"MotPasseUtilisateurP",value=updatevalue$MotPasse) } } ) observeEvent(input$CodeProfil,{ VCodeProfil<<-input$CodeProfil } ) observeEvent(input$CodeUtilisateurP,{ VCodeUtilisateurP<<-input$CodeUtilisateurP } ) observeEvent(input$NomUtilisateurP,{ VNomUtilisateurP<<-input$NomUtilisateurP } ) observeEvent(input$MotPasseUtilisateurP,{ VMotPasse<<-input$MotPasseUtilisateurP } ) observeEvent(input$updateUtilisateurP,{ req="update Utilisateur set NomUtilisateur= cast(? as varchar), MotPasse=cast(? as varchar), ProfilUtilisateur=cast(? as varchar) where CodeUtilisateur like ? " myvalue=data.frame(input$NomUtilisateurP,input$MotPasseUtilisateurP,input$CodeProfil,input$CodeUtilisateurP) sqlExecute(cn, req, myvalue) updateTextInput(session,"CodeProfil",value="") updateTextInput(session,"NomSocieteP",value="") alert("Modification effectuee!") },priority=200 ) observeEvent(input$insertUtilisateurP,{ nbUtilisateur<-0 reqRechUtilisateur<-"select * from Utilisateur where CodeUtilisateur like cast(? as varchar)" myvalue<-data.frame(input$CodeUtilisateurP) ListUtilisateur<-sqlExecute(cn, reqRechUtilisateur, myvalue,fetch=TRUE) nbUtilisateur<-nrow(ListUtilisateur) if(VCodeProfil!="" & VCodeUtilisateurP!="" & VNomUtilisateurP!="" & VMotPasse!="" & nbUtilisateur==0) { req<-"insert into Utilisateur(CodeSociete, CodeUtilisateur, NomUtilisateur, MotPasse,ProfilUtilisateur) values(?,?,?,?,?)" myvalue=data.frame("Sod",input$CodeUtilisateurP,input$NomUtilisateurP,input$MotPasseUtilisateurP,input$CodeProfil) sqlExecute(cn, req, myvalue) updateTextInput(session,"CodeProfil",value="") updateTextInput(session,"CodeUtilisateurP",value="") updateTextInput(session,"NomUtilisateurP",value="") updateTextInput(session,"MotPasse",value="") alert("Creation effectuee") #-- Actualisation liste des utilisateurs reqUtilisateur<-" select '' CodeUtilisateur, '' NomUtilisateur UNION ALL select CodeUtilisateur,NomUtilisateur from Utilisateur" VUtilisateur<-sqlExecute(cn, reqUtilisateur,fetch=TRUE) choicesUtilisateur <<- setNames(VUtilisateur$CodeUtilisateur,VUtilisateur$NomUtilisateur) updateSelectInput(session,'CodeUtilisateuP2',choices=choicesUtilisateur) }else{ if(nbUtilisateur!=0){ alert("Cet Utilisateur existe deja") } else{ if(is.null(input$CodeProfil) | input$CodeProfil==""){ alert("Societe non saisi!") }else{ if(is.null(input$CodeUtilisateurP) | input$CodeUtilisateurP==""){ alert("Code utilisateur non saisi!") }else{ if(is.null(input$NomUtilisateurP) | input$NomUtilisateurP==""){ alert("Nom utilisateur non saisi!") }else{ if(is.null(input$MotPasseUtilisateurP) | input$MotPasseUtilisateurP==""){ alert("Mot de passe non saisie!") } } } } } } },priority=200 ) #----------------- EVACUATION -------------------------------------------------------------- output$GDelaiMoy <- renderPlotly({ dataf_evacuation<-dataf_evacuation() dataf_evacuation<-dataf_evacuation()[complete.cases(dataf_evacuation()$delai),] dataf_evacuation<-dataf_evacuation %>% filter(Periode == VYear & IdUsine==VIdUsine) dataf_evacuation<-dataf_evacuation %>% group_by(DateOpe) %>% summarize(delaiMoy=mean(delai)) if(nrow(dataf_evacuation)>0){ p<-ggplot(data=dataf_evacuation, aes(x = DateOpe, y = delaiMoy)) + geom_line(size = 0.5 ) + labs(x = "DateProduction", y = "Evolution Delai(Jours))", title = "Delai Moyen Evacuation en JOURS")+ theme_minimal() ggplotly(p) } } ) output$GCorrelation <- renderPlotly({ dataf_evacuation<-dataf_evacuation() dataf_evacuation<-dataf_evacuation()[complete.cases(dataf_evacuation()$delai),] dataf_evacuation<-dataf_evacuation %>% filter(Periode == VYear & IdUsine==VIdUsine) dataf_evacuation<-dataf_evacuation %>% group_by(DateProduction,Transporteur) %>% summarize(delai=mean(delai), NbBalles=sum(NbBalles) ) if(nrow(dataf_evacuation)>0){ p<-ggplot(dataf_evacuation, aes(x=NbBalles, y=delai)) + geom_point() + ggtitle("NbBalles vs delai") + geom_smooth(method=lm, se=FALSE)+ labs(x = "Nombre de Balles", y = "Delai (Jours)", title = "Correlation Delai Vs Nb Balles") ggplotly(p) } } ) output$GEvacuationHist <- renderPlot({ dataf_evacuation<-dataf_evacuation() dataf_evacuation<-dataf_evacuation()[complete.cases(dataf_evacuation()$delai),] dataf_evacuation<-dataf_evacuation %>% filter(Periode == VYear & IdUsine==VIdUsine) if(nrow(dataf_evacuation)>0){ hist(dataf_evacuation$delai, col = "blue", main = "Frequence Delai Evacuation", xlab = "Delai Evacuation (Jours)", ylab = "Frequence") } } ) #output$value5 <- renderValueBox({ # dataf_evacuation<-dataf_evacuation() # dataf_evacuation<-dataf_evacuation()[complete.cases(dataf_evacuation()$delai),] # dataf_evacuation<-dataf_evacuation %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) # Valeur5 <- mean(dataf_evacuation$delai) # valueBox(formatC(Valeur5,digits = 0,format ="f",big.mark=',' ),'Delai Moyen Evacuation (Jours)',color = "purple") #}) #output$value51 <- renderValueBox({ # dataf_evacuation<-dataf_evacuation() # dataf_evacuation<-dataf_evacuation()[complete.cases(dataf_evacuation()$delai),] # dataf_evacuation<-dataf_evacuation %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) # Valeur6 <- sum(dataf_evacuation$NbBalles) # valueBox(formatC(Valeur6,digits = 0,format ="f",big.mark=',' ),'Nb de Balles Evacues',color = "yellow") #}) output$TabBallesEvacuation = renderDT({ dataf_evacuation<-dataf_evacuation() #dataf_evacuation<-dataf_evacuation()[complete.cases(dataf_evacuation()$Ecart_Poids),] dataf_evacuation<-dataf_evacuation %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) dataf_evacuation<-head(dataf_evacuation[order(dataf_evacuation$DateProduction),],5) dataf_evacuation<-dataf_evacuation %>% rename( DateProduction = DateOpe, Delai_Evacuation=delai ) dataf_evacuation<-dataf_evacuation[,c("DateProduction","NbBalles","PoidsBrut","PoidsNet","Ecart_Poids","Delai_Evacuation")] datatable(dataf_evacuation, rownames = FALSE) }) output$TabTransporteur = renderDT({ dataf_evacuation<-dataf_evacuation() dataf_evacuation<-dataf_evacuation %>% filter(Periode == VYear & IdUsine==VIdUsine & Month==VMonth) dataf_evacuation<-dataf_evacuation %>% group_by(Usine,Transporteur) %>% summarize(delaiMoy=mean(delai), NbBalles=sum(NbBalles) ) dataf_evacuation$delaiMoy <-formatC(dataf_evacuation$delaiMoy,digits = 1,format ="f",big.mark=',' ) dataf_evacuation<-dataf_evacuation[,c("Transporteur","delaiMoy","NbBalles")] datatable(dataf_evacuation, rownames = FALSE, options=list(autoWidth = FALSE, pageLength = 8, lengthMenu = c(8) ) ) }) appendTab(inputId = "tabselected", tabPanel("PROD.-EGRENAGE", frow1,frow4,frow3,frow2 ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("PROD.-DELINTAGE", div(style = "color:maroon;font-weight: 500", tags$h3(" "), ) ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("PROD.-CLASSEMENT FIBRE",frow6,frow8,frow7,frow9,frow10 ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("PROD.-MAINTENANCE", frow100, frow102, tags$br(), h2("Analyse des pannes, Maintenance & Arrêts "), frow33, frow34, frow35 ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("RESSOURCES H.", frow11,frow12b,frow15b,frow15c,frow14,frow15,frow29, tags$br(), h3("INFORMATIONS SUR LES DEPARTS"), frow17, frow18, frow18b, tags$br(), h3("INFORMATIONS SUR LES RECRUTEMENTS"), frow19, frow20, tags$br(), h3("INFORMATIONS SUR LES MISIONS"), frow30, frow31, frow32 ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("VENTES & STOCKS", h2("FACTURATION FIBRES"), frow21, frow21c, frow21a, frow21b, h2("STOCK HUILES"), frow22 ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("ACHATS & FINANCES", frow24, frow25, frow26, frow27, frow28 ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("SYNTHESE", h2("SYNTHESE TOTALE"), h3("1- Production Usines"), frow1Synhese, h3("2- Maintenance"), ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("HUILERIES", frowH1, frowH2, frowH3, frowH4, frowH5 ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("INFORMATIQUE", PremiereLigne_Informatique, DeuxiemeLigne_Informatique, TroisiemeLigne_Informatique , QuatriemeLigne_Informatique, CinquiemeLigne_Informatique ) # closes tabPanel, ) appendTab(inputId = "tabselected", tabPanel("PARAMETRAGE", tabsetPanel(id="Consultation", tabPanel(tags$h4("Objectifs"), tabsetPanel(id="Consultationx", tabPanel(tags$h4("Production usines")), tabPanel(tags$h4("Maintenance")), tabPanel(tags$h4("Ventes")), tabPanel(tags$h4("Achats")), tabPanel(tags$h4("Ressources Humaines")) ) ), tabPanel(tags$h4("Utilisateurs"), tags$h3(" GESTION DES UTILISATEURS"), fluidRow(div(style="height:500px; width:1540px; border: 2px solid gray", column(3,div(style = "height:400px;background-color: white;", textInput("CodeUtilisateurP", "Code Utilisateur"), textInput("NomUtilisateurP", "Nom Utilisateur"), passwordInput("MotPasseUtilisateurP", "Mot de passe"), selectInput('CodeProfil',"Profil",choices = c("DFC","DRH","PRODUCTION","ADMIN")), actionButton("updateUtilisateurP", "Modification", class = "btn-primary"), disabled( actionButton("deleteUtilisateurP", "Suppression") ), actionButton("insertUtilisateurP", "Ajout") ) ), column(6,div(style = "height:400px;background-color: white;", #tags$head( # tags$style(HTML(css)) #), DTOutput("Utilisateur") ) ) ) ) ) ), ) # closes tabPanel, ) removeTab(inputId = "tabselected", target = "1") if(user$ProfilUtilisateur=="DRH"){ hideTab(inputId = "tabselected", target = "ACHATS & FINANCES") hideTab(inputId = "tabselected", target = "HUILERIE-STOCK&VENTES") hideTab(inputId = "tabselected", target = "PROD.-MAINTENANCE") hideTab(inputId = "tabselected", target = "PROD.-EGRENAGE") hideTab(inputId = "tabselected", target = "PROD.-CLASSEMENT FIBRE") hideTab(inputId = "tabselected", target = "GESTION UTILISATEURS") hideTab(inputId = "tabselected", target = "PROD.-DELINTAGE") } if(user$ProfilUtilisateur=="DFC"){ hideTab(inputId = "tabselected", target = "RESSOURCES HUMAINES") hideTab(inputId = "tabselected", target = "HUILERIE-STOCK&VENTES") hideTab(inputId = "tabselected", target = "PROD.-MAINTENANCE") hideTab(inputId = "tabselected", target = "PROD.-EGRENAGE") hideTab(inputId = "tabselected", target = "PROD.-CLASSEMENT FIBRE") hideTab(inputId = "tabselected", target = "GESTION UTILISATEURS") hideTab(inputId = "tabselected", target = "PROD.-DELINTAGE") } if(user$ProfilUtilisateur=="PRODUCTION"){ hideTab(inputId = "tabselected", target = "RESSOURCES HUMAINES") hideTab(inputId = "tabselected", target = "ACHATS & FINANCES") hideTab(inputId = "tabselected", target = "GESTION UTILISATEURS") } } else { # username correct, password wrong } # closes if-clause } else { # username name wrong or more than 3 log-in failures alert("Nom utilisateur ou mot de passe incorrect!") } # closes second if-clause }) # closes observeEvent observeEvent(input$ScreenDownload,{ shinyjs::toggleClass(selector = "body", class = "sidebar-collapse") screenshot(scale = 0.7) } ) } #shinyApp(ui, Server, onStop(function() {odbcClose(cn)})) shinyApp(ui, Server, onStop(function() {odbcCloseAll()}))
import 'package:flutter/material.dart'; import 'package:cometchat_uikit_shared/cometchat_uikit_shared.dart'; ///[BaseStyles] is the base style class for most style classes provided by [CometChatUIKit] /// /// ```dart /// /// BaseStyles( /// width: 100.0, /// height: 50.0, /// background: Colors.blue, /// gradient: LinearGradient( /// begin: Alignment.topCenter, /// end: Alignment.bottomCenter, /// colors: [Colors.blue, Colors.green], /// ), /// border: Border.all( /// color: Colors.grey, /// width: 2.0, /// ), /// borderRadius: 10.0, /// ) /// /// ``` class BaseStyles { const BaseStyles( {this.width, this.height, this.background, this.gradient, this.border, this.borderRadius}); ///[width] provides width to the widget final double? width; ///[height] provides height to the widget final double? height; ///[background] provides background color to the widget final Color? background; ///[gradient] provides (background) gradient to the widget final Gradient? gradient; ///[border] provides border around the widget final BoxBorder? border; ///[borderRadius] provides radius to the border around the widget final double? borderRadius; }
import java.util.Random; import java.util.Scanner; // basic hero class // can be extended to specific hero type // hp = level*100 // level up mp = 1.1*mp // atk = (strength + weapon)*0.05 // dodge = agility*0.02 // exp required = level*10 public abstract class Hero extends Role { protected int experience; // current exp, when level up exp will minus the exp used for last level. protected int mp; protected int strength; protected int dexterity; protected int agility; protected int gold; protected Bag bag; protected Weapon weapon; protected Armor armor; protected final int hands = 2; // each hero has 2 hands protected int defense = 0; protected Position home; // hero's home for market and respawn protected int lane; // 0 for top, 1 for mid, 2 for bot private double normalRate; private double favorRate; // init a hero public Hero(String name, int level, int experience, int hp, int mp, int strength, int dexterity, int agility, int gold, Bag bag, Position pos) { super(name, level, hp, pos); this.experience = experience; this.mp = mp; this.strength = strength; this.dexterity = dexterity; this.agility = agility; this.gold = gold; this.bag = bag; this.weapon = null; this.armor = null; } public void setHome(Position home) { this.home = home; } public void setLane(int lane) { this.lane = lane; } public abstract void addAttribute(); // after each fight we check if the hero can level up // at most level 10 public void levelUp() { if (level >= 10) { return; } int requireExp = 10 * this.level; while (this.experience >= requireExp) { // hero might level up 2 levels or more. System.out.println("Hero " + name); System.out.println("LEVEL UP!"); this.level += 1; this.hp = Math.max(level * 100, this.hp); this.mp = (int) (this.mp * 1.1); this.updateExp(-requireExp); addAttribute(); requireExp = 10 * this.level; } } public void printHeroInfo() { System.out.println("Name: " + name + " Level: " + level + " Current Exp: " + experience); System.out.println("HP: " + hp + " MP: " + mp); System.out.println("Gold: " + gold); System.out.println("Strength: " + strength + " Dexterity: " + dexterity + " Agility: " + agility + " Defense: " + defense); if (weapon != null) { weapon.printAccurateWeaponInfo(); } if (armor != null) { armor.printAccurateArmorInfo(); } } // monster defense = value * 0.1 // monster dodge = value * 0.005 // hero atk = value * 0.1 public void attack(Monster monster) { int originDamage; if(weapon==null){ originDamage = (int) ((strength) * 0.1); } else{ originDamage = (int) ((strength + weapon.getDamage()) * 0.1); } int actualDamage = originDamage - (int) (monster.getDefense() * 0.1); double dodgeRate = monster.getDodge() * 0.005; double rate = Math.random(); if (rate < dodgeRate) { System.out.println("Hero " + name + " misses his attack on " + monster.getName()); return; } else { System.out.println("Hero " + name + " attacks " + monster.getName() + " with " + actualDamage + " hp"); monster.hp -= actualDamage; } } public void equip() { Scanner sc = new Scanner(System.in); System.out.println("\nHere are your items in the bag: "); bag.printItems(); System.out.println("\nDo you want to equip? [Q/q] to quit else continue"); String ans = sc.nextLine(); if (ans.equalsIgnoreCase("q")) { return; } System.out.println("which do you want to equip?"); System.out.println("Enter a number, for top to bottom on Weapon list, the first one is 0, second one is 1..."); int index = sc.nextInt(); // remove item from bag and put it on heroes // if already an item on hand, put it back to bag // for simple now we only allow hero to have one weapon Item tmpItem = bag.removeItem(index); if (tmpItem instanceof Weapon) { if (weapon == null) { setWeapon((Weapon) tmpItem); System.out.println("You have equipped: " + tmpItem.name); } else { Item undressed = weapon; bag.addItem(undressed); setWeapon((Weapon) tmpItem); System.out.println("You have equipped: " + tmpItem.name); } } else if (tmpItem instanceof Armor) { if (armor == null) { setArmor((Armor) tmpItem); System.out.println("You have equipped: " + tmpItem.name); } else { Item undressed = armor; bag.addItem(undressed); setArmor((Armor) tmpItem); System.out.println("You have equipped: " + tmpItem.name); } } else { System.out.println("equipment error, type wrong"); //put the item back bag.addItem(tmpItem); } } public void drinkPotion() { Scanner sc = new Scanner(System.in); System.out.println("\nHere are your items in the bag: "); bag.printItems(); System.out.println("\nDo you want to use Potion? [Q/q] to quit else continue"); String ans = sc.nextLine(); if (ans.equalsIgnoreCase("q")) { return; } System.out.println("which do you want to drink?"); System.out.println("Enter a number, for top to bottom on Potion list, the first one is 0, second one is 1..."); int index = sc.nextInt(); // get potion and use potion.use() Item tmpItem = bag.removeItem(index); if (tmpItem instanceof Potion) { ((Potion) tmpItem).usePotion(this); } else { System.out.println("potion error, type wrong"); bag.addItem(tmpItem); } } //Hero’s spell damage = 𝑠𝑝𝑒𝑙𝑙_𝑏𝑎𝑠𝑒_𝑑𝑎𝑚𝑎𝑔𝑒+(𝑑𝑒𝑥𝑡𝑒𝑟𝑖𝑡𝑦/10000)×𝑠𝑝𝑒𝑙𝑙_𝑏𝑎𝑠𝑒_𝑑𝑎𝑚𝑎𝑔𝑒 //Monster’s skill loss caused by spell effect = 𝑎𝑓𝑓𝑒𝑐𝑡𝑒𝑑𝑠𝑘𝑖𝑙𝑙×0.1 public void useSpell(Monster monster) { Scanner sc = new Scanner(System.in); System.out.println("\nHere are your items in the bag: "); bag.printItems(); System.out.println("which spell you want to use?"); System.out.println("Enter a number, for top to bottom on Spell list, the first one is 0, second one is 1..."); int index = sc.nextInt(); // get the spell and check if the hero can use it // if not but it back to the bag Item tmpItem = bag.removeItem(index); // if it is a spell if (tmpItem instanceof Spell) { // if enough mp if (mp >= ((Spell) tmpItem).getMpCost()) { double dodgeRate = monster.getDodge() * 0.005; double rate = Math.random(); // if monster dodge if (rate < dodgeRate) { System.out.println("Hero " + name + " misses his spell on " + monster.getName()); return; } else { String type = ((Spell) tmpItem).getType(); int originDamage = ((Spell) tmpItem).getDamage() + (int) ((dexterity / 10000.0) * ((Spell) tmpItem).getDamage()); int actualDamage = originDamage - (int) (monster.getDefense() * 0.1); monster.hp -= actualDamage; if (type.equalsIgnoreCase("Fire")) { System.out.println("Hero " + name + " uses FireSpell on " + monster.getName() + " with " + actualDamage + " damage"); monster.setDamage((int) (0.9 * monster.getDamage())); System.out.println("Monster " + monster.getName() + " damage decreased by 10%"); } else if (type.equalsIgnoreCase("Ice")) { System.out.println("Hero " + name + " uses IceSpell on " + monster.getName() + " with " + actualDamage + " damage"); monster.setDefense((int) (0.9 * monster.getDefense())); System.out.println("Monster " + monster.getName() + " defense decreased by 10%"); } else if (type.equalsIgnoreCase("Lightning")) { System.out.println("Hero " + name + " uses LightningSpell on " + monster.getName() + " with " + actualDamage + " damage"); monster.setDodge((int) (0.9 * monster.getDodge())); System.out.println("Monster " + monster.getName() + " dodge decreased by 10%"); } } } else { System.out.println("You don't have enough MP to use this item"); bag.addItem(tmpItem); } } else { System.out.println("spell error, type wrong"); bag.addItem(tmpItem); } } // when hero wins and gets exp ; when level up hero consumes exp public void updateExp(int val) { this.experience += val; } // hero can get money or use money public void updateGold(int val) { this.gold += val; } public void minusHp(int val) { hp -= val; System.out.println("Hero " + name + " hp decrease from " + (hp + val) + " to " + hp); } public void addHp(int val) { hp += val; System.out.println("Hero " + name + " hp increase from " + (hp - val) + " to " + hp); } public void addMp(int val) { mp += val; System.out.println("Hero " + name + " mp increase from " + (mp - val) + " to " + mp); } public void addStrength(int val) { strength += val; System.out.println("Hero " + name + " strength increase from " + (strength - val) + " to " + strength); } public void addAgility(int val) { agility += val; System.out.println("Hero " + name + " agility increase from " + (agility - val) + " to " + agility); } public void addDexterity(int val) { dexterity += val; System.out.println("Hero " + name + " dexterity increase from " + (dexterity - val) + " to " + dexterity); } public void addDefense(int val) { defense += val; System.out.println("Hero " + name + " defense increase from " + (defense - val) + " to " + defense); } @Override public void setName(String name) { super.setName(name); } @Override public String getName() { return super.getName(); } @Override public void setHp(int hp) { super.setHp(hp); } @Override public int getHp() { return super.getHp(); } @Override public void setLevel(int level) { super.setLevel(level); } @Override public int getLevel() { return super.getLevel(); } @Override public void setPos(Position pos) { super.setPos(pos); } @Override public Position getPos() { return super.getPos(); } public int getMp() { return mp; } public int getExperience() { return experience; } public int getStrength() { return strength; } public int getDexterity() { return dexterity; } public int getAgility() { return agility; } public void setGold(int gold) { this.gold = gold; } public int getGold() { return gold; } public Bag getBag() { return bag; } public void setWeapon(Weapon weapon) { this.weapon = weapon; } public Weapon getWeapon() { return weapon; } public void setArmor(Armor armor) { this.armor = armor; } public Armor getArmor() { return armor; } }
--- title: "Open Government Data, opendata.swiss" date: "2023-08-23" output: html_document --- ## Dataset: Umzüge innerhalb der Stadt nach Herkunft, seit 1971 Anzahl Umzüge innerhalb der Stadt Zürich nach Herkunft und Jahr, seit 1971. [Direct link by **opendata.swiss** for dataset](https://opendata.swiss/de/dataset/umzuge-nach-herkunft-seit-19715)<br> [Direct link by **Stadt Zürich** for dataset](https://data.stadt-zuerich.ch/dataset/bev_umzuege_herkunft_seit1971_od3557) Auto generated R starter code for data set 19e74beb-0eb1-4dd4-8a32-bd4bec206623@stadt-zurich. ## Metadata - **Publisher** `Bevölkerungsamt, Präsidialdepartement` - **Organization.display_name.de** `Stadt Zürich` - **Organization.url** `http://www.stadt-zuerich.ch/opendata` - **Maintainer** `Open Data Zürich` - **Maintainer_email** `opendata@zuerich.ch` - **Keywords.de** `['sasa', 'tabelle', 'sachdaten', 'zeitreihe', 'migration']` - **Issued** `2016-07-08T00:00:00` - **Metadata_created** `2020-03-13T07:17:15.870119` - **Metadata_modified** `2023-08-23T01:07:39.232557` # Load packages ```{r} library(tidyverse) library(skimr) ``` # Load data - The dataset has 1 distribution(s) in CSV format. - All available CSV distributions are listed below and can be read into a tibble. ```{r} # Distribution 0 # Package_id : b45a8d27-81ea-4bac-9d78-0499ca19a030 # Description : # Issued : 2019-07-29T13:37:21.372744 # Modified : 2023-08-22T19:42:34.866757 # Rights : NonCommercialAllowed-CommercialAllowed-ReferenceNotRequired df <- read_delim('https://data.stadt-zuerich.ch/dataset/bev_umzuege_herkunft_seit1971_od3557/download/BEV355OD3557.csv') ``` # Analyze data ```{r} glimpse(df) str(df) skim(df) head(df) tail(df) ``` # Continue your code here... ```{r} ``` ------------------------------------------------------------------------ # Contact opendata@zuerich.ch | Open Data Zürich
import { toastHelper } from '@/helpers/toast-helper' import axios from '@/lib/axios' import { create } from 'zustand' interface State { logo: string | null getLogo: () => Promise<void> updateLogo: (file: File) => Promise<void> } const useConfigStore = create<State>()((set) => ({ logo: null, getLogo: async () => { try { const response = await axios.get('/api/config/logo_image') const responseData = await response.data set({ logo: responseData.data.image_path }) } catch (error) { toastHelper.error(error) } }, updateLogo: async (file: File) => { try { const formData = new FormData() formData.append('logo_image', file) const response = await axios.post('/api/config/logo_image', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) const responseData = await response.data set({ logo: responseData.data.image_path }) toastHelper.success('Logo berhasil diubah') } catch (error) { toastHelper.error(error) } } })) export default useConfigStore
import { MouseEventHandler, ReactNode, RefObject } from 'react'; import { IconType } from 'react-icons'; export interface DataType extends OptionBase { isDisabled?: boolean; label: string; value: string; icon?: string; chainId: string; chainRoute?: string; } export interface ChooseChainInfo { chainName: string; chainRoute?: string; label: string; value: string; icon?: string; disabled?: boolean; } export enum WalletStatus { NotInit = 'NotInit', Loading = 'Loading', Loaded = 'Loaded', NotExist = 'NotExist', Rejected = 'Rejected' } export interface ConnectWalletType { buttonText?: string; isLoading?: boolean; isDisabled?: boolean; icon?: IconType; onClickConnectBtn?: MouseEventHandler<HTMLButtonElement>; } export interface ConnectedUserCardType { username?: string; icon?: ReactNode; walletIcon?: string; } export interface OptionBase { variant?: string; colorScheme?: string; isFixed?: boolean; isDisabled?: boolean; } export interface ChainOption extends OptionBase { isDisabled?: boolean; label: string; value: string; icon?: string; chainName: string; chainRoute?: string; } export type handleSelectChainDropdown = (value: ChainOption | null) => void; export interface ChangeChainDropdownType { data: ChainOption[]; selectedItem?: ChainOption; onChange: handleSelectChainDropdown; chainDropdownLoading?: boolean; } export interface ChangeChainMenuType { data: ChainOption[]; value?: ChainOption; onClose?: () => void; onChange: handleSelectChainDropdown; innerRef?: RefObject<HTMLInputElement>; } export interface FeatureProps { title: string; text: string; href: string; } export type CopyAddressType = { address?: string; walletIcon?: string; isLoading?: boolean; maxDisplayLength?: number; isRound?: boolean; size?: string; };
import { doc, onSnapshot } from "firebase/firestore"; import React, { useState } from "react"; import { useEffect } from "react"; import { db } from "../firebase"; /** * * @param {string} collectionName * @param {string} documentId * @returns {{document: Object | null, error: Error | null}} */ export const useDocument = (collectionName, documentId) => { const [document, setDocument] = useState(null); const [error, setError] = useState(null); useEffect(() => { const docRef = doc(db, collectionName, documentId); const unsub = onSnapshot( docRef, (snapshot) => { if (snapshot.exists) { setDocument({ ...snapshot.data(), id: snapshot.id }); setError(null); } }, (err) => { console.log(err); setError("failed to fetch document"); } ); return () => unsub(); }, [collectionName, documentId]); return { document, error }; };
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <my-paragraph> <span slot="text-contents">Text Contents</span> </my-paragraph> <my-paragraph></my-paragraph> <template my-paragraph> <p class="title">My Paragraph</p> <p><slot name="text-contents">Nothing</slot></p> <style> p.title { font-size: 30px; } </style> </template> <script> customElements.define( 'my-paragraph', class extends HTMLElement { constructor() { super(); const template = document.querySelector('template[my-paragraph]'); this.attachShadow({ mode: 'open' }); this.shadowRoot.appendChild(template.content.cloneNode(true)); } } ) </script> </body> </html>
@extends('layouts.material') @section('menuLateral') @include('inventario.menuLateral') @endsection @section('contenido') <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header card-header-success"> <div class="row"> <div class="col-6"> <h4 class="card-title">Tipos de productos</h4> </div> <div class="col-6 card-title text-right pr-5"> <a href="{{ route('tproducto.fagregar') }}"> <i class="fa fa-plus-square fa-lg mr-2"></i>Agregar</a> </div> </div> </div> <div class="card-body"> <div class="table-responsive"> <table class="table"> <thead class=" text-primary"> <th>Identificador</th> <th>Tipo producto</th> <th>Estado</th> <th>Acciones</th> </thead> <tbody> @foreach($tiposProductos as $tipoProducto) <tr> <td>{{ $tipoProducto->cod_tipo_producto }}</td> <td>{{ $tipoProducto->tipo_producto }}</td> @if( $tipoProducto->is_active) <td> <a href="#" title="Bloquear" data-toggle="modal" data-target="#bloquear{{ $tipoProducto->cod_tipo_producto }}"> <i class="fa fa-unlock fa-lg text-success" aria-hidden="true"></i> </a> <!-- Modal --> <div class="modal fade" id="bloquear{{ $tipoProducto->cod_tipo_producto }}" tabindex="-1" role="dialog" aria-labelledby="bloquearm{{ $tipoProducto->cod_tipo_producto }}" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h5 class="modal-title" id="bloquearm{{ $tipoProducto->cod_tipo_producto }}">Bloquear tipo de producto</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Si bloquea el tipo de producto, no podra ser seleccionada para las proximas transacciones en el sistema </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <form action="{{ route('tproducto.bloquear',['cod_tipo_producto'=>$tipoProducto->cod_tipo_producto]) }}" method="POST"> @csrf @method('PUT') <input type="submit" class="btn btn-success"> </form> </div> </div> </div> </div> {{-- End modal--}} </td> @else <td> <a href="#" title="Bloquear" data-toggle="modal" data-target="#desbloquear{{ $tipoProducto->cod_tipo_producto }}"> <i class="fa fa-lock fa-lg text-danger" aria-hidden="true"></i> </a> <!-- Modal --> <div class="modal fade" id="desbloquear{{ $tipoProducto->cod_tipo_producto }}" tabindex="-1" role="dialog" aria-labelledby="desbloquearm{{ $tipoProducto->cod_tipo_producto }}" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h5 class="modal-title" id="desbloquearm{{ $tipoProducto->cod_tipo_producto }}">Desbloquear tipo de producto</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Si realiza la siguiente acción, el resgistro del tipo de producto podra ser utilizado para las proximas transacciones del sistema </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <form action="{{ route('tproducto.bloquear',['cod_tipo_producto'=>$tipoProducto->cod_tipo_producto]) }}" method="POST"> @csrf @method('PUT') <input type="submit" class="btn btn-success"> </form> </div> </div> </div> </div> {{-- End modal--}} </td> @endif <td> <a href="{{ route('tproducto.factualizar',['cod_tipo_producto' => $tipoProducto->cod_tipo_producto]) }}" title="Editar"> <i class="fa fa-pencil-square fa-lg ml-2 mr-2" aria-hidden="true"></i> </a> <a href="#" title="Eliminar" data-toggle="modal" data-target="#eliminar{{ $tipoProducto->cod_tipo_producto }}"> <i class="fa fa-trash fa-lg ml-2" aria-hidden="true"></i> </a> <!-- Modal --> <div class="modal fade" id="eliminar{{ $tipoProducto->cod_tipo_producto }}" tabindex="-1" role="dialog" aria-labelledby="eliminarm{{ $tipoProducto->cod_tipo_producto }}" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h5 class="modal-title" id="eliminarm{{ $tipoProducto->cod_tipo_producto }}">Eliminar tipo de producto</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Esta seguro de eliminar el registro del tipo de producto, si lo hace ya no se podra utilizar para las proximas transacciones </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <form action="{{ route('tproducto.eliminar',['cod_tipo_producto'=>$tipoProducto->cod_tipo_producto]) }}" method="POST"> @csrf @method('DELETE') <input type="submit" class="btn btn-danger"> </form> </div> </div> </div> </div> {{-- End modal--}} </td> </tr> @endforeach </tbody> </table> </div> </div> </div> {{-- páginación --}} <div class="col-md-12"> {{ $tiposProductos->links() }} </div> </div> </div> @endsection @section('jsExtra') @if(session()->has('success')) <script> Command: toastr["success"]("{{ session()->get('success') }}", "¡Éxito!") @include('partials.message') </script> @elseif(session()->has('error')) <script> Command: toastr["error"]("{{ session()->get('error') }}", "¡Error!") @include('partials.message') </script> @endif @endsection
import UIKit import CoreData class CategoryViewController: UITableViewController { var categories = [Category]() let customAlert = CustomAlert() let context = CoreDataHelper.shared.persistentContainer.viewContext override func viewDidLoad(){ super.viewDidLoad() setupUI() customAlert.delegate = self loadCategories() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } private func setupUI() { let addCategory = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addClick)) self.navigationItem.rightBarButtonItem = addCategory } @objc private func addClick() { customAlert.showAlert(with: "Add New Category", message: "", on: self) } @objc func dismissAlert() { customAlert.dismissAlert() customAlert.addItem() } private func saveCategories() { do { try CoreDataHelper.shared.saveContext() }catch { print("Error saving category \(error)") } tableView.reloadData() } private func loadCategories() { let request: NSFetchRequest<Category> = Category.fetchRequest() do { categories = try context.fetch(request) } catch { print("Error loading categories \(error)") } tableView.reloadData() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return categories.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) var content = cell.defaultContentConfiguration() let categoriesItem = categories[indexPath.row] content.text = categoriesItem.name cell.contentConfiguration = content return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "goToItems", sender: self) tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destinationVC = segue.destination as! TodoListViewController if let indexPath = tableView.indexPathForSelectedRow { destinationVC.selectedCategory = categories[indexPath.row] } } } extension CategoryViewController: passUserTextDelegate { func addItemText(userText: String) { if userText != "" { let addCategories = Category(context: self.context) addCategories.name = userText categories.append(addCategories) saveCategories() }else { return } } }
from fastapi import Depends from sqlalchemy import Column, Date, Integer, String, ForeignKey, Sequence, Enum from sqlalchemy.orm import relationship, backref from DataBase import Base, get_db class User(Base): __tablename__ = 'users' id = Column(Integer, Sequence('user_id_seq', start=1), primary_key=True) name = Column(String(100), nullable=False) email = Column(String(100), unique=True, nullable=False) dob = Column(String(100), nullable=False) contact_number = Column(String(13), nullable=False) user_type = Column(Integer, nullable=False) students = relationship("Student", back_populates="user") faculties = relationship("Faculty", back_populates="user") marks = relationship("Mark", back_populates="user") # Added relationship def __init__(self, name, email, dob, contact_number, user_type, **d): self.name = name self.email = email self.dob = dob self.contact_number = contact_number self.user_type = user_type class Student(Base): __tablename__ = 'students' student_id = Column(Integer, Sequence( 'student_id_seq', start=1), primary_key=True) register_number = Column(String, nullable=False, unique=True) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) user = relationship("User", back_populates="students") class Faculty(Base): __tablename__ = 'faculty' faculty_id = Column(Integer, Sequence( 'faculty_id_seq', start=1), primary_key=True) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) user = relationship("User", back_populates="faculties") class Subjects(Base): __tablename__ = 'subjects' subject_id = Column(Integer, Sequence( 'subject_id_seq', start=1), primary_key=True) subject_name = Column(String, nullable=False, unique=True) # Added relationship marks = relationship("Mark", back_populates="subject") class Mark(Base): __tablename__ = 'Marks' user_id = Column(Integer, ForeignKey( 'users.id', ondelete='CASCADE'), primary_key=True) semester = Column(Integer, nullable=False, primary_key=True) subject_id = Column(Integer, ForeignKey( 'subjects.subject_id'), primary_key=True) grade = Column(String, nullable=True) # Define the 'user' relationship user = relationship("User", back_populates="marks") subject = relationship("Subjects", back_populates="marks")
import os import pandas as pd class DataExtractor: def __init__(self, files, young_person_file='young_person.txt'): self.files = files self.valid_files = [] for file in files: if os.path.exists(file): self.valid_files.append(file) self.young_person_file = young_person_file def reader(self): file_list = [] for file in self.valid_files: file_base_name = os.path.splitext(file)[0] specific_file_name = f'{file_base_name}.csv' try: df = pd.read_csv(file)[['client', 'staff']] df.drop_duplicates(inplace=True) df.to_csv(specific_file_name, index=False) file_list.append(specific_file_name) print(f'File successfully saved: {specific_file_name}') except Exception as e: print(f'Failed to process file: {file}. Error: {e}') return file_list def filter(self): young_persons = [] filtered_file_list = [] with open(self.young_person_file, 'r') as yp_file: for line in yp_file: young_persons.append(line.strip()) # Read the CSV file once for file in self.valid_files: df = pd.read_csv(file) file_base_name = os.path.splitext(file)[0] specific_file_name = f'{file_base_name}_filtered.csv' # Filter and sort data filtered_df = df[~df['client'].isin(young_persons)] sorted_df = filtered_df.sort_values(by='staff') # Save filtered data to CSV try: sorted_df.to_csv(specific_file_name, index=False) filtered_file_list.append(specific_file_name) print(f'Filtered file successfully saved: {specific_file_name}') except Exception as e: print(f'Failed to process file: {file}. Error: {e}') return filtered_file_list # Display all young persons def get_young_persons(self): with open(self.young_person_file, 'r') as yp_file: return [name.strip() for name in yp_file.readlines()] # Add a young person to the young person file def add_young_person(self, name): young_persons = self.get_young_persons() young_persons.append(name) self._save_file(young_persons) return young_persons # Delete a young person from the list def delete_young_person(self, name): try: young_persons = self.get_young_persons() young_persons_set = set(young_persons) young_persons_set.remove(name) updated_young_persons = list(young_persons_set) self._save_file(updated_young_persons) return updated_young_persons except KeyError: print(f"Young person {name}' does not exist in the list.") return young_persons # Save changes to the young person file def _save_file(self, young_persons): with open(self.young_person_file, 'w') as yp_file: for name in young_persons: yp_file.write(f'{name}\n')
/* * RealmSpeak is the Java application for playing the board game Magic Realm. * Copyright (c) 2005-2015 Robin Warren * E-mail: robin@dewkid.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * * http://www.gnu.org/licenses/ */ package com.robin.magic_realm.RealmCharacterBuilder.EditPanel; import java.awt.BorderLayout; import java.awt.GridLayout; import java.util.*; import javax.swing.*; import com.robin.general.util.StringBufferedList; import com.robin.magic_realm.components.utility.Constants; import com.robin.magic_realm.components.wrapper.CharacterWrapper; public class MonsterInteractionEditPanel extends AdvantageEditPanel { private static final String[][] MONSTERS = { {"Animals","Giant Bat","Wolf","T Serpent","H Serpent","H Spider","T Spider","Viper","Octopus","Crow","Scorpion","Carnoplant","Sabertooth","Wasp Queen"}, {"Dragons","T Flying Dragon","T Dragon","H Flying Dragon","H Dragon","Firedrake","Wyrm","Basilisk"}, {"Fantastic","Minotaur","Griffon","Behemoth","Cockatrice","Harpy","Gargrath","Swamp Thing"}, {"Humanoids","Giant","Ogre","Spear Goblin","Axe Goblin","Sword Goblin","T Troll","H Troll","Lizardman","Rat Man","Sword Orc","Orc Archer","Kobold","Frost Giant"}, {"Spirits/Undead","Ghost","Shade","Skeleton","Skeletal Archer","Skeletal Swordsman","Swamp Haunt","Tomb Guard","Wraith","Zombie"}, {"Demons","Winged Demon","Demon","Imp","Balrog"}, {"Elementals","Earth Elemental","Air Elemental","Fire Elemental","Water Elemental"}, }; private Hashtable<String,JCheckBox> hash; public MonsterInteractionEditPanel(CharacterWrapper pChar, String levelKey) { super(pChar, levelKey); hash = new Hashtable<String,JCheckBox>(); setLayout(new BorderLayout()); JPanel main = new JPanel(new GridLayout(1,5)); Box box = Box.createVerticalBox(); addOptionList(box,MONSTERS[0]); box.add(Box.createVerticalGlue()); main.add(box); box = Box.createVerticalBox(); addOptionList(box,MONSTERS[1]); addOptionList(box,MONSTERS[2]); box.add(Box.createVerticalGlue()); main.add(box); box = Box.createVerticalBox(); addOptionList(box,MONSTERS[3]); box.add(Box.createVerticalGlue()); main.add(box); box = Box.createVerticalBox(); addOptionList(box,MONSTERS[4]); box.add(Box.createVerticalGlue()); main.add(box); box = Box.createVerticalBox(); addOptionList(box,MONSTERS[5]); addOptionList(box,MONSTERS[6]); box.add(Box.createVerticalGlue()); main.add(box); add(main,"Center"); ArrayList list = getAttributeList(Constants.MONSTER_IMMUNITY); if (list!=null) { for (Iterator i=list.iterator();i.hasNext();) { String name = (String)i.next(); JCheckBox option = hash.get(name); if (option!=null) { option.setSelected(true); } } } } private void addOptionList(Box box,String[] list) { JPanel panel = new JPanel(new GridLayout(list.length-1,1)); panel.setBorder(BorderFactory.createTitledBorder(list[0])); for (int i=1;i<list.length;i++) { String name = list[i]; JCheckBox option = new JCheckBox(name); panel.add(option); hash.put(name,option); } box.add(panel); } protected void applyAdvantage() { ArrayList list = new ArrayList(); for (String name:hash.keySet()) { JCheckBox option = hash.get(name); if (option.isSelected()) { list.add(name); } } setAttributeList(Constants.MONSTER_IMMUNITY,list); } public String getSuggestedDescription() { StringBuffer sb = new StringBuffer(); sb.append("Is immune to the "); StringBufferedList list = new StringBufferedList(", ","and "); for (String name:hash.keySet()) { JCheckBox option = hash.get(name); if (option.isSelected()) { list.append(option.getText()); } } sb.append(list.toString()); sb.append("."); return sb.toString(); } public boolean isCurrent() { return hasAttribute(Constants.MONSTER_IMMUNITY); } public String toString() { return "Monster Immunity"; } }
const express = require('express'); const pool = require('../config.js') const { isLoggedIn } = require('../middleware/index.js') const Joi = require('joi') router = express.Router(); const commentOwner = async (req, res, next) => { if (req.user.role === 'admin') { return next() } const [[comment]] = await pool.query('SELECT * FROM comment WHERE comm_id = ?', [req.params.comId]) console.log(comment.mem_id); console.log(req.user.mem_id); if (comment.mem_id !== req.user.mem_id) { return res.json({ message: 'You do not have permission to perform this action' }) } else { next() } } const commentSchema = Joi.object({ comm_content:Joi.string().required().min(20).messages({ 'string.base': `Comment should be a type of 'text'`, 'string.empty': `Comment cannot be an empty field`, 'string.min': `Comment should have a minimum length of {#limit}`, 'any.required': `Comment is a required field` }) }) router.get("/comment/:postId", async function (req, res, next) { // Your code here // const {comm_content, post_id, mem_id} = req.body // console.log(comm_content, post_id, mem_id); try { const [rows, fields] = await pool.query('select * from comment c join member m on(m.mem_id = c.mem_id) where c.post_id = ? order by accept desc , comm_created_at desc', [req.params.postId]) return res.json(rows) } catch (error) { console.log(error); } }); router.post("/comment/create", isLoggedIn, async function (req, res, next) { // Your code here try { await commentSchema.validateAsync({comm_content:req.body.comm_content}, { abortEarly: false }) } catch (err) { console.log(err); return res.json({status:"error",message:err.message}) } const { comm_content, post_id, mem_id } = req.body console.log(comm_content, post_id, mem_id); try { const [rows, fields] = await pool.query('INSERT INTO comment(comm_content, post_id, mem_id) VALUES (?,?,?)', [comm_content, post_id, mem_id]) const insertId = rows.insertId // console.log(insertId); const [rows1, fields1] = await pool.query("SELECT * FROM comment c join member m on (c.mem_id = m.mem_id) WHERE comm_id = ?", [insertId]); const [[{ cnt }]] = await pool.query('select count(*) as cnt from comment c join member m on(m.mem_id = c.mem_id) where c.post_id = ? ', [post_id]) return res.json({ newComm:rows1[0], cnt:cnt, status:"success", message:"success" }) } catch (error) { console.log(error); } }); router.delete("/comment/delete/:comId", isLoggedIn, commentOwner, async function (req, res, next) { // Your code here try { const [rows, fields] = await pool.query("DELETE FROM comment WHERE comm_id = ?", [req.params.comId]); return res.json({ "message": `Comment ID ${req.params.comId} is deleted.` }); } catch (err) { console.log(err) return next(err); } }); router.put("/comment/edit/:comId", isLoggedIn, commentOwner, async function (req, res, next) { // Your code here const { comm_content } = req.body console.log(comm_content); try { const [rows, fields] = await pool.query("UPDATE comment SET comm_content=? WHERE comm_id = ?", [comm_content, req.params.comId]); return res.json({ "message": `Comment ID ${req.params.comId} is updated.` }); } catch (err) { console.log(err) return next(err); } }); exports.router = router;
const express = require('express'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const keys = require('../config/keys'); const validateRegisterInput = require('../validation/register'); const validateLoginInput = require('../validation/login'); const User = require('../models/User'); const authRouter = express.Router(); authRouter.post('/register', async (req, res) => { const { errors, isValid } = validateRegisterInput(req.body); if (!isValid) { return res.status(400).json(errors); } const { username, password } = req.body; const userExists = await User.findOne({ username: username }); if (userExists) { return res.status(400).json({ username: 'Username Already Exists', }); } else { const newUser = new User({ username: username, password: password, recipes: [], }); bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(newUser.password, salt, async (err, hash) => { if (err) throw err; newUser.password = hash; try { const createdUser = await newUser.save() res.status(201).json(createdUser); } catch (error) { console.log('Error:', error); } }); }); } }); authRouter.post('/login', async (req, res) => { const { errors, isValid } = validateLoginInput(req.body); if (!isValid) { return res.status(400).json(errors); } const { username, password } = req.body; try { const user = await User.findOne({ username }); if (!user) { return res.status(404).json({ usernamenotfound: 'Username Not Found', }); } const isMatch = await bcrypt.compare(password, user.password); if (isMatch) { const payload = { id: user.id, username: user.username, }; jwt.sign( payload, keys.secretOrKey, { expiresIn: '1d', }, (err, token) => { res.json({ success: true, token: 'Bearer ' + token, }); } ); } else { return res.status(404).json({ passwordincorrect: 'Password Incorrect', }); } } catch (error) { console.log(error); } }); module.exports = authRouter;
import { HardhatRuntimeEnvironment } from "hardhat/types"; import { Contracts } from "./Contracts"; type Account = ReturnType<typeof web3.eth.accounts.privateKeyToAccount>; export async function switchToProductionMode( hre: HardhatRuntimeEnvironment, contracts: Contracts, deployerPrivateKey: string, genesisGovernancePrivateKey: string, quiet: boolean = false ) { const web3 = hre.web3; const artifacts = hre.artifacts as Truffle.Artifacts; // Turn over governance if (!quiet) { console.error("Switching to production mode..."); } // Define accounts in play for the deployment process let deployerAccount: Account; let genesisGovernanceAccount: Account; // Get deployer account try { deployerAccount = web3.eth.accounts.privateKeyToAccount(deployerPrivateKey); } catch (e) { throw Error("Check .env file, if the private keys are correct and are prefixed by '0x'.\n" + e) } // Get deployer account try { genesisGovernanceAccount = web3.eth.accounts.privateKeyToAccount(genesisGovernancePrivateKey); } catch (e) { throw Error("Check .env file, if the private keys are correct and are prefixed by '0x'.\n" + e) } if (!quiet) { console.error(`Switching to production from deployer address ${deployerAccount.address} and genesis governance address ${genesisGovernanceAccount.address}`); console.error(`Using governance settings at ${contracts.getContractAddress(Contracts.GOVERNANCE_SETTINGS)}`); } // Wire up the default account that will do the deployment web3.eth.defaultAccount = deployerAccount.address; // Contract definitions const AddressUpdater = artifacts.require("AddressUpdater"); const InflationAllocation = artifacts.require("InflationAllocation"); const FtsoManager = artifacts.require("FtsoManager"); const Inflation = artifacts.require("Inflation"); const FtsoRewardManager = artifacts.require("FtsoRewardManager"); const Supply = artifacts.require("Supply"); const VoterWhitelister = artifacts.require("VoterWhitelister"); const CleanupBlockNumberManager = artifacts.require("CleanupBlockNumberManager"); const FtsoRegistry = artifacts.require("FtsoRegistry"); const ClaimSetupManager = artifacts.require("ClaimSetupManager"); const PollingFoundation = artifacts.require("PollingFoundation"); const FlareAssetRegistry = artifacts.require("FlareAssetRegistry"); const PollingFtso = artifacts.require("PollingFtso"); // Get deployed contracts const addressUpdater = await AddressUpdater.at(contracts.getContractAddress(Contracts.ADDRESS_UPDATER)); const supply = await Supply.at(contracts.getContractAddress(Contracts.SUPPLY)); const inflation = await Inflation.at(contracts.getContractAddress(Contracts.INFLATION)); const inflationAllocation = await InflationAllocation.at(contracts.getContractAddress(Contracts.INFLATION_ALLOCATION)); const ftsoRewardManager = await FtsoRewardManager.at(contracts.getContractAddress(Contracts.FTSO_REWARD_MANAGER)); const ftsoManager = await FtsoManager.at(contracts.getContractAddress(Contracts.FTSO_MANAGER)); const voterWhitelister = await VoterWhitelister.at(contracts.getContractAddress(Contracts.VOTER_WHITELISTER)); const cleanupBlockNumberManager = await CleanupBlockNumberManager.at(contracts.getContractAddress(Contracts.CLEANUP_BLOCK_NUMBER_MANAGER)); const ftsoRegistry = await FtsoRegistry.at(contracts.getContractAddress(Contracts.FTSO_REGISTRY)); const pollingFoundation = await PollingFoundation.at(contracts.getContractAddress(Contracts.POLLING_FOUNDATION)); const flareAssetRegistry = await FlareAssetRegistry.at(contracts.getContractAddress(Contracts.FLARE_ASSET_REGISTRY)); const claimSetupManager = await ClaimSetupManager.at(contracts.getContractAddress(Contracts.CLAIM_SETUP_MANAGER)); const pollingFtso = await PollingFtso.at(contracts.getContractAddress(Contracts.POLLING_FTSO)); // switch to production mode await addressUpdater.switchToProductionMode(); await supply.switchToProductionMode(); await inflation.switchToProductionMode(); await inflationAllocation.switchToProductionMode(); await ftsoRewardManager.switchToProductionMode(); await claimSetupManager.switchToProductionMode(); await ftsoManager.switchToProductionMode(); await voterWhitelister.switchToProductionMode(); await cleanupBlockNumberManager.switchToProductionMode(); await ftsoRegistry.switchToProductionMode(); await pollingFoundation.switchToProductionMode(); await flareAssetRegistry.switchToProductionMode(); await pollingFtso.switchToProductionMode(); }
import React, { FC } from "react"; import styles from "./slugpage.module.css"; import Image from "next/image"; import Menu from "../components/menu"; import CommentSection from "../components/comments"; import BlogContent from "../components/BlogContent"; import BlogItem from "../components/RelatedBlog/BlogItem"; import RelatedBlog from "../components/RelatedBlog"; import getSidebarPost from "../serverActions/getSidebarPost"; import getPostDetails from "../serverActions/getPostDetails"; import moment from "moment"; import getAllCommentsByPostId from "../serverActions/getAllComments"; interface PostDetailsPageProps { params:{slug:string} } const PostDetailsPage: FC<PostDetailsPageProps> = async({params}) => { const sidebarPosts = await getSidebarPost(); const postDetails = await getPostDetails(params.slug); console.log('postDetails: ', postDetails); // const allComments = await getAllCommentsByPostId(params.slug); if(!postDetails?.id) return( <div className={styles.container}> No Post found </div> ) return ( <div className={styles.container}> <div className={styles.infoContainer}> <div className={styles.imageContainer}> <Image src={String(postDetails.img)} alt="logo" fill /> </div> <div className={styles.textContainer}> <h1 className={styles.title}> {postDetails?.title} </h1> <div className={styles.user}> <div className={styles.userImageContainer}> <Image src={String(postDetails.user.image)} alt="logo" fill className={styles.profileImage} /> </div> <div className={styles.userTextContainer}> <p className={styles.username}>{postDetails.user.name}</p> <p className={styles.date}>{moment(postDetails.createdAt).format('lll')}</p> </div> </div> </div> </div> <div className={styles.content}> <div className={styles.post}> <BlogContent content={postDetails.desc} /> <div className={styles.commentssection}> <CommentSection postDetails={postDetails} /> </div> <div className={styles.relatedContent}> <RelatedBlog postData={postDetails.relatedPosts}/> </div> </div> <div className={styles.sidebar}> <Menu postData={sidebarPosts as any[]} /> </div> </div> </div> ); }; export default PostDetailsPage;
package com.restaurant.orderservice.web; import javax.validation.Valid; import com.restaurant.orderservice.domain.Order; import com.restaurant.orderservice.domain.OrderService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("orders") public class OrderController { private final OrderService orderService; private static final Logger log = LoggerFactory.getLogger(OrderController.class); public OrderController(OrderService orderService) { this.orderService = orderService; } @GetMapping public Flux<Order> getAllOrders(@AuthenticationPrincipal Jwt jwt) { log.info("Fetching all orders"); return orderService.getAllOrders(jwt.getSubject()); } @PostMapping public Mono<Order> submitOrder(@RequestBody @Valid OrderRequest orderRequest) { log.info("Order for {} copies of the food with ref {}", orderRequest.quantity(), orderRequest.ref()); return orderService.submitOrder(orderRequest.ref(), orderRequest.quantity()); } }
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; function readHideList(workspacePath: string): RegExp[] { const hideListPath = path.join(workspacePath, '.hideme'); try { const hideListContent = fs.readFileSync(hideListPath, 'utf8'); return hideListContent .split('\n') .map((line) => line.trim()) .filter((entry) => entry !== '') .map((entry) => new RegExp(`^${entry}$`)); // Use '^' and '$' to match the whole line } catch (error) { console.error(`Error reading .hideme file: ${error}`); return []; } } function hideFilesAndFolders(hideList: RegExp[]) { const workspaceFolders = vscode.workspace.workspaceFolders; if (!workspaceFolders) { return; } workspaceFolders.forEach((folder) => { const config = vscode.workspace.getConfiguration('files', folder.uri); const updatedExcludes: Record<string, boolean> = {}; hideList.forEach((entry) => { // Iterate through files and folders in the workspace if (folder.uri.fsPath) { const filesAndFolders = fs.readdirSync(folder.uri.fsPath); filesAndFolders.forEach((item) => { if (entry.test(item)) { // If the regular expression matches, exclude the file or folder updatedExcludes[item] = true; } }); } }); config.update('exclude', updatedExcludes, vscode.ConfigurationTarget.Workspace); }); } export function activate(context: vscode.ExtensionContext) { console.log('[XYZ HideMe] is now active.'); // Read and apply .hideme file on extension activation const hideList = readHideList(vscode.workspace.rootPath || ''); hideFilesAndFolders(hideList); const disposables: vscode.Disposable[] = []; // Monitor changes to the .hideme file and update configuration vscode.workspace.onDidChangeTextDocument((e) => { if (e.document.fileName.endsWith('.hideme')) { hideFilesAndFolders(readHideList(vscode.workspace.rootPath || '')); } }); context.subscriptions.push(...disposables); } export function deactivate() { console.log('[XYZ HideMe] is now deactivated.'); }
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; import { UserDto } from '@subscribely/contracts'; import { LoggerService } from '@subscribely/core'; import { UserNotFoundException } from '@subscribely/exceptions'; import { UserRepository } from '../../repositories'; import { DeleteUserCommand } from '../impl'; @CommandHandler(DeleteUserCommand) export class DeleteUserHandler implements ICommandHandler<DeleteUserCommand> { constructor( private readonly userRepository: UserRepository, private readonly loggerService: LoggerService, ) { this.loggerService.setContext(DeleteUserHandler.name); } async execute(command: DeleteUserCommand): Promise<UserDto> { this.loggerService.log('DeleteUserHandler#execute.command', { command, }); const { id } = command; let user = await this.userRepository.findOne({ id, }); if (!user) throw new UserNotFoundException(); user = await this.userRepository.delete({ id, }); return user; } }
<!DOCTYPE html> <html> <head> <title>Lession 5 Challenge</title> <meta charset="UTF-8" /> <script src="https://fb.me/react-0.14.7.js"></script> <script src="https://fb.me/react-dom-0.14.7.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.2/browser.min.js"></script> <link rel="stylesheet" type="text/css" href="css/Lession05-Challenge.css"> </head> <body> <div id="app"></div> <script type="text/babel"> var CounterChallenge = React.createClass({ getInitialState: function(){ return { count: 0 } }, incrementCount: function(value) { this.setState({ count: this.state.count + value }) }, render: function(){ return ( <div className="container"> <h1>Count: {this.state.count}</h1> <button className="btn blue-btn" onClick={this.incrementCount.bind(this,1)}>Add 1</button> <button className="btn green-btn" onClick={this.incrementCount.bind(this,5)}>Add 5</button> <button className="btn purple-btn" onClick={this.incrementCount.bind(this,10)}>Add 10</button> </div> ) } }); ReactDOM.render(<CounterChallenge/>,document.getElementById('app')); </script> </body> </html>
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.shortcuts import get_object_or_404 from django.http import JsonResponse from django.views.decorators.http import require_POST from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, \ PageNotAnInteger from .forms import ImageCreateForm from .models import Image @login_required def image_create(request): if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_image = form.save(commit=False) # assign current user to the item new_image.user = request.user new_image.save() messages.success(request, 'Image added successfully') # redirect to new created image detail view return redirect(new_image.get_absolute_url()) else: # build form with data provided by the bookmarklet via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form}) def image_detail(request, id, slug): image = get_object_or_404(Image, id=id, slug=slug) return render(request, 'images/image/detail.html', {'section': 'images', 'image': image}) @login_required @require_POST def image_like(request): image_id = request.POST.get('id') action = request.POST.get('action') if image_id and action: try: image = Image.objects.get(id=image_id) if action == 'like': image.users_like.add(request.user) else: image.users_like.remove(request.user) return JsonResponse({'status': 'ok'}) except Image.DoesNotExist: pass return JsonResponse({'status': 'error'}) @login_required def image_list(request): images = Image.objects.all() paginator = Paginator(images, 8) page = request.GET.get('page') images_only = request.GET.get('images_only') try: images = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page images = paginator.page(1) except EmptyPage: if images_only: # If AJAX request and page out of range # return an empty page return HttpResponse('') # If page out of range return last page of results images = paginator.page(paginator.num_pages) if images_only: return render(request, 'images/image/list_images.html', {'section': 'images', 'images': images}) return render(request, 'images/image/list.html', {'section': 'images', 'images': images})
import { GetDiceRoll, GetRandomBetween } from "../dice.js"; import { Room } from "./room.js"; import { Level } from "./level.js"; import { Tile } from "./tile.js"; export class SimpleLevelBuilder { newLevel({ height, width, min = 3, max = 10, rooms = 40 }) { const level = new Level({ height, width }); level.forEachTile((i, t, p) => { level.tiles[i] = Tile.WallTile(p.x, p.y); }); this.createLevelTiles(level, min, max, rooms); level.entrance = level.rooms[0]?.center(); level.spawn_points = level.rooms .filter((_, i) => i !== 0) .map((r) => r.center()); return level; } createLevelTiles(level, min_size, max_size, max_rooms) { for (let idx = 0; idx < max_rooms; idx++) { const w = GetRandomBetween(min_size, max_size); const h = GetRandomBetween(min_size, max_size); const x = GetDiceRoll(level.width - w - 1); const y = GetDiceRoll(level.height - h - 1); const newRoom = new Room(x, y, h, w); if (!level.inBounds(x, y)) continue; if (level.rooms.some((r) => r.intersects(newRoom))) continue; if (level.rooms.length !== 0) { const lastRoom = level.rooms[level.rooms.length - 1]; this.connectRooms(level, lastRoom, newRoom); } this.addRoom(level, newRoom); } } addRoom(level, r) { level.rooms.push(r); for (let x = 0; x < r.w; x++) { for (let y = 0; y < r.h; y++) { const i = level.getIndexFromXY(r.x + x, r.y + y); level.tiles[i].convertToFloor(); } } } createHorizontalTunnel(level, x1, x2, y) { for (let x = Math.min(x1, x2); x < Math.max(x1, x2) + 1; x++) { if (level.inBounds(x, y)) { level.tiles[level.getIndexFromXY(x, y)].convertToFloor(); } } } createVerticalTunnel(level, y1, y2, x) { for (let y = Math.min(y1, y2); y < Math.max(y1, y2) + 1; y++) { if (level.inBounds(x, y)) { level.tiles[level.getIndexFromXY(x, y)].convertToFloor(); } } } connectRooms(level, r1, r2) { const c1 = r1.center(); const c2 = r2.center(); const coin = GetDiceRoll(2); if (coin === 2) { this.createHorizontalTunnel(level, c1.x, c2.x, c1.y); this.createVerticalTunnel(level, c1.y, c2.y, c2.x); } else { this.createHorizontalTunnel(level, c1.x, c2.x, c2.y); this.createVerticalTunnel(level, c1.y, c2.y, c1.x); } } }
import React from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { Paper, Fab, Box, Grid } from '@material-ui/core'; import { Theme, createStyles, WithStyles, withStyles } from '@material-ui/core/styles'; import { Pagination, Skeleton } from '@material-ui/lab'; import { Add as AddIcon } from '@material-ui/icons'; import { AddAnimalDialog } from './AddAnimalDialog'; import { AnimalsListItem } from './AnimalsListItem'; import { RootState } from '../../app/store'; import { thunkGetCount, thunkGetAnimals } from '../../thunks'; const styles = (theme: Theme) => createStyles({ paper: { marginLeft: 'auto', marginRight: 'auto', padding: theme.spacing(1), width: 'fit-content' }, pagination: { alignItems: 'center', display: 'flex', flexDirection: 'column' }, fab: { bottom: theme.spacing(2), position: 'fixed', right: theme.spacing(2) } }); // https://material-ui.com/guides/typescript/#augmenting-your-props-using-withstyles interface AnimalsListProps extends PropsFromRedux, WithStyles<typeof styles> { } interface AnimalsListOwnState { openAddAnimalDialog: boolean; page: number; } class AnimalsList extends React.Component<AnimalsListProps, AnimalsListOwnState> { constructor(props: AnimalsListProps) { super(props); this.state = { openAddAnimalDialog: false, page: 1 }; this.setOpenAddAnimalDialog = this.setOpenAddAnimalDialog.bind(this); } componentDidMount() { console.debug('AnimalsList => componentDidMount'); this.props.thunkGetCount(); this.props.thunkGetAnimals(this.state.page); } render() { const { classes } = this.props; return ( <React.Fragment> <Paper className={classes.paper} elevation={2} square > <Pagination className={classes.pagination} color='primary' count={Math.ceil(this.props.count / 5)} onChange={(event: React.ChangeEvent<unknown>, page: number) => { this.setState({ page }); this.props.thunkGetAnimals(page); }} page={this.state.page} showFirstButton showLastButton /> </Paper> <Box mt={2} /> <Grid container justify='center' spacing={2} > { this.props.animals.map(animal => <AnimalsListItem key={animal.id} {...animal} />) } </Grid> <Fab className={classes.fab} color='primary' onClick={() => { this.setOpenAddAnimalDialog(true); }} > <AddIcon /> </Fab> <AddAnimalDialog openAddAnimalDialog={this.state.openAddAnimalDialog} setOpenAddAnimalDialog={this.setOpenAddAnimalDialog} /> </React.Fragment> ); } setOpenAddAnimalDialog(open: boolean) { this.setState({ openAddAnimalDialog: open }); } } /** * "Because types can be defined in any order, * you can still declare your component before declaring the connector if you want.": * https://react-redux.js.org/using-react-redux/static-typing#typing-the-connect-higher-order-component */ // Map state to props. const mapState = (state: RootState) => ({ animals: state.animals.animals, count: state.animals.count, loading: state.system.loading }); // Map dispatch to props. const mapDispatch = { thunkGetCount, thunkGetAnimals }; const connector = connect( mapState, mapDispatch ); // Inferring the connected props automatically. type PropsFromRedux = ConnectedProps<typeof connector>; export default connector( withStyles(styles, { /* withTheme: true */ })(AnimalsList) );
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:my_app/pages/settings/widgets/should_delete.dart'; import 'package:my_app/services/services.dart'; import '../widgets/text_form_field.dart'; class ProfilePage extends StatelessWidget { final _formKey = GlobalKey<FormState>(); final Object? arguments; ProfilePage({super.key, required this.arguments}); @override Widget build(BuildContext context) { final activeuser = arguments as DatabaseUser; final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Container( decoration: const BoxDecoration( image: DecorationImage( image: AssetImage('asset/images/login.png'), fit: BoxFit.fill, ), ), child: Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Colors.transparent, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, ), // delete profile floatingActionButton: FloatingActionButton( backgroundColor: Colors.redAccent, child: const Icon(Icons.delete_forever), onPressed: () { ShouldDelete.showDialog(context, activeuser); }, ), body: Stack( children: [ // Label Create Account Container( padding: EdgeInsets.only(left: width * 0.15, top: height * 0.08), child: const Text( 'User\nProfile', style: TextStyle(color: Colors.white, fontSize: 33), ), ), // Form Filet entry Input Form( key: _formKey, child: Container( padding: EdgeInsets.only(top: height * 0.36), margin: EdgeInsets.symmetric(horizontal: width * 0.05), child: Column( children: [ // margin SizedBox(height: height * 0.05), // Text field for name FormInputField( formKey: _formKey, onSave: (newValue) async { if (newValue != activeuser.name) { final name = newValue; // update user's Name context.read<NodeBloc>().add( NodeEventUpdateUser(name: name), ); } }, value: activeuser.name, lable: 'Name', hint: 'eg. Your Name', icon: Icons.person, ), // margin SizedBox(height: height * 0.02), // text field for description FormInputField( formKey: _formKey, onSave: (newValue) async { if (newValue != activeuser.info) { final info = newValue; // update user's Name context.read<NodeBloc>().add( NodeEventUpdateUser(info: info), ); } }, value: activeuser.info, lable: 'Info', hint: 'eg. Personal', icon: Icons.info_outline, ), ], ), ), ), // profile pic Positioned( top: height * 0.14, right: width * 0.05, child: Hero( tag: 'Active User', child: CircleAvatar( backgroundColor: Colors.blueGrey.withAlpha(240), radius: 90.0, child: const Icon( Icons.person, size: 130.0, ), ), ), ) ], ), ), ); } }
# Multiple Producers and Multiple Consumers, same Topic Apache Kafka is a distributed streaming platform that allows you to publish and subscribe to streams of records, store those records in a fault-tolerant manner, and process them. In Kafka, you can have multiple producers and consumers communicating through topics. Let's assume you have Kafka up and running on your local machine, and you have a topic named "my-topic" that you want to work with. To demonstrate multiple producers and consumers working with the same Kafka topic from the terminal: ## Create a Kafka Topic You can create a Kafka topic using the following command: bin\windows\kafka-topics.sh --create --topic my-topic --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1 This command creates a topic named "my-topic" with a single partition and no replication. You can adjust the number of partitions and replication as needed. ## Start Multiple Producers Open multiple terminal windows to simulate multiple producers, and run the following command in each window to start a producer: bin\windows\kafka-console-producer.sh --topic my-topic --bootstrap-server localhost:9092 This command starts a Kafka producer that allows you to enter messages that will be sent to the "my-topic" topic. You can have as many producer instances as you like. ## Start Multiple Consumers Open multiple terminal windows to simulate multiple consumers, and run the following command in each window to start a consumer: bin\windows\kafka-console-consumer.sh --topic my-topic --bootstrap-server localhost:9092 ## Sending Messages You can now use your producer terminals to send messages to the "my-topic" topic. Just type messages and press Enter. ## Reading Messages Consumers can read messages from the topic. By default, consumers read messages from the latest offset. However, you can use the --from-beginning flag to read messages from the beginning of the topic. Without --from-beginning: bin\windows\kafka-console-consumer.sh --topic my-topic --bootstrap-server localhost:9092 This consumer will read messages from the latest offset. If a message is produced after the consumer starts, it will read that message. With --from-beginning: bin\windows\kafka-console-consumer.sh --topic my-topic --bootstrap-server localhost:9092 --from-beginning This consumer will read messages from the beginning of the topic, even if the messages were produced before the consumer started. Now, you can see that multiple producers can send messages to the same Kafka topic, and multiple consumers can read those messages either from the latest offset or from the beginning, depending on the --from-beginning flag. This allows for a flexible and scalable message processing system using Kafka.
# %% import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from multi_variable_loess import fit, single_variable_fit # %% def función_sintética(x,funcion,varianza): if funcion == 1 : return (1/np.sqrt(2))* x + np.sqrt(5) + np.random.normal(loc = 0.0, scale = varianza, size = None) else: return (x-4)**3 +4*(x-4)**2 + (x - 4) + np.random.normal(loc = 0.0, scale = varianza, size = None) def synthetic_data(n,funcion,varianza): xs = [np.random.uniform(0,6) for i in range(0,n)] ys = [función_sintética(xi,funcion,varianza) for xi in xs] return [xs,ys] n = 100 ##subir mucho pq puede generar matrices singulares varianza = 50 f = 0.5 funciones = ["lineal","cuadratica"] sns.set_theme() fig, axes = plt.subplots(1,2,figsize = (10,5)) metric_data = pd.DataFrame(data = {"xs" : [], "fitted_values" : [],"residuos":[],"gradoRegresion":[], "case" : []}) for caso in range(1,3): [xs_l,ys_l] = synthetic_data(n,caso,varianza) xs = np.array(xs_l) ys = np.array(ys_l) scatter_data = pd.DataFrame(data = {"xs":xs, "ys":ys}) sns.scatterplot(data = scatter_data, x = "xs", y = "ys", ax = axes[caso-1]) for grado in range(1,3): fitted_values = fit(xs.reshape(-1,1),xs.reshape(-1,1),ys,f,grado) metric_data = pd.concat([metric_data, pd.DataFrame({"xs" : xs, "fitted_values" : fitted_values,"residuos" : [ys[i] - fitted_values[i] for i in range(0,len(xs))] ,"gradoRegresion" : funciones[grado-1],"case" : funciones[caso-1]})],ignore_index = True) metric_data_sliced = metric_data.loc[metric_data["case"] == funciones[caso-1]] ##metric data tiene todo, aca lo grafico para el caso que toca sns.lineplot(data = metric_data_sliced, x = "xs",y = "fitted_values",hue = "gradoRegresion",ax = axes[caso - 1]) axes[0].set(xlabel = "x", ylabel = "f(x)") axes[1].set(xlabel = "x", ylabel = "g(x)") plt.savefig("../figures/img_experimento_d_values.pdf",bbox_inches='tight') # %% graficamos los residuos <- residuos vs fitted listaGrados = ["lineal","cuadratica"] fig, axes = plt.subplots(2,2,figsize = (10,10)) for i in range(0,2): ##por funcion(caso) <- 1 es lineal for j in range(0,2): ##por regresion df = metric_data.loc[metric_data["case"] == funciones[i]] df = df.loc[df["gradoRegresion"] == funciones[j]] sns.scatterplot(data = df, x = "fitted_values", y = "residuos", ax = axes[i][j]) ## Hacemos loess univariado por cada grafico xs = df["fitted_values"].to_numpy() fit_loess = fit(xs.reshape(-1,1),xs.reshape(-1,1),df["residuos"],0.5,1) df_loess = pd.DataFrame(data = {"xs" : xs,"ys" : fit_loess}) sns.lineplot(data = df_loess, x = "xs", y = "ys", color = "black", ax = axes[i][j]) axes[i][j].set(xlabel = "Valores ajustados", ylabel = "Residuos") plt.subplots_adjust(wspace=0.25, hspace=0.25) axes[0][0].title.set_text('Regresión lineal, f(x)') axes[0][1].title.set_text('Regresión cuadrática, f(x)') axes[1][0].title.set_text('Regresión lineal, g(x)') axes[1][1].title.set_text('Regresión cuadrática, g(x)') plt.savefig("../figures/img_experimento_d_residuos.pdf",bbox_inches='tight') # %%
import java.util.ArrayList; public class OddEvenList { public static void main(String[] args) { Solution solution = new Solution(); int arr[] = new int[] { 10, 20, 30, 40, 50, 60 }; Node head = new Node(arr[0]); Node cur = head; for (int i = 1; i < arr.length; i++) { Node temp = new Node(arr[i]); cur.next = temp; cur = cur.next; } Node bruteForceNode = solution.bruteForce(head); System.out.println("Brute Force : "); while (bruteForceNode != null) { System.out.println(bruteForceNode.data); bruteForceNode = bruteForceNode.next; } System.out.println("Optimal Sol : "); cur = head; for (int i = 1; i < arr.length; i++) { Node temp = new Node(arr[i]); cur.next = temp; cur = cur.next; } Node optimalNode = solution.optimalSol(head); while (optimalNode != null) { System.out.println(optimalNode.data); optimalNode = optimalNode.next; } } private static class Solution { private Node bruteForce(Node head) { Node temp = head; ArrayList<Integer> arr = new ArrayList<>(); while (temp != null && temp.next != null) { arr.add(temp.data); temp = temp.next.next; } // thus if the temp is last it will skip that so assign directly if (temp != null) arr.add(temp.data); temp = head.next; while (temp != null && temp.next != null) { arr.add(temp.data); temp = temp.next.next; } if (temp != null) { arr.add(temp.data); } temp = head; int i = 0; while (temp != null) { temp.data = arr.get(i++); temp = temp.next; } return head; } private Node optimalSol(Node head) { Node oddNodes = head; Node evenNodes = head.next; Node evenHead = head.next; while (oddNodes != null && evenNodes != null && oddNodes.next != null && evenNodes.next != null) { oddNodes.next = oddNodes.next.next; evenNodes.next = evenNodes.next.next; oddNodes = oddNodes.next; evenNodes = evenNodes.next; } oddNodes.next = evenHead; return head; } } private static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } }
#' Calculation of the variance-covariance matrix for a specified survey design (experimental function) #' #' @param vcovMat a variance-covariance matrix. #' @param estfun a gradient function of the log-likelihood function. #' @param design a \code{survey.design} object. #' @description #' This function is an equivalent of \code{survey:::svy.varcoef}. In the original approach \code{estfun} is calculated from #' glm's working residuals:\cr #' \code{estfun <- model.matrix(glm.object) * resid(glm.object, "working") * glm.object$weights}\cr #' In the hopit package, estfun is directly calculated as a gradient (vector of partial derivatives) of the log likelihood function. #' Depending on detected design an appropriate \code{survey} function is called. #' @seealso #' \code{\link[survey]{svydesign}} #' \code{\link{hopit}} #' @importFrom survey svyrecvar twophasevar twophase2var svyCprod svy.varcoef_hopit <- function (vcovMat, estfun, design) { x <- estfun %*% vcovMat if (inherits(design, "survey.design2")) varcoef <- survey::svyrecvar(x = x, clusters = design$cluster, stratas = design$strata, fpcs = design$fpc, postStrata = design$postStrata) else if (inherits(design, "twophase")) varcoef <- survey::twophasevar(x, design) else if (inherits(design, "twophase2")) varcoef <- survey::twophase2var(x, design) else if (inherits(design, "pps")) stop(hopit_msg(89),call.=NULL) else varcoef <-survey::svyCprod(x = x, strata = design$strata, psu = design$cluster[[1]], fpc = design$fpc, nPSU = design$nPSU, certainty = design$certainty, postStrata = design$postStrata) varcoef }
package com.ichi2.anki.tests; import android.Manifest; import android.content.SharedPreferences; import androidx.annotation.StringRes; import androidx.test.annotation.UiThreadTest; import androidx.test.rule.GrantPermissionRule; import com.ichi2.anki.AnkiDroidApp; import com.ichi2.anki.R; import org.acra.ACRA; import org.acra.builder.ReportBuilder; import org.acra.collections.ImmutableList; import org.acra.config.ACRAConfigurationException; import org.acra.config.Configuration; import org.acra.config.CoreConfiguration; import org.acra.config.LimitingReportAdministrator; import org.acra.config.ToastConfiguration; import org.acra.data.CrashReportData; import org.acra.data.CrashReportDataFactory; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.lang.reflect.Method; import timber.log.Timber; import static com.ichi2.anki.AnkiDroidApp.FEEDBACK_REPORT_ALWAYS; import static com.ichi2.anki.AnkiDroidApp.FEEDBACK_REPORT_ASK; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(androidx.test.ext.junit.runners.AndroidJUnit4.class) public class ACRATest extends InstrumentedTest { @Rule public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE); private AnkiDroidApp mApp = null; private final String[] debugLogcatArguments = { "-t", "300", "-v", "long", "ACRA:S"}; //private String[] prodLogcatArguments = { "-t", "100", "-v", "time", "ActivityManager:I", "SQLiteLog:W", AnkiDroidApp.TAG + ":D", "*:S" }; @Before @UiThreadTest public void setUp() { mApp = (AnkiDroidApp) getTestContext().getApplicationContext(); // Note: attachBaseContext can't be called twice as we're using the same instance between all tests. mApp.onCreate(); } /** * helper method to invoke private method to set acra config builder * * @param mode either Debug or Production, used to construct method name to invoke * @param prefs the preferences to use during method invocation * @exception NoSuchFieldException if the method isn't found, possibly IllegalAccess or InvocationAccess as well */ private void setAcraConfig(String mode, SharedPreferences prefs) throws Exception { Method method = mApp.getClass().getDeclaredMethod("set" + mode + "ACRAConfig", SharedPreferences.class); method.setAccessible(true); method.invoke(mApp, prefs); } @Test public void testDebugConfiguration() throws Exception { // Debug mode overrides all saved state so no setup needed setAcraConfig("Debug"); assertArrayEquals("Debug logcat arguments not set correctly", mApp.getAcraCoreConfigBuilder().build().logcatArguments().toArray(), new ImmutableList<>(debugLogcatArguments).toArray()); verifyDebugACRAPreferences(); } private void verifyDebugACRAPreferences() { assertTrue("ACRA was not disabled correctly", getSharedPrefs() .getBoolean(ACRA.PREF_DISABLE_ACRA, true)); assertEquals("ACRA feedback was not turned off correctly", AnkiDroidApp.FEEDBACK_REPORT_NEVER, getSharedPrefs() .getString(AnkiDroidApp.FEEDBACK_REPORT_KEY, "undefined")); } @Test public void testProductionConfigurationUserDisabled() throws Exception { // set up as if the user had prefs saved to disable completely setReportConfig(AnkiDroidApp.FEEDBACK_REPORT_NEVER); // ACRA initializes production logcat via annotation and we can't mock Build.DEBUG // That means we are restricted from verifying production logcat args and this is the debug case again setAcraConfig("Production"); verifyDebugACRAPreferences(); } @Test public void testProductionConfigurationUserAsk() throws Exception { // set up as if the user had prefs saved to ask setReportConfig(FEEDBACK_REPORT_ASK); // If the user is set to ask, then it's production, with interaction mode dialog setAcraConfig("Production"); verifyACRANotDisabled(); assertToastMessage(R.string.feedback_manual_toast_text); assertToastIsEnabled(); assertDialogEnabledStatus("Dialog should be enabled", true); } @Test public void testCrashReportLimit() throws Exception { // To test ACRA switch on reporting, plant a production tree, and trigger a report Timber.plant(new AnkiDroidApp.ProductionCrashReportingTree()); // set up as if the user had prefs saved to full auto setReportConfig(FEEDBACK_REPORT_ALWAYS); // If the user is set to always, then it's production, with interaction mode toast // will be useful with ACRA 5.2.0 setAcraConfig("Production"); // The same class/method combo is only sent once, so we face a new method each time (should test that system later) Exception crash = new Exception("testCrashReportSend at " + System.currentTimeMillis()); StackTraceElement[] trace = new StackTraceElement[] { new StackTraceElement("Class", "Method" + (int)System.currentTimeMillis(), "File", (int)System.currentTimeMillis()) }; crash.setStackTrace(trace); // one send should work CrashReportData crashData = new CrashReportDataFactory(getTestContext(), AnkiDroidApp.getInstance().getAcraCoreConfigBuilder().build()).createCrashData(new ReportBuilder().exception(crash)); assertTrue(new LimitingReportAdministrator().shouldSendReport( getTestContext(), AnkiDroidApp.getInstance().getAcraCoreConfigBuilder().build(), crashData) ); // A second send should not work assertFalse(new LimitingReportAdministrator().shouldSendReport( getTestContext(), AnkiDroidApp.getInstance().getAcraCoreConfigBuilder().build(), crashData) ); // Now let's clear data AnkiDroidApp.deleteACRALimiterData(getTestContext()); // A third send should work again assertTrue(new LimitingReportAdministrator().shouldSendReport( getTestContext(), AnkiDroidApp.getInstance().getAcraCoreConfigBuilder().build(), crashData) ); } @Test public void testProductionConfigurationUserAlways() throws Exception { // set up as if the user had prefs saved to full auto setReportConfig(FEEDBACK_REPORT_ALWAYS); // If the user is set to always, then it's production, with interaction mode toast setAcraConfig("Production"); verifyACRANotDisabled(); assertToastMessage(R.string.feedback_auto_toast_text); assertToastIsEnabled(); assertDialogEnabledStatus("Dialog should not be enabled", false); } @Test public void testDialogEnabledWhenMovingFromAlwaysToAsk() throws Exception { // Raised in #6891 - we ned to ensure that the dialog is re-enabled after this transition. setReportConfig(FEEDBACK_REPORT_ALWAYS); // If the user is set to ask, then it's production, with interaction mode dialog setAcraConfig("Production"); verifyACRANotDisabled(); assertDialogEnabledStatus("dialog should be disabled when status is ALWAYS", false); assertToastMessage(R.string.feedback_auto_toast_text); setAcraReportingMode(FEEDBACK_REPORT_ASK); assertDialogEnabledStatus("dialog should be re-enabled after changed to ASK", true); assertToastMessage(R.string.feedback_manual_toast_text); } @Test public void testToastTextWhenMovingFromAskToAlways() throws Exception { // Raised in #6891 - we ned to ensure that the text is fixed after this transition. setReportConfig(FEEDBACK_REPORT_ASK); // If the user is set to ask, then it's production, with interaction mode dialog setAcraConfig("Production"); verifyACRANotDisabled(); assertToastMessage(R.string.feedback_manual_toast_text); setAcraReportingMode(FEEDBACK_REPORT_ALWAYS); assertToastMessage(R.string.feedback_auto_toast_text); } private void setAcraReportingMode(String feedbackReportAlways) { AnkiDroidApp.getInstance().setAcraReportingMode(feedbackReportAlways); } private void assertDialogEnabledStatus(String message, boolean isEnabled) throws ACRAConfigurationException { CoreConfiguration config = mApp.getAcraCoreConfigBuilder().build(); for (Configuration configuration : config.pluginConfigurations()) { // Make sure the dialog is set to pop up if (configuration.getClass().toString().contains("Dialog")) { assertThat(message, configuration.enabled(), is(isEnabled)); } } } private void assertToastIsEnabled() throws ACRAConfigurationException { CoreConfiguration config = mApp.getAcraCoreConfigBuilder().build(); for (Configuration configuration : config.pluginConfigurations()) { if (configuration.getClass().toString().contains("Toast")) { assertThat("Toast should be enabled", configuration.enabled(), is(true)); } } } private void assertToastMessage(@StringRes int res) throws ACRAConfigurationException { CoreConfiguration config = mApp.getAcraCoreConfigBuilder().build(); for (Configuration configuration : config.pluginConfigurations()) { if (configuration.getClass().toString().contains("Toast")) { assertEquals(mApp.getResources().getString(res), ((ToastConfiguration)configuration).text()); assertTrue("Toast should be enabled", configuration.enabled()); } } } private void verifyACRANotDisabled() { assertFalse("ACRA was not enabled correctly", getSharedPrefs().getBoolean(ACRA.PREF_DISABLE_ACRA, false)); } private void setAcraConfig(String production) throws Exception { setAcraConfig(production, getSharedPrefs()); } private void setReportConfig(String feedbackReportAsk) { getSharedPrefs().edit() .putString(AnkiDroidApp.FEEDBACK_REPORT_KEY, feedbackReportAsk).commit(); } private SharedPreferences getSharedPrefs() { return AnkiDroidApp.getSharedPrefs(getTestContext()); } }
import HomeView from '@/views/HomeView.vue' import AboutView from '@/views/AboutView.vue' import { createRouter, createWebHistory } from 'vue-router' const routes = [ { path: '/', name: 'home', component: HomeView, meta: { title: 'Home', }, }, { path: '/about', name: 'about', component: AboutView, meta: { title: 'About', }, }, ] const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: routes, }) export default router
import React, { useEffect, useState } from "react"; import { apiBaseUrl } from "../../index.js"; export default function Users() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetch(apiBaseUrl + "users", { method: "GET", }) .then((response) => { return response.json(); }) .then((data) => { setUsers(data); console.log("data is :", data); }) .catch((error) => { console.log("error in users api call : ", error); }) .finally(() => { setLoading(false); }); }, []); return ( <div> {loading ? ( <div className="spinner-border" role="status"> <span className="sr-only">Loading...</span> </div> ) : ( <table className="table"> <thead> <tr> <th scope="col">Id</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Borrowed Books</th> </tr> </thead> <tbody> {users.map((user) => ( <tr key={user.id}> <th scope="row">{user.id}</th> <td>{user.name}</td> <td>{user.email}</td> <td>{user.borrowedBooks}</td> </tr> ))} </tbody> </table> )} </div> ); }
import { Action } from "redux"; import { NormalizedObjects } from "../../store/normalized-objects"; import { User } from "./user-state"; export enum UserActionTypes { LOAD_USERS_INIT = "Users__LoadUsersInit", LOAD_USERS_SUCCESS = "Users__LoadUsersSuccess", GET_USER = "Users__GetUser", GET_USER_SUCCESS = "Users__GetUserSuccess", FIND_USER = "Users__FindUser", FIND_USER_SUCCESS = "Users__FindUserSuccess", LOGOUT_USER = "Users__Logout", } export interface LoadUsersInit extends Action { type: UserActionTypes.LOAD_USERS_INIT; } export function loadUsersInit(): UsersActions { return { type: UserActionTypes.LOAD_USERS_INIT }; } export interface LoadUsersSuccess extends Action { type: UserActionTypes.LOAD_USERS_SUCCESS; users: NormalizedObjects<User>; } export function loadUsersSuccess(users: NormalizedObjects<User>): UsersActions { return { type: UserActionTypes.LOAD_USERS_SUCCESS, users }; } export interface GetUser extends Action { type: UserActionTypes.GET_USER; keycloakId: string; } export function getUser(keycloakId: string): UsersActions { return { type: UserActionTypes.GET_USER, keycloakId }; } export interface GetUserSuccess extends Action { type: UserActionTypes.GET_USER_SUCCESS; user: User; } export function getUserSuccess(user: User): UsersActions { return { type: UserActionTypes.GET_USER_SUCCESS, user }; } export interface FindUser extends Action { type: UserActionTypes.FIND_USER; userId: string; } export function findUser(userId: string): UsersActions { return { type: UserActionTypes.FIND_USER, userId }; } export interface FindUserSuccess extends Action { type: UserActionTypes.FIND_USER_SUCCESS; user: User; } export function findUserSuccess(user: User): UsersActions { return { type: UserActionTypes.FIND_USER_SUCCESS, user }; } export interface Logout extends Action { type: UserActionTypes.LOGOUT_USER; } export function logout(): UsersActions { return { type: UserActionTypes.LOGOUT_USER }; } export type UsersActions = | LoadUsersInit | LoadUsersSuccess | GetUser | GetUserSuccess | FindUser | FindUserSuccess | Logout;
<template> <div> <navbar /> <main class="day-review-list-wrapper"> <div class="review-type">여정 일기</div> <div class="review-list-header"> <div class="review-list-header-item review-list-header-title">제목</div> <div class="review-list-header-item">작성자</div> <div class="review-list-header-item">작성일</div> <div class="review-list-header-item">조회수</div> <div class="review-list-header-item">좋아요</div> </div> <div> <review-list-item v-for="review in reviews" :key="review.reviewId" :review="review" /> </div> <div class="reivew-list-page-number-list"> <div class="review-list-page-number" v-for="pageNumber in pageRange" :class="{ 'current-page-number': pageNumber === currentPage }" :key="pageNumber" @click="getOtherPageNumberList(pageNumber + 1)" > {{ pageNumber + 1 }} </div> </div> </main> </div> </template> <script> import Navbar from '../../components/Navbar.vue'; import ReviewListItem from '../../components/review-list/ReviewListItem.vue'; import _axios from '../../util/_axios'; export default { components: { Navbar, ReviewListItem }, data() { return { totalPages: null, currentPage: null, reviews: [], pageRange: [], }; }, methods: { async getDayReviewList(){ try { const pageNumber = this.$route.query.currentPage === undefined ? 0 : this.$route.query.currentPage - 1; const res = await _axios.get( `/api/review/day/list?currentPage=${pageNumber}` ); this.totalPages = res.data.totalPages; this.currentPage = res.data.currentPage; this.reviews = res.data.reviews; const range = []; let offset; if (this.currentPage < 2) { offset = this.currentPage; } else if (this.totalPages - this.currentPage < 3) { offset = 5 - (this.totalPages - this.currentPage); } else { offset = 2; } for ( let i = this.currentPage - offset; i < this.currentPage + 5 - offset; i++ ) { if (i < 0) continue; if (i >= this.totalPages) break; range.push(i); } this.pageRange = range; } catch (e) { console.log(e); alert(`에러 발생 : ${e.message}`); } }, async getOtherPageNumberList(pageNumber) { if (pageNumber !== this.currentPage) { await this.$router.push(`/review/day/list?currentPage=${pageNumber}`); this.getDayReviewList() } }, }, async created() { this.getDayReviewList() }, }; </script> <style> .day-review-list-wrapper { width: 960px; margin: 0 auto; } @media (max-width: 960px) { .day-review-list-wrapper { width: 98%; } } .review-list-header { display: flex; padding: 12px 0px; border-bottom: 0.12rem solid rgba(160, 37, 37, 1); } .review-list-header-item { flex: 1; font-size: 15px; font-weight: bold; text-align: center; } .review-list-header-title { flex: 6; } .reivew-list-page-number-list { display: flex; justify-content: center; margin: 18px 0px; font-size: 15px; } .current-page-number { font-weight: bold; } .review-list-page-number { padding: 0px 6px; cursor: pointer; } .review-list-page-number:not(:last-child) { border-right: 1px solid rgba(0, 0, 0, 0.4); } </style>
import React from "react"; import { PersonalInfo } from "../../../models/personal-info"; import { FinancialInfo } from "../../../models/financial-info"; // @todo - Can we use the actual machine context here? type Context = { personalInfo: PersonalInfo; financialInfo: FinancialInfo }; export type TipType = | "credit" | "debt" | "education" | "estate" | "insurance" | "medical" | "retirement" | "savings" | "social-security"; export interface Tip { id: string; title: string | ((context: Context) => string); description: | string | JSX.Element | ((context: Context) => string) | ((context: Context) => JSX.Element); type: TipType; isRelevant: (context: Context) => boolean; } const tips: Tip[] = [ { id: "AA", title: ({ financialInfo }: Context): string => { const savingsRate = financialInfo.expenses / financialInfo.income; if (savingsRate >= 0.9) { return "Work on your savings rate!"; } if (savingsRate >= 0.86) { return "Great job on saving some money every month! Almost there"; } if (savingsRate >= 0.81) { return "You're on fire saving all that money!"; } return "Amazing savings rate! Keep it up 🔥"; }, description: "A good savings target is 15–20% of gross income.", type: "savings", isRelevant: ({ financialInfo }) => financialInfo.income > 0, }, { id: "AB", title: ({ financialInfo }: Context): string => { const debtToIncome = financialInfo.debt / financialInfo.income; if (debtToIncome >= 0.5) { return "Stop! Take action now on your debt."; } return "Try to improve your debt-to-income ratio"; }, description: "Your debt-to-income (DTI) ratio is an important part of your overall financial health. It’s the percentage of your gross monthly income (before taxes) that goes towards payments for rent, mortgage, credit cards, or other debt. Ideally, you'd like this number to be less than 35%.", type: "debt", isRelevant: ({ financialInfo }: Context): boolean => { if (financialInfo.income <= 0) { // Avoid divide by zero errors return false; } const debtToIncome = financialInfo.debt / financialInfo.income; return debtToIncome >= 0.35; }, }, { id: "AC", title: "Catch up on your retirement contributions", description: "The government allows you to make an additional $6,500 contribution to your IRA, Roth IRA, 401(k), 403(b), and 457 at age 50.", type: "retirement", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.age >= 50 && financialInfo.income > financialInfo.expenses, }, { id: "AD", title: "You might be eligible for Social Security benefits as a disabled widow/widower", description: "If you are disabled and a widow, you may be able to draw Social Security benefits based on your deceased spouse's record.", type: "social-security", isRelevant: ({ personalInfo }) => personalInfo.age >= 50 && personalInfo.maritalStatus === "widowed", }, { id: "AE", title: "You're eligible to claim Social Security survivor benefits as a widow/widower", description: ( <p> If you are a widow, you may be able to draw Social Security benefits based on your deceased spouse&rsquo;s record. If you draw the benefit before your full retirement age ( <a href="https://www.ssa.gov/benefits/retirement/planner/agereduction.html" target="_blank" rel="noreferrer" > what&rsquo;s my full retirement age? </a> ), the benefit will be reduced, so it might make sense to wait. </p> ), type: "social-security", isRelevant: ({ personalInfo }) => personalInfo.age >= 60 && personalInfo.maritalStatus === "widowed", }, { id: "AF", title: "Make a catch-up contribution to your health savings account", description: "The government allows you to make an additional $1,000 contribution to HSAs at age 55.", type: "retirement", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.age >= 55 && financialInfo.income > financialInfo.expenses, }, { id: "AG", title: "You're eligible for penalty exceptions for certain withdrawals from retirement accounts", description: "The IRS Rule of 55 allows an employee who is laid off, fired, or who quits a job between the ages of 55 and 59 1/2 to pull money out of their 401(k) or 403(b) plan without penalty. Only applies to assets in your current 401(k) or 403(b)—the one you invested in while you were at the job you leave at age 55 or older.", type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age >= 55 && personalInfo.age < 60, }, { id: "AH", title: "You can withdraw from IRAs without 10% early distribution penalty", description: "In order to discourage people from using their retirement savings for anything other than retirement income, the IRS charges a 10% penalty on most early (i.e., prior to age 59.5) withdrawals from retirement plans.", type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age >= 60, }, { id: "AI", title: "You're eligible to claim Social Security retirement benefits", description: ( <p> You are eligible to draw Social Security benefits based on your record. If you draw the benefit before your full retirement age ( <a href="https://www.ssa.gov/benefits/retirement/planner/agereduction.html" target="_blank" rel="noreferrer" > what&rsquo;s my full retirement age? </a> ), the benefit will be reduced, so it might make sense to wait. </p> ), type: "social-security", isRelevant: ({ personalInfo }) => personalInfo.age >= 62, }, { id: "AJ", title: "You're eligible to claim Social Security retirement benefits", description: ( <> <p> When you&rsquo;re first eligible for Medicare, you have a 7-month Initial Enrollment Period to sign up for Part A and/or Part B. If you&rsquo;re eligible for Medicare when you turn 65, you can sign up during the 7-month period that: </p> <ul> <li>Begins 3 months before the month you turn 65</li> <li>Includes the month you turn 65</li> <li>Ends 3 months after the month you turn 65</li> </ul> </> ), type: "medical", isRelevant: ({ personalInfo }) => personalInfo.age >= 64 && personalInfo.age <= 66, }, { id: "AK", title: "You can do non-medical withdrawals from your health savings account (HSA) without penalty", description: "After age 65, you can use your HSA withdrawal for non-medical expenses without paying the 20% tax penalty.", type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age >= 65, }, { id: "AL", title: "You're at your full retirement age", description: ( <p> You are eligible to draw Social Security benefits based on your record without penalty. <a href="https://www.ssa.gov/benefits/retirement/planner/agereduction.html" target="_blank" rel="noreferrer" > Check your exact full retirement age because it might be between 66 and 67. </a> </p> ), type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age >= 66 && personalInfo.age <= 67, }, { id: "AM", title: "You're past your full retirement age", description: "You are past your full retirement age and are eligible to draw Social Security benefits based on your record without penalty. Benefits are increased by a certain percentage for each month you delay starting your benefits beyond full retirement age until age 70.", type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age > 67 && personalInfo.age < 70, }, { id: "AN", title: "Invest enough in employer's retirement plan to get the match", description: "A match made by your employer is free money. This is a freebie you don't want to miss.", type: "retirement", isRelevant: ({ personalInfo, financialInfo }: Context): boolean => { if (personalInfo.age >= 65) { return false; } return financialInfo.expenses < financialInfo.income; }, }, { id: "AO", title: "Review eligibility of contributing to a health savings account (HSA)", description: "HSAs let you set aside money on a pre-tax basis to pay for qualified medical expenses. By using untaxed dollars in a Health Savings Account (HSA) to pay for deductibles, copayments, coinsurance, and some other expenses, you may be able to lower your overall health care costs.", type: "medical", isRelevant: ({ personalInfo, financialInfo }: Context): boolean => { if (personalInfo.age >= 65) { return false; } return financialInfo.expenses < financialInfo.income; }, }, { id: "AP", title: "Claim your Social Security benefits", description: "Social Security benefits are increased by a certain percentage for each month you delay starting your benefits beyond full retirement age until age 70. You are past that age and should no longer delay claiming Social Security on your record.", type: "social-security", isRelevant: ({ personalInfo }) => personalInfo.age >= 70, }, { id: "AQ", title: "Qualified charitable distribution (QCD)", description: "A QCD is a direct transfer of funds from your IRA custodian, payable to a qualified charity. QCDs can be counted toward satisfying your required minimum distributions (RMDs) for the year, as long as certain rules are met. A QCD excludes the amount donated from taxable income, which is unlike regular withdrawals from an IRA. Keeping your taxable income lower may reduce the impact to certain tax credits and deductions, including Social Security and Medicare.", type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age >= 71, }, { id: "AR", title: "Required minimum distribution (RMD)", description: ( <> <p> When you reach age 72, you&rsquo;re required to withdraw a certain amount of money from your retirement accounts each year. RMD rules apply to tax-deferred retirement accounts: </p> <ul> <li>Traditional IRAs</li> <li>Rollover IRAs</li> <li>SIMPLE IRAs</li> <li>SEP IRAs</li> <li>Most small-business accounts</li> <li>Most 401(k) and 403(b) plans</li> </ul> </> ), type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age >= 72, }, { id: "AS", title: "Confirm beneficiary designations are accurate", description: "A beneficiary designation is the description of the person or persons you want to receive a specific asset upon your death. Retirement accounts and insurance contracts have beneficiary designations. Confirm your beneficiary designations are correct to ensure your wishes are carried out.", type: "estate", isRelevant: () => true, }, { id: "AT", title: "Consider life insurance on each spouse", description: "The purpose of life insurance is to alleviate the financial consequences of premature death. Life insurance is almost always economically justified if you earn an income and others are financially dependent on that income for all or part of their financial support.", type: "insurance", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus === "married" && financialInfo.income > 0, }, { id: "AU", title: "Consider life insurance", description: "The purpose of life insurance is to alleviate the financial consequences of premature death. Life insurance is almost always economically justified if you earn an income and others are financially dependent on that income for all or part of their financial support.", type: "insurance", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus !== "married" && personalInfo.dependents > 0 && financialInfo.income > 0, }, { id: "AV", title: "Consider disability insurance on spouse with income", description: "The purpose of disability insurance is to provide income in the event that illness or injury prevents you or your spouse from producing the needed income for support. If you earn an income and others are financially dependent on that income for all or part of their financial support, you should consider disability insurance on the spouse with income.", type: "insurance", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus === "married" && financialInfo.income > 0, }, { id: "AW", title: "Consider disability insurance", description: "The purpose of disability insurance is to provide income in the event that illness or injury prevents you from producing the needed income for support. If you earn an income and others are financially dependent on that income for all or part of their financial support, you should consider disability insurance", type: "insurance", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus !== "married" && personalInfo.dependents > 0 && financialInfo.income > 0, }, { id: "AX", title: "Consider obtaining a will and/or trust, healthcare power of attorney, and durable power of attorney", description: "In the event of your death or incapacity, you want your family to be able to carry out your wishes as easily as possible. Additionally, you want to make sure your dependents are cared for by the individual(s) you trust. Proper estate documents ensure your family can carry out your wishes and provide adequate care for you individuals dependent on you.", type: "estate", isRelevant: ({ personalInfo }) => personalInfo.dependents > 0, }, { id: "AY", title: "Consider obtaining a will and/or trust, healthcare power of attorney, and durable power of attorney", description: "In the event of your death or incapacity, you want your family to be able to carry out your wishes as easily as possible. Proper estate documents ensure your family can carry out your wishes in a way you desire.", type: "estate", isRelevant: ({ personalInfo }) => personalInfo.dependents === 0, }, { id: "AZ", title: "Consider contributing to a 529 plan for college savings", description: "If your dependent is a minor and you plan on helping pay for college, contributing funds to a 529 plan could be a tax-efficient way to save and pay for college. Savings plans grow tax-deferred, and withdrawals are tax-free if they're used for qualified education expenses.", type: "education", isRelevant: ({ personalInfo }) => personalInfo.dependents > 0, }, { id: "Aa", title: "Consider contributing to a 529 plan for K-12 tuition", description: "If your dependent is a minor and you pay tuition for K-12 education, you are eligible to withdraw up to $10,000 tax-free from a 529 plan to pay for up to $10,000 per per year in K-12 tuition expenses. Some states also offer an additional tax benefit for families who use their 529 plan to pay for elementary or high school.", type: "education", isRelevant: ({ personalInfo }) => personalInfo.dependents > 0, }, { id: "Ab", title: "Consider a Roth IRA contribution", description: "A Roth IRA is an individual retirement account (IRA) that allows qualified withdrawals on a tax-free basis provided certain conditions are satisfied. Roth IRAs are funded with after-tax dollars; the contributions are not tax-deductible. But once you start withdrawing funds, the money is tax-free.", type: "retirement", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus !== "married" && personalInfo.age < 70 && financialInfo.income > financialInfo.expenses && financialInfo.income < 10417, }, { id: "Ac", title: "Consider a Roth IRA contribution for each spouse", description: "A Roth IRA is an individual retirement account (IRA) that allows qualified withdrawals on a tax-free basis provided certain conditions are satisfied. Roth IRAs are funded with after-tax dollars; the contributions are not tax-deductible. But once you start withdrawing funds, the money is tax-free. You may fund a Roth IRA on behalf of your married partner who earns little or no income. Spousal Roth IRA contributions are subject to the same rules and limits as regular Roth IRA contributions.", type: "retirement", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus === "married" && personalInfo.age < 70 && financialInfo.income > financialInfo.expenses && financialInfo.income < 16500, }, { id: "Ad", title: "Consider a backdoor Roth IRA contribution for each spouse", description: "A Roth IRA is an individual retirement account (IRA) that allows qualified withdrawals on a tax-free basis provided certain conditions are satisfied. Roth IRAs are funded with after-tax dollars; the contributions are not tax-deductible. But once you start withdrawing funds, the money is tax-free. You may fund a Roth IRA on behalf of your married partner who earns little or no income. Spousal Roth IRA contributions are subject to the same rules and limits as regular Roth IRA contributions. A backdoor Roth IRA contribution is an informal name for a complicated but IRS-sanctioned method for high-income taxpayers to fund a Roth, even if their incomes exceed the limits that the IRS allows for regular Roth contributions.", type: "retirement", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus === "married" && personalInfo.age < 70 && financialInfo.income > financialInfo.expenses && financialInfo.income >= 16500, }, { id: "Ae", title: "Consider a backdoor Roth IRA contribution", description: "A Roth IRA is an individual retirement account (IRA) that allows qualified withdrawals on a tax-free basis provided certain conditions are satisfied. Roth IRAs are funded with after-tax dollars; the contributions are not tax-deductible. But once you start withdrawing funds, the money is tax-free. A backdoor Roth IRA contribution is an informal name for a complicated but IRS-sanctioned method for high-income taxpayers to fund a Roth, even if their incomes exceed the limits that the IRS allows for regular Roth contributions.", type: "retirement", isRelevant: ({ personalInfo, financialInfo }) => personalInfo.maritalStatus !== "married" && personalInfo.age < 70 && financialInfo.income > financialInfo.expenses && financialInfo.income >= 10417, }, { id: "Af", title: "Consider a Roth conversion", description: "A Roth IRA conversion is a transfer of retirement assets from a qualified retirement account (Traditional IRA, SEP IRA, or SIMPLE IRA) into a Roth IRA, creating a taxable event. A Roth IRA conversion can be advantageous if you have large qualified retirement accounts and expect your future tax rate to stay at the same level or grow at the time you plan to start withdrawing from qualified retirement accounts. Roth IRAs allow for tax-free withdrawals of qualified distributions.", type: "retirement", isRelevant: ({ personalInfo }) => personalInfo.age < 72, }, { id: "Ag", title: "Check your credit reports", description: ( <p> Your credit report gives potential lenders information about you and your payment history, with recent activities receiving more consideration. By law, you&rsquo;re allowed to obtain your credit report once a year for free (go to{" "} <a href="https://annualcreditreport.com" target="_blank" rel="noreferrer" > annualcreditreport.com </a>{" "} to access yours). In reviewing your credit report, you want to make sure all your personal information and borrowing history is correct. </p> ), type: "credit", isRelevant: ({ personalInfo }) => personalInfo.age < 65, }, { id: "Ah", title: "Check your credit score", description: ( <p> Your credit score is an easy-to-digest number between 300 and 850 (the higher the better) that indicates the riskiness of lending you money. This score is used in combination with other data points (age and income) to decide whether or not to loan you money and at what rate. To check your score, you have a free option at{" "} <a href="https://creditkarma.com" target="_blank" rel="noreferrer"> creditkarma.com </a>{" "} or an option with a small fee at{" "} <a href="https://myfico.com" target="_blank" rel="noreferrer"> myfico.com </a> . </p> ), type: "credit", isRelevant: ({ personalInfo }) => personalInfo.age < 65, }, ]; export default tips;
import React, { useState, useContext } from 'react'; import { TaskContext } from './taskcontext'; // Import TaskContext const AddTask = () => { const { tasks, setTasks } = useContext(TaskContext); const [task, setTask] = useState(''); const [dueDate, setDueDate] = useState(null); // Optional for date input const handleSubmit = async (e) => { e.preventDefault(); try { const newTask = { text: task, dueDate, // Optional }; const response = await createTask(newTask); // Assuming createTask API function setTasks([...tasks, response.data]); // Update tasks with new task (replace with actual update logic) setTask(''); // Clear input field setDueDate(null); // Optional: Clear date input } catch (error) { console.error('Error adding task:', error); // Handle errors appropriately (e.g., display error message to user) } }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter task description" value={task} onChange={(e) => setTask(e.target.value)} required /> {/* ... other input fields and dateunit (if applicable) */} <button type="submit">Add Task</button> </form> ); }; export default AddTask;
import {expect} from 'chai'; import {describe, beforeEach, afterEach, it} from 'mocha'; import NumbersValidator from '../../app/numbers_validator.js'; describe('getEvenNumbersFromArray', () => { let validator; beforeEach(() => { validator = new NumbersValidator(); }); afterEach(() => { validator = null; }); // Positive it('it should return an array of even number', () => { const arrayNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const arrayNumberResult = validator.getEvenNumbersFromArray(arrayNumber); expect(arrayNumberResult).to.be.deep.eq([2, 4, 6, 8]); }); it('it should return an array of even number', () => { const arrayNumber = [-2, -0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9990]; const arrayNumberResult = validator.getEvenNumbersFromArray(arrayNumber); expect(arrayNumberResult).to.be.deep.eq([-2, -0, 0, 2, 4, 6, 8, 10, 9990]); }); it('it should return an array of even number', () => { const arrayNumber = [-2, -0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9990]; const arrayNumberResult = validator.getEvenNumbersFromArray(arrayNumber); expect(arrayNumberResult) .to.have.all.members([-2, -0, 0, 2, 4, 6, 8, 10, 9990]); }); it('it should return an empty array', () => { const emptyArrayResult = validator.getEvenNumbersFromArray([]); expect(emptyArrayResult).to.be.eql([]); }); it('should return an array of even numbers for negative numbers', () => { const arrayNumber = [-9, -8, -7, -6, -5, -4, -3, -2, -1]; const arrayNumberResult = validator.getEvenNumbersFromArray(arrayNumber); expect(arrayNumberResult).to.be.deep.eq([-8, -6, -4, -2]); }); it('should return an array of even numbers for decimal numbers', () => { const arrayNumber = [1.5, 2, 3.8, 4.3, 5.6]; const arrayNumberResult = validator.getEvenNumbersFromArray(arrayNumber); expect(arrayNumberResult).to.be.deep.eq([2]); }); it('should return an empty array when provided NaN and Infinity', () => { const arrayNumber = [NaN, Infinity]; const arrayNumberResult = validator.getEvenNumbersFromArray(arrayNumber); expect(arrayNumberResult).to.eql([]); }); // Negative it('should throw an error when provided string in array', () => { const arrayNumber = [1, '2', 3, 4, 5, 6, 7, 8, 9]; expect(() => { validator.getEvenNumbersFromArray(arrayNumber); }).to.throw(`[${arrayNumber}] is not an array of "Numbers"`); }); it('should throw an error when provided mixed value in array', () => { const arrayNumber = [1, '2', 3, true, 5, 6, false, null, {value: 9}]; expect(() => { validator.getEvenNumbersFromArray(arrayNumber); }).to.throw( `[${arrayNumber}] is not an array of "Numbers"`, ); }); });
class Compute { public String isSubset( long a1[], long a2[], long n, long m) { HashMap<Long, Integer> frequencyMap1 = new HashMap<>(); // Create a frequency map of elements in array a1 for (long num : a1) { frequencyMap1.put(num, frequencyMap1.getOrDefault(num, 0) + 1); } //System.out.println("Frequency Map of A1 is: "+frequencyMap1); // Check if all elements in a2 are present and have equal or greater frequency in a1 for (long num : a2) { int freqInA1 = frequencyMap1.getOrDefault(num, 0); // System.out.println("Frequency in A1: "+freqInA1); if (freqInA1 == 0) { return "No"; // If any element from a2 is not found in a1, return "No" } //Main Step to reduce already occured element's count frequencyMap1.put(num, freqInA1 - 1); // Reduce the frequency count in a1 } return "Yes"; // If all elements from a2 are found in a1 with equal or greater frequency, return "Yes" } }
package uni.UNIA088341; import io.dcloud.uniapp.*; import io.dcloud.uniapp.extapi.*; import io.dcloud.uniapp.framework.*; import io.dcloud.uniapp.runtime.*; import io.dcloud.uniapp.vue.*; import io.dcloud.uniapp.vue.shared.*; import io.dcloud.unicloud.*; import io.dcloud.uts.*; import io.dcloud.uts.Map; import io.dcloud.uts.Set; import io.dcloud.uts.UTSAndroid; import kotlinx.coroutines.CoroutineScope; import kotlinx.coroutines.Deferred; import kotlinx.coroutines.Dispatchers; import kotlinx.coroutines.async; import io.dcloud.uniapp.extapi.navigateTo as uni_navigateTo; open class GenPagesIndexIndex : BasePage { constructor(instance: ComponentInternalInstance) : super(instance) { onLoad(fun(_: OnLoadOptions) {}, instance); } @Suppress("UNUSED_PARAMETER") override fun `$render`(): VNode? { val _ctx = this; val _component_button = resolveComponent("button"); val _component_bgani = resolveEasyComponent("bgani", GenComponentsBganiBganiClass); return createVNode(_component_bgani, null, utsMapOf("default" to withCtx(fun(): UTSArray<Any> { return utsArrayOf( createElementVNode("view", utsMapOf("class" to "content"), utsArrayOf( createElementVNode("view", utsMapOf("class" to "btnGroup"), utsArrayOf( createElementVNode(Fragment, null, RenderHelpers.renderList(_ctx.btnList, fun(item, _, _): VNode { return createElementVNode("view", utsMapOf("class" to "btnitem"), utsArrayOf( createVNode(_component_button, utsMapOf("onClick" to fun(){ _ctx.navTo(item.id); } , "type" to "button", "style" to normalizeStyle(utsMapOf("border-radius" to "14rpx", "background-color" to item.btnColor, "color" to item.txtColor))), utsMapOf("default" to withCtx(fun(): UTSArray<Any> { return utsArrayOf( toDisplayString(item.btnName) ); } ), "_" to 2), 1032, utsArrayOf( "onClick", "style" )) )); } ), 256) )) )) ); } ), "_" to 1)); } open var btnList: UTSArray<btnItem> by `$data`; @Suppress("USELESS_CAST") override fun data(): Map<String, Any?> { return utsMapOf("btnList" to utsArrayOf<btnItem>(btnItem(id = 1, btnName = "探险/探索故事", btnColor = "linear-gradient(to right, #eee, #333)", txtColor = "#fff"), btnItem(id = 2, btnName = "武侠/古代故事", btnColor = "linear-gradient(to left, #eee, #333)", txtColor = "#fff"))); } override fun `$initMethods`() { this.navTo = fun(id: Number) { uni_navigateTo(NavigateToOptions(url = "/pages/chatView/chatView?id=" + id)); } ; } open lateinit var navTo: (id: Number) -> Unit; companion object { val styles: Map<String, Map<String, Map<String, Any>>> get() { return normalizeCssStyles(utsArrayOf( styles0 ), utsArrayOf( GenApp.styles )); } val styles0: Map<String, Map<String, Map<String, Any>>> get() { return utsMapOf("content" to utsMapOf("" to utsMapOf("display" to "flex", "alignItems" to "center", "justifyContent" to "center")), "btnGroup" to utsMapOf("" to utsMapOf("width" to "750rpx", "height" to "100%", "padding" to "45rpx", "display" to "flex", "flexDirection" to "row", "justifyContent" to "space-around", "alignItems" to "center")), "btnitem" to utsMapOf(".btnGroup " to utsMapOf("margin" to "15rpx 0", "boxShadow" to "4rpx 4rpx 24rpx #333"))); } } }
s3napback: Cycling, Incremental, Compressed, Encrypted Backups on Amazon S3 Manual for version 1.0 2008-05-07 Copyright (c) 2008 David Soergel <dev@davidsoergel.com> The problem ----------- In searching for a way to back up one of my Linux boxes to Amazon S3, I was surprised to find that none of the many backup methods and scripts I found on the net did what I wanted, so I wrote yet another one. The design requirements were: * Occasional full backups, and daily incremental backups * Stream data to S3, rather than making a local temp file first (i.e., if I want to archive all of /home at once, there's no point in making huge local tarball, doing lots of disk access in the process) * Break up large archives into manageable chunks * Encryption As far as I could tell, no available backup script (including, e.g. s3sync, backup-manager, s3backup, etc. etc.) met all four requirements. The closest thing is [js3tream](http://js3tream.sourceforge.net), which handles streaming and splitting, but not incrementalness or encryption. Those are both fairly easy to add, though, using tar and gpg, as [suggested] (http://js3tream.sourceforge.net/linux_tar.html) by the js3tream author. However, the s3backup.sh script he provides uses temp files (unnecessarily), and does not encrypt. So I modified it a bit to produce [s3backup-gpg-streaming.sh](s3backup-gpg-streaming.sh). That's not the end of the story, though, since it leaves open the problem of managing the backup rotation. I found the explicit cron jobs suggested on the js3tream site too messy, especially since I sometimes want to back up a lot of different directories. Some other available solutions will send incremental backups to S3, but never purge the old ones, and so use ever more storage. Finally, I wanted to easily deal with MySQL and Subversion dumps. The solution ------------ I wrote s3napback.pl, which wraps js3tream and solves all of the above issues by providing: * Dead-simple configuration * Automatic rotation of backup sets * Alternation of full and incremental backups (using "tar -g") * Integrated GPG encryption * No temporary files used anywhere, only pipes and TCP streams (optionally, uses smallish temp files to save memory) * Integrated handling of MySQL dumps * Integrated handling of Subversion repositories, and of directories containing multiple Subversion repositories. It's not rocket science, just a wrapper that makes things a bit easier. Prerequisites ------------- * Java 1.5 or above * gpg Quick Start ----------- Download and extract the s3napback package. There's no "make" or any such needed, so just extract it to some convenient location (I use /usr/local/s3napback). Configure it with your S3 login information by creating a file called e.g. /usr/local/s3napback/key.txt containing key=your AWS key secret=your AWS secret You'll need a GPG key pair for encryption. Create it with gpg --gen-key Since you'll need the secret key to decrypt your backups, you'll obviously need to store it in a safe place (see [the GPG manual](http://www.gnupg.org/gph/en/manual/c481.html)) If you'll be backing up a different machine from the one where you generated the key pair, export the public key: gpg --export me@example.com > backup.pubkey and import it on the machine to be backed up: gpg --import backup.pubkey gpg --edit-key backup@example.com then "trust" Create a configuration file something like this (descriptions of the options follow, if they're not entirely obvious): DiffDir /usr/local/s3napback/diffs Bucket dev.davidsoergel.com.backup1 GpgRecipient backup@davidsoergel.com S3Keyfile /usr/local/s3napback/key.txt ChunkSize 25000000 NotifyEmail me@example.com # not implemented yet LogFile /var/log/s3napback.log # not implemented yet LogLevel 2 # not implemented yet # make diffs of these every day, store fulls once a week, and keep two weeks <Cycle> Frequency 1 Phase 0 Diffs 7 Fulls 2 Directory /etc Directory /home/build Directory /home/notebook Directory /home/trac Directory /usr Directory /var </Cycle> # make diffs of these every week, store fulls once a month, and keep two months <Cycle> Frequency 7 Phase 0 Diffs 4 Fulls 2 Directory /bin Directory /boot Directory /lib Directory /lib64 Directory /opt Directory /root Directory /sbin </Cycle> # make a diff of this every day, store fulls once a week, and keep eight weeks <Directory /home/foobar> Frequency 1 Phase 0 Diffs 7 Fulls 8 Exclude /home/foobar/wumpus </Directory> # backup an entire machine <Directory /> Frequency 1 Phase 0 Diffs 7 Fulls 8 Exclude /proc Exclude /dev Exclude /sys Exclude /tmp </Directory> # store a MySQL dump of all databases every day, keeping 14. <MySQL all> Frequency 1 Phase 0 Fulls 14 </MySQL> # store a MySQL dump of a specific database every day, keeping 14. <MySQL mydatabase> Frequency 1 Phase 0 Fulls 14 </MySQL> # store a full dump of all Subversion repos every day, keeping 10. <SubversionDir /home/svn/repos> Frequency 1 Phase 0 Fulls 10 </SubversionDir> # store a full dump of a specific Subversion repo every day, keeping 10. <Subversion /home/svn/repos/myproject> Frequency 1 Phase 0 Fulls 10 </Subversion> To run it, just run the script, passing the config file with the -c option: ./s3snapback.pl -c s3snap.conf That's it! You can put that command in a cron job to run once a day. Note that gpg will look for a keyring under ~/.gnupg, but on some systems /etc/crontab sets the HOME environment variable to "/". So, you may want to change that to "/root"; or actually create and populate /.gnupg; or just use the GpgKeyring option in the s3napback config file to specify a keyring explicitly. Priniciples of operation ------------------------ The cycling of backup sets here is rudimentary, taking its inspiration from the cron job approach given on the js3tream page. The principle is that we'll sort the snapshots into a fixed number of "slots"; every new backup simply overwrites the oldest slot, so we don't need to explicitly purge old files. This is a fairly crappy schedule, in that the rotation doesn't decay over time. We just keep a certain number of daily backups (full or diff), and that's it. For my purposes, that's good enough for now; but I bet someone out there will figure out a clever means of producing a decaying schedule. Note also that the present scheme means that, once the oldest full backup is deleted, the diffs based on it will still be stored until they are overwritten, but may not be all that useful. For instance, if you do daily diffs and weekly fulls for two weeks, then at some point you'll go from this situation, where you can reconstruct your data for any day from the last two weeks (F = full, D = diff, time flowing to the right): FDDDDDDFDDDDDD to this one: DDDDDDFDDDDDDF where the full backup on which the six oldest diffs are based is gone, so in fact you can only fully reconstruct the last 8 days. You can still retrieve files that changed on the days represented by the old diffs, of course. Configuration ------------- First off you'll need some general configuration statements: * DiffDir a directory where tar can store its diff files (necessary for incremental backups). * Bucket the destination bucket on S3. * GpgRecipient the address of the public key to use for encryption. The gpg keyring of the user you're running the script as (i.e., root, for a systemwide cron job) must contain a matching key. * GpgKeyring path to the keyring file containing the public key for the GpgRecipient. Defaults to ~/.gnupg/pubring.gpg * S3KeyFile the file containing your AWS authentication keys. * ChunkSize the size of the chunks to be stored on S3, in bytes. Then you can specify as many directories, databases, and repositories as you like to be backed up. These may be contained in <Cycle> blocks, for the sake of reusing timing configuration, or may be blocks themselves with individual timings. * <Cycle name> <name> a unique identifier for the cycle. This is not used except to establish the uniqueness of each block. * Frequency <days> tells how often a backup should be made at all, in days. * Phase <days> Allows adjusting the day on which the backup is made, with respect to the frequency. Can take values 0 <= Phase < Frequency; defaults to 0. This can be useful, for instance, if you want to alternate daily backups between two backup sets. This can be accomplished by creating two nearly identical backup specifications, both with Frequency 2, but where one has a Phase of 0 and the other has a Phase of 1. * Diffs <number> tells how long the cycle between full backups should be. (Really there will be one fewer diffs than this, since the full backup that starts the cycle itself counts as one). * Fulls <number> tells how many total cycles to keep. * Directory <name> or <Directory name> <name> a directory to be backed up May appear as a property within a cycle block, or as a block in its own right, e.g. <Directory /some/path>. The latter case is just a shorthand for a cycle block containing a single Directory property. * MySQL <databasename> or <MySQL databasename> In order for this to work, the user you're running the script as must be able to mysqldump the requested databases without entering a password. This can be accomplished through the use of a .my.cnf file in the user's home directory. <databasename> names a single database to be backed up, or "all" to dump all databases. the Diffs property is ignored, since mysql dumps are always "full". * Subversion <repository> or <Subversion repository> In order for this to work, the user you're running the script as must have permission to svnadmin dump the requested repository. <repository> names a single svn repository to be backed up. the Diffs property is ignored, since svnadmin dumps are always "full". * SubversionDir <repository-dir> or <SubversionDir repository-dir> <repository-dir> a directory containing multiple subversion repositories, all of which should be backed up the Diffs property is ignored, since svnadmin dumps are always "full". (this feature was inspired by http://www.hlynes.com/2006/10/01/backups-part-2-subversion) Recovery -------- Recovery is not automated, but if you need it, you'll be motivated to follow this simple manual process. To retrieve a backup, use js3tream to download the files you need, then decrypt them with GPG, then extract the tarballs. Always start with the most recent FULL backup, then apply all available diffs in date order, regardless of the slot number. The procedure will be something along these lines: java -jar js3tream.jar --debug -n -f -v -K $s3keyfile -o -b $bucket:$name | gpg -d | tar xvz Note that because of the streaming nature of all this, you can extract part of an archive even if there's not enough disk space to store the entire archive. You'll still have to download the whole thing, unfortunately, since it's only at the tar stage that you can select which files will be restored. java -jar js3tream.jar --debug -n -f -v -K $s3keyfile -o -b $bucket:$name | gpg -d | tar xvz /path/to/desired/file Future Improvements ------------------- * Code could be a lot cleaner, handle errors better, etc. * Rotation schedule should be made decaying somehow * S3 uploads could be done in parallel, since that can speed things up a lot * Recovery could be automated Please let me know if you make these or any other improvements!
<script setup> import { onMounted, ref } from 'vue' import axios from 'axios' import cartMethods from "@/utils/cart"; const cart = ref([]) const isLoaded = ref(false) const getWishList = async () => { isLoaded.value = false const response = await axios.get('http://localhost:8000/api/wishlist/', { headers: { Authorization: `Bearer ${localStorage.getItem('access_token')}` } }) response.data.map(async (product) => { const { data } = await axios.get('http://localhost:8000/api/products/' + product) cart.value.push(data) }) console.log(cart.value); isLoaded.value = true } const removeItem = (id) => { cartMethods.removeFromCartById(id); cart.value = cartMethods.getCart(); } const clearCart = () => { cartMethods.clearCart(); cart.value = cartMethods.getCart(); } onMounted(async () => { await getWishList(); }) </script> <template> <section class="h-100 h-custom" style="background-color: #eee;"> <div class="container py-5 h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col"> <div class="card"> <div class="card-body p-4"> <div class="row"> <div class="col-lg-7"> <h5 class="mb-3"> <RouterLink to="/products" class="text-body"><i class="fas fa-long-arrow-alt-left me-2"></i>Continue shopping</RouterLink></h5> <hr> <div class="d-flex justify-content-between align-items-center mb-4"> <div> <p class="mb-1">Shopping cart</p> </div> <div> <div v-if="cart.length > 0"> <button @click="clearCart()" style="border: none;">Clear cart</button> </div> </div> </div> <div v-if="cart.length === 0"> <h3>Cart is empty</h3> </div> <div v-for="item in cart" :key="item.id"> <div class="card mb-3"> <div class="card-body"> <div class="d-flex justify-content-between"> <div class="d-flex flex-row align-items-center"> <div> <img :src="item.image" class="img-fluid rounded-3" :alt="item.title" style="width: 65px" /> </div> <div class="ms-3 "> <RouterLink :to="'products/' + item.id"><h6 >{{ item.title }}</h6> </RouterLink> </div> </div> <div class="d-flex flex-row align-items-center"> <div style="width: 80px;"> <h6 class="mb-0">{{item.price}}₸</h6> </div> <button @click="removeItem(item.id)"> <i class="bi bi-trash-fill "> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash-fill" viewBox="0 0 16 16"> <path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/> </svg> </i> </button> </div> </div> </div> </div> </div> </div> <div class="col-lg-5"> <div class="card bg-primary text-white rounded-3"> <div class="card-body"> <div class="d-flex justify-content-between align-items-center mb-4"> <h5 class="mb-0">Card details</h5> <img src="https://mdbcdn.b-cdn.net/img/Photos/Avatars/avatar-6.webp" class="img-fluid rounded-3" style="width: 45px;" alt="Avatar"> </div> <p class="small mb-2">Card type</p> <a href="#!" type="submit" class="text-white"><i class="fab fa-cc-mastercard fa-2x me-2"></i></a> <a href="#!" type="submit" class="text-white"><i class="fab fa-cc-visa fa-2x me-2"></i></a> <a href="#!" type="submit" class="text-white"><i class="fab fa-cc-amex fa-2x me-2"></i></a> <a href="#!" type="submit" class="text-white"><i class="fab fa-cc-paypal fa-2x"></i></a> <form class="mt-4"> <div class="form-outline form-white mb-4"> <input type="text" id="typeName" class="form-control form-control-lg" size="17" placeholder="Cardholder's Name" /> <label class="form-label" for="typeName">Cardholder's Name</label> </div> <div class="form-outline form-white mb-4"> <input type="text" id="typeText" class="form-control form-control-lg" size="17" placeholder="1234 5678 9012 3457" minlength="19" maxlength="19" /> <label class="form-label" for="typeText">Card Number</label> </div> <div class="row mb-4"> <div class="col-md-6"> <div class="form-outline form-white"> <input type="text" id="typeExp" class="form-control form-control-lg" placeholder="MM/YYYY" size="7" minlength="7" maxlength="7" /> <label class="form-label" for="typeExp">Expiration</label> </div> </div> <div class="col-md-6"> <div class="form-outline form-white"> <input type="password" id="typeText" class="form-control form-control-lg" placeholder="&#9679;&#9679;&#9679;" size="1" minlength="3" maxlength="3" /> <label class="form-label" for="typeText">CVV</label> </div> </div> </div> </form> <hr class="my-4"> <div class="d-flex justify-content-between"> <p class="mb-2">Subtotal</p> <p class="mb-2">{{cartMethods.getCartTotal()}} ₸</p> </div> <div class="d-flex justify-content-between"> <p class="mb-2">Shipping</p> <p class="mb-2">100 ₸</p> </div> <div class="d-flex justify-content-between mb-4"> <p class="mb-2">Total(Incl. taxes)</p> <p class="mb-2">{{cartMethods.getCartTotal() + 100}} ₸</p> </div> <button type="button" class="btn btn-info btn-block btn-lg"> <div class="d-flex justify-content-between"> <span>Checkout <i class="fas fa-long-arrow-alt-right ms-2"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/> </svg> </i></span>&nbsp;&nbsp; <span>{{cartMethods.getCartTotal() + 100}} ₸</span> </div> </button> </div> </div> </div> </div> </div> </div> </div> </div> </div> </section> </template> <style> @media (min-width: 1025px) { .h-custom { height: 100vh !important; } }</style>
#include "twig_hardware/twig_lib.hpp" twig_hardware::TwigLib::TwigLib(int i2c_bus, int i2c_address, std::string i2c_device) : i2c_bus(i2c_bus), i2c_address(i2c_address), i2c_device(i2c_device) { } twig_hardware::TwigLib::~TwigLib() { i2c_close_connection(); } // I2c bool twig_hardware::TwigLib::i2c_open_connection() { // TODO: Remove the line below and replace with a timeout // Ensure there is no pre-existing connection i2c_close_connection(); int connection = open(i2c_device.c_str(), O_RDWR); if (connection < 0) { return false; } if (ioctl(connection, I2C_SLAVE, i2c_address) < 0) { return false; } i2c_connection = connection; return true; } bool twig_hardware::TwigLib::i2c_close_connection() { if (i2c_connection != -1) { close(i2c_connection); i2c_connection = -1; return true; } return false; } bool twig_hardware::TwigLib::i2c_send(std::byte * data, int data_size) { i2c_open_connection(); // Send the I2C message if (write(i2c_connection, data, data_size) != data_size) { i2c_close_connection(); return false; } i2c_close_connection(); return true; } bool twig_hardware::TwigLib::i2c_read(std::byte * buffer, int data_size) { i2c_open_connection(); // Request the state from the i2c device if (read(i2c_connection, buffer, data_size) != data_size) { i2c_close_connection(); return false; } i2c_close_connection(); return true; } // Sync void twig_hardware::TwigLib::set_hardware_config(twig_hardware::TwigHardwareConfig hardware_config) { command.config = hardware_config; has_unpushed_commands_ = true; } bool twig_hardware::TwigLib::write_command(int max_retries, bool force) { if (!has_unpushed_commands_ && !force) { return true; } int fails = 0; while (true) { if (i2c_send(reinterpret_cast<std::byte *>(&command), sizeof(command))) { has_unpushed_commands_ = false; return true; } fails++; if (fails > max_retries) { return false; } } } bool twig_hardware::TwigLib::read_state(int max_retries) { int fails = 0; while (true) { twig_hardware::TwigState payload; if (i2c_read(reinterpret_cast<std::byte *>(&payload), sizeof(twig_hardware::TwigState))) { if (payload.integrityCheck == 85) { state = payload; return true; } } fails++; if (fails > max_retries) { return false; } } } // Hardware Reboot bool twig_hardware::TwigLib::driver_rebooted() { return (command.sessionId == 0) || (state.sessionId == 0); } bool twig_hardware::TwigLib::hardware_rebooted() { return !driver_rebooted() && (state.sessionId != command.sessionId); } void twig_hardware::TwigLib::acknowledge_hardware_reboot() { command.sessionId = state.sessionId; has_unpushed_commands_ = true; } // Utility double twig_hardware::TwigLib::raw_to_radians(int16_t raw) { return (((double) raw) / 4096.0) * 2 * M_PI; } double twig_hardware::TwigLib::degrees_to_radians(double degrees) { return degrees * M_PI / 180.0; } bool twig_hardware::TwigLib::respects_position_limits( double position, double velocity, Range limits) { if (velocity > 0 && position >= limits.max) { return false; } if (velocity < 0 && position <= limits.min) { return false; } return true; } // Converts the range [0, 2 * M_PI] to [-M_PI, M_PI] double twig_hardware::TwigLib::full_angle_to_center_angle(double angle) { return angle - M_PI; } // Applies an angular offset to an angle in the range [-M_PI, M_PI] double twig_hardware::TwigLib::apply_angular_offset(double angle, double offset) { double new_angle = angle + offset; if (new_angle > M_PI) { return new_angle - 2 * M_PI; } if (new_angle < -M_PI) { return new_angle + 2 * M_PI; } return new_angle; } // Current conversion when using the PSM current sensor double twig_hardware::TwigLib::raw_to_current_psm(uint16_t raw) { double input_voltage = raw * (microcontroller_ref_voltage / 1024.0); double corrected_input_voltage = input_voltage - psm_offset; double current = corrected_input_voltage * psm_sensitivity; return current; } // Current conversion when using the ACS70331 current sensor double twig_hardware::TwigLib::raw_to_current_acs(uint16_t raw) { double input_voltage = raw * (microcontroller_ref_voltage / 1024.0); double corrected_input_voltage = input_voltage - acs_offset; // Compared to the PSM the ACS sensor has a different formula for current calculation double current = corrected_input_voltage / acs_sensitivity; return current; } // TODO: Implement current estimation uint16_t twig_hardware::TwigLib::current_to_raw_psm(double current) { double corrected_input_voltage = current / psm_sensitivity; double input_voltage = corrected_input_voltage + psm_offset; return input_voltage * (1024.0 / microcontroller_ref_voltage); } // TODO: Implement current estimation uint16_t twig_hardware::TwigLib::current_to_raw_acs(double current) { double corrected_input_voltage = current * acs_sensitivity; double input_voltage = corrected_input_voltage + acs_offset; return input_voltage * (1024.0 / microcontroller_ref_voltage); } // TODO: Implement effort estimation double twig_hardware::TwigLib::current_to_effort(double current) { return current; } // Activate void twig_hardware::TwigLib::activate_shoulder_servo() { stop_shoulder_servo(); command.shoulderServoPowered = true; has_unpushed_commands_ = true; } void twig_hardware::TwigLib::activate_wrist_servo() { stop_wrist_servo(); command.wristServoPowered = true; has_unpushed_commands_ = true; } void twig_hardware::TwigLib::activate_gripper_servo() { stop_gripper_servo(); command.gripperServoPowered = true; has_unpushed_commands_ = true; } void twig_hardware::TwigLib::activate_all_servos() { activate_shoulder_servo(); activate_wrist_servo(); activate_gripper_servo(); } // Deactivate void twig_hardware::TwigLib::deactivate_shoulder_servo() { stop_shoulder_servo(); command.shoulderServoPowered = false; has_unpushed_commands_ = true; } void twig_hardware::TwigLib::deactivate_wrist_servo() { stop_wrist_servo(); command.wristServoPowered = false; has_unpushed_commands_ = true; } void twig_hardware::TwigLib::deactivate_gripper_servo() { stop_gripper_servo(); command.gripperServoPowered = false; has_unpushed_commands_ = true; } void twig_hardware::TwigLib::deactivate_all_servos() { deactivate_shoulder_servo(); deactivate_wrist_servo(); deactivate_gripper_servo(); } // Set velocity // TODO: Implement velocity control void twig_hardware::TwigLib::set_shoulder_servo_velocity(double velocity) { auto new_value = velocity * -200; if (!respects_position_limits( get_shoulder_servo_position(), new_value, jointConfig.shoulderLimits )) { new_value = 0; } if (command.shoulder != new_value) { has_unpushed_commands_ = true; command.shoulder = new_value; } } void twig_hardware::TwigLib::set_wrist_servo_velocity(double velocity) { auto new_value = velocity * -200; if (command.wrist != new_value) { has_unpushed_commands_ = true; command.wrist = new_value; } } void twig_hardware::TwigLib::set_gripper_servo_velocity(double velocity) { auto new_value = velocity * -200; if (!respects_position_limits( get_gripper_servo_position(), new_value, jointConfig.gripperLimits )) { new_value = 0; } if (command.gripper != new_value) { has_unpushed_commands_ = true; command.gripper = new_value; } } // Stop void twig_hardware::TwigLib::stop_shoulder_servo() { set_shoulder_servo_velocity(0); } void twig_hardware::TwigLib::stop_wrist_servo() { set_wrist_servo_velocity(0); } void twig_hardware::TwigLib::stop_gripper_servo() { set_gripper_servo_velocity(0); } void twig_hardware::TwigLib::stop_all_servos() { stop_shoulder_servo(); stop_wrist_servo(); stop_gripper_servo(); } // Get activation status double twig_hardware::TwigLib::get_shoulder_servo_activation_status() { return state.shoulderServoPowered; } double twig_hardware::TwigLib::get_wrist_servo_activation_status() { return state.wristServoPowered; } double twig_hardware::TwigLib::get_gripper_servo_activation_status() { return state.gripperServoPowered; } // Get current double twig_hardware::TwigLib::get_shoulder_servo_current() { return raw_to_current_psm(state.shoulderCurrent); } double twig_hardware::TwigLib::get_wrist_servo_current() { return raw_to_current_psm(state.wristCurrent); } double twig_hardware::TwigLib::get_gripper_servo_current() { return raw_to_current_acs(state.gripperCurrent); } // Get velocity double twig_hardware::TwigLib::get_shoulder_servo_velocity() { return degrees_to_radians(state.shoulderVelocity); } double twig_hardware::TwigLib::get_wrist_servo_velocity() { return degrees_to_radians(state.wristVelocity); } double twig_hardware::TwigLib::get_gripper_servo_velocity() { return degrees_to_radians(state.gripperVelocity); } // Get position double twig_hardware::TwigLib::get_shoulder_servo_position() { return apply_angular_offset( full_angle_to_center_angle(raw_to_radians(state.shoulderPosition)), jointConfig.shoulderOffset ); } double twig_hardware::TwigLib::get_wrist_servo_position() { return apply_angular_offset( full_angle_to_center_angle(raw_to_radians(state.wristPosition)), jointConfig.wristOffset ); } double twig_hardware::TwigLib::get_gripper_servo_position() { return apply_angular_offset( full_angle_to_center_angle(raw_to_radians(state.gripperPosition)), jointConfig.gripperOffset ); } // Get encoder magnitude double twig_hardware::TwigLib::get_shoulder_encoder_magnitude() { return state.shoulderEncoderMagnitude; } double twig_hardware::TwigLib::get_wrist_encoder_magnitude() { return state.wristEncoderMagnitude; } double twig_hardware::TwigLib::get_gripper_encoder_magnitude() { return state.gripperEncoderMagnitude; } // Get effort double twig_hardware::TwigLib::get_shoulder_servo_effort() { return current_to_effort(get_shoulder_servo_current()); } double twig_hardware::TwigLib::get_wrist_servo_effort() { return current_to_effort(get_wrist_servo_current()); } double twig_hardware::TwigLib::get_gripper_servo_effort() { return current_to_effort(get_gripper_servo_current()); }
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from flask_blog.config import DevelopmentConfig, TestingConfig from flask_migrate import Migrate from flask_pagedown import PageDown from flask_bootstrap import Bootstrap db = SQLAlchemy() migrate = Migrate() bcrypt = Bcrypt() pagedown = PageDown() login_manager = LoginManager() login_manager.login_view = 'users.login' login_manager.login_message_category = 'info' mail = Mail() def create_app(environment='testing'): app = Flask(__name__) if environment == 'development': app.config.from_object('flask_blog.config.DevelopmentConfig') elif environment == 'testing': app.config.from_object('flask_blog.config.TestingConfig') db.init_app(app) migrate.init_app(app, db) bcrypt.init_app(app) pagedown.init_app(app) login_manager.init_app(app) mail.init_app(app) Bootstrap(app) from flask_blog.app.users.routes import users from flask_blog.app.posts.routes import posts from flask_blog.app.main.routes import main from flask_blog.errors.error_handlers import errors from flask_blog.commands.users_crud_cli import users_crud app.register_blueprint(users) app.register_blueprint(posts) app.register_blueprint(main) app.register_blueprint(errors) app.register_blueprint(users_crud) return app
#include <stdio.h> #include <stdlib.h> #include <string.h> int n_entered = 0; void get_input(int *n, double arr[][*n]) { if (n_entered == 0) { printf("Enter n: "); scanf("%d", n); n_entered++; } if (arr != NULL) { printf("Enter the elements of the array:\n"); for (int i = 0; i < *n; i++) { for (int j = 0; j < *n; j++) { scanf("%lf", &arr[i][j]); } } } } void print_diag_elem(int n, double arr[n][n], char choice[]) { if (strcmp(choice, "main") == 0) { for (int i = 0; i < n; i++) { printf("%.2lf ", arr[i][i]); } } else if (strcmp(choice, "other") == 0) { for (int i = 0; i < n; i++) { printf("%.2lf ", arr[i][n - i - 1]); } } else if (strcmp(choice, "elements above") == 0) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { printf("%.2lf ", arr[i][j]); } } } else if (strcmp(choice, "elements below") == 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { printf("%.2lf ", arr[i][j]); } } } else { printf("ERROR: Invalid value for 'choice' in print_diag_elem function."); } } void zad_1() { int n; get_input(&n, NULL); double arr[n][n]; get_input(&n, arr); printf("Main Diagonal: "); print_diag_elem(n, arr, "main"); printf("\nOther Diagonal: "); print_diag_elem(n, arr, "other"); printf("\nElements above main diagonal: "); print_diag_elem(n, arr, "elements above"); printf("\nElements below other diagonal: "); print_diag_elem(n, arr, "elements below"); } int zad_2() { int n; get_input(&n, NULL); double arr[n][n]; get_input(&n, arr); double sum = 0; for (int i = 0; i < n; i++) { sum += arr[0][i]; } for (int i = 0; i < n; i++) { double row_sum = 0, col_sum = 0; for (int j = 0; j < n; j++) { row_sum += arr[i][j]; col_sum += arr[j][i]; } if (row_sum != sum || col_sum != sum) { printf("The square is not magic\n"); return 0; } } double diag1_sum = 0, diag2_sum = 0; for (int i = 0; i < n; i++) { diag1_sum += arr[i][i]; } for (int i = 0; i < n; i++) { diag2_sum += arr[i][n - i - 1]; } if (diag1_sum != sum || diag2_sum != sum) { printf("The square is not magic\n"); return 0; } printf("The square is magic\n"); } int main() { zad_1(); return 0; }
import {{pascalCase schemaName}}, { {{pascalCase schemaName}}Attributes } from '@modules/{{camelCase moduleName}}/infra/mongoose/schemas/{{pascalCase schemaName}}.schema' import I{{pascalTableName}}, { CreateProps, FindByIdProps, UpdateProps, DeleteProps } from '@modules/{{camelCase moduleName}}/repositories/interfaces/I{{pascalTableName}}.interface' export default class {{pascalCase schemaName}}Repository implements I{{pascalTableName}} { async create ({ content }: CreateProps): Promise<{{pascalCase schemaName}}Attributes> { return {{pascalCase schemaName}}.create({ content }) } async findAll (): Promise<{{pascalCase schemaName}}Attributes[]> { return {{pascalCase schemaName}}.find() } async findById ({ id }: FindByIdProps): Promise<{{pascalCase schemaName}}Attributes> { return {{pascalCase schemaName}}.findOne({ _id: { $ne: id } }) } async update ({ {{camelCase moduleName}} }: UpdateProps): Promise<{{pascalCase schemaName}}Attributes> { const id = {{camelCase moduleName}}._id return {{pascalCase schemaName}}.findByIdAndUpdate(id, {{camelCase moduleName}}, { new: true }) } async delete ({ id }: DeleteProps): Promise<{{pascalCase schemaName}}Attributes> { return {{pascalCase schemaName}}.findByIdAndDelete(id) } }
use uo; include "include/dotempmods"; exported function GetLifeRegenRate (character) // 1 point per 5 seconds // ... is 12 points per minute // ... is 1200 hundredths per minute //No regen if poisoned if (character.poisoned) return 0; endif //NPCs regenerate faster if they have more HP if (!character.acctname) if (GetAttributeBaseValue (character, "Strength") < 1500) return 1200; endif return (CINT (GetAttributeBaseValue (character, "Strength")/10) * 12); endif var racialbonus := 0; if (character.race == RACE_HUMAN) racialbonus := 1200; endif //If they're hungry, don't regenerate HP as fast or at all var hunger := CINT (GetObjProperty (character, "hunger")); if (!hunger) hunger := 0; endif if (hunger >= 9) return 0+racialbonus; elseif (hunger >= 7) return 600+racialbonus; elseif (hunger > 5) return 1000+racialbonus; endif return 1200+racialbonus; endfunction exported function GetLifeMaximumValue(character) //Do a stat cap on players var playerbonus := 0; if (character.acctname) if (!character.cmdlevel) var maxstr := GetObjProperty (character, "maxstr"); if (!maxstr) maxstr := 75; endif if (GetAttributeBaseValue (character, "Strength") > maxstr * 10); SetAttributeBaseValue (character, "Strength", maxstr*10); endif endif playerbonus := 50; elseif (GetObjProperty (character, "BonusMaxHP")) //permanent bonus MaxHP, usually for NPCs var bonusmaxhp := GetObjProperty (character, "BonusMaxHP"); return (GetAttribute (character, "Strength") + bonusmaxhp) * 100; endif //possible bonus MaxHP from spell effects if (GetObjProperty (character, "longtermmods")) var bonusmaxhp := 0; var tempmods := GetObjProperty (character, "longtermmods"); foreach submod in tempmods if (submod[1] == "BonusMaxHP" or submod[1] == "cBonusMaxHP") bonusmaxhp := bonusmaxhp + submod[2]; endif endforeach if (bonusmaxhp) return (GetAttribute (character, "Strength") + playerbonus + bonusmaxhp) * 100; endif endif return (GetAttribute (character, "Strength") + playerbonus) * 100; endfunction exported function GetStaminaRegenRate (character) //(Almost) no regen if poisoned if (character.poisoned) return 100; endif //Ignore all this for NPCs if (!character.acctname) return 1200; endif var racialbonus := 0; var stamregenbonus := racialbonus + GetAttribute (character, ATTRIBUTEID_FOCUS)*60; //If they're hungry, don't regenerate stamina as fast or at all var hunger := CINT (GetObjProperty (character, "hunger")); if (!hunger) hunger := 0; endif if (hunger >= 9) return 100 + stamregenbonus; elseif (hunger >= 7) return 600 + stamregenbonus; endif //If the last thing they ate was a high food value item, they regenerate stamina faster var foodregen := GetObjProperty (character, "#dotempmod_stamina_regen_rate"); if (!foodregen) return 1200 + stamregenbonus; endif return foodregen + stamregenbonus; endfunction exported function GetStaminaMaximumValue(character) //Do a stat cap on players if (character.acctname) if (!character.cmdlevel) var maxdex := GetObjProperty (character, "maxdex"); if (!maxdex) maxdex := 75; endif if (GetAttributeBaseValue (character, "Dexterity") > maxdex * 10); SetAttributeBaseValue (character, "Dexterity", maxdex*10); endif endif elseif (GetObjProperty (character, "BonusMaxStam")) //permanent bonus MaxStam, usually for NPCs var bonusmaxstam := GetObjProperty (character, "BonusMaxStam"); return (GetAttribute (character, "Dexterity") + bonusmaxstam) * 100; endif //possible bonus MaxStamina from spell effects if (GetObjProperty (character, "longtermmods")) var bonusmaxstam := 0; var tempmods := GetObjProperty (character, "longtermmods"); foreach submod in tempmods if (submod[1] == "BonusMaxStam" or submod[1] == "cBonusMaxStam") bonusmaxstam := bonusmaxstam + submod[2]; endif endforeach if (bonusmaxstam) return (GetAttribute (character, "Dexterity") + bonusmaxstam) * 100; endif endif return GetAttribute (character, "Dexterity") * 100; endfunction exported function GetManaRegenRate(character) //No regen if poisoned if (character.poisoned) return 0; endif //Ignore all this for NPCs // if (!character.acctname) // return 1200; // endif var racialbonus := 0; if (character.race == RACE_GARGOYLE) racialbonus := 1200; endif var manaregenbonus := 0; // check for medable armor pending... must figure out a faster way. // if () manaregenbonus := ((GetAttribute (character, ATTRIBUTEID_MEDITATION)* 3) + GetAttribute (character, "Intelligence"))*15; // endif manaregenbonus := manaregenbonus + racialbonus + (GetAttribute (character, ATTRIBUTEID_FOCUS)*30); //If they're hungry, don't regenerate mana as fast or at all var hunger := CINT (GetObjProperty (character, "hunger")); if (!hunger) hunger := 0; endif if (hunger >= 9) return 0+manaregenbonus; elseif (hunger >= 7) return 600+manaregenbonus; elseif (hunger > 5) return 1000+manaregenbonus; endif return 1200+manaregenbonus; endfunction exported function GetManaMaximumValue(character) //Do a stat cap on players if (character.acctname) if (!character.cmdlevel) var maxint := GetObjProperty (character, "maxint"); if (!maxint) maxint := 75; endif if (GetAttributeBaseValue (character, "Intelligence") > maxint * 10); SetAttributeBaseValue (character, "Intelligence", maxint*10); endif endif elseif (GetObjProperty (character, "BonusMaxMana")) //permanent bonus MaxMana, usually for NPCs var bonusmaxmana := GetObjProperty (character, "BonusMaxMana"); return (GetAttribute (character, "Intelligence") + bonusmaxmana) * 100; endif var racialbonus := 0; if (character.race == RACE_ELF) racialbonus := 50; endif //possible bonus MaxMana from spell effects if (GetObjProperty (character, "longtermmods")) var bonusmaxmana := 0; var tempmods := GetObjProperty (character, "longtermmods"); foreach submod in tempmods if (submod[1] == "BonusMaxMana" or submod[1] == "cBonusMaxMana") bonusmaxmana := bonusmaxmana + submod[2]; endif endforeach if (bonusmaxmana) return (GetAttribute (character, "Intelligence") + bonusmaxmana + racialbonus) * 100; endif endif return (GetAttribute (character, "Intelligence")+racialbonus) * 100; endfunction program regen() return 1; endprogram
import React, { useState } from "react"; import { useQuery, useMutation } from "@apollo/client"; import { GET_GOALS } from "../utils/queries"; import { CREATE_GOAL } from "../utils/mutations"; import AuthService from "../utils/auth"; import '../assets/Goal.css'; function GoalManagement() { const [goalInput, setGoalInput] = useState({ name: "", description: "", dueDate: "", activityId: "", }); const [selectedActivity, setSelectedActivity] = useState(""); const [createdGoal, setCreatedGoal] = useState(null); const { loading, error, data, refetch } = useQuery(GET_GOALS, { variables: { userId: AuthService.getUserId() }, }); const [createGoal] = useMutation(CREATE_GOAL); const handleInputChange = (e) => { const { name, value } = e.target; if (name === "activityId") { setSelectedActivity(value); } else { setGoalInput({ ...goalInput, [name]: value }); } }; const createNewGoal = async () => { try { const { data: { createGoal: newGoal } } = await createGoal({ variables: { goalInput: { ...goalInput, activityId: selectedActivity, }, }, }); setCreatedGoal(newGoal); setGoalInput({ name: "", description: "", dueDate: "", activityId: "", }); setSelectedActivity(""); refetch(); } catch (error) { console.error("Error creating goal:", error); } }; if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <h2>Goal Management</h2> <form onSubmit={createNewGoal}> <label> Goal Name: <input type="text" name="name" value={goalInput.name} onChange={handleInputChange} required /> </label> <label> Description: <textarea name="description" value={goalInput.description} onChange={handleInputChange} /> </label> <label> Due Date: <input type="date" name="dueDate" value={goalInput.dueDate} onChange={handleInputChange} required /> </label> <label> Activity: <select name="activityId" value={selectedActivity} // Use selectedActivity as the value onChange={handleInputChange} required > <option value="" disabled> Select an activity </option> {data.activities && data.activities.map((activity) => ( <option key={activity._id} value={activity._id}> {activity.title} </option> ))} </select> </label> <button type="submit" className='btn-goal'>Create Goal</button> </form> {createdGoal && ( // Display the created goal if it exists <div> <h3>Created Goal:</h3> <p>Name: {createdGoal.name}</p> <p>Description: {createdGoal.description}</p> <p>Due Date: {createdGoal.dueDate}</p> <p>Activity: {createdGoal.activityId}</p> </div> )} {data.goals.map((goal) => ( <div key={goal._id}> <p>{goal.name}</p> {/* Display other goal details */} </div> ))} </div> ); } export default GoalManagement;
import { ReactNode, useEffect, useState } from 'react'; import { SortableContainer, SortableElement, SortableHandle, arrayMove, } from 'react-sortable-hoc'; import { Space } from 'antd'; import './index.less'; const DragHandle = SortableHandle(() => ( <i className="iconfont spicon-drag2 core-form-drag-list-item-icon" /> )); const SortContainer = SortableContainer((props: any) => ( <div className="core-form-drag-list" {...props} /> )); interface DragListProps { /** * 列表数据源 * @default [] */ list: { /** 唯一标识 */ key: string | number; /** 显示文案 */ label: ReactNode | string; }[]; /** 列顺序改变事件 */ onChange?: Function; /** 点击事件事件 */ onClick?: Function; /** 默认选中 */ defaultActiveKey?: string | number; /** * 是否展示图标 * @default true */ showIcon?: boolean; } export default ({ list = [], onChange, onClick, defaultActiveKey, showIcon = true, }: DragListProps) => { const [activeKey, setActiveKey] = useState(defaultActiveKey); const [innerList, setInnerList] = useState([...list]); const SortableItem = SortableElement((props: any) => ( <div className="core-form-drag-list-item" {...props} onClick={(e) => { setActiveKey(props.value.key); onClick?.(props.value, e); }} /> )); useEffect(() => { setInnerList([...list]); }, [list]); // 拖拽结束 const onSortEnd = ({ oldIndex, newIndex, }: { oldIndex: number; newIndex: number; }) => { if (oldIndex !== newIndex) { const newData = arrayMove([...innerList], oldIndex, newIndex); setInnerList([...newData]); onChange?.(newData); } }; return ( <div className="core-form-drag-list"> <SortContainer distance={1} onSortEnd={onSortEnd} helperClass="core-form-drag-item-dragging" > {innerList.map((i, index) => { return ( <SortableItem index={index} key={i.key} value={i}> <Space> {showIcon && <DragHandle />} <div className={ activeKey === i.key ? 'core-form-drag-list-item-active-label' : 'core-form-drag-list-item-label' } > {i.label} </div> </Space> </SortableItem> ); })} </SortContainer> </div> ); };
const detectEndpoint = async (force = false) => { const endpoint = sessionStorage.getItem("endpoint"); if (!endpoint || force) { const myHeaders = new Headers(); myHeaders.append("accept-language", "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,ru;q=0.6"); myHeaders.append("cache-control", "no-cache"); myHeaders.append("pragma", "no-cache"); myHeaders.append("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"); const requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; try { const htmlResponse = await fetch("https://cors-anywhere.herokuapp.com/https://crudcrud.com/", requestOptions).then(response => response.text()); const tempElement = document.createElement('div'); tempElement.innerHTML = htmlResponse; const newEndpoint = tempElement.querySelector(".endpoint-url").textContent.replaceAll(/\s|https\:\/\/crudcrud\.com\/api\//g, ""); sessionStorage.setItem("endpoint", newEndpoint); } catch (error) { sessionStorage.setItem("endpoint", ""); alert("erro ao obter conexão com a API"); } } } detectEndpoint(); const getUsers = async () => { const endpoint = sessionStorage.getItem("endpoint"); const requestOptions = { method: 'GET', redirect: 'follow' }; const users = await fetch(`https://crudcrud.com/api/${endpoint}/users`, requestOptions).then(response => response.json()); return users; } const createUser = async (name = "", surname = "", birthday = "", email = "", user = "", password = "") => { const endpoint = sessionStorage.getItem("endpoint"); const someEmptyParam = [name, surname, birthday, email, user, password].some(param => param === ""); if (someEmptyParam) { return { "status": false, "data": {}, "message": { "error": "Some empty parameter", "message": "" } }; } const myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); const raw = JSON.stringify({ "name": name, "surname": surname, "birthday": birthday, "email": email, "user": user, "password": password }); const requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; const response = await fetch(`https://crudcrud.com/api/${endpoint}/users`, requestOptions).then(response => response.json()); return { "status": true, "data": response, "message": { "error": "", "message": "user created successfully" } }; } const deleteUser = async (userId = "") => { const endpoint = sessionStorage.getItem("endpoint"); if (userId === "") { return { "status": false, "data": {}, "message": { "error": "Some empty parameter", "message": "" } }; } const requestOptions = { method: 'DELETE', redirect: 'follow' }; const req = await fetch(`https://crudcrud.com/api/${endpoint}/users/${userId}`, requestOptions); if (req.status !== 200) { return { "status": false, "data": {}, "message": { "error": "unknown error when deleting user", "message": "" } }; } return { "status": true, "data": {}, "message": { "error": "", "message": "user successfully deleted" } }; } const updateUser = async (name = "", surname = "", birthday = "", email = "", user = "", password = "", _id = "") => { const endpoint = sessionStorage.getItem("endpoint"); const someEmptyParam = [name, surname, birthday, email, user, password, _id].some(param => param === ""); if (someEmptyParam) { return { "status": false, "data": {}, "message": { "error": "Some empty parameter", "message": "" } }; } const myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); const raw = JSON.stringify({ "name": name, "surname": surname, "birthday": birthday, "email": email, "user": user, "password": password }); const requestOptions = { method: 'PUT', headers: myHeaders, body: raw, redirect: 'follow' }; const req = await fetch(`https://crudcrud.com/api/${endpoint}/users/${_id}`, requestOptions); if (req.status !== 200) { return { "status": false, "data": {}, "message": { "error": "unknown error when deleting user", "message": "" } }; } return { "status": true, "data": {name, surname, birthday, email, user, password, _id}, "message": { "error": "", "message": "user created successfully" } }; }
const API_KEY = 'api_key=3646c928b1d09ad843c146504a0749e0'; const BASE_URL = 'https://api.themoviedb.org/3'; const API_URL = BASE_URL + '/discover/movie?sort_by=popularity.desc&'+API_KEY; const IMG_URL = 'https://image.tmdb.org/t/p/w500'; const SEARCH_URL = BASE_URL + '/search/movie?'+API_KEY const main = document.getElementById("main") const form = document.getElementById("form") const search = document.getElementById("search") const prevButton = document.getElementById("prev-page") const nextButton = document.getElementById("next-page") getMovies(API_URL); function getMovies(url) { fetch(url).then(res => res.json()).then(data =>{ console.log(data.results); if (data.results.length !== 0) { showMovies(data.results); current_page = data.page; next_page = current_page + 1; prev_page = current_page - 1; total_pages = data.total_pages if (current_page <= 1) { prevButton.style.display = "none"; nextButton.style.display = "block"; nextButton.onclick = function() {pageCall(url, next_page)} } else if (current_page < total_pages) { prevButton.style.display = "block" nextButton.style.display = "block" nextButton.onclick = function() {pageCall(url, next_page)} prevButton.onclick = function() {pageCall(url, prev_page)} } } else { main.innerHTML =`<h4>Pencarian tidak ditemukan</h4>`; prevButton.style.display = "none"; nextButton.style.display = "none"; } }) } function showMovies(data) { main.innerHTML =``; data.forEach(movie => { const{id, title, poster_path, popularity, overview, release_date} = movie; const movieFormat = document.createElement('div'); movieFormat.className = 'movie' movieFormat.onclick = function() {showModal(id);} movieFormat.innerHTML = ` <img src="${IMG_URL+poster_path}" alt="${title} poster" /> <div class="movie-info"> <h3 id="popularity" class="popularity">${popularity} popularity</h3> <h2 id="title">${title}</h2> </div> `; main.appendChild(movieFormat); const modalFormat = document.createElement('div'); modalFormat.id = id modalFormat.className = 'modal' modalFormat.innerHTML = ` <div class="modal-content"> <span class="close" onclick='closeModal(${id})'>&times;</span> <img src="${IMG_URL+poster_path}" alt="${title} poster" /> <div class="modal-movie-info"> <h1 id="title" class="movie-title">${title}</h1> <div class="modal-movie-detail"> <h3 id="date" class="release-date">${release_date} |</h3> <h3 id="popularity" class="movie-popularity">${popularity} popularity</h3> </div> </div> <p class="movie-desc"> ${overview} </p> </div> `; main.appendChild(modalFormat); }); } function showModal(id) { var modal = document.getElementById(id) modal.style.display = "block"; window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } } function closeModal(id) { var modal = document.getElementById(id) modal.style.display = "none"; } form.addEventListener('submit', (e) => { e.preventDefault(); const searchTerm = search.value; if(searchTerm) { getMovies(SEARCH_URL+'&query='+searchTerm) }else{ getMovies(API_URL); } }) function pageCall(url, page) { page = page.toString() getMovies(url+'&page='+page) }
import discord from discord.ext import commands import random # Cogs are used to make categories col = discord.Color.purple() class Actions(commands.Cog): def footer(self): return f"!help fun [command] for more information" @commands.group() async def fun(self, ctx): if ctx.invoked_subcommand is None: await ctx.send(f"```{ctx.subcommand_passed} doesn't belong to fun\n\nFor more info on a specific command, use {'*help*'} command```") # * ------------------------------------------------------------------- @fun.command() async def slap(self, ctx, who : discord.Member, *reason): li = [ 'https://media.tenor.com/aCZMe2OKWX0AAAAC/fail-water.gif', 'https://media.tenor.com/pUatwfgNCZUAAAAd/fish-slap-w2s.gif', 'https://media.tenor.com/pmCZDX1MB1gAAAAC/johnny-knoxville-slap.gif', 'https://media.tenor.com/83tH-nXQeAMAAAAC/fish-slap.gif', 'https://media.tenor.com/-RSry4HDatUAAAAC/slap-out-kast.gif', 'https://media.tenor.com/__oycZBexeAAAAAC/slap.gif', 'https://media.tenor.com/WsKM5ZDigvgAAAAC/penguin-penguins.gif', 'https://media.tenor.com/tKF3HiguDmEAAAAC/wrrruutchxxxxiii-slapt.gif', 'https://media.tenor.com/2L_eT6hPUhcAAAAC/spongebob-squarepants-patrick-star.gif', 'https://media.tenor.com/fw6gs_ia_UIAAAAd/slap-slapping.gif', 'https://media.tenor.com/OXFdOzVbsW0AAAAC/smack-you.gif', 'https://media.tenor.com/R6LaPVpPwfcAAAAd/slap-slapping.gif', 'https://media.tenor.com/zdNVA6sB53AAAAAC/molorant-ckaz.gif', 'https://media.tenor.com/E3OW-MYYum0AAAAC/no-angry.gif', 'https://media.tenor.com/2-r7BEc-cb8AAAAC/slap-smack.gif', 'https://media.tenor.com/rVXByOZKidMAAAAd/anime-slap.gif', 'https://media.tenor.com/Ws6Dm1ZW_vMAAAAC/girl-slap.gif', 'https://media.tenor.com/5jBuDXkDsjYAAAAC/slap.gif', 'https://media.tenor.com/eU5H6GbVjrcAAAAC/slap-jjk.gif', 'https://media.tenor.com/0yMtzZ0GUGsAAAAC/hyouka-good.gif' ] embed = discord.Embed( colour=col, title=f"{ctx.author.display_name} slaps {who.display_name} for being {' '.join(reason)}" ) embed.set_author(name = ctx.author.display_name ,icon_url=ctx.author.display_avatar.url) embed.set_image(url=random.choice(li)) await ctx.send(embed=embed) # * ------------------------------------------------------------------- @fun.command () async def say(self, ctx, *what): embed = discord.Embed( colour=col, # description=, title=" ".join(what) # bot will send the same message as user ) embed.set_author(name = ctx.author.display_name, icon_url=ctx.author.display_avatar.url) # embed.set_footer(text=self.footer()) # embed.set_thumbnail(url=str(ctx.author.display_avatar.url)) await ctx.send(embed = embed) # * ------------------------------------------------------------------- @fun.command () async def choice(self, ctx, *options): embed = discord.Embed( color=col, title="I'll be choosing ", description=random.choice(options)+"!" ) embed.set_author(name = ctx.author.display_name, icon_url=ctx.author.display_avatar.url) await ctx.send(embed = embed) # * ------------------------------------------------------------------- # * ------------------------------------------------------------------- async def setup(bot): await bot.add_cog(Actions(bot))
function renderLicenseBadge(license) { if (license !== "None") { return `![Github license](https://img.shields.io/badge/license-${license}-olive.svg)`; } return ""; } function generateMarkdown(data) { return `# ${data.title} ${renderLicenseBadge(data.license)} ## Description ${data.description} ## Table of Contents * [Description](#description) * [Languages](#languages) * [Installation](#installation) * [Usage](#usage) * [License](#license) * [Contribution](#contributing) * [Test](#test) * [Contact](#contact) ## Languages ${data.languages} ## Installation ${data.installation} ## Usage ${data.usage} ## License ${data.license} ## Contribution ${data.contributing} ## Test ${data.test} ## Contact Please feel free to reach out if you have any questions. -[Github]('https://github.com/${data.github}')<br/> -[Email]('https://github.com/${data.email}') <br/> ### This generator is created by Masihullah Omer.👏🏻 `; } module.exports = generateMarkdown;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const transfer_status_enum_1 = require("../enums/transfer-status.enum"); class ChunkTransferHelper { constructor(io, importStepHelper, transfersRepository) { this.io = io; this.importStepHelper = importStepHelper; this.transfersRepository = transfersRepository; } async transfer(params) { let { import: impt, transfer, datasets, chunkLength } = params; const { id: transferId, offset } = transfer; let slicedDatasets = datasets.slice(offset, datasets.length); datasets = null; const chunkedDatasets = this.chunkObjectArray(slicedDatasets, chunkLength); slicedDatasets = null; while (chunkedDatasets.length) { const refreshedTransfer = await this.transfersRepository.load(transferId); if (refreshedTransfer.status === transfer_status_enum_1.TransferStatus.PAUSED) { this.io.to(String(transferId)).emit('transfer', { ...refreshedTransfer, log: refreshedTransfer.log[0] || [] }); return; } const datasetsChunk = chunkedDatasets.shift(); await this.importStepHelper.step(impt, refreshedTransfer, datasetsChunk); } const completedTransfer = await this.transfersRepository.update({ id: transferId, status: transfer_status_enum_1.TransferStatus.COMPLETED }); this.io.to(String(transferId)).emit('transfer', { ...completedTransfer, log: completedTransfer.log[0] || [] }); } // chunkObjectArray([1,2,3,4,5,6,7,8,9], 3) => [[1,2,3],[4,5,6],[7,8,9]] chunkObjectArray(array, chunkLength) { const chunkedArray = []; for (let i = 0; i < array.length; i += chunkLength) { const chunk = array.slice(i, i + chunkLength); chunkedArray.push(chunk); } return chunkedArray; } } exports.default = ChunkTransferHelper; //# sourceMappingURL=chunk-transfer.helper.js.map
--- title: folders section: 5 description: Folder Structures Used by npm --- ### Description npm puts various things on your computer. That's its job. This document will tell you what it puts where. #### tl;dr * Local install (default): puts stuff in `./node_modules` of the current package root. * Global install (with `-g`): puts stuff in /usr/local or wherever node is installed. * Install it **locally** if you're going to `require()` it. * Install it **globally** if you're going to run it on the command line. * If you need both, then install it in both places, or use `npm link`. #### prefix Configuration The [`prefix` config](/using-npm/config#prefix) defaults to the location where node is installed. On most systems, this is `/usr/local`. On Windows, it's `%AppData%\npm`. On Unix systems, it's one level up, since node is typically installed at `{prefix}/bin/node` rather than `{prefix}/node.exe`. When the `global` flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already. #### Node Modules Packages are dropped into the `node_modules` folder under the `prefix`. When installing locally, this means that you can `require("packagename")` to load its main module, or `require("packagename/lib/path/to/sub/module")` to load other modules. Global installs on Unix systems go to `{prefix}/lib/node_modules`. Global installs on Windows go to `{prefix}/node_modules` (that is, no `lib` folder.) Scoped packages are installed the same way, except they are grouped together in a sub-folder of the relevant `node_modules` folder with the name of that scope prefix by the @ symbol, e.g. `npm install @myorg/package` would place the package in `{prefix}/node_modules/@myorg/package`. See [`scope`](/using-npm/scope) for more details. If you wish to `require()` a package, then install it locally. #### Executables When in global mode, executables are linked into `{prefix}/bin` on Unix, or directly into `{prefix}` on Windows. Ensure that path is in your terminal's `PATH` environment to run them. When in local mode, executables are linked into `./node_modules/.bin` so that they can be made available to scripts run through npm. (For example, so that a test runner will be in the path when you run `npm test`.) #### Man Pages When in global mode, man pages are linked into `{prefix}/share/man`. When in local mode, man pages are not installed. Man pages are not installed on Windows systems. #### Cache See [`npm cache`](/commands/npm-cache). Cache files are stored in `~/.npm` on Posix, or `%LocalAppData%/npm-cache` on Windows. This is controlled by the [`cache` config](/using-npm/config#cache) param. #### Temp Files Temporary files are stored by default in the folder specified by the [`tmp` config](/using-npm/config#tmp), which defaults to the TMPDIR, TMP, or TEMP environment variables, or `/tmp` on Unix and `c:\windows\temp` on Windows. Temp files are given a unique folder under this root for each run of the program, and are deleted upon successful exit. ### More Information When installing locally, npm first tries to find an appropriate `prefix` folder. This is so that `npm install foo@1.2.3` will install to the sensible root of your package, even if you happen to have `cd`ed into some other folder. Starting at the $PWD, npm will walk up the folder tree checking for a folder that contains either a `package.json` file, or a `node_modules` folder. If such a thing is found, then that is treated as the effective "current directory" for the purpose of running npm commands. (This behavior is inspired by and similar to git's .git-folder seeking logic when running git commands in a working dir.) If no package root is found, then the current folder is used. When you run `npm install foo@1.2.3`, then the package is loaded into the cache, and then unpacked into `./node_modules/foo`. Then, any of foo's dependencies are similarly unpacked into `./node_modules/foo/node_modules/...`. Any bin files are symlinked to `./node_modules/.bin/`, so that they may be found by npm scripts when necessary. #### Global Installation If the [`global` config](/using-npm/config#global) is set to true, then npm will install packages "globally". For global installation, packages are installed roughly the same way, but using the folders described above. #### Cycles, Conflicts, and Folder Parsimony Cycles are handled using the property of node's module system that it walks up the directories looking for `node_modules` folders. So, at every stage, if a package is already installed in an ancestor `node_modules` folder, then it is not installed at the current location. Consider the case above, where `foo -> bar -> baz`. Imagine if, in addition to that, baz depended on bar, so you'd have: `foo -> bar -> baz -> bar -> baz ...`. However, since the folder structure is: `foo/node_modules/bar/node_modules/baz`, there's no need to put another copy of bar into `.../baz/node_modules`, since when baz calls `require("bar")`, it will get the copy that is installed in `foo/node_modules/bar`. This shortcut is only used if the exact same version would be installed in multiple nested `node_modules` folders. It is still possible to have `a/node_modules/b/node_modules/a` if the two "a" packages are different versions. However, without repeating the exact same package multiple times, an infinite regress will always be prevented. Another optimization can be made by installing dependencies at the highest level possible, below the localized "target" folder (hoisting). Since version 3, npm hoists dependencies by default. #### Example Consider this dependency graph: ```bash foo +-- blerg@1.2.5 +-- bar@1.2.3 | +-- blerg@1.x (latest=1.3.7) | +-- baz@2.x | | `-- quux@3.x | | `-- bar@1.2.3 (cycle) | `-- asdf@* `-- baz@1.2.3 `-- quux@3.x `-- bar ``` In this case, we might expect a folder structure like this (with all dependencies hoisted to the highest level possible): ```bash foo +-- node_modules +-- blerg (1.2.5) <---[A] +-- bar (1.2.3) <---[B] | +-- node_modules | +-- baz (2.0.2) <---[C] +-- asdf (2.3.4) +-- baz (1.2.3) <---[D] +-- quux (3.2.0) <---[E] ``` Since foo depends directly on `bar@1.2.3` and `baz@1.2.3`, those are installed in foo's `node_modules` folder. Even though the latest copy of blerg is 1.3.7, foo has a specific dependency on version 1.2.5. So, that gets installed at [A]. Since the parent installation of blerg satisfies bar's dependency on `blerg@1.x`, it does not install another copy under [B]. Bar [B] also has dependencies on baz and asdf. Because it depends on `baz@2.x`, it cannot re-use the `baz@1.2.3` installed in the parent `node_modules` folder [D], and must install its own copy [C]. In order to minimize duplication, npm hoists dependencies to the top level by default, so asdf is installed under [A]. Underneath bar, the `baz -> quux -> bar` dependency creates a cycle. However, because bar is already in quux's ancestry [B], it does not unpack another copy of bar into that folder. Likewise, quux's [E] folder tree is empty, because its dependency on bar is satisfied by the parent folder copy installed at [B]. For a graphical breakdown of what is installed where, use `npm ls`. #### Publishing Upon publishing, npm will look in the `node_modules` folder. If any of the items there are not in the `bundleDependencies` array, then they will not be included in the package tarball. This allows a package maintainer to install all of their dependencies (and dev dependencies) locally, but only re-publish those items that cannot be found elsewhere. See [`package.json`](/configuring-npm/package-json) for more information. ### See also * [package.json](/configuring-npm/package-json) * [npm install](/commands/npm-install) * [npm pack](/commands/npm-pack) * [npm cache](/commands/npm-cache) * [npm config](/commands/npm-config) * [npmrc](/configuring-npm/npmrc) * [config](/using-npm/config) * [npm publish](/commands/npm-publish)
import React from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import {Title} from "../components"; class PopupBody extends React.Component { componentDidMount() { if (!this.props.scroll) { document.getElementsByTagName("body")[0].style.overflow = "hidden"; } } componentWillUnmount() { if (!this.props.scroll) { document.getElementsByTagName("body")[0].style.overflow = ""; } } renderCloseButton(displayCloseButton, onClose) { if (!displayCloseButton) { return null; } return ( <span className="wg-icon wg-icon_close-popup wg-popup__close" onClick={onClose} /> ); } renderContinueButton(display, callback) { if (!display) { return null; } return ( <a className="wg-button wg-button_small wg-popup__continue" onClick={callback}> {this.props.continueButtonText || this.context.localize("Продолжить")} </a> ); } render() { const classes = classNames({ "wg-popup": true, "wg-popup_fixed": this.props.fixed }); return ( <div className={classes} style={{display: "block"}}> <div className="wg-popup__veil" /> <div className="wg-popup__inner-wrap"> {this.renderCloseButton(this.props.displayCloseButton, this.props.onClose)} <Title level={3}>{this.props.title}</Title> <div className="wg-popup__text"> {this.props.children} {this.renderContinueButton(this.props.displayContinueButton, this.props.onContinue)} </div> </div> </div> ); } } PopupBody.contextTypes = { localize: PropTypes.func }; PopupBody.propTypes = { children: PropTypes.node, title: PropTypes.string, displayCloseButton: PropTypes.bool, onClose: PropTypes.func, fixed: PropTypes.bool, scroll: PropTypes.bool, displayContinueButton: PropTypes.bool, onContinue: PropTypes.func, continueButtonText: PropTypes.string }; export default PopupBody;
using System.Text; using static Entidades.Llamada; namespace Entidades { public class Centralita : IGuardar<string> { private List<Llamada> listaDeLlamadas; private string razonSocial; private string rutaDeArchivo = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\centralita.txt"; public Centralita() { listaDeLlamadas = new List<Llamada>(); } public Centralita(string nombreEmpresa) : this() { razonSocial = nombreEmpresa; } public List<Llamada> Llamadas { get => listaDeLlamadas; } public float GananciaPorLocal { get { return CalcularGanancia(TipoLlamada.Local); } } public float GananciaPorProvincial { get { return CalcularGanancia(TipoLlamada.Provincial); } } public float GananciaPorTotal { get { return CalcularGanancia(TipoLlamada.Todas); } } public string RutaDeArchivo { get { return rutaDeArchivo; } set { rutaDeArchivo = value; } } private float CalcularGanancia(TipoLlamada tipo) { float sumador = 0; foreach (Llamada item in Llamadas) { if ((typeof(Local) == item.GetType() && tipo == TipoLlamada.Local) || (typeof(Provincial) == item.GetType() && tipo == TipoLlamada.Provincial) || tipo == TipoLlamada.Todas) { sumador += item.CostoLlamada; } } return sumador; } private string Mostrar() { StringBuilder sb = new StringBuilder(); sb.AppendLine($"Razon social: {razonSocial}"); sb.AppendLine($"Ganancia total: {GananciaPorTotal} Provincial: {GananciaPorProvincial} Local: {GananciaPorLocal}"); foreach (Llamada item in Llamadas) { sb.AppendLine(item.ToString()); } return sb.ToString(); } public void OrdenarLlamadas() { Llamadas.Sort(Llamada.OrdenarPorDuracion); } public override string ToString() { return Mostrar(); } private void AgregarLlamada(Llamada l1) { Llamadas.Add(l1); } public bool Guardar() { try { using StreamWriter sw = new StreamWriter(RutaDeArchivo); sw.WriteLine(DateTime.Now.ToString("dddd dd MMMM yyyy HH:mm-") + "Se realizo una llamada"); } catch (Exception) { throw new FallaLogException("Error en archivo"); } return true; } public string Leer() { using StreamReader sr = new StreamReader(RutaDeArchivo); return sr.ReadToEnd(); } public static bool operator ==(Centralita c, Llamada l) { foreach (Llamada item in c.Llamadas) { if (item == l) { return true; } } return false; } public static bool operator !=(Centralita c, Llamada l) { return !(c == l); } public static Centralita operator +(Centralita c, Llamada l) { if (c != l) { c.AgregarLlamada(l); c.Guardar(); } else { throw new CentralitaException("Ya se encuentra la llamada", "Centralita", "Operador de suma"); } return c; } } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .classObject{ color:red; } </style> </head> <body> <div id="app"> <my-component v-bind:show="nice" ></my-component> <button v-on:click="noColor">noColor</button> </div> <template id="myComponent"> <div class="dialog" v-bind:class="{classObject: show}" v-bind:style="{fontSize:size +'px'}">This is a component!</div> </template> </body> <script src="../js/vue.js"></script> <script> Vue.component('my-component',{ template: '#myComponent', data:function(){ return { size:40 } }, props:["show"], }) var VM = new Vue({ el: '#app', data:{ size:20, nice: true, }, methods:{ noColor:function(){ if(this.nice == true){ this.nice = false; }else{ this.nice = true; } } } }); // VM.noColor(); </script> </html>
@page "/Task/{id:int}" <h3>TaskPage</h3> @if (State != null && State.Identity.Name != "Anonymous") { @if (task == null && id != -1) { <tr>Loading Data ...</tr> } else { <label for="fname">Заголовок:</label> <input type="text" rows="100" @bind="@task.Title" @bind:event="oninput" placeholder="@task.Title" id="fname" name="fname"><br><br> <label for="lname">Очки:</label> <input type="text" @bind="@task.Points" @bind:event="oninput" placeholder="@task.Points" id="lname" name="lname"><br><br> <label for="lname">Дедлайн:</label> <input type="datetime-local" @bind="@deadline" @bind:event="oninput" placeholder="@deadline" id="lname" name="lname"><br><br> <label for="lname">Описание:</label> <textarea rows="30" cols="100" @bind="@task.Description" @bind:event="oninput" placeholder=@task.Description></textarea><br><br> <label for="lname">Сделать видимым пользователям:</label> @task.IsSeen <label for="lname">Тип Задания:</label> <select @bind="@task.Type" @bind:event="oninput"> @foreach (var category in Types) { <option value="@category">@category</option> } </select><br><br> @if (task.IsSeen) { <button type="submit" class="btn btn-danger" @onclick="ChangeTaskVisibility">Скрыть задание</button> } else { <button type="submit" class="btn btn-primary" @onclick="ChangeTaskVisibility">Показать задание</button> }<br><br> @if (id == -1) { <button type="submit" class="btn btn-primary" @onclick="CreateMaterial">Сохранить</button> } else { <button type="submit" class="btn btn-primary" @onclick="UpdateMaterial">Изменить</button> <br/> <button type="submit" class="btn btn-danger" @onclick="DeleteMaterial">Удалить</button> } }} @code { [Parameter] public int id { get; set; } private GetTaskResponse task = new GetTaskResponse(); private ClaimsPrincipal State { get; set; } private DateTime deadline { get; set; } private List<TaskType> Types { get; set; } protected override async Task OnInitializedAsync() { var state = await AuthenticationStateProvider.GetAuthenticationStateAsync(); if (!state.User.Identity.IsAuthenticated) return; State = state.User; Types = Enum.GetValues(typeof(TaskType)).Cast<TaskType>().ToList(); var task_ = await taskService.GetTaskById(id); if (task_ != null) { task = task_; deadline = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(task_.Deadline).ToLocalTime(); } } private async Task UpdateMaterial() { if (await taskService.UpdateTask(MakeChangeTaskResponse(task))) { await jsRuntime.InvokeVoidAsync("alert", "Задание успешно изменено"); NavigationManager.NavigateTo("/veco/TaskList"); } else { await jsRuntime.InvokeVoidAsync("alert", "Ошибка изменения задания"); } } private async Task CreateMaterial() { if (await taskService.CreateTask(MakeAddTaskResponse(task))) { await jsRuntime.InvokeVoidAsync("alert", "Задание успешно создано"); NavigationManager.NavigateTo("/veco/TaskList"); } else { await jsRuntime.InvokeVoidAsync("alert", "Ошибка при создании Задания"); } } private async Task DeleteMaterial() { if (await taskService.DeleteTask(id)) { await jsRuntime.InvokeVoidAsync("alert", "Задание успешно удалено"); NavigationManager.NavigateTo("/veco/TaskList"); } else { await jsRuntime.InvokeVoidAsync("alert", "Ошибка удаления материала"); } } private AddTaskResponse MakeAddTaskResponse(GetTaskResponse taskResponse) { var addTaskResponse = new AddTaskResponse(); addTaskResponse.Deadline = deadline; addTaskResponse.Status = taskResponse.Status; addTaskResponse.Type = taskResponse.Type; addTaskResponse.Title = taskResponse.Title; addTaskResponse.Description = taskResponse.Description; addTaskResponse.Points = taskResponse.Points; return addTaskResponse; } private ChangeTaskResponse MakeChangeTaskResponse(GetTaskResponse taskResponse) { var changeTaskResponse = new ChangeTaskResponse(); changeTaskResponse.Deadline = deadline; changeTaskResponse.Status = taskResponse.Status; changeTaskResponse.Id = taskResponse.Id; changeTaskResponse.Type = taskResponse.Type; changeTaskResponse.Title = taskResponse.Title; changeTaskResponse.Description = taskResponse.Description; changeTaskResponse.Points = taskResponse.Points; return changeTaskResponse; } private DateTime AddDeadline(TaskType type) { switch (type) { case TaskType.Day: return DateTime.Now.AddDays(1); case TaskType.Week: return DateTime.Now.AddDays(7); case TaskType.Month: return DateTime.Now.AddMonths(1); default: return DateTime.Now; } } private async Task ChangeTaskVisibility() { if(await taskService.ChangeTaskVisibility(task.Id, !task.IsSeen)) { task.IsSeen = !task.IsSeen; await jsRuntime.InvokeVoidAsync("alert", "Задание успешно изменено"); return; } await jsRuntime.InvokeVoidAsync("alert", "Ошибка изменения задания"); } }
<html lang="zh-tw"> <!-- Mirrored from www.1keydata.com/css-tutorial/tw/box-model.php by HTTrack Website Copier/3.x [XR&CO'2013], Thu, 22 Aug 2013 15:42:07 GMT --> <head> <title>CSS 盒子模式CSS 語法教學</title> <meta name="description" content="解釋 CSS 內的盒子模式 (Box Model)。"> <link rel="canonical" href="box-model.html" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel=stylesheet type="text/css" href="css-tutorial.css"> </head> <body> <center><table border=0 bgcolor="FFA900" width=960 cellspacing=0 cellpadding=0><tr valign=top><td><h2> CSS 盒子模式 </h2> </td><td align=right> </td></tr></table> <table border="0" cellspacing="0" cellpadding="0" width="960" bgcolor="FFFFFF"> <tr><td height=1 width=190 bgcolor=6600FF></td><td rowspan=2 valign=top width=690 valign=top> <table border=0 cellspacing=5 class=main><tr><td valign="top"><h6><a href="index.html">CSS 教學</a> &nbsp;&gt;&nbsp; 盒子模式</h6> <center> </center><p>盒子模式 (box model) 是在 CSS 中一個很重要的觀念。它是用來描述一個元素是如何組成的。以下是盒子模式的式樣: </p> <p><center><img src="box-model-tw.gif" border=0 /></center> <p>在盒子模式中,內容 (content) 是最內層的部分,接下來依序為留白 (padding)、邊框 (border)、以及邊界 (margin)。邊界是用來設定各個元素之間的距離。 <p> 相關的 CSS 指令為 <a href="margin.html">margin</a>、<a href="border.html">border</a>、以及 <a href="padding.html">padding</a>。在下面的三頁我們會一一介紹。 <p><center>下一頁: <a href="margin.html">CSS 邊界</a></center> </td>  </tr></table> </td></tr><tr valign=top> <td valign="top" width="190" nowrap vlink="#000000" bgcolor=6600FF> <table border=0 cellpadding=8> <tr><td> <br> <font size="-1" face="Verdana, Arial, Helvetica, sans-serif"> <a class=nav href="index.html">CSS 語法教學</a><br> <a class=nav href="syntax.html">CSS 語法</a><br> <a class=nav href="apply.html">CSS 套用方式</a><br> <a class=nav href="media-types.html">CSS 媒體類別</a><br> <a class=nav href="cascade.html">CSS 串接</a><br> <a class=nav href="inheritance.html">CSS 繼承</a><br> <a class=nav href="class-id.html">CSS Class 與 ID</a><br> <a class=nav href="div-span.html">CSS Div 與 Span</a><br> <a class=nav href="length-units.html">CSS 長度單位</a><br><br> <a class=nav href="box-model.html">CSS 盒子模式</a><br> <a class=nav href="margin.html">CSS 邊界 (Margin)</a><br> <a class=nav href="border.html">CSS 邊框 (Border)</a><br> <a class=nav href="padding.html">CSS 留白 (Padding)</a><br> <a class=nav href="background.html">CSS 背景 (Background)</a><br> <a class=nav href="color.html">CSS 顏色</a><br> <a class=nav href="font.html">CSS 字體</a><br> <a class=nav href="link.html">CSS 連接</a><br> <a class=nav href="list.html">CSS 清單 (List)</a><br> <a class=nav href="table.html">CSS 表格 (Table)</a><br> <a class=nav href="position.html">CSS 位置 (Position)</a><br> <a class=nav href="text.html">CSS 文字 (Text)</a><br> <a class=nav href="float.html">CSS 浮動 (Float)</a><br> <a class=nav href="clear.html">CSS 清除 (Clear)</a><br> <a class=nav href="cursor.html">CSS 滑鼠游標圖案</a><br><br> <a class=nav href="codes.html">CSS 樣式</a><br><br> </td></tr></table></td> </td> </tr> </table> </center> </body> <!-- Mirrored from www.1keydata.com/css-tutorial/tw/box-model.php by HTTrack Website Copier/3.x [XR&CO'2013], Thu, 22 Aug 2013 15:42:07 GMT --> </html>
from datetime import datetime, timedelta import pytest from django.test.client import Client from django.urls import reverse from django.utils import timezone from news.models import Comment, News from news.pytest_tests.constants import ( AUTHOR_USERNAME, COMMENT_TEXT, NEWS_DELETE, NEWS_DETAIL, NEWS_EDIT, NEWS_TEXT, NEWS_TITLE, NOT_AUTHOR_USERNAME, ) from yanews.settings import NEWS_COUNT_ON_HOME_PAGE @pytest.fixture def author(django_user_model): return django_user_model.objects.create(username=AUTHOR_USERNAME) @pytest.fixture def not_author(django_user_model): return django_user_model.objects.create(username=NOT_AUTHOR_USERNAME) @pytest.fixture def author_client(author): client = Client() client.force_login(author) return client @pytest.fixture def not_author_client(not_author): client = Client() client.force_login(not_author) return client @pytest.fixture def guest_client(): return Client() @pytest.fixture def news(): news = News.objects.create( title=NEWS_TITLE, text=NEWS_TEXT, date=timezone.now(), ) return news @pytest.fixture def comment(author, news): comm = Comment.objects.create( news=news, author=author, text=COMMENT_TEXT, ) return comm @pytest.fixture def news_url(news): return reverse(NEWS_DETAIL, args=(news.id,)) @pytest.fixture def edit_url(comment): return reverse(NEWS_EDIT, args=(comment.id,)) @pytest.fixture def delete_url(comment): return reverse(NEWS_DELETE, args=(comment.id,)) @pytest.fixture def form_data_comm(): return {"text": COMMENT_TEXT} @pytest.fixture def several_news_objects(): today = datetime.today() News.objects.bulk_create( News( title=f"Новость {index}", text=f"Tекст {index}", date=today - timedelta(days=index), ) for index in range(NEWS_COUNT_ON_HOME_PAGE + 1) ) yield @pytest.fixture def several_comments_objects(news, author): now = timezone.now() for index in range(NEWS_COUNT_ON_HOME_PAGE): comm = Comment.objects.create( news=news, author=author, text=f"Tекст {index}", ) comm.created = now + timedelta(days=index) comm.save() yield
using System.Runtime.ConstrainedExecution; using System.Runtime.Serialization; using System.Text; using Azure; using Azure.AI.OpenAI; namespace Claire; public class Claire { private class CommandDefinition(string name, string description, Action function) { public readonly string Name = name; public readonly string Description = description; public readonly Action Execute = function; } private readonly UserInterface _userInterface = new(); private readonly List<CommandDefinition> _commands = []; private readonly ClaireConfiguration _configuration; private readonly OpenAIClient _openAiClient; // Prompt completion state private string _promptCompletion = string.Empty; private CancellationTokenSource _promptCompletionCancellationTokenSource = new(); private readonly ClaireShell _shell; private readonly IList<Message> _messages = new List<Message>(); private readonly ChatMessage _promptStartMessage; private readonly ChatMessage _completionStartMessage; private bool _active = false; public ClaireConfiguration Configuration => _configuration; public UserInterface UserInterface => _userInterface; public Claire(ClaireConfiguration configuration) { _configuration = configuration; _userInterface.DebugOutput = _configuration.Debug; // Initialize commands _commands.Add(new CommandDefinition("help", "Display a list of commands", CommandHelp)); _commands.Add(new CommandDefinition("debug", "Enable/disable debug output", CommandDebug)); _commands.Add(new CommandDefinition("exit", "Exit Claire", CommandExit)); // Create OpenAI client _openAiClient = new OpenAIClient( new Uri(_configuration.OpenAiUrl), new AzureKeyCredential(_configuration.OpenAiKey) ); // Create shell _shell = new ClaireShell(_configuration.ShellProcessName); // Create starter prompt var intro = $"You are Claire, a Command-Line AI Runtime Environment who guides users with the {_configuration.ShellProcessName} shell.\n"; var starterPrompt = intro; starterPrompt += "You will provide command, scripts, configuration files and explanation to the user\n"; starterPrompt += "You will also provide help with using the Azure CLI.\n"; _promptStartMessage = new ChatMessage("system", starterPrompt); // Create completion prompt var completionPrompt = intro; completionPrompt += "Users will provide the start of a question related to the shell or command and you will complete the question or command for them. Do not answer the question. Just provide a completion. Make sure to include a space at the start of the completion if necessary."; _completionStartMessage = new ChatMessage("system", completionPrompt); } private void AddMessage(MessageType messageType, string text) { var message = new Message { Type = messageType, Text = text, }; _messages.Add(message); } private List<ChatMessage> GetConversationHistory(int size) { var messages = _messages .Select(m => new ChatMessage(Message.MessageTypeToString(m.Type), m.Text)) .TakeLast(_configuration.ChatHistorySize) .ToList(); return messages; } private List<ChatMessage> PrepareChatMessages(string prompt, ChatMessage startMessage) { var messages = GetConversationHistory(_configuration.ChatHistorySize); messages.Insert(0, startMessage); messages.Add(new ChatMessage(ConvertMessageTypeToRole(MessageType.User), prompt)); return messages; } private async Task GetPromptCompletionsAsync(string prompt) { if (!_configuration.SuggestCompletions) { // Suggestions are turned off. return; } if (prompt.Length < 3) { // Wait until we have at least 3 characters return; } if (prompt[0] == '/') { // Don't complete commands...yet? return; } if (_promptCompletionCancellationTokenSource != null) { _promptCompletionCancellationTokenSource.Cancel(); _promptCompletionCancellationTokenSource.Dispose(); } _promptCompletionCancellationTokenSource = new CancellationTokenSource(); _promptCompletion = string.Empty; // Wait before requesting completions await Task.Delay(_configuration.SuggestionDelay, _promptCompletionCancellationTokenSource.Token); var requestPrompt = prompt; _promptCompletion = await ExecuteCompletion( requestPrompt, _promptCompletionCancellationTokenSource.Token ); _userInterface.WriteCompletion(_promptCompletion, newLine: false); // try // { // _userInterface.WriteDebug($"completion request: {prompt}"); // var messages = PrepareChatMessages(prompt); // var prompts = messages.Select(m => m.Content).ToList(); // prompts.Add(prompt); // _promptCompletionCancellationTokenSource?.Cancel(); // _promptCompletionCancellationTokenSource = new CancellationTokenSource(); // var options = new CompletionsOptions(_configuration.OpenAiModel, prompts); // // https://github.com/Azure/azure-sdk-for-net/pull/40155 // options.DeploymentName = _configuration.OpenAiModel; // var response = await _openAiClient.GetCompletionsAsync(options, _promptCompletionCancellationTokenSource.Token); // _promptCompletion = response.Value.Choices[0].Text; // _userInterface.WriteCompletion($"completion response: {_promptCompletion}"); // } // catch (Exception exception) // { // _userInterface.WriteDebug($"completion exception: {exception.Message}"); // } } private void ErasePromptCompletion() { if (_promptCompletion.Length > 0) { var backSpaces = new string('\b', _promptCompletion.Length); var spaces = new string(' ', _promptCompletion.Length); Console.Write(backSpaces); Console.Write(spaces); Console.Write(backSpaces); } } private string GetUserPrompt() { string prompt = string.Empty; do { _userInterface.WriteSystem("Please tell me what you would like to do?", newLine: false); if (_configuration.SuggestCompletions) { _userInterface.WriteSystem(" (Press TAB for suggestions)", newLine: false); } _userInterface.NextLine(); char keyChar; do { var key = Console.ReadKey(true); keyChar = key.KeyChar; ErasePromptCompletion(); switch (keyChar) { case '\t': if (_promptCompletion.Length > 0) { prompt += _promptCompletion; _userInterface.WriteInput(_promptCompletion, newLine: false); // We purposely don't `await` this call to allow user to continue typing _ = GetPromptCompletionsAsync(prompt); } break; case '\r': case '\n': // Ignore CR/LF. They are checked for at the end of the loop. break; case '\b': if (prompt.Length > 0) { if (Console.CursorLeft == 0) { // On a new line. Need to re-draw the prompt. _userInterface.WriteInput(prompt, newLine: false); } else { // Erase the last character prompt = prompt.Substring(0, prompt.Length - 1); Console.Write("\b \b"); // Erase the current character with a space, and back again } } break; default: prompt += keyChar; _userInterface.WriteInput(keyChar.ToString(), newLine: false); // We purposely don't `await` this call to allow user to continue typing _ = GetPromptCompletionsAsync(prompt); break; } } while (keyChar != '\r' && keyChar != '\n'); // Move to the next line. _userInterface.NextLine(); if (string.IsNullOrWhiteSpace(prompt)) { _userInterface.WriteSystem("Use `/help` to see a list of commands."); } } while (string.IsNullOrWhiteSpace(prompt)); return prompt; } private string ConvertMessageTypeToRole(MessageType type) { return type switch { MessageType.User => "user", MessageType.Claire => "system", _ => throw new Exception("Internal error: Invalid message type"), }; } private async Task<string> ExecuteChatPrompt(string prompt, bool saveHistory = false) { return await ExecuteChat( prompt, _promptStartMessage, temperature: 0.7f, maxTokens: 800, saveHistory: saveHistory ); } private async Task<string> ExecuteCompletion(string prompt, CancellationToken cancellationToken) { return await ExecuteChat( prompt, _completionStartMessage, temperature: 0.0f, maxTokens: 20, cancellationToken: cancellationToken, saveHistory: false ); } private async Task<string> ExecuteChat(string prompt, ChatMessage startMessage, float temperature = 0.7f, int maxTokens = 800, CancellationToken cancellationToken = new CancellationToken(), bool saveHistory = false) { var messages = PrepareChatMessages(prompt, startMessage); var options = new ChatCompletionsOptions(_configuration.OpenAiModel, messages); options.Temperature = temperature; _userInterface.WriteDebug($"prompt: {prompt}"); var response = await _openAiClient.GetChatCompletionsAsync(options, cancellationToken); var responseMessage = response.Value.Choices[0].Message.Content; _userInterface.WriteDebug($"response: {responseMessage}"); if (saveHistory) { _messages.Add(new Message() { Type = MessageType.User, Text = prompt }); _messages.Add(new Message() { Type = MessageType.Claire, Text = responseMessage }); } return responseMessage; } private async Task<ChatResponse> GetIntentAsync(string prompt, ChatResponse intent) { var intentPrompt = $"Determine if the following statement is asking about a specific command, generate a file, or an explanation:\n\n"; intentPrompt += $"\"{prompt}\"\n\n"; intentPrompt += $"Reply only with the word `command`, `file`, `explain` or 'unknown."; var intentText = await ExecuteChatPrompt(intentPrompt); switch (intentText.ToLower()) { case "command": intent.Type = ChatResponseType.Command; break; case "file": intent.Type = ChatResponseType.File; break; case "explain": intent.Type = ChatResponseType.Explain; break; case "unknown": intent.Type = ChatResponseType.Unknown; break; default: Console.Error.WriteLine($"Unknown intent type: {intentText}"); intent.Type = ChatResponseType.Unknown; break; } return intent; } private async Task<ChatResponse> GetUnknownAsync(string prompt, ChatResponse intent) { var response = await ExecuteChatPrompt(prompt, saveHistory: true); intent.Response = response; return intent; } private async Task<ChatResponse> GetCommandAsync(string prompt, ChatResponse intent) { var commandPrompt = $"Provide the command required for the statement below:\n\n"; commandPrompt += $"{prompt}\n\n"; commandPrompt += $"Reply with only the text for the command. Do not include explanation or markdown."; var commandText = await ExecuteChatPrompt(commandPrompt, saveHistory: true); commandText = RemoveMarkdownFences(commandText); intent.Response = commandText; return intent; } private async Task<ChatResponse> GetFileNameAsync(string prompt, ChatResponse intent) { var fileNamePrompt = $"Provide the file name associated with this prompt:\n\n"; fileNamePrompt += $"{prompt}\n\n"; fileNamePrompt += $"Provide only the file name in the response. No additional text. If no file name are found in the prompt, then respond with the following text: <<unknown>>"; var fileName = await ExecuteChatPrompt(fileNamePrompt); fileName = RemoveMarkdownFences(fileName); if (fileName.Contains("<<unknown>>")) { fileName = ""; } intent.FileName = fileName; return intent; } private string RemoveMarkdownFences(string text) { if (text.StartsWith("```")) { //Strip off the markdown var lines = text.Split('\n'); text = string.Join("\n", lines.Skip(1).SkipLast(1)); } return text; } private async Task<ChatResponse> GetFileAsync(string prompt, ChatResponse intent) { var filePrompt = $"Generate the file requested below:\n\n"; filePrompt += $"{prompt}\n\n"; filePrompt += $"Respond with only the content of the file without any Markdown annotation. No additional text before or after the content of the file. Comments in the file are permissible"; var responseText = await ExecuteChatPrompt(filePrompt, saveHistory: true); responseText = RemoveMarkdownFences(responseText); intent.Response = responseText; return intent; } private async Task<ChatResponse> GetExplanationAsync(string prompt, ChatResponse intent) { var response = await ExecuteChatPrompt(prompt, saveHistory: true); intent.Response = response; return intent; } public async Task<ChatResponse> GetPromptResult(string prompt) { var intent = new ChatResponse(); await GetIntentAsync(prompt, intent); switch (intent.Type) { case ChatResponseType.Unknown: await GetUnknownAsync(prompt, intent); break; case ChatResponseType.Command: await GetCommandAsync(prompt, intent); break; case ChatResponseType.File: await GetFileNameAsync(prompt, intent); await GetFileAsync(prompt, intent); break; case ChatResponseType.Explain: await GetExplanationAsync(prompt, intent); break; default: throw new Exception("Internal error: Unknown intent type"); } _messages.Add(new Message() { Type = MessageType.User, Text = intent.Response, FileName = intent.FileName, }); return intent; } private async Task<ShellResult> ExecuteCommand(string command) { try { _userInterface.WriteDebug($"command: {command}"); var result = await _shell.Execute(command); _userInterface.WriteDebug($"stdout: {result.Output}"); _userInterface.WriteDebug($"stderr: {result.Error}"); return result; } catch (Exception exception) { _userInterface.WriteError($"Exception: {exception.Message}"); throw; } } private async Task ExecuteIntentUnknown(ChatResponse intent) { _userInterface.WriteSystem("Sorry, I don't understand what you mean. Please try again."); } private async Task<string> GetErrorDescription(string command, string error) { var prompt = $"Explain why the command `{command}` encountered the following error:\n"; prompt += $"{error}\n"; var response = await ExecuteChatPrompt(prompt, saveHistory: true); return response; } private async Task ExecuteIntentCommand(ChatResponse intent) { _userInterface.WriteSystem($"I believe the command you are looking for is:"); _userInterface.WriteChatResponse($"{intent.Response}"); _userInterface.NextLine(); var execute = _userInterface.PromptConfirm("Shall I executed it for you?"); if (execute) { var result = await ExecuteCommand(intent.Response); _userInterface.WriteCommand(result.Output); if (result.HasError) { _userInterface.WriteCommandError(result.Error); _userInterface.WriteSystem("It looks like the command encountered a problem. Investigating..."); var errorDescription = await GetErrorDescription(intent.Response, result.Error); _userInterface.WriteChatResponse(errorDescription); } } } private async Task ExecuteIntentFile(ChatResponse action) { _userInterface.WriteSystem($"The following file was generated:"); _userInterface.WriteChatResponse(action.Response); var saveFile = _userInterface.PromptConfirm("Would you like to save the file?"); if (saveFile) { if (string.IsNullOrEmpty(action.FileName)) { var fileName = _userInterface.Prompt("Please enter a filename: "); if (string.IsNullOrEmpty(fileName)) { _userInterface.WriteSystem("No file name provide. File will not be saved."); return; } action.FileName = fileName; } try { // TODO: Need to save through working directory of the command line... await File.WriteAllTextAsync(action.FileName, action.Response); _userInterface.WriteSystem($"File {action.FileName} saved."); } catch (Exception exception) { _userInterface.WriteCommandError($"Could not save file {action.FileName}: {exception.Message}"); } } } private async Task ExecuteIntentExplain(ChatResponse action) { _userInterface.WriteChatResponse(action.Response); } private async Task ExecuteIntent(ChatResponse action) { switch (action.Type) { case ChatResponseType.Unknown: await ExecuteIntentUnknown(action); break; case ChatResponseType.Command: await ExecuteIntentCommand(action); break; case ChatResponseType.File: await ExecuteIntentFile(action); break; case ChatResponseType.Explain: await ExecuteIntentExplain(action); break; default: throw new Exception($"Unexpected response: {action.Type}"); } } public void Stop() { _active = false; } public async Task Run() { _userInterface.WriteSystem("Welcome to Claire. Where would you like to go today?"); _active = true; while (_active) { var prompt = GetUserPrompt(); if (!string.IsNullOrEmpty(prompt) && prompt[0] == '/') { var command = prompt.Substring(1); var commandDefinition = _commands.FirstOrDefault(c => c.Name == command); if (commandDefinition == null) { _userInterface.WriteSystem($"Unknown command: {command}"); _userInterface.WriteSystem($"Use `/help` to see a list of commands."); } else { commandDefinition.Execute(); } } else { _userInterface.WriteSystem("Let me think about that for a moment..."); var intent = await GetPromptResult(prompt); _userInterface.WriteDebug($"Intent: {intent.Type}"); _userInterface.WriteDebug($"Command: {intent.Response}"); _userInterface.WriteDebug($"File Name: {intent.FileName}"); await ExecuteIntent(intent); } } _userInterface.Reset(); } private void CommandHelp() { UserInterface.WriteSystem("Available commands:"); foreach (var command in _commands) { UserInterface.WriteSystem($" /{command.Name} - {command.Description}"); } } private void CommandExit() { Stop(); } private void CommandDebug() { if (_userInterface.DebugOutput) { _userInterface.DebugOutput = false; _userInterface.WriteSystem("Debug output now is off"); } else { _userInterface.DebugOutput = true; _userInterface.WriteSystem("Debug output now is on"); } } }
import React from "react"; import { useNavigate } from "react-router-dom"; import StyledPopup, { StyledButtons, StyledText, StyledButton, } from "./StyledPopup"; import { useDataLayerValue } from "../../DataLayer"; const Popup = () => { const navigate = useNavigate(); const [{ showPopup }, dispatch] = useDataLayerValue(); function handleCancel() { dispatch({ type: "SET_POPUP", showPopup: false }); } function handleLogout() { dispatch({ type: "SET_TOKEN", token: null }); navigate("/"); } return ( <StyledPopup show={showPopup}> <StyledText> <p>Are you sure you want to logout</p> </StyledText> <StyledButtons> <StyledButton pos="left" onClick={handleCancel}> Cancel </StyledButton> <StyledButton pos="right" onClick={handleLogout}> Log out </StyledButton> </StyledButtons> </StyledPopup> ); }; export default Popup;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 验证二叉搜索树 // https://leetcode-cn.com/problems/validate-binary-search-tree/ // 定一个二叉树,判断其是否是一个有效的二叉搜索树。 // 假设一个二叉搜索树具有如下特征: // 节点的左子树只包含小于当前节点的数。 // 节点的右子树只包含大于当前节点的数。 // 所有左子树和右子树自身必须也是二叉搜索树。 // 解题思路: // 二叉搜索树的中序遍历是升序的,因此可以进行中序遍历,检查是否是中序来判断 /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ function fn(root) { if (!root) return true; let stack = []; let pre = -Infinity; while (root || stack.length > 0) { while(root) { stack.push(root); root = root.left; } root = stack.pop(); if (root.val <= pre) return false; pre = root.val; root = root.right; } return true; } </script> </body> </html>
import json import logging import os from typing import Any, Optional import boto3 import sagemaker import sagemaker.session from botocore.exceptions import ClientError from sagemaker.huggingface import HuggingFaceModel, get_huggingface_llm_image_uri from sagemaker.workflow.parameters import ParameterString from sagemaker.workflow.pipeline import Pipeline from sagemaker.workflow.step_collections import RegisterModel logger = logging.getLogger(__name__) ACCESS_TOKEN_SECRET = os.environ["HUGGING_FACE_ACCESS_TOKEN_SECRET"] # read token from secret using boto3 SECRET_REGION = os.environ["AWS_REGION"] def get_acess_token_from_secret(secretid: str, secret_region: str) -> Any: # Create a Secrets Manager client session = boto3.session.Session() client = session.client(service_name="secretsmanager", region_name=secret_region) try: get_secret_value_response = client.get_secret_value(SecretId=secretid) except ClientError as e: raise e # Get the secret value secret_value = get_secret_value_response["SecretString"] return secret_value ACCESS_TOKEN = get_acess_token_from_secret(ACCESS_TOKEN_SECRET, SECRET_REGION) def get_session(region: str, default_bucket: Optional[str]) -> sagemaker.session.Session: """Gets the sagemaker session based on the region. Args: region: the aws region to start the session default_bucket: the bucket to use for storing the artifacts Returns: `sagemaker.session.Session instance """ boto_session = boto3.Session(region_name=region) sagemaker_client = boto_session.client("sagemaker") runtime_client = boto_session.client("sagemaker-runtime") session = sagemaker.session.Session( boto_session=boto_session, sagemaker_client=sagemaker_client, sagemaker_runtime_client=runtime_client, default_bucket=default_bucket, ) return session def get_pipeline( region: str, hugging_face_model_id: str, role: Optional[str] = None, default_bucket: Optional[str] = None, model_package_group_name: str = "AbalonePackageGroup", pipeline_name: str = "AbalonePipeline", project_id: str = "SageMakerProjectId", ) -> Any: sagemaker_session = get_session(region, default_bucket) if role is None: role = sagemaker.session.get_execution_role(sagemaker_session) # parameters for pipeline execution model_approval_status = ParameterString(name="ModelApprovalStatus", default_value="PendingManualApproval") inference_image_uri = get_huggingface_llm_image_uri("huggingface", version="0.9.3") llm_model = HuggingFaceModel( role=role, image_uri=inference_image_uri, env={ "HF_MODEL_ID": hugging_face_model_id, # model_id from hf.co/models "SM_NUM_GPUS": json.dumps(1), # Number of GPU used per replica "MAX_INPUT_LENGTH": json.dumps(2048), # Max length of input text "MAX_TOTAL_TOKENS": json.dumps(4096), # Max length of the generation (including input text) "MAX_BATCH_TOTAL_TOKENS": json.dumps( 8192 ), # Limits the number of tokens that can be processed in parallel during the generation "HUGGING_FACE_HUB_TOKEN": ACCESS_TOKEN, # ,'HF_MODEL_QUANTIZE': "bitsandbytes", # comment in to quantize }, ) step_register = RegisterModel( name="RegisterModel", model=llm_model, # estimator=xgb_train, # image_uri=inference_image_uri, # model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts, content_types=["text/csv"], response_types=["text/csv"], inference_instances=["ml.g5.2xlarge", "ml.g5.12xlarge"], # transform_instances=["ml.g5.12xlarge", "ml.p4d.24xlarge"], model_package_group_name=model_package_group_name, approval_status=model_approval_status, ) # pipeline instance pipeline = Pipeline( name=pipeline_name, parameters=[ model_approval_status, ], steps=[step_register], sagemaker_session=sagemaker_session, ) return pipeline
structure AST = struct type id = string datatype binop = Plus | Minus | Times datatype unop = Not | Neg datatype logicop = And | Or | Xor | Implies datatype relop = Equals | LessThan | GreaterThan datatype decl = ValDecl of id * exp and prg = Program of exp*prg | LastExp of exp and exp = NumExp of int | ConstExp of string | VarExp of id | BinExp of binop * exp * exp | LetExp of decl * exp | UnExp of unop * exp | LogicExp of logicop * exp * exp | RelExp of relop*exp*exp | IfExp of exp * exp * exp | Fn of id*typ*typ*exp | Fun of id*id*typ*typ*exp | AppExp of exp*exp and typ = INT | STRING | BOOL | ARROW of typ*typ | TypeEnv of typeenvironment withtype typeenvironment = (id * typ) list fun typeEnvAdd (var:id, v:typ, env:typeenvironment) = (var,v)::env fun typeEnvLookup (var:id, env:typeenvironment) = case List.find(fn (x, _) => x = var) env of SOME (x, v) => v | NONE => raise Fail ("Unbound variable or constructor: " ^ var) datatype value = IntVal of int | BoolVal of bool | FunVal of id*exp*environment | Env of environment withtype environment = (id * value) list fun envAdd (var:id, v:value, env:environment) = (var,v)::env fun envLookup (var:id, env:environment) = case List.find(fn (x, _) => x = var) env of SOME (x, v) => v | NONE => raise Fail ("Unbound variable or constructor: " ^ var) fun type_to_string(t: typ): string = case t of INT => "int" | STRING => "string" | BOOL => "bool" | ARROW(t1, t2) => type_to_string(t1) ^ "->" ^ type_to_string(t2) fun exp_to_string(e: exp): string = case e of NumExp i => Int.toString(i) | ConstExp s => s | VarExp x => x | BinExp (b, e1, e2) => (case b of Plus => exp_to_string(e1) ^ " PLUS " ^ exp_to_string(e2) | Minus => exp_to_string(e1) ^ " MINUS " ^ exp_to_string(e2) | Times => exp_to_string(e1) ^ " TIMES " ^ exp_to_string(e2) ) | UnExp(u, e) => (case u of Not => " NOT " ^ exp_to_string(e) | Negate => " NEGATE " ^ exp_to_string(e) ) | LogicExp(l, e1, e2) => (case l of And => exp_to_string(e1) ^ " AND " ^ exp_to_string(e2) | Or => exp_to_string(e1) ^ " OR " ^ exp_to_string(e2) | Xor => exp_to_string(e1) ^ " XOR " ^ exp_to_string(e2) | Implies => exp_to_string(e1) ^ " IMPLIES " ^ exp_to_string(e2) ) | RelExp(r, e1, e2) => (case r of Equals => exp_to_string(e1) ^ " EQUALS " ^ exp_to_string(e2) | LessThan => exp_to_string(e1) ^ " LESSTHAN " ^ exp_to_string(e2) | GreaterThan => exp_to_string(e1) ^ " GREATERTHAN " ^ exp_to_string(e2) ) | Fn (farg, ty1, ty2, e1) => "fn " ^ " (" ^ farg ^ ": " ^ type_to_string(ty1) ^ "): " ^ type_to_string(ty2) ^"=>" ^ exp_to_string(e1) | Fun (f, farg, ty1, ty2, e1) => "fun " ^ f ^ " (" ^ farg ^ ": " ^ type_to_string(ty1) ^ "): " ^ type_to_string(ty2) ^"=>" ^ exp_to_string(e1) | AppExp (e1, e2) => "(" ^ exp_to_string(e1) ^ " " ^ exp_to_string(e2) ^ ")" | IfExp (e1, e2, e3) => "if " ^ exp_to_string(e1) ^ " then " ^ exp_to_string(e2) ^ " else " ^ exp_to_string(e3) | LetExp(ValDecl(x, e1), e2) => "let\n\t" ^ exp_to_string(e1) ^ "\nin\n\t" ^ exp_to_string(e2) ^ "\nend" end
import { Inject } from '@nestjs/common'; import { BigNumberish } from 'ethers'; import { APP_TOOLKIT, IAppToolkit } from '~app-toolkit/app-toolkit.interface'; import { PositionTemplate } from '~app-toolkit/decorators/position-template.decorator'; import { DefaultDataProps } from '~position/display.interface'; import { MetaType } from '~position/position.interface'; import { ContractPositionTemplatePositionFetcher } from '~position/template/contract-position.template.position-fetcher'; import { GetTokenDefinitionsParams, UnderlyingTokenDefinition, GetDisplayPropsParams, GetTokenBalancesParams, } from '~position/template/contract-position.template.types'; import { BeanstalkBalanceResolver } from '../common/beanstalk.balance-resolver'; import { BeanstalkViemContractFactory } from '../contracts'; import { Beanstalk } from '../contracts/viem'; export type BeanstalkSiloDepositDefinition = { address: string; underlyingTokenAddresses: string; name: string; }; export const SILOS = [ { name: 'Bean', underlyingTokenAddress: '0xbea0000029ad1c77d3d5d23ba2d8893db9d1efab', }, { name: 'BEAN:3CRV LP', underlyingTokenAddress: '0xc9c32cd16bf7efb85ff14e0c8603cc90f6f2ee49', }, { name: 'Unripe Bean', underlyingTokenAddress: '0x1bea0050e63e05fbb5d8ba2f10cf5800b6224449', }, { name: 'Unripe BEAN:3CRV LP', underlyingTokenAddress: '0x1bea3ccd22f4ebd3d37d731ba31eeca95713716d', }, ]; @PositionTemplate() export class EthereumBeanstalkSiloDepositContractPositionFetcher extends ContractPositionTemplatePositionFetcher< Beanstalk, DefaultDataProps, BeanstalkSiloDepositDefinition > { groupLabel = 'Silo Deposits'; constructor( @Inject(APP_TOOLKIT) protected readonly appToolkit: IAppToolkit, @Inject(BeanstalkViemContractFactory) protected readonly contractFactory: BeanstalkViemContractFactory, @Inject(BeanstalkBalanceResolver) protected readonly beanstalkBalanceResolver: BeanstalkBalanceResolver, ) { super(appToolkit); } getContract(address: string) { return this.contractFactory.beanstalk({ address, network: this.network }); } async getDefinitions(): Promise<BeanstalkSiloDepositDefinition[]> { const address = '0xc1e088fc1323b20bcbee9bd1b9fc9546db5624c5'; const definition = SILOS.map(silo => { return { address, underlyingTokenAddresses: silo.underlyingTokenAddress, name: silo.name, }; }); return definition; } async getTokenDefinitions({ definition, }: GetTokenDefinitionsParams<Beanstalk, BeanstalkSiloDepositDefinition>): Promise<UnderlyingTokenDefinition[]> { return [ { metaType: MetaType.SUPPLIED, address: definition.underlyingTokenAddresses, network: this.network, }, ]; } async getLabel({ definition, }: GetDisplayPropsParams<Beanstalk, DefaultDataProps, BeanstalkSiloDepositDefinition>): Promise<string> { return definition.name; } async getTokenBalancesPerPosition({ address, contractPosition, }: GetTokenBalancesParams<Beanstalk, DefaultDataProps>): Promise<BigNumberish[]> { const tokenAddress = contractPosition.tokens[0].address; const balanceRaw = await this.beanstalkBalanceResolver.getSiloBalances(address, tokenAddress); return [balanceRaw]; } }
const mongoose = require('mongoose') const passportLocalMongoose = require('passport-local-mongoose') const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true, minlength: 3, maxlength: 60 }, avatar: { type: String, trim: true }, isDeleted: { type: Boolean, default: false }, deletedAt: { type: Date, default: null } }) class User { static checkDeleted (email) { return this.exists({ email, isDeleted: true }) } delete () { this.isDeleted = true this.deletedAt = Date.now() return this.save() } changeAvatar (url) { this.avatar = url return this.save() } } userSchema.plugin(passportLocalMongoose, { usernameField: 'email', lastLoginField: true }) userSchema.loadClass(User) module.exports = mongoose.model('User', userSchema, 'users')
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Meep(models.Model): user = models.ForeignKey( User, related_name="meeps", on_delete=models.DO_NOTHING ) body = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User,related_name="meep_like", blank=True) def number_of_likes(self): return self.likes.count() def __str__(self): return( f"{self.user} " f"({self.created_at: %Y-%m-%d : %H-%M}): " f"{self.body}..." ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField("self", related_name="followed_by", symmetrical=False, blank=True) date_modified = models.DateTimeField(User, auto_now=True) profile_image=models.ImageField(null=True, blank=True, upload_to="images/") profile_bio = models.CharField(null=True, blank=True, max_length=500) homepage_link = models.CharField(null=True, blank=True, max_length=200) facebook_link = models.CharField(null=True, blank=True, max_length=200) instagram_link = models.CharField(null=True, blank=True, max_length=200) linkedin_link = models.CharField(null=True, blank=True,max_length=200) def __str__(self): return self.user.username def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() # have the user to follow themselves user_profile.follows.set([instance.profile.id]) user_profile.save() post_save.connect(create_profile, sender=User)
/* Goal: Lotto Application - Refactoring Number matching and Player functions Synopsis: (1)This game will take 3 players (2) Produce Weekly random Lotto winning numbers (3) Each Player will enter thier numbers for the week. (4) Mathing numbers will bank an amount for player (5) The winner will be the one with the hirst bank Math.floor((Math.random() * 100) + 1) */ //Load Libraries const rdLnSync = require('readline-sync'); //Take input from the keyboard const color = require('colors'); //Set the colors const say = require('say'); //Enable computer to speak to player //Arrays for both Machine and Player Numbers let playersOne = []; let playersTwo = []; let playersThree = []; let weeklyLottoNumber = []; //Player names let playerOneName = ''; let playerTwoName = ''; let playerThreeName = ''; //Array for counting let matchArrayOne = []; let matchArrayOneCount = 0; let matchArrayTwo = []; let matchArrayTwoCount = 0; let matchArrayThree = []; let matchArrayThreeCount = 0; //Prize money let prizeMoney = Number; //Quit function PlayerQuit = (lottoFunc) => { if (rdLnSync.keyInYN('Is this the only game player? ')) { lottoMatch(); } else if ((playersOne == 0) || (playersTwo == 0) || (playersThree == 0)) { //Call function lottoFunc(); } else { console.log(color.red('No more player slots!! hit any key to proceed with game')); rdLnSync.keyInPause(); lottoMatch(); }; }; //Function to create the weekly random numbers LottoGen = () => { let genNumbers = 0; for (let i = 0; i < 7; i ++) { genNumbers = Math.floor(Math.random() * 60); weeklyLottoNumber.push(genNumbers); }; }; //Player slot availability playerSlotChk = (inPlyrOne, inPlyrTwo, inPlyrThree) => { console.log(color.red('Player status!!!')); console.log(''); if (inPlyrOne.length == 0) { console.log(color.green('Player 1 Slot is available')); } else { console.log(color.red('Player 1 Slot is not available, select the next avalaible slot')); }; if (inPlyrTwo.length == 0) { console.log(color.green('Player 2 Slot is available')) } else { console.log(color.red('Player 2 Slot is not available, select the next avalaible slot')); }; if (inPlyrThree.length == 0) { console.log(color.green('Player 3 Slot is available')) } else { console.log(color.red('Player 2 Slot is not available, select the next avalaible slot')); }; }; enterLottoNumbers = (inPlyNumber) => { for (let i = 0; i < 7; i ++) { let inNum = rdLnSync.questionInt(color.yellow('Input number : ')); say.speak(inNum); if (inNum > 60) { console.log(color.red('Input must be between 0 and 60, Exiting...')); process.exit(0); }; inPlyNumber.push(inNum); }; }; //Function to take in User Number playerLottoNum = () => { say.speak('Players menu. Select a player, enter your name and lotto numbers'); console.log('\033c'); console.log(color.cyan('---------------- PLAYERS MENU ----------------')); console.log(''); console.log(color.green('Players')); let playerArray = ['Player 1', 'Player 2', 'Player 3']; //Player Slot chekc function playerSlotChk(playersOne, playersTwo, playersThree); let playSelect = rdLnSync.keyInSelect(playerArray, 'Enter player number: '); //Player 1 Condition if (playerArray[playSelect] == 'Player 1') { //Take Player one name playerOneName = rdLnSync.question('Enter your name: '); //Take in lotto numbers enterLottoNumbers(playersOne); //Player 2 Condition } else if (playerArray[playSelect] == 'Player 2') { //Take Player two name playerTwoName = rdLnSync.question('Enter your name: '); //Take in lotto numbers enterLottoNumbers(playersTwo); //Player 3 Condition } else if (playerArray[playSelect] == 'Player 3') { //Take Player three name playerThreeName = rdLnSync.question('Enter your name: '); //Take in lotto numbers enterLottoNumbers(playersThree); } else { //Go to the main menu mainMenu(); }; //Player quit function PlayerQuit(playerLottoNum); }; //Call function for the weekly number call lottoWeeksResult = () => { console.log('\033c'); console.log(color.cyan('************ THE WEEKS RESULTS ********************')); console.log('') LottoGen(); console.log(color.green(weeklyLottoNumber)); say.speak(`The Weekly Lotto Numbers are ${weeklyLottoNumber}`); }; //Check player one against Lotto number lottoNumCompare = (WklyLottoNum, PersonalLottoNum) => { if (PersonalLottoNum == 0) { //Array Count console.log(''); console.log(color.red(`No ${PersonalLottoNum} !!!`)); } else { console.log(''); console.log(color.green(`Number match for ${PersonalLottoNum}`)); console.log(''); //Match Player 1 numbers for (let i = 0; i < WklyLottoNum.length; i ++) { for (let g = 0; g < PersonalLottoNum.length; g ++) { if (WklyLottoNum[i] == PersonalLottoNum[g]) { console.log(PersonalLottoNum[g]); //Inset matches into an array for prize matchArrayOne.push(PersonalLottoNum[g]); } }; }; }; }; //Function to perform match of player number and weekly draw lottoMatch = () => { //Run weeks Lotto weeks results lottoWeeksResult(); //Pause program to continue for matching rdLnSync.keyInPause(); console.log('Matching process is starting now...'); lottoNumCompare(weeklyLottoNumber, playersOne); //Matching number count matchArrayOneCount = matchArrayOne.length; //Prize money calc function prizeMoneyCalc(matchArrayOneCount); say.speak(`${playerOneName} lotto numbers are ${playersOne}. Number match = ${matchArrayOneCount}. Prize is ${prizeMoney} pounds`); console.log(color.yellow(`Your numbers: ${playersOne}`)); console.log(`Lotto numbers: ${weeklyLottoNumber}`); console.log(''); console.log(color.cyan(matchArrayOneCount, `Matches`)); //Prize money lottoPrizeMoney(matchArrayOneCount); //Pause program to go to next player rdLnSync.keyInPause(); console.log('Press any letter to go to next player...'); //Check player two against Lotto number lottoNumCompare(weeklyLottoNumber, playersTwo); //Matching number count matchArrayTwoCount = matchArrayTwo.length; prizeMoneyCalc(matchArrayTwoCount); say.speak(`${playerTwoName} lotto numbers are ${playersTwo}. Number match = ${matchArrayTwoCount}. Prize is ${prizeMoney} pounds`); console.log(color.yellow(`Your numbers: ${playersTwo}`)); console.log(`Lotto numbers: ${weeklyLottoNumber}`); console.log(''); console.log(color.cyan(matchArrayTwoCount, `Matches`)); //Prize money lottoPrizeMoney(matchArrayTwoCount); //Pause program to go to next player rdLnSync.keyInPause(); console.log('Press any letter to go to next player...'); //Check player three against Lotto number lottoNumCompare(weeklyLottoNumber, playersThree); //Matching number count matchArrayThreeCount = matchArrayThree.length; prizeMoneyCalc(matchArrayTwoCount); say.speak(`${playerThreeName} lotto numbers are ${playersThree}. Number match = ${matchArrayThreeCount}. Prize is ${prizeMoney} pounds`); console.log(color.yellow(`Your numbers: ${playersThree}`)) ; console.log(`Lotto numbers: ${weeklyLottoNumber}`); console.log(''); console.log(color.cyan(matchArrayThreeCount, `Matches`)); //Prize money lottoPrizeMoney(matchArrayThreeCount); //Pause program to go to next player rdLnSync.keyInPause(); console.log('Press any letter to go to continue'); mainMenu(); }; //Prize money calculator prizeMoneyCalc = (inPrize) => { if (inPrize == 3) { prizeMoney = 10; } else if (inPrize == 4) { prizeMoney = 140; } else if (inPrize == 5) { prizeMoney = 1750; } else if (inPrize== 6) { prizeMoney = 1000000; } else { prizeMoney = 0 }; }; //Fuction to calculate prize money lottoPrizeMoney = (matchCount) => { switch (matchCount) { case 3: console.log('Congratulation!!! you matched 3 numbers and have been awarded £10'); break; case 4: console.log('Congratulation!!! you matched 4 numbers and have been awarded £140.00 '); break; case 5: console.log('Congratulation!!! you matched 5 numbers and have been awarded £1750.00 '); break; case 6: console.log('Congratulation!!! you matched 5 numbers and have been awarded £1 Million '); break; default: console.log('You matched less than 3 numbers. Better luck next time'); break; }; }; //Main Menu mainMenu = () => { say.speak('Welcome to the lotto guessing game. The game can be played by a maximum of 3 players. Good Luck') console.log('\033c'); console.log(''); console.log(color.cyan('------------------ LOTTO GUESSING GAME ------------------')); console.log(''); let menuArray = ['Lottery Game']; let menuSelect = rdLnSync.keyInSelect(menuArray, 'Make selection'); if(menuArray[menuSelect] == 'Lottery Game') { //Call main menu console.log('\033c'); playerLottoNum(); } else { console.log('\033c'); console.log(color.red('You have chosen to quit the game')); process.exit(0); }; }; //****************** MAIN PROGRAM STARTS HERE ************ */ //Game main menu mainMenu();
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { RegisterPage } from './register.page'; import { Router } from '@angular/router'; import { IonicModule } from '@ionic/angular'; import { AppRoutingModule } from 'src/app/app-routing.module'; describe('RegisterPage', () => { let component: RegisterPage; let fixture: ComponentFixture<RegisterPage>; let router: Router; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [RegisterPage], imports: [IonicModule.forRoot(), AppRoutingModule ] }).compileComponents(); fixture = TestBed.createComponent(RegisterPage); component = fixture.componentInstance; fixture.detectChanges(); router = TestBed.inject(Router); })); it('should go to home page on register', () => { spyOn(router,'navigate'); component.register(); expect(router.navigate).toHaveBeenCalledWith(['home']); }); });
import { ErrorRequestHandler } from 'express'; export interface ErrorObject { type: | 'unauthorized' | 'forbidden' | 'notFound' | 'conflict' | 'unprocessableEntity'; message: string; } const serviceErrorToStatusCode = { unauthorized: 401, forbidden: 403, notFound: 404, conflict: 409, unprocessableEntity: 422, }; function unauthorizedError(message: string): ErrorObject { return { type: 'unauthorized', message }; } function forbiddenError(message: string): ErrorObject { return { type: 'forbidden', message }; } function notFoundError(message: string): ErrorObject { return { type: 'notFound', message }; } function conflictError(message: string): ErrorObject { return { type: 'conflict', message }; } function unprocessableEntityError(message: string): ErrorObject { return { type: 'unprocessableEntity', message }; } // eslint-disable-next-line const errorHandler: ErrorRequestHandler = (error, req, res, next) => { const { type, message } = error as ErrorObject; if (type) { return res.status(serviceErrorToStatusCode[type]).send(message); } return res.status(500).send('Internal server error !'); }; export { errorHandler, unauthorizedError, forbiddenError, notFoundError, conflictError, unprocessableEntityError, };
from langchain.document_loaders import PyPDFLoader from langchain.chat_models.openai import ChatOpenAI from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores.chroma import Chroma from langchain.chains.conversation.memory import ConversationBufferWindowMemory from langchain.chains import ConversationalRetrievalChain from dotenv import load_dotenv import os load_dotenv() os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") #Initialize LLM llm = ChatOpenAI( openai_api_key = OPENAI_API_KEY, model_name='gpt-4', temperature=0.0 ) #Load PDF Document loader = PyPDFLoader("data/Resume-Self.pdf") #Split the PDF document into pages pages = loader.load_and_split() #Initialize chunk size and split the pages into smaller chuncks text_splitter = RecursiveCharacterTextSplitter( chunk_size = 500, chunk_overlap = 150 ) docs = text_splitter.split_documents(pages) #Create OPENAI Embeddings embeddings = OpenAIEmbeddings() #Chroma VectorStore to store the embeddings of the pdf chunks persist_directory = "" vectordb = Chroma.from_documents( documents = docs, embedding=embeddings, persist_directory = persist_directory ) #Create conversational memory conversational_memory = ConversationBufferWindowMemory( memory_key = 'chat_history', k = 5, return_message = True ) #create retreival chain using conversational memory qa = ConversationalRetrievalChain.from_llm( llm, retriever=vectordb.as_retriever(), memory=conversational_memory ) '''question1 = "Where did she do her bachelors?" print(question1) result = qa({"question": question1}) print(result['answer']) print("--------------------------------") question2 = "When did she graduate from her bachelors?" print(question2) result = qa({"question": question2}) print(result['answer']) print("--------------------------------") question3 = "Which city was her bachelors college located in?" print(question3) result = qa({"question": question3}) print(result['answer']) print("--------------------------------") question4 = "Where is she currently working and as what?" print(question4) result = qa({"question": question4}) print(result['answer']) print("--------------------------------")''' question5 = "What are her skill sets?" print(question5) result = qa({"question": question5}) print("--------------------------------") print(result['answer'])