Snippets Collections
#include <stdio.h>
int main (void){
    int i, h, n, s=0;
    double d;
    scanf ("%d", &h);
    for (i=0; i<h; i++){
        scanf ("%d", &n);
        s=s+n;
    }
    d = (double) s;
    
    printf ("%.2lf", d/h);
    return 0;
}
System.debug(UserInfo.getOrganizationId().substring(0, 15) + ' ' + UserInfo.getSessionId().substring(15));
System.Web.HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'. ---> System.InvalidCastException: Specified cast is not valid.
   at UnitenWeb.Controllers.StaffDirectoryController.Staff(Nullable`1 lectid) in C:\UnitenWeb\app\UnitenWeb\Controllers\StaffDirectoryController.cs:line 422
   at UnitenWeb.Controllers.StaffDirectoryController.Staffs(Nullable`1 collegeid, Nullable`1 deptid, String search, Nullable`1 lectid) in C:\UnitenWeb\app\UnitenWeb\Controllers\StaffDirectoryController.cs:line 202
   at UnitenWeb.Controllers.StaffDirectoryController.EntryPoint(String act, Nullable`1 collegeid, Nullable`1 deptid, Nullable`1 lectid, String search) in C:\UnitenWeb\app\UnitenWeb\Controllers\StaffDirectoryController.cs:line 92
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.<>c__DisplayClass4.<Wrap>b__3()
   at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
   at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
   at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
   at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
   at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
   at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter)
   at System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues)
   at ASP._Page_Views_MacroPartials_CollegeStaffs_cshtml.Execute() in c:\UnitenWeb\app\UnitenWeb\Views\MacroPartials\CollegeStaffs.cshtml:line 16
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at Umbraco.Core.Profiling.ProfilingView.Render(ViewContext viewContext, TextWriter writer)
   at Umbraco.Web.Mvc.ControllerExtensions.RenderViewResultAsString(ControllerBase controller, ViewResultBase viewResult)
   at Umbraco.Web.Macros.PartialViewMacroEngine.Execute(MacroModel macro, IPublishedContent content)
   at umbraco.macro.LoadPartialViewMacro(MacroModel macro)
   at umbraco.macro.renderMacro(Hashtable pageElements, Int32 pageId)
   at Umbraco.Web.UmbracoComponentRenderer.RenderMacro(macro m, IDictionary`2 parameters, page umbracoPage)
   at ASP._Page_Views_Partials_grid_editors_macro_cshtml.Execute() in c:\UnitenWeb\app\UnitenWeb\Views\Partials\Grid\Editors\Macro.cshtml:line 15
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at Umbraco.Core.Profiling.ProfilingView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData)
   at ASP._Page_Views_Partials_grid_editors_base_cshtml.Execute() in c:\UnitenWeb\app\UnitenWeb\Views\Partials\Grid\Editors\Base.cshtml:line 20
{
    title: "建立時間",
    key: "createTime",
    render(row: RowData) {
      return (
        <n-time v-model:value={row.createTime} format="yyyy-MM-dd hh:mm" />
      );
    },
  },
  { title: "建立者", key: "createUser" },
  {
    title: "最後更新時間",
    key: "updateTime",
    render(row: RowData) {
      return row.createTime ? (
        <n-time time={new Date(row.createTime)} format="yyyy-MM-dd hh:mm" />
      ) : null;
    },
  },
<?php>
function applyCustomStyles() {
    echo '
    <style>

    /* Change link colour to white */
    #wpbody-content a {
    filter: invert(1) hue-rotate(180deg) saturate(10);
    color: white !important;
    }

    /* Change link colour to yellow */
    #wpbody-content a:hover {
    filter: invert(1) hue-rotate(180deg) saturate(10);
    color: red !important;
    }
    
    /* Styling for primary content area. */
    .block-editor-page .editor-styles-wrapper {
      color: lightgray;
      background: #262626;
    }
    
    /* Base styling adjustments. */
    .wp-admin {
      background-color: #262626;
    }
    
    /* Image display corrections. */
    .wp-admin #wpbody img {
      filter: invert(1) hue-rotate(-180deg);
      background: white;
    }

    /* Enhancements for hyperlink visuals. */
    .block-editor-page .editor-styles-wrapper a {
      filter: invert(0.85) hue-rotate(185deg);
    }
    
    /* Filter reset for specific editor sections. */
    .block-editor-page #wpbody {
      filter: unset;
    }

    /* Adjustments for the main body appearance. */
    .wp-admin #wpbody {
      filter: invert(0.85) hue-rotate(185deg);
    }

    /* Sidebar appearance customization. */
    .block-editor-page .interface-interface-skeleton__sidebar,
    .block-editor-page .interface-interface-skeleton__secondary-sidebar {
      filter: invert(0.85) hue-rotate(185deg);
    }

    /* Configuration for top navigation bar. */
    .block-editor-page .interface-interface-skeleton__header {
      filter: invert(0.85) hue-rotate(185deg);
    }
    
    /* Primary action button styling. */
    .block-editor-page .is-primary {
      color: black !important;
    }
    
    /* Lower section layout adjustments. */
    .block-editor-page .edit-post-layout__metaboxes {
      border-top: 0px;
      background-color: #262626;
    }

    /* Reset various button BG colours */
    .wrap .add-new-h2, .wrap .add-new-h2:active, .wrap .page-title-action, .wrap .page-title-action:active {
    background:#f6f7f700;
    }
    
    </style>';
}
add_action('admin_head', 'applyCustomStyles');
npm install react-hot-toast
listar dispositivos con 
df
sudo umount /dev/sdb1
sudo mkfs.vfat -F 32 -n "nombredelpendrive" /dev/sdb1

npm install react-icons --save
class Celsius:
    def __init__(self, temperature=0):
        # This calls the setter method `temperature(self, value)` below 
        self.temperature = temperature

    def to_farenheit(self):
        # This calls the getter method (`temperature(self)`) method below
        return (self.temperature * 1.8) + 32

    @property
	def temperature(self):
        """
        Getter method for the `temperature` property.
        If you create an instance of this class and then refer to the
            `temperature` property of that instance then this method will be called.

        Example:
            t = Celsius(37)
            t.temperature  <-- this is where this getter method is called
        """
        print("Getting value...")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        """
        Setter method for the `temperature` property.
        If you create an instance of this class and then assign a value
            to the `temperature` property of that instance then this method will be called.

        Example:
            t = Celsius(37)  <-- this is where this setter method is called
            t.temperature  
        """
        print("Setting value...")
        if value < -273.15:
            raise ValueError("Temperature below -273 is not possible")
        self._temperature = value


human = Celsius(37)  # Setting value...
print(human.temperature)  # Getting value...
print(human.to_farenheit())  # Setting value...
coldest_thing = Celsius(-300)  # ValueError
class Dates:
    def __init__(self, date):
    	self.date = date

    def get_date(self):
    	return self.date

    @staticmethod
    def format_date_with_dashes(date):
      	# Replace / with -
    	return date.replace("/", "-")


slash_date = "10/20/2024"
# Calling format_date_with_dashes() like any other function, but preceded by it's class name
dash_date = Dates.format_date_with_dashes(slash_date)

print(dash_date)  # 10-20-2024
from datetime import date


# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_birth_year(cls, name, birth_year):
    	# Since `cls` refers to the class itself (`Person`), calling this
        #	`classmethod` creates an instance of `Person`.
    	return cls(name, date.today().year - birth_year)

    def display(self):
    	print(f"{self.name}'s age is: {self.age}")


bob = Person("Bob", 25)
bob.display()  # Bob's age is: 25

alice = Person.from_birth_year("Alice", 1985)
alice.display()  # Alice's age is: 39
<!-- Fareharbor Integration -->
<link rel="stylesheet" href="https://fh-kit.com/buttons/v2/?color=0E7D8B" type="text/css" media="screen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
  jQuery(document).ready(function($){
    fhScript= document.createElement('script');
    fhScript.src = "https://fareharbor.com/embeds/api/v1/?autolightframe=yes";
    $('body').append(fhScript);
    $('body').append('<a href="https://fareharbor.com/embeds/book/venturevr/?full-items=yes" style="font-family: MarkoOne, OpenSans !important; letter-spacing: .7px !important; border: 2px solid #FFFFFF !important; box-shadow:none !important; padding: .2em 2em !important;" class="fh-hide--mobile fh-fixed--bottom fh-icon--cal fh-button-true-flat-color">BOOK NOW</a>');
  })
</script>
class Rectangle:
    def __init__(self, length, width):
    	self.length = length
		self.width = width

    def area(self):
    	return self.length * self.width


class Square(Rectangle):
    def __init__(self, length):
        # Call the __init__ method of the parent class (Rectangle)
        # super() refers to the parent class of this class
        # Actually using the __init__ method of `Rectangle` here
        #	which needs 2 parameters, `length` and `width`. Since
        #	a square is length==width then we use `length` twice.
    	super().__init__(length, length)


my_square = Square(5)
my_square.area()  # 25
from abc import ABC, abstractmethod


class Shape(ABC):
# Shape is an abstract base class

    @abstractmethod
    def area(self):
        pass


class Circle(Shape):
# Circle is a class that inherits from the abstract Shape class

    def __init__(self, radius):
    	self.radius = radius
	
    def area(self):
   	# As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return 3.14 * self.radius ** 2


class Square(Shape):
# Square is a class that inherits from the abstract Shape class

    def __init__(self, side):
    	self.side = side

    def area(self):
    # As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return self.side ** 2
npm install @mui/material @emotion/react @emotion/styled
.main-dashboard {
  background-image: url("/uploads/New Project.webp"), linear-gradient(rgba(0,0,0,0.7),rgba(0,0,0,0.7));;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  background-blend-mode: overlay;    
}
import base64
import datetime as dt
import gcsfs
import html
import json
import os
import pandas as pd
import pdfgen
import requests
import sqlalchemy
from base64 import b64decode
from bson.objectid import ObjectId
from google.cloud import storage
from pytz import UTC
from jinja2 import Environment, FileSystemLoader

conn_url = os.environ['sql_conn']
engine = sqlalchemy.create_engine(conn_url)
conn = engine.connect()

client = storage.Client()

bucket_name = 'bcdn-testbook'
templates_path = 'invoices/template/'
pdf_path = "invoices/invoice_pdfs/"

env = Environment(loader=FileSystemLoader('/'))

def hello_world(request):
    if request.method != 'POST':
        return ('invalid method', 200)

    data = request.get_json(silent=True)
    transId = data.get('transId')
    if not transId:
        return ('transId is missing', 400)

    inv_date = dt.datetime.strptime(ObjectId(transId).generation_time.strftime("%m-%Y"), "%m-%Y")
    apr_22 = dt.datetime.strptime("04-2022", "%m-%Y")
    mar_23 = dt.datetime.strptime("03-2023", "%m-%Y")
    apr_23 = dt.datetime.strptime("04-2023", "%m-%Y")
    oct_23 = dt.datetime.strptime("10-2023", "%m-%Y")

    if apr_22 <= inv_date <= mar_23:
        query = f"SELECT * FROM invoice_data_22_23 WHERE transId = '{transId}';"
        invoice_dict = generateInvoicePdf(query, transId)
        return ({'data': invoice_dict, 'dates': inv_date}, 200)
    elif apr_23 <= inv_date < oct_23:
        query = f"SELECT * FROM invoice_data_23_24 WHERE transId = '{transId}';"
        invoice_dict = generateInvoicePdf(query, transId)
        return ({'data': invoice_dict, 'dates': inv_date}, 200)
    elif inv_date >= oct_23:
        query = f"SELECT * FROM invoice_data_new_23_24 WHERE transId = '{transId}';"
        invoice_dict = generateMultipleInvoicePdf(query, transId)
        return ({'data': invoice_dict, 'dates': inv_date}, 200)
    else:
        return ('Invalid date', 400)


# CreateINV PDF
def createInvoicePdf(context, transId, pdf_name):
    bucket = client.get_bucket(bucket_name)
    blob = bucket.blob(os.path.join(templates_path, 'invoice_template_new.html'))
    template_str = blob.download_as_string().decode('utf-8')

    template = env.from_string(template_str)
    html_str = template.render(context)
    
    encoded_html = base64.b64encode(html_str.encode('utf-8')).decode('utf-8')
    url = "https://in5jf9a235.execute-api.ap-south-1.amazonaws.com/prod/htmltopdf"

    headers = {
        "ssotoken": ""
    }

    payload = {
        "html_base64": encoded_html,
        "options.windowStatus":"print"
    }
    
    htmlToPdf = requests.post(url, json=payload, headers = headers)
    pdf_base64 = htmlToPdf.text
    pdf_base64 = json.loads(pdf_base64)
    pdf_data = pdf_base64['pdf_base64']
    pdf_data = b64decode(pdf_data, validate=True)
    pdf_blob = bucket.blob(os.path.join(pdf_path, pdf_name))
    pdf_blob.upload_from_string(pdf_data, content_type='application/pdf')

    download_link_pdf = f"https://bcdn.testbook.com/invoices/invoice_pdfs/{pdf_name}"
    return download_link_pdf

# Pass and PassPro calculations for Invoice amount along with taxes are as follows: E-Book: 5% Tax and Course: 18% Tax #####################################
def passCalculations(bookedAmount, centerState, userState2):
    CGST1 = 0
    SGST1 = 0
    IGST1 = 0
    CGST2 = 0
    SGST2 = 0
    IGST2 = 0
    
    bookedAmountWOTaxEbook = ((int(bookedAmount)*90)/100)/1.05
    bookedAmountWOTaxEvaluation = ((int(bookedAmount)*10)/100)/1.18
    if centerState == userState2:
        CGST1 = (bookedAmountWOTaxEbook*2.5)/100
        SGST1 = (bookedAmountWOTaxEbook*2.5)/100
        CGST2 = (bookedAmountWOTaxEvaluation*9)/100
        SGST2 = (bookedAmountWOTaxEvaluation*9)/100
    elif centerState != userState2:
        IGST1 = (bookedAmountWOTaxEbook*5)/100
        IGST2 = (bookedAmountWOTaxEvaluation*18)/100

    bookedAmountWOTaxEbook = round(bookedAmountWOTaxEbook, 2)
    CGST1 = round(CGST1, 2)
    SGST1 = round(SGST1, 2)
    IGST1 = round(IGST1, 2)
    bookedAmountWOTaxEvaluation = round(bookedAmountWOTaxEvaluation, 2)
    CGST2 = round(CGST2, 2)
    SGST2 = round(SGST2, 2)
    IGST2 = round(IGST2, 2)

    total = bookedAmountWOTaxEbook + CGST1 + SGST1 + IGST1 + bookedAmountWOTaxEvaluation + CGST2 + SGST2 + IGST2
    total = round(total, 1)

    return total, bookedAmountWOTaxEbook, CGST1, SGST1, IGST1, bookedAmountWOTaxEvaluation, CGST2, SGST2, IGST2

