Snippets Collections
Table.TransformColumns(Source, {{"Data", each Table.PromoteHeaders(_), type table}})
A Planilha de Fluxo de Caixa que todo negócio precisa para ter um controle de entradas e saídas bem feito possui 5 dashboards prontos, relatórios automáticos, classificação de contas e controle de status de pagamento. Com ela, você vai conseguir visualizar rapidamente a saúde financeira do seu negócio para tomar decisões mais seguras.
Com a Planilha de Fluxo de Caixa da LUZ, você ganha as funcionalidades de um sistema junto com a flexibilidade e a intuitividade de um modelo de Excel para controlar o seu fluxo de caixa.

A Planilha de Fluxo de Caixa ajuda negócios a controlarem suas entradas e saídas financeiras por meio de dashboards e relatórios automáticos.

Resumo da Planilha de Fluxo de Caixa
Dashboards e Relatórios Automáticos – Contém 5 dashboards para análise financeira rápida e relatórios automáticos.
Cadastro de Receitas e Despesas – Permite classificar entradas e saídas por tipo, ajudando na visualização detalhada do fluxo de caixa.
Lançamentos Diários – Registra entradas e saídas mensalmente, acompanhando saldos e pagamentos.
Monitoramento Diário – Identifica os melhores e piores dias para gestão do fluxo de caixa.
Relatório de Fluxo de Caixa – Exibe receitas, despesas, lucro/prejuízo e saldo acumulado.
Definição de Metas – Compara receitas e despesas planejadas com os valores realizados.
DRE (Demonstrativo de Resultado do Exercício) – Relatórios detalhados para análise pelo regime de competência.
Gestão de Valores em Aberto – Acompanha inadimplência de clientes e pagamentos pendentes.
Contas a Pagar e a Receber – Controle detalhado de obrigações financeiras.
Relatório para Impressão – Resultados financeiros apresentados em gráficos e tabelas prontas para impressão.
Dashboards Analíticos – Visões mensal, anual, de receitas, despesas e análise de contas para tomada de decisão.
A planilha permite tomadas de decisão mais seguras e melhor controle financeiro para o crescimento do negócio.

Dê uma olhada no link abaixo para acessar o Prompt que pode auxiliar você nesse tema. Tenho certeza de que isso vai transformar a maneira como você trabalha com seus dados e trazer mais praticidade ao seu dia a dia!

Link do Prompt:

https://prime.luz.vc/post/prompt-criar-plano-de-contas-gerencial-para-o-seu-fluxo-de-caixa

Lembre-se de SEMPRE habiltar as macros antes de ativar a planilha. Não sabe como?
Como Ativar sua Planilha LUZ
Precisa Compartilhar uma Planilha LUZ com sua equipe? Veja como:
Como Compartilhar sua Planilha
Para outras dúvidas: Fale com o Suporte
​[PROMPT] Fluxo de Caixa - Como criar metas de receitas e despesas precisas

Objetivo
Auxiliar na projeção de metas de receitas e despesas mensais para o ano, considerando fatores estratégicos, históricos financeiros, objetivos de crescimento sustentável e características específicas do ramo de mercado.


[INÍCIO DO PROMPT]

Atue como um consultor financeiro especializado no ramo de mercado do cliente e ajude a projetar metas de receitas e despesas mensais realistas e alinhadas com os objetivos estratégicos. Utilize as seguintes diretrizes para preencher uma tabela detalhada:

Histórico Financeiro:

Analise os dados passados para identificar padrões de receita e despesa ao longo dos meses.
Proponha ajustes para meses com sazonalidade, típicos do setor (ex.: varejo pode ter alta em dezembro; serviços educacionais em fevereiro).
Metas de Crescimento:

Estabeleça metas de receita alinhadas ao crescimento percentual esperado (ex.: 10% ao ano ou conforme o mercado).
Para as despesas, ajuste com base em reduções estratégicas ou investimentos planejados (ex.: marketing digital, treinamento de equipe).
Sazonalidade do Setor:

Identifique períodos de alta ou baixa demanda, comuns ao segmento (ex.: alta demanda no verão para turismo, ou baixa em feriados para indústrias).
Redistribua as metas para alinhar com essas flutuações naturais.
Investimentos Estratégicos:

Inclua projeções para despesas com iniciativas específicas do setor, como aquisição de estoque sazonal, lançamento de produtos ou serviços, ou campanhas publicitárias.
Equilíbrio Financeiro:

Garanta que o saldo anual de receitas menos despesas seja positivo, promovendo estabilidade e reserva financeira.
Dados fornecidos pelo usuário:

Ramo de mercado: (Exemplo: Varejo, Serviços Educacionais, Turismo, Indústria, etc.)
Receita mensal média histórica: (Exemplo: R$ 50.000)
Despesa mensal média histórica: (Exemplo: R$ 40.000)
Meta de crescimento anual: (Exemplo: 15%)
Meses de maior demanda no setor: (Exemplo: Dezembro, Janeiro)
Meses de maiores investimentos no setor: (Exemplo: Março, Agosto)
Prioridades estratégicas: (Exemplo: Expandir alcance digital, Aumentar vendas de produtos sazonais)
Novas tendências no mercado: (Exemplo: Crescimento no consumo online, Demanda por produtos sustentáveis)
Saída esperada:
A resposta deve apresentar uma tabela detalhada com as metas projetadas:

Mês	Receita Meta (R$)	Despesa Meta (R$)	Saldo Mensal (R$)
Janeiro	R$ XXX	R$ XXX	R$ XXX
Fevereiro	R$ XXX	R$ XXX	R$ XXX
Março	R$ XXX	R$ XXX	R$ XXX
...	...	...	...
Dezembro	R$ XXX	R$ XXX	R$ XXX
Total	R$ XXXX	R$ XXXX	R$ XXXX
Além disso, inclua uma breve explicação para cada projeção mensal, justificando ajustes e decisões estratégicas (ex.: "aumento de receita em dezembro devido à alta demanda no varejo" ou "despesa maior em março por conta de campanhas de marketing digital").

[FIM DO PROMPT]

---------------------------------------------------------------------------------------

Planilha de Controle de Tarefas para Download: https://prime.luz.vc/post/planilha-de-fluxo-de-caixa-40-em-excel
​[PROMP] Pitch de Negócio com o Círculo Dourado de Simon Sinek
Objetivo
Esse prompt foi idealizado para te ajudar a construri seu Pitch de Negócio utilizando a metodologia do Círculo Dourado de Simon Sinek


[INÍCIO DO PROMPT]
Olá, eu estou definindo um pitch para o meu negócio baseado no Cículo Dourado do Simon Sinek.
Eu sigo os parâmetros abaixo:
- Por que? - Missão / Propósito
- Como? - Proposta de Valor + Metodologia / Foco na Transformação que quero entregar para o meu ICP
- O que? - Produtos e Serviços
O meu negócio é uma consultoria em finanças, mas não quero me posicionar como consultoria.
Quero me posicionar como especialista no meu método exclusivo que entrega a minha proposta de valor.
Vou colocar alguns exemplos abaixo de pitches que eu gostei, para que você entenda a lógica e me ajude a estruturar meu pitch:

|| Exemplo 1
(Por quê?) Tudo que nós fazemos é pela nossa crença de desafiar o status quo. Nós acreditamos no poder da criatividade e da inovação.
(Como?) Ajudamos as pessoas a desafiarem o status quo construindo produtos com design arrojado, fáceis de usar e focados na experiência do usuário.
(O quê?) Como consequência, fazemos os melhores computadores do mercado. Vamos conversar?

|| Exemplo 2
(Por quê?) Tudo o que fazemos é por acreditar que o empreendedorismo desenvolve a sociedade. Todo empreendedor é um herói, merece atingir o seu potencial. Quando ajudamos um empreendedor, estamos criando uma sociedade mais próspera.
(Como?) Ajudamos empreendedores a ganharem escala em seus negócios com estratégia, ferramentas e automatização.
(O quê?) Você encontra tudo isso no LUZ Prime, uma plataforma onde você terá acesso a mais de 400 ferramentas de gestão, cursos e networking. Você quer fazer parte?

|| Exemplo 3
(Por quê?) Na LogiExpress, acreditamos que uma experiência de compra digital perfeita só ocorre quando a entrega é perfeita. O problema do seu cliente é um problema nosso!
(Como?) A sua logística não é um custo, é um diferencial competitivo, e nosso método exclusivo garante que você atinja cada canto do Brasil, sem atrasar.
(O quê?) Conheça a nossa consultoria em planejamento de rotas, gestão de estoque e estratégias de distribuição, especializada para o seu e-commerce. Vamos conversar?

Agora, eu quero que você atue como um especialista em branding e me passe 5 opções de pitch para a minha empresa, depois de olhar as instruções extras abaixo:
1. Você vai me fazer 5 perguntas, uma de cada vez sobre a minha empresa e sobre quem eu atendo.
2. Após fazer cada pergunta, você vai esperar a minha resposta antes de prosseguir
3. Quando você tiver a resposta, você vai me passar as opções de pitch
4. Eu quero ser o mais visceral o possível. Evite usar fatores que todos os consultores usam, como “ajudo sua empresa a se estruturar”, ou “ajudo você a se planejar”. Crie uma proposta que realmente chame a atenção do meu ICP. Que faça o meu convite para ele ser irrecusável!

[FIM DO PROMPT]
​[PROMPT] O Método Vaca Roxa para Dominar o Mercado
Objetivo
Ajudar profissionais e empresas a construir uma presença de destaque no LinkedIn, aplicando o conceito de "Vaca Roxa" para se diferenciarem da concorrência, estabelecerem autoridade, manterem consistência, gerarem engajamento e acelerarem seu crescimento na plataforma. O objetivo é criar estratégias práticas para transformar o perfil e o conteúdo em um ativo poderoso de conexão e oportunidades.

INÍCIO DO PROMPT
Você é um estrategista de marketing digital especializado em LinkedIn e diferenciação de marca pessoal e corporativa. Seu papel é orientar profissionais e empresas a aplicarem o conceito de "Vaca Roxa", garantindo que sua presença na plataforma seja notável e irresistível. Para isso, faça perguntas detalhadas e forneça estratégias personalizadas para que cada usuário possa criar conteúdo impactante, estabelecer autoridade e gerar crescimento.

1. Diferenciação: Criando uma Vaca Roxa no LinkedIn
Qual é o seu nicho ou setor de atuação?
O que faz você ou sua empresa únicos em relação à concorrência?
Há alguma história pessoal ou da empresa que mostre essa diferenciação de forma autêntica?
Como você pode transformar sua proposta de valor em algo notável? (Ex.: um formato de conteúdo inovador, um posicionamento ousado, uma abordagem inesperada).
2. Autoridade: Construindo Credibilidade e Reconhecimento
Quais são os temas centrais nos quais você quer ser reconhecido como especialista?
Você já compartilha conhecimento regularmente? Se sim, como (posts, artigos, vídeos, enquetes)?
Como você pode reforçar sua credibilidade? (Ex.: Compartilhando cases reais, publicando estudos de mercado, dando palestras).
Quais são as dúvidas mais comuns da sua audiência que você pode responder para demonstrar expertise?
3. Consistência: Mantendo uma Presença Sólida e Estratégica
Com que frequência você publica no LinkedIn? (Diária, semanal, esporádica)?
Existe um planejamento de conteúdo estruturado ou você posta de forma espontânea?
Quais tipos de conteúdo você já utiliza? (Ex.: Textos, vídeos, carrosséis, enquetes, lives).
Como você pode criar uma rotina para manter sua presença constante sem perder qualidade?
4. Engajamento: Criando Conteúdo Irresistível e Estimulando Conversas
Seu conteúdo gera interações significativas ou costuma ter pouco engajamento?
Você utiliza técnicas como storytelling, perguntas abertas e chamadas para ação para incentivar comentários?
Como você se envolve com sua audiência além de apenas postar? (Ex.: Respondendo comentários, interagindo em postagens de outros, enviando mensagens diretas estratégicas).
Quais formatos de postagens você pode testar para aumentar o engajamento? (Ex.: Conteúdo polêmico, bastidores do trabalho, insights sobre tendências, desafios pessoais/profissionais).
5. Estratégia de Crescimento: Aumentando Conexões e Oportunidades
Seu perfil está otimizado para atrair novos seguidores? (Ex.: Foto profissional, headline impactante, sobre bem estruturado).
Como você pode ampliar sua rede com conexões estratégicas? (Ex.: Conectando-se com influenciadores do setor, participando de discussões relevantes).
Você já utiliza mensagens diretas para fortalecer relacionamentos e gerar oportunidades de negócios?
Quais métricas você acompanha para avaliar seu crescimento no LinkedIn? (Ex.: Engajamento, visualizações de perfil, número de conexões, alcance das postagens).
6. Proposta de Projeto: Construindo uma Presença Notável no LinkedIn
Com base nas respostas fornecidas, desenvolva um Plano Estratégico de Posicionamento no LinkedIn contendo:

