SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

How do I get a list of installed CPAN modules?

This works for me

perl -e 'print join("\n",@INC,"")'

Converting a year from 4 digit to 2 digit and back again in C#

//using java script
var curDate = new Date();
var curYear = curDate.getFullYear();
curYear = curYear.toString().slice(2);
document.write(curYear)
//using java script
//using sqlserver
select Right(Year(getDate()),2)
//using sql server
//Using c#.net 
DateTime dt = DateTime.Now;
            string curYear = dt.Year.ToString().Substring(2,2).ToString()  ;
//using c#.net

Do you use source control for your database items?

As a rule, we keep all of our object code (stored procedures, views, triggers, functions, etc.) in source control because these objects are code, and as about every other answer here agrees, code belongs in some form of version control system.

As for CREATE, DROP, ALTER statements, etc. (DDL), we developed and use BuildMaster to manage the deployment of these scripts such that they can be run once and only once against a target database (whether they fail or not). The general idea is that developers will upload change scripts into the system and when it comes time for deployment, only the change scripts that haven't been run against the target environment's database will be run (this is managed very similarly to Autocracy's answer). The reason for this separation of script types lies in that once you manipulate a table's structure, add an index, etc., you effectively cannot undo that without writing a brand new script, or restoring the database - as opposed to the object code where you can simply drop a view or stored procedure then recreate it.

Some of the benefits can be seen when, for example, you restore your production database into your integration environment, the system automatically knows exactly which scripts haven't been run and will alter the table structure of that newly restored database to be current with regards to development.

How can I consume a WSDL (SOAP) web service in Python?

Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.

How can we print line numbers to the log in java

Look at this link. In that method you can jump to your line code, when you double click on LogCat's row.

Also you can use this code to get line number:

public static int getLineNumber()
{
    int lineNumber = 0;
    StackTraceElement[] stackTraceElement = Thread.currentThread()
            .getStackTrace();
    int currentIndex = -1;
    for (int i = 0; i < stackTraceElement.length; i++) {
        if (stackTraceElement[i].getMethodName().compareTo("getLineNumber") == 0)
        {
            currentIndex = i + 1;
            break;
        }
    }

    lineNumber = stackTraceElement[currentIndex].getLineNumber();

    return lineNumber;
}

NULL values inside NOT IN clause

this is for Boy:

select party_code 
from abc as a
where party_code not in (select party_code 
                         from xyz 
                         where party_code = a.party_code);

this works regardless of ansi settings

Disable and later enable all table indexes in Oracle

Combining the two answers:

First create sql to make all index unusable:

alter session set skip_unusable_indexes = true;
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;

Do import...

select 'alter index ' || u.index_name || ' rebuild online;' from user_indexes u;

What's the effect of adding 'return false' to a click event listener?

By default, when you click on the button, the form would be sent to server no matter what value you have input.

However, this behavior is not quite appropriate for most cases because we may want to do some checking before sending it to server.

So, when the listener received "false", the submitting would be cancelled. Basically, it is for the purpose to do some checking on front end.

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

If at all possible, use generics. This includes:

  • List instead of ArrayList
  • Dictionary instead of HashTable

Disable all table constraints in Oracle

with cursor for loop (user = 'TRANEE', table = 'D')

declare
    constr all_constraints.constraint_name%TYPE;
begin
    for constr in
        (select constraint_name from all_constraints
        where table_name = 'D'
        and owner = 'TRANEE')
    loop
        execute immediate 'alter table D disable constraint '||constr.constraint_name;
    end loop;
end;
/

(If you change disable to enable, you can make all constraints enable)

When do I use the PHP constant "PHP_EOL"?

No, PHP_EOL does not handle endline issues, because the system where you use that constant is not the same system where you send the output to.

I would not recommend using PHP_EOL at all. Unix/Linux use \n, MacOS / OS X changed from \r to \n too and on Windows many applications (especially browsers) can display it correctly too. On Windows, it is also easy change existing client-side code to use \n only and still maintain backward-compatibility: Just change the delimiter for line trimming from \r\n to \n and wrap it in a trim() like function.

Should import statements always be at the top of a module?

I have adopted the practice of putting all imports in the functions that use them, rather than at the top of the module.

The benefit I get is the ability to refactor more reliably. When I move a function from one module to another, I know that the function will continue to work with all of its legacy of testing intact. If I have my imports at the top of the module, when I move a function, I find that I end up spending a lot of time getting the new module's imports complete and minimal. A refactoring IDE might make this irrelevant.

There is a speed penalty as mentioned elsewhere. I have measured this in my application and found it to be insignificant for my purposes.

It is also nice to be able to see all module dependencies up front without resorting to search (e.g. grep). However, the reason I care about module dependencies is generally because I'm installing, refactoring, or moving an entire system comprising multiple files, not just a single module. In that case, I'm going to perform a global search anyway to make sure I have the system-level dependencies. So I have not found global imports to aid my understanding of a system in practice.

I usually put the import of sys inside the if __name__=='__main__' check and then pass arguments (like sys.argv[1:]) to a main() function. This allows me to use main in a context where sys has not been imported.

How can I lock a file using java (if possible)

Use this for unix if you are transferring using winscp or ftp:

public static void isFileReady(File entry) throws Exception {
        long realFileSize = entry.length();
        long currentFileSize = 0;
        do {
            try (FileInputStream fis = new FileInputStream(entry);) {
                currentFileSize = 0;
                while (fis.available() > 0) {
                    byte[] b = new byte[1024];
                    int nResult = fis.read(b);
                    currentFileSize += nResult;
                    if (nResult == -1)
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("currentFileSize=" + currentFileSize + ", realFileSize=" + realFileSize);
        } while (currentFileSize != realFileSize);
    }

How do I pull from a Git repository through an HTTP proxy?

I got around the proxy using https... some proxies don't even check https.

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

c:\git\meantest>git clone http://github.com/linnovate/mean.git
Cloning into 'mean'...
fatal: unable to access 'http://github.com/linnovate/mean.git/': Failed connect
to github.com:80; No error

c:\git\meantest>git clone https://github.com/linnovate/mean.git
Cloning into 'mean'...
remote: Reusing existing pack: 2587, done.
remote: Counting objects: 27, done.
remote: Compressing objects: 100% (24/24), done.
rRemote: Total 2614 (delta 3), reused 4 (delta 0)eceiving objects:  98% (2562/26

Receiving objects: 100% (2614/2614), 1.76 MiB | 305.00 KiB/s, done.
Resolving deltas: 100% (1166/1166), done.
Checking connectivity... done

Working copy XXX locked and cleanup failed in SVN

The clean up did not work for me no matter how many ways I tried. Instead from Visual Studio I committed each folder individually. Then I committed the top folder and was successful.

How do I parse an ISO 8601-formatted date?

New in Python 3.7+


The datetime standard library introduced a function for inverting datetime.isoformat().

classmethod datetime.fromisoformat(date_string):

Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat().

Specifically, this function supports strings in the format(s):

YYYY-MM-DD[*HH[:MM[:SS[.mmm[mmm]]]][+HH:MM[:SS[.ffffff]]]]

where * can match any single character.

Caution: This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat().

Example of use:

from datetime import datetime

date = datetime.fromisoformat('2017-01-01T12:30:59.000000')

Algorithm to return all combinations of k elements from n

Here is an elegant, generic implementation in Scala, as described on 99 Scala Problems.

object P26 {
  def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] = 
    ls match {
      case Nil => Nil
      case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
    }

  def combinations[A](n: Int, ls: List[A]): List[List[A]] =
    if (n == 0) List(Nil)
    else flatMapSublists(ls) { sl =>
      combinations(n - 1, sl.tail) map {sl.head :: _}
    }
}

Using Caps Lock as Esc in Mac OS X

Karabiner-Elements A powerful and stable keyboard customizer for macOS. (freeware)

https://pqrs.org/osx/karabiner/index.html

Worked for me for Mojave to change caps-lock to backspace

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

Is there any sed like utility for cmd.exe?

> (Get-content file.txt) | Foreach-Object {$_ -replace "^SourceRegexp$", "DestinationString"} | Set-Content file.txt

This is behaviour of

sed -i 's/^SourceRegexp$/DestinationString/g' file.txt

Could you explain STA and MTA?

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

How do I check if an index exists on a table field in MySQL?

show index from table_name where Column_name='column_name';

Copy / Put text on the clipboard with FireFox, Safari and Chrome

From addon code:

In case anyone else was looking for how to do it from chrome code, you can use the nsIClipboardHelper interface as described here: https://developer.mozilla.org/en-US/docs/Using_the_Clipboard

How to force a web browser NOT to cache images

Armin Ronacher has the correct idea. The problem is random strings can collide. I would use:

<img src="picture.jpg?1222259157.415" alt="">

Where "1222259157.415" is the current time on the server.
Generate time by Javascript with performance.now() or by Python with time.time()

Iterate a list with indexes in Python

Here's another using the zip function.

>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]

Ways to eliminate switch in code

For C++

If you are referring to ie an AbstractFactory I think that a registerCreatorFunc(..) method usually is better than requiring to add a case for each and every "new" statement that is needed. Then letting all classes create and register a creatorFunction(..) which can be easy implemented with a macro (if I dare to mention). I believe this is a common approach many framework do. I first saw it in ET++ and I think many frameworks that require a DECL and IMPL macro uses it.

C99 stdint.h header and MS Visual Studio

Another portable solution:

POSH: The Portable Open Source Harness

"POSH is a simple, portable, easy-to-use, easy-to-integrate, flexible, open source "harness" designed to make writing cross-platform libraries and applications significantly less tedious to create and port."

http://poshlib.hookatooka.com/poshlib/trac.cgi

as described and used in the book: Write portable code: an introduction to developing software for multiple platforms By Brian Hook http://books.google.ca/books?id=4VOKcEAPPO0C

-Jason

How do you find out which version of GTK+ is installed on Ubuntu?

I think a distribution-independent way is:

gtk-config --version

How to efficiently count the number of keys/properties of an object in JavaScript?

You can use:

Object.keys(objectName).length; 

and

Object.values(objectName).length;

What processes are using which ports on unix?

netstat -ln | awk '/^(tcp|udp)/ { split($4, a, /:/); print $1, a[2]}' | sort -u

gives you the active tcp/udp ports. Then you can use the ports with fuser -n tcp or fuser -n udp, as root, and supposing that fuser is GNU fuser or has similar options.

If you need more help, let me know.

Easier way to debug a Windows service

You can also start the service through the command prompt (sc.exe).

Personally, I'd run the code as a stand-alone program in the debugging phase, and when most bugs are ironed out, change to running as service.

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

How to modify a text file?

Depends on what you want to do. To append you can open it with "a":

 with open("foo.txt", "a") as f:
     f.write("new line\n")

If you want to preprend something you have to read from the file first:

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

A typical algo for tic-tac-toe should look like this:

Board : A nine-element vector representing the board. We store 2 (indicating Blank), 3 (indicating X), or 5 (indicating O). Turn: An integer indicating which move of the game about to be played. The 1st move will be indicated by 1, last by 9.

The Algorithm

The main algorithm uses three functions.

Make2: returns 5 if the center square of the board is blank i.e. if board[5]=2. Otherwise, this function returns any non-corner square (2, 4, 6 or 8).

Posswin(p): Returns 0 if player p can’t win on his next move; otherwise, it returns the number of the square that constitutes a winning move. This function will enable the program both to win and to block opponents win. This function operates by checking each of the rows, columns, and diagonals. By multiplying the values of each square together for an entire row (or column or diagonal), the possibility of a win can be checked. If the product is 18 (3 x 3 x 2), then X can win. If the product is 50 (5 x 5 x 2), then O can win. If a winning row (column or diagonal) is found, the blank square in it can be determined and the number of that square is returned by this function.

Go (n): makes a move in square n. this procedure sets board [n] to 3 if Turn is odd, or 5 if Turn is even. It also increments turn by one.

The algorithm has a built-in strategy for each move. It makes the odd numbered move if it plays X, the even-numbered move if it plays O.

Turn = 1    Go(1)   (upper left corner).
Turn = 2    If Board[5] is blank, Go(5), else Go(1).
Turn = 3    If Board[9] is blank, Go(9), else Go(3).
Turn = 4    If Posswin(X) is not 0, then Go(Posswin(X)) i.e. [ block opponent’s win], else Go(Make2).
Turn = 5    if Posswin(X) is not 0 then Go(Posswin(X)) [i.e. win], else if Posswin(O) is not 0, then Go(Posswin(O)) [i.e. block win], else if Board[7] is blank, then Go(7), else Go(3). [to explore other possibility if there be any ].
Turn = 6    If Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else Go(Make2).
Turn = 7    If Posswin(X) is not 0 then Go(Posswin(X)), else if Posswin(X) is not 0, then Go(Posswin(O)) else go anywhere that is blank.
Turn = 8    if Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else go anywhere that is blank.
Turn = 9    Same as Turn=7.

I have used it. Let me know how you guys feel.

What is the T-SQL syntax to connect to another SQL Server?

Also, make sure when you write the query involving the linked server, you include brackets like this:

SELECT * FROM [LinkedServer].[RemoteDatabase].[User].[Table]

I've found that at least on 2000/2005 the [] brackets are necessary, at least around the server name.

Protecting cells in Excel but allow these to be modified by VBA script

I selected the cells I wanted locked out in sheet1 and place the suggested code in the open_workbook() function and worked like a charm.

ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
UserInterfaceOnly:=True

How can I dynamically switch web service addresses in .NET without a recompile?

As long as the web service methods and underlying exposed classes do not change, it's fairly trivial. With Visual Studio 2005 (and newer), adding a web reference creates an app.config (or web.config, for web apps) section that has this URL. All you have to do is edit the app.config file to reflect the desired URL.

In our project, our simple approach was to just have the app.config entries commented per environment type (development, testing, production). So we just uncomment the entry for the desired environment type. No special coding needed there.

Dynamic type languages versus static type languages

It is all about the right tool for the job. Neither is better 100% of the time. Both systems were created by man and have flaws. Sorry, but we suck and making perfect stuff.

I like dynamic typing because it gets out of my way, but yes runtime errors can creep up that I didn't plan for. Where as static typing may fix the aforementioned errors, but drive a novice(in typed languages) programmer crazy trying to cast between a constant char and a string.

How do you do Impersonation in .NET?

Here's my vb.net port of Matt Johnson's answer. I added an enum for the logon types. LOGON32_LOGON_INTERACTIVE was the first enum value that worked for sql server. My connection string was just trusted. No user name / password in the connection string.

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <summary>
      ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
      ''' by a terminal server, remote shell, or similar process.
      ''' This logon type has the additional expense of caching logon information for disconnected operations; 
      ''' therefore, it is inappropriate for some client/server applications,
      ''' such as a mail server.
      ''' </summary>
      LOGON32_LOGON_INTERACTIVE = 2

      ''' <summary>
      ''' This logon type is intended for high performance servers to authenticate plaintext passwords.
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_NETWORK = 3

      ''' <summary>
      ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without 
      ''' their direct intervention. This type is also for higher performance servers that process many plaintext
      ''' authentication attempts at a time, such as mail or Web servers. 
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_BATCH = 4

      ''' <summary>
      ''' Indicates a service-type logon. The account provided must have the service privilege enabled. 
      ''' </summary>
      LOGON32_LOGON_SERVICE = 5

      ''' <summary>
      ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
      ''' The new logon session has the same local identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

You need to Use with a Using statement to contain some code to run impersonated.

Should 'using' directives be inside or outside the namespace?

There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:

// File1.cs
using System;
namespace Outer.Inner
{
    class Foo
    {
        static void Bar()
        {
            double d = Math.PI;
        }
    }
}

Now imagine that someone adds another file (File2.cs) to the project that looks like this:

// File2.cs
namespace Outer
{
    class Math
    {
    }
}

The compiler searches Outer before looking at those using directives outside the namespace, so it finds Outer.Math instead of System.Math. Unfortunately (or perhaps fortunately?), Outer.Math has no PI member, so File1 is now broken.

This changes if you put the using inside your namespace declaration, as follows:

// File1b.cs
namespace Outer.Inner
{
    using System;
    class Foo
    {
        static void Bar()
        {
            double d = Math.PI;
        }
    }
}

Now the compiler searches System before searching Outer, finds System.Math, and all is well.

Some would argue that Math might be a bad name for a user-defined class, since there's already one in System; the point here is just that there is a difference, and it affects the maintainability of your code.

It's also interesting to note what happens if Foo is in namespace Outer, rather than Outer.Inner. In that case, adding Outer.Math in File2 breaks File1 regardless of where the using goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any using directive.

How do I remove the file suffix and path portion from a path string in Bash?

Using basename I used the following to achieve this:

for file in *; do
    ext=${file##*.}
    fname=`basename $file $ext`

    # Do things with $fname
done;

This requires no a priori knowledge of the file extension and works even when you have a filename that has dots in it's filename (in front of it's extension); it does require the program basename though, but this is part of the GNU coreutils so it should ship with any distro.

MySQL search and replace some text in a field

Change table_name and field to match your table name and field in question:

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;

PHP code to convert a MySQL query to CSV

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;

(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)

or:

$select = "SELECT * FROM table_name";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                            
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

Create Word Document using PHP in Linux

By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component phpLiveDocx.

From the project web site:

"phpLiveDocx allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge."

XML Schema (XSD) validation tool?

You can connect your XML schema to Microsoft Visual Studio's Intellisense. This option gives you both real-time validation AND autocomplete, which is just awesome.

I have this exact scenario running on my free copy of Microsoft Visual C++ 2010 Express.

Could not load type from assembly error

I want to mention additional things and make a conclusion.

Commonly, As Otherones explained, This exception will raise when there is a problem with loading expected type (in an existing assembly) in runtime. More specific, Whenever there is loaded assembly that is stale (and not contains the requiring type). Or when an assembly with different version or build is already loaded that not contains the expected type.

Also, I must mention that It seems Rarely, But It is possible to be runtime limitation or a compiler bug (suppose compiler not negated about something and just compiled problematic code), But runtime throws System.TypeLoadException exception. Yes; this actually occurred for me!

An Example (witch occurred for me)

Consider an struct that defines a nullable field of its own type inside itself. Defining such the filed non-nullable, will take you a compile-time error and prevents you from build (Obviously This behavior has a logical reason). But what about nullable struct filed? Actually, nullable value-types is Nullable<T> at behind. As c# compiler not prevented me from defining in this way, I tried it and the project built. But I get runtime exception System.TypeLoadException: 'Could not load type 'SomeInfo' from assembly ... ', And It seems to be Problem in loading the part of my code (otherwise, we may say: the compiler not-truly performed compilation process at least) for me in my environment:

public struct SomeInfo
{
   public SomeInfo? Parent { get; } 
   
   public string info { get; }
}

My environment specs:

  • Visual Studio 2019 16.4.4
  • Language Version: c# 7.3
  • Project type: netstandard 2.0.3 library
  • Runtime: classic DotNetFramework 4.6.1

(I checked and ensured that the compiled assembly is up to date And actually is newly compiled. Even, I throwed away all bin directory and refreshed the whole project. Even I created a new project in a fresh solution and tested, But such the struct generates the exception.)

It seems to be a runtime limitation (logically or technically) or bug or a same problem else, because Visual Studio not prevents me from compile And Also other newer parts of my codes (excluding this struct) are executing fine. Changing the struct to a class, the compiled assembly contains and executes the type as well.

I have no any idea to explain in-detail why this behavior occurs in my environment, But I faced this situation.

Conclusion

Check the situations:

  • When a same (probably older) assembly already exists in GAC that is overriding the referenced assembly.

  • When re-compilation was need but not performed automatically (therefore the referenced assembly is not updated) and there is needs to perform build manually or fix solution build configuration.

  • When a custom tool or middleware or third-party executable (such as tests runner tool or IIS) loaded an older version of that assembly from cached things and there is need to cleaning somethings up or causing to reset somethings.

  • When an Unappropriated Configuration caused demanding a no longer existing type by a custom tool or middleware or a third-party executable that loads the assembly and there is need to update configuration or cleaning somethings up (such as removing an http handler in web.config file on IIS deployment as @Brian-Moeskau said)

  • When there is a logical or technical problem for runtime to execute the compiled assembly, (for example when compiler was compiled a problematic code that the in-using runtime cannot understand or execute it), as I faced.

Picking a random element from a set

PHP, using MT:

$items_array = array("alpha", "bravo", "charlie");
$last_pos = count($items_array) - 1;
$random_pos = mt_rand(0, $last_pos);
$random_item = $items_array[$random_pos];

What exactly are DLL files, and how do they work?

DLL files contain an Export Table which is a list of symbols which can be looked up by the calling program. The symbols are typically functions with the C calling convention (__stcall). The export table also contains the address of the function.

With this information, the calling program can then call the functions within the DLL even though it did not have access to the DLL at compile time.

Introducing Dynamic Link Libraries has some more information.

What are some great online database modeling tools?

I like Clay Eclipse plugin. I've only used it with MySQL, but it claims Firebird support.

How to make asynchronous HTTP requests in PHP

You can do trickery by using exec() to invoke something that can do HTTP requests, like wget, but you must direct all output from the program to somewhere, like a file or /dev/null, otherwise the PHP process will wait for that output.

If you want to separate the process from the apache thread entirely, try something like (I'm not sure about this, but I hope you get the idea):

exec('bash -c "wget -O (url goes here) > /dev/null 2>&1 &"');

It's not a nice business, and you'll probably want something like a cron job invoking a heartbeat script which polls an actual database event queue to do real asynchronous events.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

I probably wouldn't do it this way, as it's less efficient than the already mentioned CASE constructs - unless, perhaps, you had covering indexes for both queries. Either way, it's a useful technique for similar problems:

SELECT OrderId, MAX(Price) as Price FROM (
   SELECT o.OrderId, o.NegotiatedPrice as Price FROM Order o
   UNION ALL
   SELECT o.OrderId, o.SuggestedPrice as Price FROM Order o
) as A
GROUP BY OrderId

Simplest SOAP example

Has anyone tried this? https://github.com/doedje/jquery.soap

Seems very easy to implement.

Example:

$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',

data: {
    name: 'Remy Blom',
    msg: 'Hi!'
},

success: function (soapResponse) {
    // do stuff with soapResponse
    // if you want to have the response as JSON use soapResponse.toJSON();
    // or soapResponse.toString() to get XML string
    // or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
    // show error
}
});

will result in

<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <helloWorld>
        <name>Remy Blom</name>
        <msg>Hi!</msg>
    </helloWorld>
  </soap:Body>
</soap:Envelope>

How can I tell if a DOM element is visible in the current viewport?

See the source of verge, which uses getBoundingClientRect. It's like:

function inViewport (el) {

    var r, html;
    if ( !el || 1 !== el.nodeType ) { return false; }
    html = document.documentElement;
    r = el.getBoundingClientRect();

    return ( !!r
      && r.bottom >= 0
      && r.right >= 0
      && r.top <= html.clientHeight
      && r.left <= html.clientWidth
    );

}

It returns true if any part of the element is in the viewport.

Access Enum value using EL with JSTL

A simple comparison against string works:

<c:when test="${someModel.status == 'OLD'}">

How to validate phone numbers using regex

Here's one that works well in JavaScript. It's in a string because that's what the Dojo widget was expecting.

It matches a 10 digit North America NANP number with optional extension. Spaces, dashes and periods are accepted delimiters.

"^(\\(?\\d\\d\\d\\)?)( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$"

Command-line Unix ASCII-based charting / plotting tool

While gnuplot is powerful, it's also really irritating when you just want to pipe in a bunch of points and get a graph.

Thankfully, someone created eplot (easy plot), which handles all the nonsense for you.

It doesn't seem to have an option to force terminal graphs; I patched it like so:

--- eplot.orig  2012-10-12 17:07:35.000000000 -0700
+++ eplot       2012-10-12 17:09:06.000000000 -0700
@@ -377,6 +377,7 @@
                # ---- print the options
                com="echo '\n"+getStyleString+@oc["MiscOptions"]
                com=com+"set multiplot;\n" if doMultiPlot
+               com=com+"set terminal dumb;\n"
                com=com+"plot "+@oc["Range"]+comString+"\n'| gnuplot -persist"
                printAndRun(com)
                # ---- convert to PDF

An example of use:

[$]> git shortlog -s -n | awk '{print $1}' | eplot 2> /dev/null


  3500 ++-------+-------+--------+--------+-------+--------+-------+-------++
       +        +       +        "/tmp/eplot20121012-19078-fw3txm-0" ****** +       *                                                                    |  3000 +*                                                                  ++       |*                                                                   |       | *                                                                  |  2500 ++*                                                                 ++       | *                                                                  |
       |  *                                                                 |
  2000 ++ *                                                                ++
       |  **                                                                |
  1500 ++   ****                                                           ++
       |        *                                                           |
       |         **                                                         |
  1000 ++          *                                                       ++
       |            *                                                       |
       |            *                                                       |
   500 ++            ***                                                   ++
       |                **************                                      |
       +        +       +        +    **********  +        +       +        +
     0 ++-------+-------+--------+--------+-----***************************++
       0        5       10       15       20      25       30      35       40

How can you strip non-ASCII characters from a string? (in C#)

I came here looking for a solution for extended ascii characters, but couldnt find it. The closest I found is bzlm's solution. But that works only for ASCII Code upto 127(obviously you can replace the encoding type in his code, but i think it was a bit complex to understand. Hence, sharing this version). Here's a solution that works for extended ASCII codes i.e. upto 255 which is the ISO 8859-1

It finds and strips out non-ascii characters(greater than 255)

Dim str1 as String= "â, ??î or ôu? n?i?++$-?!??4?od;/?'®;?:?)///1!@#"

Dim extendedAscii As Encoding = Encoding.GetEncoding("ISO-8859-1", 
                                                New EncoderReplacementFallback(String.empty),
                                                New DecoderReplacementFallback())

Dim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)

Dim str2 As String = extendedAscii.GetString(extendedAsciiBytes)

console.WriteLine(str2)
'Output : â, ??î or ôu ni++$-!??4od;/';:)///1!@#$%^yz:

Here's a working fiddle for the code

Replace the encoding as per the requirement, rest should remain the same.

How can a file be copied?

Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.

shutil_methods =
{'copy':['shutil.copyfileobj',
          'shutil.copyfile',
          'shutil.copymode',
          'shutil.copystat',
          'shutil.copy',
          'shutil.copy2',
          'shutil.copytree',],
 'move':['shutil.rmtree',
         'shutil.move',],
 'exception': ['exception shutil.SameFileError',
                 'exception shutil.Error'],
 'others':['shutil.disk_usage',
             'shutil.chown',
             'shutil.which',
             'shutil.ignore_patterns',]
}

Secondly, explain methods of copy in exmaples:

  1. shutil.copyfileobj(fsrc, fdst[, length]) manipulate opened objects
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
    ...:      shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
  1. shutil.copyfile(src, dst, *, follow_symlinks=True) Copy and rename
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
  1. shutil.copy() Copy without preseving the metadata
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
  1. shutil.copy2() Copy with preseving the metadata
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
  1. shutil.copytree()

Recursively copy an entire directory tree rooted at src, returning the destination directory

How to return multiple values in one column (T-SQL)?

group_concat() sounds like what you're looking for.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:

http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html

What is the time complexity of indexing, inserting and removing from common data structures?

Amortized Big-O for hashtables:

  • Insert - O(1)
  • Retrieve - O(1)
  • Delete - O(1)

Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.

What is a simple command line program or script to backup SQL server databases?

Schedule the following to backup all Databases:

Use Master

Declare @ToExecute VarChar(8000)

Select @ToExecute = Coalesce(@ToExecute + 'Backup Database ' + [Name] + ' To Disk =     ''D:\Backups\Databases\' + [Name]   + '.bak'' With Format;' + char(13),'')
From
Master..Sysdatabases
Where
[Name] Not In ('tempdb')
and databasepropertyex ([Name],'Status') = 'online'

Execute(@ToExecute)

There are also more details on my blog: how to Automate SQL Server Express Backups.

How can I decode HTML characters in C#?

Use Server.HtmlDecode to decode the HTML entities. If you want to escape the HTML, i.e. display the < and > character to the user, use Server.HtmlEncode.

How do I trim leading/trailing whitespace in a standard way?

#include<stdio.h>
#include<ctype.h>

main()
{
    char sent[10]={' ',' ',' ','s','t','a','r','s',' ',' '};
    int i,j=0;
    char rec[10];

    for(i=0;i<=10;i++)
    {
        if(!isspace(sent[i]))
        {

            rec[j]=sent[i];
            j++;
        }
    }

printf("\n%s\n",rec);

}

How to copy and paste code without rich text formatting?

If you are using MS Word then try ALT+E, S, U, Enter (Uses the Paste Special)

How do I find the location of my Python site-packages directory?

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

(or just first item with site.getsitepackages()[0])

Get the IP Address of local computer

The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.

Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:

void ListIpAddresses(IpAddresses& ipAddrs)
{
  IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);
  IP_ADAPTER_ADDRESSES* adapter(NULL);

  // Start with a 16 KB buffer and resize if needed -
  // multiple attempts in case interfaces change while
  // we are in the middle of querying them.
  DWORD adapter_addresses_buffer_size = 16 * KB;
  for (int attempts = 0; attempts != 3; ++attempts)
  {
    adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);
    assert(adapter_addresses);

    DWORD error = ::GetAdaptersAddresses(
      AF_UNSPEC, 
      GAA_FLAG_SKIP_ANYCAST | 
        GAA_FLAG_SKIP_MULTICAST | 
        GAA_FLAG_SKIP_DNS_SERVER |
        GAA_FLAG_SKIP_FRIENDLY_NAME, 
      NULL, 
      adapter_addresses,
      &adapter_addresses_buffer_size);

    if (ERROR_SUCCESS == error)
    {
      // We're done here, people!
      break;
    }
    else if (ERROR_BUFFER_OVERFLOW == error)
    {
      // Try again with the new size
      free(adapter_addresses);
      adapter_addresses = NULL;

      continue;
    }
    else
    {
      // Unexpected error code - log and throw
      free(adapter_addresses);
      adapter_addresses = NULL;

      // @todo
      LOG_AND_THROW_HERE();
    }
  }

  // Iterate through all of the adapters
  for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)
  {
    // Skip loopback adapters
    if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
    {
      continue;
    }

    // Parse all IPv4 and IPv6 addresses
    for (
      IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; 
      NULL != address;
      address = address->Next)
    {
      auto family = address->Address.lpSockaddr->sa_family;
      if (AF_INET == family)
      {
        // IPv4
        SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);

        char str_buffer[INET_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);
        ipAddrs.mIpv4.push_back(str_buffer);
      }
      else if (AF_INET6 == family)
      {
        // IPv6
        SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);

        char str_buffer[INET6_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);

        std::string ipv6_str(str_buffer);

        // Detect and skip non-external addresses
        bool is_link_local(false);
        bool is_special_use(false);

        if (0 == ipv6_str.find("fe"))
        {
          char c = ipv6_str[2];
          if (c == '8' || c == '9' || c == 'a' || c == 'b')
          {
            is_link_local = true;
          }
        }
        else if (0 == ipv6_str.find("2001:0:"))
        {
          is_special_use = true;
        }

        if (! (is_link_local || is_special_use))
        {
          ipAddrs.mIpv6.push_back(ipv6_str);
        }
      }
      else
      {
        // Skip all other types of addresses
        continue;
      }
    }
  }

  // Cleanup
  free(adapter_addresses);
  adapter_addresses = NULL;

  // Cheers!
}

Checkout one file from Subversion

cd C:\path\dir
svn checkout https://server/path/to/trunk/dir/dir/parent_dir--depth empty
cd C:\path\dir\parent_dir
svn update filename.log

(Edit filename.log)

svn commit -m "this is a comment."

What is the most efficient way to deep clone an object in JavaScript?

This isn't generally the most efficient solution, but it does what I need. Simple test cases below...

function clone(obj, clones) {
    // Makes a deep copy of 'obj'. Handles cyclic structures by
    // tracking cloned obj's in the 'clones' parameter. Functions 
    // are included, but not cloned. Functions members are cloned.
    var new_obj,
        already_cloned,
        t = typeof obj,
        i = 0,
        l,
        pair; 

    clones = clones || [];

    if (obj === null) {
        return obj;
    }

    if (t === "object" || t === "function") {

        // check to see if we've already cloned obj
        for (i = 0, l = clones.length; i < l; i++) {
            pair = clones[i];
            if (pair[0] === obj) {
                already_cloned = pair[1];
                break;
            }
        }

        if (already_cloned) {
            return already_cloned; 
        } else {
            if (t === "object") { // create new object
                new_obj = new obj.constructor();
            } else { // Just use functions as is
                new_obj = obj;
            }

            clones.push([obj, new_obj]); // keep track of objects we've cloned

            for (key in obj) { // clone object members
                if (obj.hasOwnProperty(key)) {
                    new_obj[key] = clone(obj[key], clones);
                }
            }
        }
    }
    return new_obj || obj;
}

Cyclic array test...

a = []
a.push("b", "c", a)
aa = clone(a)
aa === a //=> false
aa[2] === a //=> false
aa[2] === a[2] //=> false
aa[2] === aa //=> true

Function test...

f = new Function
f.a = a
ff = clone(f)
ff === f //=> true
ff.a === a //=> false

favicon not working in IE

Regarding incompatibilities with IE9 I came across this blog post which gives tips for creating a favicon that is recognised by IE9.

In an essence, try creating a favicon with the following site: http://www.xiconeditor.com/

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I use this one. It allows you to determine the length you want the result to be as well as a default padding character if one is not provided. Of course you can customize the length of the input and output for whatever maximums you are running into.

/*===============================================================
 Author         : Joey Morgan
 Create date    : November 1, 2012
 Description    : Pads the string @MyStr with the character in 
                : @PadChar so all results have the same length
 ================================================================*/
 CREATE FUNCTION [dbo].[svfn_AMS_PAD_STRING]
        (
         @MyStr VARCHAR(25),
         @LENGTH INT,
         @PadChar CHAR(1) = NULL
        )
RETURNS VARCHAR(25)
 AS 
      BEGIN
        SET @PadChar = ISNULL(@PadChar, '0');
        DECLARE @Result VARCHAR(25);
        SELECT
            @Result = RIGHT(SUBSTRING(REPLICATE('0', @LENGTH), 1,
                                      (@LENGTH + 1) - LEN(RTRIM(@MyStr)))
                            + RTRIM(@MyStr), @LENGTH)

        RETURN @Result

      END

Your mileage may vary. :-)

Joey Morgan
Programmer/Analyst Principal I
WellPoint Medicaid Business Unit

How do I replace text inside a div element?

I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.

$("field_name").update("New text");

Where can I find free WPF controls and control templates?

Codeplex is definitively the right place. Recent "post": SofaWPF.codeplex.com based on AvalonDock.codeplex.com, an IDE like framework.

Getting value from a cell from a gridview on RowDataBound event

First you need to wrap your code in a Label or Literal control so that you can reference it properly. What's happening is that there's no way for the system to keep track of it, because there's no control associated with the text. It's the control's responsibility to add its contents to viewstate.

You need to use gridView.FindControl("controlName"); to get the control in the row. From there you can get at its properties including Text.

You can also get at the DataItem property of the Row in question and cast it to the appropriate type and extract the information directly.

Undoing a git rebase

If you successfully rebased against remote branch and can not git rebase --abort you still can do some tricks to save your work and don't have forced pushes. Suppose your current branch that was rebased by mistake is called your-branch and is tracking origin/your-branch

  • git branch -m your-branch-rebased # rename current branch
  • git checkout origin/your-branch # checkout to latest state that is known to origin
  • git checkout -b your-branch
  • check git log your-branch-rebased, compare to git log your-branch and define commits that are missing from your-branch
  • git cherry-pick COMMIT_HASH for every commit in your-branch-rebased
  • push your changes. Please aware that two local branches are associated with remote/your-branch and you should push only your-branch

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

# is better than javascript:anything, but the following is even better:

HTML:

<a href="/gracefully/degrading/url/with/same/functionality.ext" class="some-selector">For great justice</a>

JavaScript:

$(function() {
    $(".some-selector").click(myJsFunc);
});

You should always strive for graceful degradation (in the event that the user doesn't have JavaScript enabled...and when it is with specs. and budget). Also, it is considered bad form to use JavaScript attributes and protocol directly in HTML.

How do I find the mime-type of a file with php?

If you are working with Images only and you need mime type (e.g. for headers), then this is the fastest and most direct answer:

$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));

It will output true image mime type even if you rename your image file

What is the difference between bool and Boolean types in C#

No actual difference unless you get the type string. There when you use reflection or GetType() you get {Name = "Boolean" FullName = "System.Boolean"} for both.

What's the key difference between HTML 4 and HTML 5?

In short it is much simple compared to html, the long doctype is removed and also center and font tag is removed. I also answered this difference in my blog : http://ravisinghblog.in/key-difference-between-html-and-html-5/

c++ exception : throwing std::string

In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw std::string("it's the end of the world!");
  }
}

void Foo:Caller(){
  try{
    this->Bar();// should throw
  }catch(std::string& caught){ // not quite sure the syntax is ok here...
    std::cout<<"Got "<<caught<<std::endl;
  }
}
  • You should throw anonymous temporaries so the compiler deals with the object lifetime of whatever you're throwing - if you throw something new-ed off the heap, someone else needs to free the thing.
  • You should catch references to prevent object slicing

.

See Meyer's "Effective C++ - 3rd edition" for details or visit https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference

Are PDO prepared statements sufficient to prevent SQL injection?

Yes, it is sufficient. The way injection type attacks work, is by somehow getting an interpreter (The database) to evaluate something, that should have been data, as if it was code. This is only possible if you mix code and data in the same medium (Eg. when you construct a query as a string).

Parameterised queries work by sending the code and the data separately, so it would never be possible to find a hole in that.

You can still be vulnerable to other injection-type attacks though. For example, if you use the data in a HTML-page, you could be subject to XSS type attacks.

What strategies and tools are useful for finding memory leaks in .NET?

If the leaks you are observing are due to a runaway cache implementation, this is a scenario where you might want to consider the use of WeakReference. This could help to ensure that memory is released when necessary.

However, IMHO it would be better to consider a bespoke solution - only you really know how long you need to keep the objects around, so designing appropriate housekeeping code for your situation is usually the best approach.

How can I load the contents of a text file into a batch file variable?

Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...

set FileContents=

Then in your batch file do something like this...

   @echo off
   copy SetFile.bat + %1 $tmp$.bat > nul
   call $tmp$.bat
   del $tmp$.bat

%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.

Find CRLF in Notepad++

Image with CRLF

enter image description here


Image without CRLF

enter image description here

JavaScript post request like a form submit

Dynamically create <input>s in a form and submit it

/**
 * sends a request to the specified url from a form. this will change the window location.
 * @param {string} path the path to send the post request to
 * @param {object} params the paramiters to add to the url
 * @param {string} [method=post] the method to use on the form
 */

function post(path, params, method='post') {

  // The rest of this code assumes you are not using a library.
  // It can be made less wordy if you use one.
  const form = document.createElement('form');
  form.method = method;
  form.action = path;

  for (const key in params) {
    if (params.hasOwnProperty(key)) {
      const hiddenField = document.createElement('input');
      hiddenField.type = 'hidden';
      hiddenField.name = key;
      hiddenField.value = params[key];

      form.appendChild(hiddenField);
    }
  }

  document.body.appendChild(form);
  form.submit();
}

Example:

post('/contact/', {name: 'Johnny Bravo'});

EDIT: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the hasOwnProperty check to fix any inadvertent bugs.

Stop and Start a service via batch or cmd file?

I am writing a windows service in C#, the stop/uninstall/build/install/start loop got too tiring. Wrote a mini script, called it reploy.bat and dropped in my Visual Studio output directory (one that has the built service executable) to automate the loop.

Just set these 3 vars

servicename : this shows up on the Windows Service control panel (services.msc)

slndir : folder (not the full path) containing your solution (.sln) file

binpath : full path (not the folder path) to the service executable from the build

NOTE: This needs to be run from the Visual Studio Developer Command Line for the msbuild command to work.

SET servicename="My Amazing Service"
SET slndir="C:dir\that\contains\sln\file"
SET binpath="C:path\to\service.exe"
SET currdir=%cd%

call net stop %servicename%
call sc delete %servicename%
cd %slndir%
call msbuild 
cd %bindir%
call sc create %servicename% binpath=%binpath%
call net start %servicename%
cd %currdir%

Maybe this helps someone :)

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I checked all my settings according to this list: http://msdn.microsoft.com/en-us/library/ts7eyw4s.aspx#feedback . It is helpful to me and for my situation, I find out that Link Dependency of projects' properties has double-quote, which should not be there.

Can regular expressions be used to match nested patterns?

No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a finite automaton.

You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input).

There are many parser generators avialable, for instance ANTLR for Java. Finding an existing grammar for Java (or C) is also not difficult.
For more background: Automata Theory at Wikipedia

Elevating process privilege programmatically?

You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:

startInfo.Verb = "runas";

This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.

This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Since the original question was about jQuery.get, it is worth mentioning here that (as mentioned here) one could use async: false in a $.get() but ideally avoid it since asynchronous XMLHTTPRequest is deprecated (and the browser may give a warning):

$.get({
  url: url,// mandatory
  data: data,
  success: success,
  dataType: dataType,
  async:false // to make it synchronous
});

Is there a typical state machine implementation pattern?

One of my favourite patterns is the state design pattern. Respond or behave differently to the same given set of inputs.
One of the problems with using switch/case statements for state machines is that as you create more states, the switch/cases becomes harder/unwieldy to read/maintain, promotes unorganized spaghetti code, and increasingly difficult to change without breaking something. I find using design patterns helps me to organize my data better, which is the whole point of abstraction. Instead of designing your state code around what state you came from, instead structure your code so that it records the state when you enter a new state. That way, you effectively get a record of your previous state. I like @JoshPetit's answer, and have taken his solution one step further, taken straight from the GoF book:

stateCtxt.h:

#define STATE (void *)
typedef enum fsmSignal
{
   eEnter =0,
   eNormal,
   eExit
}FsmSignalT;

typedef struct fsm 
{
   FsmSignalT signal;
   // StateT is an enum that you can define any which way you want
   StateT currentState;
}FsmT;
extern int STATECTXT_Init(void);
/* optionally allow client context to set the target state */
extern STATECTXT_Set(StateT  stateID);
extern void STATECTXT_Handle(void *pvEvent);

stateCtxt.c:

#include "stateCtxt.h"
#include "statehandlers.h"

typedef STATE (*pfnStateT)(FsmSignalT signal, void *pvEvent);

static FsmT      fsm;
static pfnStateT UsbState ;

int STATECTXT_Init(void)
{    
    UsbState = State1;
    fsm.signal = eEnter;
    // use an enum for better maintainability
    fsm.currentState = '1';
    (*UsbState)( &fsm, pvEvent);
    return 0;
}

static void ChangeState( FsmT *pFsm, pfnStateT targetState )
{
    // Check to see if the state has changed
    if (targetState  != NULL)
    {
        // Call current state's exit event
        pFsm->signal = eExit;
        STATE dummyState = (*UsbState)( pFsm, pvEvent);

        // Update the State Machine structure
        UsbState = targetState ;

        // Call the new state's enter event
        pFsm->signal = eEnter;            
        dummyState = (*UsbState)( pFsm, pvEvent);
    }
}

void STATECTXT_Handle(void *pvEvent)
{
    pfnStateT newState;

    if (UsbState != NULL)
    {
         fsm.signal = eNormal;
         newState = (*UsbState)( &fsm, pvEvent );
         ChangeState( &fsm, newState );
    }        
}


void STATECTXT_Set(StateT  stateID)
{
     prevState = UsbState;
     switch (stateID) 
     {
         case '1':               
            ChangeState( State1 );
            break;
          case '2':
            ChangeState( State2);
            break;
          case '3':
            ChangeState( State3);
            break;
     }
}

statehandlers.h:

/* define state handlers */
extern STATE State1(void);
extern STATE State2(void);
extern STATE State3(void);

statehandlers.c:

#include "stateCtxt.h:"

/* Define behaviour to given set of inputs */
STATE State1(FsmT *fsm, void *pvEvent)
{   
    STATE nextState;
    /* do some state specific behaviours 
     * here
     */
    /* fsm->currentState currently contains the previous state
     * just before it gets updated, so you can implement behaviours 
     * which depend on previous state here
     */
    fsm->currentState = '1';
    /* Now, specify the next state
     * to transition to, or return null if you're still waiting for 
     * more stuff to process.  
     */
    switch (fsm->signal)
    {
        case eEnter:
            nextState = State2;
            break;
        case eNormal:
            nextState = null;
            break;
        case eExit:
            nextState = State2;
            break;
    }

    return nextState;
}

STATE  State3(FsmT *fsm, void *pvEvent)
{
    /* do some state specific behaviours 
     * here
     */
    fsm->currentState = '2';
    /* Now, specify the next state
     * to transition to
     */
     return State1;
}

STATE   State2(FsmT *fsm, void *pvEvent)
{   
    /* do some state specific behaviours 
     * here
     */
    fsm->currentState = '3';
    /* Now, specify the next state
     * to transition to
     */
     return State3;
}

For most State Machines, esp. Finite state machines, each state will know what its next state should be, and the criteria for transitioning to its next state. For loose state designs, this may not be the case, hence the option to expose the API for transitioning states. If you desire more abstraction, each state handler can be separated out into its own file, which are equivalent to the concrete state handlers in the GoF book. If your design is simple with only a few states, then both stateCtxt.c and statehandlers.c can be combined into a single file for simplicity.

What is the difference between visibility:hidden and display:none?

They are not synonyms.

display:none removes the element from the normal flow of the page, allowing other elements to fill in.

visibility:hidden leaves the element in the normal flow of the page such that is still occupies space.

Imagine you are in line for a ride at an amusement park and someone in the line gets so rowdy that security plucks them from the line. Everyone in line will then move forward one position to fill the now empty slot. This is like display:none.

Contrast this with the similar situation, but that someone in front of you puts on an invisibility cloak. While viewing the line, it will look like there is an empty space, but people can't really fill that empty looking space because someone is still there. This is like visibility:hidden.

How to check if a column exists in a SQL Server table?

//Only checks
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'Database_Name'
and TABLE_SCHEMA = 'Schema_Name'
and TABLE_NAME = 'Table_Name'
and COLUMN_NAME = 'Column_Name'
and DATA_TYPE = 'Column_Type') -- Where statement lines can be deleted.

BEGIN
--COLUMN EXISTS IN TABLE
END

ELSE BEGIN
--COLUMN DOES NOT EXISTS IN TABLE
END

Is there a difference between "==" and "is"?

As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:

There is one and only one instance of NoneType i.e. None is a singleton. Consequently foo == None and foo is None mean the same. However the is test is faster and the Pythonic convention is to use foo is None.

If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for foo is bar.

True and False are also (now) singletons, but there is no use-case for foo == True and no use case for foo is True.

What is the Windows version of cron?

If you prefer good ol' cron, CRONw is the way to go.

Supported systems

* Windows 2000 (any version)    works
* Windows XP (SP 2)             works
* Windows Server 2003           works
* Windows NT 4 (SP 6)           should work but not tested
* Windows 3.11, Windows 95,
  Windows 98, Windows ME,
  Windows XP beneath SP2        not supported by design

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

I know it's for a long time ago but may be helpful to any other new comers,

I decided to pass user name,password and domain while requesting SSRS reports, so I created one class which implements IReportServerCredentials.

 public class ReportServerCredentials : IReportServerCredentials   
{
    #region  Class Members
        private string username;
        private string password;
        private string domain;
    #endregion

    #region Constructor
        public ReportServerCredentials()
        {}
        public ReportServerCredentials(string username)
        {
            this.Username = username;
        }
        public ReportServerCredentials(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }
        public ReportServerCredentials(string username, string password, string domain)
        {
            this.Username = username;
            this.Password = password;
            this.Domain = domain;
        }
    #endregion

    #region Properties
        public string Username
        {
            get { return this.username; }
            set { this.username = value; }
        }
        public string Password
        {
            get { return this.password; }
            set { this.password = value; }
        }
        public string Domain
        {
            get { return this.domain; }
            set { this.domain = value; }
        }
        public WindowsIdentity ImpersonationUser
        {
            get { return null; }
        }
        public ICredentials NetworkCredentials
        {
            get
            {
                return new NetworkCredential(Username, Password, Domain);
            }
        }
    #endregion

    bool IReportServerCredentials.GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority)
    {
        authCookie = null;
        userName = password = authority = null;
        return false;
    }
}

while calling SSRS Reprots, put following piece of code

 ReportViewer rptViewer = new ReportViewer();
 string RptUserName = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUser"]);
        string RptUserPassword = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserPassword"]);
        string RptUserDomain = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserDomain"]);
        string SSRSReportURL = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportURL"]);
        string SSRSReportFolder = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportFolder"]);

        IReportServerCredentials reportCredentials = new ReportServerCredentials(RptUserName, RptUserPassword, RptUserDomain);
        rptViewer.ServerReport.ReportServerCredentials = reportCredentials;
        rptViewer.ServerReport.ReportServerUrl = new Uri(SSRSReportURL);

SSRSReportUser,SSRSReportUserPassword,SSRSReportUserDomain,SSRSReportFolder are defined in web.config files.