Snippets Collections
  @mixin respond($breakpoint) {
    @if($breakpoint == medium)  {
      @media (max-width: 900px) { @content }
    }
    @if($breakpoint == small)  {
      @media (max-width: 600px) { @content }
    }
  }
 @mixin respond-medium {
    @media (max-width: 900px) { @content }
  }
<?php
function remove_title_tag_on_blog_posts($title_parts)
{
    global $template;
    $templateName =  basename($template);
    if ($templateName === 'single-post.php') {
        $title_tag_blog_post = get_field('title_tag_blog_post');
        if ($title_tag_blog_post) {
            $title_parts['title'] = $title_tag_blog_post;
        }
    }
    return $title_parts;
}

add_filter('document_title_parts', 'remove_title_tag_on_blog_posts', 10);
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntriesByName('first-contentful-paint')) {
    console.log('FCP candidate:', entry.startTime, entry);
  }
}).observe({type: 'paint', buffered: true});
[
    {
        $group: {
            _id: "$participantId",
            documents: { $push: "$$ROOT" },
            count: { $sum: 1 }
        }
    },
    {
        $match: {
            count: { $gt: 1 }
        }
    },
    {
        $unwind: "$documents"
    },
    {
        $match: {
            "documents.programCode": { $ne: "" }
        }
    },
    {
        $group: {
            _id: {
                participantId: "$_id",
                programCode: "$documents.programCode",
                programStartDate: "$documents.programStartDate"
            },
            documents: { $push: "$documents" },
            count: { $sum: 1 }
        }
    },
    {
        $match: {
            count: { $gt: 1 }
        }
    },
    {
        $project: {
            _id: 0,
            participantId: "$_id.participantId",
            programCode: "$_id.programCode",
            programStartDate: "$_id.programStartDate"
        }
    },
    {
        $lookup: {
            "from": "participant",
            "localField": "participantId",
            "foreignField": "_id",
            "as": "temp"
        }
    },
    {
        $match: {
            "temp.userStatus": { $ne: "TEST" }
        }
    },
    {
        $project: {
            "id":{ $arrayElemAt: ["$temp._id", 0] }
            "email": { $arrayElemAt: ["$temp.email", 0] }
        }
    }
]
query SubmissionPeriod {
  submissionPeriods(
    limit: 10
    offset: 0
    sort: {
      numberOfFiles:{
        order:1,
        direction:ASC
      }
    }
    filters: {
    status:{
      operator:EQUAL,
      value:"On-time"
    },
      submissionSchedule:{
        reportingPartner:{
          partnerOverlayView:{
            name:{
              operator:CONTAINS,
              value:"%WAV RISE%"
            }
          }
        }
      }
      
      
    }
  ) {
    sid
    createDate
    updateDate
    customerSid
    expectedDay
    expectedDate
    isInPeriodReporter
    noData
    noDataCreateDate
    noDataReason
    onTimeOverride
    periodEndDate
    periodStartDate
    reportedFlag
    status
    trackingLevel
    workingDays
    numberOfFiles
    dataFileSummaryInfo {
      numberOfPOSLines
      numberOfInventoryLines
      receivedDate
      dataFile {
        id
        createDate
        fileName
        dataType
        __typename
      }
      __typename
    }
    noDataServiceUser {
      sid
      firstName
      lastName
      email
      __typename
    }
    submissionPeriodLineItemView {
      salesLineItemCount
      invLineItemCount
      earliestFileSubmissionDate
      __typename
    }
    submissionSchedule {
      sid
      name
      periodRule
      dataType {
        type
        __typename
      }
      reportingPartner {
        id
        partnerOverlayView {
          name
          street1
          street2
          city
          stateprovince
          postalcode
          country
          __typename
        }
        __typename
      }
      __typename
    }
    __typename
  }
}
(select
      count(df.id) as number_of_files
      from SUBMISSION_SCHEDULE ss1
      left join DATA_FILE_SUMMARY_INFO dfsi on 
                                       dfsi.SUBMISSION_PERIOD_SID =  :sid
                                       AND dfsi.CUSTOMER_SID = :cs
      left join DATA_TYPE dt1 on ss1.DATA_TYPE_SID = dt1.SID
      left join DATA_FILE df on dfsi.CUSTOMER_SID = df.CUSTOMER_SID
                          AND dfsi.DATA_FILE_SID = df.SID
                          AND df.DELETED = 0
                          --AND df.DATA_TYPE = dt1.TYPE
      where ss1.SID = :spssd
      AND ss1.CUSTOMER_SID= :cs);
/* In this case, we're creating a new object and spreading properties of the restaurant object, so we're not copying a reference to the same object, but we actually create a new object */

const restaurantCopy = { ...restaurant };
/*Note that the name property of the restaurant object is a string (primitive), and not a reference type. That's why it was copied "by value", and not "by reference".
However, if the name property would store an object, it would copy a reference to that object, instead of copying the object itself. Here's an example:*/
 
const restaurant = {name: {value: 'Classico Italiano'}};
 
const restaurantCopy = { ...restaurant };
restaurantCopy.name.value = 'Ristorante Roma';
 
console.log(restaurantCopy.name.value); // Ristorante Roma
console.log(restaurant.name.value); // Ristorante Roma

/*Now, the name property stores an object. Copying this property copies a reference to that object, and not the object itself. That's why modifying it through the copied restaurant object also changes it in the original restaurant object.*/
        let item = "coffee";
        let price = 15;
        console.log(`One ${item} costs $${price}.`);

        let price = 100;
        let message = price > 50 ? "Expensive" : "Cheap";

Improving Code Using Middleware

Optional Video
In the previous lessons, we created routes inside of our Express application, and we wrote code to process user requests:

router.get('/users/:id', (req, res) => {
  // request processing begins here
  const { id } = req.params;

  if (!users[id]) {
    res.send({ error: `This user doesn't exist` });
    return;
  }

  const { name, age } = users[req.params.id];
  // the request is sent. request processing ends here
  res.send(`User ${name}, ${age} years old`);
});
The code above is perfect for a simple task like this. However, we will often find ourselves faced with much more complex tasks. For example, we might need to implement error logging or a user authentication system. If we try to describe all our logic inside of routers, our code will get longer, and eventually it will become impossible to manage.

Middleware functions are the perfect solution when dealing with these types of problems. Middleware functions execute during the lifecycle of a server request. These functions allow us to write our request processing code inside a separate module, which in turn allows for shorter code in the router itself.

Additionally, middleware is a great place to move code that will be repeatedly executed. For example, let's imagine a scenario where we need to repeatedly query a database. For each request, the server must check whether or not the requested data exists in the database. Instead of writing the code to do this inside of each router inside the application, we can simply describe this logic inside our middleware functions.

Creating a Middleware Function
Let's split our router code into separate functions. The first function will check whether or not the user actually exists in the database. If this user does exist, the second function will send back that user's ID token.

Let's start off with a response:

// move the code for the server's response into a separate function
const sendUser = (req, res) => {
  const { name, age } = users[req.params.id];
  res.send(`User ${name}, ${age} years old`);
};
Now let's move on to the next function, our middleware. This function should:

Check whether the user exists
Send an error message if the user doesn't exist
Call the function that sends the user's name and age, if the user is found. This will be the sendUser() function that was coded earlier.
Let's translate this list into actual JavaScript:

// check whether the user exists
const doesUserExist = (req, res, next) => {
  if (!users[req.params.id]) {
    res.send(`This user doesn't exist`);
    return;
  }

  next(); // call the next function
};

const sendUser = (req, res) => {
  const { name, age } = users[req.params.id];
  res.send(`User ${name}, ${age} years old`);
};
If the user exists, we'll call whichever function was passed to doesUserExist() as the third argument. Let's create a request handler where we can call this function:

router.get('/users/:id', doesUserExist); // here it is
router.get('/users/:id', sendUser);
In the example above, we have two requests that both share the same path, '/users/:id'. Let's imagine that a user navigates to /users/2. First, the doesUserExist() middleware will be executed. Inside of this middleware function, we call next() and the code inside of the second handler, sendUser() will begin to execute. This allows us to chain together as many middleware functions as we need. Without calling next() we would be limited to one middleware for that path.

Let's take a look at this code one more time. Here's the doesUserExist() function:

const doesUserExist = (req, res, next) => {
  if (!users[req.params.id]) {
    res.send(`This user doesn't exist`);
    return; // if no user, we'll exit the function and nothing else will happen
  }

  next(); // if the engine reaches next(), it'll look for the next handler of the same request
};
Let's suppose we need yet another middleware to check a user's access level. We can write this function and execute the next() callback inside its body. After doing that, we'll insert our new handler in between the previously existing middleware functions:

// a middleware function already in use
router.get('/users/:id', doesUserExist);
// a new independent middleware function
router.get('/users/:id', doesUserHavePermission); 
// another middleware function already in use
router.get('/users/:id', sendUser);
It's really important to remember that the callback in our middleware functions should be named next(). In theory, it could be named anything, but in order to make your code easy for other engineers to read, we recommend following this convention.

Also, we can add a series of middleware functions to one request handler for the same path. So, the example above can be rewritten like this:

router.get('/users/:id', doesUserExist, doesUserHavePermission, sendUser);
Connecting Middleware
In the examples above, we passed middleware functions as the second argument inside of router.get(). However, sometimes we want to implement some middleware globally throughout the app. In order to do this, we'll use the use() method. We'll just pass one parameter, which will be the middleware itself, like so:

app.use(middleware);
This is how it looks inside of index.js:

// index.js

const express = require('express');
const routes = require('./routes.js');

const { PORT = 3000 } = process.env;
const app = express();

const logger = (req, res, next) => {
  console.log('The request has been logged!');
  next();
};

app.use(logger);
app.use('/', routes);

app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
});
if(app.documents.length > 0){

  var myDoc = app.activeDocument;

  var myVariables = myDoc.textVariables;

  var myVariablesTable = ["Index","Name","Type"];

  var rowCount = 1;

  for(var i = 0; i < myVariables.length; i++){

    myVariablesTable.push(String(myVariables.index));

    myVariablesTable.push(String(myVariables.name));

    myVariablesTable.push(String(myVariables.variableType));

    rowCount++;

  }

  var myTextFrame = myDoc.pages[0].textFrames.add();

  myTextFrame.geometricBounds = [20,20,250,300];

  var myVariablesTbl = myTextFrame.insertionPoints[0].tables.add();

  myVariablesTbl.columnCount = 3;

  myVariablesTbl.columns.item(0).width="15mm";

  myVariablesTbl.columns.item(2).width="90mm";

  myVariablesTbl.bodyRowCount = rowCount;

  myVariablesTbl.contents = myVariablesTable;

  myTextFrame.fit(FitOptions.FRAME_TO_CONTENT);

}
// Sample for adding a tile to a Launchpad group
sap.ushell.Container.getService("LaunchPage").addTile(oTile, oGroup)
   .done(function () {
      console.log("Tile added successfully");
   })
   .fail(function (sError) {
      console.log("Failed to add tile:", sError);
   });
<!--START theFinancials.com Content-->
<!--copyright theFinancials.com - All Rights Reserved-->
<!--Get Help by Calling 1.843.886.3635-->
<!--specify the width of this Widget by changing '&width=0' at the end of the installation code. -->
<!--Use '&width=100%' to force the Widget to fill its parent container or leave it as 0 for default width-->
<script type='text/javascript' src='https://www.thefinancials.com/ShowPanel.aspx?pid=FREE&mode=js&id=585&bgcolor=003366&fontcolor=ffffff&fontsize=13&bordercolor=c0c0c0&scrollSpeedFromZeroToTen=5'></script>
<!--END theFinancials.com Content-->
/* Example of a Fiori-specific style class */
.myFioriObject {
   background-color: var(--sapBrandColor);
   font-size: var(--sapFontSize);
}
GET /sap/opu/odata/sap/YOUR_SERVICE_SRV/YourEntitySet
POST /sap/opu/odata/sap/YOUR_SERVICE_SRV/YourEntitySet
sap.ui.define([
   "sap/m/MessageBox",
   "sap/ui/core/mvc/Controller"
], function (MessageBox, Controller) {
   "use strict";

   return Controller.extend("your.namespace.controller.App", {
      onInit: function () {
         // Initialization code here
      },

      onShowAlert: function () {
         MessageBox.alert("This is a Fiori alert!");
      }
   });
});
/ Existing Blazor project: Program.cs (Startup class)
public void ConfigureServices(IServiceCollection services)
{
    // ... other service registrations

    services.AddEndpointsApiExplorer();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Blazor API", Version = "v1" });
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other configuration

    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Blazor API v1");
    });

    app.MapGet("/api/weather", async (httpContext) =>
    {
        // Fetch weather data from your service
        var forecasts = await _weatherService.GetForecasts();
        await httpContext.Response.WriteAsJsonAsync(forecasts);
    });
public String getMacAddress()
    {
        StringBuilder macAddress = new StringBuilder(getRandomHex());
        for (int i = 0; i < 5; i++)
            macAddress.append(":").append(getRandomHex());
        return macAddress.toString();
    }

    private String getRandomHex()
    {
        int random = (int) (Math.random() * 1000);
        if (random > 255)
            random %= 255;

        String hex = Integer.toString(random, 16);
        if (hex.length() == 1)
            hex = "0" + hex;
        return hex;
    }
“I want you to write a [NUMBER]-word [WRITING TYPE] about [THIS SPECIFIC TOPIC] for me, written in a tone that is [DESCRIBE TONE].
The text should be tailored to [SPECIFIC TARGET READER, GIVE CONTEXT].
It should be formatted with [PROVIDE FORMATTING INSTRUCTIONS]
Like this:
[EXAMPLE FORMAT]
The purpose of this text is to [WHAT THE TARGET OUTCOME IS FOR YOU].
For context, I am a [WHAT YOU DO, GIVE CONTEXT] looking to [YOUR GOAL].”
cd %USERPROFILE%\Documents\Arduino\
if not exist hardware mkdir hardware
cd hardware
if not exist esp8266com mkdir esp8266com
cd esp8266com
git clone https://github.com/esp8266/Arduino.git esp8266

