Saturday, December 31, 2022

What is the difference between LINQ methods that start with "As" and those that start with "To"?

 LINQ is a set of extension methods for the .NET Framework that allow developers to query data from various sources using a consistent syntax.

The methods that start with "As" generally return a new sequence that is a projection of the original sequence, with each element in the new sequence being a transformation of the corresponding element in the original sequence. These methods do not perform any conversion, but rather just change the way the data is presented. For example, the AsEnumerable() method returns the input sequence as an IEnumerable<T>, regardless of its original type.

On the other hand, the methods that start with "To" perform a conversion of the input sequence to a new type or format. These methods often involve creating a new collection or data structure to store the elements of the input sequence, and as such may have a performance impact. For example, the ToList() method converts an input sequence to a List<T>, and the ToDictionary() method converts an input sequence to a Dictionary<TKey, TValue>.

Does IEnumerable.ToList() have performance impacts ?

 ToList() creates a new List object and copies all the elements from the source IEnumerable<T> into the new List. This means that it has to iterate through all the elements in the source IEnumerable<T>, which has a time complexity of O(n), where n is the number of elements in the source IEnumerable<T>.

This can have a performance impact, especially if the source IEnumerable<T> is large and the operation is being performed frequently. In these cases, it may be more efficient to use a different approach, such as using a loop to add the elements to the List manually, or using a different data structure that allows for more efficient insertion and retrieval of elements.

However, in many cases the performance impact of ToList() will not be significant, especially if the source IEnumerable<T> is small or the operation is only being performed infrequently. It is generally a good idea to use ToList() when you need to work with a List rather than an IEnumerable<T>, as it can make the code more readable and easier to work with.

List Capacity vs Count

 That's correct! In the .NET framework, the List<T> class is implemented as an array that grows dynamically as items are added to it. The Capacity property represents the size of the underlying array, and the Count property represents the number of items that have been added to the list.


When you add an item to the list and the list is already at capacity, the List<T> class will automatically double the size of the underlying array and copy all of the items from the old array to the new one. This process is known as "resizing the array."


It's important to note that the Capacity property is not the same as the Count property. The Capacity property represents the size of the underlying array, while the Count property represents the number of items that have been added to the list. The Count property will always be less than or equal to the Capacity property.


For example, if you have a list with a capacity of 10 and you add 5 items to it, the Count property will be 5 and the Capacity property will be 10. If you then add another item to the list, the list will automatically resize the array and the Capacity property will be increased to 20. However, the Count property will still be 6.

Tuesday, December 27, 2022

Dependency Injection (DI)


The Dependency Injection pattern is a particular implementation of Inversion of Control. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).



Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.



The advantages of using Dependency Injection pattern and Inversion of Control are the following:
  • Reduces class coupling
  • Increases code reusing
  • Improves code maintainability
  • Improves application testing

    The principle say that "High level module should not depend upon the low level module, both should depend on abstraction. Details should depends upon abstraction". 



    Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor or via property setters, and you make it somebody else's problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph). A dependency as I'm using it here is any other object the current object needs to hold a reference to.
    One of the major advantages of dependency injection is that it can make testing lots easier. Suppose you have an object which in its constructor does something like:
    public SomeClass() {
        myObject = Factory.getObject();
    }
    
    This can be troublesome when all you want to do is run some unit tests on SomeClass, especially if myObject is something that does complex disk or network access. So now you're looking at mocking myObject but also somehow intercepting the factory call. Hard. Instead, pass the object in as an argument to the constructor. Now you've moved the problem elsewhere, but testing can become lots easier. Just make a dummy myObject and pass that in. The constructor would now look a bit like:
    public SomeClass (MyClass myObject) {
        this.myObject = myObject;
    }
    

C# DateTime from Excel turns into float number

 In Excel, dates and times are stored as a floating point number representing the number of days since the epoch date of January 1, 1970. This means that when you read a date or time value from an Excel file into a C# DateTime object, you will need to convert the floating point value to a DateTime object.


Here is an example of how you could do this in C#:


// Assume that the Excel date value is stored in a variable called "excelDate" // Convert the Excel date value to a DateTime object DateTime dateTime = DateTime.FromOADate(excelDate); // You can also use the following syntax to achieve the same result: // DateTime dateTime = new DateTime((long)(excelDate * 86400000) + new DateTime(1970, 1, 1).Ticks);


In this example, the FromOADate method is used to convert the Excel date value to a DateTime object. This method is part of the System.DateTime struct and takes a floating point value representing the number of days since the epoch date.

Alternatively, you can use the Ticks property of the DateTime struct and some simple math to convert the Excel date value to a DateTime object. In this case, the value is first converted to a number of ticks (multiplying it by the number of ticks per day), and then the resulting ticks are



How to make sure unmanaged memory release .net core ?

 In .NET Core, unmanaged memory is typically allocated and released through the use of pointers and the Marshal.AllocHGlobal and Marshal.FreeHGlobal methods. These methods are part of the System.Runtime.InteropServices namespace and are used to allocate and release unmanaged memory in the global heap.


To ensure that unmanaged memory is properly released, you should make sure to call the FreeHGlobal method when you are finished using the memory. You can do this in a finally block to ensure that the memory is released even if an exception is thrown. Here is an example of how you might use these methods to allocate and release unmanaged memory in .NET Core:



using System; using System.Runtime.InteropServices; namespace UnmanagedMemoryExample { class Program { static void Main(string[] args) { // Allocate unmanaged memory IntPtr ptr = Marshal.AllocHGlobal(1024); try { // Use the unmanaged memory here... } finally { // Release the unmanaged memory Marshal.FreeHGlobal(ptr); } } } }

Note that you should only use the global heap for small blocks of memory that are needed for a short period of time. For larger blocks of memory or for memory that is needed for a longer period of time, you should consider using the Marshal.AllocCoTaskMem method or creating a managed wrapper class that can be used to manage the memory.

It is also a good idea to use the using statement whenever possible to automatically release resources when they are no longer needed. This can help simplify your code and reduce the chances of resource leaks.

linq query to get maximum salary in employee list object

 Here is an example of how you could use LINQ (Language Integrated Query) to get the maximum salary in a list of employee objects in C#:


  using System.Linq;


// Assume that the list of employees is stored in a variable called "employees"


// Get the maximum salary from the list of employees

decimal maxSalary = employees.Max(e => e.Salary);


// You can also use the following syntax to achieve the same result:

// decimal maxSalary = (from e in employees select e.Salary).Max();



In this example, the Max method is used to get the maximum salary from the list of employees. The method takes a lambda expression that specifies the property to use for the comparison (in this case, the Salary property).


Alternatively, you can use a LINQ query to achieve the same result. The query uses the from and select clauses to specify the source collection and the property to select, and the Max method is used to get the maximum value.


Note that this code assumes that the employees list and the Employee class have already been defined and that the Employee class has a Salary property of type decimal. You will need to modify the code to match the structure of your own data.

Friday, December 23, 2022

How I can track shopify customer data journey for my own website to present right offers to customer ?

 There are several ways you can track customer data and use it to present personalized offers to customers on your Shopify website:


1. Use the Shopify Customer API: This API allows you to retrieve information about customers, including their purchase history, and use it to create personalized offers.

2. Use Shopify's built-in customer segments: You can use Shopify's built-in customer segments to segment your customers based on various criteria, such as location or purchase history, and then use this information to create personalized offers.

3. Use a customer data platform (CDP): A CDP is a software platform that allows you to collect, manage, and activate customer data across multiple channels and devices. With a CDP, you can create customer profiles that include data from multiple sources, such as online and offline interactions, and use this information to create personalized offers.

4. Use a marketing automation tool: Marketing automation tools allow you to automate your marketing campaigns and send personalized emails to customers based on their behavior and interests. You can use these tools to create targeted email campaigns and present personalized offers to customers.

Regardless of which approach you choose, it's important to ensure that you are complying with data privacy laws and regulations, such as the General Data Protection Regulation (GDPR) and the California Consumer Privacy Act (CCPA). You should also make sure to obtain customer consent before collecting and using their personal data.


How I can generate more leads for my hotel booking through using digital channels ?

There are several ways you can generate leads for your hotel booking through digital channels:

1.       Optimize your website: Make sure that your website is up-to-date and easy to navigate, as this will help to attract more visitors and convert them into leads.

 

2.       Use social media: Use social media platforms such as Facebook, Instagram, and Twitter to promote your hotel and its services. Make sure to post regular updates and engage with your followers to build a community around your brand.

 

3.       Use email marketing: Use email marketing to reach out to potential guests and promote your hotel's services. Make sure to segment your email list and personalize your emails to increase their effectiveness.

 

4.       Use paid advertising: Consider using paid advertising platforms such as Google AdWords and Facebook Ads to reach a wider audience and drive more traffic to your website.

 

5.       Optimize for search engines: Make sure that your website is optimized for search engines so that it appears at the top of search results when people search for hotels in your area. This can be done through search engine optimization (SEO) techniques such as keyword research and on-page optimization.

 

6.       Offer special deals and promotions: Consider offering special deals and promotions to attract potential guests and encourage them to book with you.

 

7.       Collaborate with local businesses and tourist attractions: Partner with local businesses and tourist attractions to offer package deals and attract more visitors to your area.

 

8.       Use online travel agencies (OTAs): Consider listing your hotel on online travel agencies (OTAs) such as Expedia and Booking.com, as these platforms can help you reach a wider audience and generate more leads.

 

By following these strategies, you should be able to generate more leads for your hotel booking through digital channels.


Idea of automation in digital marketing agency?

 


Automation in a digital marketing agency can refer to the use of technology and software tools to streamline and optimize various tasks and processes. Some examples of automation in a digital marketing agency may include:

 

Email marketing automation: Using tools to send personalized, automated emails to a large list of subscribers based on specific triggers, such as signing up for a newsletter or abandoning a shopping cart.

 

Social media automation: Scheduling and publishing social media posts in advance using tools like Hootsuite or Buffer.

 

Ad campaign automation: Using tools like Google Ads to set up and run automated ad campaigns based on specific targeting criteria and budget constraints.

 

SEO automation: Using tools like Ahrefs or SEMrush to automate keyword research, backlink analysis, and other SEO tasks.

 

 

 

 

Lead generation automation: Using tools like Leadformly or OptinMonster to create and publish customizable lead generation forms on a website, and then automating the process of capturing, storing, and following up with leads.

 

Content marketing automation: Using tools like HubSpot or Marketo to automate the distribution and promotion of blog posts, ebooks, and other content assets across various channels, such as social media, email, and paid advertising.

 

Website analytics and tracking automation: Using tools like Google Analytics to track and analyze website traffic and user behavior automatically, and then using that data to optimize marketing campaigns and improve the user experience.

 

Customer relationship management (CRM) automation: Using tools like Salesforce or Zoho CRM to manage and automate the process of tracking and interacting with customers, including tasks like lead scoring, segmentation, and personalized communication.

 

 

 

Landing page and form automation: Using tools like Unbounce or Leadpages to create and publish customizable landing pages and forms, and then automating the process of capturing and storing leads.

 

Influencer marketing automation: Using tools like Tribe or AspireIQ to automate the process of identifying, contacting, and collaborating with influencers on social media platforms.

 

Chatbot automation: Using tools like MobileMonkey or ManyChat to create and deploy chatbots on websites and social media platforms to automate customer interactions and support.

 

Marketing automation platform integration: Using tools like Zapier or Integromat to integrate various marketing automation tools and platforms, allowing for seamless communication and data transfer between different systems.

 

Reputation management automation: Using tools like Reputation.com or ReviewTrackers to automate the process of tracking and responding to online customer reviews and ratings across various platforms.

 

Personalization automation: Using tools like Qubit or Adobe Target to automate the process of delivering personalized content and experiences to website visitors based on their location, behavior, and other factors.

 

Lead nurturing automation: Using tools like Pardot or Act-On to automate the process of nurturing leads through the sales funnel with personalized communication and content based on their level of engagement and readiness to buy.

 

Event marketing automation: Using tools like Eventbrite or Cvent to automate the process of planning, promoting, and managing events, including tasks like registration, ticket sales, and email communication.

 

Customer segmentation automation: Using tools like Segment or Lytics to automate the process of dividing customers into different segments based on shared characteristics, allowing for more targeted and personalized marketing efforts.

 

Remarketing automation: Using tools like Google Ads or Facebook Ads to automate the process of targeting ads to website visitors who have previously shown interest in a product or service.

 

Customer service automation: Using tools like Zendesk or Freshdesk to automate the process of handling customer inquiries and complaints, including tasks like routing, prioritization, and resolution.

 

Video marketing automation: Using tools like Animoto or InVideo to automate the process of creating and editing professional-quality marketing videos, including tasks like selecting templates, adding images and text, and rendering the final product.

 

 

Overall, the goal of automation in a digital marketing agency is to save time, increase efficiency, and improve the accuracy and effectiveness of marketing campaigns. By automating certain tasks, digital marketers can focus on higher-level strategy and creative tasks, rather than getting bogged down in the details.

 

Thursday, July 7, 2022

how to make sure mysql use more ram in window server

  find your .ini file and increase the limit in innodb_buffer_pool_size  and dont forget to restart the service. 

Thursday, December 30, 2021

visual-studio-code-angular-node-prevent-debugger-from-stepping-into-library-cod

 https://code.visualstudio.com/updates/v1_8#_node-debugging 


https://code.visualstudio.com/updates/v1_8#_node-debugging 

Wednesday, January 6, 2021

How can I remove background from images using OpenCV python ?

import cv2

import numpy as np


#== Parameters =======================================================================

BLUR = 21

CANNY_THRESH_1 = 10

CANNY_THRESH_2 = 200

MASK_DILATE_ITER = 10

MASK_ERODE_ITER = 10

MASK_COLOR = (0.0,0.0,1.0) # In BGR format



#== Processing =======================================================================


#-- Read image -----------------------------------------------------------------------

img = cv2.imread('C:/Temp/person.jpg')

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)


#-- Edge detection -------------------------------------------------------------------

edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)

edges = cv2.dilate(edges, None)

edges = cv2.erode(edges, None)


#-- Find contours in edges, sort by area ---------------------------------------------

contour_info = []

_, contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

# Previously, for a previous version of cv2, this line was: 

#  contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

# Thanks to notes from commenters, I've updated the code but left this note

for c in contours:

    contour_info.append((

        c,

        cv2.isContourConvex(c),

        cv2.contourArea(c),

    ))

contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)

max_contour = contour_info[0]


#-- Create empty mask, draw filled polygon on it corresponding to largest contour ----

# Mask is black, polygon is white

mask = np.zeros(edges.shape)

cv2.fillConvexPoly(mask, max_contour[0], (255))


#-- Smooth mask, then blur it --------------------------------------------------------

mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)

mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)

mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)

mask_stack = np.dstack([mask]*3)    # Create 3-channel alpha mask


#-- Blend masked img into MASK_COLOR background --------------------------------------

mask_stack  = mask_stack.astype('float32') / 255.0          # Use float matrices, 

img         = img.astype('float32') / 255.0                 #  for easy blending


masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR) # Blend

masked = (masked * 255).astype('uint8')                     # Convert back to 8-bit 


cv2.imshow('img', masked)                                   # Display

cv2.waitKey()


#cv2.imwrite('C:/Temp/person-masked.jpg', masked)           # Save

how to blur background using opencv python

    import cv2

import numpy as np

img = cv2.imread("C:/my_pics/rahul.png")
blurred_img = cv2.GaussianBlur(img, (21, 21), 0)

mask = np.zeros((512, 512, 3), dtype=np.uint8)
mask = cv2.circle(mask, (258, 258), 100, np.array([255, 255, 255]), -1)

out = np.where(mask==np.array([255, 255, 255]), img, blurred_img)

cv2.imwrite("./out.png", out)

Monday, January 4, 2021

Which datatype should I use in c# while SQL column is money type

 The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.

You can use a decimal as follows:

decimal myMoney = 300.5m;

how to get total number of public properties in a class c#

 class MyClass

{  
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }

    public MyClass()
    {
        int count = this.GetType().GetProperties().Count();
        // or
        count = typeof(MyClass).GetProperties().Count();
    }
}

Monday, December 14, 2020

how to find the table name using column name in mysql

 SELECT DISTINCT TABLE_NAME 

FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';

Wednesday, December 2, 2020

linq error At least one object must implement IComparable

 Well, you're trying to use SortedSet<>... which means you care about the ordering. But by the sounds of it your Player type doesn't implement IComparable<Player>. So what sort order would you expect to see?

Basically, you need to tell your Player code how to compare one player with another. Alternatively, you could implement IComparer<Player> somewhere else, and pass that comparison into the constructor of SortedSet<> to indicate what order you want the players in. For example, you could have:

public class PlayerNameComparer : IComparer<Player>
{
    public int Compare(Player x, Player y)
    {
        // TODO: Handle x or y being null, or them not having names
        return x.Name.CompareTo(y.Name);
    }
}

Then:

// Note name change to follow conventions, and also to remove the
// implication that it's a list when it's actually a set...
SortedSet<Player> players = new SortedSet<Player>(new PlayerNameComparer());

linq orderby collection property

 IQueryable<Parent> data = context.Parents.OrderBy(p=>p.Children.OrderBy(chi => chi.Name).FirstOrDefault());

Tuesday, December 1, 2020

How to execute sql queries in workbench mysql ?

 If you are from MS SQL background and first time working with MySql , you may be struggling for finding the shortcut key to execute the sql query in workbench. 


Here is the short cut to execute the SQL query in workbench MySql. 

Default key mapping
  1. Execute (All or Selection) -> Ctrl + Shift + Enter.
  2. Execute Current Statement -> Ctrl + Enter.

Saturday, November 28, 2020

How to assign property value while initializing class in typescript

 While creating new object you want to set the value of few fields of class , then you can use following feature of typescript to do that : 


class Person {
    public name: string = "default"
    public address: string = "default"
    public age: number = 0;

    public constructor(init?:Partial<Person>) {
        Object.assign(this, init);
    }
}

let persons = [
    new Person(),
    new Person({}),
    new Person({name:"John"}),
    new Person({address:"Earth"}),    
    new Person({age:20, address:"Earth", name:"John"}),
];


Saturday, November 21, 2020

How to make sure application always run with admin access

 Most of the time it happen with programmer , that they forget to run the application (Visual Studio/VS Code or any other IDE) with admin access. Because of that in result they face weird errors. So instead of every time facing same issue again and again, we can set the application permission in such way that its always run with admin access. 


Here are the steps which you can use to make sure your application always run with admin access. 


how to make sure application always run with admin access


        1. Open Start.
        2. Search for the app that you want to run elevated.
        3. Right-click the top result, and select Open file location. ...
        4. Right-click the app shortcut and select Properties.
        5. Click on the Shortcut tab.
        6. Click the Advanced button.
        7. Check the Run as administrator option.

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...