Definição do Posicionamento:

Descrição clara da sua diferenciação e proposta de valor.
Temas principais que você abordará para se destacar.
Plano de Conteúdo:

Formatos de postagens que serão priorizados (textos, vídeos, enquetes, artigos).
Frequência de publicações para manter a consistência.
Estratégias para tornar o conteúdo envolvente e relevante.
Táticas de Engajamento:

Estratégias para interagir com a audiência e criar conexões.
Abordagens para incentivar comentários e compartilhamentos.
Plano de Crescimento:

Como expandir a rede de conexões e atrair seguidores qualificados.
Métodos para fortalecer a autoridade e credibilidade no setor.
Métricas e Ajustes:

Quais indicadores acompanhar para medir o sucesso da estratégia.
Como otimizar as postagens e presença digital com base nos resultados.
FIM DO PROMPT
💰 Launch Your Own Stablecoin with Confidence!

Enter the world of stable digital assets with a secure, transparent, and fully customizable stablecoin development solution.

✅ Fiat-pegged, crypto-collateralized, or algorithmic stablecoins
✅ Regulatory-compliant & highly secure
✅ Seamless integration with wallets & exchanges
✅ Built for scalability & global transactions

🚀 Power up your crypto ecosystem with Dappfort – The Trusted Stablecoin Development Company!
  
Instant Reach Experts:
Contact : +91 8838534884
Mail : sales@dappfort.com
At Dappfort, a leading decentralized exchange development company, we provide end-to-end solutions to build high-performance DEX platforms. Our expertise ensures seamless trading, advanced security, and optimized scalability, empowering businesses to launch future-ready decentralized exchanges.

Instant Reach Experts:
Contact : +91 8838534884
Mail : sales@dappfort.com
🚀 The Future of Blockchain Business in 2025!

Blockchain is no longer just about crypto—it’s opening doors to groundbreaking business opportunities! From DeFi platforms to tokenized assets, new ventures are reshaping industries and creating endless possibilities.

Want to know which blockchain business ideas will dominate 2025? We've got 15 game-changing ideas that could be your next big move!

Don't miss out

Instant Reach Experts:

Contact : +91 8838534884
Mail : sales@dappfort.com
Dappfort is a leading cryptocurrency exchange development company committed to delivering high-quality, secure, and scalable trading platforms. With a strong focus on customer satisfaction, we have successfully developed and deployed various types of crypto exchanges tailored to our clients unique requirements. Our expert team ensures top-tier security, privacy, and reliability, fostering trust between business owners and their users. By leveraging our advanced cryptocurrency exchange solutions, including P2P trading and Bitcoin exchange systems, businesses can offer a seamless and highly secure trading experience. To explore how Dappfort can help you build a robust crypto exchange, schedule a consultation with our blockchain experts today.

Instant Reach Experts:

Visit us :  https://www.dappfort.com/cryptocurrency-exchange-development-company/      
Contact : +91 8838534884
Mail : sales@dappfort.com
https://medium.com/javarevisited/10-best-resources-to-learn-software-architecture-in-2025-2524ac91dc76
1) 10 Best Resources of books to Learn Software Architecture. 
1)delete my personal phone no which is linked to metriqe's google account, the google account which I created in the name of stephen-metriqe.
2)just have to return laptop and charger.
map(int, input().split())
// html
 <div id="app">
      <div class="grid-container">
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
      </div>
    </div>


//css


.grid-container {
  background-color: aliceblue;
  width: 100%;
  min-height: 200px;
  display: grid;
  column-gap: 1rem;
  grid-template-columns: repeat(
    var(--col-grid-count, 4),
    var(--col-make-width, 1fr)
  );
}

.box {
  width: 100%;
  height: 100%;
  background-color: firebrick;
  padding-top: 1rem;
}

.box a {
  text-align: center;
  margin-top: 1rem;
  color: white;
  display: flex;
  justify-content: center;
  cursor: pointer;
  text-decoration: none;
}


//js

(function () {
  "use strict";

  const gridContainer = document.querySelector(".grid-container");

  if (!gridContainer) return;

  function changeItemWith(value) {
    gridContainer.style.setProperty("--col-make-width", value);
  }

  function updateGrid(number) {
    const updatedBoxes = document.querySelectorAll(".box").length;
    gridContainer.style.setProperty("--col-grid-count", updatedBoxes);

    const widthOptions = {
      1: () => changeItemWith("minmax(230px, 250px)"),
      2: () => changeItemWith("minmax(295px, 320px)"),
      3: () => changeItemWith("minmax(245px, 420px)"),
      4: () => changeItemWith("minmax(243px, 500px)"),
    };

    console.log(`Number of boxes: ${number}`);
    console.log(`Function in widthOptions:`, widthOptions[number]);

    // Fix: Call the function if it exists, otherwise apply default width
    // see note on how widthOptions[number](); works
    if (widthOptions[number]) {
      widthOptions[number]();
    } else {
      changeItemWith("205px"); // Default case
    }
  }

  function onHandleLink(event) {
    event.preventDefault();

    const link = event.currentTarget;
    const box = link.parentElement;

    if (box) {
      box.remove();
      // Fix: Pass the correct length
      updateGrid(document.querySelectorAll(".box").length); 
    }

    console.log(box);
  }

  function listeners() {
    document.querySelectorAll(".box").forEach((box) => {
      const link = box.querySelector("a");
      if (link) {
        link.addEventListener("click", onHandleLink);
      }
    });
  }

  function init() {
    // Fix: Pass the correct length
    updateGrid(document.querySelectorAll(".box").length); 
    listeners();
  }

  init();
})();



/*
NOTE; Understanding widthOptions 

widthOptions is an object where each key (like 1, 2, etc.) maps to a function:

const widthOptions = {
  1: () => changeItemWith("minmax(230px, 250px)"),
  2: () => changeItemWith("minmax(295px, 249px)"),
  3: () => changeItemWith("minmax(245px, 1fr)"),
  4: () => changeItemWith("minmax(243px, 1fr)"),
};

Each value is an anonymous function (() => {}) that calls changeItemWith(...).


Accessing a Function in an Object
If number is 1, then: widthOptions[1]

is the same as: () => changeItemWith("minmax(230px, 250px)");
which in the widthOptions object is:  1: () => changeItemWith("minmax(230px, 250px)")


So if we call it with (), it executes:
widthOptions[1]();
*/ 

// See codesandbox for my implementation
// https://codesandbox.io/p/sandbox/q3926h?file=%2Fsrc%2Findex.mjs%3A28%2C6-28%2C30
{
	"xlog": {
    "prefix": "xlog",
    "body": [
        "console.log(JSON.parse(JSON.stringify(${1:var}));"
    ],
    "description": "logs json stuff through proxy"
	}
}
span {
  display: block;
  -webkit-mask-image: linear-gradient(to bottom, white, transparent);
  mask-image: linear-gradient(to bottom, white, transparent);
}
Public Function getXPathElement(sXPath As String, objElement As Object) As HTMLBaseElement
Dim sXPathArray() As String

Dim sNodeName As String
Dim sNodeNameIndex As String
Dim sRestOfXPath As String
Dim lNodeIndex As Long
Dim lCount As Long

' Split the xpath statement
sXPathArray = Split(sXPath, "/")
sNodeNameIndex = sXPathArray(1)
If Not InStr(sNodeNameIndex, "[") &gt; 0 Then
sNodeName = sNodeNameIndex
lNodeIndex = 1
Else
sXPathArray = Split(sNodeNameIndex, "[")
sNodeName = sXPathArray(0)
lNodeIndex = CLng(Left(sXPathArray(1), Len(sXPathArray(1)) - 1))
End If
sRestOfXPath = Right(sXPath, Len(sXPath) - (Len(sNodeNameIndex) + 1))

Set getXPathElement = Nothing
For lCount = 0 To objElement.ChildNodes().Length - 1
If UCase(objElement.ChildNodes().item(lCount).nodeName) = UCase(sNodeName) Then
If lNodeIndex = 1 Then
If sRestOfXPath = "" Then
Set getXPathElement = objElement.ChildNodes().item(lCount)
Else
Set getXPathElement = getXPathElement(sRestOfXPath, objElement.ChildNodes().item(lCount))
End If
End If
lNodeIndex = lNodeIndex - 1
End If
Next lCount
End Function
Public Sub parsehtml()
Dim http As Object, html As New HTMLDocument, topics As Object, titleElem As Object, detailsElem As Object, topic As HTMLHtmlElement
Dim i As Integer
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://news.ycombinator.com/", False
http.send
html.body.innerHTML = http.responseText
Set topics = html.getElementsByClassName("athing")
i = 2
For Each topic In topics
Set titleElem = topic.getElementsByTagName("td")(2)
Sheets(1).Cells(i, 1).Value = titleElem.getElementsByTagName("a")(0).innerText
Sheets(1).Cells(i, 2).Value = titleElem.getElementsByTagName("a")(0).href
Set detailsElem = topic.NextSibling.getElementsByTagName("td")(1)
Sheets(1).Cells(i, 3).Value = detailsElem.getElementsByTagName("span")(0).innerText
Sheets(1).Cells(i, 4).Value = detailsElem.getElementsByTagName("a")(0).innerText
i = i + 1
Next
End Sub
Common          EmployeeHoliday;
DictTable       dictTable;
SQLDICTIONARY   SqlDictionary;
int             FromDate, ToDate;

select tabId from SqlDictionary
    where SqlDictionary.name == "NW_UpdateEmployeeHoliday"
    && SqlDictionary.fieldId == 0;

dictTable = new DictTable(SqlDictionary.tabId);
EmployeeHoliday = dictTable.makeRecord();

FromDate = fieldname2id(SqlDictionary.tabId,"FromDate");
ToDate   = fieldname2id(SqlDictionary.tabId,"ToDate");
date holiday, endHoliday;
end =  start+180;
while select EmployeeHoliday
{
    holiday = EmployeeHoliday.(FromDate);
    endHoliday = EmployeeHoliday.(ToDate);
    while(holiday <= endHoliday && (start <= holiday && holiday <= end))
    {
        holiday+=1;
        end+=1;
    }
}
https://medium.com/@janpaepke/structured-logging-in-the-grafana-monitoring-stack-8aff0a5af2f5
1) Structured Logging in the Grafana monitoring stack
  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  assignedTeamIds?: string[];

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  assignedMemberIds?: string[];
1.




import 'package:enum_to_string/enum_to_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:rrispat_app/src/constants/enums.dart';
import 'package:rrispat_app/src/core/utils.dart';
import 'package:rrispat_app/src/features/gi/domain/models/pco_handover_model.dart';
import 'package:rrispat_app/src/features/gi/domain/provider/all_pco_handover_provider.dart';

import '../../../../core/components/division_card.dart';
import 'verify_details_page.dart';

class VerifyHandOverPage extends ConsumerStatefulWidget {
  const VerifyHandOverPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _VerifyHandOverPageState();
}

class _VerifyHandOverPageState extends ConsumerState<VerifyHandOverPage> {
  List<PCOHandoverModel> pcoHandOverdata = [];

  @override
  Widget build(BuildContext context) {
    pcoHandOverdata.clear();
    ref
        .read(giAllPcoHandOverDataProvider.notifier)
        .getAllHandOver()
        .forEach((element) {
      pcoHandOverdata.add(element);
    });
    return ListView.builder(
      itemCount: pcoHandOverdata.length,
      itemBuilder: (context, index) {
        return buildTransaction(pcoHandOverdata[index]);
      },
    );
  }

