Showing posts with label How To. Show all posts
Showing posts with label How To. Show all posts

Thursday, October 07, 2021

Break the sleep and leave the scope immediately immediately!

I wanted to write a quick and dirty code... but I didn't want to make it lousy in execution. Had simple requirement: Run a piece of code in a separate thread every 6 seconds but have ability to terminate (almost) immediately. Like any other lousy programmer, I didn't want to implement a timer (which is lengthy process in  C++). So I stumbled upon a solution which uses std::future to terminate the sleep immediately and doesn't execute anything once the future times out. Even if I was using while loop instead of do..while, it would have come out of the scope immediately. I am publishing it here as my example is more clear and that "Bad bad code." is present in that solution. Happy programming!


to compile: > g++ -pthread test.cpp


#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
using namespace std;
void threadFunction(std::future<void> future){
   std::cout << "Starting the thread" << std::endl;
   do {
      std::cout << "Executing the thread....." << std::endl;
      //std::this_thread::sleep_for(std::chrono::milliseconds(6000)); //bad bad code
   } while (future.wait_for(std::chrono::milliseconds(6000)) == std::future_status::timeout);
   std::cout << "Thread Terminated" << std::endl;
}
main(){
   std::promise<void> signal_exit; //create promise object
   std::future<void> future = signal_exit.get_future();//create future objects
   std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future
   std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds
   std::cout << "Threads will be stopped soon...." << std::endl;
   signal_exit.set_value(); //set value into promise
   my_thread.join(); //join the thread with the main thread
   std::cout << "Doing task in main function" << std::endl;
}

Tuesday, September 22, 2020

Simple GroupBy Function in for Python

After a lot of research I found that Python has no good groupby function that you can use in a single line (like Linq GroupBy of C#). For that, I've made a sample reusable groupby function that works with one or more keys, I wouldn't say it has great performance (actually far from it). But, it works and it is easier to use :) 

You may want to make changes based on your input:

import copy
import itertools

def yogee_groupby(collkeys):

    copied_collection = copy.deepcopy(coll)
    master_key = ""

    if len(keys) > 1:
        copied_collection = copy.deepcopy(coll)
        for key in keys:
            master_key = master_key + key
        
        for an_element in copied_collection:
            element_key = ""
            for key in keys:
                element_key = element_key + an_element[key]
            an_element[master_key] = element_key
    else:
        master_key = keys[0]

    grouped = {}
    sorted_collection = sorted(copied_collection, key = lambda item: item[master_key])
    for k, g in itertools.groupby(sorted_collection,  lambda item: item[master_key]):
        group = list(g)
        if len(keys) > 1:
            for an_element in group:
                an_element.pop(master_key, None)
        
        grouped[k] = group
    return grouped


def test_groupby_2():
    test_data = [
        {
            "E1""V1",
            "E2""V2",
            "E3": ["V31","V32","V33","V34"],
            "E3": {"E31":"V31","E32""V32","E33""V33","E34":"V34"}
        },
        {
            "E1""W1",
            "E2""W2",
            "E3": ["W31","W32","W33","W34"],
            "E3": {"E31":"W31","E32""W32","E33""W33","E34":"W34"}
        },
        {
            "E1""V1",
            "E2""V2",
            "E3": ["VV31","VV32","VV33","VV34"],
            "E3": {"E31":"VV31","E32""VV32","E33""VV33","E34":"VV34"}
        },
        {
            "E1""V1",
            "E2""V22",
            "E3": ["X31","X32","X33","X34"],
            "E3": {"E31":"X31","E32""X32","E33""X33","E34":"X34"}
        },
    ]
    grouped = yogee_groupby(test_data, ["E1""E2"])
    print(grouped)
    grouped = yogee_groupby(test_data, ["E1"])
    print(grouped)

test_groupby_2()



Thursday, April 04, 2013

Firefox 20 Feature - Click To Play

If you, my friend, are annoyed by zillions of flash advertisements running on your browser for which you haven't subscribed, have a look at the latest version of Firefox 20. It has a hidden lovable feature called "Click To Play". If enabled, it will deactivate all Flash (and Java) plugins except the one which you select to activate in a page. I've a netbook ('cheap laptop') which cannot handle the army of flash advertisements so I chose to activate this hidden Click_To_Play feature on my recently updated Firefox.

How to Enable Click_To_Play:

  1. Open a new firefox tab and type "about:config" in address bar.
  2. Click on button which says "I will be careful" etc..
  3. Now search for Click_To_Play in "Search" box.
  4. Double click preference named "plugins.click_to_play". It will change value of the preference to 'true'.
  5. You are done. Go to any web site and click only the plugin which you know you want to activate.  
Happy Browsing and don't let the Flash ads bite!

Tuesday, September 11, 2012

Extract BINK to PNG Sequence (with transparency)


BINK movies are widely  used in games because they provide transparency in the video from long back. Sometime you have to reverse engineer the BINK file and get the PNGs out of (not JPEG but PNG with  transparency) the movie. I've used FFMpeg to get PNGs out of BINK (.bik format) file as followed.

1. Download latest ffmpeg static build from http://ffmpeg.zeranoe.com/builds/
2. Extract the .7z build to any folder.
3. Give this command to convert “my.bik” to “output” folder and %d is sequence number in output image.  %d will auto increment by one, you have to just give %d in the command.
ffmpeg.exe -i D:\my.bik D:\output\my_%d.png
Note that this is a general command which applies to any type of movie format supported by ffmpeg. There are hell lot of more things you can with ffmpeg. For example, your popular VLC is built using ffmpeg library :) 

Thursday, December 01, 2011

Floating/Fixed Table Header in HTML Page or Inside DIV control

I’ve looked a lot for finding a solution were we can float a header of a table so that the header always appears on the top no matter how down do I scroll.
All the ‘floating table header’ solution ‘mostly’ worked were full HTML body is getting the scroll but none of them worked which can work inside scrolling div. None!
So I though I can create one. The concept was simple, get the ‘onScroll’ even of Div control and change CSS “top” property of table header to current scrolled position of Div. 
Unfortunately, there are many browser issues. Like mozilla doesn’t like when table cells change their position. Chrome rendering issues shows two headers rows when scrolled up.
At last, after storming through the problems, I arrived on this complex but simplified solution which is mentioned below. Copy the content in a blank HTML file and see the fun.

<html> 
    <head> 
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" > </script> 
        <script  type="text/javascript"> 
            $(function() { 
                if($.browser.mozilla) 
                    //table row doean't float in firefox, div floats 
                    $(".floatingHeader" + " tr th div") 
                            .addClass("floatingStyle"); 
                else 
                    //table row can float in IE and Chrome 
                    $(".floatingHeader"+ " tr th") 
                            .addClass("floatingStyle"); 
            }); 
            function changeFloatingHeaderPosition(container, headerId) { 
                    if($.browser.webkit) //chrome rendering bug fix 
                        $("#"+headerId + " tr th") 
                            .css("visibility", "hidden"); 
                    if($.browser.mozilla) 
                        $("#"+headerId + " tr th div") 
                            .css("top", container.scrollTop); 
                    else 
                        $("#"+headerId + " tr th") 
                            .css("top", container.scrollTop); 
                    if($.browser.webkit) //chrome rendering bug fix 
                        $("#"+headerId + " tr th") 
                            .css("visibility", "visible"); 
            } 
     
      // Remove this method if you are using Jqeury earlier than 1.9
     (function() {
      var matched, browser;

      // Use of jQuery.browser is frowned upon.
      // More details: http://api.jquery.com/jQuery.browser
      // jQuery.uaMatch maintained for back-compat
      jQuery.uaMatch = function( ua ) {
   ua = ua.toLowerCase();

   var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
       /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
       /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
       /(msie) ([\w.]+)/.exec( ua ) ||
       ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
       [];

   return {
       browser: match[ 1 ] || "",
       version: match[ 2 ] || "0"
   };
      };

      matched = jQuery.uaMatch( navigator.userAgent );
      browser = {};

      if ( matched.browser ) {
   browser[ matched.browser ] = true;
   browser.version = matched.version;
      }

      // Chrome is Webkit, but Webkit is also Safari.
      if ( browser.chrome ) {
   browser.webkit = true;
      } else if ( browser.webkit ) {
   browser.safari = true;
      }

      jQuery.browser = browser;
  })();
        </script> 
        <style> 
            .floatingStyle 
            { 
                position:relative; 
                background-color:#829DC0; 
                top:0px; 
            } 
        </style> 
    </head> 
<body> 
    <div class="floatingContainer"     onscroll="changeFloatingHeaderPosition(this, 'idHeader' );"      style="height:150px; width: 100px;overflow:auto;"> 
        <table cellspacing=0 cellpadding=0> 
            <thead class="floatingHeader" id="idHeader"> 
                <tr> 
                    <th><div>Col1</div></th>                     <th ><div>Col2<div></th> 
                    <th ><div>Col3<div></th> 
                </tr> 
            </thead> 
            <tbody> 
                <tr><td>first_row</td><td>first_row</td><td>first_row</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr>             </tbody> 
        </table> 
</div></body><html>
Note: Dan/Kenji has written plugging for the same which might be useful to you. I've not verified if it works in all case but worth having a look. You can find it: here: http://www.redkitetechnologies.com/2013/03/floatingsticky-headers-for-visualforce-pageblocktable/

Tuesday, November 15, 2011

Find Missing Foreign Key References

If you database column naming convention says all foreign key columns must end with 'ID' then this is the query for you to find missing foreign key reference. E.g. PRIZE_ID means Foreign Key reference to PRIZE table.
SELECT 
    colT.TABLE_NAME , 
    colT.COLUMN_NAME 
FROM 
    INFORMATION_SCHEMA.COLUMNS AS colT 
WHERE 
    COLUMN_NAME LIKE '%id'
    AND 
    (colT.TABLE_NAME + colT.COLUMN_NAME) NOT IN
     ( SELECT 
          KOM.TABLE_NAME + KOM.COLUMN_NAME 
      FROM 
          INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS KOM)

Monday, June 21, 2010

Solve “You are not allowed to upload ‘FileName’. the requested file type: 'FileType’” problem on Vanilla Forum 1.x

Issue:

You get this exception when you try to upload any file in your Vanilla Forum (Version 1) using any Attachment extension :
You are not allowed to upload ‘FileName’. the requested file type: 'FileType’

Resolution 1:

Add specified type as allowed type. Steps to do so follow here:

  1. Note the 'FileType’ in the error message.
  2. Go to extensions\Attachments\default.php file in your Vanilla forum’s directory.
  3. Add appropriate entry in Context->Configuration['ATTACHMENTS_ALLOWED_FILETYPES'] list.
  4. Note that it’s also important that you give correct extensions for the mime type you are allowing as both, 'FilteType’ (i.e. mime type) and file extensions are corss checked in Framework code of vanilla forum.
  5. Save the file and test.

Resolution 2:

Remove check for allowed types. Note that this is not very safe for public forum but it’s ‘ok’ for internal forum with known and responsible user. Steps to do so follow here:

  1. Go to “library\Framework\Framework.Class.Uploader.php”  file.
  2. Find this line of code “if (!array_key_exists($FileType, $this->AllowedFileTypes))”  and comment this ‘if’ and ‘else’ of it. Yes you need to comment if AND else.
  3. Save the file and test.

Thursday, January 28, 2010

Fix "The project type not supported by this installation" blah blah blah after resetsettings command

Is your visual studio settings are messed up? You can reset your visual studio settings by starting it from visual studio command prompt:

devenv.exe /resetsettings

But often, WCF related stuff doesn't work after above command. When you open the WCF porject in your Visual Studio, you may get this error:
"The project type not supported by this installation" blah blah blah..

If you are the one who has done so, close the Visual Studio and run this command from visual studio command prompt:

devenv /ResetSkipPkgs

It should reset (i.e. remove in our case) the checks that should be skiped in order to open newer WCF project into your relatively older visual studio.

Tuesday, December 29, 2009

How to Fix Error 1606: Could not access network location

This error often comes while installing some software.
Scenario A: You are getting error 1606 saying "Could not access network location [Some environment variable with % in it]..." then these links may help you solve the issue.
http://support.microsoft.com/default.aspx/kb/330766
and
http://support.microsoft.com/kb/256986/


Scenario B: You are getting error 1606 saying it cannot access internet location. But you can download same file using internet explorer,
1. Try hitting 'Retry' button. You may be in luck.
2. Not solved yet? Most probably you are behind proxy server. To solve this issue, go to Control Panel -> Internet Options -> Connections -> LAN Settings. What do you see? Is "Automatic Detect Setting" checked? If yes then uncheck it and see if your installation works. If it still doesn't work, contact your network administrator and manually provide proxy IP and Port in the LAN Settings of Internet Options.

Still not working? Please find solution and put your solution here :)

Tuesday, September 15, 2009

Get Exception without being in catch block

In .NET, when exception is thrown, the exception passed though the call stacks. While debugging you may not be inside the catch block (may be in finally) or you may not have catch block at all. But if you want to still see what exception occurred then just go to 'watch' window in visual studio and type '$exception' and you will get the exception as it is.

Happy Debugging!

ps: I got this trick free from my ex-colleague Manish

Sunday, August 09, 2009

Syntax Highlighter on Blogger

At last, I got source Syntax Highlighter on my blog. Adding script in Gadget didn't work for me as I couldn't add <link> tag in HTML/Javascript gadget. Then I tried adding script in template itself and it works like a charm :)


function test() : String
{
return 10;
}

Tuesday, May 12, 2009

About CProxyType*_NHibernate_ProxyINHibernateProxy_System_Runtime_SerializationISerializable2

Are you getting this exception while debugging on Visual Studio?
CProxyType*ENTITY_FULL_NAME*_NHibernate_ProxyINHibernateProxy_System_Runtime_SerializationISerializable2

Are you worried? Are you banging your head? Don't worry now, I have a solution for you! Follow as described below (step by step):
Step 1. Stop Debugging. Sometime NHibernate doesn't load lazy loaded entity during debug (specially in 'watch' or 'quick watch'). Test your code at runtime like Message Pop-up box or Console.Write etc
Step 2. Take a cup of tea.

Wednesday, December 17, 2008

Clear MSSQL Server Query Cache

NOTE: Strictly not for production servers and I mean it.

If you are first time optimizing query or choosing right index then you must know that SQL Server gives result from it's caches if query was already fired once. This is very useful feature but this behavior may tempt you to take wrong decision if this happens outside your knowledge.
You must see:

1. DBCC DROPCLEANBUFFERS -- Cleans temp buffers and dirty data.  You may want to use CHECKPOINT before this command. http://msdn.microsoft.com/en-us/library/ms187762.aspx

2. DBCC FREEPROCCACHE -- Use this to clear execution plans http://msdn.microsoft.com/en-us/library/ms174283.aspx 

I've not given FREEPROCCACHE with parameters which you may or may not be interested in but you should check out the link of microsoft site given there.

NOTE: Strictly not for production servers and I mean it.

Tuesday, October 07, 2008

Secure Your Wireless Internet

Note: Tips applicable for home networking only.
Here are some tips to secure your Internet sharing using Wi-Fi, securing not just for namesake but for real.

Tips for Securing router:
1. Make sure you change user name & password of your router. Remember, any obvious password or password that can be cracked by simple brute force techniques.
2. Restrict “Remote Access” of your router by which people can access your router without being part of your network.
3. You will get many option for Wi-Fi security out of which WEP (Wired Equivalent Privacy) being default. Don’t go on name, WEP is the security which only dumb cannot crack. Use any of WPA (Wi-Fi Protected Access). WPA can also be cracked if the password is weak.
4. Last but not least, don’t lure hackers. Switch off your modem and router when not in use.

Suggestion for strong password:
I know this need not to be a part of this discussion but if you use weak password, no security can help you. A good brute force with proper dictionary can crack these easily.
Do:
1. Mixture of Capital and Small letter, special character
2. Password length should be at least 8 character
3. For longer password, use 256 bit encryption technique
4. You are lucky if you are from non-English speaking country as you can have words which does not exist in common world list for bruit force attack. Use these words freely.
5. Try to have less used letter i.e. ‘x’ or ‘f’ or ‘q’ etc

Don’t:
1. Part of a password with complete English word. e.g. say no to ‘EightNineTen’
2. Password having any (key) sequence e.g. say no to ‘xxx1234’ or ‘xxx!@#$’ or ‘asdf’
3. Password having any obvious personal information e.g. say not to password with birth year
4. Password having repeating words i.e. say no to “IndiaIndia11”

Wednesday, September 17, 2008

Get List of File Associated with multiple Changesets

I wrote a cmdlet for powershell by which you can get list of file associated with list of changesets.
param(
[string] $changesets = $(throw 'Usage: Get-Changeset-Files 'changesets')
)

process
{
# get TFS object
$tfs = get-tfs ;

# build up list of file items
$fileItems = @();

$changesets.Split(',') | foreach {
$tfs.vcs.GetChangeset($_).Changes | foreach {
if($fileItems -notcontains $_.Item.ServerItem) {
$fileItems += $_.Item.ServerItem;
}
}
}
return $fileItems | Sort-Object;
}


Steps:
1. Create a file Get-Changeset-Files.ps1 and copy above code in the file (preferably where get-tfs resides). Also add this directory into your $path
2. Open Powershell, go to Directory where above file recides
3. Run 'Set-ExecutionPolicy unrestricted' so that you can run above cmdlet
4. Everything is ready.. just run for example: Get-Changeset-Files('10, 20, 30')

See here for get-tfs.ps1

Tuesday, September 02, 2008

Vertical Text Selection

You may need to do sometime vertical selection. For example, in example below, I want to select and remove all “SolidX”.


I need to do vertical selection for this. Selecting text vertically not commonly used but an excellent functionality provided by all serious text editors.

This is how to do it (Windows specific): Hold ALT and SHIFT key and select the text vertically and horizontally. It is not important whether you select first vertically or horizontally but you MUST press and hold ALT key before SHIFT key.

You can do this on all modern Code editors, good text editors like Scintilla based SciTE, TextPad etc. Once you know about vertical text selection selection, you will find its use at more places than what you can think about when unaware.

Friday, August 29, 2008

How to Get Calling Assembly

I work on a product which has more than 80 assemblies call around each other. We have build with pdb file specially distributed to developers for debugging purpose but all are not so fortunate :)
It is obvious that you cannot be sure about which assembly you will need to compile in order to get full call stack. But with : System.Reflection.Assembly.GetCallingAssembly()

This way you get the calling assembly so you can compile that assembly. There are a lot of goodies to explore in System.Reflection.Assembly class for debugging.

Happy Debugging!!

Thursday, August 14, 2008

Change-Set Rollback using TFS Power Tool (tfpt.exe)

Have you made a booboo by checking in something which you shouldn’t have? If you are using TFS and TFS Power Tools (tfpt in short) installed on your system, you are still good to roll the s#%t back.
Here are the steps that you will need to follow:
1. Install TFS Power Tool. This is recommended as it provides a lot of goodies without which you may see hell some day.

2. ‘Shelve’ all changes, as you will have to ‘undo’ all your changes.

3. Open cmd prompt. Make sure your $path environment variable is configured to find tfpt.exe

4. Change directory to the workspace

5. Give this command: rollback /changeset:{Change-Set Number}
(For example rollback /changeset:39356)

6. It will take latest of all your workspace. This is what I don’t like as it doesn’t work otherwise. It takes some but works…

7. After above step, tfpt has taken older version and all those file will be ready to be check-in with older viersion.. Check-in those and take a tea.

Tip [02/24/2009]: Step 6 may kill you if you are storing huge amount of data into TFS. I advice you to create a new workspace with only required files downloaded. For Example, if your all changes are in '$codebase/folder/subfolder/" then create workspace for $codebase/folder/subfolder/ mapped to local directory C:\for_rollback\ Due to this, step 6 will become very fast.

Powertool help and website: http://msdn.microsoft.com/en-us/tfs2008/bb980963.aspx

Saturday, April 12, 2008

Track down TransientObjectException

Problem:

TransientObjectException is hibernate (nhibernate in my little world) exception which occurs when you flush.

Identify the code which causes it:

It is simple. Put nhibernate session.IsDirty() underwatch. Execute your program stpe by step. You are 'ok' till IsDirty give you 'true' or 'false'. You can identify the culprit step when IsDirty raises any exception.

Cause and Solution:

No one can you tell you exact solution as this may be caused by variety of mistakes. The root cause is that you are trying to save an object into database which has transient objects (not existing in database in our context) attached to it. Solution is to save the transient objects before flush or just remove the "cascade" attribute from the HBM.

Wednesday, February 13, 2008

.NET Assembly uninstall problem

Have you ever encountered this error when you try to uninstall a .NET assembly?

Unable to uninstall: assembly is required by one or more applications Pending references:

Most probably yes!

Cause:

It is because that assembly is installed by an installer (anyone.. including standard .net MSI) . Installer specifies a traced reference count on the assembly being installed so when you try to delete assembly using GACUTIL, you get above error. I couldn’t uninstall some assembly while I was manually uninstalling a software.

Work Around:

Method 1:

Use GACBrowser software to remove such assembly (uses 3rd approach specified below). It’s Easy, search and select assembly to remove. And removed!!

Download from here: http://sourceforge.net/project/showfiles.php?group_id=214315

GAC Browser is powerful tool to search and remove assembly. It is must have tool for any developer dealing with assemblies. On an average, if you have visual studio 2005 installed on your PC, you may see more than 1000 assemblies on you PC. There is no good way of searching assembly in you GAC unless you have GAC Browser with you. Also visibility in GAC is increased with more info like when it was last GACed. Double click any assembly to de-assemble the assembly in ILDASM. All in one! That’s why I said it a “must have”!

Method 2:

Windows maintains trace reference count in registry at two places.

[HKCU\Software\Microsoft\Installer\Assemblies\Global]

[HKLM\SOFTWARE\Classes\Installer\Assemblies\Global]

So you may want to go to this registry and remove the entry of the assembly that you want to uninstall. Use GACUTIL to remove assembly from GAC.


Method 3:

Go to Assembly folder using command prompt.
1. Open CMD
2. Go to assembly directory (for most of us: C:\Windows\assembly), If you type ‘DIR’, you may find different folders (important are: GAC, GAC_MSIL, GAC_32)
3. Search your assembly folder from this folder, go to appropriate version folder and remove the folder.


Conclusion:

You may want to have GAC Browser software as well has use method 2 for clean operation. GAC browser is soon coming up with in build method 2.