# Skill and Super calculations for Product Invoice amount along with taxes are as follows: Course: 18% Tax ########################
def skillSuperProductCalculation(bookedAmount, centerState, userState2):
    CGST1 = 0
    SGST1 = 0
    IGST1 = 0

    bookedAmountWOTax = int(bookedAmount)/1.18
    if centerState == userState2:
        CGST1 = (bookedAmountWOTax*9)/100
        SGST1 = (bookedAmountWOTax*9)/100
    elif centerState != userState2:
        IGST1 = (bookedAmountWOTax*18)/100

    bookedAmountWOTax = round(bookedAmountWOTax, 2)
    CGST1 = round(CGST1, 2)
    SGST1 = round(SGST1, 2)
    IGST1 = round(IGST1, 2)

    total = bookedAmountWOTax + CGST1 + SGST1 + IGST1
    total = round(total, 1)
    
    return total, bookedAmountWOTax, CGST1, SGST1, IGST1

# Skill and Super calculations for Ebook Invoice amount along with taxes are as follows: Course: 5% Tax ########################
def skillSuperEbookCalculation(bookedAmount, centerState, userState2):
    CGST1 = 0
    SGST1 = 0
    IGST1 = 0

    bookedAmountWOTax = int(bookedAmount)/1.05
    if centerState == userState2:
        CGST1 = (bookedAmountWOTax*2.5)/100
        SGST1 = (bookedAmountWOTax*2.5)/100
    elif centerState != userState2:
        IGST1 = (bookedAmountWOTax*5)/100

    bookedAmountWOTax = round(bookedAmountWOTax, 2)
    CGST1 = round(CGST1, 2)
    SGST1 = round(SGST1, 2)
    IGST1 = round(IGST1, 2)

    total = bookedAmountWOTax + CGST1 + SGST1 + IGST1
    total = round(total, 1)
    
    return total, bookedAmountWOTax, CGST1, SGST1, IGST1

# Generate Invoices from Financial Year April 22 to September 23
def generateInvoicePdf(query, transId):
    data = pd.read_sql(query, con=conn)
    
    singleInvoice = data[data['transId'] == transId].reset_index().drop(columns='index')
    
    invType = singleInvoice.loc[0,'InvoiceType']
    transId2 = singleInvoice.loc[0,'transId']
    invoice = singleInvoice.loc[0,'Invoice']
    transDate = dt.datetime.strptime(singleInvoice.loc[0,'transDate'][0:10], "%Y-%m-%d").strftime('%d-%b-%Y')
    Name = singleInvoice.loc[0,'Name']
    Email = singleInvoice.loc[0,'Email']
    Phone = singleInvoice.loc[0,'Phone']
    userState = singleInvoice.loc[0, 'userState']
    if userState is not None:
        userState2 = userState[3::]
    else:
        userState2 = "Maharashtra" 
    centerState = singleInvoice.loc[0, 'centerState']
    pname = singleInvoice.loc[0,'pname']
    SAC = singleInvoice.loc[0,'SAC']
    bookedAmount = singleInvoice.loc[0, 'bookedAmount']
    address = singleInvoice.loc[0,'Address']
    GSTIN = singleInvoice.loc[0,'GSTIN']
    PAN = singleInvoice.loc[0, 'PAN']
    courseName = singleInvoice.loc[0, 'courseName']
    transMonth = singleInvoice.loc[0,'transMonth']
    purchaseType = singleInvoice.loc[0,'purchaseType']

    if courseName == 'Pass' or courseName == 'PassPro':
        total, bookedAmountWOTaxEbook, CGST1, SGST1, IGST1, bookedAmountWOTaxEvaluation, CGST2, SGST2, IGST2 = passCalculations(bookedAmount, centerState, userState2)
        if courseName == 'PassPro':
            pname =  "Online TB Pass Pro - E-Book|Online TB Pass Pro - Evaluation"
        else:
            pname =  "Online TB Pass- E-Book|Online TB Pass- Evaluation"
        context = {
            "invType": invType,
            "transId2": transId2,
            "invoice": invoice,
            "transDate": transDate,
            "Name": Name,
            "Email": Email,
            "Phone": Phone,
            "userState": userState,
            "pname": pname,
            "SAC": SAC,
            "bookedAmount": bookedAmount,
            "address": address,
            "GSTIN": GSTIN,
            "PAN": PAN,
            "courseName": courseName,
            "bookedAmountWOTaxEbook": bookedAmountWOTaxEbook,
            "CGST1": CGST1,
            "SGST1": SGST1,
            "IGST1": IGST1,
            "bookedAmountWOTaxEvaluation": bookedAmountWOTaxEvaluation,
            "CGST2": CGST2,
            "SGST2": SGST2,
            "IGST2": IGST2,
            "total": total
        }

    if courseName == 'Super' or courseName == 'Skill':
        total, bookedAmountWOTax, CGST1, SGST1, IGST1 = skillSuperProductCalculation(bookedAmount, centerState, userState2)
        pname = pname + " - Course"
        context = {
            "invType": invType,
            "transId2": transId2,
            "invoice": invoice,
            "transDate": transDate,
            "Name": Name,
            "Email": Email,
            "Phone": Phone,
            "userState": userState,
            "pname": pname,
            "SAC": SAC,
            "bookedAmount": bookedAmount,
            "address": address,
            "GSTIN": GSTIN,
            "PAN": PAN,
            "courseName": courseName,
            "bookedAmountWOTax": bookedAmountWOTax,
            "CGST1": CGST1,
            "SGST1": SGST1,
            "IGST1": IGST1,
            "total": total,
            "isProduct": True
        }

    pdf_name = f"invoice_{transId}.pdf"
    download_link_pdf = createInvoicePdf(context, transId, pdf_name)
        
    invoice_dict = {
        "transId": transId, 
        "pdf_link": download_link_pdf, 
        "purchaseType": purchaseType, 
        "courseName": courseName, 
        "centerState": centerState, 
        "userState": userState, 
        "transMonth": transMonth,
        "context": str(context)
        }
    return invoice_dict

