Snippets Collections
<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            * {
                cursor: url(https://ani.cursors-4u.net/cursors/cur-12/cur1103.ani), url(https://ani.cursors-4u.net/cursors/cur-12/cur1103.png), auto !important;
            }
        </style>
        <a href="https://www.cursors-4u.com/cursor/2014/03/14/rainbow-pinwheel-pointer.html" target="_blank" title="Rainbow Pinwheel Pointer">
            <img src="https://cur.cursors-4u.net/cursor.png" border="0" alt="Rainbow Pinwheel Pointer" style="position:absolute; top: 0px; right: 0px;" />
        </a>
        <style>
            body {
                background-color: green background-image: url('link');
                background-repeat: no-repeat;
                background-attachment: fixed;
                background-size: cover;
            }
        </style>
        <style>
            .container {
                width: 1000px;
                height: auto;
                max-height: 100%;
                border: 5px solid transparent;
                border-radius: 8px;
                padding: 5px;
                float: left;
                background: url("https://cdn.pixabay.com/photo/2020/02/07/19/05/spaceship-4828098_1280.jpg") no-repeat fixed;
                background-size: cover;
                background-clip: padding-box;
                margin: 5px;
            }
        </style>
        <style>
            .smallcontainer {
                width: 200px;
                height: auto;
                max-height: 100%;
                float: left;
                background-color: transparent;
                background-clip: padding-box;
            }
        </style>
        <style>
            .bigcontainer {
                width: 800px;
                height: auto;
                max-height: 100%;
                float: left;
                background-color: transparent;
                background-clip: padding-box;
            }
        </style>
        <style>
            .sidebar {
                width: 150px;
                height: auto;
                max-height: 100%;
                border: 3px solid white;
                border-radius: 8px;
                padding: 5px;
                float: left;
                overflow: auto;
                line-height: 100%;
                background-color: white;
                background-clip: padding-box;
                text-align: center;
                color: black;
                margin: 5px 2.5px 5px 5px;
                font-family: 'OD';
                background-color: rgba(31, 31, 31, 0.5);
                background-image: url('link');
                background-repeat: no-repeat;
                background-attachment: fixed;
                background-size: cover;
            }
        </style>
        <style>
            .sidebarr {
                width: 150px;
                height: auto;
                max-height: 100%;
                border: 5px solid black;
                border-radius: 8px;
                padding: 5px;
                float: right;
                overflow: auto;
                line-height: 100%;
                background-color: white;
                background-clip: padding-box;
                text-align: center;
                color: black;
                margin: 5px 2.5px 5px 5px;
                font-family: 'OD';
                background-image: url('link');
                background-repeat: no-repeat;
                background-attachment: fixed;
                background-size: cover;
            }
        </style>
        <style>
            .hi {
                float: right;
                overflow: auto;
            }
        </style>
        <style>
            .main {
                width: 700px;
                height: auto;
                max-height: 100%;
                border: 5px solid black;
                border-radius: 8px;
                padding: 5px;
                line-height: 100%;
                float: left;
                background-color: white;
                text-align: center;
                color: black;
                overflow: auto;
                margin: 5px 5px 5px 2.5px;
                font-family: 'OD';
                background-image: url('link');
                background-repeat: no-repeat;
                background-attachment: fixed;
                background-size: cover;
            }

            @font-face {
                font-family: Name;
                src: url(link);
            }

            @font-face {
                font-family: Name;
                src: url(link);
                font-weight: bold;
            }

            a:link {
                color: blue;
                background-color: transparent;
                text-decoration: none;
            }

            a:visited {
                color: purple;
                background-color: transparent;
                text-decoration: none;
            }

            a:hover {
                color: purple;
                background-color: transparent;
                text-decoration: underline;
            }

            a:active {
                color: purple;
                background-color: transparent;
                text-decoration: underline;
            }
        </style>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Site Title</title>
        <div class="container">
            <div class="hi">
                <img src="http://www.gigaglitters.com/created/jUWfkFIrUB.gif" />
                <div class="smallcontainer">
                    <div class="sidebar">
                        <h3>HEADER</h3>
                        <p>
                            <a href="link">Link</a>
                        </p>
                        <p>Text</p>
                    </div>
                    <div class="sidebar">
                        <p>Text</p>
                    </div>
                    <div class="sidebar">
                        <testarea rows="5" cols="15">You can use a box like this to make code visible and copyable! The rows and cols let you change its size. Mess around and find a size you like.</testarea>
                    </div>
                    <div class="sidebar">
                        <img src="https://blinkies.cafe/b/display/0150-alligator.gif">
                        <img>
                        <p>I left a blinkie here so you can see how they are embedded.</p>
                    </div>
                </div>
                <div class="bigcontainer">
                    <div class="main">
                        <img src="image" alt="Placeholder image, describe images with alt text like this. If the link is broken as it is here, the alt text displays instead of the image." width="250" height="300" style="float:left">
                        <h2>Header</h2>
                        <p>Text goes here. The box will scale with your text and image. Wow!</p>
                    </div>
                    <div class="main">
                        <p>You can have as many of these boxes as you want. They'll be nested inside your "Big Container" div if you keep the code like this, but if you take them out of that div, they'll arrange themselves instead of being constrained by the box. "Container," "Small Container" and "Big Container" divs can all have background colors and borders assigned to them if you want, but in this version of the code, they are transparent. </p>
                        <p>To change the colors of various elements, you can replace the "white" and "black" color tags with other color names or with hex codes. To add a background image, replace "link" in the background image code with an actual link. To change your font, upload a font file to Neocities and set it as the src link for the font. You can name the font family whatever you want then. Alternately, you can remove the src link and use the name of a web font (you can look up the names of these).</p>
                        <p>I left my custom cursor code in here at the top. In order to get rid of the custom cursor, just delete that section of code. In order to replace it with a different custom cursor, go to Cursors-4U and copy the code for your desired custom cursor, then replace it. Cursor animation doesn't work outside Internet Explorer as far as I can tell, so pick one that looks fine not animated.
                        <p>
                        <p>You can make more styles of div if you like - as many as you want! This is good if you want lots of different elements on your page, but it can gum up your code somewhat.</p>
                        <p align="left">To make text align left, put in an alignment tag like this. This can also be changed in the div styles, if you want your whole div's text aligned left.</p>
                        <div class="sidebar" style="height:200px">
                            <p>You can also put smaller divs inside bigger divs like this. This is how I do the character boxes on my characters page - they are all sidebar divs with links and images in them. </p>
                        </div>
                        <div class="sidebar" style="height:200px">
                            <p>If you put in more than one, they'll sit next to each other until they run out of room, at which point they'll start going vertically.</p>
                        </div>
                        <div class="sidebar" style="height:200px">
                            <p>To make them stay the same height, you can add a height code in as seen here. See how some of these have a scroll bar? That's because it reached its max height. If max height is a number, this can happen. If max height is set to "auto," the divs will just stretch with content.</p>
                        </div>
                    </div>
                </div>
            </div>
            </body>
</html>
{/* another layout  */}
      <div className="mx-auto mt-12 max-w-6xl space-y-12 sm:mt-16 sm:space-y-20 lg:mt-20 lg:space-y-24 xl:space-y-32">
        <div className="grid grid-cols-1 gap-x-12 gap-y-8 lg:grid-cols-2 lg:items-center xl:gap-x-16">
          <div>
            <CustomImage
              src="/oneHour/customdomain1.jpg"
              sizes="(max-width: 479px) 100vw, (max-width: 767px) 74vw, (max-width: 991px) 55vw, (max-width: 1279px) 96vw, (max-width: 1439px) 82vw, (max-width: 1919px) 1186px, 1346px"
            />
          </div>
          <div className="flex flex-col items-start justify-start lg:self-center">
            <div className="inline-flex h-14 w-14 items-center justify-center rounded-xl border border-paleAqua bg-paleAqua/20">
              <Globe width={24} height={24} className="text-[#00838d]" />
            </div>
            <Title title="Your Name. Your Domain. Your Personal Brand." />
            <Subtitle
              text=" Set up your custom domain in a few simple steps and make your
                portfolio truly yours."
            />
          </div>
        </div>

        {/* second feature  */}
        <div className="grid grid-cols-1 gap-x-12 gap-y-8 lg:grid-cols-2 lg:items-center xl:gap-x-16">
          <div className="lg:order-2">
            <CustomImage
              src="/oneHour/blog.jpg"
              sizes="(max-width: 479px) 100vw, (max-width: 767px) 74vw, (max-width: 991px) 55vw, (max-width: 1279px) 96vw, (max-width: 1439px) 82vw, (max-width: 1919px) 1186px, 1346px"
            />
          </div>
          <div className="flex flex-col items-start justify-start lg:order-1 lg:self-center">
            <div className="inline-flex h-14 w-14 items-center justify-center rounded-xl border border-paleAqua bg-paleAqua/20">
              <Globe width={24} height={24} className="text-[#00838d]" />
            </div>
            <Title title="Launch Your Blog with Ease" />
            <Subtitle text="  Create, and publish posts effortlessly—all within Notion." />
          </div>
        </div>
      </div>















const CustomImage = ({
  src,
  className,
  sizes,
}: {
  src: string;
  className?: string;
  sizes?: string;
}) => {
  return (
    <img
      src={src}
      className={twMerge(
        "h-full w-full rounded-2xl border border-paleAqua object-cover shadow-xl shadow-paleAqua/20",
        className,
      )}
      alt=""
    />
  );
};

const Title = ({ title, className }: { title: string; className?: string }) => {
  return (
    <h3
      className={twMerge(
        "mt-4 text-start text-2xl font-bold text-midnightBlue sm:text-3xl",
        className,
      )}
    >
      {title}
    </h3>
  );
};

const Subtitle = ({
  text,
  className,
}: {
  text: string;
  className?: string;
}) => {
  return (
    <h4
      className={twMerge(
        "mt-2 text-start text-base font-normal text-slateGray lg:text-lg",
        className,
      )}
    >
      {text}
    </h4>
  );
};
public class WhileLoopExample {
    public static void main(String[] args) {
        double n = 20;
        
        double guess = n / 2;
        while (guess * guess < n - 0.0001 || guess * guess > n + 0.0001) {
            guess = (n / guess + guess) / 2;
            System.out.println(guess + " squared is " + guess * guess
                    + " and n / guess is "
                    + n / guess);
        }
    }
}
// Define the region of interest (could be a point or polygon)
var point = ee.Geometry.Point(90.2611485521762, 23.44690280909043);

// Define the start and end years for the time series from 2013 to 2024
var startYear = 2013;
var endYear = 2024;

// Function to filter Landsat images for a specific year and calculate average NDVI
var calculateYearlyAverageNDVI = function(year) {
  // Define the date range for the current year
  var startDate = ee.Date.fromYMD(year, 1, 1);
  var endDate = ee.Date.fromYMD(year, 12, 31);
  
  // Filter the image collection for the year and apply cloud cover filter
  var yearlyCollection = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
    .filterBounds(point)
    .filterDate(startDate, endDate)
    .filter(ee.Filter.lt('CLOUD_COVER', 20)) // Cloud cover less than 20%
    .map(function(image) {
      var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
      return image.addBands(ndvi);
    });

  // Compute the average NDVI for the year
  var averageNDVI = yearlyCollection.select('NDVI').mean();

  // Extract the average NDVI value at the specified point
  var averageNDVIValue = averageNDVI.reduceRegion({
    reducer: ee.Reducer.mean(),
    geometry: point,
    scale: 30
  }).get('NDVI');

  // Return the result as a feature with the year and average NDVI value
  return ee.Feature(null, {
    'year': year,
    'average_NDVI': averageNDVIValue
  });
};

// Generate a list of years from 2013 to 2024
var years = ee.List.sequence(startYear, endYear);

// Apply the function to each year and create a feature collection with the results
var yearlyNDVICollection = ee.FeatureCollection(years.map(calculateYearlyAverageNDVI));

// Print the average NDVI values for each year
print('Yearly Average NDVI:', yearlyNDVICollection);

// Chart the yearly average NDVI values
var chart = ui.Chart.feature.byFeature(yearlyNDVICollection, 'year', 'average_NDVI')
  .setOptions({
    title: 'Yearly Average NDVI at Point (2013-2024)',
    hAxis: {title: 'Year'},
    vAxis: {title: 'Average NDVI'},
    lineWidth: 2,
    pointSize: 3
  });
print(chart);

// Map Visualization
Map.centerObject(point, 10);
Map.addLayer(point, {color: 'red'}, 'Selected Point');

// Optionally visualize NDVI of the last year's average
var lastYearNDVI = yearlyNDVICollection.sort('year', false).first();
var lastYearNDVIImage = ee.Image(ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterDate(ee.Date.fromYMD(endYear, 1, 1), ee.Date.fromYMD(endYear, 12, 31))
  .select('NDVI')
  .mean());
Map.addLayer(lastYearNDVIImage, {min: 0, max: 1, palette: ['white', 'green']}, 'NDVI (2024)');

// Optionally, add a legend for NDVI
var legend = ui.Panel({
  style: {
    position: 'bottom-right',
    padding: '8px 15px'
  }
});
legend.add(ui.Label({
  value: 'NDVI Values',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

var palette = ['white', 'green'];
var ndviRanges = ['Low NDVI', 'High NDVI'];

for (var i = 0; i < palette.length; i++) {
  var colorBox = ui.Label({
    style: {
      backgroundColor: palette[i],
      padding: '8px',
      margin: '0 0 4px 0'
    }
  });
  var description = ui.Label({
    value: ndviRanges[i],
    style: {margin: '0 0 4px 6px'}
  });
  legend.add(
    ui.Panel({
      widgets: [colorBox, description],
      layout: ui.Panel.Layout.Flow('horizontal')
    })
  );
}

// Add the legend to the map
Map.add(legend);
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":newspaper:  STAY IN THE KNOW  :newspaper:"
			}
		},
		{
			"type": "context",
			"elements": [
				{
					"text": "*October, 2024*  |  Office Announcements",
					"type": "mrkdwn"
				}
			]
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay in the loop about what's happening at the office such as upcoming visitors, onsite meetings, lunches, and more. Don't miss out- check out the <https://calendar.google.com/calendar/u/0?cid=Y19jNmI2NzM1OTU0NDA0NzE1NWE3N2ExNmE5NjBlOWZkNTgxN2Y1MmQ3NjgyYmRmZmVlMjU4MmQwZDgyMGRiNzMyQGdyb3VwLmNhbGVuZGFyLmdvb2dsZS5jb20|*Tor Happenings Calendar*>"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":calendar: | :breakfast: *TUESDAY BREAKFAST SCHEDULE* :breakfast: | :calendar: "
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`10/1` *Greenbox*"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`10/8` *Le Gourmand*"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`10/15` *Impact Kitchen*"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`10/22` *Neon Commissary*"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`10/29` *Goat Coffee Co.*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":calendar: |:lunch: *THURSDAY LUNCH SCHEDULE* :lunch: | :calendar: "
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`8/1` *Chiang Mai* _Thai_"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`8/8` *Pie Commission*"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`8/15` *Impact Kitchen* _Salad Bowls_"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`8/22` *Scotty Bons* _Caribbean_"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "`8/29` *Black Camel* _Sandwiches_"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":loud_sound:*FOR YOUR INFORMATION* :loud_sound:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":coffee: *Every Tuesday and Thursday*: Enjoy coffee and café-style beverages from our partner, *HotBlack Coffee*, located at *245 Queen St W*, by showing your *Xero ID* \n\n:holiday-potato: *Upcoming Public Holiday*: Monday, 14th October \n\n:OFFICE: *Self-Serviced Fridays* _WX will still be online and working, just not onsite_. For more information, check out our <https://docs.google.com/document/d/1yPfsoOt4o-_scOmAGtYuZduzW_8333id2w5dhrlnVz0/edit| *FAQ page*> or reach out to WX. \n\n :standup: *Canada Stand Up* \n *August 15th*- Hosted by Intern Engineer, *Daniel Iseoluwa* \n\n:blob-party: *Monthly Social: :jack_o_lantern: Pumpkin Carving :jack_o_lantern:* \n*October 31st @ 3:30pm*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":WX: *WX offers comprehensive event planning services, including:*\n - Assistance with logistics and coordination \n - Access to a network of vendors for catering, supply ordering, etc.\n\n _Note: Even if you don’t need our assistance but are using the office space, kindly inform WX._ "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":tada: *Happy Birthday* :tada: to all Xeros celebrating their birthdays this October! We hope you have an amazing day :party_wiggle: "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "context",
			"elements": [
				{
					"type": "mrkdwn",
					"text": ":pushpin: Have something important to add to our calendar or need some assistance? Get in touch with us by logging a ticket via the <https://xerohelp.zendesk.com/hc/en-us/requests/new?ticket_form_id=900001672246| *HelpCentre*>. We are here to help!"
				}
			]
		},
		{
			"type": "divider"
		}
	]
}
import java.sql.*;
public class JDBC{
    public static void main(String[] args)throws ClassNotFoundException,SQLException{
        String url="jdbc:oracle:thin:@//localhost:1521/XE";
        String username="system";
        String password="cvr123";
        String query="SELECT * FROM Employee";
        
        try{
            Connection conn = DriverManager.getConnection(url,username,password);
            Statement statement1 = conn.createStatement();
            ResultSet result1 = statement1.executeQuery(query);
            while(result1.next()){
                int id = result1.getInt(1);
                String name = result1.getString(2);
                int salary = result1.getInt(3);
                System.out.println(id+" "+name+" "+salary);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }   
}






        ID NAME                                                                                                                                                       SALARY
---------- ------------------------------------------------------------------------------------------------------------------------------------------------------ ----------
         1 Varshith                                                                                                                                                     5000
         2 Suhas                                                                                                                                                        5000
         3 Manish                                                                                                                                                       6000
         4 Keerthan                                                                                                                                                     3000
         5 Chandhu                                                                                                                                                      3500






D:\22B81A05V5>set classpath=C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6_g.jar;.;

D:\22B81A05V5>JAVAC JDBC.java

D:\22B81A05V5>java JDBC
1 Varshith 5000
2 Suhas 5000
3 Manish 6000
4 Keerthan 3000
5 Chandhu 3500
npx create-dynamic-app@latest
Sucess Banner:
<div class="slds-box slds-box_small slds-theme_success">
  
Failure Banner:
<div class="slds-box slds-box_small slds-theme_error">

Warning Banner:
<div class="slds-box slds-box_small slds-theme_warning">

Information Banner:
<div class="slds-box slds-box_small slds-theme_shade">

Success Notification 
<div class="slds-scoped-notification slds-theme_success" role="status">

Failure  Notification
<div class="slds-scoped-notification slds-theme_error" role="status">
  
Warning Notification 
<div class="slds-scoped-notification slds-theme_warning" role="status">

SELECT 
    CASE 
        WHEN nombre = 'FEDERICO DE LEON' 
        THEN 'Jefe de Transformacion y Personas'
        ELSE PUENOM
    END AS PUENOM,
    AVG(SUELDO) AS Promedio_Sueldo_Anual,
    AVG(PRODUCTIVIDAD) AS Promedio_Productividad,
    AVG([COMISIONES VARIABLES]) AS Promedio_Comisiones_Variables_Anual,
    AVG(GRATIFICACION) AS Promedio_Gratificacion
FROM (
    SELECT 
        RTRIM(primer_nombre) + ' ' + RTRIM(primer_apellido) AS nombre,
        PUENOM,
        [PREMIOS] AS PRODUCTIVIDAD,
        [COMISIONES VARIABLES] AS [COMISIONES VARIABLES],
        [SUELDO] AS SUELDO,
        [GRATIFICACION]
    FROM (
        SELECT 
            vista_completa.primer_nombre,
            vista_completa.primer_apellido,
            PUESTOS.PUENOM,
            vista_completa.DEPARTAMENTO_NOMBRE,
            VISTA_GENEXCEL.FECHA_INGRESO,
            vista_genexcel.mes_y_anio,
            vista_genexcel.importe,
            vista_completa.fecha_de_egreso,
            CASE 
                WHEN vista_genexcel.CONCEPTO IN (45, 40, 46) THEN 'COMISIONES VARIABLES'
                ELSE vista_genexcel.concepto_nombre
            END AS concepto_nombre
        FROM 
            sueldosprod.dbo.fundef FUNDEF,
            sueldosprod.dbo.puestos PUESTOS,
            sueldosprod.dbo.vista_genexcel VISTA_GENEXCEL
            INNER JOIN sueldosprod.dbo.vista_completa VISTA_COMPLETA
                ON vista_genexcel.funcionario = vista_completa.ci
        WHERE  
            ((( vista_genexcel.mes_y_anio >= {ts '2024-08-01 00:00:00'} ) and ( vista_genexcel.mes_y_anio < {ts '2024-09-01 00:00:00'} )) or ( vista_genexcel.mes_y_anio >= {ts '2024-01-01 00:00:00'} and VISTA_GENEXCEL.CONCEPTO=2000))
            AND fundef.deffuncod = vista_completa.funcionario_codigo
            AND puestos.empcod = fundef.empcod
            AND puestos.puecod = fundef.puecod
            AND vista_genexcel.CONCEPTO IN (1, 44, 20, 45, 40, 46, 2000)
    ) AS SourceTable
    PIVOT (
        SUM(importe)
        FOR concepto_nombre IN ([PREMIOS], [COMISIONES VARIABLES], [SUELDO],[GRATIFICACION])
    ) AS PivotTable
    WHERE fecha_de_egreso IS NULL 
) AS ResultTable
where PUENOM != 'SIN DEFINIR'
GROUP BY 
    CASE 
        WHEN nombre = 'FEDERICO DE LEON' 
        THEN 'Jefe de Transformacion y Personas'
        ELSE PUENOM
    END
<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define( 'WP_USE_THEMES', true );

/** Loads the WordPress Environment and Template */
require __DIR__ . '/wp-blog-header.php';
//@version=5
strategy("MA30 Long Strategy ", overlay=true)
 
// Set the trading date range
startDate = timestamp(2020, 01, 01, 00, 00)
endDate = timestamp(2024, 12, 31, 23, 59)
 
// Calculate the 30-period moving average
ma30 = ta.sma(close, 30)
ma2= ta.sma(close, 10)
 
// Calculate the standard deviation of the last 30 periods
stdDev = ta.stdev(close, 30)
 
// Maximum position size as 10% of the available capital
positionSize = strategy.equity * 1 / close
 
// Define the exit level (1.5 standard deviations below the MA30)
stopLossPercentage = 0.08
stopPriceShort = close * (1 + stopLossPercentage)
exitLevel =  ma2 - (1.5* stdDev) 
 
// Define the strategy logic for trading
if (time >= startDate and time <= endDate)  // Only trade within the specified date range
    // Open a long position when the stock price crosses above the MA30
    if (ta.crossover(close, ma30))
        // Open a long position using 10% of the fund
        strategy.entry("Long", strategy.long, qty = positionSize)
        
    // Close the position when the stock price drops below 1.5 standard deviations from the MA30
    if (close < ma30 )
        // Close the long position
        strategy.close("Long")
 
longlen = input.int(30, "Long MA Length", minval=1)
long = ta.sma(close, longlen)
plot(long, color = color.rgb(249, 18, 18), title="Long MA")
import pendulum

current_date = pendulum.now().date()
uploaded_date = pendulum.date(2018, 8, 1)

diff_days = current_date.diff(uploaded_date).in_days()

print(current_date.subtract(days = diff_days).diff_for_humans()) # 6 years ago
import pendulum

try:
    print(pendulum.parse('{:0>2}-{:0>2}-{:0>2}'.format(2024, 9, 21)))
except Exception as e:
    print(e)
model/userbackend:

class Userbackend extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const ROLE_ADMIN = 25; //RolMaximo
    const ROLE_ENTE = 15; //Rol#1
    const ROLE_SUP_ENTE = 20; //Rol#2
    const ROLE_PRESIDENTE_ENTE = 26; //Rol#3
    const ROLE_VICEMINISTRO_SECTOR = 30; //Rol#4
    const ROLE_DESPACHO_MINISTRO = 35; //Rol#5

 public function getRole()
    {
        if ($this->role == self::ROLE_ADMIN) { //MAXIMO
            $r = 'ADMINISTRADOR';
        } elseif ($this->role == self::ROLE_ENTE) {//Rol#1
            $r = 'ENTE';
        } elseif ($this->role == self::ROLE_SUP_ENTE) { //Rol#2
            $r = 'SUPERVIDOR ENTE';
        } elseif ($this->role == self::ROLE_PRESIDENTE_ENTE) {//Rol#3
            $r = 'PRESIDENTE ENTE';

        } elseif ($this->role == self::ROLE_VICEMINISTRO_SECTOR){//Rol#4
            $r = 'VICEMINISTRO SECTOR';

        } elseif ($this->role == self::ROLE_DESPACHO_MINISTRO) {//Rol#5
            $r = 'DESPACHO MINISTRO';

        } else {
            $r = '';
        }
        return $r;
    }

nota: las siguientes lineas van debajo de la siguiente funcion:

public function getDatosUsuario()
    {
        return $this->nomper . " " . $this->apeper . " (" . $this->username . ")";
    }

// desde aqui

public static function isUserAdmin($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_ADMIN])) {//maximo
            return true;
        } else {
            return false;
        }
    }

    
    public static function isUserEnte($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_ENTE])) {//Rol#1
            return true;
        } else {
            return false;
        }
    }

    public static function isUserSup_Ente($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_SUP_ENTE])) {//Rol#2
            return true;
        } else {
            return false;
        }
    }

    public static function isUserPres_Ente($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_PRESIDENTE_ENTE])) {//Rol#3
            return true;
        } else {
            return false;
        }
    }


    public static function isUserVice_Sector($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_VICEMINISTRO_SECTOR])) {//Rol#4
            return true;
        } else {
            return false;
        }
    }

    public static function isUserDesp_Ministro($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_DESPACHO_MINISTRO])) {//Rol#5
            return true;
        } else {
            return false;
        }
    }