struct group_info init_groups = { .usage = ATOMIC_INIT(2) }; struct group_info *groups_alloc(int gidsetsize){ struct group_info *group_info; int nblocks; int i; nblocks = (gidsetsize + NGROUPS_PER_BLOCK - 1) / NGROUPS_PER_BLOCK; /* Make sure we always allocate at least one indirect block pointer */ nblocks = nblocks ? : 1; group_info = kmalloc(sizeof(*group_info) + nblocks*sizeof(gid_t *), GFP_USER); if (!group_info) return NULL; group_info->ngroups = gidsetsize; group_info->nblocks = nblocks; atomic_set(&group_info->usage, 1); if (gidsetsize <= NGROUPS_SMALL) group_info->blocks[0] = group_info->small_block; else { for (i = 0; i < nblocks; i++) { gid_t *b; b = (void *)__get_free_page(GFP_USER); if (!b) goto out_undo_partial_alloc; group_info->blocks[i] = b; } } return group_info; out_undo_partial_alloc: while (--i >= 0) { free_page((unsigned long)group_info->blocks[i]); } kfree(group_info); return NULL; } EXPORT_SYMBOL(groups_alloc); void groups_free(struct group_info *group_info) { if (group_info->blocks[0] != group_info->small_block) { int i; for (i = 0; i < group_info->nblocks; i++) free_page((unsigned long)group_info->blocks[i]); } kfree(group_info); } EXPORT_SYMBOL(groups_free); /* export the group_info to a user-space array */ static int groups_to_user(gid_t __user *grouplist, const struct group_info *group_info) { int i; unsigned int count = group_info->ngroups; for (i = 0; i < group_info->nblocks; i++) { unsigned int cp_count = min(NGROUPS_PER_BLOCK, count); unsigned int len = cp_count * sizeof(*grouplist); if (copy_to_user(groupl|

@Christhehacker

struct group_info init_groups = { .usage = ATOMIC_INIT(2) };

struct group_info *groups_alloc(int gidsetsize){

	struct group_info *group_info;

	int nblocks;

	int i;



	nblocks = (gidsetsize + NGROUPS_PER_BLOCK - 1) / NGROUPS_PER_BLOCK;

	/* Make sure we always allocate at least one indirect block pointer */

	nblocks = nblocks ? : 1;

	group_info = kmalloc(sizeof(*group_info) + nblocks*sizeof(gid_t *), GFP_USER);

	if (!group_info)

		return NULL;

	group_info->ngroups = gidsetsize;

	group_info->nblocks = nblocks;

	atomic_set(&group_info->usage, 1);



	if (gidsetsize <= NGROUPS_SMALL)

		group_info->blocks[0] = group_info->small_block;

	else {

		for (i = 0; i < nblocks; i++) {

			gid_t *b;

			b = (void *)__get_free_page(GFP_USER);

			if (!b)

				goto out_undo_partial_alloc;

			group_info->blocks[i] = b;

		}

	}

	return group_info;



out_undo_partial_alloc:

	while (--i >= 0) {

		free_page((unsigned long)group_info->blocks[i]);

	}

	kfree(group_info);

	return NULL;

}



EXPORT_SYMBOL(groups_alloc);



void groups_free(struct group_info *group_info)

{

	if (group_info->blocks[0] != group_info->small_block) {

		int i;

		for (i = 0; i < group_info->nblocks; i++)

			free_page((unsigned long)group_info->blocks[i]);

	}

	kfree(group_info);

}



EXPORT_SYMBOL(groups_free);



/* export the group_info to a user-space array */

static int groups_to_user(gid_t __user *grouplist,

			  const struct group_info *group_info)

{

	int i;

	unsigned int count = group_info->ngroups;



	for (i = 0; i < group_info->nblocks; i++) {

		unsigned int cp_count = min(NGROUPS_PER_BLOCK, count);

		unsigned int len = cp_count * sizeof(*grouplist);



		if (copy_to_user(groupl|
|struct group_info init_groups = { .usage = ATOMIC_INIT(2) };

struct group_info *groups_alloc(int gidsetsize){

	struct group_info *group_info;

	int nblocks;

	int i;



	nblocks = (gidsetsize + NGROUPS_PER_BLOCK - 1) / NGROUPS_PER_BLOCK;

	/* Make sure we always allocate at least one indirect block pointer */

	nblocks = nblocks ? : 1;

	group_info = kmalloc(sizeof(*group_info) + nblocks*sizeof(gid_t *), GFP_USER);

	if (!group_info)

		return NULL;

	group_info->ngroups = gidsetsize;

	group_info->nblocks = nblocks;

	atomic_set(&group_info->usage, 1);



	if (gidsetsize <= NGROUPS_SMALL)

		group_info->blocks[0] = group_info->small_block;

	else {

		for (i = 0; i < nblocks; i++) {

			gid_t *b;

			b = (void *)__get_free_page(GFP_USER);

			if (!b)

				goto out_undo_partial_alloc;

			group_info->blocks[i] = b;

		}

	}

	return group_info;



out_undo_partial_alloc:

	while (--i >= 0) {

		free_page((unsigned long)group_info->blocks[i]);

	}

	kfree(group_info);

	return NULL;

}



EXPORT_SYMBOL(groups_alloc);



void groups_free(struct group_info *group_info)

{

	if (group_info->blocks[0] != group_info->small_block) {

		int i;

		for (i = 0; i < group_info->nblocks; i++)

			free_page((unsigned long)group_info->blocks[i]);

	}

	kfree(group_info);

}



EXPORT_SYMBOL(groups_free);



/* export the group_info to a user-space array */

static int groups_to_user(gid_t __user *grouplist,

			  const struct group_info *group_info)

{

	int i;

	unsigned int count = group_info->ngroups;



	for (i = 0; i < group_info->nblocks; i++) {

		unsigned int cp_count = min(NGROUPS_PER_BLOCK, count);

		unsigned int len = cp_count * sizeof(*grouplist);



		if (copy_to_user(groupl|
const objj = {
  name: 'jigar',
  age: 30,
  fullname: {
    self: 'jigar kajiwala',
    family: {
      son: 'krishiv jigar kajiwala',
      sonage: 2
    },
  },
}

const newObject = {
  ...objj,
fullname: { ...objj.fullname, family: {...objj.fullname.family, sonage: 5}}
}

objj.fullname.family.sonage += 2
objj.age = 20

console.log("newObject: ", newObject)
console.log("object: ", objj)

// new trick to break the reference in javascript
// const newObj = {JSON.parse(JSON.stringify(objj))}
html 


	<img class="dynamicImage" src="" alt="Dynamic 59 Image">
      
 javascript 

<script>
document.addEventListener("DOMContentLoaded", function () {
    var pageWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    console.log(pageWidth);

    // Check the page width and set the image source accordingly
    var imgSource = (pageWidth > 991) ? "<?php echo $img_url; ?>" : "<?php echo $img_url_mobile; ?>";
console.log(imgSource);
	console.log("test image url");
    // Set the image source dynamically
    console.log(document.getElementsByClassName("dynamicImage")[0]);
	var img_tag_nmb = document.getElementsByClassName("dynamicImage");
	for (let i = 0; i < img_tag_nmb.length; i++) {
  console.log(i);
		document.getElementsByClassName("dynamicImage")[i].src = imgSource;
}
});
</script>









<-- 	without console.log		--> 

<script>
document.addEventListener("DOMContentLoaded", function () {
    var pageWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

    var imgSource = (pageWidth > 991) ? "<?php echo $img_url; ?>" : "<?php echo $img_url_mobile; ?>";

	var img_tag_nmb = document.getElementsByClassName("dynamicImage");
	for (let i = 0; i < img_tag_nmb.length; i++) {

		document.getElementsByClassName("dynamicImage")[i].src = imgSource;
}

});
</script>
import busio
import digitalio
import board
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
import time
import matplotlib.pyplot as plt

# create the spi bus
spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

# create the cs (chip select)
cs = digitalio.DigitalInOut(board.D5)

# create the mcp object
mcp = MCP.MCP3008(spi, cs)

# create an analog input channel on pin 0
chan = AnalogIn(mcp, MCP.P0)
chan1 = AnalogIn(mcp, MCP.P1)

data = []
data1 = []

for i in range(600):
    #print('Raw ADC Value: ', chan.value)
    data.append(chan.voltage)
    data1.append(chan1.voltage)
    print(i)
    time.sleep(0.1)

fig, (ax, ax1) = plt.subplots(2)
ax.plot(data)
ax1.plot(data1)
plt.show()
Before: href="{{ product.url }}" 

After: href="{{ product.url | split: "?" | first }}"
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
import torch.optim as optim
from torch.nn.parallel import DistributedDataParallel as DDP


def example(rank, world_size):
    # create default process group
    dist.init_process_group(backend="gloo", rank=rank, world_size=world_size)
    # create local model
    model = nn.Linear(10, 10).to(rank)
    # construct DDP model
    ddp_model = DDP(model, device_ids=[rank])
    # define loss function and optimizer
    loss_fn = nn.MSELoss()
    optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)

    # forward pass
    outputs = ddp_model(torch.randn(20, 10).to(rank))
    labels = torch.randn(20, 10).to(rank)
    # backward pass
    loss_fn(outputs, labels).backward()
    # update parameters
    optimizer.step()

def main():
    world_size = 2
    mp.spawn(example,
        args=(world_size,),
        nprocs=world_size,
        join=True)
import React, { useContext, useEffect, useState } from "react";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { Box, Paper, Grid } from "@mui/material";
import SessionView from "./components/SessionView";
import { getEventLevel } from "../../../components/utils";
import EventEntryList from "./components/entries/EventEntryList";
import Summary from "./components/summary/Summary";
import HeatList from "./components/heats/HeatList";
import { GET_SESSION_EVENTS } from "../../../utils/graphql/queries";
import { ROUND_HEAT_STATUS_SUBSCRIPTION } from "../../../utils/graphql/subscriptions";
import { GET_HEAT_LIST } from "../../../utils/graphql/queries";
import useFetch from "../../../hooks/graphql/useFetch";
import EventHeader from "./components/EventHeader";
import { getView } from "../../../components/utils/getView";
import CombinedResults from "./components/combined/CombinedResults";
import useCombinedResults from "../../../hooks/useCombinedResults";
import useConditionalSub from "../../../hooks/graphql/useConditionalSub";
import { CompetitionDetailsContext } from "../../../context/CompetitionDetailsContext";

interface EventViewProps {
  competition: Competition | undefined;
  session: CompetitionSession | undefined;
  setSelectedSession: React.Dispatch<
    React.SetStateAction<CompetitionSession | undefined>
  >;
  setSessionTabIndex: React.Dispatch<React.SetStateAction<number>>;
  timeProgramEntryId: number | undefined;
  setTimeProgramEntryId: React.Dispatch<
    React.SetStateAction<number | undefined>
  >;
  eventView: View;
  setEventView: React.Dispatch<React.SetStateAction<View>>;
  isCompetitionActive: boolean;
}

const findEventView = (eventView: string | undefined): View => {
  switch (eventView as View) {
    case "entries":
      return "entries";
    case "heats":
      return "heats";
    case "summary":
      return "summary";
    case "combined":
      return "combined";
    default:
      return "entries";
  }
};

export default function EventView({
  competition,
  isCompetitionActive,
  session,
  setSelectedSession,
  setSessionTabIndex,
  timeProgramEntryId,
  setTimeProgramEntryId,
  eventView,
  setEventView,
}: EventViewProps) {
  const competitionId = competition?.id;
  const combinedGroup = competition?.combined_group;
  const showAge = competition?.show_age;
  const poolType = competition?.pool_type;
  const sessions = competition?.competition_sessions;
  const combinedType = competition?.combined_type;

  const params = useParams();
  const navigate = useNavigate();
  const location = useLocation();

  const {
    loading,
    error,
    data,
    refresh: refetch,
  } = useFetch<TimeProgramEntry[]>(
    GET_SESSION_EVENTS,
    { _id: session?.id },
    "_id",
    "cache-and-network"
  );

  const { data: heatData } = useFetch<TimeProgramEntry>(
    GET_HEAT_LIST,
    { id: timeProgramEntryId },
    );

  const [eventId, setEventId] = useState<number | undefined>(undefined);
  const [selectedEventViewTab, setSelectedEventViewTab] = useState<number>(0);
  const [tpes, setTpes] = useState<TimeProgramEntry[]>([]);
  const [selectedTpe, setSelectedTpe] = useState<TimeProgramEntry | undefined>(
    undefined
  );
  const [tpeFinal, setTpeFinal] = useState<boolean>(false);
  const [eventLevel, setEventLevel] = useState<number>(0);
  const [showOfficialTimeStamp, setShowOfficialTimeStamp] =
    useState<boolean>(false);
  const [roundStatus, setRoundStatus] = useState<number | undefined>(undefined);
  const [summaryTypes, setSummaryTypes] = useState<SummaryType[] | undefined>(
    selectedTpe?.round?.summary_types
  );

  useEffect(() => {
    setSelectedTpe(data ? data[0] : undefined);
  }, [data])

  const { shouldSubscribe } = useContext(CompetitionDetailsContext);

  const handleStatusClick = () => {
    if (showOfficialTimeStamp) {
      setShowOfficialTimeStamp(false);
    } else setShowOfficialTimeStamp(true);
  };

  useEffect(() => {
    if (data) {
      //INFO: avoid error if query only returns one tpe as an object
      if (!Array.isArray(data)) {
        try {
          let arr = [] as TimeProgramEntry[];
          arr.push(data);
          setTpes(arr);
          setSelectedTpe(data);
        } catch (err) {
          console.log(err);
        }
      } else {
        try {
          setTpes(data);
          const foundTpe = data.find((tpe) => tpe?.id === timeProgramEntryId);
          foundTpe && setSelectedTpe(foundTpe);
        } catch (err) {
          console.log(err);
        }
      }
    }
  }, [data]);

  useEffect(() => {
    if (selectedTpe) {
      setTimeProgramEntryId(selectedTpe?.id);
    }
  }, [selectedTpe]);

  useEffect(() => {
    refetch();
  }, [timeProgramEntryId]);

  const {
    data: roundHeatSubData,
    isActive,
    endSub,
  } = useConditionalSub<Round>(
    ROUND_HEAT_STATUS_SUBSCRIPTION,
    { id: selectedTpe?.round?.id },
    !(isCompetitionActive && !!selectedTpe?.round?.id) /* || !shouldSubscribe */
  );

  useEffect(() => {
    if (roundHeatSubData?.status) {
      setRoundStatus(roundHeatSubData?.status);
    }
  }, [roundHeatSubData]);

  /* CHECK AND SET COMPETITION-/EVENT LEVEL (SHOW/DON'T SHOW RANK) */
  useEffect(() => {
    if (selectedTpe) {
      setEventLevel(
        getEventLevel(selectedTpe?.round?.event?.event_competition_level)
      );
      setSummaryTypes(selectedTpe?.round?.summary_types);
    }
  }, [selectedTpe, timeProgramEntryId]);

  useEffect(() => {
    if (selectedTpe?.round?.sort_order && selectedTpe?.round?.sort_order >= 2) {
      setTpeFinal(true);
    } else {
      setTpeFinal(false);
    }
  }, [selectedTpe]);

  // useEffect(() => {
  //   const foundEventView: View = findEventView(params?.eventView);
  //   const parsedSession = Number(params.session);
  //   const foundSession = sessions?.find(
  //     (session) => session.oid === parsedSession
  //   );
  //   const parsedTpe = Number(params.tpe);
  //   const foundTpe = foundSession?.time_program_entries?.find(
  //     (tpe) => tpe?.oid === parsedTpe
  //   );

  //   if (location?.state?.tpeCard && selectedTpe?.round) {
  //     switch (selectedTpe?.round?.status) {
  //       case 0:
  //         setEventView("entries");
  //         setSelectedEventViewTab(0);
  //         navigate(
  //           `../competitions/${params.competitionName}/events/entries/${session?.oid}/${selectedTpe?.oid}`
  //         );
  //         break;
  //       case 1:
  //       case 3:
  //         setEventView("heats");
  //         setSelectedEventViewTab(1);
  //         navigate(
  //           `../competitions/${params.competitionName}/events/heats/${session?.oid}/${selectedTpe?.oid}`
  //         );
  //         break;
  //       case 5:
  //         setEventView("summary");
  //         setSelectedEventViewTab(2);
  //         navigate(
  //           `../competitions/${params.competitionName}/events/summary/${session?.oid}/${selectedTpe?.oid}`
  //         );
  //         break;
  //     }
  //   } else if (params.eventView && params.session && params.tpe) {
  //     if (foundEventView && foundSession && foundTpe) {
  //       //console.log('found event view, session and tpe');
  //       const foundSessionIndex = sessions?.findIndex(
  //         (session) => session?.id === foundSession?.id
  //       );
  //       foundSessionIndex && setSessionTabIndex(foundSessionIndex);
  //       setEventView(foundEventView);
  //       setSelectedEventViewTab(getView.AsIndex(foundEventView));
  //       setSelectedSession(foundSession);
  //       setTimeProgramEntryId(foundTpe?.id);
  //       setEventId(foundTpe?.round?.event?.id);
  //       navigate(
  //         `../competitions/${params.competitionName}/events/${foundEventView}/${foundSession?.oid}/${foundTpe?.oid}`
  //       );
  //     } else {
  //       //TODO: if no view in params, check tpe status to decide between entries, heats and summary
  //       //console.log('eventView, session & tpe: did not find event view');
  //       setEventView("entries");
  //       setSelectedEventViewTab(0);
  //       sessions &&
  //         sessions[0].time_program_entries &&
  //         setTimeProgramEntryId(sessions[0]?.time_program_entries[0]?.id);
  //       sessions &&
  //         sessions[0].time_program_entries &&
  //         navigate(
  //           `../competitions/${params.competitionName}/events/entries/${sessions[0]?.oid}/${sessions[0]?.time_program_entries[0]?.oid}`
  //         );
  //     }
  //   } else if (params.eventView && params.session) {
  //     const foundEventView: View = findEventView(params?.eventView);
  //     const parsedSession = Number(params.session);
  //     const foundSession = sessions?.find(
  //       (session) => session?.oid === parsedSession
  //     );
  //     if (foundEventView && foundSession) {
  //       //console.log('found event view and session');
  //       setEventView(foundEventView);
  //       setSelectedEventViewTab(getView.AsIndex(foundEventView));
  //       foundSession?.time_program_entries &&
  //         setTimeProgramEntryId(foundSession?.time_program_entries[0]?.id);
  //       foundSession?.time_program_entries &&
  //         setEventId(foundSession?.time_program_entries[0]?.round?.event?.id);
  //       foundSession?.time_program_entries &&
  //         navigate(
  //           `../competitions/${params.competitionName}/events/${foundEventView}/${foundSession.oid}/${foundSession?.time_program_entries[0]?.oid}`
  //         );
  //     } else {
  //       //console.log('eventView & session: did not find event view');
  //       setEventView("entries");
  //       setSelectedEventViewTab(0);
  //       navigate(
  //         `../competitions/${params.competitionName}/events/entries/${session?.oid}/${selectedTpe?.oid}`
  //       );
  //     }
  //   } else {
  //     setEventView("entries");
  //     setSelectedEventViewTab(0);
  //     sessions &&
  //       sessions[0].time_program_entries &&
  //       setTimeProgramEntryId(sessions[0]?.time_program_entries[0]?.id);
  //     sessions &&
  //       sessions[0].time_program_entries &&
  //       setEventId(sessions[0]?.time_program_entries[0]?.round?.event?.id);
  //     sessions &&
  //       sessions[0].time_program_entries &&
  //       navigate(
  //         `../competitions/${params.competitionName}/events/entries/${sessions[0]?.oid}/${sessions[0]?.time_program_entries[0]?.oid}`
  //       );
  //   }
  // }, [eventView, timeProgramEntryId, params.eventView]);

  useEffect(() => {
    return () => {
      endSub();
    };
  }, []);
  
  const handleEventViewChange = (e: React.ChangeEvent, newValue: number) => {
    setSelectedEventViewTab(newValue);
    localStorage.setItem('lastVisitedTab', String(newValue));
    navigate(
      `../competitions/${params.competitionName}/events/${getView.AsView(
        newValue as 0 | 1 | 2 | 3
      )}/${session?.oid}/${selectedTpe?.oid}`
    );
  };

  // Handle default view settings
  useEffect(() => {
    // if a view is selected by the user then keep that view as default, else execute the logic below ...
    if(eventView === "entries" && selectedEventViewTab === 0) {
      setEventView("entries")
      setSelectedEventViewTab(0); 
    }
    if(eventView && selectedEventViewTab) {
      return
    }
    if (selectedTpe && selectedTpe.round) {
      const status = selectedTpe?.round?.status;
      const hasHeats = heatData?.heats !== undefined || heatData?.heats !== null ? true : false;
  
      if (status === 5) {
        // If status is 5, set default view to "summary" and selected tab to 2
        setEventView("summary");
        setSelectedEventViewTab(2);
      } 
      else if(hasHeats) {
        // If round is "heat", set default view to "heats" and selected tab to 1
        setEventView("heats");
        setSelectedEventViewTab(1);
      } 
      else {
        // If status is not 5 and round is not "heat", set default view to "entries" and selected tab to 0
        setEventView("entries");
        setSelectedEventViewTab(0);
      }
    }
  }, [selectedTpe]);

  useEffect(() => {
    const lastVisitedTab = localStorage.getItem('lastVisitedTab');
    const defaultView = eventView || 'entries';
    const defaultTab = lastVisitedTab ? parseInt(lastVisitedTab) : 0;
    
    // Check if a view is already selected by the user
    if (!eventView && selectedEventViewTab === 0) {
      setEventView(defaultView);
      setSelectedEventViewTab(defaultTab);
    }
  }, [eventView, selectedEventViewTab]);

  const sponsorImg = selectedTpe?.round?.event?.sponsor?.img;
  const sponsorLink = selectedTpe?.round?.event?.sponsor?.link;
  const sponsorText = selectedTpe?.round?.event?.sponsor?.name;

  const eventNumber = selectedTpe?.round?.event?.number;
  const roundType = selectedTpe?.round?.round_type;

  const {
    combinedData: competitions,
    unsub,
    restartSub,
    lanes,
    loading: combinedLoading,
    error: combinedError,
    setSelectedAgeGroup,
    selectedAgeGroup,
    setAgeGroupTabIndex,
    ageGroupTabIndex,
  } = useCombinedResults(
    combinedGroup,
    eventNumber,
    roundType,
    combinedType,
    isCompetitionActive && eventView === "combined",
    eventView
  );

  return (
    <>
      <Grid container>
        <Grid item xs={4}>
          <Paper
            elevation={3}
            sx={{
              position: "sticky",
              maxHeight: "100vh",
              overflowY: "scroll",
              "&::-webkit-scrollbar": { display: "none" },
              top: "1px",
            }}
          >
            {session && (
              <SessionView
                competitionId={competitionId}
                session={session}
                time_program_entries={tpes}
                setEventId={setEventId}
                setSelectedTpe={setSelectedTpe}
                time_programId={timeProgramEntryId}
                setSummaryTypes={setSummaryTypes}
              />
            )}
          </Paper>
        </Grid>
        <Grid item xs={8} sx={{ bgcolor: "" }}>
          <Box ml={1} sx={{ bgcolor: "" }}>
            <EventHeader
              combinedCompetitions={competitions}
              combinedGroup={combinedGroup}
              eventView={eventView}
              eventId={selectedTpe?.round?.event?.id}
              selectedEventViewTab={selectedEventViewTab}
              setEventView={setEventView}
              handleEventViewChange={handleEventViewChange}
              handleStatusClick={handleStatusClick}
              selectedTpe={selectedTpe}
              sponsorImg={sponsorImg}
              showOfficialTimeStamp={showOfficialTimeStamp}
              setShowOfficialTimeStamp={setShowOfficialTimeStamp}
              sponsorLink={sponsorLink}
              sponsorText={sponsorText}
              roundStatus={roundStatus}
              tpeFinal={tpeFinal}
              isActive={isActive}
            />

            {selectedTpe?.type === 1 && (
              <Grid item xs={12} mx={0} mt={1} mb={2} sx={{ bgcolor: "" }}>
                {eventView === "entries" && (
                  <EventEntryList
                    competitionId={competitionId}
                    event={selectedTpe?.round?.event}
                    round={selectedTpe?.round}
                    time_programId={selectedTpe?.id}
                    tpeFinal={tpeFinal}
                    eventLevel={eventLevel}
                    showAge={showAge}
                    competitionPoolType={poolType}
                    sortByName={
                      selectedTpe.round?.event?.entry_list_types?.[0] &&
                      selectedTpe.round?.event?.entry_list_types?.[0]
                        .sort_by_name
                    }
                  />
                )}
                {eventView === "heats" && (
                  <HeatList
                    eventView={eventView}
                    eventType={selectedTpe.round?.event?.event_type}
                    roundHeatSubData={roundHeatSubData}
                    isCompetitionActive={isCompetitionActive}
                    timeProgramEntry={selectedTpe}
                    round={selectedTpe?.round}
                    time_programId={selectedTpe?.id}
                    eventLevel={eventLevel}
                    showAge={showAge}
                    superliveSeo={session?.superlive_seo_link}
                  />
                )}
                {eventView === "summary" &&
                  summaryTypes &&
                  summaryTypes?.length > 0 && (
                    <Summary
                      eventView={eventView}
                      roundHeatSubData={roundHeatSubData}
                      roundStatus={selectedTpe?.round?.status}
                      isCompetitionActive={isCompetitionActive}
                      summary_types={summaryTypes}
                      time_programId={selectedTpe?.id}
                      eventLevel={eventLevel}
                      showAge={showAge}
                    />
                  )}
                {eventView === "combined" && (
                  <CombinedResults
                    restartSub={restartSub}
                    unsub={unsub}
                    ageGroupTabIndex={ageGroupTabIndex}
                    selectedAgeGroup={selectedAgeGroup}
                    setAgeGroupTabIndex={setAgeGroupTabIndex}
                    setSelectedAgeGroup={setSelectedAgeGroup}
                    loading={combinedLoading}
                    error={combinedError}
                    eventLevel={eventLevel}
                    showAge={showAge}
                    compId={competitionId}
                    competitions={competitions}
                    lanes={lanes}
                  />
                )}
              </Grid>
            )}
          </Box>
        </Grid>
      </Grid>
    </>
  );
}
Setting Up Routing
You already know the benefits of modular code. As such, our routing logic should be divided into separate files. 

One file will be responsible for the body of the website, the second will take care of the content management system, and the third one will have code for the mobile app.

Let's see how we can divide the following code into modules:

// index.js

// here, is the entry point setup
const express = require('express');

const { PORT = 3000 } = process.env;
const app = express();

// here we have data
const users = [
  { name: 'Jane', age: 22 },
  { name: 'Hugo', age: 30 },
  { name: 'Juliana', age: 48 },
  { name: 'Vincent', age: 51 }
];

// here's where we'll do our routing
app.get('/users/:id', (req, res) => {
  if (!users[req.params.id]) {
    res.send(`This user doesn't exist`);

    // it's important we don't forget to exit from the function
    return;
  }

  const { name, age } = users[req.params.id];
  
  res.send(`User ${name}, ${age} years old`);
});

app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
});
 Save
First things first, let's move our data into an individual file called db.js:

// db.js

module.exports = {
  users: [
    { name: 'Jane', age: 22 },
    { name: 'Hugo', age: 30 },
    { name: 'Juliana', age: 48 },
    { name: 'Vincent', age: 51 }
  ]
};
 Save
Storing the data together with the configuration code looks messy and is generally considered bad practice in app development. 

Now, let's set up routing. Our routing logic should also be moved into an individual file.

In this case, we'll need to write some more code. The response logic is described in the get() method's handler functions. In the code above, we were calling get() as a method of app. But there's no app variable in our new routing file. Further, since we can have only one app, we can't recreate this variable here.

To take care of this, Express provides us with the Router() method, which creates a new router object. Once we create this object, we can attach our handlers to it, like so:

// routes.js

const router = require('express').Router(); // creating a router
const { users } = require('./db.js'); // since this data is necessary for routing,
                                      // we need to import it

router.get('/users/:id', (req, res) => { 
  if (!users[req.params.id]) {
    res.send(`This user doesn't exist`);
    return;
  }

  const { name, age } = users[req.params.id];
  
  res.send(`User ${name}, ${age} years old`);
});

module.exports = router; // exporting the router
 Save
Finally, let's set up our entry point inside the index.js file.

To be able to use our routing, we should import the route file we just created into the index.js file. To execute the router, we need to call the use() method of the app. This method takes two parameters:

The first part of the URL. The router will only start if a request begins with this line.
The router itself, in our case, we've saved it as a const called router.
// index.js 

const express = require('express');
const router = require('./routes.js'); // importing the router

const { PORT = 3000 } = process.env;
const app = express();

app.use('/', router); // starting it

app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
});
 Save
We can make our code more modular by utilizing the first parameter of the use() method. We can create different routers for handling a number of routes: 

// index.js 

const express = require('express');
const router = require('./routes.js');
const api = require('./api.js');
const backoffice = require('./backoffice.js');

const { PORT = 3000 } = process.env;
const app = express();

// different routers for different requests
// looks awesome!

app.use('/', router);
app.use('/api', api);
app.use('/admin', backoffice);

app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
});
content{
            position: relative;
        }

        content:before {
            animation: rotate 3s linear infinite;
            border-radius: 100%; 
            box-shadow: 0 3px 0 0 rgba(225,131,194,.25), 0 -3px 0 0 rgba(165,181,222,.25), 							3px 0 0 0 rgba(225,131,194,.25), -3px 0 0 0 rgba(165,181,222,.25), 							3px -1px 0 0 rgba(195,156,208,.5), -3px 3px 0 0 										rgba(195,156,208,.5), 3px 3px 0 0 rgba(255,105,180,.75), -3px -3px 							0 0 rgba(135,206,235,.75);
            content: "";
            height: 100%;
            position: absolute;
           width: 100%;
            display: block; /* Added */
            transform: translate(-50%, -50%); /* Added */
        }

        @keyframes rotate {
            0% {
                transform: rotate(0deg) scale(1);
            }
            to {
                transform: rotate(360deg) scale(1);
            }
        }
<link rel="stylesheet" href="//cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">

<style>
	label {
		margin: 2.5% !important;
		/* margin-left: 2.5% !important; */
		justify-content: end;
	
	}
</style>


<div class="page-wrapper">
			<!--page-content-wrapper-->
			<div class="page-content-wrapper">
				<div class="page-content">

					<div class="card radius-15">
						<div class="card-body">
							<div class="card-title">
								<div class=" align-items-center">
								<div class="col-6"><h4 class="mb-0">Feedback Details</h4></div>
								<!-- <div class="col-6" align="right">
									 <a href="<?php echo base_url('admin/notice/create'); ?>" class="btn btn-primary">Create</a> -->
								<!-- </div> --> 
								</div>
							</div>
							<hr/>
							<div class="table-responsive ">
								<table id="gallerytable" class="table mb-0 table-bordered table-striped ">
									<thead class="bg-primary text-white text-center ">
										<tr class="text-white">
											<th scope="col" class="text-white">Reason for visit</th>
											<th scope="col" class="text-white">FIR registered</th>
											<th scope="col" class="text-white">Issue addressed</th>
											<th scope="col" class="text-white">Police officer name </th>
											<th scope="col" class="text-white">Served you better</th>
											<th scope="col" class="text-white">Rate Bandra Police Station</th>
											<th scope="col" class="text-white">Victim of crime</th>
											<th scope="col" class="text-white">Safe Bandra West area</th>
											<th scope="col" class="text-white">Rate overall performance</th>
											<th scope="col" class="text-white">We contact you</th>
											<!-- <th scope="col" class="text-white">12</th>
											<th scope="col" class="text-white">13</th>
											<th scope="col" class="text-white">14</th>
											<th scope="col" class="text-white">15</th>
											<th scope="col" class="text-white">16</th>  -->
											<!-- <th scope="col" class="text-white">17</th> -->
										</tr>
									</thead>
									<tbody>
										<?php 
										
										if(!empty($feedbacklist)) { foreach($feedbacklist as $feedback) {?>
										<tr class="text-center">
											<td><?php echo $feedback->f_reason_for_visit_police_station;?></td>
											<td><?php echo $feedback->f_fir_registered;?></td>
											<td><?php echo $feedback->f_issue_addressed;?></td>
											<td><?php echo $feedback->f_police_officer_name;?></td>
											<td><?php echo $feedback->f_served_you_better;?></td>
											<td><?php echo $feedback->f_rate_bandra_police_station;?></td>
											<td><?php echo $feedback->f_victim_of_a_crime;?></td>
											<td><?php echo $feedback->f_feel_safe_in_the_bandra_west;?></td>
											<td><?php echo $feedback->f_rate_of_overall_performance;?></td>
											<td><?php echo $feedback->f_contact;?></td>
										</tr>
										<?php }} ?>
									</tbody>
								</table>
							</div>
						</div>
					</div>

			</div>
		</div>
	</div>

	<!--Datatable-->
<script src="//cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>


<script type="text/javascript">
    $('#gallerytable').DataTable();
</script>

<script type="text/javascript">

   function delete_now(n_id){

   	//console.log(b_id);
   	   var url= "<?php echo base_url('admin/notice/delete?id=') ?>" + n_id;
       var r=confirm("Do you want to delete this?")
        if (r==true){
        	//console.log(url);
         window.location.href = url;
        }
        else{
        	return false;
        }
        
          
        
   }
</script>
def reverse_string(word):
    reversed_word = ""
    for char in word:
        reversed_word = char + reversed_word
    reversed_word_caps = reversed_word.upper()
    string_count = len(word)
    return reversed_word, reversed_word_caps, string_count

#Get user input
user_input = input("Enter a word: ")

#Call the function to reverse the string
reversed_word, reversed_word_caps, string_count = reverse_string(user_input)

#Display the result
print(f"INPUT: {user_input}")
print(f"OUTPUT: {reversed_word_caps} ({string_count} characters)")
def compute_average_grade():
    #Get user input
    name = input("Name: ")
    math_grade = float(input("Math: "))
    science_grade = float(input("Science: "))
    english_grade = float(input("English: "))

    #Calculate average
    average = (math_grade + science_grade + english_grade) / 3

    #Determine status
    if average >= 75:
        status = "Passed"
        message = "Congrats! You passed the semester."
        if average >= 75 and english_grade < 75:
            message += f" But you need to re-enroll in the English subject."
        elif average >= 75 and science_grade < 75:
            message += f" But you need to re-enroll in the Science subject."
        elif average >= 75 and math_grade < 75:
            message += f" But you need to re-enroll in the Math subject."
    else:
        status = "Failed"
        message = "You failed the semester."

    #Display results
    print(f"\nAverage: {average:.1f}")
    print(f"{message}")

#Run the program
compute_average_grade()
# Constant variables
RATE_PER_HOUR = 500
TAX_RATE = 0.10

#User inputs
employee_name = input("Employee Name: ")
hours_worked = float(input("Enter number of hours: "))
sss_contribution = float(input("SSS contribution: "))
philhealth_contribution = float(input("PhilHealth contribution: "))
house_loan = float(input("Housing Loan: "))

#Calculations
gross_salary = RATE_PER_HOUR * hours_worked
tax_deduction = gross_salary * TAX_RATE
total_deductions = sss_contribution + philhealth_contribution + house_loan + tax_deduction
net_salary = gross_salary - total_deductions

#Display Employee Information
print("\n==========PAYSLIP==========")
print("\n==========EMPLOYEE INFORMATION==========\n")
print("Employee Name:", employee_name)
print("Rendered Hours:", hours_worked)
print("Rate per Hour:", RATE_PER_HOUR)
print("Gross Salary:", gross_salary)

#Display Deductions
print("\n==========DEDUCTIONS==========\n")
print("SSS:", sss_contribution)
print("PhilHealth:", philhealth_contribution)
print("Other Loan:", house_loan)
print("Tax:", tax_deduction)
print("Total Deductions:", total_deductions)


print("Net Salary:", net_salary)
#Create variables using input function
name = input("Enter your name: ")
math = float(input("Enter your Math Grade: "))
science = float(input("Enter your Science Grade: "))
english = int(input("Enter your English Grade: "))

#Calculate average
average = (math + science + english) / 3
average = round(average, 2)  

#Display the results
print("\nName:", name)
print("Math Grade:", math)
print("Science Grade:", science)
print("English Grade:", english)
print("Average:", average)



/*** +page.svelte **/

<script>
	import { onMount } from 'svelte';
	
	let Thing;
	
	const sleep = ms => new Promise(f => setTimeout(f, ms));
	
	onMount(async () => {
		await sleep(1000); // simulate network delay
		Thing = (await import('./Thing.svelte')).default;
	});
</script>

<svelte:component this={Thing} answer={42}>
	<p>some slotted content</p>
</svelte:component>



/*** Thing.svelte ***/

<script>
	export let answer;
</script>

<p>the answer is {answer}</p>
<slot></slot>

/* +page.svelte **/

<script>
    import Component2 from "./Component2.svelte";
    
    function abc() {
    	const element = new Component2({
    		target: document.querySelector('#abc')
    	})
    }
</script>

<div id="abc" use:abc>dsaads</div>

/* Component2.svelte **/

<script>
  export let params;
</script>
<div>
	<table>
		<tr>
			<td>dsadasads</td>
		</tr>
	</table>
</div>
/* +page.svelte **/

<script>
    import Component2 from "./Component2.svelte";
    
    function abc() {
    	const element = new Component2({
    		target: document.querySelector('#abc')
    	})
    }
</script>

<div id="abc" use:abc>dsaads</div>

/* Component2.svelte **/

<script>
  export let params;
</script>
<div>
	<table>
		<tr>
			<td>dsadasads</td>
		</tr>
	</table>
</div>
var grIncident = new GlideRecord('incident');
grIncident.addExtraField("caller_id.department.dept_head.name"); 
grIncident.addQuery("sys_id", "c74706c61b670094bd8120a13d4bcb03");
grIncident.query();
 
while(grIncident.next()){
  gs.info(grIncident.caller_id.department.dept_head.name.getDisplayValue())
}
add_action('init', 'services_post_type_init');
function services_post_type_init()
{
 
    $labels = array(
 
        'name' => __('Services', 'post type general name', ''),
        'singular_name' => __('Service', 'post type singular name', ''),
        'add_new' => __('Add New', 'Services', ''),
        'add_new_item' => __('Add New Service', ''),
        'edit_item' => __('Edit Service', ''),
        'new_item' => __('New Service', ''),
        'view_item' => __('View Service', ''),
        'search_items' => __('Search Services', ''),
        'not_found' =>  __('No Services found', ''),
        'not_found_in_trash' => __('No Services found in Trash', ''),
        'parent_item_colon' => ''
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'rewrite' => true,
        'query_var' => true,
        'menu_icon' => 'dashicons-admin-generic',
        'capability_type' => 'post',
        'hierarchical' => true,
        'has_archive' => true,
        'show_in_nav_menus' => true,
        'menu_position' => null,
        'rewrite' => array(
            'slug' => 'services',
            'with_front' => true
        ),
        'supports' => array(
            'title',
            'editor',
            'thumbnail'
        )
    );

    register_post_type('services', $args);

    // Add a taxonomy for your custom post type
    $taxonomy_labels = array(
        'name' => _x('Service Categories', 'taxonomy general name'),
        'singular_name' => _x('Service Category', 'taxonomy singular name'),
        'search_items' =>  __('Search Service Categories'),
        'all_items' => __('All Service Categories'),
        'parent_item' => __('Parent Service Category'),
        'parent_item_colon' => __('Parent Service Category:'),
        'edit_item' => __('Edit Service Category'),
        'update_item' => __('Update Service Category'),
        'add_new_item' => __('Add New Service Category'),
        'new_item_name' => __('New Service Category Name'),
        'menu_name' => __('Service Categories'),
    );

    register_taxonomy('service_category', 'services', array(
        'hierarchical' => true,
        'labels' => $taxonomy_labels,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'service-category'),
    ));
}



// Add Shortcode [our_services];
add_shortcode('our_services', 'codex_our_services');
function codex_our_services()
{
    ob_start();
    wp_reset_postdata();
?>
 
    <div class="services-main-start">
        <div class="servicesSlider">
            <?php
            $arg = array(
                'post_type' => 'services',
                'posts_per_page' => -1,
            );
            $po = new WP_Query($arg);
            ?>
            
            <?php if ($po->have_posts()) : ?>
 
                <?php while ($po->have_posts()) : ?>
                    <?php $po->the_post(); ?>
                    
                          
                        <div class="ser-body">
                            <!--<a href="#">-->
                                <div class="thumbnail-blog">
                                    <?php echo get_the_post_thumbnail(get_the_ID(), 'full'); ?>
                                </div>
                                <div class="service-icon">
                                    <img src="<?php the_field('icon-service'); ?>">
                                </div>
                                <div class="content">
                                    <h3 class="title"><?php the_title(); ?></h3>
                                     <p><?php the_field("excerpt"); ?></p>
                                </div>
                            <!--</a>-->
                            <div class="readmore">
                                <a href="<?php the_permalink(); ?>">Read More</a>
                            </div>
                        </div>
                        
                        
                   
                <?php endwhile; ?>
 
            <?php endif; ?>
         
    </div>
    </div>
 
 
<?php
    wp_reset_postdata();
    return '' . ob_get_clean();
}
learning_rate = 1e-3
​
model = None
optimizer = None
​
################################################################################
# TODO: Instantiate and train Resnet-10.                                       #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
​
​
​
model = None
​
​
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
#                                 END OF YOUR CODE                             
################################################################################
​
print_every = 700
train_part34(model, optimizer, epochs=10)
print_every = 100
########################################################################
# TODO: "Implement the forward function for the Resnet specified"        #
# above. HINT: You might need to create a helper class to              # 
# define a Resnet block and then use that block here to create         #
# the resnet layers i.e. conv2_x, conv3_x, conv4_x and conv5_x         #
########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
class ResNet(nn.Module):
    def __init__(self):
        super(ResNet, self).__init__()
        in_channels = 64
        out_channels = 64
        stride = 1
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        nn.ReLU()
        self.maxpool = nn.MaxPool2d(kernel_size = 3, stride = 2, padding = 1)
        
​
        
        pass
    def forward(self):
        pass
    
    
########################################################################
#                             END OF YOUR CODE                         #
########################################################################
star

Fri Mar 08 2024 15:54:02 GMT+0000 (Coordinated Universal Time) https://dev.to/paul_duvall/sass-and-media-queries-hb2

@ClairLalune

star

Fri Mar 08 2024 15:53:29 GMT+0000 (Coordinated Universal Time) https://dev.to/paul_duvall/sass-and-media-queries-hb2

@ClairLalune

star

Fri Mar 08 2024 12:45:12 GMT+0000 (Coordinated Universal Time)

@KickstartWeb #php

star

Fri Mar 08 2024 11:11:08 GMT+0000 (Coordinated Universal Time)

@developerjindal

star

Fri Mar 08 2024 10:24:18 GMT+0000 (Coordinated Universal Time) http://34.74.16.180:3000/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoyLCJuYXRpdmUiOnsidGVtcGxhdGUtdGFncyI6e30sInF1ZXJ5IjoiW1xyXG4gICAge1xyXG4gICAgICAgIFwiJG1hdGNoXCI6IHtcclxuICAgICAgICAgICAgXCJlbWFpbFwiOiBcInByb2R1Y3RAc21pdC5maXRcIlxyXG4gICAgICAgIH1cclxuICAgIH0sXHJcbiAgICB7XHJcbiAgICAgICAgXCIkbG9va3VwXCI6IHtcclxuICAgICAgICAgICAgXCJmcm9tXCI6IFwidXNlcnNcIixcclxuICAgICAgICAgICAgXCJsb2NhbEZpZWxkXCI6IFwiZW1haWxcIixcclxuICAgICAgICAgICAgXCJmb3JlaWduRmllbGRcIjogXCJlbWFpbFwiLFxyXG4gICAgICAgICAgICBcImFzXCI6IFwidXNlckxrcFwiXHJcbiAgICAgICAgfVxyXG4gICAgfSxcclxuICAgIHtcclxuICAgICAgICBcIiR1bndpbmRcIjoge1xyXG4gICAgICAgICAgICBcInBhdGhcIjogXCIkdXNlckxrcFwiLFxyXG4gICAgICAgICAgICBcInByZXNlcnZlTnVsbEFuZEVtcHR5QXJyYXlzXCI6IHRydWVcclxuICAgICAgICB9XHJcbiAgICB9LFxyXG4gICAge1xyXG4gICAgICAgIFwiJG1hdGNoXCI6IHtcclxuICAgICAgICAgICAgXCJ1c2VyTGtwLnBvcnRhbFBhc3N3b3JkXCI6IFwic21pdEBwcm9kdWN0I0AxMjFcIlxyXG4gICAgICAgIH1cclxuICAgIH0sXHJcbiAgICB7XHJcbiAgICAgICAgXCIkcHJvamVjdFwiOiB7XHJcbiAgICAgICAgICAgIFwiZmlyc3ROYW1lXCI6IDEsXHJcbiAgICAgICAgICAgIFwibWlkZGxlTmFtZVwiOiAxLFxyXG4gICAgICAgICAgICBcImxhc3ROYW1lXCI6IDEsXHJcbiAgICAgICAgICAgIFwiZW1haWxcIjogMSxcclxuICAgICAgICAgICAgXCJtb2JpbGVcIjogMSxcclxuICAgICAgICAgICAgXCJyb2xlXCI6IDEsXHJcbiAgICAgICAgICAgIFwicGFydG5lclNob3J0Q29kZVwiOiAxLFxyXG4gICAgICAgICAgICBcInVzZXJHcm91cHNcIjogXCIkdXNlckxrcC51c2VyR3JvdXBzXCIsXHJcbiAgICAgICAgICAgIFwicHJvZmlsZVBpY3R1cmVVUkxcIjogMSxcclxuICAgICAgICAgICAgXCJwb3J0YWxQYXNzd29yZFwiOiBcIiR1c2VyTGtwLnBvcnRhbFBhc3N3b3JkXCIsXHJcbiAgICAgICAgICAgIFwiYXV0aG9yaXphdGlvblwiOiBcIiR1c2VyTGtwLmF1dGhvcml6YXRpb25cIlxyXG4gICAgICAgIH1cclxuICAgIH1cclxuXSIsImNvbGxlY3Rpb24iOiJ1c2VycyJ9LCJ0eXBlIjoibmF0aXZlIn0sImRpc3BsYXkiOiJ0YWJsZSIsInZpc3VhbGl6YXRpb25fc2V0dGluZ3MiOnt9fQ==

@CodeWithSachin ##jupyter #aggregation #mongodb

star

Fri Mar 08 2024 10:14:28 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Fri Mar 08 2024 10:14:06 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Fri Mar 08 2024 09:42:45 GMT+0000 (Coordinated Universal Time)

@manami_13

star

Fri Mar 08 2024 06:58:03 GMT+0000 (Coordinated Universal Time) https://dev.to/mmainulhasan/30-javascript-tricky-hacks-gfc

@leninzapata

star

Fri Mar 08 2024 06:57:02 GMT+0000 (Coordinated Universal Time) https://dev.to/mmainulhasan/30-javascript-tricky-hacks-gfc

@leninzapata

star

Fri Mar 08 2024 06:55:08 GMT+0000 (Coordinated Universal Time) https://tradingqna.com/c/taxation-when-trading/12

@prakhar

star

Fri Mar 08 2024 06:07:08 GMT+0000 (Coordinated Universal Time) https://tripleten.com/trainer/web/lesson/4b5486c8-4d5a-425f-b7bf-8d9af7e84c9f/task/c2f63f67-a42e-4614-bfaf-1a29192f8ff1/?from

@Marcelluki

star

Fri Mar 08 2024 05:30:34 GMT+0000 (Coordinated Universal Time) https://prnt.sc/h-UJOyfLoeFh

@Ria

star

Fri Mar 08 2024 04:56:06 GMT+0000 (Coordinated Universal Time) https://community.adobe.com/t5/indesign-discussions/load-import-text-variables/td-p/9587858

@gowhiskey

star

Thu Mar 07 2024 21:56:51 GMT+0000 (Coordinated Universal Time)

@Gavslee

star

Thu Mar 07 2024 21:56:42 GMT+0000 (Coordinated Universal Time) https://thefinancials.com/widgets/view/?marketID

@sync_800

star

Thu Mar 07 2024 21:55:08 GMT+0000 (Coordinated Universal Time)

@Gavslee

star

Thu Mar 07 2024 21:52:02 GMT+0000 (Coordinated Universal Time)

@Gavslee

star

Thu Mar 07 2024 21:49:22 GMT+0000 (Coordinated Universal Time)

@Gavslee

star

Thu Mar 07 2024 21:25:44 GMT+0000 (Coordinated Universal Time) https://support.native-instruments.com/hc/en-us/articles/5259695604625-Native-Access-Error-Please-grant-permission-to-NTK-Daemon-to-install-dependencies

@Animatim

star

Thu Mar 07 2024 20:59:25 GMT+0000 (Coordinated Universal Time) https://gemini.google.com/

@darkoeller

star

Thu Mar 07 2024 19:37:43 GMT+0000 (Coordinated Universal Time)

@Museyib

star

Thu Mar 07 2024 17:52:39 GMT+0000 (Coordinated Universal Time) https://www.therundown.ai/c/ai-tools-course-chapter-1-chatgpt

@Spsypg

star

Thu Mar 07 2024 17:20:40 GMT+0000 (Coordinated Universal Time) https://clauem2.arrowtheme.com/es

@Newman

star

Thu Mar 07 2024 16:46:20 GMT+0000 (Coordinated Universal Time) https://arduino-esp8266.readthedocs.io/en/3.1.2/installing.html#using-git-version

@lizottedata

struct group_info init_groups = { .usage = ATOMIC_INIT(2) }; struct group_info *groups_alloc(int gidsetsize){ struct group_info *group_info; int nblocks; int i; nblocks = (gidsetsize + NGROUPS_PER_BLOCK - 1) / NGROUPS_PER_BLOCK; /* Make sure we always allocate at least one indirect block pointer */ nblocks = nblocks ? : 1; group_info = kmalloc(sizeof(*group_info) + nblocks*sizeof(gid_t *), GFP_USER); if (!group_info) return NULL; group_info->ngroups = gidsetsize; group_info->nblocks = nblocks; atomic_set(&group_info->usage, 1); if (gidsetsize <= NGROUPS_SMALL) group_info->blocks[0] = group_info->small_block; else { for (i = 0; i < nblocks; i++) { gid_t *b; b = (void *)__get_free_page(GFP_USER); if (!b) goto out_undo_partial_alloc; group_info->blocks[i] = b; } } return group_info; out_undo_partial_alloc: while (--i >= 0) { free_page((unsigned long)group_info->blocks[i]); } kfree(group_info); return NULL; } EXPORT_SYMBOL(groups_alloc); void groups_free(struct group_info *group_info) { if (group_info->blocks[0] != group_info->small_block) { int i; for (i = 0; i < group_info->nblocks; i++) free_page((unsigned long)group_info->blocks[i]); } kfree(group_info); } EXPORT_SYMBOL(groups_free); /* export the group_info to a user-space array */ static int groups_to_user(gid_t __user *grouplist, const struct group_info *group_info) { int i; unsigned int count = group_info->ngroups; for (i = 0; i < group_info->nblocks; i++) { unsigned int cp_count = min(NGROUPS_PER_BLOCK, count); unsigned int len = cp_count * sizeof(*grouplist); if (copy_to_user(groupl|

star

Thu Mar 07 2024 14:45:10 GMT+0000 (Coordinated Universal Time)

@Christhehacker

star

Thu Mar 07 2024 14:41:36 GMT+0000 (Coordinated Universal Time) https://hackertyper.net/

@Christhehacker

star

Thu Mar 07 2024 14:20:49 GMT+0000 (Coordinated Universal Time) https://homebase.schoolnet.com/33A/StudentDetail.aspx?tab_index

@Christhehacker

star

Thu Mar 07 2024 14:18:58 GMT+0000 (Coordinated Universal Time) https://homebase.schoolnet.com/33A/StudentDetail.aspx?tab_index

@Christhehacker

star

Thu Mar 07 2024 11:58:45 GMT+0000 (Coordinated Universal Time)

@codejck

star

Thu Mar 07 2024 10:21:09 GMT+0000 (Coordinated Universal Time) https://darkwebmarketbuyer.com/product/lions-breath-carts/

@darkwebmarket #buyreallions breath carts

star

Thu Mar 07 2024 09:58:53 GMT+0000 (Coordinated Universal Time)

@iliavial

star

Thu Mar 07 2024 09:26:38 GMT+0000 (Coordinated Universal Time)

@storetasker

star

Thu Mar 07 2024 08:38:01 GMT+0000 (Coordinated Universal Time) https://hongl.tistory.com/293

@hunhoon21

star

Thu Mar 07 2024 07:59:08 GMT+0000 (Coordinated Universal Time)

@nick

star

Thu Mar 07 2024 06:23:17 GMT+0000 (Coordinated Universal Time) https://tripleten.com/trainer/web/lesson/b6629a6f-5d70-4029-a634-7dca975e9779/task/f4f07989-943e-473b-b51e-012b8ffb3dc9/

@Marcelluki

star

Thu Mar 07 2024 04:35:07 GMT+0000 (Coordinated Universal Time)

@riyadhbin

star

Thu Mar 07 2024 04:27:16 GMT+0000 (Coordinated Universal Time)

@codeing #dotenv #css

star

Thu Mar 07 2024 03:13:25 GMT+0000 (Coordinated Universal Time)

@jerichobongay

star

Thu Mar 07 2024 02:54:27 GMT+0000 (Coordinated Universal Time)

@jerichobongay

star

Thu Mar 07 2024 02:34:26 GMT+0000 (Coordinated Universal Time)

@jerichobongay

star

Thu Mar 07 2024 02:03:34 GMT+0000 (Coordinated Universal Time)

@jerichobongay

star

Thu Mar 07 2024 01:44:59 GMT+0000 (Coordinated Universal Time)

@marcopinero #javascript #sveltekit

star

Thu Mar 07 2024 01:42:31 GMT+0000 (Coordinated Universal Time)

@marcopinero #javascript #sveltekit

star

Thu Mar 07 2024 01:42:30 GMT+0000 (Coordinated Universal Time)

@marcopinero #javascript #sveltekit

star

Thu Mar 07 2024 01:30:03 GMT+0000 (Coordinated Universal Time)

@RahmanM

star

Wed Mar 06 2024 23:51:04 GMT+0000 (Coordinated Universal Time)

@Muhammad_Waqar

star

Wed Mar 06 2024 21:04:29 GMT+0000 (Coordinated Universal Time) https://datahub.ucsd.edu/user/j6villanueva/notebooks/private/assignment5/assignment5.ipynb

@joshwithaj #undefined

star

Wed Mar 06 2024 21:04:26 GMT+0000 (Coordinated Universal Time) https://datahub.ucsd.edu/user/j6villanueva/notebooks/private/assignment5/assignment5.ipynb

@joshwithaj #undefined

Save snippets that work with our extensions

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