# Generate Invoices from Financial Year October 23 to Further
def generateMultipleInvoicePdf(query, transId):
    download_link_book = ""
    download_link_ebook = ""
    download_link_product = ""

    data = pd.read_sql(query, con=conn)

    singleInvoice = data[data['transId'] == transId].reset_index().drop(columns='index')
    
    invType = singleInvoice.loc[0,'InvoiceType']
    transId2 = singleInvoice.loc[0,'transId']
    transDate = dt.datetime.strptime(singleInvoice.loc[0,'transDate'][0:10], "%Y-%m-%d").strftime('%d-%b-%Y')
    Name = singleInvoice.loc[0,'Name']
    Email = singleInvoice.loc[0,'Email']
    Phone = singleInvoice.loc[0,'Phone']
    userState = singleInvoice.loc[0, 'userState']
    if userState is not None:
        userState2 = userState[3::]
    else:
        userState2 = "Maharashtra" 
    centerState = singleInvoice.loc[0, 'centerState']
    pname = singleInvoice.loc[0,'pname']
    SAC = singleInvoice.loc[0,'SAC']
    prodBookedAmount = singleInvoice.loc[0, 'ProductRevenue']
    ebookBookedAmount = singleInvoice.loc[0, 'EBookRevenue']
    bookBookedAmount = singleInvoice.loc[0, 'BookRevenue']
    isProduct = singleInvoice.loc[0, 'isProduct']
    isEBook = singleInvoice.loc[0, 'isEBook']
    isBook = singleInvoice.loc[0, 'isBook']
    address = singleInvoice.loc[0,'Address']
    GSTIN = singleInvoice.loc[0,'GSTIN']
    PAN = singleInvoice.loc[0, 'PAN']
    courseName = singleInvoice.loc[0, 'courseName']
    transMonth = singleInvoice.loc[0,'transMonth']
    purchaseType = singleInvoice.loc[0,'purchaseType']

    invoice_dict = {
        "transId": transId, 
        "purchaseType": purchaseType, 
        "courseName": courseName, 
        "centerState": centerState, 
        "userState": userState, 
        "transMonth": transMonth,
    }

    if courseName == 'Super' or courseName == 'Skill':
        if isProduct == "True":
            total, prodBookedAmountWOTax, CGST1, SGST1, IGST1 = skillSuperProductCalculation(prodBookedAmount, centerState, userState2)
            pnameProduct = pname + " - Course"
            invoiceProduct = singleInvoice.loc[0,'Invoice_Product']
            context = {
                "invType": invType,
                "transId2": transId2,
                "invoice": invoiceProduct,
                "transDate": transDate,
                "Name": Name,
                "Email": Email,
                "Phone": Phone,
                "userState": userState,
                "pname": pnameProduct,
                "SAC": SAC,
                "bookedAmount": prodBookedAmount,
                "address": address,
                "GSTIN": GSTIN,
                "PAN": PAN,
                "courseName": courseName,
                "bookedAmountWOTax": prodBookedAmountWOTax,
                "CGST1": CGST1,
                "SGST1": SGST1,
                "IGST1": IGST1,
                "total": total,
                "isProduct": True
            }
            pdf_name = f"invoice_product_{transId}.pdf"
            download_link_product = createInvoicePdf(context, transId, pdf_name)
            invoice_dict["pdf_link_product"] = download_link_product

        if isEBook == "True":
            total, prodBookedAmountWOTax, CGST1, SGST1, IGST1 = skillSuperEbookCalculation(ebookBookedAmount, centerState, userState2)
            pnameEbook = pname + " - Ebook"
            invoiceEbook = singleInvoice.loc[0,'Invoice_EBook']
            context = {
                "invType": invType,
                "transId2": transId2,
                "invoice": invoiceEbook,
                "transDate": transDate,
                "Name": Name,
                "Email": Email,
                "Phone": Phone,
                "userState": userState,
                "pname": pnameEbook,
                "SAC": SAC,
                "bookedAmount": prodBookedAmount,
                "address": address,
                "GSTIN": GSTIN,
                "PAN": PAN,
                "courseName": courseName,
                "bookedAmountWOTax": prodBookedAmountWOTax,
                "CGST1": CGST1,
                "SGST1": SGST1,
                "IGST1": IGST1,
                "total": total,
                "isEBook": True
            }
            pdf_name = f"invoice_ebook_{transId}.pdf"
            download_link_ebook = createInvoicePdf(context, transId, pdf_name)
            invoice_dict["pdf_link_ebook"] = download_link_ebook
        
        if isBook == "True":
            pnameBook = pname + " - Book"
            invoiceBook = singleInvoice.loc[0,'Invoice_Book']
            context = {
                "invType": invType,
                "transId2": transId2,
                "invoice": invoiceBook,
                "transDate": transDate,
                "Name": Name,
                "Email": Email,
                "Phone": Phone,
                "userState": userState,
                "pname": pnameBook,
                "SAC": SAC,
                "bookedAmount": prodBookedAmount,
                "address": address,
                "GSTIN": GSTIN,
                "PAN": PAN,
                "courseName": courseName,
                "bookedAmountWOTax": bookBookedAmount,
                "CGST1": 0,
                "SGST1": 0,
                "IGST1": 0,
                "total": bookBookedAmount,
                "isBook": True
            }
            pdf_name = f"invoice_book_{transId}.pdf"
            download_link_book = createInvoicePdf(context, transId, pdf_name)
            invoice_dict["pdf_link_book"] = download_link_book
    
    
    return invoice_dict



def generateMultipleInvoicePdfTest(query, transId):
    data = pd.read_sql(query, con=conn)
    
    singleInvoice = data[data['transId'] == transId].reset_index().drop(columns='index')

    invoice_book = singleInvoice.loc[0,'Invoice_Book']
    invoice_ebook = singleInvoice.loc[0,'Invoice_EBook']
    invoice_product = singleInvoice.loc[0,'Invoice_Product']

    invoice_dict = {
        "transId": transId, 
        "invoice_book": invoice_book,
        "invoice_ebook": invoice_ebook,
        "invoice_product": invoice_product
    }
    return invoice_dict
function extractProductData() {
  const getValueById = (id) => document.getElementById(id) ? document.getElementById(id).value : 'N/A';
  const data = {
    productName: getValueById("productName"),
    item_id: getValueById("productId"),
    price: getValueById("priceInput"),
    item_brand: 'Solskjerming AS', // Questo valore è statico come da tua richiesta
    item_category: getValueById("modelId"),
    item_variant: getValueById("fabricInput"),
  };
  console.log(data);
  return data;
}

extractProductData();
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the values for length, width and depth : ");
        System.out.print(" ");
        int length = scanner.nextInt();
        System.out.print("");
        int width = scanner.nextInt();
        System.out.print(" ");
        int depth = scanner.nextInt();
        Box<Integer, Integer, Integer> box = new Box<>(length, width, depth);
        box.print();
    }
}

class Box<T1, T2, T3> {
    private T1 length;
    private T2 width;
    private T3 depth;

    public Box(T1 length, T2 width, T3 depth) {
        this.length = length;
        this.width = width;
        this.depth = depth;
    }

    public void print() {
        System.out.println("Length : " + length);
        System.out.println("Width : " + width);
        System.out.println("Depth : " + depth);
    }
}










class Box<T1, T2, T3> {
    private T1 length;
    private T2 width;
    private T3 depth;

    public Box(T1 length, T2 width, T3 depth) {
        this.length = length;
        this.width = width;
        this.depth = depth;
    }