from pynput.keyboard import Listener

def on_press(key):
    print(str(key))


with Listener(on_press = on_press) as l:
    l.join()
#include <iostream>
#include <bits/stdc++.h>
 using namespace std;


void findTimeToBuyTicket(vector<int> tickets ,int k){
   
    int timetaken=0;
    while(tickets[k]!=0){
       
      for (int i =0;i<tickets.size();i++){
         if(tickets[i] ==0){
          continue;
         }
        tickets[i]--;
        timetaken++;
        if(i==k){
            break;
        }
    }
    }
    cout<<"Time taken of kth person is: " <<timetaken<<endl;
}
 

 int main() {
 //Write your C++ code here
 vector<int> tickets ={5,1,1,1};
 findTimeToBuyTicket(tickets,2);
 return 0;
 }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        input, button {
            margin: 5px;
            padding: 10px;
            font-size: 16px;
        }
        #result {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <h3>Simple Calculator</h3>
    <input type="number" id="value1" placeholder="Enter first number">
    <input type="number" id="value2" placeholder="Enter second number">
    
    <div>
        <button name="add" onclick="add()">ADDITION</button>
        <button name="sub" onclick="sub()">SUBTRACT</button>
        <button name="mul" onclick="mul()">MULTIPLY</button>
        <button name="div" onclick="div()">DIVISION</button>
    </div>

    <div id="result"></div>

    <script>
        function add() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const result = value1 + value2;
            document.getElementById('result').innerText = `Addition of ${value1} and ${value2} is ${result}`;
        }

        function sub() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const result = value1 - value2;
            document.getElementById('result').innerText = `Subtraction of ${value1} and ${value2} is ${result}`;
        }

        function mul() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const result = value1 * value2;
            document.getElementById('result').innerText = `Multiplication of ${value1} and ${value2} is ${result}`;
        }

        function div() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            if (value2 === 0) {
                document.getElementById('result').innerText = 'Error: Division by zero';
            } else {
                const result = value1 / value2;
                document.getElementById('result').innerText = `Division of ${value1} and ${value2} is ${result}`;
            }
        }
    </script>

</body>
</html>
#include <iostream>
#include <bits/stdc++.h>
 using namespace std;


void findStudentsUnableToEatLunch(queue<int> food, queue<int>students){
    int foodNotMatched =0;
    while(!food.empty()){

    if(students.front() == food.front()){
        food.pop();
        students.pop();
    }else{
        foodNotMatched++;
        if(foodNotMatched == students.size()){
            break;
        }else{
            students.push(students.front());
            students.pop();
        }
    }
      
    
    
}
cout<<"The element remaning is: " << students.size()<<endl;
}
 

 int main() {
 //Write your C++ code here
 queue<int> food;
 food.push(1);
 food.push(0);
 food.push(0);
 food.push(0);
 food.push(1);
 food.push(1);
 queue<int> students;
 students.push(1);
 students.push(1);
 students.push(1);
 students.push(0);
 students.push(0);
 students.push(1);
 findStudentsUnableToEatLunch(food,students);
 return 0;
 }
<a href="facebook.com">hhh</a>
Understanding Solana Meme Coin Development

In the fast-paced world of cryptocurrencies, meme coins have become a unique trend, combining fun with digital innovation. Solana meme coins highlight this trend through their use of the Solana blockchain. Known for its high speed and low transaction costs, Solana offers an ideal platform for these meme coins. Solana meme coins blend the playful spirit of meme culture with the advanced technology of Solana, making them stand out in the crypto market. This introduction will explore what makes Solana meme coins special, their benefits, and how they are shaping the future of digital assets.
Innovative Technology
The advanced technology of the Solana blockchain, renowned for its quick transaction times and inexpensive fees, is utilized by Solana meme currencies. Because meme currencies frequently involve large volume, low-value exchanges, Solana's distinct Proof of History (PoH) agreement process in conjunction with Proof of Stake (PoS) guarantees quick and safe transactions, which makes it the perfect platform for meme currencies that seek to garner community involvement as well as commercial attention.
The Rise of Solana Meme Coins
Solana meme coins are gaining popularity because they blend internet culture with advanced blockchain tech. Thanks to Solana’s fast and affordable network, these tokens attract both crypto fans and the general public. Solana’s ability to process many transactions quickly makes it perfect for meme coins, which often see rapid trading and high price swings. This trend shows how playful, community-focused projects can thrive with strong technology, capturing the spirit of the crypto world and engaging a wide range of online communities.
Community Engagement
Community involvement is key to the success of Solana meme coins. These coins thrive on the enthusiasm and support of their online communities, which help drive their popularity and value. Active communities engage in discussions, share memes, and promote the coin across social media platforms, creating a buzz around the project. Events, giveaways, and collaborative activities further strengthen community bonds and encourage more people to get involved. By fostering a strong, engaged community, Solana meme coins can build a loyal user base and sustain interest, making community support a key factor in their growth and success.
Future Prospects for Solana Meme Coins:
The future looks bright for Solana meme coins as they continue to grow in popularity. With Solana’s fast and low-cost transactions, these meme coins can handle increasing activity and trading volume. As more people join the Solana ecosystem, meme coins could see greater adoption and integration into various applications. The community’s enthusiasm and creativity will likely drive new projects and innovations. Additionally, as the crypto market evolves, Solana meme coins may benefit from increased visibility and support, potentially leading to new opportunities and expanded use cases. Overall, their future appears promising with ongoing development and engagement.

Solana Updates and Upgrades
Solana consistently updates and upgrades its blockchain to boost performance and enhance security. Recent advancements include optimizations for transaction speed and scalability, ensuring the network handles growing demand efficiently. Upgrades also focus on reducing fees and enhancing developer tools, which support the growth of decentralized applications and tokens. These ongoing improvements strengthen Solana’s position as a leading platform, benefiting projects like meme coins by providing a robust and reliable infrastructure.
 Conclusion
Beleaf Technologies has demonstrated remarkable growth and innovation in Solana meme coin development. The company has established itself as a leader by consistently leveraging cutting-edge technology and fostering a culture of creativity and excellence. Their commitment to delivering high-quality solutions and adapting to the ever-evolving technological landscape positions them well for continued success.
Visit — https://www.beleaftechnologies.com/solana-meme-coin
Contact Details:
Phone +91 8148147362

Are you ready to dive into the awesome world of Solana meme coins? These super cool tokens are all about having a blast and connecting with others. Not only that, but they're also making a big impact on the future of cryptocurrency and adding some extra fun to the Solana network.
Visit us:https://www.beleaftechnologies.com/solana-meme-coin
#SolanaMemeCoin #SolanaShenanigans #SolanaLols #SOLMeme #SolanaLaughs #SOLFun
 #MemeCoinOnSOL #SolanaToTheMoon #SOLGiggles #SolanaVibes

Visit — https://www.beleaftechnologies.com/solana-meme-coin
Contact Details:
Phone +91 8148147362
R Studio has emerged as one of the most powerful tools for data analysis, statistical computing, and graphical representation. Students in various fields such as data science, statistics, and computer science rely heavily on it for their academic projects. However, mastering R Studio is no easy task. It requires a deep understanding of programming concepts, statistical theories, and the ability to work with complex data sets. This is where R Studio assignment help becomes essential for students striving to excel in their coursework.

One of the major reasons why students seek assistance with R Studio assignments is the complexity of the software itself. It is a versatile tool that offers extensive libraries and functions for data manipulation and visualization. However, students often find it challenging to implement these tools effectively without proper guidance. This can lead to frustration, especially when faced with tight deadlines. Seeking r studio assignment help can save time, reduce stress, and ensure that assignments are completed accurately and on time. Professional assistance allows students to focus on learning and understanding the core concepts rather than getting bogged down by technical difficulties.

Moreover, R Studio assignments often involve advanced statistical analysis, which can be daunting for students who are not well-versed in these concepts. Statistical modeling, hypothesis testing, regression analysis, and data visualization are common components of these assignments. For students unfamiliar with these techniques, completing the tasks becomes overwhelming. In such situations, seeking expert r studio assignment help is a practical solution. With professional guidance, students can gain a clearer understanding of statistical concepts and learn how to apply them effectively in R Studio.

In addition to the complexity of the assignments, another reason students opt for help is the need for high-quality submissions. Academic assignments are often graded based on accuracy, clarity, and presentation. Submitting an assignment with errors or poorly presented data can result in low grades, even if the student understands the concepts. By turning to experts, students can ensure their assignments meet academic standards. Professional services like myassignment help offer tailored solutions that not only assist with coding and statistical analysis but also ensure that the final submission is well-structured and free of errors.

Lastly, learning how to navigate and utilize R Studio effectively is a skill that extends beyond academia. As industries increasingly rely on data-driven decision-making, proficiency in R Studio has become a valuable asset in the job market. Students who seek help with their assignments are not only ensuring their academic success but are also building a strong foundation for their future careers. R Studio assignment help provides students with the opportunity to develop these critical skills while managing their academic workload efficiently.

In conclusion, the complexity of R Studio, coupled with the demands of academic assignments, makes professional assistance a valuable resource for students. Whether it’s to save time, ensure accuracy, or enhance understanding, seeking r studio assignment help is an essential step toward academic and career success. For students looking for comprehensive support, platforms like myassignment help offer expert guidance, enabling them to tackle their assignments with confidence

Visit : https://myassignmenthelp.expert/r-studio-assignment-help.html
connectedCallback() {
        const inputAligncenter = document.createElement('style');
        inputAligncenter.innerText = `c-fdvgc_simulation-financial-create-quote-qroup {position: relative;} .uiModal--horizontalForm .modal-container:has(c-fdvgc_simulation-financial-create-quote-qroup) { width: 99%; max-width: 99%;} .runtime_platform_actionsQuickActionWrapper .quick-actions-panel:has(c-fdvgc_simulation-financial-create-quote-qroup) { overflow-y: clip;}`;
        document.body.appendChild(inputAligncenter);
    }

int converter(int decimalno)
{
    int binaryno = 0;
    
    for(int base = 1; decimalno > 0; decimalno /= 2)
    {
        binaryno += (decimalno % 2) * base;
        base *= 10;
    }
    
    return binaryno;
}
set.seed(28092024) 
n <- 3 
sample_norm <- rnorm(3,0,sqrt(5)) 
unb_estim <- var(sample_norm) 
max_estim <- var(sample_norm) * ((n-1)/n) 
mse_estim <- var(sample_norm) * ((n-1)/(n+1)) 
popul_var <- 5



estimates <- c(max_estim , unb_estim , mse_estim ) 
differences <- estimates - popul_var 
result <- data.frame( Estimator = c("MLE", "Unbiased", "MinMSE"), Estimate = estimates, Difference = differences ) 
print(result)
barplot(result$Difference, names.arg = result$Estimator, main = "Difference of Estimator values fromTrue Population Variance", ylab = "Difference", col = c("red", "green", "blue"), ylim = c(min(result$Difference) - 1, max(result$Difference) + 1))



calculate_estimators <- function(n, S, mean, popul_var) { 
unbiased_vals <- numeric(S) 
mle_vals <- numeric(S) 
mse_vals <- numeric(S) 
for (i in 1:S) { 
sample <- rnorm(n, mean, sqrt(popul_var)) 
unbiased <- var(sample) 
mle <- unbiased * ((n - 1) / n) 
minmse <- unbiased * ((n - 1) / (n + 1)) 
unbiased_vals[i] <- unbiased 
mle_vals[i] <- mle 
mse_vals[i] <- minmse } 
return(list( unbiased_var = unbiased_vals, mle_var = mle_vals, mse_var = mse_vals )) } 



stats_calc <- function(estimate_vals, popul_var) { 
avg_val <- mean(estimate_vals) 
bias <- avg_val - popul_var 
variance <- var(estimate_vals) 
mse <- mean((estimate_vals - popul_var)^2) 
return(c(Average = avg_val, Bias = bias, Variance = variance, MSE = mse)) } 
exp_n3 = calculate_estimators(3,10000,0,sqrt(5))
exp_n20 = calculate_estimators(20,10000,0,sqrt(5))
exp_n200 = calculate_estimators(200,10000,0,sqrt(5))



results_n3 <- data.frame( Estimator = c("Unbiased", "MLE", "MinMSE"), Average = c(n3_unbiased_stats["Average"], n3_mle_stats["Average"], n3_minmse_stats["Average"]), Bias = c(n3_unbiased_stats["Bias"], n3_mle_stats["Bias"], n3_minmse_stats["Bias"]), Variance = c(n3_unbiased_stats["Variance"], n3_mle_stats["Variance"], n3_minmse_stats["Variance"]), MSE = c(n3_unbiased_stats["MSE"], n3_mle_stats["MSE"], n3_minmse_stats["MSE"]) )

results_n20 <- data.frame( Estimator = c("Unbiased", "MLE", "MinMSE"), Average = c(n20_unbiased_stats["Average"], n20_mle_stats["Average"], n20_minmse_stats["Average"]), Bias = c(n20_unbiased_stats["Bias"], n20_mle_stats["Bias"], n20_minmse_stats["Bias"]), Variance = c(n20_unbiased_stats["Variance"], n20_mle_stats["Variance"], n20_minmse_stats["Variance"]), MSE = c(n20_unbiased_stats["MSE"], n20_mle_stats["MSE"], n20_minmse_stats["MSE"]) )


results_n200 <- data.frame( Estimator = c("Unbiased", "MLE", "MinMSE"), Average = c(n200_unbiased_stats["Average"], n200_mle_stats["Average"], n200_minmse_stats["Average"]), Bias = c(n200_unbiased_stats["Bias"], n200_mle_stats["Bias"], n200_minmse_stats["Bias"]), Variance = c(n200_unbiased_stats["Variance"], n200_mle_stats["Variance"], n200_minmse_stats["Variance"]), MSE = c(n200_unbiased_stats["MSE"], n200_mle_stats["MSE"], n200_minmse_stats["MSE"]) )





<?php
// تأكد من تثبيت مكتبة apple-signin-php باستخدام Composer
require_once 'vendor/autoload.php';

use AppleSignIn\ASDecoder;

// إعدادات قاعدة البيانات
$servername = "localhost";
$username = "nullsafety_app";
$password = "gQ0T(DHze!5L";
$dbname = "nullsafety_app";

// إعدادات Apple Sign In
$LOGIN_APPLE_CLIENT_ID = "io.fitness.club";
$LOGIN_APPLE_SECRET = "eyJraWQiOiJMQ1hESDJSTDJSIiwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiI2TFRESjJITldZIiwiaWF0IjoxNjk3MTQ2MDU2LCJleHAiOjE3MTI2OTgwNTYsImF1ZCI6Imh0dHBzOi8vYXBwbGVpZC5hcHBsZS5jb20iLCJzdWIiOiJpby5maXRuZXNzLmNsdWIifQ.D4YPbDBiRv76ToNUa9Lll1F82uohsgIUzIN4x-NBNahfZuC_A8LTNzFuaBDCBp4m5ohPa9eTc2xoK4NRJjWJWA";

// إنشاء اتصال
$conn = new mysqli($servername, $username, $password, $dbname);

// التحقق من الاتصال
if ($conn->connect_error) {
    die("فشل الاتصال: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // استلام البيانات من Apple
    $id_token = $_POST['id_token'];
    
    try {
        // فك تشفير وتحقق من الـ token
        $appleSignInPayload = ASDecoder::getAppleSignInPayload($id_token);
        
        // استخراج معلومات المستخدم
        $email = $appleSignInPayload->getEmail();
        $user_id = $appleSignInPayload->getUser();
        // الاسم غير متوفر دائمًا، لذا نحتاج للتحقق
        $name = isset($_POST['user']) ? json_decode($_POST['user'])->name : null;
        
        // التحقق مما إذا كان المستخدم موجودًا بالفعل
        $stmt = $conn->prepare("SELECT id FROM users WHERE apple_id = ?");
        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // المستخدم موجود بالفعل، قم بتحديث المعلومات إذا لزم الأمر
            $stmt = $conn->prepare("UPDATE users SET email = ?, name = ? WHERE apple_id = ?");
            $stmt->bind_param("sss", $email, $name, $user_id);
        } else {
            // مستخدم جديد، قم بإدراجه في قاعدة البيانات
            $stmt = $conn->prepare("INSERT INTO users (apple_id, email, name) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $user_id, $email, $name);
        }
        
        if ($stmt->execute()) {
            echo "تم تسجيل الدخول وحفظ البيانات بنجاح!";
        } else {
            echo "حدث خطأ أثناء حفظ البيانات: " . $stmt->error;
        }
        
    } catch (Exception $e) {
        echo "حدث خطأ: " . $e->getMessage();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>تسجيل الدخول باستخدام Apple</title>
</head>
<body>
    <div id="appleid-signin" data-color="black" data-border="true" data-type="sign in"></div>
    <script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
    <script type="text/javascript">
        AppleID.auth.init({
            clientId : '<?php echo $LOGIN_APPLE_CLIENT_ID; ?>',
            scope : 'name email',
            redirectURI : 'https://developer.null-safety.com/',
            state : 'YOUR_STATE_VALUE'
        });
    </script>
</body>
</html>
var ProductTypes = new Product_Type[]
{
  // Types for "Tops" (Category_ID = 1)
  new Product_Type { Type_ID = 1, Type_Name = "Shirts", Category_ID = 1 },  // T-shirts, long sleeves, crop tops
    new Product_Type { Type_ID = 2, Type_Name = "Tank Tops", Category_ID = 1 }, // All tank tops
      new Product_Type { Type_ID = 3, Type_Name = "Hoodies", Category_ID = 1 },   // Sleeveless and regular hoodies
        new Product_Type { Type_ID = 4, Type_Name = "Sweats", Category_ID = 1 },    // Sweatshirts and similar

          // Types for "Bottoms" (Category_ID = 2)
          new Product_Type { Type_ID = 5, Type_Name = "Shorts", Category_ID = 2 },    // All types of shorts
            new Product_Type { Type_ID = 6, Type_Name = "Joggers", Category_ID = 2 },   // Joggers and sweatpants
              new Product_Type { Type_ID = 7, Type_Name = "Leggings", Category_ID = 2 },  // All leggings
                new Product_Type { Type_ID = 8, Type_Name = "Compression Tights", Category_ID = 2 }, // Compression tights

                  // Types for "Gear" (Category_ID = 3)
                  new Product_Type { Type_ID = 9, Type_Name = "Gloves", Category_ID = 3 },    // Weightlifting gloves, workout gloves
                    new Product_Type { Type_ID = 10, Type_Name = "Socks", Category_ID = 3 },    // Athletic socks
                      new Product_Type { Type_ID = 11, Type_Name = "Accessories", Category_ID = 3 } // Wrist wraps, resistance bands, gym bags, etc.
};

builder.Entity<Product_Type>().HasData(ProductTypes);
import Axios from 'axios';
import CONFIG from '../../../config/config';
import moment from 'moment';

const url = {
  getPortfolioSurveysConsultants:
    CONFIG.BASE_URL + 'double-materiality/getPortfolioSurveysConsultants',
  getSurveys: CONFIG.BASE_URL + 'double-materiality/getSurveys',
};
/*
 Desc: Api to create double materiality
 Params: Data:- will be save on collection based on consultantId
*/ const localUrl =
  'http://localhost:17538/api/v1/';

const createDoubleMaterialitySurvey = async data => {
  let url = CONFIG.BASE_URL + 'createSurveyResult';
  const response = await Axios.post(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

/*
 Desc: Api to update double materiality
 Params: Data:- will be save on collection based on consultantId
 consultantId:- to identity collection
 currentSurveyId:- id to update doc in collection
 surveyId:- id to update doc in collection
*/
const updateDoubleMaterialitySurvey = async (data, consultantId, currentSurveyId, surveyId) => {
  let url =
    CONFIG.BASE_URL +
      'double-materiality/portfolio-surveys-consultants' +
      '?currentSurveyId=' +
      currentSurveyId ??
    '' + '&surveyId=' + surveyId ??
    '' + '&consultantId=' + consultantId;
  const response = await Axios.put(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

/*
 Desc: Api to get double materiality details
 Params: 
 consultantId:- to identity collection
 surveyId:- id to update doc in collection
*/
const getbysurveyid = async (surveyId,consultantId) => {
  const response = await Axios.get(`${CONFIG.BASE_URL}getbysurveyid?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
})
if(response?.data?.data['survey-results']) {
  delete response?.data?.data['survey-results'];
}
if(response?.data?.data['workshops']) {
  delete response?.data?.data['workshops'];
}
if(response?.data?.data['financial-workshops']) {
  delete response?.data?.data['financial-workshops'];
}

  return { response, data: () => response?.data?.data || {}, id: response?.data?.data?.id ?? '' };
};

/*
 Desc: Api to get surveyresults details
 Params: 
 consultantId:- to identity collection
 surveyId:- fetch data based on surveyId
*/
const getsurveyresultsbysurveyId = (surveyId,consultantId) => {
  return Axios.get(`${CONFIG.BASE_URL}getsurveyresultsbysurveyId?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
}

/*
 Desc: Api to get workshops details
 Params: 
 consultantId:- to identity collection
surveyId:- fetch data based on surveyId
*/
const getworkshopsbysurveyId = (surveyId,consultantId) => {
  return Axios.get(`${CONFIG.BASE_URL}getworkshopsbysurveyId?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
}

/*
 Desc: Api to get financialworkshops details
 Params: 
 consultantId:- to identity collection
surveyId:- fetch data based on surveyId
*/
const getfinancialworkshopsbysurveyid = (surveyId,consultantId) => {
  return Axios.get(`${CONFIG.BASE_URL}getfinancialworkshopsbysurveyid?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
}

/*
 Desc: function to get subcollection details
 Params: 
 consultantId:- to identity collection
 surveyId:- fetch data based on surveyId
 collectionName: indicate collection name
*/
const getSurveyResultForSubcollection = async (surveyId, consultantId, collectionName) => {
  try {
    if(collectionName == 'survey-results') {
      const response = await getsurveyresultsbysurveyId(surveyId,consultantId);
      const [surveyResult = []] =  response?.data?.data;

      let value = parseSnapShortData(response,collectionName);
      return value;
    }
    if(collectionName == 'workshops') {
      const response = await getworkshopsbysurveyId(surveyId,consultantId);
      const [surveyResult = []] =  response?.data?.data;

      let value = parseSnapShortData(response,collectionName);
      debugger
      return value;
    }
    if(collectionName == 'financial-workshops') {
      const response = await getfinancialworkshopsbysurveyid(surveyId,consultantId);
      const [surveyResult = []] =  response?.data?.data;

      let value = parseSnapShortData(response,collectionName);
      return value;
    }
    if (collectionName == 'dashboard-worksheet-audit-logs') {
      let url = 'getsurveyDashboardWorksheetAuditLogs';
      if (consultantId) {
        url = 'getportfolioSurveyDashboardWorksheetAuditLogs';
      }
      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'methodology-logs') {
      let url = 'getSurveyMethodologyLogs';
      if (consultantId) {
        url = 'getportfolioSurveyMethodologyLogs';
      }
      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;

      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'methodology-task-logs') {
      let url = 'getsurveyMethodologyTaskAuditLogModel';
      if (consultantId) {
        url = 'getportfolioSurveyMethodologyTaskAuditLogModel';
      }

      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'action-report-task-logs') {
      let url = 'getsurveyActionReportLogs';
      if (consultantId) {
        url = 'getportfolioSurveyActionReportLogs';
      }

      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'audit-log') {
      let url = 'getbysurveyId';
      if (consultantId) {
        url = 'getbyportfolioSurveyConsultantId';
      }

      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
  } catch (error) {
    console.log(error, 'error');
  }
};

const getsubmittedSurveyResult = async (surveyId,consultantId) => {
  const response = await Axios.get(`${CONFIG.BASE_URL}getsubmittedSurveyResult?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
  let value = [];
  if (response?.data?.data?.length && response?.data?.data[0]['survey-results']?.length) {
    value = response?.data?.data[0]['survey-results'].map((v, i) => {
      return {
        data: () => v,
        id: v.id || i,
      };
    });
  }
 
  return value;
}

/*
 Desc: function to parse the response and return in expected formate
 Params: 
 response: Response from collection
*/
const parseSnapShortData = response => {
  const surveyResult = response?.data?.data ?? [];
  let value = [];
  if (surveyResult?.length) {
    value = surveyResult.map((v, i) => {
      return {
        data: () => v || {},
        id: v.id || v?._id?.toString() || i,
      };
    });
  }
  return value;
};

const parseLogSnapShortData = (response, collectionName) => {
  const surveyResult = response?.data?.data ?? [];
  let value = [];
  if (surveyResult?.length) {
    value = surveyResult.map((v, i) => {
      return {
        data: () => v || {},
        id: v.id || v?._id?.toString() || i,
      };
    });
  }
  return value;
};

/*
 Desc: Api to update double materiality
 Params: 
 consultantId:- to identity collection
 surveyId:- fetch data based on surveyId
*/
const updateSurveyById =  (consultantId,surveyId,currentSurveyId) => {
  let url = CONFIG.BASE_URL+'double-materiality/portfolio-surveys-consultants'+'?surveyId='+surveyId ?? '';
  url += '&consultantId='+consultantId ?? '';
  url += '&currentSurveyId='+currentSurveyId ?? '';

  const update = async (data, url) => {
    const response = await Axios.put(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  };

  return { update: data => update(data, url), consultantId, surveyId, currentSurveyId };
};

const addToMethodologyLogs = (consultantId, surveyId, currentSurveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'setSurveyMethodologyLogs';
  if (consultantId) {
    url = CONFIG.AUDIT_LOG_URL + 'setportfolioSurveyMethodologyLogs';
  }
  
  const add  = async (data,url) => {
    const id =  surveyId ? surveyId :  currentSurveyId;
    console.log(url)
    data = {
      data,
      surveyId: id,
      currentSurveyId,
    };

    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  }
  
  return {add : (data) => add(data,url) , consultantId, surveyId,currentSurveyId};
}


const setWorkshops = async (consultantId,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/set-workshops?';
    url += '&consultantId='+consultantId ?? '';
    const response = await Axios.post(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}

const updateWorkshops = async (consultantId,id,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/update-workshops?';
    url += '&consultantId='+consultantId ?? '';
    url += '&id='+id ?? '';
    const response = await Axios.put(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}

const setFinancialWorkshops = async (consultantId,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/set-financial-workshops?';
    url += '&consultantId='+consultantId ?? '';
    const response = await Axios.post(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}

const updateFinancialWorkshops = async (consultantId,id,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/update-financial-workshops?';
    url += '&consultantId='+consultantId ?? '';
    url += '&id='+id ?? '';
    const response = await Axios.put(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}


/**
 * Desc: Api to get survey result by id
 * Params: 
    surveyResultId:- to fetch data based on the survey result
 */
const getSurveyResultById = async surveyResId => {
  const response = await Axios.get(
    `${CONFIG.BASE_URL}getsurveyresultsbyId?surveyResultId=${surveyResId}`,
    {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    },
  );
  return { response, data: () => response?.data?.data || {}, id: response?.data?.data?.id ?? '' };
};

/**
 * Desc: Api to update survey result
 * Params: 
    consultantId: to identify the collection
    data: to be added in survey-results
 */
const setSurveyResult = async (consultantId, data) => {
  let url = CONFIG.BASE_URL + 'double-materiality/set-survey-results?';
  url += '&consultantId=' + consultantId ?? '';
  const response = await Axios.post(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

/**
 * Desc: Api to update survey result
 * Params: 
    consultantId: to identify the collection
    id: id of the survey-result to be updated
    data: to be updated against the survey-result selected
 */
const updateSurveyResultData = async (consultantId, id, data) => {
  let url = CONFIG.BASE_URL + 'double-materiality/update-survey-results?';
  url += 'consultantId=' + consultantId ?? '';
  url += '&id=' + id ?? '';
  const response = await Axios.put(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

const addToSurveyResults = (surveyId, currentSurveyId) => {
  const url = CONFIG.BASE_URL + 'insertIntoSurveyResults';
  const add = async (payload, url) => {
    const id = surveyId ? surveyId : currentSurveyId;

    const data = {
      data: payload,
      surveyId: id,
    };

    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  };

  return { add: payload => add(payload, url), surveyId, currentSurveyId };
};

const addToAuditLogs = (consultantId, surveyId, currentSurveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'addauditstosurveys';
  if (consultantId) {
    url = CONFIG.AUDIT_LOG_URL + 'addauditstoportfoilosurveysconsultants';
  }
 
  const add = async (data, url) => {
    const id = surveyId ? surveyId : currentSurveyId;
    console.log(url);
    data = {
      data,
      surveyId: id,
      currentSurveyId,
    };
 
    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  };
 
  return { add: data => add(data, url), consultantId, surveyId, currentSurveyId };
};

/**
 * Adds a new comment to an answered topic.
 * @param {Object} params - an object containing surveyId and consultantId.
 * @param {Object} body - data to be sent in the request body.
 * @returns {Object} - an object containing response, data and status.
 * @throws {Error} - if unable to fetch the workshop.
 */

const addAnsweredTopicComment = async (params, body) => {
  const { surveyId, consultantId } = params;
  let URL = `${localUrl}addAnsweredTopic?surveyId=${surveyId}&consultantId=${consultantId || ""}`;

  try {
    const response = await Axios.post(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
};

const editAnsweredTopicComment = async (params, body) => {
  const { surveyId, consultantId, workshopId } = params;
  console.log("workshopId", workshopId)
  let URL = `${localUrl}updateAnsweredTopic?surveyId=${surveyId}&consultantId=${consultantId || ""}&workshopId=${workshopId || ""}`;
  console.log("URL", URL)
  try {
    const response = await Axios.put(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
};

/**
 * Updates a workshop property based on given endpoint, params and data.
 * @param {Object} params - an object containing surveyId, consultantId, workshopId, type and property.
 * @param {Object} data - data to be sent in the request body.
 * @returns {Object} - an object containing response and a function to get the data.
 * @throws {Error} - if unable to fetch the workshop.
 */
const updateWorkshopProperty = async (params, body) => {
  const { surveyId, consultantId, workshopId, type, property } = params;
  console.log('workshopId', workshopId);
  let URL = `${localUrl}double-materiality/update-workshop-property?surveyId=${surveyId}&consultantId=${consultantId ||
    ''}&workshopId=${workshopId || ''}&type=${type}`;

  if (property) URL += `&property=${property}`;

  console.log('URL', URL);

  try {
    const response = await Axios.post(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
};

/*
 * Updates consultants or survey Model property based on given endpoint, params and data.
 * @param {Object} params - an object containing surveyId, consultantId and property.
 * @param {Object} data - data to be sent in the request body.
 * @returns {Object} - an object containing response and a function to get the data.
 * @throws {Error} - if unable to fetch the workshop.
 */
const updateConsultantsOrSurveyProperty = async (params, body) => {
  const { surveyId, consultantId, property } = params;
  let URL = `${localUrl}double-materiality/updateConsultantsOrSurvey?surveyId=${surveyId}&consultantId=${consultantId ||
    ''}`;

  if (property) URL += `&property=${property}`;

  try {
    const response = await Axios.post(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
}


/**
 * Creates a new document with the action report task audit log details based on the data provided.
 * @param {String} consultantId - consultantId to identify the collection
 * @param {String} surveyId - surveyId to fetch data based on
 * @param {String} currentSurveyId - currentSurveyId to fetch data based on if surveyId is not provided
 * @returns {Object} - an object containing add function and consultantId, surveyId, currentSurveyId
 * @throws {Error} - if unable to created the document.
 */
const addToActionReportTaskAuditLogs = (consultantId, surveyId, currentSurveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'setSurveyActionReportLogs';
  if (consultantId) {
    url = CONFIG.AUDIT_LOG_URL + 'setportfolioSurveyActionReportLogs';
  }

  const add = async (data, url) => {
    const id = surveyId ? surveyId : currentSurveyId;
    data = {
      data,
      surveyId: id,
      currentSurveyId
    }

    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  }

  return { add: (data) => add(data, url), consultantId, surveyId, currentSurveyId };
}

/**
 * Creates a new document with the double materiality audit log details based on the data provided.
 * @param {data} params - contains surveyId, consultantId, field and updated by details
 * @returns {Object} - an object with status
 * @throws {Error} - if unable to created the document.
 */
const addToDoubleMaterialityAuditLog = (consultantId, surveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'setDoubleMaterialityAuditLogs';

  const add = async (data, url) => {
    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  }

  return { add: (data) => add(data, url), consultantId, surveyId };
}

/**
 * Fetches the double materiality audit logs by its surveyId.
 * @param {surveyId} params - contains the surveyId of which the details are to be fetched.
 * @returns {Object} - an object containing audit log details.
 * @throws {Error} - if unable to fetch the details.
 */
const getDoubleMaterialityAuditLogs = async (surveyId) => {
  const response = await Axios.get(`${CONFIG.AUDIT_LOG_URL}getDoubleMaterialityAuditLogs?surveyId=${surveyId}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
  let value = [];
  if (response?.data?.data?.length && response?.data?.data[0]['survey-results']?.length) {
    value = response?.data?.data[0]['survey-results'].map((v, i) => {
      return {
        data: () => v,
        id: v.id || i
      }
    })
  }

  return value;
}


export {
    parseSnapShortData,
    getsurveyresultsbysurveyId,
    getworkshopsbysurveyId,
    getfinancialworkshopsbysurveyid,
    getsubmittedSurveyResult,
    getSurveyResultForSubcollection,
    addToMethodologyLogs,
    updateSurveyById,
    getbysurveyid,
    createDoubleMaterialitySurvey,
    updateDoubleMaterialitySurvey,
    setWorkshops,
    updateWorkshops,
    setFinancialWorkshops,
    updateFinancialWorkshops,
    getSurveyResultById,
    setSurveyResult,
    updateSurveyResultData,
    addToAuditLogs,
    addToSurveyResults,
};
handleSubmitReasonForMaxOrAverage = e => {
    const { surveyId, currentSurveyId, consultantId, reasonForMaxOrAverage } = this.state;
    this.setState({ loading: true });
    this.setState({ maxOrAverageSelectionWarningModal: false });

    const body = {
      reasonForMaxOrAverage: reasonForMaxOrAverage
    }

    updateConsultantsOrSurveyProperty({
      surveyId,
      consultantId,
      property: "reasonForMaxOrAverage"
    }, body).then((res) => {
      console.log("updated the reason for max and average", res)
      this.setState({ loading: false });
    }).catch((err) => {
      console.log("error while updating", err)
      this.setState({ loading: false });
    })

    // const surveysRef = firebase
    //   .firestore()
    //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys');

    // surveysRef
    //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId)
    //   .update({
    //     reasonForMaxOrAverage: this.state.reasonForMaxOrAverage,
    //   })
    //   .then(() => {
    //     this.setState({ loading: false });
    //   })
    //   .catch(error => {
    //     console.log('error updating parent topics');
    //   });
  };

  handleSaveBooleanValue = (type, value) => {
    console.log("handleSaveBooleanValue", type, value)
    this.setState({ [type]: value });

    const payload = {
      [type]: value,
    }

    updateConsultantsOrSurveyProperty(
      {
        surveyId: this.state.surveyId,
        consultantId: this.state.consultantId,
        property: type,
      },
      payload,
    ).then(() => { })
      .catch(error => {
        console.log('error updating');
      });

    // const surveysRef = firebase
    //   .firestore()
    //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys');

    // surveysRef
    //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId)
    //   .update({
    //     [type]: value,
    //   })
    //   .then(() => { })
    //   .catch(error => {
    //     console.log('error updating');
    //   });
  };
  handleChangeScoringSetting = newScoringSetting => {
    const { surveyId, currentSurveyId, consultantId, scoringSetting } = this.state;

    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId);

    if (scoringSetting !== newScoringSetting) {
      this.setState({
        scoringSetting: newScoringSetting,
      });

      const body = {
        scoringSettings: newScoringSetting,
      };

      updateConsultantsOrSurveyProperty({
        surveyId,
        consultantId,
        property: "scoringSettings"
      }, body).then((res) => {
        console.log(`Updated scoring setting`, res);
      }).catch((err) => {
        console.log("Error updating scoring setting", err)
      })

      // matrixWorkshopsRef
      //   .update({
      //     scoringSetting: newScoringSetting,
      //   })
      //   .then(() => {
      //     console.log(`Updated scoring setting`);
      //   })
      //   .catch(error => {
      //     console.log('Updated scoring setting');
      //   });
    }
  };
#elevated command prompt, all accounts
wmic UserAccount set PasswordExpires=False

#elevated command prompt, particular accounts
wmic UserAccount where Name="user name" set PasswordExpires=False
#Substitute user name in the command above with the actual user name of the local account.
 appendImportedData_Impact = async book => {
    console.log("appendImportedData_Impact function called")
    try {
      const _selectedAnsweredEntry = this.state.selectedworkshop.answeredEntries;

      if (!_selectedAnsweredEntry) {
        this.state.selectedworkshop.answeredEntries = [];
        this.setState({
          selectedworkshop: { ...this.state.selectedworkshop, answeredEntries: [] },
        });
      }

      const selectedAnsweredEntry = this.state.selectedworkshop.answeredEntries;

      let _worksheet = this.state.selectedworkshop.worksheet
        .filter((item, index, self) => index === self.findIndex(t => t.id === item.id))
        .sort((a, b) => {
          if (a.framework == 'CSRD') {
            let _a =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == a['mainId'] && item2['topic'] == a['topic'],
              )?.sortIndex || 0;
            let _b =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == b['mainId'] && item2['topic'] == b['topic'],
              )?.sortIndex || 0;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.framework == 'GRI') {
            let _a = a.id;
            let _b = b.id;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.topic < b.topic) return -1;
          if (a.topic > b.topic) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .filter((item, index) => {
          return item.entryType !== 'comment' && item.entryType !== 'added-entry';
        });

      let allAnsweredEntries = [];
      _worksheet.forEach(item => {
        const answerData = this.state.answeredTopics.find(data => data.id === item.id);
        let answer = '';
        if (answerData) {
          answer = answerData;
        }

        const topicResult = this.state.surveyResultsIROComments.filter(
          item2 => item2.id == item.id,
        );

        let allComments = this.getAllCommentsFromShortSurvey_Impact(
          topicResult,
          Array.from(this.state.financialConsolidatedReports || []),
          Array.from(this.state.addedCommentTopics || []),
        );

        if (allComments.length > 0) {
          allComments
            .filter((v, i, a) => a.findIndex(t => t.id === v.id) === i)
            .filter(item => (item.assessmentType ? item.assessmentType == 'Impact' : item))
            .forEach((commData, commIndex) => {
              let item = commData;

              const workshopWithEntry = Array.from(this.state.workshops || [])
                .concat(Array.from(this.state.financialworkshops || []))
                .find(ws => {
                  return Array.from(ws.worksheet || []).find(data => data.id === commData.id);
                });

              if (workshopWithEntry) {
                const prevItem = Array.from(workshopWithEntry.worksheet || []).find(
                  data => data.id === commData.id,
                );

                if (prevItem) {
                  item = prevItem;
                }
              }

              const answerData = this.state.answeredTopics.find(data => data.id === item.id);
              let answer = '';
              if (answerData) {
                answer = answerData;
              }

              const entryId = `${this.state.surveyId}__${this.state.selectedworkshop.id}__${item.id}`;
              let entry = {
                topic: item.topic,
                id: entryId,
                surveyId: this.state.surveyId,
                workshopId: this.state.selectedworkshop.id,
                oldid: item.id,
              };

              if (
                item?.entryType == 'comment' &&
                (!answer?.['Verification'] ||
                  answer?.['Verification']?.value == 'No' ||
                  answer?.['Verification']?.value == '')
              ) {
                return null;
              }

              allAnsweredEntries.push(entry);
            });
        }
      });

      if (book && book.SheetNames) {
        book.SheetNames.forEach((parentitem, parentindex) => {
          const data = xlsx2.utils.sheet_to_json(book.Sheets[parentitem]);

          data.forEach(item => {
            const itemFind = selectedAnsweredEntry?.find(item2 => item2.topic == item['Topic']);

            if (item?.['Comment or Added Entry'] == 'Yes') {
              if (itemFind) {
                if (parentindex == 0) {
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`People or Environmental`] = item[`People or Environmental`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Remediability`] = item[`Remediability`] || '';
                  itemFind[`Scale`] = item[`Scale`] || '';
                  itemFind[`Scope`] = item[`Scope`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }
              } else {
                let itemFind = {};
                let answeredEntryFind = allAnsweredEntries.find(
                  item2 => item2['topic'] == item['Topic'],
                );
                if (answeredEntryFind) {
                  itemFind = {
                    ...itemFind,
                    ...answeredEntryFind,
                  };
                }

                if (parentindex == 0) {
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`People or Environmental`] = item[`People or Environmental`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Remediability`] = item[`Remediability`] || '';
                  itemFind[`Scale`] = item[`Scale`] || '';
                  itemFind[`Scope`] = item[`Scope`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }

                selectedAnsweredEntry.push(itemFind);
              }
            }
          });
        });
      }

      const { surveyId, currentSurveyId, consultantId, selectedworkshop } = this.state;
      // const matrixWorkshopsRef = firebase
      //   .firestore()
      //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
      //   .doc(surveyId ? surveyId : currentSurveyId)
      //   .collection('workshops')
      //   .doc(selectedworkshop.id);

      const updatedWorkshop = {
        ...selectedworkshop,
        answeredEntries: [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
          (item, index, self) => index === self.findIndex(t => t.id === item.id),
        ),
      };

      console.log('updatedWorkshop', updatedWorkshop);

      this.setState({
        selectedworkshop: updatedWorkshop,
        loading: false,
      });

      const payload = [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
        (item, index, self) => index === self.findIndex(t => t.id === item.id),
      )


      updateWorkshopProperty({
        surveyId,
        consultantId,
        workshopId: selectedworkshop.id,
        type: "impact",
        property: "answeredEntries"
      }, payload).then((res) => {
        console.log("submitted to api", res)
      }).catch(error => {
        console.log('error saving answered entries');
      });

      // matrixWorkshopsRef
      //   .update({
      //     answeredEntries: [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
      //       (item, index, self) => index === self.findIndex(t => t.id === item.id),
      //     ),
      //   })
      //   .then(() => {
      //     console.log(`saved answered entries`);
      //   })
      //   .catch(error => {
      //     console.log('error saving answered entries');
      //   });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({ loading: false });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
      return;
    }
  };
appendImportedData_Financial = async book => {
    try {
      const _selectedAnsweredEntry = this.state.selectedfinancialworkshop.answeredEntries;

      if (!_selectedAnsweredEntry) {
        this.state.selectedfinancialworkshop.answeredEntries = [];
        this.setState({
          selectedfinancialworkshop: {
            ...this.state.selectedfinancialworkshop,
            answeredEntries: [],
          },
        });
      }

      const selectedAnsweredEntry = this.state.selectedfinancialworkshop.answeredEntries;

      let _worksheet = this.state.selectedfinancialworkshop.worksheet
        .sort((a, b) => {
          if (a.framework == 'CSRD') {
            let _a =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == a['mainId'] && item2['topic'] == a['topic'],
              )?.sortIndex || 0;
            let _b =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == b['mainId'] && item2['topic'] == b['topic'],
              )?.sortIndex || 0;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.framework == 'GRI') {
            let _a = a.id;
            let _b = b.id;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.topic < b.topic) return -1;
          if (a.topic > b.topic) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .filter((item, index) => {
          return item.entryType !== 'comment' && item.entryType !== 'added-entry';
        });

      let allAnsweredEntries = [];
      _worksheet.forEach(item => {
        let verifiedTopic = '';
        if (item.value) {
          if (Array.isArray(item.value)) {
            verifiedTopic = item.value.map(item => item.label).join(', ');
          } else {
            verifiedTopic = item.value;
          }
        }

        const answerData = this.state.answeredTopics.find(data => data.id === item.id);
        let answer = '';
        if (answerData) {
          answer = answerData;
        }

        const riskValue = answer['Risk']?.value || '';
        const oppValue = answer['Opportunities']?.value || '';

        let riskValueColor = '#fff';
        let oppValueColor = '#fff';

        if (riskValue === 'Yes') {
          riskValueColor = '#D1060A';
        } else if (riskValue === 'No') {
          riskValueColor = '#2EB917';
        }

        if (oppValue === 'Yes') {
          oppValueColor = '#2EB917';
        }

        const topicResult = this.state.surveyResultsIROComments.filter(
          item2 => item2.id == item.id,
        );

        let allComments = this.getAllCommentsFromShortSurvey_Financial(
          topicResult,
          Array.from(this.state.financialConsolidatedReports || []),
          Array.from(this.state.addedCommentTopics || []),
        );

        if (allComments.length > 0) {
          allComments
            .filter((v, i, a) => a.findIndex(t => t.id === v.id) === i)
            .filter(item => (item.assessmentType ? item.assessmentType == 'Financial' : item))
            .forEach((commData, commIndex) => {
              let addedEntryTopicName = '';
              let item = commData;

              const workshopWithEntry = Array.from(this.state.workshops || [])
                .concat(Array.from(this.state.financialworkshops || []))
                .find(ws => {
                  return Array.from(ws.worksheet || []).find(data => data.id === commData.id);
                });

              if (workshopWithEntry) {
                const prevItem2 = Array.from(workshopWithEntry.worksheet || []).find(
                  data => data.id === commData.id,
                );

                if (prevItem2) {
                  addedEntryTopicName = prevItem2;
                }
              }

              const prevItem = Array.from(
                this.state.selectedfinancialworkshop.worksheet || [],
              ).find(data => data.id === commData.id);

              if (prevItem) {
                item = prevItem;
              }

              let verifiedTopic = '';
              if (item.value) {
                if (Array.isArray(item.value)) {
                  verifiedTopic = item.value.map(item => item.label).join(', ');
                } else {
                  verifiedTopic = item.value;
                }
              }

              const answerData = this.state.answeredTopics.find(data => data.id === item.id);
              let answer = '';
              if (answerData) {
                answer = answerData;
              }

              const entryId = `${this.state.surveyId}__${this.state.selectedfinancialworkshop.id}__${item.id}`;
              let entry = {
                topic: item.topic,
                id: entryId,
                surveyId: this.state.surveyId,
                workshopId: this.state.selectedfinancialworkshop.id,
                oldid: item.id,
              };
              const answeredEntryData = this.state.selectedfinancialworkshop?.answeredEntries?.find(
                entry => entry.id === entryId,
              );

              if (answeredEntryData) {
                entry = {
                  ...entry,
                  ...answeredEntryData,
                };
              }

              if (
                item?.entryType == 'comment' &&
                (!answer?.['Verification'] ||
                  answer?.['Verification']?.value == 'No' ||
                  answer?.['Verification']?.value == '')
              ) {
                return null;
              }

              allAnsweredEntries.push(entry);
            });
        }
      });

      if (book && book.SheetNames) {
        book.SheetNames.forEach((parentitem, parentindex) => {
          const data = xlsx2.utils.sheet_to_json(book.Sheets[parentitem]);

          data.forEach(item => {
            const itemFind = selectedAnsweredEntry?.find(item2 => item2.topic == item['Topic']);

            if (item?.['Comment or Added Entry'] == 'Yes') {
              if (itemFind) {
                if (parentindex == 0) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Significant Assets`]) {
                    itemFind[`Significant Assets`] =
                      item[`Significant Assets`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  itemFind[`Significant Locations`] = item[`Significant Locations`] || '';
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Magnitude`] = item[`Magnitude`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Opportunity Value`] = item[`Opportunity Value`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }
              } else {
                let itemFind = {};
                let answeredEntryFind = allAnsweredEntries.find(
                  item2 => item2['topic'] == item['Topic'],
                );
                if (answeredEntryFind) {
                  itemFind = {
                    ...itemFind,
                    ...answeredEntryFind,
                  };
                }

                if (parentindex == 0) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Significant Assets`]) {
                    itemFind[`Significant Assets`] =
                      item[`Significant Assets`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  itemFind[`Significant Locations`] = item[`Significant Locations`] || '';
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Magnitude`] = item[`Magnitude`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Opportunity Value`] = item[`Opportunity Value`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }

                selectedAnsweredEntry.push(itemFind);
              }
            }
          });
        });
      }

      const { surveyId, currentSurveyId, consultantId, selectedfinancialworkshop } = this.state;
      // const matrixWorkshopsRef = firebase
      //   .firestore()
      //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
      //   .doc(surveyId ? surveyId : currentSurveyId)
      //   .collection('financial-workshops')
      //   .doc(selectedfinancialworkshop.id);

      const updatedWorkshop = {
        ...selectedfinancialworkshop,
        answeredEntries: [
          ...selectedfinancialworkshop.answeredEntries,
          ...selectedAnsweredEntry,
        ].filter((item, index, self) => index === self.findIndex(t => t.id === item.id)),
      };

      this.setState({
        selectedfinancialworkshop: updatedWorkshop,
        loading: false,
      });

      const payload = [
        ...selectedfinancialworkshop.answeredEntries,
        ...selectedAnsweredEntry,
      ].filter((item, index, self) => index === self.findIndex(t => t.id === item.id));

      updateWorkshopProperty({
        surveyId,
        consultantId,
        workshopId: selectedfinancialworkshop.id,
        type: "financial",
        property: "answeredEntries"
      }, payload).then((res) => {
        console.log("submitted to api", res)
      }).catch(error => {
        console.log('error saving answered entries');
      });

      // matrixWorkshopsRef
      //   .update({
      //     answeredEntries: [
      //       ...selectedfinancialworkshop.answeredEntries,
      //       ...selectedAnsweredEntry,
      //     ].filter((item, index, self) => index === self.findIndex(t => t.id === item.id)),
      //   })
      //   .then(() => {
      //     console.log(`saved answered entries`);
      //   })
      //   .catch(error => {
      //     console.log('error saving answered entries');
      //   });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({ loading: false });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
      return;
    }
  };
saveFinancialWorkshopAnswerEntry = () => {
    const { surveyId, currentSurveyId, consultantId, selectedfinancialworkshop } = this.state;
    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('financial-workshops')
    //   .doc(selectedfinancialworkshop.id);

    const updatedWorkshop = {
      ...selectedfinancialworkshop,
      answeredEntries: [...selectedfinancialworkshop.answeredEntries],
    };

    const newWorkshops = Array.from(this.state.financialworkshops || []);
    const workshopIndex = newWorkshops.findIndex(item => item.id === updatedWorkshop.id);

    if (workshopIndex > -1) {
      newWorkshops[workshopIndex] = updatedWorkshop;

      this.setState({
        financialworkshops: newWorkshops,
        selectedfinancialworkshop: updatedWorkshop,
      });
    } else {
      this.setState({
        selectedfinancialworkshop: updatedWorkshop,
      });
    }

    saveToWorkshopAnswerEntry({
      surveyId,
      consultantId,
      workshopId: selectedfinancialworkshop.id,
      type: "financial",
    }, [...selectedfinancialworkshop.answeredEntries]).then((res) => {
      console.log("added to workshop entry", res)
    }).catch(error => {
      console.log('error saving entry');
    });

    // matrixWorkshopsRef
    //   .update({
    //     answeredEntries: [...selectedfinancialworkshop.answeredEntries],
    //   })
    //   .then(() => {
    //     console.log(`saved entry`);
    //   })
    //   .catch(error => {
    //     console.log('error saving entry');
    //   });
  };
handleFinancialWorkshopAnswerEntryChange = (e, item, key) => {
    const { selectedfinancialworkshop } = this.state;
    const itemFind = selectedfinancialworkshop?.answeredEntries?.find(
      item2 => item['id'] == item2['id'],
    );

    if (itemFind) {
      if (key) {
        itemFind[key] = e;

        this.setState({
          selectedfinancialworkshop: {
            ...selectedfinancialworkshop,
            answeredEntries: [...selectedfinancialworkshop.answeredEntries],
          },
        });

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      this.setState({
        selectedfinancialworkshop: {
          ...selectedfinancialworkshop,
          answeredEntries: [...selectedfinancialworkshop.answeredEntries],
        },
      });
    } else {
      const itemFind = {
        ...item,
      };
      let newAnsweredEntries = [];

      if (selectedfinancialworkshop.answeredEntries) {
        newAnsweredEntries = [...selectedfinancialworkshop.answeredEntries];
      }

      if (key) {
        itemFind[key] = e;

        newAnsweredEntries.push(itemFind);
        selectedfinancialworkshop.answeredEntries = newAnsweredEntries;

        this.setState({
          selectedfinancialworkshop: {
            ...selectedfinancialworkshop,
            answeredEntries: [...newAnsweredEntries],
          },
        });

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      newAnsweredEntries.push(itemFind);
      selectedfinancialworkshop.answeredEntries = newAnsweredEntries;

      this.setState({
        selectedfinancialworkshop: {
          ...selectedfinancialworkshop,
          answeredEntries: [...newAnsweredEntries],
        },
      });
    }
  };
 saveWorkshopAnswerEntry = () => {
    const { surveyId, currentSurveyId, consultantId, selectedworkshop } = this.state;

    console.log("selectedworkshop in saveWorkshopAnswerEntry", selectedworkshop)
    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('workshops')
    //   .doc(selectedworkshop.id);

    const updatedWorkshop = {
      ...selectedworkshop,
      answeredEntries: [...selectedworkshop.answeredEntries],
    };

    const newWorkshops = Array.from(this.state.workshops || []);
    const workshopIndex = newWorkshops.findIndex(item => item.id === updatedWorkshop.id);

    if (workshopIndex > -1) {
      newWorkshops[workshopIndex] = updatedWorkshop;

      this.setState({
        workshops: newWorkshops,
        selectedworkshop: updatedWorkshop,
      });
    } else {
      this.setState({
        selectedworkshop: updatedWorkshop,
      });
    }

    saveToWorkshopAnswerEntry({
      surveyId,
      consultantId,
      workshopId: selectedworkshop.id,
      type: "impact",
    }, [...selectedworkshop.answeredEntries]).then((res) => {
      console.log("added to workshop entry", res)
    }).catch(error => {
      console.log('error saving entry');
    });

    // Create POST api to answeredEntries in Porfolio-survey-consultatnts/survey Models or WorkshopsModel?
    // matrixWorkshopsRef
    //   .update({
    //     answeredEntries: [...selectedworkshop.answeredEntries],
    //   })
    //   .then(() => {
    //     console.log(`saved entry`);
    //   })
    //   .catch(error => {
    //     console.log('error saving entry');
    //   });
  };
handleWorkshopWorksheetChange = (e, item, key) => {
    console.log("handleWorkshopWorksheetChange", item, e, key);
    const { selectedworkshop, surveyId, consultantId, answeredTopics } = this.state;
    console.log("selectedworkshop", selectedworkshop);
    const itemFind = selectedworkshop.worksheet.find(item2 =>
      item['id'] ? item['id'] == item2['id'] : item['code'] == item2['code'],
    );

    // console.log('e', e);
    // console.log('item', item);
    // console.log('key', key);
    console.log('itemFind', itemFind);

    if (itemFind) {
      console.log("edit condition entered");
      if (key) {
        itemFind[key] = e;

        this.setState({
          selectedworkshop: { ...selectedworkshop, worksheet: [...selectedworkshop.worksheet] },
        });

        // console.log('item', item);
        // console.log('itemFind', itemFind);
        // console.log('selectedworkshop.worksheet', selectedworkshop.worksheet);

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      this.setState({
        selectedworkshop: { ...selectedworkshop, worksheet: [...selectedworkshop.worksheet] },
      });

      const newAnswered = Array.from(this.state.answeredTopics || []);
      const answerData = newAnswered.find(ans => ans.id === item.id);
      console.log("answerData in edit condition", answerData)
      if (answerData) {
        answerData[e.target.name] = e.target.value;
        console.log('3');
        this.setState({
          answeredTopics: newAnswered,
        });
        const workshopId = selectedworkshop.id;

        editAnsweredTopicComment(
          {
            surveyId,
            consultantId,
            workshopId,
          },
          itemFind,
        )
          .then(response => {
            console.log('Added new comment', response);
          })
          .catch(error => {
            console.log('error adding new row');
          });

        // const matrixWorkshopsRef = firebase
        //   .firestore()
        //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId);

        // matrixWorkshopsRef
        //   .update({
        //     answeredTopics: newAnswered,
        //   })
        //   .then(() => {
        //     console.log(`Added new row`);
        //   })
        //   .catch(error => {
        //     console.log('error adding new row');
        //   });
      }
    }
    // Add new entry
    else {
      console.log("Add new entry");
      const itemFind = {
        ...item,
      };

      const newWorksheet = [...selectedworkshop.worksheet];

      if (key) {
        itemFind[key] = e;

        newWorksheet.push(itemFind);
        selectedworkshop.worksheet = newWorksheet;

        this.setState({
          selectedworkshop: { ...selectedworkshop, worksheet: [...newWorksheet] },
        });

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      newWorksheet.push(itemFind);
      selectedworkshop.worksheet = newWorksheet;

      this.setState({
        selectedworkshop: { ...selectedworkshop, worksheet: [...newWorksheet] },
      });

      console.log("answeredTopics in state", answeredTopics)
      const newAnswered = Array.from(answeredTopics || []);
      console.log("newAnswered", newAnswered)
      const answerData = newAnswered.find(ans => ans.id === item.id);
      console.log("answerData", answerData)
      console.log("itemFind", itemFind)
      if (answerData) {
        answerData[e.target.name] = e.target.value; doubt
        console.log('5');
        this.setState({
          answeredTopics: newAnswered,
        });

        addAnsweredTopicComment({
          surveyId,
          consultantId,
        }, itemFind)
          .then(response => {
            console.log('Added new comment', response);
          })
          .catch(error => {
            console.log('error adding new row');
          });

        // const matrixWorkshopsRef = firebase
        //   .firestore()
        //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId);

        // matrixWorkshopsRef
        //   .update({
        //     answeredTopics: newAnswered,
        //   })
        //   .then(() => {
        //     console.log(`Added new row`);
        //   })
        //   .catch(error => {
        //     console.log('error adding new row');
        //   });
      }
    }
  };
confirmdeleteworkshop = async () => {
    const { surveyId, currentSurveyId, consultantId, workshops, workshopdata } = this.state;

    this.setState({
      showdeleteworkshopmodal: false,
      loading: true,
    });

    try {
      // Delete workshop if already present
      if (workshopdata && workshopdata.id) {
        // await firebase
        //   .firestore()
        //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(surveyId ? surveyId : currentSurveyId)
        //   .collection('workshops')
        //   .doc(workshopdata.id)
        //   .delete()
        //   .then(() => {
        //     this.handleAddAuditLog(
        //       'delete',
        //       this.state.assessmentType,
        //       'Assessment',
        //       `${this.state.user.name} deleted the worksheet of ${workshopdata['Name of Person']} (${workshopdata.id})`,
        //       'worksheet',
        //     );
        //   });

        // Delete existing workshop
        const response = await removeWorkshop("workshop", {
          surveyId: surveyId,
          consultantId: consultantId,
          workshopId: workshopdata.id,
        });

        this.handleAddAuditLog(
          'delete',
          this.state.assessmentType,
          'Assessment',
          `${this.state.user.name} deleted the worksheet of ${workshopdata['Name of Person']} (${workshopdata.id})`,
          'worksheet',
        );

        const deleteIndex = workshops.findIndex(item => item.id == workshopdata.id);
        workshops.splice(deleteIndex, 1);
        this.setState({
          loading: false,
          workshopdata: {},
          workshops: [...workshops],
        });
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({
        loading: false,
        workshopdata: {},
      });
    }
  };
confirmdeletefinancialworkshop = async () => {
    const {
      surveyId,
      currentSurveyId,
      consultantId,
      financialworkshops,
      financialworkshopdata,
    } = this.state;

    this.setState({
      showdeletefinancialworkshopmodal: false,
      loading: true,
    });

    try {
      if (financialworkshopdata && financialworkshopdata.id) {
        // await firebase
        //   .firestore()
        //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(surveyId ? surveyId : currentSurveyId)
        //   .collection('financial-workshops')
        //   .doc(financialworkshopdata.id)
        //   .delete()
        //   .then(() => {
        //     this.handleAddAuditLog('delete', this.state.assessmentType, 'Assessment', `${this.state.user.name} deleted the worksheet of ${financialworkshopdata['Name of Person']} (${financialworkshopdata.id})`, 'worksheet');
        //   })

        const response = await removeWorkshop("financial", {
          surveyId: surveyId,
          consultantId: consultantId,
          workshopId: financialworkshopdata.id
        });

        if (response.status === 200) {
          this.handleAddAuditLog(
            'delete',
            this.state.assessmentType,
            'Assessment',
            `${this.state.user.name} deleted the worksheet of ${financialworkshopdata['Name of Person']} (${financialworkshopdata.id})`,
            'worksheet',
          );

        }


        const deleteIndex = financialworkshops.findIndex(
          item => item.id == financialworkshopdata.id,
        );
        financialworkshops.splice(deleteIndex, 1);
        this.setState({
          loading: false,
          financialworkshopdata: {},
          financialworkshops: [...financialworkshops],
        });
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({
        loading: false,
        financialworkshopdata: {},
      });
    }
  };
handleSubmitFinancialWorkshop = async e => {
    const {
      financialworkshops,
      financialworkshopdata,
      surveyId,
      currentSurveyId,
      consultantId,
    } = this.state;
    // const matrixFinancialWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('financial-workshops');

    e.preventDefault();

    this.setState({
      loading: true,
      financialWorkshopTabIndex: 0,
    });

    const formatDate = (date) => {
      if (!date) return null;
      const d = date.seconds ? new Date(date.seconds * 1000 + date.nanoseconds / 1000000) : new Date(date);
      const month = ('0' + (d.getMonth() + 1)).slice(-2);
      const day = ('0' + d.getDate()).slice(-2);
      const year = d.getFullYear();
      return `${month}/${day}/${year}`;
    };

    try {
      // Edit condition (if id exists)
      if (financialworkshopdata.id) {
        // const docRef = matrixFinancialWorkshopsRef.doc(financialworkshopdata.id);
        // const docSnapshot = await docRef.get();
        // const oldData = docSnapshot.data();

        const workshopData = await getWorkshopById("financial-workshops", {
          surveyId: surveyId,
          consultantId: consultantId,
          id: financialworkshopdata.id,
        });

        const oldData = workshopData.data();
        const _date = financialworkshopdata['Date of Workshop or Interview'];
        const payload = {
          ...financialworkshopdata,
          answeredEntries: financialworkshopdata?.answeredEntries ? financialworkshopdata?.answeredEntries : [],
          ['Date of Workshop or Interview']:
            _date && _date.seconds
              ? new Date(_date.seconds * 1000 + _date.nanoseconds / 1000000)
              : _date,
          date: new Date(),
        };

        // await matrixFinancialWorkshopsRef.doc(financialworkshopdata.id).update(payload)
        // )

        await updateFinancialWorkshops(consultantId, financialworkshopdata.id, payload)

        const changes = [];
        // const oldDateFormatted = formatDate(oldData['Date of Workshop or Interview']);
        // const newDateFormatted = formatDate(financialworkshopdata['Date of Workshop or Interview']);
        const oldDateFormatted = oldData['Date of Workshop or Interview'];
        const newDateFormatted = financialworkshopdata['Date of Workshop or Interview'];

        if (financialworkshopdata['Name of Person'] !== oldData['Name of Person']) {
          changes.push(`Name of Person changed from ${oldData['Name of Person']} to ${financialworkshopdata['Name of Person']}`);
        }
        if (financialworkshopdata['Stakeholder Type'] !== oldData['Stakeholder Type']) {
          changes.push(`Stakeholder Type changed from ${oldData['Stakeholder Type']} to ${financialworkshopdata['Stakeholder Type']}`);
        }
        if (financialworkshopdata['Type'] !== oldData['Type']) {
          changes.push(`Type changed from ${oldData['Type']} to ${financialworkshopdata['Type']}`);
        }


        if (financialworkshopdata['Interviewer Name'] !== oldData['Interviewer Name']) {
          changes.push(`Interviewer Name changed from ${oldData['Interviewer Name']} to ${financialworkshopdata['Interviewer Name']}`);
        }

        if (newDateFormatted !== oldDateFormatted) {
          changes.push(`Date of Workshop or Interview changed from ${oldDateFormatted} to ${newDateFormatted}`);
        }

        if (financialworkshopdata['Comments'] !== oldData['Comments']) {
          const oldcomment = oldData['Comments'] || 'Blank';
          changes.push(`Comments changed from ${oldcomment} to ${financialworkshopdata['Comments']}`);
        }
        if (financialworkshopdata['Recommendations'] !== oldData['Recommendations']) {
          const oldrec = oldData['Recommendations'] || 'Blank';
          changes.push(`Recommendations changed from ${oldrec} to ${financialworkshopdata['Recommendations']}`);
        }

        this.handleAddAuditLog(
          'update',
          this.state.assessmentType,
          'Assessment',
          `${this.state.user.name} Updated worksheet of ${financialworkshopdata['Name of Person']} (${financialworkshopdata.id}) : ${changes} `,
          'worksheet',
        );

        const index = financialworkshops.findIndex(item => item.id == financialworkshopdata.id);

        financialworkshops[index] = payload;
        this.setState({
          loading: false,
          financialworkshopdata: {},
          financialworkshops: [...financialworkshops],
          selectedfinancialworkshop: payload,
          showfinancialworkshopmodal: false,
        });

        return;

      }


      // Add new financial Workshop
      const payload = {
        ...financialworkshopdata,
        ['Date of Workshop or Interview']:
          financialworkshopdata['Date of Workshop or Interview'] || new Date(),
        companyId: this.state.companyId,
        surveyId: surveyId,
        worksheet: [],
        date: new Date(),
      };

      // const { id } = await matrixFinancialWorkshopsRef.add(payload);

      const response = await setFinancialWorkshops(consultantId, payload)

      const answeredTopics = this.sortAnsweredTopics(this.state.answeredTopics || []);
      const payloadfinal = {
        ...payload,
        id: response.data.data.id,
        worksheet:
          payload.worksheet && payload.worksheet.length > 0
            ? payload.worksheet
            : answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      };

      this.handleAddAuditLog(
        'add',
        this.state.assessmentType,
        'Assessment',
        `${this.state.user.name} added worksheet for ${payloadfinal['Name of Person']} (${payloadfinal.id})`,
        'worksheet',
      );

      financialworkshops.push(payloadfinal);

      this.setState({
        loading: false,
        financialworkshopdata: {},
        financialworkshops: [...financialworkshops],
        showfinancialworkshopmodal: false,
        selectedfinancialworkshop: payloadfinal,
        financialWorkshopViewIndex: 1,
        answeredTopics: answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      });
    } catch (ex) {
      console.log(ex.message);
      this.setState({
        loading: false,
        financialworkshopdata: {},
        showfinancialworkshopmodal: false,
      });
    }
  };
#include <bits/stdc++.h>
using namespace std;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    int a;
    cin >> a;
    string n;
    cin >> n;
    int A = 0;
    int B = 0;
    for(int i =0; i < n.size(); i++){
        if(n[i] == 'a'){
            A = A + 1;
        }
        
        if(n[i] == 'b'){
            B = B + 1;
        }
    }
    cout << A << " " << B << " ";
    cout << n.size() / 2 - min(A,B);
    return 0;
}
#include <bits/stdc++.h>
using namespace std;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    int l;
    int r;
    int x;
    cin >> l >> r >> x;
    int ans = 1;
    int count = 0;
    while(ans <= r){
        if(ans >= r && ans <= r){
            cout << ans << " ";
            count = count + 1;
        }
        ans *= x;
    }
    if(count == 0){
        cout << "-1";
    }
    return 0;
}
import java.util.Arrays;
import java.util.Scanner;

class Job {
    int id;
    int deadline;
    int profit;

    Job(int id, int deadline, int profit) {
        this.id = id;
        this.deadline = deadline;
        this.profit = profit;
    }
}

public class JobScheduling {
    
    public static void scheduleJobs(Job[] jobs) {
        // Sort jobs based on profit in descending order
        Arrays.sort(jobs, (a, b) -> b.profit - a.profit);
        
        // Find the maximum deadline
        int maxDeadline = 0;
        for (Job job : jobs) {
            if (job.deadline > maxDeadline) {
                maxDeadline = job.deadline;
            }
        }
        
        // Create a slot array based on maximum deadline
        boolean[] slot = new boolean[maxDeadline];
        int[] result = new int[maxDeadline];

        for (Job job : jobs) {
            // Find a free slot for this job
            for (int j = Math.min(maxDeadline - 1, job.deadline - 1); j >= 0; j--) {
                if (!slot[j]) {
                    slot[j] = true;
                    result[j] = job.id; 
                    break;
                }
            }
        }

        // Output the scheduled jobs
        System.out.println("Scheduled Jobs:");
        for (int jobId : result) {
            if (jobId != 0) {
                System.out.print(jobId + " ");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of jobs: ");
        int n = sc.nextInt();

        Job[] jobs = new Job[n];
        System.out.println("Enter jobs (id, deadline, profit):");
        for (int i = 0; i < n; i++) {
            int id = sc.nextInt();
            int deadline = sc.nextInt();    
            int profit = sc.nextInt();
            jobs[i] = new Job(id, deadline, profit);
        }

        scheduleJobs(jobs);
        sc.close();
    }
}
 handleSubmitWorkshop = async e => {
    const { workshops, workshopdata, surveyId, currentSurveyId, consultantId } = this.state;
    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('workshops'); // -->

    e.preventDefault();

    this.setState({
      loading: true,
      workshopTabIndex: 0,
    });
    const formatDate = (date) => {
      if (!date) return null;
      const d = date.seconds ? new Date(date.seconds * 1000 + date.nanoseconds / 1000000) : new Date(date);
      const month = ('0' + (d.getMonth() + 1)).slice(-2);
      const day = ('0' + d.getDate()).slice(-2);
      const year = d.getFullYear();
      return `${month}/${day}/${year}`;
    };

    try {
      // Edit condition (check if id present in the current workshop displayed in the UI)
      if (workshopdata.id) {
        // const docRef = matrixWorkshopsRef.doc(workshopdata.id); // -->
        // const docSnapshot = await docRef.get(); // -->
        // const oldData = docSnapshot.data(); // --> 
        // console.log("old data from firebase", oldData);

        const workshopData = await getWorkshopById("workshops", {
          surveyId: surveyId,
          consultantId: consultantId,
          id: workshopdata.id,
        },)

        console.log("workshopdata", workshopData);


        // Get previous data from the workshops collection in DB
        const oldData = workshopData.data();

        const _date = workshopdata['Date of Workshop or Interview'];
        const payload = {
          ...workshopdata,
          answeredEntries: workshopdata?.answeredEntries ? workshopdata?.answeredEntries : [],
          ['Date of Workshop or Interview']:
            _date && _date.seconds
              ? new Date(_date.seconds * 1000 + _date.nanoseconds / 1000000)
              : _date,
        };

        // await matrixWorkshopsRef.doc(workshopdata.id).update(payload) // --> Replace with API call

        console.log("payload", payload);

        const response = await updateWorkshops(consultantId, workshopdata.id, payload);
        console.log("Response after editing workshop", response);

        const changes = [];
        // const oldDateFormatted = formatDate(oldData['Date of Workshop or Interview']);
        // const newDateFormatted = formatDate(workshopdata['Date of Workshop or Interview']);
        const oldDateFormatted = oldData['Date of Workshop or Interview'];
        const newDateFormatted = workshopdata['Date of Workshop or Interview'];

        if (workshopdata['Name of Person'] !== oldData['Name of Person']) {
          changes.push(`Name of Person changed from ${oldData['Name of Person']} to ${workshopdata['Name of Person']}`);
        }
        if (workshopdata['Stakeholder Type'] !== oldData['Stakeholder Type']) {
          changes.push(`Stakeholder Type changed from ${oldData['Stakeholder Type']} to ${workshopdata['Stakeholder Type']}`);
        }
        if (workshopdata['Type'] !== oldData['Type']) {
          changes.push(`Type changed from ${oldData['Type']} to ${workshopdata['Type']}`);
        }


        if (workshopdata['Interviewer Name'] !== oldData['Interviewer Name']) {
          changes.push(`Interviewer Name changed from ${oldData['Interviewer Name']} to ${workshopdata['Interviewer Name']}`);
        }

        if (newDateFormatted !== oldDateFormatted) {
          changes.push(`Date of Workshop or Interview changed from ${oldDateFormatted} to ${newDateFormatted}`);
        }

        if (workshopdata['Comments'] !== oldData['Comments']) {
          const oldcomment = oldData['Comments'] || 'Blank';
          changes.push(`Comments changed from ${oldcomment} to ${workshopdata['Comments']}`);
        }
        if (workshopdata['Recommendations'] !== oldData['Recommendations']) {
          const oldrec = oldData['Recommendations'] || 'Blank';
          changes.push(`Recommendations changed from ${oldrec} to ${workshopdata['Recommendations']}`);
        }

        this.handleAddAuditLog(
          'update',
          this.state.assessmentType,
          'Assessment',
          `${this.state.user.name} Updated worksheet of ${workshopdata['Name of Person']} (${workshopdata.id}) : ${changes} `,
          'worksheet',
        );

        const index = workshops.findIndex(item => item.id == workshopdata.id);

        workshops[index] = payload;
        this.setState({
          loading: false,
          workshopdata: {},
          workshops: [...workshops],
          selectedworkshop: payload,
          showworkshopmodal: false,
        });
        return;

      }

      // Add new workshop functionality
      const payload = {
        ...workshopdata,
        ['Date of Workshop or Interview']:
          workshopdata['Date of Workshop or Interview'] || new Date(),
        companyId: this.state.companyId,
        surveyId: surveyId,
        worksheet: [],
        date: new Date(),
      };

      // const { id } = await matrixWorkshopsRef.add(payload);
      // Submit new workshop to DB

      const response = await setWorkshops(consultantId, payload);

      const answeredTopics = this.sortAnsweredTopics(this.state.answeredTopics || []);
      const payloadfinal = {
        ...payload,
        id: response.data.data.id, // Find out what to enter here instead of id from firebase add call
        // id,
        worksheet:
          payload.worksheet && payload.worksheet.length > 0
            ? payload.worksheet
            : answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      };

      console.log("payloadfinal", payloadfinal);

      this.handleAddAuditLog(
        'add',
        this.state.assessmentType,
        'Assessment',
        `${this.state.user.name} added worksheet for ${payloadfinal['Name of Person']} (${payloadfinal.id})`,
        'worksheet',
      );

      workshops.push(payloadfinal);
      console.log("workshops", workshops);

      this.setState({
        loading: false,
        workshopdata: {},
        workshops: [...workshops],
        showworkshopmodal: false,
        selectedworkshop: payloadfinal,
        workshopViewIndex: 1,
        answeredTopics: answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      });
    } catch (ex) {
      console.log(ex?.message);
      this.setState({
        loading: false,
        workshopdata: {},
        showworkshopmodal: false,
      });
    }
  };
handleSubmitTabComment = async (e, type) => {
    e.preventDefault();
    this.setState({ loading: true });

    const allComments = Array.from(this.state.comments);

    const newComment = {
      date: new Date(),
      user: {
        name: this.state.user.username || this.state.user.name || 'N/A',
        companyId: this.state.user.companyId || 'N/A',
        id: this.state.user.id || 'N/A',
        email: this.state.user.email || 'N/A',
      },
      comment: this.state.tabcommentvalue,
      type: type,
    };

    allComments.push(newComment);

    allComments.sort((a, b) => new Date(b.date) - new Date(a.date));

    const { surveyId, currentSurveyId, consultantId } = this.state;
    // axios(this.postOptions(postUrl, newComment))
    addComment(
      {
        surveyId,
        consultantId,
      },
      newComment,
    )
      .then(response => {
        console.log('submitted response', response);
        this.setState({
          loading: false,
          showtabcommentmodal: {
            open: false,
            type: '',
          },
          tabcommentvalue: '',
          tabComments: allComments,
        });
        const summary = `${this.state.user.name} Added new comment ${newComment.comment}`;
        this.handleAddAuditLog(
          'add',
          this.state.assessmentType,
          'Assessment',
          summary,
          'Tab Comment',
        );
      })
      .catch(error => {
        this.setState({
          loading: false,
          showtabcommentmodal: {
            open: false,
            type: '',
          },
          tabcommentvalue: '',
          tabComments: allComments,
        });
      });

   
  };
 getSurveys = async (
    surveyId,
    filterByStakeholderTypeValue,
    filterByCountryValue,
    filterByContinentValue,
    consultantId,
  ) => {
    try {
      const { assessmentType } = this.state;

      // Fetch survey details
      const surveyDetails = await getbysurveyid(surveyId, consultantId);
      const survey = surveyDetails.data();
      console.log("survey", survey);
      const submittedSurveyResults = await getsubmittedSurveyResult(surveyId, consultantId);
      const tabComments = survey["tab-comments"] || []; 
      const surveyConditions = () => (Object.keys(survey).length > 0 && survey?.approvedTopics) ? survey?.approvedTopics : false;

      const workshops = await getSurveyResultForSubcollection(surveyId, consultantId, 'workshops')
      const financialWorkshops = await getSurveyResultForSubcollection(surveyId, consultantId, 'financial-workshops')

      // this.setState({
      //   survey: { ...survey, id: survey.id },
      //   // loading: false,
      // });

      // Object to hold all state changes to schedule the state updations
      const newState = {}
      console.log("newState 1", newState)

      newState.survey = { ...survey, id: survey.id }

      if (survey.answeredTopics) {
        let allTopics = survey?.surveyTopicsShort
          ? [
            ...survey.surveyTopicsShort.business,
            ...survey.surveyTopicsShort.social,
            ...survey.surveyTopicsShort.human,
            ...survey.surveyTopicsShort.environment,
            ...survey.surveyTopicsShort.leadership,
          ]
          : [];
        newState.materialityAssessmentTopics = survey.answeredTopics;
        newState.financialConsolidatedReports = [...survey.answeredTopics, ...allTopics]
          .filter((v, i, a) => a.findIndex(t => t.topic === v.topic && t.id === v.id) === i)
          .filter(item => item.entryType !== 'comment' && item.entryType !== 'added-entry')
          .sort((a, b) => {
            if (a.framework == 'CSRD') {
              let _a =
                CSRDAllTopics?.find(
                  item2 => item2['mainId'] == a['mainId'] && item2['topic'] == a['topic'],
                )?.sortIndex || 0;
              let _b =
                CSRDAllTopics?.find(
                  item2 => item2['mainId'] == b['mainId'] && item2['topic'] == b['topic'],
                )?.sortIndex || 0;

              return _a < _b ? -1 : _a > _b ? 1 : 0;
            }

            if (a.framework == 'GRI') {
              let _a = a.id;
              let _b = b.id;

              return _a < _b ? -1 : _a > _b ? 1 : 0;
            }

            if (a.topic < b.topic) return -1;
            if (a.topic > b.topic) return 1;
          })
          ?.sort((a, b) => {
            if (a.isCustom || b.isCustom) {
              // Move objects with 'isCustom' property to the end
              if (a.isCustom && !b.isCustom) {
                return 1;
              } else if (!a.isCustom && b.isCustom) {
                return -1;
              } else {
                // If both have 'isCustom' or neither have 'isCustom', sort by customSortId
                if (a.customSortId && b.customSortId) {
                  return a.customSortId > b.customSortId ? 1 : -1;
                } else {
                  return a.topic > b.topic ? 1 : -1;
                }
              }
            }
          })
          .sort((a, b) => {
            if (this.renderESG(a.dimension) == 'Environmental') return -1;
            if (this.renderESG(b.dimension) == 'Environmental') return 1;
            if (this.renderESG(a.dimension) == 'Social') return -1;
            if (this.renderESG(b.dimension) == 'Social') return 1;
            if (this.renderESG(a.dimension) == 'Governance') return -1;
            if (this.renderESG(b.dimension) == 'Governance') return 1;

            if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
            if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
          })
          .sort((a, b) => {
            if (this.renderESG(a.dimension) == 'Environmental') return -1;
            if (this.renderESG(b.dimension) == 'Environmental') return 1;
            if (this.renderESG(a.dimension) == 'Social') return -1;
            if (this.renderESG(b.dimension) == 'Social') return 1;
            if (this.renderESG(a.dimension) == 'Governance') return -1;
            if (this.renderESG(b.dimension) == 'Governance') return 1;

            if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
            if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
          });

        newState.allTopics = allTopics;
        newState.answeredTopics = survey.answeredTopics
          ? [...survey.answeredTopics, ...allTopics].filter(
            (v, i, a) => a.findIndex(t => t.topic === v.topic && t.id === v.id) === i,
          )
          : [];
        newState.addedCommentTopics = Array.from(survey.addedCommentTopics || []);

   
      } else {
        // this.setState({ loading: false });
      }





      const properties = {
        impactMaterialityMethodology: true,
        impactMaterialityScoringMethodology: true,
        financialMaterialityMethodology: true,
        financialMaterialityScoringMethodology: true,
        financialMappingMethodology: true,
        materialityAssessmentTopics: true,
        verifiedTopics: true,
        scoringSetting: true,
        reasonForMaxOrAverage: true,
        isNotFirstTimeOpeningImpactWorksheet: true,
        isNotFirstTimeOpeningFinancialWorksheet: true
      };

      for (const key in properties) {
        if (survey[key] !== undefined) {
          newState[key] = survey[key];
        }
      }

      // Default value for stakeholderTypes
      newState.stakeholderTypes = survey.stakeholderTypes || _stakeholderTypes;

      const getProperDate = date => {
        if (date.toDate) {
          return date.toDate();
        } else {
          return date;
        }
      };

      // Survey List operations
      this.handleSubmittedSurveyListOperation(submittedSurveyResults, surveyConditions)

      const workshopList = workshops.map(workshop => {
        return {
          ...workshop,
          id: workshop.id,
          answeredEntries: workshop?.['answeredEntries']?.map(itm => ({
            ...itm,
            Scale: itm['Scale'] == '0 - None' ? '1 - Minimal' : itm['Scale'] || '',
            Scope: itm['Scope'] == '0 - No impact' ? '1 - Limited' : itm['Scope'] || '',
            Likelihood:
              itm['Likelihood'] ==
                '0 - Very Unlikely (Has not occurred, and the possible chance of occuring is low)'
                ? '1 - Rare'
                : itm['Likelihood'] || '',
            Remediability:
              itm['Remediability'] == '0 - Very Easy to remedy'
                ? '1 - Relatively easy to remedy'
                : itm['Remediability'] || '',
          })),
        };
      });

      const financialWorkshopList = financialWorkshops.map(workshop => ({
        ...workshop,
        id: workshop.id,
        answeredEntries: workshop?.['answeredEntries']?.map(itm => ({
          ...itm,
          Likelihood:
            itm['Likelihood'] ==
              '0 - Very Unlikely (Has not occurred, and the possible chance of occuring is low)'
              ? '1 - Rare'
              : itm['Likelihood'] || '',
          Magnitude:
            itm['Magnitude'] == '0 - Not material (0%)'
              ? '1 - Minimal Impact'
              : itm['Magnitude'] || '',
        })),
      }));

      const tabCommentsList = tabComments.map(comment => {
        if (!comment.comment) return; // Workaround for damaged data --> remove once data is changed from DB

        return {
          ...comment,
          id: comment.id,
          // date: getProperDate(comment.date)
          date: comment.date.toDate ? comment.date.toDate() : comment.date,
        };
      });

      newState.workshops = workshopList
      newState.financialworkshops = financialWorkshopList
      newState.tabComments = tabCommentsList
      newState.loading = false

      console.log("newState", newState);

      this.setState(newState);

    
    } catch (ex) {
      this.setState({ loading: false });
    }
  };
star

Sat Sep 21 2024 19:41:22 GMT+0000 (Coordinated Universal Time) https://vuejs.org/guide/quick-start.html

@emilycoordoba #vue.js

star

Sat Sep 21 2024 18:00:03 GMT+0000 (Coordinated Universal Time)

@sunnywhateverr

star

Sat Sep 21 2024 16:04:46 GMT+0000 (Coordinated Universal Time)

@asha #react

star

Sat Sep 21 2024 15:03:10 GMT+0000 (Coordinated Universal Time)

@arutonee

star

Sat Sep 21 2024 11:27:29 GMT+0000 (Coordinated Universal Time)

@Rehbar #javascript

star

Sat Sep 21 2024 06:15:41 GMT+0000 (Coordinated Universal Time)

@WXCanada

star

Sat Sep 21 2024 05:47:23 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Sep 21 2024 02:52:33 GMT+0000 (Coordinated Universal Time) https://docs.dynamic.xyz/example-apps

@JohnPillix

star

Fri Sep 20 2024 21:28:30 GMT+0000 (Coordinated Universal Time) https://unofficialsf.com/build-lightning-styled-screen-flows-that-users-will-love/

@dannygelf #flow #salesforce #slds

star

Fri Sep 20 2024 21:20:17 GMT+0000 (Coordinated Universal Time)

@fededeleon #sql

star

Fri Sep 20 2024 20:24:14 GMT+0000 (Coordinated Universal Time) https://github.com/WordPress/WordPress/blob/master/index.php

@systemsroncal

star

Fri Sep 20 2024 20:16:49 GMT+0000 (Coordinated Universal Time)

@cc.garylau831

star

Fri Sep 20 2024 17:35:37 GMT+0000 (Coordinated Universal Time) undefined

@lndarl28

star

Fri Sep 20 2024 16:05:04 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri Sep 20 2024 16:02:56 GMT+0000 (Coordinated Universal Time)

@freepythoncode ##python #coding #python #programming #game

star

Fri Sep 20 2024 14:02:28 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@deshmukhvishal2

star

Fri Sep 20 2024 08:49:34 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Sep 20 2024 08:12:57 GMT+0000 (Coordinated Universal Time) https://maticz.com/white-label-crypto-exchange

@HenryJames

star

Fri Sep 20 2024 08:12:27 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@deshmukhvishal2

star

Fri Sep 20 2024 07:02:08 GMT+0000 (Coordinated Universal Time)

@peterjhonsonpj

star

Fri Sep 20 2024 06:44:21 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/

@sivaprasadm203 #blockchain #cryptocurrency #defi #web3

star

Fri Sep 20 2024 05:27:50 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.expert/

@steve1997 #elixir

star

Fri Sep 20 2024 00:24:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/67045764/how-can-i-remove-white-spaces-between-words

@dannygelf #sheets #googlesheets

star

Thu Sep 19 2024 23:55:16 GMT+0000 (Coordinated Universal Time)

@gbritgs

star

Thu Sep 19 2024 23:43:17 GMT+0000 (Coordinated Universal Time) https://www.onlinegdb.com/edit/sXLBZW-Wda

@realGuyCrimson

star

Thu Sep 19 2024 22:09:36 GMT+0000 (Coordinated Universal Time)

@madgakantara #r

star

Thu Sep 19 2024 20:16:29 GMT+0000 (Coordinated Universal Time)

@mebean #flutter #laravel #api #http #2lancer

star

Thu Sep 19 2024 14:33:08 GMT+0000 (Coordinated Universal Time)

@FXA

star

Thu Sep 19 2024 13:40:09 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Thu Sep 19 2024 12:35:53 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 12:13:58 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 12:13:20 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 11:35:26 GMT+0000 (Coordinated Universal Time)

@Curable1600 #windows

star

Thu Sep 19 2024 11:26:24 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 11:26:05 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 09:54:15 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 09:53:08 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 09:52:40 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 08:48:30 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 08:47:41 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 08:40:51 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 05:50:03 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Thu Sep 19 2024 05:40:30 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Thu Sep 19 2024 05:20:01 GMT+0000 (Coordinated Universal Time)

@signup

star

Thu Sep 19 2024 04:47:27 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 04:36:22 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 04:35:18 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

Save snippets that work with our extensions

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