Posts

Showing posts from 2024

host

import pandas as pd from datetime import datetime import os # Example DataFrame df_final = pd.DataFrame({     'Name': ['Alice', 'Bob', 'Charlie'],     'Age': [25, 30, 35],     'City': ['New York', 'Los Angeles', 'Chicago'] }) # Generate today's date in 'YYYY-MM-DD' format today = datetime.now().strftime("%Y-%m-%d") # Create a dynamic filename filename = f"{today}_data.csv" # Network drive path (Windows) network_folder = r"\\network_drive\shared_folder" # Full path to save the file full_path = os.path.join(network_folder, filename) # Save DataFrame to CSV try:     df_final.to_csv(full_path, index=False)     print(f"File saved successfully to {full_path}") except Exception as e:     print(f"Error saving file: {e}")

requirement.txt

import os # Path to the directory containing the downloaded packages package_dir = '/path/to/my_packages' # List to hold the package names and versions requirements = [] # Iterate over all files in the directory for filename in os.listdir(package_dir):     # Process .whl files     if filename.endswith('.whl'):         # Split the filename by dashes and underscores to extract the package name and version         parts = filename.split('-')         package_name = parts[0]         version = parts[1]         requirements.append(f'{package_name}=={version}')     # Process .tar.gz files     elif filename.endswith('.tar.gz'):         # Remove the .tar.gz and split the filename by dashes to extract the package name and version         parts = filename.replace('.tar.gz', '').split('-')         packa...

Optimizing Tableau Dashboard Performance in Web Applications: Strategies for Caching and Faster Load Times"

  Caching a Tableau dashboard that has been rendered within an iframe is difficult, but here are some suggestions you can look into to make things better and seem like the dashboard is cached: Browser Caching Make sure the server is configured to cache Tableau dashboard resources by using appropriate cache headers for the HTML, CSS, JS, and image resources that the dashboard uses. The browser will cache all those resources after the first load, thus making load times shorter for revisits. Via a Reverse Proxy You can configure a reverse proxy in front of your Tableau server, for example, Nginx or Apache. This reverse proxy can cache the dashboard resources; thus, on subsequent hits for the same dashboard, it serves that copy from the cache without going again to Tableau for the data. This setup drastically improves load times on successive visits. Loading the Dashboard You could preload the Tableau dashboard in the background of the application flow before the user even navigates to...

T

 # List of allowed fund names keep_fund_names = ["A", "B", "C", "D"] # Filter the funds to include only the allowed names keep_fund_names = {name: id for name, id in fund_names.items() if name in keep_fund_names}

Steps to create SSH key from git bash

Generating an SSH key in OpenSSH involves a few simple steps. Here’s how you can do it: 1. Open a Terminal If you're on Linux or macOS, you can use the built-in terminal. On Windows, you can use the Command Prompt, PowerShell, or Git Bash if you have Git installed. 2. Generate the SSH Key Pair Run the following command: bash Copy code ssh-keygen -t rsa -b 4096 -C "your_email@example.com" Here’s what each option means: -t rsa : Specifies the type of key to create, in this case, RSA. -b 4096 : Specifies the number of bits in the key, 4096 bits is a good choice for strong encryption. -C "your_email@example.com" : Adds a label to the key, usually your email address. 3. Choose a File Location After running the above command, you'll be prompted to choose a location to save the key. By default, it will be saved in ~/.ssh/id_rsa (on Linux or macOS) or in C:\Users\YourUserName\.ssh\id_rsa (on Windows). Press Enter to accept the default location, or specify a diff...

p

 import requests import json from requests.auth import HTTPBasicAuth # Define the GraphQL endpoint url = 'https://graphql-demo.mead.io/' # Define user ID and password for authentication user_id = 'your_user_id' password = 'your_password' # Define the GraphQL query with date range filter query = """ {   events(filter: { startDate: { gte: "2023-01-01" }, endDate: { lte: "2023-01-31" } }) {     id     name     date     location   } } """ # Perform the query with authentication response = requests.post(url, json={'query': query}, auth=HTTPBasicAuth(user_id, password)) data = response.json() # Print the result print(json.dumps(data, indent=2))

Last 30 days

SELECT      MIN(CalendarDate) AS StartDate FROM (     SELECT          TOP 30          DATEADD(DAY, -n, CAST(GETDATE() AS DATE)) AS CalendarDate     FROM (         SELECT              ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n         FROM              sys.objects     ) AS Numbers     WHERE          DATEPART(WEEKDAY, DATEADD(DAY, -n, CAST(GETDATE() AS DATE))) NOT IN (1, 7) -- 1 = Sunday, 7 = Saturday     ORDER BY          CalendarDate DESC ) AS Last30WorkingDays;

Formula

WITH DateSequence AS (     SELECT CAST(GETDATE() AS DATE) AS BusinessDate     UNION ALL     SELECT DATEADD(DAY, -1, BusinessDate)     FROM DateSequence     WHERE DATEADD(DAY, -1, BusinessDate) > DATEADD(DAY, -14, GETDATE()) -- Generate enough days to cover weekends ), BusinessDays AS (     SELECT BusinessDate     FROM DateSequence     WHERE DATENAME(WEEKDAY, BusinessDate) NOT IN ('Saturday', 'Sunday') ) SELECT MIN(BusinessDate) AS TMinus5BusinessDay FROM (     SELECT BusinessDate, ROW_NUMBER() OVER (ORDER BY BusinessDate DESC) AS RowNum     FROM BusinessDays ) AS NumberedBusinessDays WHERE RowNum = 5 OPTION (MAXRECURSION 100);

PROCEDURE GetTopResults

CREATE PROCEDURE GetTopOrBottomResults     @N INT,              -- Accepts number of top/bottom results     @OrderType VARCHAR(10) -- Accepts 'Top', 'Bottom', or 'All' AS BEGIN     SET NOCOUNT ON;     -- Determine the number of rows in the table if 'All' is specified     DECLARE @TotalRows INT;     SET @TotalRows = (SELECT COUNT(*) FROM YourTable);     -- Handle the 'All' case by setting @N to the total number of rows     IF @OrderType = 'All'     BEGIN         SET @N = @TotalRows;     END     -- Determine the query to execute based on the @OrderType parameter     IF @OrderType = 'Top' OR @OrderType = 'All'     BEGIN         -- Select top N results ordered by SomeColumn         SELECT TOP (@N) *         FROM YourTable         ...

CurrencyReference Table

 -- Create the CurrencyReference table CREATE TABLE CurrencyReference (     CurrencyDescription NVARCHAR(100),     CurrencyShortName CHAR(3) ); -- Insert all possible currency descriptions and their corresponding ISO codes INSERT INTO CurrencyReference (CurrencyDescription, CurrencyShortName) VALUES     ('Afghan Afghani', 'AFN'),     ('Albanian Lek', 'ALL'),     ('Algerian Dinar', 'DZD'),     ('Angolan Kwanza', 'AOA'),     ('Argentine Peso', 'ARS'),     ('Armenian Dram', 'AMD'),     ('Aruban Florin', 'AWG'),     ('Australian Dollar', 'AUD'),     ('Azerbaijani Manat', 'AZN'),     ('Bahamian Dollar', 'BSD'),     ('Bahraini Dinar', 'BHD'),     ('Bangladeshi Taka', 'BDT'),     ('Barbadian Dollar', 'BBD'),     ('Belarusian Ruble', 'BYN'),     ('Belize Dollar', ...

Python Dash App: Calculate Difference

 # Import necessary libraries import dash from dash import dcc, html from dash.dependencies import Input, Output, State # Initialize the Dash app app = dash.Dash(__name__) # Global default values DEFAULT_VALUE1 = 1000 DEFAULT_VALUE2 = 400 # Function to calculate the difference between two values def calculate_difference(value1, value2):     return value1 - value2 # Define the layout of the app app.layout = html.Div([     html.Div([         html.Label('Value1'),         dcc.Input(             id='input-box-1',              type='number',              value=DEFAULT_VALUE1,              placeholder='Enter first value'         ),     ]),     html.Div([         html.Label('Value2'),         dcc.Input(     ...

PowerShell Function to get the last business day from today's date

# Function to get the last business day from today's date function Get-LastBusinessDay {     # Get today's date     $today = Get-Date     # Determine the last business day based on today's day of the week     switch ($today.DayOfWeek) {         'Monday'   { $lastBusinessDay = $today.AddDays(-3) } # Last Friday         'Sunday'   { $lastBusinessDay = $today.AddDays(-2) } # Last Friday         'Saturday' { $lastBusinessDay = $today.AddDays(-1) } # Last Friday         default    { $lastBusinessDay = $today.AddDays(-1) } # Previous day     }     # Return the last business day     return $lastBusinessDay } # Get and print the last business day $lastBusinessDay = Get-LastBusinessDay Write-Output "The last business day from today's date is: $($lastBusinessDay.ToString('yyyy-MM-dd'))"

Grovey

@echo off @echo off REM Set environment variable to suppress the welcome screen set STREAMLIT_SERVER_HEADLESS=true  set STREAMLIT_BROWSER_GATHERUSAGESTATS=false REM Change to the directory containing your Streamlit app cd /d "C:\path\to\your\streamlit\app" REM Run the Streamlit app using the specified Python executable "C:\Python39\python.exe" -m streamlit run app.py REM Close the command prompt window after execution exit REM Change to the directory containing your Streamlit app cd /d "C:\path\to\your\streamlit\app" REM Run the Streamlit app using the specified Python executable "C:\Python39\python.exe" -m streamlit run app.py REM Keep the command prompt open after execution pause path - C:\Windows\System32\cmd.exe C:\path\to\your\batchfile Step 4: Configure the Service Using NSSM GUI Path : In the Application tab, for the Path field, browse to your cmd.exe executable, typically located at C:\Windows\System32\cmd.exe . Startup Directory : Set...

Step-by-Step Guide for Offline Installation of python packages

  Step-by-Step Guide for Offline Installation of Dash Step 1: Download All Required Packages and Dependencies Download Packages on an Online Machine : sh Copy code mkdir dash_packages pip download -d dash_packages dash This command downloads the dash package and all its dependencies into the dash_packages directory. Step 2: Transfer Packages to the Offline Environment Transfer the dash_packages Directory : Use a USB drive, external hard drive, or any other method to copy the dash_packages directory to the offline environment. Step 3: Install Packages in the Offline Environment Install Packages Using pip : sh Copy code pip install --no-index --find-links=dash_packages dash This command tells pip to install the dash package and its dependencies from the local dash_packages directory instead of looking for them online. Handling Complex Dependencies In some cases, a package may have very complex dependencies. Here’s how you can ensure all dependencies are captured: Use pip wit...

Power BI Interview Questions and Answers

  Power BI Interview Questions and Answers What is Power BI, and how does it differ from other BI tools? Answer: Power BI is a business analytics service by Microsoft that provides interactive visualizations and business intelligence capabilities. It allows users to connect to a wide variety of data sources, create reports and dashboards, and share insights across their organization. Unlike traditional BI tools, Power BI is cloud-based, making it easy to access and collaborate on data from anywhere. Explain the components of Power BI. Answer: The key components of Power BI include Power Query for data preparation, Power Pivot for data modeling, Power View for data visualization, and Power Map for geospatial analysis. These components work together seamlessly to help users transform raw data into meaningful insights. What are the different types of connections available in Power BI? Answer: Power BI supports various types of connections, including importing data from local files (su...