Snippets Collections
int singleNonDuplicate(vector<int>& nums) {
        int ans=0;
        for(int i=0;i<nums.size();i++)
        {
            ans = ans^nums[i];
        }
        return ans;
#include <stdio.h>

float sum(float n1, float n2);
float difference(float n1, float n2);
float product(float n1, float n2);
float quotient(float n1, float n2);

int main() {
    float n1, n2, total;
    char op;

    printf("Enter an operator: ");
    scanf(" %c", &op);

    printf("Enter first number: ");
    scanf("%f", &n1);

    printf("Enter second number: ");
    scanf("%f", &n2);

    switch (op) {
        case '+':
            total = sum(n1, n2);
            printf("The sum is: %.2f\n", total);
            break;
        case '-':
            total = difference(n1, n2);
            printf("The difference is: %.2f\n", total);
            break;
        case '*':
        case 'x':
            total = product(n1, n2);
            printf("The product is: %.2f\n", total);
            break;
        case '/':
        case '÷':
            total = quotient(n1, n2);
            printf("The quotient is: %.2f\n", total);
            break;
        default:
            printf("Invalid operator.\n");
    }

    return 0;
}

float sum(float n1, float n2) {
    return n1 + n2;
}

float difference(float n1, float n2) {
    return n1 - n2;
}

float product(float n1, float n2) {
    return n1 * n2;
}

float quotient(float n1, float n2) {
    if (n2 != 0) {
        return n1 / n2;
    } else {
        printf("Error: Division by zero.\n");
        return 0;
    }
}
import React, { useState } from 'react';

const DataTable = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [data, setData] = useState([
    { name: 'computer', amt: 5000 },
    { name: 'Laptop', amt: 15000 },
    { name: 'electricity', amt: 200000 },
    // ... other data
  ]);

  const handleSearchChange = (event) => {
    setSearchTerm(event.target.value);
  };

  const getFilteredData = () => {
    return data.filter(item =>
      item.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
  };

  return (
    <div>
      <input
        type="search"
        className="search form-control"
        placeholder="Search Category Here..."
        spellCheck="false"
        data-ms-editor="true"
        onChange={handleSearchChange}
        // ... other styles
      />
      <hr />
      <div class="table-responsive">
        <table class="table header-border table-hover table-custom spacing5">
          <thead>
            <tr>
              <th>Name</th>
              <th>Amt</th>
              <th>#</th>
            </tr>
          </thead>
          <tbody>
            {getFilteredData().map((item, index) => (
              <tr key={index}>
                <td>{item.name}</td>
                <td><span>{item.amt.toLocaleString()}</span></td>
                <td>⋮</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default DataTable;
import groceryData from '$lib/data.json';
let groceryItems = groceryData;
var largestLocal = function (grid) {
    let rowLen = grid.length, colLen = grid[0].length
    console.log(rowLen, colLen)
    let mainArr = []
    for (let init = 0; rowLen - init > 2; init++) {
        let childArr = []
        let tem = 0
        for (let col = tem; rowLen - col > 2; col++) {
            let container = []
            for (let sub = init; sub < 3; sub++) {
                let sumTemp = grid[sub].slice(col, 3);
                console.log("sumTemp at ", sub, " is ", sumTemp)
                container.push(...sumTemp)
                console.log("container at ", sub, " is ", container)
            }
            let max = Math.max(...container);
            console.log("max at ", col, " is ", max)
            childArr.push(max)
            console.log("childArr at ", col, " is ", childArr)

        }
        mainArr.push([...childArr])
    }
    return mainArr
};
miG32FcOWH2VOGMQMhHhzbMLLrxgai1718796870
{
  "FFlagHandleAltEnterFullscreenManually": "False",
  "FLogNetwork": "7",
  "DFIntTaskSchedulerTargetFps": "200",
  "DFIntCSGLevelOfDetailSwitchingDistance": "250",
  "DFIntCSGLevelOfDetailSwitchingDistanceL12": "500",
  "DFIntCSGLevelOfDetailSwitchingDistanceL23": "750",
  "DFIntCSGLevelOfDetailSwitchingDistanceL34": "1000",
  "DFFlagTextureQualityOverrideEnabled": "True",
  "DFIntTextureQualityOverride": "2",
  "DFIntDebugFRMQualityLevelOverride": "2",
  "FFlagCoreGuiTypeSelfViewPresent": "False",
  "FFlagInGameMenuV1FullScreenTitleBar": "False",
  "FIntFullscreenTitleBarTriggerDelayMillis": "3600000",
  "FFlagDebugDisplayFPS": "True",
  "FIntRenderShadowIntensity": "0",
  "FFlagDisablePostFx": "True",
  "FFlagDebugDisableTelemetryEphemeralCounter": "True",
  "FFlagDebugDisableTelemetryEphemeralStat": "True",
  "FFlagDebugDisableTelemetryEventIngest": "True",
  "FFlagDebugDisableTelemetryPoint": "True",
  "FFlagDebugDisableTelemetryV2Counter": "True",
  "FFlagDebugDisableTelemetryV2Event": "True",
  "FFlagDebugDisableTelemetryV2Stat": "True"
}
{
  "DFIntTaskSchedulerTargetFps": 5588562,
  "FFlagDebugSkyGray": true,
  "FFlagDebugDisplayFPS": false,
  "DFFlagDebugRenderForceTechnologyVoxel": true,
  "DFFlagDebugPauseVoxelizer": true,
  "FFlagNewLightAttenuation": true,
  "FIntRenderShadowIntensity": 0,
  "FFlagDisablePostFx": true,
  "DFFlagTextureQualityOverrideEnabled": true,
  "DFIntTextureQualityOverride": 0,
  "FIntRenderShadowmapBias": 0,
  "FFlagLuaAppSystemBar": false,
  "FIntFontSizePadding": 3,
  "FFlagAdServiceEnabled": false,
  "FIntScrollWheelDeltaAmount": 25,
  "FFlagDebugDisableTelemetryEphemeralCounter": true,
  "FFlagDebugDisableTelemetryEphemeralStat": true,
  "FFlagDebugDisableTelemetryEventIngest": true,
  "FFlagDebugDisableTelemetryPoint": true,
  "FFlagMSRefactor5": false,
  "FFlagDebugDisableTelemetryV2Counter": true,
  "FFlagDebugDisableTelemetryV2Event": true,
  "FFlagDebugDisableTelemetryV2Stat": true,
  "DFIntCSGLevelOfDetailSwitchingDistance": 1
}
import React, { useState } from 'react';
import { View, Button, Image } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { GoogleVisionApiKey } from './config';

const App = () => {
  const [image, setImage] = useState(null);
  const [books, setBooks] = useState([]);

  const pickImage = async () => {
    let result = await ImagePicker.launchCameraAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.cancelled) {
      setImage(result.uri);
      analyzeImage(result.uri);
    }
  };

  const analyzeImage = async (uri) => {
    const response = await fetch(uri);
    const blob = await response.blob();

    const formData = new FormData();
    formData.append('file', blob);
    formData.append('key', GoogleVisionApiKey);

    const visionResponse = await fetch(`https://vision.googleapis.com/v1/images:annotate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        requests: [
          {
            image: {
              content: blob,
            },
            features: [
              { type: 'TEXT_DETECTION', maxResults: 5 },
            ],
          },
        ],
      }),
    });

    const resultJson = await visionResponse.json();
    const detectedTexts = resultJson.responses[0].textAnnotations.map((item) => item.description);
    setBooks(detectedTexts);
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Capture Image" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
      {books.length > 0 && (
        <View>
          {books.map((book, index) => (
            <Text key={index}>{book}</Text>
          ))}
        </View>
      )}
    </View>
  );
};

export default App;
import React from 'react'
import { connect } from 'react-redux'

const TodoList = ({ todos }) => ( <ul> {todos.map(todo => <li key={todo.id}>{todo.text}</li>)} </ul> ) const mapStateToProps = state => ({ todos: state.todos })

export default connect(mapStateToProps)(TodoList)
import React from 'react' import ReactDOM from 'react-dom' 
import { Provider } from 'react-redux'
import { createStore } from 'redux' import rootReducer from './reducers' 
import App from './App' 

const store = createStore(rootReducer) 
ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
from openai import OpenAI 
import os

MODEL="gpt-4o"
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

# 1 - Basic Chat

completion = client.chat.completions.create(
  model=MODEL,
  messages=[
    {"role": "system", "content": "You are a helpful assistant. Help me with my math homework!"},
    {"role": "user", "content": "Hello! Could you solve 2+2?"}
  ]
)

print("Assistant: " + completion.choices[0].message.content)

# 2 - Image Processing: Base64
import base64

IMAGE_PATH = "triangle.png"

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

base64_image = encode_image(IMAGE_PATH)

response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful assistant that responds in Markdown. Help me with my math homework!"},
        {"role": "user", "content": [
            {"type": "text", "text": "What's the area of the triangle?"},
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}
            }
        ]}
    ],
    temperature=0.0,
)

print(response.choices[0].message.content)

# 3 - Image Processing: URL
response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful assistant that responds in Markdown. Help me with my math homework!"},
        {"role": "user", "content": [
            {"type": "text", "text": "What's the area of the triangle?"},
            {"type": "image_url", "image_url": {"url": "https://upload.wikimedia.org/wikipedia/commons/e/e2/The_Algebra_of_Mohammed_Ben_Musa_-_page_82b.png"}
            }
        ]}
    ],
    temperature=0.0,
)

print(response.choices[0].message.content)

# 4 - Summarization: Video Summary
import cv2
from moviepy.editor import VideoFileClip
import time
import base64

VIDEO_PATH = "keynote_recap.mp4"

def process_video(video_path, seconds_per_frame=2):
    base64Frames = []
    base_video_path, _ = os.path.splitext(video_path)

    video = cv2.VideoCapture(video_path)
    total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = video.get(cv2.CAP_PROP_FPS)
    frames_to_skip = int(fps * seconds_per_frame)
    curr_frame=0

    while curr_frame < total_frames - 1:
        video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
        success, frame = video.read()
        if not success:
            break
        _, buffer = cv2.imencode(".jpg", frame)
        base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
        curr_frame += frames_to_skip
    video.release()

    audio_path = f"{base_video_path}.mp3"
    clip = VideoFileClip(video_path)
    clip.audio.write_audiofile(audio_path, bitrate="32k")
    clip.audio.close()
    clip.close()

    print(f"Extracted {len(base64Frames)} frames")
    print(f"Extracted audio to {audio_path}")
    return base64Frames, audio_path

base64Frames, audio_path = process_video(VIDEO_PATH, seconds_per_frame=1)

response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content": "You are generating a video summary. Please provide a summary of the video. Respond in Markdown."},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames)
        ],
    }
    ],
    temperature=0,
)
print(response.choices[0].message.content)

# 5 - Summarization: Audio Summary
transcription = client.audio.transcriptions.create(
    model="whisper-1",
    file=open(audio_path, "rb"),
)

response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."""},
    {"role": "user", "content": [
        {"type": "text", "text": f"The audio transcription is: {transcription.text}"}
        ],
    }
    ],
    temperature=0,
)
print(response.choices[0].message.content)

# 6 - Summarization: Audio + Visual Summary
response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""You are generating a video summary. Create a summary of the provided video and its transcript. Respond in Markdown"""},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
                        {"type": "text", "text": f"The audio transcription is: {transcription.text}"}
        ],
    }
],
    temperature=0,
)
print(response.choices[0].message.content)

# 7 - Q&A: Visual Q&A
QUESTION = "Question: Why did Sam Altman have an example about raising windows and turning the radio on?"

qa_visual_response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content": "Use the video to answer the provided question. Respond in Markdown."},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
        QUESTION
        ],
    }
    ],
    temperature=0,
)
print("Visual QA:\n" + qa_visual_response.choices[0].message.content)

# 8 - Q&A: Audio Q&A
qa_audio_response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""Use the transcription to answer the provided question. Respond in Markdown."""},
    {"role": "user", "content": f"The audio transcription is: {transcription.text}. \n\n {QUESTION}"},
    ],
    temperature=0,
)
print("Audio QA:\n" + qa_audio_response.choices[0].message.content)

# 11 - Q&A: Visual + Audio Q&A
qa_both_response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""Use the video and transcription to answer the provided question."""},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
                        {"type": "text", "text": f"The audio transcription is: {transcription.text}"},
        QUESTION
        ],
    }
    ],
    temperature=0,
)
print("Both QA:\n" + qa_both_response.choices[0].message.content)
// Get user media
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => {
    const localVideo = document.getElementById('localVideo');
    localVideo.srcObject = stream;

    const peerConnection = new RTCPeerConnection();
    stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));

    // Set up ICE handling
    peerConnection.onicecandidate = event => {
      if (event.candidate) {
        // Send the candidate to the remote peer
        sendToServer({ type: 'candidate', candidate: event.candidate });
      }
    };

    // When remote stream arrives
    peerConnection.ontrack = event => {
      const remoteVideo = document.getElementById('remoteVideo');
      remoteVideo.srcObject = event.streams[0];
    };

    // Create an offer to connect
    peerConnection.createOffer()
      .then(offer => peerConnection.setLocalDescription(offer))
      .then(() => {
        // Send the offer to the remote peer
        sendToServer({ type: 'offer', offer: peerConnection.localDescription });
      });

    // Handle offer from a remote peer
    receiveFromServer(message => {
      if (message.type === 'offer') {
        peerConnection.setRemoteDescription(new RTCSessionDescription(message.offer))
          .then(() => peerConnection.createAnswer())
          .then(answer => peerConnection.setLocalDescription(answer))
          .then(() => {
            // Send the answer to the remote peer
            sendToServer({ type: 'answer', answer: peerConnection.localDescription });
          });
      } else if (message.type === 'answer') {
        peerConnection.setRemoteDescription(new RTCSessionDescription(message.answer));
      } else if (message.type === 'candidate') {
        peerConnection.addIceCandidate(new RTCIceCandidate(message.candidate));
      }
    });
  })
  .catch(error => {
    console.error('Error accessing media devices.', error);
  });

function sendToServer(message) {
  // Implement server communication to exchange messages
}

function receiveFromServer(callback) {
  // Implement server communication to receive messages
}
if(Object.keys(user).length > 0){
    console.log('objec has values')
}
# dictionary comprehension example
square_dict = {num: num*num for num in range(1, 11)}
print(square_dict)
Sub RemoveEmptyLines()
    Dim para As Paragraph
    For Each para In ActiveDocument.Paragraphs
        If Len(para.Range.Text) <= 1 Then
            para.Range.Delete
        End If
    Next para
End Sub
    Source = Odbc.DataSource("dsn=SNOWFLAKE", [HierarchicalNavigation=true]),
! Create restart file with initial condition
program InitCond

  use ModDataTypes
  use ModDataStruct
  use ModRbc
  use ModWall
  use ModConf
  use ModData
  use ModIO
  use ModBasicMath
  use ModPostProcess
  ! use MPI

  implicit none

  integer, parameter :: nrbcMax = 128
  integer, parameter :: nwallMax = 4
  type(t_rbc), pointer :: rbc
  type(t_rbc)         :: rbcRef
  type(t_wall), pointer :: wall
  real(WP) :: radEqv, szCell(3)
  integer :: nlat0, nlat1, ii
  real(WP) :: theta, th, rc, xc(3), ztemp
  real(WP) :: xmin, xmax, ymin, ymax, zmin, zmax
  integer :: iz, i, p, l, dealias
  integer, parameter :: ranseed = 161269
  character(CHRLEN) :: fn
  ! real = double, fp
  real :: lengtube, lengspacing, phi, actlen
  real(WP) :: rand(27, 3), minDist, platRad, platDiam
  real :: wbcs(2), tubeDiam, layerx(3), layery(3), halflen

  ! Initialize
  call InitMPI
  ! Allocate working arrays
  allocate (rbcs(nrbcMax))
  ! allocate(walls(nwallMax))

  tubeDiam = 4

  nrbc = 1
  nlat0 = 6
  dealias = 3
  phi = 70/real(100)
  ! 11.34
  lengtube = 5 ! nrbc/real(phi) !XXLL

  lengspacing = lengtube/Real(nrbc)
  ! print *, "1"
  nwall = 1
  allocate (walls(nwall))
  wall => walls(1)

  call ReadWallMesh('Input/new_cyl_D6_L13_33.e', wall)
  actlen = 13.33
  wall%f = 0.
  do i = 1, wall%nvert
    th = ATAN2(wall%x(i, 1), wall%x(i, 2))
    wall%x(i, 1) = (tubeDiam/2.0)*COS(th)    !!!!!!!!!
    wall%x(i, 2) = (tubeDiam/2.0)*SIN(th)    !!!!!!!!!
    wall%x(i, 3) = lengtube/actlen*wall%x(i, 3)
  end do

  xmin = minval(wall%x(:, 1))
  xmax = maxval(wall%x(:, 1))

  ymin = minval(wall%x(:, 2))
  ymax = maxval(wall%x(:, 2))

  zmin = minval(wall%x(:, 3))
  zmax = maxval(wall%x(:, 3))

  ! size of the periodic box
  Lb(1) = xmax - xmin + 0.5
  Lb(2) = Lb(1)
  Lb(3) = zmax - zmin
  lengtube = Lb(3)

  print *, "Lb", Lb(:)
  !  Lb   8.3013429849047267        8.3013429849047267        11.347517730496456
  ! lengspacing = lengtube/real(nrbc)
  print *, 'lengtube 2', lengtube
  print *, 'lengspacing 2', lengspacing

  ! Reference cell i
  xc = 0.

  radEqv = 1.0
  platRad = .3

  print *, "platRad", platRad

  call Rbc_Create(rbcRef, nlat0, dealias)
  call Rbc_MakePlatelet(rbcRef, platRad, xc)

  do ii = 1, 3
    ! dimensions of cell !
    szCell(ii) = maxval(rbcRef%x(:, :, ii)) - minval(rbcRef%x(:, :, ii))
  end do
  if (rootWorld) then
    print *, "szCell", szCell
  end if

  ! place cells
  do iz = 1, nrbc
    xc(1:2) = 0.
    xc(3) = 1
    print *, 'platelet iz:', iz, 'xc:', xc
    rbc => rbcs(iz)
    rbc%celltype = 3
    print *, nlat0, dealias, platRad, xc
    call Rbc_Create(rbc, nlat0, dealias)
    call Rbc_MakePlatelet(rbc, platRad, xc)
  end do

  ! Put things in the middle of the periodic box
  call Recenter_Cells_and_Walls

  ! platDiam = GetDiameter(3)

  ! Output
  write (*, '(A,3F10.3)') 'Periodic domain size = ', Lb

  Nt0 = 0; time = 0.
  vBkg(1:2) = 0.; vBkg(3) = 8.

  ! Write intial conditions
  if (nrbc > 0) then
    write (fn, FMT=fn_FMT) 'D/', 'x', 0, '.dat'
    call WriteManyRBCs(fn, nrbc, rbcs)

    write(fn, FMT=fn_FMT) 'D/', '3x', 0, '.dat'
    call WriteManyRBCsByType(fn, nrbc, rbcs, 3)

    write (*, '(A,A)') 'Cell file: ', trim(fn)

    fn = 'D/restart.LATEST.dat'
    call WriteRestart(fn, Nt0, time)
    write (*, '(A,A)') 'Binary restart file: ', trim(fn)
  end if

  if (nwall > 0) then
    write (fn, FMT=fn_FMT) 'D/', 'wall', 0, '.dat'
    call WriteManyWalls(fn, nwall, walls)
    write (*, '(A,A)') 'Wall file: ', trim(fn)
  end if

  write (fn, FMT=fn_FMT) 'D/', 'restart', Nt0, '.dat'
  call WriteRestart(fn, Nt0, time)
  write (*, '(A,A)') 'Binary restart file: ', trim(fn)

  ! Deallocate working arrays
  deallocate (rbcs)

  ! Finalize
  call FinalizeMPI

  stop

contains
  subroutine Recenter_Cells_and_Walls
    integer :: irbc, iwall, ii, gen, repeat, j
    real :: x, y, a
    real, parameter :: PI = 3.14159265359
    type(t_rbc), pointer :: rbc
    type(t_wall), pointer :: wall
    real(WP) :: xmin(3), xmax(3), xc(3), xmax2, ymax2

    ! cells
    ! translate cells
    do irbc = 1, nrbc
      rbc => rbcs(irbc)
      rbc%x(:, :, 1) = rbc%x(:, :, 1) + 0.5*Lb(1)
      rbc%x(:, :, 2) = rbc%x(:, :, 2) + 0.5*Lb(2)
      print *, 'Zc', sum(rbc%x(:, :, 3))/real(rbc%nlat*rbc%nlon)
    end do

    ! walls
    ! find the bounding box
    xmin = 1.D10
    xmax = -1.D10
    do iwall = 1, nwall
      print *, "iwall", iwall
      wall => walls(iwall)
      do ii = 1, 3
        xmin(ii) = min(xmin(ii), minval(wall%x(:, ii)))
        xmax(ii) = max(xmax(ii), maxval(wall%x(:, ii)))
      end do
    end do
    xc = 0.5*(xmin + xmax)

    ! translate walls
    do iwall = 1, nwall
      wall => walls(iwall)
      do ii = 1, 3
        wall%x(:, ii) = wall%x(:, ii) + 0.5*Lb(ii) - xc(ii)
      end do
    end do

    xmax2 = maxval(wall%x(:, 1))
    print *, "xmax2: ", xmax2

    ymax2 = maxval(wall%x(:, 2))
    print *, "ymax2: ", ymax2

  end subroutine Recenter_Cells_and_Walls

end program InitCond
! Create restart file with initial condition
program InitCond

  use ModDataTypes
  use ModDataStruct
  use ModRbc
  use ModWall
  use ModConf
  use ModData
  use ModIO
  use ModBasicMath
  use ModPostProcess
  ! use MPI

  implicit none

  integer, parameter :: nrbcMax = 128
  integer, parameter :: nwallMax = 4
  type(t_rbc), pointer :: rbc
  type(t_rbc)         :: rbcRef
  type(t_wall), pointer :: wall
  real(WP) :: radEqv, szCell(3)
  integer :: nlat0, nlat1, ii
  real(WP) :: theta, th, rc, xc(3), ztemp
  real(WP) :: xmin, xmax, ymin, ymax, zmin, zmax
  integer :: iz, i, p, l, dealias
  integer, parameter :: ranseed = 161269
  character(CHRLEN) :: fn
  ! real = double, fp
  real :: lengtube, lengspacing, phi, actlen
  real(WP) :: rand(27, 3), minDist, platRad, platDiam
  real :: wbcs(2), tubeDiam, layerx(3), layery(3), halflen

  ! Initialize
  call InitMPI
  ! Allocate working arrays
  allocate (rbcs(nrbcMax))
  ! allocate(walls(nwallMax))

  tubeDiam = 4

  nrbc = 1
  nlat0 = 6
  dealias = 3
  phi = 70/real(100)
  ! 11.34
  lengtube = 5 ! nrbc/real(phi) !XXLL

  lengspacing = lengtube/Real(nrbc)
  ! print *, "1"
  nwall = 1
  allocate (walls(nwall))
  wall => walls(1)

  call ReadWallMesh('Input/new_cyl_D6_L13_33.e', wall)
  actlen = 13.33
  wall%f = 0.
  do i = 1, wall%nvert
    th = ATAN2(wall%x(i, 1), wall%x(i, 2))
    wall%x(i, 1) = (tubeDiam/2.0)*COS(th)    !!!!!!!!!
    wall%x(i, 2) = (tubeDiam/2.0)*SIN(th)    !!!!!!!!!
    wall%x(i, 3) = lengtube/actlen*wall%x(i, 3)
  end do

  xmin = minval(wall%x(:, 1))
  xmax = maxval(wall%x(:, 1))

  ymin = minval(wall%x(:, 2))
  ymax = maxval(wall%x(:, 2))

  zmin = minval(wall%x(:, 3))
  zmax = maxval(wall%x(:, 3))

  ! size of the periodic box
  Lb(1) = xmax - xmin + 0.5
  Lb(2) = Lb(1)
  Lb(3) = zmax - zmin
  lengtube = Lb(3)

  print *, "Lb", Lb(:)
  !  Lb   8.3013429849047267        8.3013429849047267        11.347517730496456
  ! lengspacing = lengtube/real(nrbc)
  print *, 'lengtube 2', lengtube
  print *, 'lengspacing 2', lengspacing

  ! Reference cell i
  xc = 0.

  radEqv = 1.0
  platRad = .3

  print *, "platRad", platRad

  call Rbc_Create(rbcRef, nlat0, dealias)
  call Rbc_MakePlatelet(rbcRef, platRad, xc)

  do ii = 1, 3
    ! dimensions of cell !
    szCell(ii) = maxval(rbcRef%x(:, :, ii)) - minval(rbcRef%x(:, :, ii))
  end do
  if (rootWorld) then
    print *, "szCell", szCell
  end if

  ! place cells
  do iz = 1, nrbc
    xc(1:2) = 0.
    xc(3) = 1
    print *, 'platelet iz:', iz, 'xc:', xc
    rbc => rbcs(iz)
    rbc%celltype = 3
    print *, nlat0, dealias, platRad, xc
    call Rbc_Create(rbc, nlat0, dealias)
    call Rbc_MakePlatelet(rbc, platRad, xc)
  end do

  ! Put things in the middle of the periodic box
  call Recenter_Cells_and_Walls

  ! platDiam = GetDiameter(3)

  ! Output
  write (*, '(A,3F10.3)') 'Periodic domain size = ', Lb

  Nt0 = 0; time = 0.
  vBkg(1:2) = 0.; vBkg(3) = 8.

  ! Write intial conditions
  if (nrbc > 0) then
    write (fn, FMT=fn_FMT) 'D/', 'x', 0, '.dat'
    call WriteManyRBCs(fn, nrbc, rbcs)

    write(fn, FMT=fn_FMT) 'D/', '3x', 0, '.dat'
    call WriteManyRBCsByType(fn, nrbc, rbcs, 3)

    write (*, '(A,A)') 'Cell file: ', trim(fn)

    fn = 'D/restart.LATEST.dat'
    call WriteRestart(fn, Nt0, time)
    write (*, '(A,A)') 'Binary restart file: ', trim(fn)
  end if

  if (nwall > 0) then
    write (fn, FMT=fn_FMT) 'D/', 'wall', 0, '.dat'
    call WriteManyWalls(fn, nwall, walls)
    write (*, '(A,A)') 'Wall file: ', trim(fn)
  end if

  write (fn, FMT=fn_FMT) 'D/', 'restart', Nt0, '.dat'
  call WriteRestart(fn, Nt0, time)
  write (*, '(A,A)') 'Binary restart file: ', trim(fn)

  ! Deallocate working arrays
  deallocate (rbcs)

  ! Finalize
  call FinalizeMPI

  stop

contains
  subroutine Recenter_Cells_and_Walls
    integer :: irbc, iwall, ii, gen, repeat, j
    real :: x, y, a
    real, parameter :: PI = 3.14159265359
    type(t_rbc), pointer :: rbc
    type(t_wall), pointer :: wall
    real(WP) :: xmin(3), xmax(3), xc(3), xmax2, ymax2

    ! cells
    ! translate cells
    do irbc = 1, nrbc
      rbc => rbcs(irbc)
      rbc%x(:, :, 1) = rbc%x(:, :, 1) + 0.5*Lb(1)
      rbc%x(:, :, 2) = rbc%x(:, :, 2) + 0.5*Lb(2)
      print *, 'Zc', sum(rbc%x(:, :, 3))/real(rbc%nlat*rbc%nlon)
    end do

    ! walls
    ! find the bounding box
    xmin = 1.D10
    xmax = -1.D10
    do iwall = 1, nwall
      print *, "iwall", iwall
      wall => walls(iwall)
      do ii = 1, 3
        xmin(ii) = min(xmin(ii), minval(wall%x(:, ii)))
        xmax(ii) = max(xmax(ii), maxval(wall%x(:, ii)))
      end do
    end do
    xc = 0.5*(xmin + xmax)

    ! translate walls
    do iwall = 1, nwall
      wall => walls(iwall)
      do ii = 1, 3
        wall%x(:, ii) = wall%x(:, ii) + 0.5*Lb(ii) - xc(ii)
      end do
    end do

    xmax2 = maxval(wall%x(:, 1))
    print *, "xmax2: ", xmax2

    ymax2 = maxval(wall%x(:, 2))
    print *, "ymax2: ", ymax2

  end subroutine Recenter_Cells_and_Walls

end program InitCond
! Create restart file with initial condition
program InitCond

  use ModDataTypes
  use ModDataStruct
  use ModRbc
  use ModWall
  use ModConf
  use ModData
  use ModIO
  use ModBasicMath
  use ModPostProcess
  ! use MPI

  implicit none

  integer, parameter :: nrbcMax = 128
  integer, parameter :: nwallMax = 4
  type(t_rbc), pointer :: rbc
  type(t_rbc)         :: rbcRef
  type(t_wall), pointer :: wall
  real(WP) :: radEqv, szCell(3)
  integer :: nlat0, nlat1, ii
  real(WP) :: theta, th, rc, xc(3), ztemp
  real(WP) :: xmin, xmax, ymin, ymax, zmin, zmax
  integer :: iz, i, p, l, dealias
  integer, parameter :: ranseed = 161269
  character(CHRLEN) :: fn
  ! real = double, fp
  real :: lengtube, lengspacing, phi, actlen
  real(WP) :: rand(27, 3), minDist, platRad, platDiam
  integer :: j, ierr, half2, index, layer, newiz
  real :: wbcs(2), tubeDiam, layerx(3), layery(3), halflen

  ! Initialize
  call InitMPI
  ! Allocate working arrays
  allocate (rbcs(nrbcMax))
  ! allocate(walls(nwallMax))

  tubeDiam = 22.0/2.82 ! 7.8, rad = 4

  nrbc = 24
  nlat0 = 12
  nlat1 = 6
  dealias = 3
  phi = 70/real(100)
  ! 11.34
  lengtube = 32.0/2.82 ! nrbc/real(phi) !XXLL

  lengspacing = (lengtube - ((2.62/2.82)*9))/9 ! lengtube/Real(nrbc)
  ! print *, "1"
  nwall = 1
  allocate (walls(nwall))
  wall => walls(1)

  call ReadWallMesh('Input/new_cyl_D6_L13_33.e', wall)
  actlen = 13.33
  wall%f = 0.
  do i = 1, wall%nvert
    th = ATAN2(wall%x(i, 1), wall%x(i, 2))
    wall%x(i, 1) = (tubeDiam/2.0)*COS(th)    !!!!!!!!!
    wall%x(i, 2) = (tubeDiam/2.0)*SIN(th)    !!!!!!!!!
    wall%x(i, 3) = lengtube/actlen*wall%x(i, 3)
  end do

  xmin = minval(wall%x(:, 1))
  xmax = maxval(wall%x(:, 1))

  ymin = minval(wall%x(:, 2))
  ymax = maxval(wall%x(:, 2))

  zmin = minval(wall%x(:, 3))
  zmax = maxval(wall%x(:, 3))

  ! size of the periodic box
  Lb(1) = xmax - xmin + 0.5
  Lb(2) = Lb(1)
  Lb(3) = zmax - zmin
  lengtube = Lb(3)

  print *, "Lb", Lb(:)
  !  Lb   8.3013429849047267        8.3013429849047267        11.347517730496456
  ! lengspacing = lengtube/real(nrbc)
  print *, 'lengtube 2', lengtube
  print *, 'lengspacing 2', lengspacing

  ! Reference cell i
  xc = 0.

  radEqv = 1.0
  platRad = .3

  print *, "nlat1", nlat1, "platRad", platRad

  call Rbc_Create(rbcRef, nlat1, dealias)
  call Rbc_MakePlatelet(rbcRef, platRad, xc)

  do ii = 1, 3
    ! dimensions of cell !
    szCell(ii) = maxval(rbcRef%x(:, :, ii)) - minval(rbcRef%x(:, :, ii))
  end do
  if (rootWorld) then
    print *, "szCell", szCell
  end if

  layerx = (/-1.63, 1.63, 0.0/)
  layery = (/-.943, -.943, 1.89/)

  ! place cells
  do iz = 1, nrbc
    index = (modulo(iz, 3) + 1)
    layer = (iz - 1)/3
    xc(1) = layerx(index) ! + ((rand(iz, 1) - 0.2) - 0.4)
    xc(2) = layery(index) ! + ((rand(iz, 2) - 0.2) - 0.4)
    xc(3) = (layer + .5) + (.5*layer) ! + ((rand(iz, 3) - 0.5)/3)
    if (iz == 20) then
      print *, 'platelet iz:', iz, 'index: ', index, "layer: ", layer, 'xc:', xc
      rbc => rbcs(iz)
      rbc%celltype = 3
      call Rbc_Create(rbc, nlat1, dealias)
      call Rbc_MakePlatelet(rbc, platRad, xc)
    else
      print *, 'iz:', iz, 'index: ', index, "layer: ", layer, 'xc:', xc
      rbc => rbcs(iz)
      rbc%celltype = 1
      call Rbc_Create(rbc, nlat0, dealias)
      call Rbc_MakeBiConcave(rbc, radEqv, xc)
    end if
  end do

  ! Put things in the middle of the periodic box
  call Recenter_Cells_and_Walls

  ! platDiam = GetDiameter(3)

  ! Output
  write (*, '(A,3F10.3)') 'Periodic domain size = ', Lb

  Nt0 = 0; time = 0.
  vBkg(1:2) = 0.; vBkg(3) = 8.

  ! Write intial conditions
  if (nrbc > 0) then
    write (fn, FMT=fn_FMT) 'D/', 'x', 0, '.dat'
    call WriteManyRBCs(fn, nrbc, rbcs)

    write(fn, FMT=fn_FMT) 'D/', '3x', 0, '.dat'
    call WriteManyRBCsByType(fn, nrbc, rbcs, 3)

    write (*, '(A,A)') 'Cell file: ', trim(fn)

    fn = 'D/restart.LATEST.dat'
    call WriteRestart(fn, Nt0, time)
    write (*, '(A,A)') 'Binary restart file: ', trim(fn)
  end if

  if (nwall > 0) then
    write (fn, FMT=fn_FMT) 'D/', 'wall', 0, '.dat'
    call WriteManyWalls(fn, nwall, walls)
    write (*, '(A,A)') 'Wall file: ', trim(fn)
  end if

  write (fn, FMT=fn_FMT) 'D/', 'restart', Nt0, '.dat'
  call WriteRestart(fn, Nt0, time)
  write (*, '(A,A)') 'Binary restart file: ', trim(fn)

  ! Deallocate working arrays
  deallocate (rbcs)

  ! Finalize
  call FinalizeMPI

  stop

contains
  subroutine Recenter_Cells_and_Walls
    integer :: irbc, iwall, ii, gen, repeat, j
    real :: x, y, a
    real, parameter :: PI = 3.14159265359
    type(t_rbc), pointer :: rbc
    type(t_wall), pointer :: wall
    real(WP) :: xmin(3), xmax(3), xc(3), xmax2, ymax2

    ! cells
    ! translate cells
    do irbc = 1, nrbc
      rbc => rbcs(irbc)
      rbc%x(:, :, 1) = rbc%x(:, :, 1) + 0.5*Lb(1)
      rbc%x(:, :, 2) = rbc%x(:, :, 2) + 0.5*Lb(2)
      print *, 'Zc', sum(rbc%x(:, :, 3))/real(rbc%nlat*rbc%nlon)
    end do

    ! walls
    ! find the bounding box
    xmin = 1.D10
    xmax = -1.D10
    do iwall = 1, nwall
      print *, "iwall", iwall
      wall => walls(iwall)
      do ii = 1, 3
        xmin(ii) = min(xmin(ii), minval(wall%x(:, ii)))
        xmax(ii) = max(xmax(ii), maxval(wall%x(:, ii)))
      end do
    end do
    xc = 0.5*(xmin + xmax)

    ! translate walls
    do iwall = 1, nwall
      wall => walls(iwall)
      do ii = 1, 3
        wall%x(:, ii) = wall%x(:, ii) + 0.5*Lb(ii) - xc(ii)
      end do
    end do

    xmax2 = maxval(wall%x(:, 1))
    print *, "xmax2: ", xmax2

    ymax2 = maxval(wall%x(:, 2))
    print *, "ymax2: ", ymax2

  end subroutine Recenter_Cells_and_Walls

end program InitCond
{
  "trailingComma": "none",
  "overrides": [
    {
      "files": "**/lwc/**/*.html",
      "options": {
        "tabWidth": 4,
        "parser": "lwc"
      }
    },
    {
      "files": "**/*.{cls,trigger,apex}",
      "options": {
        "apexInsertFinalNewline": true,
        "printWidth": 140,
        "tabWidth": 4
      }
    },
    {
      "files": "*.{cmp,page,component}",
      "options": {
        "parser": "html",
        "tabWidth": 4
      }
    }
  ]
}
function combinations(arr, len) {
    let tempArry = []
    let final = []
    for (let i = 0; i < arr.length; i++) {
        //console.log("i ", i)
        if ((arr.length - i) == (len - 1)) {
            break
        }
        tempArry.push(arr[i])
        for (let j = i + 1; j < arr.length; j++) {
            //console.log("j ", j)
            tempArry.push(arr[j])
            //console.log("tempArry ", tempArry)
            if (tempArry.length == len) {
                //console.log("tempArry inside if ", tempArry)
                final.push([...tempArry])
                //console.log("final inside if ", final)
                tempArry.pop()
            }
        }
        tempArry = []
    }
    //console.log("final ", final)
    return final
}

function getPermutations(arr, outputLength) {
  const results = [];

  function permute(currentArr, remaining) {
    if (currentArr.length === outputLength) {
      results.push([...currentArr]); // Copy current arrangement to avoid mutation
      return;
    }

    for (let i = 0; i < remaining.length; i++) {
      const nextElement = remaining[i];
      const remainingCopy = [...remaining]; // Copy to avoid mutation
      remainingCopy.splice(i, 1);
      permute([...currentArr, nextElement], remainingCopy);
    }
  }

  permute([], arr);
  return results;
}

function processor(ind, finalQuality, mapWages, combOfWage) {
    let currentQua1 = finalQuality[ind]
    let currentWage1 = combOfWage[ind]
    //let currentWage1 = mapWages.get(finalQuality[ind])
    let after = Number(ind) + 1
    let afterQua = finalQuality[after]
    let afterWage1 = combOfWage[after]
    //let afterWage1 = mapWages.get(finalQuality[after])
    let g = afterQua / currentQua1
    combOfWage[after] = (g * currentWage1)
    //mapWages.set(afterQua, (g * currentWage1))
}
var mincostToHireWorkers = function (quality, wage, k) {
    let accumulate = 0
    let mapWages = new Map()
    for (const f in quality) {
        mapWages.set(quality[f], wage[f])
    }
    let resAccu = []
    console.log(mapWages)

    // let comb = combinations(quality, k)
    // console.log("comb ", comb)
    // let combOfWages = combinations(wage, k)
    // console.log("combOfWages ", combOfWages)

    let comb = getPermutations(quality, k)
    console.log("comb ", comb)
    let combOfWages = getPermutations(wage, k)
    console.log("combOfWages ", combOfWages)

    for (const g in comb) {
        let SortedQuality = comb[g]
        let combOfWage = combOfWages[g]
        console.log("SortedQuality is ", SortedQuality)
        let finalQuality = SortedQuality
        console.log("finalQuality is ", finalQuality)
        for (let i = finalQuality.length - 1; i >= 0; i--) {
            let prev = Number(i) - 1
            console.log("prev ", prev)
            let currentQua = finalQuality[i]
            console.log("currentQua ", currentQua)
            let currentWage = combOfWages[g][i]
            //let currentWage = mapWages.get(finalQuality[i])
            console.log("currentWage ", currentWage)
            if (i > 0) {
                let prevQua = finalQuality[prev]
                console.log("prevQua ", prevQua)
                let prevWage = combOfWages[g][prev]
                //let prevWage = mapWages.get(finalQuality[prev])
                console.log("prevWage ", prevWage)
                let ntha = currentQua / prevQua
                console.log("ntha ", ntha)
                let x = (currentWage * prevQua) / currentQua
                console.log("x ", x)
                if (x < prevWage) {
                    combOfWages[g][i] = (ntha * prevWage)
                    console.log("combOfWages[g][i] is ", combOfWages[g][i])
                    //mapWages.set(currentQua, (ntha * prevWage))
                    for (let k = i; k < finalQuality.length; k++) {
                        processor(k, finalQuality, mapWages,combOfWage )
                    }
                } else if (x > prevWage) {
                    accumulate = accumulate + currentWage
                    combOfWages[g][prev] = x
                    //mapWages.set(prevQua, x)
                } else if (x == prevWage) {
                    accumulate = accumulate + currentWage
                }
            } else {
                accumulate = accumulate + currentWage
            }
            console.log("accumulate ", accumulate)

        }
        accumulate = 0
        for (const l in finalQuality) {
            accumulate = accumulate + combOfWages[g][l]
            console.log("last finalQuality", finalQuality)
            console.log("last accumulate", accumulate)
            //accumulate = accumulate + mapWages.get(l)
        }
        resAccu.push(accumulate)
        console.log("resAccu is ", resAccu)
    }
    let finalResAccu = resAccu.sort((a, b) => a - b)
    return finalAcc = finalResAccu[0]
};
function combinations(arr, len) {
    let tempArry = []
    let final = []
    for (let i = 0; i < arr.length; i++) {
        //console.log("i ", i)
        if ((arr.length - i) == (len - 1)) {
            break
        }
        tempArry.push(arr[i])
        for (let j = i + 1; j < arr.length; j++) {
            //console.log("j ", j)
            tempArry.push(arr[j])
            //console.log("tempArry ", tempArry)
            if (tempArry.length == len) {
                //console.log("tempArry inside if ", tempArry)
                final.push([...tempArry])
                //console.log("final inside if ", final)
                tempArry.pop()
            }
        }
        tempArry = []
    }
    //console.log("final ", final)
    return final
}

function getPermutations(arr, outputLength) {
  const results = [];

  function permute(currentArr, remaining) {
    if (currentArr.length === outputLength) {
      results.push([...currentArr]); // Copy current arrangement to avoid mutation
      return;
    }

    for (let i = 0; i < remaining.length; i++) {
      const nextElement = remaining[i];
      const remainingCopy = [...remaining]; // Copy to avoid mutation
      remainingCopy.splice(i, 1);
      permute([...currentArr, nextElement], remainingCopy);
    }
  }

  permute([], arr);
  return results;
}

function processor(ind, finalQuality, mapWages, combOfWage) {
    let currentQua1 = finalQuality[ind]
    let currentWage1 = combOfWage[ind]
    //let currentWage1 = mapWages.get(finalQuality[ind])
    let after = Number(ind) + 1
    let afterQua = finalQuality[after]
    let afterWage1 = combOfWage[after]
    //let afterWage1 = mapWages.get(finalQuality[after])
    let g = afterQua / currentQua1
    combOfWage[after] = (g * currentWage1)
    //mapWages.set(afterQua, (g * currentWage1))
}
var mincostToHireWorkers = function (quality, wage, k) {
    let accumulate = 0
    let mapWages = new Map()
    for (const f in quality) {
        mapWages.set(quality[f], wage[f])
    }
    let resAccu = []
    console.log(mapWages)

    // let comb = combinations(quality, k)
    // console.log("comb ", comb)
    // let combOfWages = combinations(wage, k)
    // console.log("combOfWages ", combOfWages)

    let comb = getPermutations(quality, k)
    console.log("comb ", comb)
    let combOfWages = getPermutations(wage, k)
    console.log("combOfWages ", combOfWages)

    for (const g in comb) {
        let SortedQuality = comb[g]
        let combOfWage = combOfWages[g]
        console.log("SortedQuality is ", SortedQuality)
        let finalQuality = SortedQuality
        console.log("finalQuality is ", finalQuality)
        for (let i = finalQuality.length - 1; i >= 0; i--) {
            let prev = Number(i) - 1
            console.log("prev ", prev)
            let currentQua = finalQuality[i]
            console.log("currentQua ", currentQua)
            let currentWage = combOfWages[g][i]
            //let currentWage = mapWages.get(finalQuality[i])
            console.log("currentWage ", currentWage)
            if (i > 0) {
                let prevQua = finalQuality[prev]
                console.log("prevQua ", prevQua)
                let prevWage = combOfWages[g][prev]
                //let prevWage = mapWages.get(finalQuality[prev])
                console.log("prevWage ", prevWage)
                let ntha = currentQua / prevQua
                console.log("ntha ", ntha)
                let x = (currentWage * prevQua) / currentQua
                console.log("x ", x)
                if (x < prevWage) {
                    combOfWages[g][i] = (ntha * prevWage)
                    console.log("combOfWages[g][i] is ", combOfWages[g][i])
                    //mapWages.set(currentQua, (ntha * prevWage))
                    for (let k = i; k < finalQuality.length; k++) {
                        processor(k, finalQuality, mapWages,combOfWage )
                    }
                } else if (x > prevWage) {
                    accumulate = accumulate + currentWage
                    combOfWages[g][prev] = x
                    //mapWages.set(prevQua, x)
                } else if (x == prevWage) {
                    accumulate = accumulate + currentWage
                }
            } else {
                accumulate = accumulate + currentWage
            }
            console.log("accumulate ", accumulate)

        }
        accumulate = 0
        for (const l in finalQuality) {
            accumulate = accumulate + combOfWages[g][l]
            console.log("last finalQuality", finalQuality)
            console.log("last accumulate", accumulate)
            //accumulate = accumulate + mapWages.get(l)
        }
        resAccu.push(accumulate)
        console.log("resAccu is ", resAccu)
    }
    let finalResAccu = resAccu.sort((a, b) => a - b)
    return finalAcc = finalResAccu[0]
};
function combinations(arr, len) {
    let tempArry = []
    let final = []
    for (let i = 0; i < arr.length; i++) {
        //console.log("i ", i)
        if ((arr.length - i) == (len - 1)) {
            break
        }
        tempArry.push(arr[i])
        for (let j = i + 1; j < arr.length; j++) {
            //console.log("j ", j)
            tempArry.push(arr[j])
            //console.log("tempArry ", tempArry)
            if (tempArry.length == len) {
                //console.log("tempArry inside if ", tempArry)
                final.push([...tempArry])
                //console.log("final inside if ", final)
                tempArry.pop()
            }
        }
        tempArry = []
    }
    //console.log("final ", final)
    return final
}

function getPermutations(arr, outputLength) {
  const results = [];

  function permute(currentArr, remaining) {
    if (currentArr.length === outputLength) {
      results.push([...currentArr]); // Copy current arrangement to avoid mutation
      return;
    }

    for (let i = 0; i < remaining.length; i++) {
      const nextElement = remaining[i];
      const remainingCopy = [...remaining]; // Copy to avoid mutation
      remainingCopy.splice(i, 1);
      permute([...currentArr, nextElement], remainingCopy);
    }
  }

  permute([], arr);
  return results;
}

function processor(ind, finalQuality, mapWages, combOfWage) {
    let currentQua1 = finalQuality[ind]
    let currentWage1 = combOfWage[ind]
    //let currentWage1 = mapWages.get(finalQuality[ind])
    let after = Number(ind) + 1
    let afterQua = finalQuality[after]
    let afterWage1 = combOfWage[after]
    //let afterWage1 = mapWages.get(finalQuality[after])
    let g = afterQua / currentQua1
    combOfWage[after] = (g * currentWage1)
    //mapWages.set(afterQua, (g * currentWage1))
}
var mincostToHireWorkers = function (quality, wage, k) {
    let accumulate = 0
    let mapWages = new Map()
    for (const f in quality) {
        mapWages.set(quality[f], wage[f])
    }
    let resAccu = []
    console.log(mapWages)

    // let comb = combinations(quality, k)
    // console.log("comb ", comb)
    // let combOfWages = combinations(wage, k)
    // console.log("combOfWages ", combOfWages)

    let comb = getPermutations(quality, k)
    console.log("comb ", comb)
    let combOfWages = getPermutations(wage, k)
    console.log("combOfWages ", combOfWages)

    for (const g in comb) {
        let SortedQuality = comb[g]
        let combOfWage = combOfWages[g]
        console.log("SortedQuality is ", SortedQuality)
        let finalQuality = SortedQuality
        console.log("finalQuality is ", finalQuality)
        for (let i = finalQuality.length - 1; i >= 0; i--) {
            let prev = Number(i) - 1
            console.log("prev ", prev)
            let currentQua = finalQuality[i]
            console.log("currentQua ", currentQua)
            let currentWage = combOfWages[g][i]
            //let currentWage = mapWages.get(finalQuality[i])
            console.log("currentWage ", currentWage)
            if (i > 0) {
                let prevQua = finalQuality[prev]
                console.log("prevQua ", prevQua)
                let prevWage = combOfWages[g][prev]
                //let prevWage = mapWages.get(finalQuality[prev])
                console.log("prevWage ", prevWage)
                let ntha = currentQua / prevQua
                console.log("ntha ", ntha)
                let x = (currentWage * prevQua) / currentQua
                console.log("x ", x)
                if (x < prevWage) {
                    combOfWages[g][i] = (ntha * prevWage)
                    console.log("combOfWages[g][i] is ", combOfWages[g][i])
                    //mapWages.set(currentQua, (ntha * prevWage))
                    for (let k = i; k < finalQuality.length; k++) {
                        processor(k, finalQuality, mapWages,combOfWage )
                    }
                } else if (x > prevWage) {
                    accumulate = accumulate + currentWage
                    combOfWages[g][prev] = x
                    //mapWages.set(prevQua, x)
                } else if (x == prevWage) {
                    accumulate = accumulate + currentWage
                }
            } else {
                accumulate = accumulate + currentWage
            }
            console.log("accumulate ", accumulate)

        }
        accumulate = 0
        for (const l in finalQuality) {
            accumulate = accumulate + combOfWages[g][l]
            console.log("last finalQuality", finalQuality)
            console.log("last accumulate", accumulate)
            //accumulate = accumulate + mapWages.get(l)
        }
        resAccu.push(accumulate)
        console.log("resAccu is ", resAccu)
    }
    let finalResAccu = resAccu.sort((a, b) => a - b)
    return finalAcc = finalResAccu[0]
};
#include<iostream>
using namespace std;
class book
{
  protected:
  string title;
  string author;
  float price;
  string isbn;
  public:
   Book(string title, string author, float price, string isbn)
        : title(title), author(author), price(price), isbn(isbn) {}
  virtual ~Book() {}
    string getTitle() 
    { 
      return title; 
    }
    string getAuthor() 
    { 
      return author; 
    }
    float getPrice() 
    { 
      return price; 
    }
    string getISBN() 
    { 
      return isbn; 
    }

    void setTitle(string title) 
    { 
      title = title; 
    }
    void setAuthor(string author) 
    { 
      author = author; 
    }
    void setPrice(float price) 
    { 
      price = price; 
    }
    void setISBN(string isbn) 
    { 
      isbn = isbn; 
    }
  virtual void displayInfo()
  {
        cout << "Title: " << title << endl;
        cout << "Author: " << author << endl;
        cout << "Price: $" << price << endl;
        cout << "ISBN: " << isbn << endl;
  }
  friend float calculateDiscount(book);
};
class eBook : public Book {
private:
    string format;
    float size; 
public:
    eBook(string title, string author, float price, string isbn,
           string format, float size)
        : book(title, author, price, isbn), format(format), size(size) {}

    
    virtual void displayInfo() 
  {
        book::displayInfo(); 
        cout << "Format: " << format << endl;
        cout << "Size: " << size << " MB" << endl;
    }
};
float calculatediscount(book b)
{
        int bk=b.price;
        if(500<bk<1000)
            {
                cout<<"Discount :"<< bk-(bk*0.3)<<endl;
            }
        else if(bk>1500)
           {
                cout<<"Discount :"<< bk-(bk*0.5)<<endl;
           }
        else
           {
                cout<<"No Discount"<<endl;
    }
    return 0;
}
    
https://voidnull.es/instalacion-de-pgadmin-para-gestionar-postgresql/
// 1. You need to use tags in the Template
/// Here is link for tags: https://help.zoho.com/portal/en/kb/zoho-sign/user-guide/sending-a-document/articles/automatic-field-addition-in-zoho-sign

dealLDetails = zoho.crm.getRecordById("Deals",DealID);
// info dealLDetails;
// getAllFieldsResponse = invokeurl
// [
// 	url :"https://writer.zoho.com/api/v1/documents/flo7ld4ba09726a694424994054acbb636e81/fields"
// 	type :GET
// 	connection:"zoho_crm"
// ];
// info getAllFieldsResponse;
fieldTextData = Map();
fieldTextData.put("Deal_Name",dealLDetails.get("Deal_Name"));
fieldTextData.put("Stage",dealLDetails.get("Stage"));
fieldTextData.put("Owner",dealLDetails.get("Owner").get("name"));
contact_roles = zoho.crm.getRelatedRecords("Contact_Roles","Deals",DealID);
// info contact_roles;
contact_List = List();
count = 0;
signerList = List();
for each  contact in contact_roles
{
	count = count +1;
	name = contact.get("Full_Name");
	contact_map = Map();
	contact_map.put("Contact_Roles.Full_Name",name);
	contact_map.put("Contact_Roles.First_Name", count);
	signerMap = Map();
	signerMap.put("recipient_"+count, contact.get("Email"));
	signerMap.put("action_type", "sign");
	signerMap.put("language","en");
	contact_List.add(contact_map);
	signerList.add(signerMap);
}
fieldTextData.put("Contact_Roles",contact_List);
data_mp = Map();
data_mp.put("data",fieldTextData);
params = Map();
params.put("merge_data",data_mp);
params.put("service_name","zohosign");
params.put("signer_data",signerList);
params.put("sign_in_order","true");
// optional
params.put("message","Please find the document to be signed here");
//optional
params.put("reminder_period","15");
//optional
params.put("set_expire","30");
//optional
documentid = "flo7ld4ba09726a694424994054acbb636e81";
templatename = "Test Shareholder Agreement";
params.put("filename",templatename);
url = "https://zohoapis.com/writer/api/v1/documents/" + documentid + "/merge/sign";
info params;
/////////////////////////////
documentObj = invokeurl
[
	url :url
	type :POST
	parameters:params
	connection:"zoho_crm"
];
info documentObj;
§x§0§0§7§9§F§F§lᴄ§x§0§6§8§5§F§B§lʀ§x§0§D§9§1§F§8§lᴀ§x§1§3§9§E§F§4§lꜰ§x§1§A§A§A§F§0§lᴛ§x§2§0§B§6§E§C§lᴏ§x§2§7§C§2§E§9§lᴘ§x§2§D§C§E§E§5§lɪ§x§3§4§D§A§E§1§lᴀ §x§3§A§E§7§D§D§lɴ§x§4§1§F§3§D§A§lᴇ§x§4§7§F§F§D§6§lᴛ
§x§0§0§7§9§F§F§lᴄ§x§0§6§8§5§F§B§lʀ§x§0§D§9§1§F§8§lᴀ§x§1§3§9§E§F§4§lꜰ§x§1§A§A§A§F§0§lᴛ§x§2§0§B§6§E§C§lᴏ§x§2§7§C§2§E§9§lᴘ§x§2§D§C§E§E§5§lɪ§x§3§4§D§A§E§1§lᴀ §x§3§A§E§7§D§D§lɴ§x§4§1§F§3§D§A§lᴇ§x§4§7§F§F§D§6§lᴛ
/**
 * Method to authenticate an external credential using the external credential using the 
 * Auth URL.
 */

String externalCredential = 'TDX_DC_ORG';
String principalName = 'NAMED_PRINCIPAL';


System.debug(getAuthUrlFromConnectApi(externalCredential, principalName));


String getAuthUrlFromConnectApi(String externalCredential, String principalName){
    
    String body = JSON.serialize(
        new Map<String,String>{
            'externalCredential'=> externalCredential,
            'principalName'     => principalName,
            'principalType'     => 'NamedPrincipal'
        }
    );
    
    // Create a new request
    HttpRequest req = new HttpRequest();
    req.setMethod('POST');
    req.setEndpoint(Url.getOrgDomainUrl().toExternalForm() + '/services/data/v60.0/named-credentials/credential/auth-url/o-auth');
    req.setHeader('Authorization','Bearer ' + UserInfo.getSessionId());
    req.setHeader('Content-Length', String.ValueOf(body.length()));
    req.setBody(body);
    
    System.debug(body);

    // Execute request and fetch response
    HttpResponse res = new Http().send(req);

    // Throw an error if the status code for the final call is not equal to 200
    if(res.getStatusCode() != 200){
        throw new StringException('Unexpected status code in connect api callout. Response: ' + res.getBody());
    }

    // Parse the response into a Connect API class
    ConnectApi.OAuthCredentialAuthUrl ocau = (ConnectApi.OAuthCredentialAuthUrl) JSON.deserializeStrict(
        res.getBody(),
        ConnectApi.OAuthCredentialAuthUrl.class
    );

    // Return the authentication from the Connect API response
    return ocau.authenticationUrl;
}



// This comes from your Apex API Call
Integer statusCode        = 400;
Boolean statusIsAuthError = true;

// Configuration for
String  authUrl           = 'https://dc-mgmt-dev-ed.develop.my.salesforce.com/services/auth/xds/TDX_DC_ORG?startURL=/0puQy0000000AQn';

// Run this logic when
if(statusCode == 400 && statusIsAuthError){

    // Start the flow by calling the external credential auth URL and validate that the response is as we expect
    RedirectResponse initialResponse = validateRedirectResponse(
        callout(
            authUrl,
            null
        )
    );

    // Handle the first redirect and validate that the response is as we expect
    RedirectResponse firstRedirectResponse = validateRedirectResponse(
        callout(
            initialResponse.location,
            initialResponse.cookie
        )
    );

    // Handle the second redirect and validate that the response is as we expect
    // !! Use the cookie from the initial request !!
    HttpResponse finalResponse = callout(
            firstRedirectResponse.location,
            initialResponse.cookie
    );

    // Throw an error if the status code for the final call is not equal to 200
    if(finalResponse.getStatusCode() != 200){
        throw new StringException('Unexpected status code in final callout. Response: ' + finalResponse.getBody());
    }
}


/**
 * Method to do a get callout with a cookie header setter
 */
HttpResponse callout(String endpoint, String cookie){
    HttpRequest req = new HttpRequest();
    req.setEndpoint(endpoint);
    req.setMethod('GET');

    // Set the cookie if not blank
    if(!String.isBlank(cookie)){
        secondRedirectRequest.setHeader('Cookie',cookie);
    }
    HttpResponse res = new Http().send(req);
}


/**
 * Basic validation that the response is as we expect
 */
RedirectResponse validateRedirectResponse(HttpResponse res){
    // Check it is a status 302
    if(res.getStatusCode() != 302){
        throw new StringException('Unexpected response code, expected the response status code to be 302');
    }

    // Return a redirect response object
    return new RedirectResponse(
        res.getHeader('Location')
        res.getHeader('Set-Cookie');
    );
}


/**
 * Simple redirect response object to make the code more readable
 */
class RedirectResponse{

    public String location;
    public String cookie;

    RedirectResponse(String location, String cookie){
        this.location = location;
        this.cookie   = cookie;
    }
}
new Response(body, options):
body: The body of the response, often a JSON string.
options: An object containing configuration options for the response, such as headers and status.
By following this structure, you can handle POST requests effectively, returning appropriate responses based on the request's success or failure.
from spherov2 import scanner

with scanner.find_toy() as toy:
    ...
@mixin pseudoInit{
        content: "";
        display: block;
        position: absolute;
        left: 0; top: 0;
        z-index: -1;
}
@mixin beforeContainer($bg: transparent, $w: 100%, $h: $w){
    position: relative;
    z-index: 1;
    &::before{
        @include pseudoInit;
        background: $bg;
        width: $w;
        height: $h;
    }
}
@mixin afterContainer($bg: transparent, $w: 100%, $h: $w){
    &::after{
        @include pseudoInit;
        background: $bg;
        width: $w;
        height: $h;
    }
}
extends CharacterBody3D

# Enum for weapon states


enum WeaponState {
	UNEQUIPPED,
	EQUIPPED
}
var current_state = WeaponState.UNEQUIPPED
@onready var mesh_root = $MeshRoot

@export var S_H = 0.1
@export var S_v = 0.1
@onready var animation_player = $MeshRoot/AuxScene/AnimationPlayer
@onready var C_M = $Node3D
@onready var weapon = $MeshRoot/AuxScene/ALS_AnimMan_CharacterBP/Skeleton3D/BoneAttachment3D2/Sketchfab_Scene


var SPEED = 2
const JUMP_VELOCITY = 4.5
var running = false
var aiming = false

var running_speed = 5
var walking_speed = 2

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

func _ready():
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	weapon.hide()  # Hide the weapon initially

func _input(event):
	if event is InputEventMouseMotion:
		rotate_y(deg_to_rad(-event.relative.x * S_H))
		C_M.rotate_x(deg_to_rad(-event.relative.y * S_v))

	if event.is_action_pressed("equip_weapon"): 
		if current_state == WeaponState.UNEQUIPPED:
			equip_weapon()
		elif current_state == WeaponState.EQUIPPED:
			unequip_weapon()

	if event.is_action_pressed("aim_weapon") and current_state == WeaponState.EQUIPPED:
		start_aiming()
	elif event.is_action_released("aim_weapon") and current_state == WeaponState.EQUIPPED:
		stop_aiming()

	if event.is_action_pressed("fire_weapon") and current_state == WeaponState.EQUIPPED and aiming:
		fire_weapon()

func _physics_process(delta):
	if Input.is_action_pressed("run"):
		SPEED = running_speed
		running = true
	else:
		SPEED = walking_speed
		running = false

	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta

	# Handle jump.
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		if running:
			if current_state == WeaponState.EQUIPPED:
				if animation_player.current_animation != "gun_running":
					animation_player.play("RifleRun(2)0")
			else:
				if animation_player.current_animation != "running":
					animation_player.play("Running(2)0")
		else:
			if current_state == WeaponState.EQUIPPED:
				if animation_player.current_animation != "gun_walking":
					animation_player.play("RifleWalk(1)0")
			else:
				if animation_player.current_animation != "walking":
					animation_player.play("WalkWithBriefcase0")
					
					
		mesh_root.look_at(position + direction)
						
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		if current_state == WeaponState.EQUIPPED:
			if aiming:
				if animation_player.current_animation != "gun_aiming":
					animation_player.play("aim")
			else:
				if animation_player.current_animation != "gun_idle":
					animation_player.play("RifleIdle(1)0")
		else:
			if animation_player.current_animation != "idle":
				animation_player.play("Idle(3)0")
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()

# Function to equip the weapon
func equip_weapon():
	current_state = WeaponState.EQUIPPED
	animation_player.play("RiflePullOut(1)0")  # Play equip animation
	weapon.show()  # Make weapon visible

# Function to unequip the weapon
func unequip_weapon():
	current_state = WeaponState.UNEQUIPPED
	animation_player.play("RiflePutAway(1)0")  # Play unequip animation
	weapon.hide()  # Hide weapon after unequip

# Function to start aiming
func start_aiming():
	aiming = true
	animation_player.play("aim")  # Play aiming animation

# Function to stop aiming
func stop_aiming():
	aiming = false
	animation_player.play("gun_idle")  # Play idle animation with gun

# Function to handle firing the weapon
func fire_weapon():
	animation_player.play("FiringRifle(2)0")  # Play fire animation

# Optionally, handle animation finished signal to perform actions after animation ends
func _on_AnimationPlayer_animation_finished(anim_name):
	if anim_name == "unequip":
		weapon.hide()
	elif anim_name == "equip":
		weapon.show()
	elif anim_name == "gun_fire":
		if aiming:
			animation_player.play("aim")  # Return to aiming animation after firing
		else:
			animation_player.play("RifleIdle(1)0")
# Performing inner join
inner_join_df = df1.join(df2, df1['key'] == df2['key'], 'inner')

# Performing left join
left_join_df = df1.join(df2, df1['key'] == df2['key'], 'left')
extends CharacterBody3D

# Enum for weapon states
enum WeaponState {
	UNEQUIPPED,
	EQUIPPED
}
var current_state = WeaponState.UNEQUIPPED


@export var S_H = 0.1
@export var S_v = 0.1
@onready var animation_player = $MeshRoot/AuxScene/AnimationPlayer
@onready var C_M = $Node3D

var SPEED = 2
const JUMP_VELOCITY = 4.5
var running = false

var running_speed = 5
var walking_speed = 2



# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

func _ready():
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	
	
func _input(event):
	if event is InputEventMouseMotion:
		rotate_y(deg_to_rad(-event.relative.x*S_H))
		C_M.rotate_x(deg_to_rad(-event.relative.y*S_v))

func _physics_process(delta):
	
	if Input.is_action_pressed("run"):
		SPEED = running_speed
		running = true
	else:
		SPEED = walking_speed
		running = false
		
	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta

	# Handle jump.
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		if running:
			if animation_player.current_animation != "running":
				animation_player.play("Running(2)0")
		else:
			if animation_player.current_animation != "WalkWithBriefcase0":
				animation_player.play("WalkWithBriefcase0")
			

		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		if animation_player.current_animation != "idle":
			animation_player.play("Idle(3)0")
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()
$(function () {
      $("#teacher_grade_subject").on("click", ".btn-tambah", function() {
          $(this).css("display","none");
          $('.js-select2-2').select2({
            closeOnSelect : false,
            placeholder : "Click to select tes",
            theme: 'bootstrap4',
            allowHtml: true,
            allowClear: true,
          });
          var valtes = $(this).parent().find(".btn-hapus").css("display","none");
      });

      $("#teacher_grade_subject").on("click", ".btn-hapus", function(){
        var button_id = $(this).attr("id");
        var btn = (button_id)-1;
        var row = ($(".row-status").length)-1; 
        $('.baru-data'+button_id+'').remove();

        $(".btn-tambah").find('.baru-data'+row+'').css("display","");
        if(row != 1){
          $('.baru-data'+btn+'').find(".btn-tambah").css("display","");
          $('.baru-data'+btn+'').find(".btn-hapus").css("display","");
        } 
        else{
          $(".btn-tambah").css("display","");
          $(".btn-hapus").css("display","none");
        }
      });

    $("#teacher_grade_subject").on("change", "#teacher_grade_id_0", function() {
      loadSubjectOptions2(this.value);
    });

    $("#teacher_grade_subject").on("change", "#teacher_subject_id_0", function() {
      loadSubjectOptions2(this.value);
    });

    function loadSubjectOptions2(gradeId) {
      // Hapus semua opsi yang ada di select subject
  
      // Buat request AJAX untuk mengambil data subject berdasarkan grade
      fetch(`/get-subjects/${gradeId}`)
        .then(response => response.json())
        .then(data => {
            // Tambahkan opsi baru ke select subject
            data.forEach(subject => {
                const option = document.createElement('option');
                option.value = subject.id;
                option.text = subject.name_subject;
                subjectSelect.add(option);
            });
        })
        .catch(error => console.error(error));
    }
cd\
cd "G:\My Drive\_My_projects\_Snippets\export_monday_to_csv"
cls
python export_monday_items_data_to_json_csv.py
# Grouping data by a column and calculating aggregate functions
grouped_df = df.groupBy('column').agg({'column2': 'sum', 'column3': 'avg'})

# Applying aggregate functions to entire DataFrame
agg_df = df.agg({'column1': 'max', 'column2': 'min'})
 private void PlayRound()
 {
     //Prevents Other Games Activating Achievement
     if (PlayerData.Instance.CurrentGame != CasinoGames.Blackjack) { return; }

     roundsPlayed.UpdateAchievement(1, roundsPlayedText);
     
     if (roundsPlayed.HasUnlocked)
     {
         achievementManager.AchivementUnlocked(roundsPlayed);
         BlackJackManager.OnStartPlayerTurn -= PlayRound;
     }
 }
<p>TopHomeworkHelper.com offers comprehensive programming help for students, covering various programming languages like Java, Python, C++, and more. Services include assignment help, coding assistance, and debugging support. With 24/7 availability and experienced tutors, the platform ensures timely and reliable solutions for all programming-related academic needs.<br /><br />Source:&nbsp;<a href="https://tophomeworkhelper.com/programming-help.html" target="_blank" rel="noopener">Programming Homework Help</a></p>
<p>&nbsp;</p>
$tenant->run(function ($tenant) {
    return User::all();
});

tenancy()->central(function ($tenant) {
    return User::all();
});
#Program.cs
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    var context = services.GetRequiredService<ApplicationDbContext>();
    context.Database.Migrate();
}
// main.jsx --- change the provider
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { Provider } from 'react-redux'
import store from './store/store.jsx'

ReactDOM.createRoot(document.getElementById('root')).render(
  // <React.StrictMode>
  //   <App />
  // </React.StrictMode>,
  <Provider store={store}>
    <App />
  </Provider>,
)

// App.jsx --- call the reducer functions using useDispatch and useSelector
import React, {useState} from "react";
import { useDispatch, useSelector } from "react-redux";
import { incrementNum, decrementNum } from "./store/slices/NumberSlice";

function App() {
  const [count, setCount] = useState(0);

  const numsData = useSelector((state) => {
    return state.nums;
  })
  const dispatch = useDispatch();

  const handleNumIncrement = () => {
    dispatch(incrementNum(1));
  }
  const handleNumDecrement = () => {
    dispatch(decrementNum(1));
  }

  return (
    <div className="bg-stone-700 h-screen flex">
      <div className="mx-auto my-auto flex flex-col text-center space-y-4">
        
        {/* Title */}
        <div className="text-slate-50 font-bold text-4xl">Increment / Decrement Counter</div>

        {/* Body */}
        <div className="text-slate-300 text-2xl">This is a simple app for understanding the use of react redux</div>

        {/* Counter */}
        <div className="flex flex-row space-x-2 mx-auto border-2 border-stone-900 rounded-xl bg-stone-200">
          <button 
            onClick={handleNumIncrement}
            // onClick={()=>(setCount(prev => prev+1))}
            className="px-4 py-2 bg-stone-200 hover:bg-stone-400 text-stone-900 rounded-l-xl text-[56px] w-[70px]"
          >+</button>
          <div
            className="px-4 py-2 my-2 w-[100px] text-[48px] rounded-xl bg-stone-500"
          >{numsData}</div>
          {/* >{count}</div> */}
          <button 
            onClick={handleNumDecrement}
            // onClick={()=>(setCount(prev => prev-1))}
            className="px-4 py-2 bg-stone-200 hover:bg-stone-400 text-stone-900 rounded-r-xl text-[56px] w-[70px]"
          >-</button>
        </div>
      </div>
    </div>
  );
};

export default App;

// NumberSlice.jsx --- creating the slices where the reducers are defined
import { createSlice} from '@reduxjs/toolkit';

const numberSlice = createSlice({
    name: 'num',
    initialState: 0,
    reducers: {
        incrementNum(state, action){
            return state + action.payload;
            // state.push(action.payload) // if state was an array
        },
        decrementNum(state, action){
            return state - action.payload;
        },
    }
})

console.log(numberSlice);

export default numberSlice.reducer;
export const { incrementNum, decrementNum } = numberSlice.actions;

// store.jsx --- saving the store of redux of all the slices
import { configureStore } from "@reduxjs/toolkit";
import numberSlice from "./slices/NumberSlice";

const store = configureStore({
    reducer: {
        nums: numberSlice,
    },
});

export default store;


// File and Folder Structure
root
main.jsx
App.jsx
store -> slices -> NumberSlice.jsx
store -> store.jsx
package Questão2C;

public class RecorrenciaInducao {
    // Método para calcular T(n) usando indução
    static int calcularT(int n) {
        if (n == 1) {
            return 1; // Caso Base
        } else {
            return n + calcularT(n / 3); // Passo de Indução
        }
    }

    public static void main(String[] args) {
        int n = 5; // Mude o valor de n conforme necessário

        int resultado = calcularT(n);
        System.out.println("O valor de T(" + n + ") é: " + resultado);
    }
}
star

Mon May 20 2024 09:48:16 GMT+0000 (Coordinated Universal Time)

@ayushg103

star

Mon May 20 2024 07:39:52 GMT+0000 (Coordinated Universal Time)

@codeing

star

Mon May 20 2024 06:22:18 GMT+0000 (Coordinated Universal Time) https://shopee.co.id/

@Alfikri

star

Mon May 20 2024 01:21:44 GMT+0000 (Coordinated Universal Time)

@davelauren #svelte

star

Sun May 19 2024 19:20:00 GMT+0000 (Coordinated Universal Time)

@Akhil_preetham #javascript

star

Sun May 19 2024 12:02:30 GMT+0000 (Coordinated Universal Time)

@enojiro7

star

Sun May 19 2024 12:01:42 GMT+0000 (Coordinated Universal Time)

@enojiro7

star

Sun May 19 2024 12:00:43 GMT+0000 (Coordinated Universal Time)

@enojiro7

star

Sun May 19 2024 08:33:27 GMT+0000 (Coordinated Universal Time)

@Lalizpi

star

Sun May 19 2024 07:45:03 GMT+0000 (Coordinated Universal Time)

@d2f_coder #react.js

star

Sun May 19 2024 07:38:39 GMT+0000 (Coordinated Universal Time)

@d2f_coder #react.js

star

Sun May 19 2024 05:26:24 GMT+0000 (Coordinated Universal Time) https://mer.vin/2024/05/gpt-4o-api/

@styners1 #php

star

Sun May 19 2024 04:55:41 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/2817719e-0540-4d6b-aa1b-ce381fee1845

@jass855 #javascript

star

Sun May 19 2024 04:03:24 GMT+0000 (Coordinated Universal Time)

@davidmchale #object #check #length

star

Sat May 18 2024 07:53:43 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/dictionary-comprehension

@arslank7

star

Fri May 17 2024 22:57:39 GMT+0000 (Coordinated Universal Time)

@rmdnhsn #vba

star

Fri May 17 2024 20:31:20 GMT+0000 (Coordinated Universal Time)

@bdusenberry

star

Fri May 17 2024 20:18:03 GMT+0000 (Coordinated Universal Time)

@smanasreh

star

Fri May 17 2024 20:17:16 GMT+0000 (Coordinated Universal Time)

@smanasreh

star

Fri May 17 2024 19:47:11 GMT+0000 (Coordinated Universal Time)

@smanasreh

star

Fri May 17 2024 18:04:59 GMT+0000 (Coordinated Universal Time)

@gbritgs #apex

star

Fri May 17 2024 16:44:00 GMT+0000 (Coordinated Universal Time)

@Akhil_preetham #javascript

star

Fri May 17 2024 16:43:56 GMT+0000 (Coordinated Universal Time)

@Akhil_preetham #javascript

star

Fri May 17 2024 16:43:34 GMT+0000 (Coordinated Universal Time)

@Akhil_preetham #javascript

star

Fri May 17 2024 15:37:21 GMT+0000 (Coordinated Universal Time)

@2312096

star

Fri May 17 2024 14:38:30 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri May 17 2024 10:54:39 GMT+0000 (Coordinated Universal Time)

@Sakshu1347

star

Fri May 17 2024 10:54:38 GMT+0000 (Coordinated Universal Time)

@Sakshu1347

star

Fri May 17 2024 08:14:24 GMT+0000 (Coordinated Universal Time)

@Justus

star

Fri May 17 2024 08:05:09 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/?oai-dm

@devdutt

star

Fri May 17 2024 07:53:23 GMT+0000 (Coordinated Universal Time) https://pypi.org/project/spherov2/

@Mad_Hatter

star

Fri May 17 2024 07:42:13 GMT+0000 (Coordinated Universal Time)

@vishalsingh21

star

Fri May 17 2024 05:01:32 GMT+0000 (Coordinated Universal Time) https://processwire.com/talk/topic/28116-what-is-the-optimal-way-of-getting-rid-of-double-borders-using-a-table-with-divs/

@bayzid_dev

star

Fri May 17 2024 04:41:00 GMT+0000 (Coordinated Universal Time)

@azariel #glsl

star

Fri May 17 2024 02:16:58 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/569f918a-02ec-49fd-8512-3ccb194899c3

star

Fri May 17 2024 02:06:27 GMT+0000 (Coordinated Universal Time)

@azariel #glsl

star

Fri May 17 2024 01:37:14 GMT+0000 (Coordinated Universal Time)

@helmi

star

Thu May 16 2024 19:10:59 GMT+0000 (Coordinated Universal Time) sd

@danialawa

star

Thu May 16 2024 19:09:17 GMT+0000 (Coordinated Universal Time) https://www.afabra.store/

@danialawa

star

Thu May 16 2024 17:51:21 GMT+0000 (Coordinated Universal Time)

@lavil80

star

Thu May 16 2024 16:39:49 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/569f918a-02ec-49fd-8512-3ccb194899c3

#python
star

Thu May 16 2024 13:17:41 GMT+0000 (Coordinated Universal Time)

@jakebezz

star

Thu May 16 2024 13:03:42 GMT+0000 (Coordinated Universal Time) https://www.cadsharp.com/docs/Win32API_PtrSafe.txt

@Rooffuss

star

Thu May 16 2024 12:33:51 GMT+0000 (Coordinated Universal Time) https://tophomeworkhelper.com/programming-help.html

@alecbenjamin #programming #html #css #mysql #python #java

star

Thu May 16 2024 09:45:58 GMT+0000 (Coordinated Universal Time)

@codespare

star

Thu May 16 2024 09:38:48 GMT+0000 (Coordinated Universal Time)

@Samarmhamed78

star

Thu May 16 2024 09:02:59 GMT+0000 (Coordinated Universal Time) https://redux-toolkit.js.org/tutorials/quick-start

@eziokittu #react.js #redux #redux-toolkit

star

Wed May 15 2024 23:01:59 GMT+0000 (Coordinated Universal Time) https://github.com/S4-2024/Lista2/tree/main/src

@gabriellesoares

Save snippets that work with our extensions

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