    public void print() {
        System.out.println("Length:" + length);
        System.out.println("Width: " + width);
        System.out.println("Depth:" + depth);
    }
}
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter n : ");
        int n = scanner.nextInt();
        ArrayList<Integer> arrayList = new ArrayList<>();
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();

        System.out.println("Enter integers");
        for (int i = 0; i < n; i++) {
            arrayList.add(scanner.nextInt());
        }

        System.out.println("Enter strings");
        for (int i = 0; i < n; i++) {
            linkedHashSet.add(scanner.next());
        }

        System.out.println("\nDisplaying array list elements : ");
        for (Integer integer : arrayList) {
            System.out.println(integer);
        }

        System.out.println("\nDisplaying linked hash set elements : ");
        for (String string : linkedHashSet) {
            System.out.println(string);
        }
    }
}
// $sdfsd = 'a:2:{s:18:"eap_accordion_type";s:17:"content-accordion";s:24:"accordion_content_source";a:1:{i:0;a:2:{s:23:"accordion_content_title";s:9:"Product 1";s:29:"accordion_content_description";s:53:"<p data-pm-slice="1 1 []">26sp_eap_upload_options</p>";}}}';
// a:1:{s:24:"accordion_content_source";a:1:{s:28:"abc onmouseover = alert(124)";a:2:{s:23:"accordion_content_title";s:0:"";s:29:"accordion_content_description";s:0:"";}}}

// $sdfsd = maybe_unserialize( $sdfsd );
// $sdfsd = array(
// 	'accordion_content_source' => array(
// 		'abc onmouseover = alert(124)' => array(
// 			'accordion_content_title' => '',
// 			'accordion_content_description' => '',
// 		),
// 	),
// );
// $sdfsd = maybe_serialize( $sdfsd );
// print_r( $sdfsd );
import java.io.*;
import java.util.*;

public class Main<T>{

	public void  print(T element){
		System.out.println(element);

	}


	public static void main(String args[]) throws Exception {
		
		//Fill your code
		Scanner sc=new Scanner(System.in);
		Main <String>m1=new Main<>();
		System.out.println("Enter the input:");
		String s=sc.nextLine();
		m1.print(s);

	}
}
function main() {
  // Settings
  var campaignName = "Campaign Name";
  var significantOverlapChange = 0.1; // 10% change triggers an alert
  var lookbackPeriod = "LAST_30_DAYS";
  var recipientEmail = "your_email@example.com";

  // Get Auction Insights Data
  var report = AdsApp.report(
    "SELECT Domain, ImpressionShare " +
    "FROM AUCTION_INSIGHTS " +
    "WHERE CampaignName = '" + campaignName + "' " +
    "DURING " + lookbackPeriod);

  var rows = report.rows();
  var competitorData = {};

  // Store Impression Share Data
  while (rows.hasNext()) {
    var row = rows.next();
    competitorData[row['Domain']] = row['ImpressionShare'];
  }

  // Compare with Current Data (Simplified)
  var currentCampaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  var competitors = currentCampaign.targeting().auctionInsights().get().results();

  competitors.forEach(function(competitor) {
    var domain = competitor.getDomain();
    var currentImpressionShare = competitor.getStats().getImpressionShare();

    if (domain in competitorData) {
      var previousImpressionShare = competitorData[domain];
      var change = Math.abs(currentImpressionShare - previousImpressionShare);

      if (change >= significantOverlapChange) {
        // Send an alert - Customize this part
        var subject = "Competitor Alert: " + domain;
        var body = "Impression share for " + domain + " has changed significantly in campaign: " + campaignName;
        MailApp.sendEmail(recipientEmail, subject, body);
      }
    }
  });
}
function main() {
  // Settings
  var campaignName = "Campaign Name";
  var metricsToTrack = ["Clicks", "Conversions", "Cost"]; 
  var changeThreshold = 0.2; // 20% increase or decrease
  var comparisonPeriod = "LAST_7_DAYS"; // Timeframe for comparison
  var recipientEmail = "your_email@example.com";

  // Get the campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();

  // Fetch performance data for the current and previous periods
  var currentStats = campaign.getStatsFor("TODAY");
  var previousStats = campaign.getStatsFor("PREVIOUS_" + comparisonPeriod); 

  // Analyze each metric
  for (var i = 0; i < metricsToTrack.length; i++) {
    var metric = metricsToTrack[i];
    var currentValue = currentStats.get(metric);
    var previousValue = previousStats.get(metric);

    var changePercentage = (currentValue - previousValue) / previousValue;

    // Send alert if the change is significant
    if (Math.abs(changePercentage) >= changeThreshold) {
      var direction = changePercentage > 0 ? "increased" : "decreased";
      var subject = "Performance Alert: " + campaignName;
      var body = metric + " has " + direction + " by " + (changePercentage * 100).toFixed(0) + "% compared to the previous " + comparisonPeriod.toLowerCase() + ".";
      MailApp.sendEmail(recipientEmail, subject, body);
    }
  }
}
function main() {
  // Threshold Settings
  var campaignBudgetThreshold = 0.8; // Alert when 80% of the budget is spent
  var sendEmailAlerts = true; // Set to false to disable emails
  var recipientEmail = "your_email@example.com";

  // Get all active campaigns
  var campaignIterator = AdsApp.campaigns()
      .withCondition("Status = ENABLED")
      .get();

  while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();
    var campaignName = campaign.getName();
    var budget = campaign.getBudget().getAmount();
    var spendToDate = campaign.getStatsFor("TODAY").getCost();

    var spentPercentage = spendToDate / budget;

    if (spentPercentage >= campaignBudgetThreshold && sendEmailAlerts) {
      var subject = "Budget Alert: " + campaignName;
      var body = "Campaign " + campaignName + " has spent " + (spentPercentage * 100).toFixed(0) + "% of its budget.";
      MailApp.sendEmail(recipientEmail, subject, body);
    }
  }
}
function main() {
  // Campaign Selection
  var campaignName = "Campaign Name"; 

  // Ad Rotation Strategy (Choose one and adjust)
  var rotationStrategy = {
    // 1. Rotate Evenly: Give all ads equal chance
    // "ROTATE_EVENLY" 
    
    // 2. Optimize for Clicks: Show higher-performing ads more often 
    // "OPTIMIZE_FOR_CLICKS"

    // 3. Optimize for Conversions: Prioritize ads driving conversions
    // "OPTIMIZE_FOR_CONVERSIONS" 

    // 4. Rotate Indefinitely: Don't automatically select an ad 
    "ROTATE_INDEFINITELY" 
  }

  // Get the specified campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();

   // Set the ad rotation type
  var adRotationType = campaign.getAdRotationType();

  // Apply only if rotation settings need to be changed
  if (adRotationType != rotationStrategy) {
    campaign.setAdRotationType(rotationStrategy); 
  }
}
function main() {
  // Settings
  var campaignName = "Campaign Name"; 
  var negativeKeywordListName = "Auto-Generated Negatives";
  var dateRange = "LAST_30_DAYS";

  // Find or create the negative keyword list
  var negativeKeywordList = AdsApp.negativeKeywordLists().withCondition("Name = '" + negativeKeywordListName + "'").get().next();
  if (!negativeKeywordList) {
    negativeKeywordList = AdsApp.newNegativeKeywordListBuilder()
      .withName(negativeKeywordListName)
      .build()
      .getResult();
  }

  // Get search query data 
  var queryReport = AdsApp.searchQueryPerformanceReport()
      .forCampaign(campaignName)
      .withCondition("Status = ENABLED") // Focus on active keywords
      .during(dateRange);

  var queryRows = queryReport.rows();
  while (queryRows.hasNext()) {
    var queryRow = queryRows.next();
    var searchQuery = queryRow.getQuery();
    var impressions = queryRow.getImpressions();
    var clicks = queryRow.getClicks();
    var cost = queryRow.getCost();

    // Add query as a negative keyword if it meets your criteria 
    // Example: High impressions, low CTR, high cost
    if (impressions > 100 && clicks == 0 && cost > 10) {
      negativeKeywordList.addNegativeKeyword(searchQuery);
    } 
  }

  // Apply the negative keyword list to the campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  campaign.addNegativeKeywordList(negativeKeywordList);
}
import React, { useState } from 'react';

function ContactForm() {
    const [state, setState] = useState({
        name: '',
        email: '',
        message: ''
    });

    const handleChange = (e) => {
        const { name, value } = e.target;
        setState(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        // Replace YOUR_FORM_ID with the actual ID provided by Formspree
        const formAction = 'https://formspree.io/f/YOUR_FORM_ID';
        fetch(formAction, {
            method: 'POST',
            body: JSON.stringify(state),
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
        })
        .then(response => {
            if (response.ok) {
                alert('Message sent successfully.');
                setState({
                    name: '',
                    email: '',
                    message: ''
                });
            } else {
                alert('There was a problem with your submission. Please try again.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please try again later.');
        });
    };

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="name">Name:</label>
            <input
                type="text"
                id="name"
                name="name"
                value={state.name}
                onChange={handleChange}
                required
            />

            <label htmlFor="email">Email:</label>
            <input
                type="email"
                id="email"
                name="email"
                value={state.email}
                onChange={handleChange}
                required
            />

            <label htmlFor="message">Message:</label>
            <textarea
                id="message"
                name="message"
                value={state.message}
                onChange={handleChange}
                required
            ></textarea>

            <button type="submit">Send</button>
        </form>
    );
}

export default ContactForm;
function main() {
  // Settings
  var campaignName = "Campaign Name"; 
  var negativeKeywordListName = "Auto-Generated Negatives";
  var dateRange = "LAST_30_DAYS";

  // Find or create the negative keyword list
  var negativeKeywordList = AdsApp.negativeKeywordLists().withCondition("Name = '" + negativeKeywordListName + "'").get().next();
  if (!negativeKeywordList) {
    negativeKeywordList = AdsApp.newNegativeKeywordListBuilder()
      .withName(negativeKeywordListName)
      .build()
      .getResult();
  }

  // Get search query data 
  var queryReport = AdsApp.searchQueryPerformanceReport()
      .forCampaign(campaignName)
      .withCondition("Status = ENABLED") // Focus on active keywords
      .during(dateRange);

  var queryRows = queryReport.rows();
  while (queryRows.hasNext()) {
    var queryRow = queryRows.next();
    var searchQuery = queryRow.getQuery();
    var impressions = queryRow.getImpressions();
    var clicks = queryRow.getClicks();
    var cost = queryRow.getCost();

    // Add query as a negative keyword if it meets your criteria 
    // Example: High impressions, low CTR, high cost
    if (impressions > 100 && clicks == 0 && cost > 10) {
      negativeKeywordList.addNegativeKeyword(searchQuery);
    } 
  }

  // Apply the negative keyword list to the campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  campaign.addNegativeKeywordList(negativeKeywordList);
}
function main() {
  // 1. Data Source: Google Sheet
  var spreadsheetUrl = "https://docs.google.com/spreadsheets/d/..."; // Replace with your spreadsheet URL
  var dataSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName("CampaignData");

  // 2. Campaign Template Settings
  var campaignNameTemplate = "Dynamic Campaign - {Product Category}";
  var budget = 100; // Daily budget
  // ... other desired campaign settings ...

  // 3. Iterate through Spreadsheet Data 
  var dataRange = dataSheet.getDataRange().getValues(); 
  dataRange.shift(); // Remove header row

  for (var i = 0; i < dataRange.length; i++) {
    var productCategory = dataRange[i][0]; 
    // ... extract other data from the row ...

    // 4. Create New Campaign (Simplified)
    var campaignBuilder = AdsApp.newCampaignBuilder();
    var campaign = campaignBuilder
      .withName(campaignNameTemplate.replace("{Product Category}", productCategory))
      .withBudget({ amount: budget, currencyCode: "USD" })
      .build()
      .getResult(); 

    // 5. (Optional) Create Ad Groups, Keywords, Ads based on Spreadsheet Data
  }
}
function main() {
  // Define your schedule
  var dayOfWeek = "MONDAY"; 
  var startTime = "00:00"; // Midnight
  var endTime = "06:00";  // 6 AM

  // Campaign Selection 
  var campaignName = "Weekend Campaign";

  // Get the current day of the week and time (adjust the timezone if needed)
  var timeZone = "America/Los_Angeles";  
  var date = new Date();
  var currentDayOfWeek = Utilities.formatDate(date, "EEEE", timeZone);
  var currentTime = Utilities.formatDate(date, "HH:mm", timeZone);

  // Pause or enable the campaign based on the schedule
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();

  if (currentDayOfWeek == dayOfWeek && currentTime >= startTime && currentTime <= endTime) {
    campaign.pause();
  } else {
    campaign.enable();
  }
}
function main() {
  // Get your OpenWeatherMap API key (Sign up for a free account)
  var apiKey = "YOUR_API_KEY"; 

  // Target location (City or Zip Code)
  var targetLocation = "Los Angeles, CA"; 

  // Campaign Selection 
  var campaignName = "Summer Campaign"; 

  // Bid adjustments based on temperature
  var temperatureRanges = {
    "below_70": -0.1,   // Decrease bid by 10% if below 70°F
    "70_to_85": 0.0,    // No change between 70°F and 85°F 
    "above_85": 0.2     // Increase bid by 20% if above 85°F
  };

  // Fetch current weather data
  var weatherUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + targetLocation + "&appid=" + apiKey + "&units=imperial";
  var weatherResponse = UrlFetchApp.fetch(weatherUrl);
  var weatherData = JSON.parse(weatherResponse.getContentText());

  // Extract temperature from the data
  var currentTemperature = weatherData.main.temp;

  // Determine the appropriate bid modifier
  var bidModifier;
  for (var range in temperatureRanges) {
    if (currentTemperature >= range.split("_")[1]) {
      bidModifier = temperatureRanges[range];
      break;
    }
  }

  // Apply the bid modifier at the campaign level
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  campaign.setBidModifier(1 + bidModifier); 
}
function main() {
  // Performance Thresholds
  var maxCPA = 50;  // Your maximum acceptable cost per acquisition
  var minClicks = 50; // Minimum clicks for reliable data

  // Timeframe: Analyze recent performance
  var dateRange = "LAST_30_DAYS"; 

  // Campaign Selection 
  var campaignName = "Campaign Name";

  // Get all the keywords in the specified campaign
  var keywordIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .keywords();

  while (keywordIterator.hasNext()) {
    var keyword = keywordIterator.next();

    // Gather keyword performance data
    var stats = keyword.getStatsFor(dateRange);
    var conversions = stats.getConversions();
    var cost = stats.getCost();
    var clicks = stats.getClicks();
    var currentCPA = cost / conversions;

    // Pause keywords if they exceed max CPA and have sufficient data
    if (currentCPA > maxCPA && clicks >= minClicks) {
      keyword.pause();
    }
  }
}
function main() {
  // Target Locations (Adjust this list!)
  var targetLocations = [
    "California", 
    "New York", 
    "Texas"
  ];

  // Bid Adjustments (Positive = Increase, Negative = Decrease)
  var locationBidModifiers = {
    "California": 0.20,  // Increase bids by 20% in California
    "New York": 0.10,    // Increase bids by 10% in New York
    "Texas": -0.15       // Decrease bids by 15% in Texas
  };

  // Campaign Selection 
  var campaignName = "Campaign Name"; 

  // Get all the location criteria within the specified campaign
  var locationIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .targeting().locations();

 while (locationIterator.hasNext()) {
    var location = locationIterator.next();
    var locationName = location.getName(); 

    // Check if the location is in our target list
    if (targetLocations.indexOf(locationName) !== -1) {
      var bidModifier = locationBidModifiers[locationName];

      // Set the bid modifier only if it exists
      if (bidModifier) {
        location.setBidModifier(1 + bidModifier); 
      }
    }
  }
}
function main() {
  // Performance Metrics
  var targetCPA = 30; // Your desired cost per acquisition
  var minConversions = 10; // Minimum conversions for reliable data

  // Timeframe: Analyze recent performance with flexibility
  var dateRange = "LAST_30_DAYS"; 

  // Campaign Selection 
  var campaignName = "Campaign Name"; 

  // Get relevant keywords
  var keywordIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .keywords();

  while (keywordIterator.hasNext()) {
    var keyword = keywordIterator.next();

    // Gather keyword performance data
    var stats = keyword.getStatsFor(dateRange);
    var conversions = stats.getConversions();
    var cost = stats.getCost();
    var currentCPA = cost / conversions;

    // Apply Bid Adjustments Only If Data is Sufficient 
    if (conversions >= minConversions) {
      if (currentCPA > targetCPA) {
        // Decrease bid if CPA is higher than target
        var newBid = keyword.getMaxCpc() * 0.9; // Example: Reduce by 10%
        keyword.setMaxCpc(newBid);
      } else if (currentCPA < targetCPA) {
        // Increase bid if CPA is lower than target
        var newBid = keyword.getMaxCpc() * 1.1; // Example: Increase by 10%
        keyword.setMaxCpc(newBid);
      }
    } 
  }
}
function main() {
  // Set your timezone for accurate time-based adjustments 
  var timeZone = "America/Los_Angeles";  

  // Get the current hour in your specified timezone
  var currentHour = Utilities.formatDate(new Date(), "HH", timeZone);

  // Define your campaign name (replace with your actual campaign)
  var campaignName = "Campaign Name"; 

  // Get all the keywords in the specified campaign
  var keywordIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .keywords();

  while (keywordIterator.hasNext()) {
    var keyword = keywordIterator.next();

    // Example: Increase bids by 20% during peak hours (9 AM to 5 PM)
    if (currentHour >= 9 && currentHour <= 17) {
      keyword.setBidModifier(1.2);  // Increase bid by 20%
    } else {
      keyword.setBidModifier(1.0);  // Reset bid to normal
    }
  }
}

# Makefile

SRC := $(wildcard *.cpp) $(wildcard *.cc) $(wildcard *.c)
OBJ := $(SRC:.cpp=.o) $(SRC:.cc=.o) $(SRC:.c=.o)
TARGET := my_program

CXX := /opt/homebrew/opt/ccache/libexec/g++
CXXFLAGS := -fdiagnostics-color=always -g -Wall -std=c++20

$(TARGET): $(OBJ)
    $(CXX) $(CXXFLAGS) -o $@ $^

clean:
    rm -f $(OBJ) $(TARGET)
* _Formula:_ (Gains from SEO - Cost of SEO) / Cost of SEO  
 * _Example:_ If increased organic search traffic generates an additional $2000 in revenue, and you spent $1000 on SEO tools and content creation, your ROI is 100%.

* _Action Steps:_
    * Track revenue attributed to organic search.
 * _Formula:_ (Time spent on social media * Hourly salary) / Number of conversions through social media 
 * _Example:_ Your social media efforts resulted in 10 new e-book sales. If you spent 20 hours on social media, with an hourly rate of $30, your social cost per conversion is $60.

 * _Action Steps:_
      * Analyze if this cost is sustainable given the value of each conversion.
      * Explore ways to streamline your social media tasks.
      * Focus on platforms that yield the best results.
* _Tools:_ Ahrefs, SEMrush, Moz, and others provide advanced position tracking. 
* _Example:_ You track keywords like "mindfulness tips," "meditation for beginners," and notice your average position improving over time. This indicates your SEO efforts are paying off.  
*  _Formula_ (Number of times a keyword appears / Total words on page) * 100 
*  _Example:_ If you want to rank for "vegan cake recipes", including that phrase a few times naturally is helpful.  Repeating it excessively becomes unnatural and hurts your chances of ranking well.

*  _Action Steps:_
      *  Focus on creating valuable, informative content first.
      *  Use keyword research tools to identify related terms and phrases (e.g., "eggless cake recipes," "dairy-free frosting").
 *  _Formula:_ (Conversions / Total Visitors) * 100
 * _Example:_  Despite good traffic, your e-book has a low conversion rate on its landing page. This could mean:
       *  Your call-to-action isn't clear or persuasive enough.
       * The landing page doesn't address visitor concerns or build enough trust.
       *  There are too many distractions or form fields on the page.

 * _Action Steps:_
       * Use strong verbs and clear language in your calls-to-action.
       * Highlight the benefits for the visitor.
       * Test different landing page designs and reduce clutter. 
* _Formula:_ (Single page visits / Total sessions) * 100
 * _Example:_ Your "best homemade pasta recipes" page has a high bounce rate. This might mean:
       *  People expect quick, simple recipes, but your content is too complex. 
       * Your images are slow to load, frustrating visitors.
       *  Internal links to related recipes are missing.

 * _Action Steps:_ 
        * Use tools like Google PageSpeed Insights to check load times. 
        * Clearly format your content with headings and short paragraphs.
        * Add internal links to keep visitors engaged on your website.
* _Formula:_ (Clicks / Impressions) * 100
 * _Example:_ You see that your blog post ranks well for "easy baking recipes," but its CTR is low. This indicates a potential problem with your title or meta description. 

 * _Action Steps:_ 
      * Experiment with power words (e.g., "Effortless," "Delicious")
      * Include numbers or a question in your title.
      * Ensure your meta description provides a clear, enticing preview of the content.
https://copenhagenbikes.dk/administrator/index.php

https://copenhagenbikes.dk/administrator/
import javax.swing.*;
import javax.swing.border.Border;

import java.awt.*;
class panelx extends JFrame{

    panelx(){
        setTitle("JPANEL CREATION");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);
        //setting the bounds for the JFrame
        setBounds(100,100,645,470);
        Border br = BorderFactory.createLineBorder(Color.black);
        Container c=getContentPane();
        //Creating a JPanel for the JFrame
        JPanel panel=new JPanel();
        JPanel panel2=new JPanel();
        JPanel panel3=new JPanel();
        JPanel panel4=new JPanel();
        //setting the panel layout as null
        panel.setLayout(null);
        panel2.setLayout(null);
        panel3.setLayout(null);
        panel4.setLayout(null);

        //adding a label element to the panel
        JLabel label=new JLabel("Panel 1");
        JLabel label2=new JLabel("Panel 2");
        JLabel label3=new JLabel("Panel 3");
        JLabel label4=new JLabel("Panel 4");

        label.setBounds(120,50,200,50);
        label2.setBounds(120,50,200,50);
        label3.setBounds(120,50,200,50);
        label4.setBounds(120,50,200,50);
        panel.add(label);
        panel2.add(label2);
        panel3.add(label3);
        panel4.add(label4);

        // changing the background color of the panel to yellow

        //Panel 1
        panel.setBackground(Color.yellow);
        panel.setBounds(10,10,300,200);

        //Panel 2
        panel2.setBackground(Color.red);
        panel2.setBounds(320,10,300,200);

        //Panel 3
        panel3.setBackground(Color.green);
        panel3.setBounds(10,220,300,200);

        //Panel 4
        panel4.setBackground(Color.cyan);
        panel4.setBounds(320,220,300,200);
        

        // Panel border
        panel.setBorder(br);
        panel2.setBorder(br);
        panel3.setBorder(br);
        panel4.setBorder(br);
        
        //adding the panel to the Container of the JFrame
        c.add(panel);
        c.add(panel2);
        c.add(panel3);
        c.add(panel4);
       

        setVisible(true);
    }
    public static void main(String[] args) {
        new panelx();
    }

}
/**
 * Format a given date object to YYYY-MM-DD format.
 * 
 * @param {Date} date The date object to be formatted.
 * @returns {string} The formatted date in YYYY-MM-DD format.
 */
function formatDateToYYYYMMDD(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    return formattedDate;
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class InitialProject
{   JFrame frame;
	public InitialProject()
	{   frame = new JFrame("MENU");
	     
		frame.setSize(800, 500);
		
		frame.setLayout(new BorderLayout());
		frame.add(new JButton("CVR RESTAURANT"), BorderLayout.NORTH);
		JPanel panel = new JPanel();
		panel.add(new JButton("CONFIRM"));
		panel.add(new JButton("RESET"));
        panel.add(new JButton("EXIT"));
		
		frame.add(panel, BorderLayout.SOUTH);
		
		//frame.add(new JLabel("Border Layout West"), BorderLayout.WEST);
      //  frame.add(new JTextField(20), BorderLayout.NORTH);
        frame.add(new JTextField(30), BorderLayout.WEST);
		frame.add(new JTextField(30), BorderLayout.EAST);
		frame.add(new JButton(""), BorderLayout.CENTER);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
	
	public static void main(String[] args)
	{
		new BorderLayoutDemo();
	}
}
star

Fri Feb 23 2024 10:00:46 GMT+0000 (Coordinated Universal Time) https://www.metadiac.com/binance-clone-script

@logan #binance #binanceclone #binanceclonescript #cryptoexchangedevelopment

star

Fri Feb 23 2024 08:32:28 GMT+0000 (Coordinated Universal Time)

@NoobAl

star

Fri Feb 23 2024 07:53:26 GMT+0000 (Coordinated Universal Time)

@kchan

star

Fri Feb 23 2024 01:59:22 GMT+0000 (Coordinated Universal Time) https://www.uniten.edu.my/about-uniten/colleges/uniten-business-school-ubs/our-people/?act

@YEUNA

star

Fri Feb 23 2024 01:33:03 GMT+0000 (Coordinated Universal Time)

@kiroy

star

Thu Feb 22 2024 22:13:54 GMT+0000 (Coordinated Universal Time)

@Y@sir #wordpress #dashboard #dark-mode

star

Thu Feb 22 2024 20:56:48 GMT+0000 (Coordinated Universal Time)

@abdullahalmamun

star

Thu Feb 22 2024 17:07:01 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Thu Feb 22 2024 16:47:35 GMT+0000 (Coordinated Universal Time)

@abdullahalmamun

star

Thu Feb 22 2024 16:45:47 GMT+0000 (Coordinated Universal Time) https://react-icons.github.io/react-icons/

@abdullahalmamun

star

Thu Feb 22 2024 16:29:29 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/property

@aguest #python #classes

star

Thu Feb 22 2024 15:57:47 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/methods/built-in/staticmethod

@aguest #python #classes

star

Thu Feb 22 2024 15:34:38 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/methods/built-in/classmethod

@aguest #python #classes

star

Thu Feb 22 2024 15:28:33 GMT+0000 (Coordinated Universal Time)

@Shira

star

Thu Feb 22 2024 15:18:13 GMT+0000 (Coordinated Universal Time)

@aguest #python #classes

star

Thu Feb 22 2024 14:50:14 GMT+0000 (Coordinated Universal Time)

@aguest #python #classes

star

Thu Feb 22 2024 14:43:17 GMT+0000 (Coordinated Universal Time) https://mui.com/material-ui/getting-started/installation/

@abdullahalmamun

star

Thu Feb 22 2024 11:23:11 GMT+0000 (Coordinated Universal Time)

@riyadhbin

star

Thu Feb 22 2024 09:25:50 GMT+0000 (Coordinated Universal Time)

@aatish

star

Thu Feb 22 2024 09:15:57 GMT+0000 (Coordinated Universal Time)

@dpavone #javascript

star

Thu Feb 22 2024 05:40:30 GMT+0000 (Coordinated Universal Time)

@dsce

star

Thu Feb 22 2024 05:36:25 GMT+0000 (Coordinated Universal Time)

@dsce

star

Thu Feb 22 2024 05:12:08 GMT+0000 (Coordinated Universal Time) https://textarea.online/

@hasan1d2d

star

Thu Feb 22 2024 05:03:37 GMT+0000 (Coordinated Universal Time)

@dsce

star

Thu Feb 22 2024 00:20:16 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Thu Feb 22 2024 00:16:48 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Thu Feb 22 2024 00:10:17 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 23:53:09 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 23:49:49 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 19:07:50 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/

@eziokittu

star

Wed Feb 21 2024 17:56:41 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 17:49:54 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 17:48:33 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 17:46:12 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 17:16:57 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 17:14:51 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 17:03:41 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 17:02:02 GMT+0000 (Coordinated Universal Time)

@tchives #javascript

star

Wed Feb 21 2024 16:09:03 GMT+0000 (Coordinated Universal Time)

@papi292 #c++ #makefile #make

star

Wed Feb 21 2024 14:46:58 GMT+0000 (Coordinated Universal Time)

@tchives #formula

star

Wed Feb 21 2024 14:46:33 GMT+0000 (Coordinated Universal Time)

@tchives #formula

star

Wed Feb 21 2024 14:45:39 GMT+0000 (Coordinated Universal Time)

@tchives #formula

star

Wed Feb 21 2024 14:44:09 GMT+0000 (Coordinated Universal Time)

@tchives #formula

star

Wed Feb 21 2024 14:43:21 GMT+0000 (Coordinated Universal Time)

@tchives #formula

star

Wed Feb 21 2024 14:42:31 GMT+0000 (Coordinated Universal Time)

@tchives #formula

star

Wed Feb 21 2024 14:41:06 GMT+0000 (Coordinated Universal Time)

@tchives #formula

star

Wed Feb 21 2024 10:16:04 GMT+0000 (Coordinated Universal Time)

@Shira

star

Wed Feb 21 2024 09:39:44 GMT+0000 (Coordinated Universal Time)

@dsce

star

Wed Feb 21 2024 09:25:30 GMT+0000 (Coordinated Universal Time)

@sentgine #javascript #date

star

Wed Feb 21 2024 09:06:57 GMT+0000 (Coordinated Universal Time)

@dsce

Save snippets that work with our extensions

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