  Widget buildTransaction(PCOHandoverModel pcoHandoverModel) {
    print(pcoHandoverModel);
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      child: InkWell(
        onTap: () => context.pushNamed(VerifyDetailsPage.routeName,
            pathParameters: {'id': pcoHandoverModel.id.toString()}),
        borderRadius: BorderRadius.circular(15),
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.blue.shade200, Colors.blue.shade50],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(15),
            boxShadow: [
              BoxShadow(
                color: Colors.blue.withOpacity(0.3),
                offset: const Offset(0, 6),
                blurRadius: 12,
              ),
            ],
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Header Row with Date, Division and Shift
                Row(
                  children: [
                    Text(
                      DateFormat.yMMMEd().format(
                        DateTime.parse(pcoHandoverModel.createdAt.toString()),
                      ),
                      style: Theme.of(context).textTheme.labelMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                    ),
                    const SizedBox(width: 10),
                    DivisionCard(
                      division: EnumToString.fromString(
                        Division.values,
                        pcoHandoverModel.division,
                      ) as Division,
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        Icon(
                          (pcoHandoverModel.shift == "Day")
                              ? Icons.light_mode
                              : Icons.dark_mode,
                          size: 28,
                          color: Colors.black54,
                        ),
                        Text(
                          pcoHandoverModel.shift.toString(),
                          style: Theme.of(context)
                              .textTheme
                              .labelMedium
                              ?.copyWith(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                // Summary Row with Trail No, Items Count and Verified Count
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "TrailNo : ${pcoHandoverModel.trailNo}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Type of Items : ${pcoHandoverModel.pcoModels.length}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Verify Items : ${pcoHandoverModel.pcoModels.fold(0, (previousValue, element) => (element.verify == true) ? previousValue + 1 : previousValue)}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                const Divider(
                  height: 20,
                  thickness: 1,
                  color: Colors.blueGrey,
                ),
                // Details Chips
                Wrap(
                  spacing: 10,
                  runSpacing: 8,
                  children: [
                    detailChip(
                        label: "JC No",
                        value: pcoHandoverModel.pcoModels[0].jcNo.toString()),
                    detailChip(
                        label: "Mark No",
                        value: pcoHandoverModel.pcoModels[0].markNo.toString()),
                    detailChip(
                        label: "Section",
                        value:
                            pcoHandoverModel.pcoModels[0].section.toString()),
                    detailChip(
                        label: "Thickness",
                        value:
                            pcoHandoverModel.pcoModels[0].thickness.toString()),
                    detailChip(
                        label: "Length",
                        value: pcoHandoverModel.pcoModels[0].length.toString()),
                    detailChip(
                        label: "Quantity",
                        value:
                            pcoHandoverModel.pcoModels[0].quantity.toString()),
                    detailChip(
                        label: "Weight",
                        value: pcoHandoverModel.pcoModels[0].weight.toWeight()),
                    detailChip(
                        label: "Total Weight",
                        value: (pcoHandoverModel.pcoModels[0].quantity *
                                pcoHandoverModel.pcoModels[0].weight)
                            .toWeight()),
                    detailChip(
                        label: "Reject Qty",
                        value: pcoHandoverModel.pcoModels[0].rejectQuantity
                            .toString()),
                    detailChip(
                        label: "Reject Wt",
                        value: pcoHandoverModel.pcoModels[0].rejectWeights!
                            .toWeight()),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget detailChip({required String label, required String value}) {
    return Chip(
      label: Text(
        "$label: $value",
        style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
      ),
      backgroundColor: Colors.white.withOpacity(0.8),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
    );
  }
}






2.



import 'package:enum_to_string/enum_to_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:rrispat_app/src/constants/enums.dart';
import 'package:rrispat_app/src/core/utils.dart';
import 'package:rrispat_app/src/features/gi/domain/models/pco_handover_model.dart';
import 'package:rrispat_app/src/features/gi/domain/provider/all_pco_handover_provider.dart';

import '../../../../core/components/division_card.dart';
import 'verify_details_page.dart';

class VerifyHandOverPage extends ConsumerStatefulWidget {
  const VerifyHandOverPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _VerifyHandOverPageState();
}

class _VerifyHandOverPageState extends ConsumerState<VerifyHandOverPage> {
  List<PCOHandoverModel> pcoHandOverdata = [];
  @override
  Widget build(BuildContext context) {
    pcoHandOverdata.clear();
    ref
        .read(giAllPcoHandOverDataProvider.notifier)
        .getAllHandOver()
        .forEach((element) {
      pcoHandOverdata.add(element);
    });
    return Container(
      // A subtle gradient background for an extra layer of visual depth.
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.white, Colors.grey[200]!],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: ListView.builder(
        itemCount: pcoHandOverdata.length,
        itemBuilder: (context, index) {
          return buildTransaction(pcoHandOverdata[index]);
        },
      ),
    );
  }

  Widget buildTransaction(PCOHandoverModel pcoHandoverModel) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      child: GestureDetector(
        onTap: () => context.pushNamed(
          VerifyDetailsPage.routeName,
          pathParameters: {'id': pcoHandoverModel.id.toString()},
        ),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
          // A slight transform adds a subtle 3D tilt effect.
          transform: Matrix4.identity()
            ..setEntry(3, 2, 0.001)
            ..rotateX(0.02),
          decoration: BoxDecoration(
            color: Theme.of(context).cardColor,
            borderRadius: BorderRadius.circular(12),
            // Dual shadows simulate a raised, 3D look.
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                offset: const Offset(4, 4),
                blurRadius: 8,
              ),
              BoxShadow(
                color: Colors.white.withOpacity(0.8),
                offset: const Offset(-4, -4),
                blurRadius: 8,
              ),
            ],
          ),
          child: ListTile(
            contentPadding: const EdgeInsets.all(16),
            trailing: (pcoHandoverModel.shift == "Day")
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(
                        Icons.light_mode,
                        size: 28,
                      ),
                      Text(pcoHandoverModel.shift.toString())
                    ],
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(
                        Icons.dark_mode,
                        size: 28,
                      ),
                      Text(pcoHandoverModel.shift.toString())
                    ],
                  ),
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      DateFormat().add_yMMMEd().format(DateTime.parse(
                          pcoHandoverModel.createdAt.toString())),
                      style: Theme.of(context).textTheme.labelMedium,
                    ),
                    const SizedBox(width: 10),
                    DivisionCard(
                      division: EnumToString.fromString(
                              Division.values, pcoHandoverModel.division)
                          as Division,
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "TrailNo : ${pcoHandoverModel.trailNo}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Type of Items : ${pcoHandoverModel.pcoModels.length}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Verify Items : ${pcoHandoverModel.pcoModels.fold(0, (previousValue, element) => (element.verify == true) ? previousValue + 1 : previousValue)}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ],
            ),
            // Using a Wrap for subtitle texts ensures responsiveness without altering your color choices.
            subtitle: Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Wrap(
                spacing: 8,
                runSpacing: 4,
                children: [
                  Text(
                      "JC No : ${pcoHandoverModel.pcoModels[0].jcNo.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Mark No : ${pcoHandoverModel.pcoModels[0].markNo.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Section : ${pcoHandoverModel.pcoModels[0].section.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Thickness : ${pcoHandoverModel.pcoModels[0].thickness.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Length : ${pcoHandoverModel.pcoModels[0].length.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Quantity : ${pcoHandoverModel.pcoModels[0].quantity.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Weight : ${pcoHandoverModel.pcoModels[0].weight.toWeight()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Total Weight : ${(pcoHandoverModel.pcoModels[0].quantity * pcoHandoverModel.pcoModels[0].weight).toWeight()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Reject Quantity : ${pcoHandoverModel.pcoModels[0].rejectQuantity.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Reject Weight : ${pcoHandoverModel.pcoModels[0].rejectWeights!.toWeight()}",
                      style: Theme.of(context).textTheme.labelMedium),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}


3.




import 'package:enum_to_string/enum_to_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:rrispat_app/src/constants/enums.dart';
import 'package:rrispat_app/src/core/utils.dart';
import 'package:rrispat_app/src/features/gi/domain/models/pco_handover_model.dart';
import 'package:rrispat_app/src/features/gi/domain/provider/all_pco_handover_provider.dart';

import '../../../../core/components/division_card.dart';
import 'verify_details_page.dart';

class VerifyHandOverPage extends ConsumerStatefulWidget {
  const VerifyHandOverPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _VerifyHandOverPageState();
}

class _VerifyHandOverPageState extends ConsumerState<VerifyHandOverPage> {
  List<PCOHandoverModel> pcoHandOverdata = [];
  @override
  Widget build(BuildContext context) {
    pcoHandOverdata.clear();
    ref
        .read(giAllPcoHandOverDataProvider.notifier)
        .getAllHandOver()
        .forEach((element) {
      pcoHandOverdata.add(element);
    });
    return Container(
      // decoration: BoxDecoration(
      //   gradient: LinearGradient(
      //     colors: [Colors.white, Colors.blue.shade50], // subtle gradient
      //     begin: Alignment.topCenter,
      //     end: Alignment.bottomCenter,
      //   ),
      // ),
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(vertical: 10),
        itemCount: pcoHandOverdata.length,
        itemBuilder: (context, index) {
          return buildTransaction(pcoHandOverdata[index]);
        },
      ),
    );
  }

  Widget buildTransaction(PCOHandoverModel pcoHandoverModel) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      child: Card(
        elevation: 8,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () => context.pushNamed(VerifyDetailsPage.routeName,
              pathParameters: {'id': pcoHandoverModel.id.toString()}),
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Column(
              children: [
                // Top row: Date, Division and Shift Icon/Label
                Row(
                  children: [
                    Text(
                      DateFormat().add_yMMMEd().format(DateTime.parse(
                          pcoHandoverModel.createdAt.toString())),
                      style: Theme.of(context).textTheme.labelMedium,
                    ),
                    const SizedBox(width: 10),
                    DivisionCard(
                      division: EnumToString.fromString(
                              Division.values, pcoHandoverModel.division)
                          as Division,
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        Icon(
                          pcoHandoverModel.shift == "Day"
                              ? Icons.light_mode
                              : Icons.dark_mode,
                          size: 28,
                        ),
                        Text(
                          pcoHandoverModel.shift.toString(),
                          style: Theme.of(context).textTheme.bodySmall,
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                // Middle row: TrailNo, Type of Items and Verify Items count
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "TrailNo : ${pcoHandoverModel.trailNo}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Type of Items : ${pcoHandoverModel.pcoModels.length}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Verify Items : ${pcoHandoverModel.pcoModels.fold(0, (previousValue, element) => (element.verify == true) ? previousValue + 1 : previousValue)}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                // Conditionally display the details only if there is at least one model
                if (pcoHandoverModel.pcoModels.length <= 1)
                  Wrap(
                    spacing: 10,
                    runSpacing: 5,
                    children: [
                      Text("JC No : ${pcoHandoverModel.pcoModels[0].jcNo}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text("Mark No : ${pcoHandoverModel.pcoModels[0].markNo}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text("Section : ${pcoHandoverModel.pcoModels[0].section}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Thickness : ${pcoHandoverModel.pcoModels[0].thickness}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text("Length : ${pcoHandoverModel.pcoModels[0].length}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Quantity : ${pcoHandoverModel.pcoModels[0].quantity}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Weight : ${pcoHandoverModel.pcoModels[0].weight.toWeight()}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Total Weight : ${(pcoHandoverModel.pcoModels[0].quantity * pcoHandoverModel.pcoModels[0].weight).toWeight()}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Reject Quantity : ${pcoHandoverModel.pcoModels[0].rejectQuantity}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Reject Weight : ${pcoHandoverModel.pcoModels[0].rejectWeights!.toWeight()}",
                          style: Theme.of(context).textTheme.labelMedium),
                    ],
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


Set identity_insert ma_table on

-- on ajoute les items

set identity_insert ma_table off
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:excel/excel.dart' as exc;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:rrispat_app/src/features/store/domain/models/store_user_model.dart';
import 'package:rrispat_app/src/shared/providers/providers.dart';
import '../../../../../l10n/app_localizations.dart';
import '../../../../shared/widgets/loader_widget.dart';
import '../../../../shared/widgets/rr_filled_button.dart';
import '../../../auth/controllers/auth_controller.dart';
import '../../../auth/domains/models/auth_model.dart';
import '../../../auth/domains/providers/auth_model_provider.dart';
import '../../controller/store_item_controller.dart';
import '../../controller/store_user_controller.dart';
import '../../domain/models/store_item_model.dart';
import '../../domain/store_enums.dart';

class StoreAddStock extends ConsumerStatefulWidget {
  const StoreAddStock({Key? key}) : super(key: key);

  @override
  ConsumerState<StoreAddStock> createState() => _StoreAddStockState();
}

class _StoreAddStockState extends ConsumerState<StoreAddStock> {
  final GlobalKey<FormState> _pieces = GlobalKey<FormState>();

  bool _showLoading = true;

  final TextEditingController _itemNameController = TextEditingController();
  final TextEditingController _poNumberController = TextEditingController();

  final TextEditingController pieces = TextEditingController();

  StoreUserModel? storeUser;
  List<StoreItemModel> storeItemListfromBe = [];
  List<AuthModel> authModels = [];
  double screenWidth = 0;

  PaginationParams _paginationParams = PaginationParams(
    page: 1,
    pageSize: 10,
    totalPages: 0,
    itemName: '',
    poNumber: '',
  );

  int _totalItems = 0;

  @override
  void initState() {
    super.initState();

    Timer(const Duration(seconds: 90), () {
      if (mounted) {
        setState(() {
          _showLoading = false;
        });
      }
    });
  }

  Future<void> uploadExcelDataFromWebStoreStockAdd(BuildContext context) async {
    FilePickerResult? file = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xlsx'],
      allowMultiple: false,
    );
    if (file != null) {
      List<StoreItemModel> tempList = [];
      Uint8List fileBytes = file.files.first.bytes!;
      var excel = exc.Excel.decodeBytes(fileBytes);
      for (var table in excel.tables.keys) {
        for (var row in excel.tables[table]!.rows) {
          if (row[0]?.value.toString() == "Company Name") continue;
          try {
            StoreItemModel storeItemModel = StoreItemModel(
              id: '',
              itemName: (row[4]?.value).toString(),
              vendorName: (row[1]?.value).toString(),
              pieces: double.parse((row[6]?.value).toString()),
              issuedPcs: double.parse(0.toString()),
              createdAt: DateTime.now(),
              createdBy: ref.read(authModelProvider)!.uid,
              itemCode: (row[3]?.value).toString(),
              poNumber: (row[8]?.value).toString(),
              unit: (row[5]?.value).toString(),
              issuedCompleted: double.parse(0.toString()),
              sapItemCode: '',
              plantName: (row[10]?.value).toString(),
              poDate: (row[11]?.value).toString(),
              status: StoreItemStatus.approved,
              type: StoreItemCreatedType.normal,
              remark: '',
            );
            tempList.add(storeItemModel);
          } catch (e) {
            print("$e store item error getFile");
          }
        }
      }
      for (var element in tempList) {
        ref
            .read(storeItemControllerProvider)
            .createStoreItemStock(ref, element);
      }
    }
  }

  Widget buildFilters(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth < 600) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextFormField(
            controller: _itemNameController,
            decoration: InputDecoration(
              labelText: "Filter by Item Name",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: value,
                  poNumber: _poNumberController.text,
                );
              });
            },
          ),
          const SizedBox(height: 10),
          TextFormField(
            controller: _poNumberController,
            decoration: InputDecoration(
              labelText: "Filter by PO Number",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: _itemNameController.text,
                  poNumber: value,
                );
              });
            },
          ),
          const SizedBox(height: 10),
        ],
      );
    } else {
      return Row(
        children: [
          Expanded(
            child: TextFormField(
              controller: _itemNameController,
              decoration: InputDecoration(
                labelText: "Filter by Item Name",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: value,
                    poNumber: _poNumberController.text,
                  );
                });
              },
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: TextFormField(
              controller: _poNumberController,
              decoration: InputDecoration(
                labelText: "Filter by PO Number",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: _itemNameController.text,
                    poNumber: value,
                  );
                });
              },
            ),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    screenWidth = MediaQuery.of(context).size.width;

    ref
        .watch(authUserListStreamProvider)
        .whenData((value) => authModels = value);
    ref.watch(storeUserStreamProvider).whenData((value) => storeUser = value);

    return Scaffold(
      appBar: AppBar(
        title: Text('PO - Stock Add'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            if (storeUser != null &&
                storeUser!.userType.contains(StoreUserType.poListUpload))
              Center(
                child: RrFilledButton(
                  onPressed: () {
                    uploadExcelDataFromWebStoreStockAdd(context);
                  },
                  label: ('Store Item Excel File Upload'),
                ),
              ),
            const SizedBox(height: 20),
            buildFilters(context),
            const SizedBox(height: 10),
            Expanded(
              child: ref
                  .watch(storeItemStockListWithPaginationStreamProvider(
                      _paginationParams))
                  .when(
                    data: (paginatedData) {
                      _totalItems = paginatedData.totalItems;
                      _paginationParams = PaginationParams(
                        page: _paginationParams.page,
                        pageSize: _paginationParams.pageSize,
                        totalPages: paginatedData.totalPages,
                        itemName: _itemNameController.text,
                        poNumber: _poNumberController.text,
                      );
                      if (paginatedData.storeItemStocks.isEmpty) {
                        return _showLoading
                            ? const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: CircularProgressIndicator()),
                              )
                            : const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: Text("No Stock Item Found")),
                              );
                      } else {
                        return ListView.builder(
                          itemCount: paginatedData.storeItemStocks.length,
                          itemBuilder: (context, index) {
                            return addStockCard(
                                context, paginatedData.storeItemStocks[index]);
                          },
                        );
                      }
                    },
                    error: (error, stack) =>
                        Center(child: Text(error.toString())),
                    loading: () =>
                        const Center(child: CircularProgressIndicator()),
                  ),
            ),
            _buildPageNumbers(
                computedTotalPages: _paginationParams.totalPages ?? 1),
          ],
        ),
      ),
    );
  }

  Widget _buildPageNumbers({required int computedTotalPages}) {
    int totalVisiblePages = 5;
    List<Widget> pageButtons = [];
    int startPage = max(1, _paginationParams.page - totalVisiblePages ~/ 2);
    int endPage = min(computedTotalPages, startPage + totalVisiblePages - 1);
    if (endPage - startPage < totalVisiblePages - 1) {
      startPage = max(1, endPage - totalVisiblePages + 1);
    }
    if (startPage > 1) {
      pageButtons.add(_pageButton(1, 'First'));
    }
    for (int i = startPage; i <= endPage; i++) {
      pageButtons.add(_pageButton(i, '$i'));
    }
    if (endPage < computedTotalPages) {
      pageButtons.add(_pageButton(computedTotalPages, 'Last'));
    }
    return Wrap(
      alignment: WrapAlignment.center,
      children: pageButtons,
    );
  }

  Widget _pageButton(int pageNumber, String text) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: InkWell(
        onTap: () => _changePage(pageNumber),
        child: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Text(
            text,
            style: TextStyle(
              color: pageNumber == _paginationParams.page
                  ? Theme.of(context).colorScheme.primary
                  : Colors.grey,
            ),
          ),
        ),
      ),
    );
  }

  void _changePage(int page) {
    if (page != _paginationParams.page) {
      setState(() {
        _paginationParams = PaginationParams(
          page: page,
          pageSize: _paginationParams.pageSize,
          totalPages: _paginationParams.totalPages,
          itemName: _itemNameController.text,
          poNumber: _poNumberController.text,
        );
      });
    }
  }

  Widget addStockCard(BuildContext context, StoreItemModel storeItemModel) {
    bool isClosed = storeItemModel.issuedPcs != 0;
    AuthModel closedByPerson = authModels.firstWhere(
      (element) => element.uid == storeItemModel.createdBy,
    );
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 5),
      child: Card(
        color: Theme.of(context).colorScheme.background,
        child: ListTile(
          leading: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.tertiary,
              shape: BoxShape.circle,
            ),
            alignment: Alignment.center,
            child: Text(
              storeItemModel.pieces.toStringAsFixed(2),
              style: Theme.of(context)
                  .textTheme
                  .titleMedium
                  ?.copyWith(color: Colors.white, fontSize: 9),
              textAlign: TextAlign.center,
            ),
          ),
          title: Text(
            storeItemModel.itemName.toUpperCase(),
            style: Theme.of(context).textTheme.titleLarge,
          ),
          subtitle: Wrap(
            spacing: 20,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Pieces: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.pieces.toStringAsFixed(2)),
                  Text(" ${storeItemModel.unit.toString()}"),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Vendor Name')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.vendorName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "SAP Item Code: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.itemCode),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Plant Name: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.plantName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Created Date: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poDate),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Number: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poNumber),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Created At')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(
                    ref
                        .read(dateFormatterProvider)
                        .format(storeItemModel.createdAt),
                  ),
                ],
              ),
              screenWidth <= 500
                  ? (isClosed)
                      ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              "Closed By : ${closedByPerson.fullName}",
                              style: TextStyle(
                                color: Theme.of(context).colorScheme.tertiary,
                              ),
                            ),
                          ],
                        )
                      : Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            buildIconButton(
                              Icons.done_all_rounded,
                              AppLocalizations.of(context).translate('Approve'),
                              () {
                                addStockModel(storeItemModel);
                              },
                            ),
                            const SizedBox(width: 20),
                            buildIconButton(
                              Icons.close_rounded,
                              'Close',
                              () {
                                partiallyCloseStockModel(storeItemModel);
                              },
                            ),
                          ],
                        )
                  : const SizedBox.shrink(),
            ],
          ),
          trailing: screenWidth > 500
              ? (isClosed)
                  ? Wrap(
                      children: [
                        Text(
                          "Closed By : ${closedByPerson.fullName}",
                          style: TextStyle(
                            color: Theme.of(context).colorScheme.tertiary,
                          ),
                        ),
                      ],
                    )
                  : Wrap(
                      children: [
                        buildIconButton(
                          Icons.done_all_rounded,
                          AppLocalizations.of(context).translate('Approve'),
                          () {
                            addStockModel(storeItemModel);
                          },
                        ),
                        const SizedBox(width: 20),
                        buildIconButton(
                          Icons.close_rounded,
                          'Close',
                          () {
                            partiallyCloseStockModel(storeItemModel);
                          },
                        ),
                      ],
                    )
              : null,
        ),
      ),
    );
  }

  Widget buildIconButton(
      IconData icon, String tooltip, void Function() onPressed) {
    return Tooltip(
      message: tooltip,
      child: IconButton(
        onPressed: onPressed,
        icon: Icon(
          icon,
          color: Theme.of(context).colorScheme.tertiary,
        ),
      ),
    );
  }

  void partiallyCloseStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: const SizedBox(
              height: 80,
              child: Center(
                child: Column(
                  children: [
                    Text('Are you sure you want to close this stock item?'),
                    SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('Close'),
                onPressed: () async {
                  String closedBy = ref.read(authModelProvider)!.uid;
                  ref.read(storeItemControllerProvider).updateStoreItemStock(
                      ref, storeItemModel, storeItemModel.pieces, closedBy);
                  context.pop(true);
                  ref.invalidate(
                      storeItemStockListWithPaginationStreamProvider);
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }

  void addStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: SizedBox(
              height: 180,
              child: Center(
                child: Column(
                  children: [
                    Text('Item Name : ${storeItemModel.itemName}'),
                    const SizedBox(height: 5),
                    Text(
                        'Total pcs. in Po list : ${storeItemModel.pieces} ${storeItemModel.unit}'),
                    const SizedBox(height: 10),
                    Form(
                      key: _pieces,
                      child: TextFormField(
                        validator: (text) {
                          if (text == null ||
                              text.isEmpty ||
                              double.parse(text) < 1) {
                            return 'Please enter Pieces to add';
                          }
                          if (double.parse(text) >
                              (storeItemModel.pieces +
                                  (storeItemModel.pieces * 0.1))) {
                            return 'Pcs should not be greater than available stock';
                          }
                          return null;
                        },
                        controller: pieces,
                        keyboardType: TextInputType.number,
                        textCapitalization: TextCapitalization.words,
                        decoration: InputDecoration(
                          labelText: "Pieces",
                          hintText: "Enter Pieces",
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('OK'),
                onPressed: () async {
                  if (_pieces.currentState!.validate()) {
                    double pcs = double.parse(pieces.text);
                    String updateBy = ref.read(authModelProvider)!.uid;
                    ref
                        .read(storeItemControllerProvider)
                        .updateStoreItem(ref, storeItemModel, pcs, updateBy);
                    context.pop(true);
                    pieces.clear();
                    _itemNameController.clear();
                    _poNumberController.clear();
                    ref.invalidate(
                        storeItemStockListWithPaginationStreamProvider);
                    _pieces.currentState?.reset();
                  }
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }
}
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:excel/excel.dart' as exc;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:rrispat_app/src/features/store/domain/models/store_user_model.dart';
import 'package:rrispat_app/src/shared/providers/providers.dart';
import '../../../../../l10n/app_localizations.dart';
import '../../../../shared/widgets/loader_widget.dart';
import '../../../../shared/widgets/rr_filled_button.dart';
import '../../../auth/controllers/auth_controller.dart';
import '../../../auth/domains/models/auth_model.dart';
import '../../../auth/domains/providers/auth_model_provider.dart';
import '../../controller/store_item_controller.dart';
import '../../controller/store_user_controller.dart';
import '../../domain/models/store_item_model.dart';
import '../../domain/store_enums.dart';

class StoreAddStock extends ConsumerStatefulWidget {
  const StoreAddStock({Key? key}) : super(key: key);

  @override
  ConsumerState<StoreAddStock> createState() => _StoreAddStockState();
}

class _StoreAddStockState extends ConsumerState<StoreAddStock> {
  final GlobalKey<FormState> _pieces = GlobalKey<FormState>();

  bool _showLoading = true;

  final TextEditingController _itemNameController = TextEditingController();
  final TextEditingController _poNumberController = TextEditingController();

  final TextEditingController pieces = TextEditingController();

  StoreUserModel? storeUser;
  List<StoreItemModel> storeItemListfromBe = [];
  List<AuthModel> authModels = [];
  double screenWidth = 0;

  PaginationParams _paginationParams = PaginationParams(
    page: 1,
    pageSize: 10,
    totalPages: 0,
    itemName: '',
    poNumber: '',
  );

  int _totalItems = 0;

  @override
  void initState() {
    super.initState();

    Timer(const Duration(seconds: 90), () {
      if (mounted) {
        setState(() {
          _showLoading = false;
        });
      }
    });
  }

  Future<void> uploadExcelDataFromWebStoreStockAdd(BuildContext context) async {
    FilePickerResult? file = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xlsx'],
      allowMultiple: false,
    );
    if (file != null) {
      List<StoreItemModel> tempList = [];
      Uint8List fileBytes = file.files.first.bytes!;
      var excel = exc.Excel.decodeBytes(fileBytes);
      for (var table in excel.tables.keys) {
        for (var row in excel.tables[table]!.rows) {
          if (row[0]?.value.toString() == "Company Name") continue;
          try {
            StoreItemModel storeItemModel = StoreItemModel(
              id: '',
              itemName: (row[4]?.value).toString(),
              vendorName: (row[1]?.value).toString(),
              pieces: double.parse((row[6]?.value).toString()),
              issuedPcs: double.parse(0.toString()),
              createdAt: DateTime.now(),
              createdBy: ref.read(authModelProvider)!.uid,
              itemCode: (row[3]?.value).toString(),
              poNumber: (row[8]?.value).toString(),
              unit: (row[5]?.value).toString(),
              issuedCompleted: double.parse(0.toString()),
              sapItemCode: '',
              plantName: (row[10]?.value).toString(),
              poDate: (row[11]?.value).toString(),
              status: StoreItemStatus.approved,
              type: StoreItemCreatedType.normal,
              remark: '',
            );
            tempList.add(storeItemModel);
          } catch (e) {
            print("$e store item error getFile");
          }
        }
      }
      for (var element in tempList) {
        ref
            .read(storeItemControllerProvider)
            .createStoreItemStock(ref, element);
      }
    }
  }

  Widget buildFilters(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth < 600) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextFormField(
            controller: _itemNameController,
            decoration: InputDecoration(
              labelText: "Filter by Item Name",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: value,
                  poNumber: _poNumberController.text,
                );
              });
            },
          ),
          const SizedBox(height: 10),
          TextFormField(
            controller: _poNumberController,
            decoration: InputDecoration(
              labelText: "Filter by PO Number",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: _itemNameController.text,
                  poNumber: value,
                );
              });
            },
          ),
          const SizedBox(height: 10),
        ],
      );
    } else {
      return Row(
        children: [
          Expanded(
            child: TextFormField(
              controller: _itemNameController,
              decoration: InputDecoration(
                labelText: "Filter by Item Name",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: value,
                    poNumber: _poNumberController.text,
                  );
                });
              },
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: TextFormField(
              controller: _poNumberController,
              decoration: InputDecoration(
                labelText: "Filter by PO Number",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: _itemNameController.text,
                    poNumber: value,
                  );
                });
              },
            ),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    screenWidth = MediaQuery.of(context).size.width;

    ref
        .watch(authUserListStreamProvider)
        .whenData((value) => authModels = value);
    ref.watch(storeUserStreamProvider).whenData((value) => storeUser = value);

    return Scaffold(
      appBar: AppBar(
        title: Text('PO - Stock Add'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            if (storeUser != null &&
                storeUser!.userType.contains(StoreUserType.poListUpload))
              Center(
                child: RrFilledButton(
                  onPressed: () {
                    uploadExcelDataFromWebStoreStockAdd(context);
                  },
                  label: ('Store Item Excel File Upload'),
                ),
              ),
            const SizedBox(height: 20),
            buildFilters(context),
            const SizedBox(height: 10),
            Expanded(
              child: ref
                  .watch(storeItemStockListWithPaginationStreamProvider(
                      _paginationParams))
                  .when(
                    data: (paginatedData) {
                      _totalItems = paginatedData.totalItems;
                      _paginationParams = PaginationParams(
                        page: _paginationParams.page,
                        pageSize: _paginationParams.pageSize,
                        totalPages: paginatedData.totalPages,
                        itemName: _itemNameController.text,
                        poNumber: _poNumberController.text,
                      );
                      if (paginatedData.storeItemStocks.isEmpty) {
                        return _showLoading
                            ? const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: CircularProgressIndicator()),
                              )
                            : const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: Text("No Stock Item Found")),
                              );
                      } else {
                        return ListView.builder(
                          itemCount: paginatedData.storeItemStocks.length,
                          itemBuilder: (context, index) {
                            return addStockCard(
                                context, paginatedData.storeItemStocks[index]);
                          },
                        );
                      }
                    },
                    error: (error, stack) =>
                        Center(child: Text(error.toString())),
                    loading: () =>
                        const Center(child: CircularProgressIndicator()),
                  ),
            ),
            _buildPageNumbers(
                computedTotalPages: _paginationParams.totalPages ?? 1),
          ],
        ),
      ),
    );
  }

  Widget _buildPageNumbers({required int computedTotalPages}) {
    int totalVisiblePages = 5;
    List<Widget> pageButtons = [];
    int startPage = max(1, _paginationParams.page - totalVisiblePages ~/ 2);
    int endPage = min(computedTotalPages, startPage + totalVisiblePages - 1);
    if (endPage - startPage < totalVisiblePages - 1) {
      startPage = max(1, endPage - totalVisiblePages + 1);
    }
    if (startPage > 1) {
      pageButtons.add(_pageButton(1, 'First'));
    }
    for (int i = startPage; i <= endPage; i++) {
      pageButtons.add(_pageButton(i, '$i'));
    }
    if (endPage < computedTotalPages) {
      pageButtons.add(_pageButton(computedTotalPages, 'Last'));
    }
    return Wrap(
      alignment: WrapAlignment.center,
      children: pageButtons,
    );
  }

  Widget _pageButton(int pageNumber, String text) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: InkWell(
        onTap: () => _changePage(pageNumber),
        child: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Text(
            text,
            style: TextStyle(
              color: pageNumber == _paginationParams.page
                  ? Theme.of(context).colorScheme.primary
                  : Colors.grey,
            ),
          ),
        ),
      ),
    );
  }

  void _changePage(int page) {
    if (page != _paginationParams.page) {
      setState(() {
        _paginationParams = PaginationParams(
          page: page,
          pageSize: _paginationParams.pageSize,
          totalPages: _paginationParams.totalPages,
          itemName: _itemNameController.text,
          poNumber: _poNumberController.text,
        );
      });
    }
  }

  Widget addStockCard(BuildContext context, StoreItemModel storeItemModel) {
    bool isClosed = storeItemModel.issuedPcs != 0;
    AuthModel closedByPerson = authModels.firstWhere(
      (element) => element.uid == storeItemModel.createdBy,
    );
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 5),
      child: Card(
        color: Theme.of(context).colorScheme.background,
        child: ListTile(
          leading: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.tertiary,
              shape: BoxShape.circle,
            ),
            alignment: Alignment.center,
            child: Text(
              storeItemModel.pieces.toStringAsFixed(2),
              style: Theme.of(context)
                  .textTheme
                  .titleMedium
                  ?.copyWith(color: Colors.white, fontSize: 9),
              textAlign: TextAlign.center,
            ),
          ),
          title: Text(
            storeItemModel.itemName.toUpperCase(),
            style: Theme.of(context).textTheme.titleLarge,
          ),
          subtitle: Wrap(
            spacing: 20,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Pieces: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.pieces.toStringAsFixed(2)),
                  Text(" ${storeItemModel.unit.toString()}"),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Vendor Name')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.vendorName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "SAP Item Code: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.itemCode),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Plant Name: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.plantName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Created Date: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poDate),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Number: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poNumber),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Created At')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(
                    ref
                        .read(dateFormatterProvider)
                        .format(storeItemModel.createdAt),
                  ),
                ],
              ),
              screenWidth <= 500
                  ? (isClosed)
                      ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              "Closed By : ${closedByPerson.fullName}",
                              style: TextStyle(
                                color: Theme.of(context).colorScheme.tertiary,
                              ),
                            ),
                          ],
                        )
                      : Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            buildIconButton(
                              Icons.done_all_rounded,
                              AppLocalizations.of(context).translate('Approve'),
                              () {
                                addStockModel(storeItemModel);
                              },
                            ),
                            const SizedBox(width: 20),
                            buildIconButton(
                              Icons.close_rounded,
                              'Close',
                              () {
                                partiallyCloseStockModel(storeItemModel);
                              },
                            ),
                          ],
                        )
                  : const SizedBox.shrink(),
            ],
          ),
          trailing: screenWidth > 500
              ? (isClosed)
                  ? Wrap(
                      children: [
                        Text(
                          "Closed By : ${closedByPerson.fullName}",
                          style: TextStyle(
                            color: Theme.of(context).colorScheme.tertiary,
                          ),
                        ),
                      ],
                    )
                  : Wrap(
                      children: [
                        buildIconButton(
                          Icons.done_all_rounded,
                          AppLocalizations.of(context).translate('Approve'),
                          () {
                            addStockModel(storeItemModel);
                          },
                        ),
                        const SizedBox(width: 20),
                        buildIconButton(
                          Icons.close_rounded,
                          'Close',
                          () {
                            partiallyCloseStockModel(storeItemModel);
                          },
                        ),
                      ],
                    )
              : null,
        ),
      ),
    );
  }

  Widget buildIconButton(
      IconData icon, String tooltip, void Function() onPressed) {
    return Tooltip(
      message: tooltip,
      child: IconButton(
        onPressed: onPressed,
        icon: Icon(
          icon,
          color: Theme.of(context).colorScheme.tertiary,
        ),
      ),
    );
  }

  void partiallyCloseStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: const SizedBox(
              height: 80,
              child: Center(
                child: Column(
                  children: [
                    Text('Are you sure you want to close this stock item?'),
                    SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('Close'),
                onPressed: () async {
                  String closedBy = ref.read(authModelProvider)!.uid;
                  ref.read(storeItemControllerProvider).updateStoreItemStock(
                      ref, storeItemModel, storeItemModel.pieces, closedBy);
                  context.pop(true);
                  ref.invalidate(
                      storeItemStockListWithPaginationStreamProvider);
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }

  void addStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: SizedBox(
              height: 180,
              child: Center(
                child: Column(
                  children: [
                    Text('Item Name : ${storeItemModel.itemName}'),
                    const SizedBox(height: 5),
                    Text(
                        'Total pcs. in Po list : ${storeItemModel.pieces} ${storeItemModel.unit}'),
                    const SizedBox(height: 10),
                    Form(
                      key: _pieces,
                      child: TextFormField(
                        validator: (text) {
                          if (text == null ||
                              text.isEmpty ||
                              double.parse(text) < 1) {
                            return 'Please enter Pieces to add';
                          }
                          if (double.parse(text) >
                              (storeItemModel.pieces +
                                  (storeItemModel.pieces * 0.1))) {
                            return 'Pcs should not be greater than available stock';
                          }
                          return null;
                        },
                        controller: pieces,
                        keyboardType: TextInputType.number,
                        textCapitalization: TextCapitalization.words,
                        decoration: InputDecoration(
                          labelText: "Pieces",
                          hintText: "Enter Pieces",
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('OK'),
                onPressed: () async {
                  if (_pieces.currentState!.validate()) {
                    double pcs = double.parse(pieces.text);
                    String updateBy = ref.read(authModelProvider)!.uid;
                    ref
                        .read(storeItemControllerProvider)
                        .updateStoreItem(ref, storeItemModel, pcs, updateBy);
                    context.pop(true);
                    pieces.clear();
                    _itemNameController.clear();
                    _poNumberController.clear();
                    ref.invalidate(
                        storeItemStockListWithPaginationStreamProvider);
                    _pieces.currentState?.reset();
                  }
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }
}
/**
We want to change the grid repeat() depending on the items in a grid
where repeat(4, 1fr) are dynamic values we can change in JS using setProperty()
note: setProperty(property-name, value)
*/
 
// our html = we add a data-grid attribure to show the grid number
<div class="qld-compare_page__courses" data-grid></div>
 
// our css
.courses{
  	//repeat(4, 1fr); replace with 2 new css variables, and a fallback
  	// in this case var(--compare-col-count) has a fallback of 4 
   repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
}
 
// JS function



// create the changeGrid function outside the main function below
   function changeGrid(value){
       parentGrid.style.setProperty("--compare-col-width", value);
    }
       
 
function adjustGrid(number) { // number will the dynamic value that changes
  	// get the parent to which the grid willl be appplied
    const parentGrid = document.querySelector(".qld-compare_page__courses");
 
 	 // if element exists
     if (parentGrid) { 
      // set the grid attribute in the html to the number value in the param
      parentGrid.dataset.grid = `courses-${number}`; 
	  // now we are using the set Property to get the var give it the number value
      parentGrid.style.setProperty("--compare-col-count", number);
 
       /**
       switch (number) { // if numbers 1, 2, 3 or 4 is reached then do your thing!
            case 1:
           // here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 230px)");
            break;
           
            case 2:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 249px)");
            break;
 
            case 3:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
 
           	case 4:
			// here we are using setProperty() to target that css var, and apply value
         	parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
           
                default:
                parentGrid.style.setProperty("--compare-col-width", "205px");
                break;
            }
        }
       */
       
       
       /**
       1. create object with all options
       2. create a function to call inside the object
       3. The function returns the code want to repeat with params
       4. Call that function using the object[dynamic] number
       */ 
       
       
       // Note we are still using number from the main function as this is the value
	  // that will output 1, 2, 3, 4
       
       const options = {
         // use cases here for key value pairs
				 1: () => changeGrid("minmax(205px, 230px)"),
                2: () => changeGrid("minmax(205px, 249px)"),
                3: () => changeGrid("minmax(205px, 1fr)"),
                4: () => changeGrid("minmax(205px, 1fr)"),
       }
      
       
       // call it
       // param should be the dynamic value of the oject and the matching number param
       changeGrid(options[number]) 
       
       
       
    }
 
 
 
	//use local storage for the  number we want
  adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);
 
 
 
 


// here is the full JS code with CSS variables
	

    function cssColWidthVariable(value) {
        const parentGrid = document.querySelector(".qld-compare_page__courses");
        parentGrid.style.setProperty("--compare-col-width", value);
    }

  
    function adjustGrid(number) {
        const parentGrid = document.querySelector(".qld-compare_page__courses");
        if (parentGrid) {
            parentGrid.dataset.grid = `courses-${number}`;
            parentGrid.style.setProperty("--compare-col-count", number);

            const gridOptions = {
                1: () => cssColWidthVariable("minmax(205px, 230px)"),
                2: () => cssColWidthVariable("minmax(205px, 249px)"),
                3: () => cssColWidthVariable("minmax(205px, 1fr)"),
                4: () => cssColWidthVariable("minmax(205px, 1fr)"),
            };

            cssColWidthVariable(gridOptions[number] || "205px");
        }
    }

   
  
// call the function based on a changing number
adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);
        


#include <iostream>
#include <unordered_map>
using namespace std;

int main() 
{
  int n, frequentNum, maxCount = 0;
  cin >> n;
  
  int a[n];
  for(int i = 0; i < n; ++i)
    cin >> a[i];
    
  unordered_map<int, int> container;
  for(const int& num : a)
    container[num]++;
    
  for(const auto& num : container)
  {
    if(num.second > maxCount)
    {
      maxCount = num.second;
      frequentNum = num.first;
    }
  }
  
  cout << frequentNum;
  
  return 0;
}
/**
We want to change the grid repeat() depending on the items in a grid
where repeat(4, 1fr) are dynamic values we can change in JS using setProperty()
note: setProperty(property-name, value)
*/

// our html = we add a data-grid attribure to show the grid number
<div class="qld-compare_page__courses" data-grid></div>

// our css
.courses{
  	//repeat(4, 1fr); replace with 2 new css variables, and a fallback
  	// in this case var(--compare-col-count) has a fallback of 4 
   repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
}

// JS function

function adjustGrid(number) { // number will the dynamic value that changes
  	// get the parent to which the grid willl be appplied
    const parentGrid = document.querySelector(".qld-compare_page__courses");

 	 // if element exists
     if (parentGrid) { 
      // set the grid attribute in the html to the number value in the param
      parentGrid.dataset.grid = `courses-${number}`; 
	  // now we are using the set Property to get the var give it the number value
      parentGrid.style.setProperty("--compare-col-count", number);

       switch (number) { // if numbers 1, 2, 3 or 4 is reached then do your thing!
            case 1:
           // here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 230px)");
            break;
           
            case 2:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 249px)");
            break;

            case 3:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;

           	case 4:
			// here we are using setProperty() to target that css var, and apply value
         	parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
           
                default:
                parentGrid.style.setProperty("--compare-col-width", "205px");
                break;
            }
        }
    }



	//use local storage for the  number we want
  adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);




// the css starter
// note we are resetting the --compare-col-count
 &__courses {
      display: grid;
      grid-template-columns: clamp(120px, 39vw, 180px) repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
      grid-template-rows: repeat(2, 1fr) repeat(6, 90px) repeat(1, 1fr);
      z-index: 1;
      column-gap: 1.6rem;


// NEXT SEE: CONVERT setProperty with CSS variables to object and functions
<!-------- Fareharbor Lightframe -------->
<script src="https://fareharbor.com/embeds/api/v1/?autolightframe=yes"></script>
<a href="https://fareharbor.com/embeds/book/autocaresdavid/?full-items=yes" style="-webkit-transform: rotate(0deg) !important;margin-top: 22em !important;  padding: .3em 2em !important; font-family:Aeonik, sans-serif !important; border:2px solid #000000 !important; text-decoration:none !important; font-weight: 700 !important; font-size:1.2em !important; box-shadow:none !important; border-radius: 56px !important;" class="fh-lang fh-fixed--side fh-button-1 fh-hide--desktop fh-size--small fh-button-true-flat-white fh-shape--round fh-color--black">Reserva ahora</a>


Imagine the thrill of building your financial empire without the constraints of a suit or the frenzy of Wall Street. 

	Well, the cryptocurrency exchange script could be your golden ticket to achieving that dream.

	Instead of countless hours of coding an exchange from scratch or spending a fortune on a developer, you can opt for a ready-made cryptocurrency exchange script. This allows you to set up your crypto trading platform quickly.

	It’s hassle-free so connect easily. Customize and start profiting while others dive into the trading frenzy!

Increase in demand
A growing wave of individuals is diving into the crypto market. Indicating that a large group of traders looking for a reliable crypto exchange

Endless possibilities for profits
From transaction fees to withdrawal fees and staking options, you are on the verge of creating your digital wealth!

No coding nightmares
Pre-build cryptocurrency exchange script take the burden off your shoulders. Allows you to save time, reduces stress, and avoids any existential crises.

	Why be satisfied with just watching the fluctuations in Bitcoin prices? Dive in and reap the benefits!

	Start your crypto exchange and get an exciting crypto wave of success.

	Who knows? In a few years, people might be talking about your crypto exchange in forums like this!
      
Website: https://www.trioangle.com/cryptocurrency-exchange-script/ 
WhatsApp us: +91 9361357439
Email us: sales@innblockchain.com
header {
  position: sticky; 
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center; 
 }
#!/usr/bin/env python3

"""
Extract responses from a HAR file, which can be exported by browser dev tools.
Files are written for URLs that match a certain regular expression.
"""
# XXX: Warning - Quick best effort script, i.e. no proper error handling.


import re
import sys
import json
import base64
import argparse

from typing import Dict, Iterator, Tuple, Optional


def parse_har_log(filename: str) -> Iterator[Tuple[Dict, Dict]]:
    with open(filename, "r") as fp:
        har = json.load(fp)
    if not isinstance(har, dict) or \
            "log" not in har or not isinstance(har["log"], dict)\
            or "entries" not in har["log"] or not isinstance(har["log"]["entries"], list):
        raise ValueError(f"No/invalid log entries in {filename}")
    yield from ((_["request"], _["response"]) for _ in har["log"]["entries"])


def match_request(request: Dict, url_rx: re.Pattern) -> bool:
    return "url" in request and isinstance(request["url"], str) and url_rx.match(request["url"]) is not None


def match_response(response: Dict) -> bool:
    return "status" in response and isinstance(response["status"], int) and response["status"] == 200


def dump_response(response: Dict, filename: str) -> bool:
    if "content" in response and isinstance(response["content"], dict):
        content: Dict = response["content"]
        if "text" in content and isinstance(content["text"], str):
            if "encoding" not in content:
                data: bytes = content["text"].encode("utf-8")
            elif isinstance(content["encoding"], str) and content["encoding"] == "base64":
                data = base64.b64decode(content["text"])
            else:
                return False
            try:
                with open(filename, "wb") as fp:
                    fp.write(data)
                    return True
            except OSError:
                return False
    return False


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", type=str, default=None,
                        help="regular expression for the request url, no response content dump otherwise")
    parser.add_argument("file", metavar="archive.har",
                        help="http archive file to process")

    args = parser.parse_args()
    filename: str = args.file
    url_rx: Optional[re.Pattern] = re.compile(args.url) if args.url is not None else None

    for request, response in parse_har_log(filename):
        url: str = request["url"]
        fn: str = re.sub('[^a-zA-Z0-9_-]', '_', url)
        if url_rx is not None and match_request(request, url_rx) and match_response(response):
            if dump_response(response, fn):
                print(f"DUMP: {url}")
            else:
                print(f"FAIL: {url}")
        else:
            print(f"SKIP: {url}")

    return 0


if __name__ == "__main__":
    sys.exit(main())
### **Python Programming Basics for Beginners**
 
 
 
**Role:** You are an expert Python programming tutor. Your goal is to guide students through a personalized, step-by-step learning journey, helping them grasp essential Python programming concepts, particularly if they are beginners. The learning experience should be interactive, goal-driven, and completed within 3-4 hours. Follow the structured steps below, ensuring you introduce each concept progressively to avoid overwhelming the student by presenting everything at once.
 
 
 
**Session Outline:**
 
 
 
#### **0\. Initial Setup and Orientation**
 
 
 
**0.1 Google Colab Setup**
 
 
 
- **Step 1:** Introduce Google Colab and explain its purpose.
 
- **Step 2:** Guide the student through setting up a Google Colab notebook.
 
- **Step 3:** Explain how to write and run Python code in Colab.
 
 
 
**Interactive Checkpoint:** Have the student write and run a simple "Hello, World!" program. Provide immediate feedback before moving on.
 
 
 
---
 
 
 
#### **1\. Initial Assessment and Goal Setting**
 
 
 
**1.1 Student Assessment**
 
 
 
- **Step 1:** Ask the student about their experience with Python, including:
 
  - Variables and Data Types
 
  - Loops and Functions
 
- **Step 2:** Discuss their learning goals and any specific areas of interest.
 
 
 
**1.2 Goal Setting**
 
 
 
- **Step 1:** Based on the assessment, set a personalized learning goal:
 
  - **For Beginners:** Focus on Python basics and simple coding exercises.
 
  - **For Intermediate Students:** Emphasize more complex data manipulations or problem-solving.
 
- **Step 2:** Create and share a step-by-step learning plan tailored to their needs.
 
 
 
**Note:** Confirm the student's background and goals before proceeding to the next section.
 
 
 
---
 
 
 
#### **2\. Python Fundamentals**
 
 
 
**2.1 Core Concepts**
 
 
 
- **Step 1:** Introduce basic Python concepts one by one:
 
  - Variables and Data Types
 
  - Basic operations
 
- **Step 2:** Provide a small coding challenge after each concept, ensuring the student understands before moving to the next.
 
 
 
**Interactive Checkpoint:** Have the student write code to declare variables of different types and perform basic operations. Provide feedback and clarify any misunderstandings.
 
 
 
---
 
 
 
#### **3\. Control Flow: Lists, Loops, and Functions**
 
 
 
**3.1 Lists and Loops**
 
 
 
- **Step 1:** Introduce lists, explaining their structure and use.
 
- **Step 2:** Guide the student in writing simple loops to iterate over lists.
 
 
 
**3.2 Functions**
 
 
 
- **Step 1:** Explain the concept of functions and their importance in Python.
 
- **Step 2:** Walk the student through writing their own functions.
 
 
 
**3.3 Interactive Coding**
 
 
 
- **Step 1:** Encourage the student to write their own code for loops and functions.
 
- **Step 2:** Offer guidance as needed, providing hints or partial code.
 
 
 
**Interactive Checkpoint:** After completing loops and functions, present a problem for the student to solve using these concepts. Review their solution and offer feedback.
 
 
 
---
 
 
 
#### **4\. Object-Oriented Programming (OOP) and Classes**
 
 
 
**4.1 Introduction to Classes and Objects**
 
 
 
- **Step 1:** Explain the concept of Object-Oriented Programming (OOP) and its benefits.
 
- **Step 2:** Introduce classes and objects, using simple examples.
 
 
 
**4.2 Creating and Using Classes**
 
 
 
- **Step 1:** Walk the student through creating a class with attributes and methods.
 
- **Step 2:** Demonstrate how to create objects from the class and use its methods.
 
 
 
**Interactive Checkpoint:** Have the student create a simple class and use it in a short program. Provide feedback and correct any issues.
 
 
 
---
 
 
 
#### **5\. Error Handling and Debugging**
 
 
 
**5.1 Introduction to Error Handling**
 
 
 
- **Step 1:** Explain common types of errors in Python and the importance of handling them gracefully.
 
- **Step 2:** Introduce try, except, and finally blocks for error handling.
 
 
 
**5.2 Practical Error Handling**
 
 
 
- **Step 1:** Guide the student through writing code that includes error handling.
 
- **Step 2:** Discuss strategies for debugging and finding errors in code.
 
 
 
**Interactive Checkpoint:** Provide a buggy code snippet for the student to debug. Review their approach and offer guidance as needed.
 
 
 
---
 
 
 
#### **6\. File Handling and Data Input/Output**
 
 
 
**6.1 Reading from and Writing to Files**
 
 
 
- **Step 1:** Introduce file operations, explaining how to read from and write to files in Python.
 
- **Step 2:** Demonstrate reading data from a file and processing it.
 
 
 
**Interactive Checkpoint:** Have the student write a program to read a file and perform a simple task, such as counting lines. Review their work and provide feedback.
 
 
 
---
 
 
 
#### **7\. Practical Application Project**
 
 
 
**7.1 Hands-On Project**
 
 
 
- **Step 1:** Introduce a hands-on project, such as a simple text analysis.
 
- **Step 2:** Guide the student step by step in tasks like counting word occurrences or analyzing data patterns.
 
 
 
**Interactive Experimentation:** Encourage the student to experiment with the code, making modifications to observe different results. Provide feedback on their approach and reasoning after each step.
 
 
 
---
 
 
 
#### **8\. Reflection, Q&A, and Next Steps**
 
 
 
**8.1 Reflection**
 
 
 
- **Step 1:** Encourage the student to reflect on what they've learned.
 
- **Step 2:** Discuss any areas they found challenging and what they'd like to explore further.
 
 
 
**8.2 Interactive Discussion**
 
 
 
- **Step 1:** Facilitate a Q&A session where the student can ask questions or seek clarification on any topic.
 
 
 
**8.3 Next Steps**
 
 
 
- **Step 1:** Suggest further resources or topics for continued learning.
 
- **Step 2:** Provide a clear action plan for the student's continued learning journey.
 
 
 
---
 
 
 
**Session Guidelines:**
 
 
 
1. **Interactive Learning:**
 
   - Encourage the student to code as much as possible by themselves.
 
   - Provide hints, but do not give direct answers. Allow the student to struggle a bit before offering more guidance.
 
   - Confirm understanding before moving to the next step.
 
 
 
2. **Time Management:**
 
   - Ensure the session stays within the 3-4 hour timeframe.
 
   - Adjust the pace and depth based on the student's progress.
 
 
 
3. **Continuous Feedback:**
 
   - Offer regular feedback on the student's code and understanding.
 
   - Address any questions or difficulties the student encounters.
 
 
 
4. **Expectations After Pasting the Prompt** 
 
  - Clear instructions on what students should expect after pasting the prompt into ChatGPT, such as assessment, coding exercises, problem-solving, and feedback loops.
 
 
 
Now, let's start with the first step and guide you through getting started. Remember, always confirm your understanding by asking questions or proposing exercises to ensure you're comfortable before moving on.
https://community.dynamics.com/blogs/post/?postid=be407572-9096-47a7-af67-5d9b0f0d4894
Want to launch a profitable gambling business? Addus Technologies is a trusted Casino Gambling Game Development Company offering casino games, Lucky Draw games, and sports betting software. As a Casino Gambling Game Development Company, Addus helps business people, entrepreneurs, and investors start their gambling businesses with innovative solutions.
#include <iostream>
#include <vector>
using namespace std;
 
int main() 
{
  int n1, n2, i1=0, i2=0;
  
  cin >> n1;
  int a[n1];
  for(int i = 0; i < n1; ++i)
    cin >> a[i];
    
  cin >> n2;
  int b[n2];
  for(int i = 0; i < n2; ++i)
    cin >> b[i];
    
  vector<int> answer;
    
  while(i1 < n1 && i2 < n2)
  {
    if(a[i1] < b[i2])
    {
      answer.push_back(a[i1]);
      ++i1;
    }
    else if(a[i1] > b[i2])
    {
      answer.push_back(b[i2]);
      ++i2;
    }
  }
  
  while(i1 < n1)
  {
    answer.push_back(a[i1]);
    ++i1;
  }
  
  while(i2 < n2)
  {
    answer.push_back(b[i2]);
    ++i2;
  }
  
  for(int num : answer)
    cout << num << " ";
  
  return 0;
}
#include <iostream>
using namespace std;

void PrintArray(int a[], int n)
{
  for(int i = 0; i < n; ++i)
    cout << a[i] << " ";
}

int main() 
{
  int n, p1 = 0, p2 = 0;
  cin >> n;
  
  int a[n];
  for(int i = 0; i < n; ++i)
    cin >> a[i];
  
  while(p2 < n)
  {
    if(a[p2] % 2 == 0)
    {
      swap(a[p1], a[p2]);
      ++p1;
    }
    ++p2;
  }
  
  PrintArray(a, n);
  
  return 0;
}
@RestController
public class EventProducerController {
    private final KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    public EventProducerController(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }
    @GetMapping("/message/{message}")
    public String trigger(@PathVariable String message) {
        kafkaTemplate.send("messageTopic", message);
        return "Hello, Your message has been published: " + message;
    }
}
const req = await fetch(
    "http://localhost:3000/api/auth/signin", {
      method: "POST",
      header:{
        'Accept':'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username:myusername,
        password:mypassword
      })
    },
    
  )
### **Python Programming Basics for Beginners**



**Role:** You are an expert Python programming tutor. Your goal is to guide students through a personalized, step-by-step learning journey, helping them grasp essential Python programming concepts, particularly if they are beginners. The learning experience should be interactive, goal-driven, and completed within 3-4 hours. Follow the structured steps below, ensuring you introduce each concept progressively to avoid overwhelming the student by presenting everything at once.



**Session Outline:**



#### **0\. Initial Setup and Orientation**



**0.1 Google Colab Setup**



- **Step 1:** Introduce Google Colab and explain its purpose.

- **Step 2:** Guide the student through setting up a Google Colab notebook.

- **Step 3:** Explain how to write and run Python code in Colab.



**Interactive Checkpoint:** Have the student write and run a simple "Hello, World!" program. Provide immediate feedback before moving on.



---



#### **1\. Initial Assessment and Goal Setting**



**1.1 Student Assessment**



- **Step 1:** Ask the student about their experience with Python, including:

  - Variables and Data Types

  - Loops and Functions

- **Step 2:** Discuss their learning goals and any specific areas of interest.



**1.2 Goal Setting**



- **Step 1:** Based on the assessment, set a personalized learning goal:

  - **For Beginners:** Focus on Python basics and simple coding exercises.

  - **For Intermediate Students:** Emphasize more complex data manipulations or problem-solving.

- **Step 2:** Create and share a step-by-step learning plan tailored to their needs.



**Note:** Confirm the student's background and goals before proceeding to the next section.



---



#### **2\. Python Fundamentals**



**2.1 Core Concepts**



- **Step 1:** Introduce basic Python concepts one by one:

  - Variables and Data Types

  - Basic operations

- **Step 2:** Provide a small coding challenge after each concept, ensuring the student understands before moving to the next.



**Interactive Checkpoint:** Have the student write code to declare variables of different types and perform basic operations. Provide feedback and clarify any misunderstandings.



---



#### **3\. Control Flow: Lists, Loops, and Functions**



**3.1 Lists and Loops**



- **Step 1:** Introduce lists, explaining their structure and use.

- **Step 2:** Guide the student in writing simple loops to iterate over lists.



**3.2 Functions**



- **Step 1:** Explain the concept of functions and their importance in Python.

- **Step 2:** Walk the student through writing their own functions.



**3.3 Interactive Coding**



- **Step 1:** Encourage the student to write their own code for loops and functions.

- **Step 2:** Offer guidance as needed, providing hints or partial code.



**Interactive Checkpoint:** After completing loops and functions, present a problem for the student to solve using these concepts. Review their solution and offer feedback.



---



#### **4\. Object-Oriented Programming (OOP) and Classes**



**4.1 Introduction to Classes and Objects**



- **Step 1:** Explain the concept of Object-Oriented Programming (OOP) and its benefits.

- **Step 2:** Introduce classes and objects, using simple examples.



**4.2 Creating and Using Classes**



- **Step 1:** Walk the student through creating a class with attributes and methods.

- **Step 2:** Demonstrate how to create objects from the class and use its methods.



**Interactive Checkpoint:** Have the student create a simple class and use it in a short program. Provide feedback and correct any issues.



---



#### **5\. Error Handling and Debugging**



**5.1 Introduction to Error Handling**



- **Step 1:** Explain common types of errors in Python and the importance of handling them gracefully.

- **Step 2:** Introduce try, except, and finally blocks for error handling.



**5.2 Practical Error Handling**



- **Step 1:** Guide the student through writing code that includes error handling.

- **Step 2:** Discuss strategies for debugging and finding errors in code.



**Interactive Checkpoint:** Provide a buggy code snippet for the student to debug. Review their approach and offer guidance as needed.



---



#### **6\. File Handling and Data Input/Output**



**6.1 Reading from and Writing to Files**



- **Step 1:** Introduce file operations, explaining how to read from and write to files in Python.

- **Step 2:** Demonstrate reading data from a file and processing it.



**Interactive Checkpoint:** Have the student write a program to read a file and perform a simple task, such as counting lines. Review their work and provide feedback.



---



#### **7\. Practical Application Project**



**7.1 Hands-On Project**



- **Step 1:** Introduce a hands-on project, such as a simple text analysis.

- **Step 2:** Guide the student step by step in tasks like counting word occurrences or analyzing data patterns.



**Interactive Experimentation:** Encourage the student to experiment with the code, making modifications to observe different results. Provide feedback on their approach and reasoning after each step.



---



#### **8\. Reflection, Q&A, and Next Steps**



**8.1 Reflection**



- **Step 1:** Encourage the student to reflect on what they've learned.

- **Step 2:** Discuss any areas they found challenging and what they'd like to explore further.



**8.2 Interactive Discussion**



- **Step 1:** Facilitate a Q&A session where the student can ask questions or seek clarification on any topic.



**8.3 Next Steps**



- **Step 1:** Suggest further resources or topics for continued learning.

- **Step 2:** Provide a clear action plan for the student's continued learning journey.



---



**Session Guidelines:**



1. **Interactive Learning:**

   - Encourage the student to code as much as possible by themselves.

   - Provide hints, but do not give direct answers. Allow the student to struggle a bit before offering more guidance.

   - Confirm understanding before moving to the next step.



2. **Time Management:**

   - Ensure the session stays within the 3-4 hour timeframe.

   - Adjust the pace and depth based on the student's progress.



3. **Continuous Feedback:**

   - Offer regular feedback on the student's code and understanding.

   - Address any questions or difficulties the student encounters.



4. **Expectations After Pasting the Prompt** 

  - Clear instructions on what students should expect after pasting the prompt into ChatGPT, such as assessment, coding exercises, problem-solving, and feedback loops.



Now, let's start with the first step and guide you through getting started. Remember, always confirm your understanding by asking questions or proposing exercises to ensure you're comfortable before moving on.
using System.Drawing.Drawing2D;

namespace CtrlCPopup {
    public partial class PopupForm : Form {
        private int targetY;
        private const int slideSpeed = 15;

        private System.Windows.Forms.Timer timerSlide;
        private System.Windows.Forms.Timer timerClose;

        private const int cornerRadius = 20;

        private static PopupForm currentPopup;

        public PopupForm() {
            InitializeForm();
        }

        private void InitializeForm() {
            this.StartPosition = FormStartPosition.Manual;
            this.FormBorderStyle = FormBorderStyle.None;
            this.BackColor = SystemAccentColorHelper.GetAccentColor();
            this.Size = new Size(180, 100);
            this.TopMost = true;
            this.ShowInTaskbar = false;

            Label lblMessage = new Label();
            lblMessage.Text = "Copied!";
            lblMessage.AutoSize = true;
            lblMessage.Font = new Font("Segoe UI", 20, FontStyle.Regular);
            lblMessage.ForeColor = Color.White;
            lblMessage.Location = new Point(33, 32);
            this.Controls.Add(lblMessage);

            timerSlide = new System.Windows.Forms.Timer();
            timerSlide.Interval = 10;
            timerSlide.Tick += TimerSlide_Tick;

            timerClose = new System.Windows.Forms.Timer();
            timerClose.Interval = 3000; //* 3 seconds auto-close
            timerClose.Tick += TimerClose_Tick;

            ApplyRoundedCorners();
        }

        private void ApplyRoundedCorners() {
            GraphicsPath path = new GraphicsPath();
            Rectangle bounds = new Rectangle(0, 0, this.Width, this.Height);

            path.AddArc(bounds.X, bounds.Y, cornerRadius * 2, cornerRadius * 2, 180, 90); // Top-left
            path.AddArc(bounds.Right - cornerRadius * 2, bounds.Y, cornerRadius * 2, cornerRadius * 2, 270, 90); // Top-right
            path.AddArc(bounds.Right - cornerRadius * 2, bounds.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90); // Bottom-right
            path.AddArc(bounds.X, bounds.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90); // Bottom-left
            path.CloseFigure();

            this.Region = new Region(path);
        }

        public void ShowPopup() {
            //! Close any existing popup
            if (currentPopup != null && !currentPopup.IsDisposed) {
                currentPopup.Close();
            }

            this.Left = (Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2;
            this.Top = Screen.PrimaryScreen.WorkingArea.Height;
            targetY = Screen.PrimaryScreen.WorkingArea.Height - this.Height - 20; // 20 pixels from the bottom

            this.Show();
            timerSlide.Start();
            timerClose.Start();

            currentPopup = this;
        }

        private void TimerSlide_Tick(object sender, EventArgs e) {
            if (this.Top > targetY) {
                this.Top -= slideSpeed;
            }
            else {
                timerSlide.Stop();
            }
        }

        private void TimerClose_Tick(object sender, EventArgs e) {
            this.Close();
        }
    }
}
<p>Struggling with complex equations or challenging math problems? MyAssignmenthelp offers expert Mathematics Assignment Help https://myassignmenthelp.com/uk/mathematics-assignment-help.html to simplify your academic journey. From algebra to calculus, our professionals provide accurate solutions tailored to your needs. Get timely and affordable assistance to achieve academic excellence.</p>
#include <iostream>
using namespace std;

void InsertionSort(int a[], int n)
{
  for(int i = 1; i < n; ++i)
  {
    int key = a[i];
    int j = i-1;
    
    while(j >= 0 && key < a[j])
    {
      a[j+1] = a[j];
      --j;
    }
    
    a[j+1] = key;
  }
}

int main() 
{
  int n;
  cin >> n;
  
  int a[n];
  for(int i = 0; i < n; ++i)
  {
    cin >> a[i];
    a[i] *= a[i];
  }
  
  InsertionSort(a, n);
  
  for(int i = 0; i < n; ++i)
  {
    cout << a[i] << " ";
  }
  
  return 0;
}
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;

int main() 
{
  int n; 
  cin >> n;
  
  vector<int> a(n), b(n);
  unordered_map<int, int> rankMap;
  
  for(int i = 0; i < n; ++i)
  {
    cin >> a[i];
    b[i] = a[i];
  }
  
  sort(b.begin(), b.end());
  
  for(int i = 0; i < n; ++i)
  {
    rankMap[b[i]] = i+1;
  }
  
  for(int i = 0; i < n; ++i)
  {
    cout << rankMap[a[i]] << " ";
  }
  
  return 0;
}
star

Fri Feb 21 2025 12:34:34 GMT+0000 (Coordinated Universal Time)

@davidb2107 #power_query

star

Fri Feb 21 2025 10:23:49 GMT+0000 (Coordinated Universal Time) https://prime.luz.vc/post/planilha-de-fluxo-de-caixa-40-em-excel

@senal88

star

Fri Feb 21 2025 10:23:13 GMT+0000 (Coordinated Universal Time) https://prime.luz.vc/post/prompt-fluxo-de-caixa-como-criar-metas-de-receitas-e-despesas-precisas

@senal88 #undefined

star

Fri Feb 21 2025 10:22:34 GMT+0000 (Coordinated Universal Time) https://prime.luz.vc/post/promp-pitch-de-negocio-com-o-circulo-dourado-de-simon-sinek

@senal88 #undefined

star

Fri Feb 21 2025 10:21:54 GMT+0000 (Coordinated Universal Time) https://prime.luz.vc/post/prompt-o-metodo-vaca-roxa-para-dominar-o-mercado

@senal88 #.txt

star

Fri Feb 21 2025 06:49:15 GMT+0000 (Coordinated Universal Time)

@StephenThevar #itbooks

star

Fri Feb 21 2025 06:32:23 GMT+0000 (Coordinated Universal Time)

@StephenThevar

star

Fri Feb 21 2025 04:20:59 GMT+0000 (Coordinated Universal Time)

@leah2301 #python

star

Fri Feb 21 2025 01:43:42 GMT+0000 (Coordinated Universal Time)

@gbritgs

star

Thu Feb 20 2025 23:24:36 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Thu Feb 20 2025 15:45:54 GMT+0000 (Coordinated Universal Time) https://codingislove.com/parse-html-in-excel-vba/

@acassell

star

Thu Feb 20 2025 15:44:31 GMT+0000 (Coordinated Universal Time) https://codingislove.com/parse-html-in-excel-vba/

@acassell

star

Thu Feb 20 2025 14:42:39 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Thu Feb 20 2025 12:59:18 GMT+0000 (Coordinated Universal Time)

@StephenThevar #grafana

star

Thu Feb 20 2025 11:56:11 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Feb 20 2025 09:20:30 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/metamask-wallet-clone-script/

@CharleenStewar

star

Thu Feb 20 2025 09:13:36 GMT+0000 (Coordinated Universal Time)

@lafcha #sql

star

Thu Feb 20 2025 06:51:44 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Feb 20 2025 06:51:41 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Feb 20 2025 01:50:29 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Thu Feb 20 2025 00:46:19 GMT+0000 (Coordinated Universal Time)

@davidmchale #setproperty #cssvariables

star

Wed Feb 19 2025 17:54:05 GMT+0000 (Coordinated Universal Time) /hacking.com

@wrigd8449@wrdsb #hacking

star

Wed Feb 19 2025 16:58:38 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/user/wrigd8449@wrdsb

@wrigd8449@wrdsb #hacking

star

Wed Feb 19 2025 16:07:14 GMT+0000 (Coordinated Universal Time)

@Shira

star

Wed Feb 19 2025 12:32:39 GMT+0000 (Coordinated Universal Time) https://www.trioangle.com/cryptocurrency-exchange-script/

@Johnhendrick #java #javascript #django #nodejs #react.js #css

star

Wed Feb 19 2025 10:58:20 GMT+0000 (Coordinated Universal Time)

@SophieLCDZ

star

Wed Feb 19 2025 09:43:39 GMT+0000 (Coordinated Universal Time) https://www.hackitu.de/har_dump/har_dump.py.html

@rhce143

star

Wed Feb 19 2025 09:22:53 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/cryptocurrency-exchange-development-company/

@CharleenStewar

star

Wed Feb 19 2025 09:19:22 GMT+0000 (Coordinated Universal Time)

@jak123

star

Wed Feb 19 2025 07:34:27 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Wed Feb 19 2025 07:05:53 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.expert/case-study-assignment-help.html

@steve1997 #commandline

star

Wed Feb 19 2025 06:23:51 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/casino-gambling-game-development

@Seraphina

star

Wed Feb 19 2025 02:45:07 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Wed Feb 19 2025 02:15:53 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Tue Feb 18 2025 20:59:26 GMT+0000 (Coordinated Universal Time) https://subscription.packtpub.com/book/web-development/9781803230788

@Luciano

star

Tue Feb 18 2025 18:46:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/69332201/i-tried-to-request-body-json-to-node-js-using-await-fetch-the-body-is-empty

@Luciano #javascript

star

Tue Feb 18 2025 14:17:08 GMT+0000 (Coordinated Universal Time) https://ddls.aicell.io/post/learn-python-with-chatgpt/

@Marsel

star

Tue Feb 18 2025 10:12:22 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/trustwallet-clone-app-development/

@CharleenStewar

star

Tue Feb 18 2025 09:40:44 GMT+0000 (Coordinated Universal Time)

@Kareem_Al_Hamwi #c#

star

Tue Feb 18 2025 07:42:36 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.com/uk/mathematics-assignment-help.html

@parkerharry0005 #assignment

star

Tue Feb 18 2025 02:52:07 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Tue Feb 18 2025 02:33:58 GMT+0000 (Coordinated Universal Time)

@Rohan@99

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension