Programs & Examples On #Visual studio debugging

Questions related to debugging methods and tricks in VisualStudio

Visual Studio breakpoints not being hit

Go to Visual Studio Menu:

Debug -> Attach to Process

And then click the Select button, as in the image below:

Attach to process

Then make sure the "Automatically determine the type of code to debug" option is selected, like this:

Select code type

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

I had a similar problem while moving from Visual Studio 2013 to Visual Studio 2015 on a MVC project.

Deleting the whole .vs solution worked as a charm as Johan J v Rensburg pointed out.

SSL Connection / Connection Reset with IISExpress

KASPERSKY ISSUE!! I'd tried everything, localhost with SSL worked if I ran VS2019 as Administrator, but the connection was lost after a while of debugging, and I had to re-run the app. The only worked for me was uninstall Kaspersky, unbelievable, days ago I'd tried to pause Kaspersky protection and it didn't solve the problem, so I had discarded antivirus issues, after days of trying solutions, I resumed antivirus matter, uninstalled Kaspersky V 21.1 ..., tried and worked, installed V 21.2 ... and it works fine also without running VS as Administrator

How do I start a program with arguments when debugging?

My suggestion would be to use Unit Tests.

In your application do the following switches in Program.cs:

#if DEBUG
    public class Program
#else
    class Program
#endif

and the same for static Main(string[] args).

Or alternatively use Friend Assemblies by adding

[assembly: InternalsVisibleTo("TestAssembly")]

to your AssemblyInfo.cs.

Then create a unit test project and a test that looks a bit like so:

[TestClass]
public class TestApplication
{
    [TestMethod]
    public void TestMyArgument()
    {
        using (var sw = new StringWriter())
        {
            Console.SetOut(sw); // this makes any Console.Writes etc go to sw

            Program.Main(new[] { "argument" });

            var result = sw.ToString();

            Assert.AreEqual("expected", result);
        }
    }
}

This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.

Makefile, header dependencies

I prefer this solution, over the accepted answer by Michael Williamson, it catches changes to sources+inline files, then sources+headers, and finally sources only. Advantage here is that the whole library is not recompiled if only a a few changes are made. Not a huge consideration for a project with a couple of files, bur if you have 10 or a 100 sources, you will notice the difference.

COMMAND= gcc -Wall -Iinclude ...

%.o: %.cpp %.inl
    $(COMMAND)

%.o: %.cpp %.hpp
    $(COMMAND)

%.o: %.cpp
    $(COMMAND)

How do I compile with -Xlint:unchecked?

If you work with an IDE like NetBeans, you can specify the Xlint:unchecked compiler option in the propertys of your project.

Just go to projects window, right click in the project and then click in Properties.

In the window that appears search the Compiling category, and in the textbox labeled Additional Compiler Options set the Xlint:unchecked option.

Thus, the setting will remain set for every time you compile the project.

C++ error: "Array must be initialized with a brace enclosed initializer"

The syntax to statically initialize an array uses curly braces, like this:

int array[10] = { 0 };

This will zero-initialize the array.

For multi-dimensional arrays, you need nested curly braces, like this:

int cipher[Array_size][Array_size]= { { 0 } };

Note that Array_size must be a compile-time constant for this to work. If Array_size is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector).

Datagrid binding in WPF

try to do this in the behind code

   public diagboxclass()
   {
         List<object> list = new List<object>();
         list = GetObjectList();
         Imported.ItemsSource = null;
         Imported.ItemsSource = list;
   }

Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.

Replace values in list using Python

>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]

How to send data to COM PORT using JAVA?

This question has been asked and answered many times:

Read file from serial port using Java

Reading serial port in Java

Reading file from serial port in Java

Is there Java library or framework for accessing Serial ports?

Java Serial Communication on Windows

to reference a few.

Personally I recommend SerialPort from http://serialio.com - it's not free, but it's well worth the developer (no royalties) licensing fee for any commercial project. Sadly, it is no longer royalty free to deploy, and SerialIO.com seems to have remade themselves as a hardware seller; I had to search for information on SerialPort.

From personal experience, I strongly recommend against the Sun, IBM and RxTx implementations, all of which were unstable in 24/7 use. Refer to my answers on some of the aforementioned questions for details. To be perfectly fair, RxTx may have come a long way since I tried it, though the Sun and IBM implementations were essentially abandoned, even back then.

A newer free option that looks promising and may be worth trying is jSSC (Java Simple Serial Connector), as suggested by @Jodes comment.

How to check 'undefined' value in jQuery

In this case you can use a === undefined comparison: if(val === undefined)

This works because val always exists (it's a function argument).

If you wanted to test an arbitrary variable that is not an argument, i.e. might not be defined at all, you'd have to use if(typeof val === 'undefined') to avoid an exception in case val didn't exist.

400 BAD request HTTP error code meaning?

From w3.org

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

Can you use CSS to mirror/flip text?

Just adding a working demo for horizontal and vertical mirror flip.

_x000D_
_x000D_
.horizontal-flip {_x000D_
  -moz-transform: scale(-1, 1);_x000D_
  -webkit-transform: scale(-1, 1);_x000D_
  -o-transform: scale(-1, 1);_x000D_
  -ms-transform: scale(-1, 1);_x000D_
  transform: scale(-1, 1);_x000D_
}_x000D_
_x000D_
.vertical-flip {_x000D_
  -moz-transform: scale(1, -1);_x000D_
  -webkit-transform: scale(1, -1);_x000D_
  -o-transform: scale(1, -1);_x000D_
  -ms-transform: scale(1, -1);_x000D_
  transform: scale(1, -1);_x000D_
}
_x000D_
<div class="horizontal-flip">_x000D_
  Hello, World_x000D_
  <input type="text">_x000D_
</div>_x000D_
<hr>_x000D_
<div class="vertical-flip">_x000D_
  Hello, World_x000D_
  <input type="text">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can you get the column names from a SqlDataReader?

You sure can.


protected void GetColumNames_DataReader()
{
  System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=localhost;database=northwind;trusted_connection=true");
  System.Data.SqlClient.SqlCommand SqlCmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Products", SqlCon);

  SqlCon.Open();

  System.Data.SqlClient.SqlDataReader SqlReader = SqlCmd.ExecuteReader();
  System.Int32 _columncount = SqlReader.FieldCount;

  System.Web.HttpContext.Current.Response.Write("SqlDataReader Columns");
  System.Web.HttpContext.Current.Response.Write(" ");

  for ( System.Int32 iCol = 0; iCol < _columncount; iCol ++ )
  {
    System.Web.HttpContext.Current.Response.Write("Column " + iCol.ToString() + ": ");
    System.Web.HttpContext.Current.Response.Write(SqlReader.GetName( iCol ).ToString());
    System.Web.HttpContext.Current.Response.Write(" ");
  }

}

This is originally from: http://www.dotnetjunkies.ddj.com/Article/B82A22D1-8437-4C7A-B6AA-C6C9BE9DB8A6.dcik

How to create a XML object from String in Java?

If you can create a string xml you can easily transform it to the xml document object e.g. -

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try {  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
} catch (Exception e) {  
    e.printStackTrace();  
} 

You can use the document object and xml parsing libraries or xpath to get back the ip address.

Install apps silently, with granted INSTALL_PACKAGES permission

I have been implementing installation without user consent recently - it was a kiosk application for API level 21+ where I had full control over environment.

The basic requirements are

  • API level 21+
  • root access to install the updater as a system privileged app.

The following method reads and installs APK from InputStream:

public static boolean installPackage(Context context, InputStream in, String packageName)
            throws IOException {
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        params.setAppPackageName(packageName);
        // set params
        int sessionId = packageInstaller.createSession(params);
        PackageInstaller.Session session = packageInstaller.openSession(sessionId);
        OutputStream out = session.openWrite("COSU", 0, -1);
        byte[] buffer = new byte[65536];
        int c;
        while ((c = in.read(buffer)) != -1) {
            out.write(buffer, 0, c);
        }
        session.fsync(out);
        in.close();
        out.close();

        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("info", "somedata");  // for extra data if needed..

        Random generator = new Random();

        PendingIntent i = PendingIntent.getActivity(context, generator.nextInt(), intent,PendingIntent.FLAG_UPDATE_CURRENT);
            session.commit(i.getIntentSender());


        return true;
    }

The following code calls the installation

 try {
     InputStream is = getResources().openRawResource(R.raw.someapk_source);
                    installPackage(MainActivity.this, is, "com.example.apk");
     } catch (IOException e) {
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
     }

for the whole thing to work you desperately need INSTALL_PACKAGES permission, or the code above will fail silently

<uses-permission
        android:name="android.permission.INSTALL_PACKAGES" />

to get this permission you must install your APK as System application which REQUIRES root (however AFTER you have installed your updater application it seem to work WITHOUT root)

To install as system application I created a signed APK and pushed it with

adb push updater.apk /sdcard/updater.apk

and then moved it to system/priv-app - which requires remounting FS (this is why the root is required)

adb shell
su
mount -o rw,remount /system
mv /sdcard/updater.apk /system/priv-app
chmod 644 /system/priv-app/updater.apk

for some reason it didn't work with simple debug version, but logcat shows useful info if your application in priv-app is not picked up for some reason.

Clear a terminal screen for real

The following link will explain how to make that alias permanent so you don't have to keep typing it in.

https://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias

These are the steps detailed at that link.

  1. vim ~/.bashrc or gedit ~/.bashrc or what ever text editor you like
  2. put alias cls='printf "\033c"' at the bottom of the file
  3. save and exit
  4. . ~/.bashrc (and yes there should be a space between . and ~)
  5. now check to see if everything worked!

I take no credit for this information just passing it along.

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Copy multiple files in Python

You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.

The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)

Define variable to use with IN operator (T-SQL)

No, there is no such type. But there are some choices:

  • Dynamically generated queries (sp_executesql)
  • Temporary tables
  • Table-type variables (closest thing that there is to a list)
  • Create an XML string and then convert it to a table with the XML functions (really awkward and roundabout, unless you have an XML to start with)

None of these are really elegant, but that's the best there is.

If table exists drop table then create it, if it does not exist just create it

Just use DROP TABLE IF EXISTS:

DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

Try searching the MySQL documentation first if you have any other problems.

Change the color of a bullet in a html list?

<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
  • One
  • Two
  • Three
  • How to debug Google Apps Script (aka where does Logger.log log to?)

    A little hacky, but I created an array called "console", and anytime I wanted to output to console I pushed to the array. Then whenever I wanted to see the actual output, I just returned console instead of whatever I was returning before.

        //return 'console' //uncomment to output console
        return "actual output";
    }
    

    How to force a html5 form validation without submitting it via jQuery

    You can do it without submitting the form.

    For example, if the form submit button with id "search" is in the other form . You can call click event on that submit button and call ev.preventDefault after that. For my case I validate form B from Form A submission. Like this

    function validateFormB(ev){ // DOM Event object
      //search is in Form A
      $("#search").click();
      ev.preventDefault();
      //Form B validation from here on
    }
    

    How do I compile a .c file on my Mac?

    Just for the record in modern times,

    for 2017 !

    1 - Just have updated Xcode on your machine as you normally do

    2 - Open terminal and

    $ xcode-select --install
    

    it will perform a short install of a minute or two.

    3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"

    Note - confusingly this is under the "macOS" tab.

    choose this one

    Select "C" language on the next screen...

    enter image description here

    4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.

    5 - You're golden! You can now enjoy c with Mac and Xcode.

    you're golden

    Specifying row names when reading in a file

    If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

    read.table(file = "foo.txt", row.names = 1, ....)
    

    where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

    If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

    rownames(obj) <- obj[, 1]  ## set rownames
    obj <- obj[, -1]           ## remove the first variable
    

    How can I find the OWNER of an object in Oracle?

    You can query the ALL_OBJECTS view:

    select owner
         , object_name
         , object_type
      from ALL_OBJECTS
     where object_name = 'FOO'
    

    To find synonyms:

    select *
      from ALL_SYNONYMS
     where synonym_name = 'FOO'
    

    Just to clarify, if a user user's SQL statement references an object name with no schema qualification (e.g. 'FOO'), Oracle FIRST checks the user's schema for an object of that name (including synonyms in that user's schema). If Oracle can't resolve the reference from the user's schema, Oracle then checks for a public synonym.

    If you are looking specifically for constraints on a particular table_name:

    select c.*
      from all_constraints c 
     where c.table_name = 'FOO'
     union all
    select cs.*
      from all_constraints cs
      join all_synonyms s 
        on (s.table_name = cs.table_name
         and s.table_owner = cs.owner 
         and s.synonym_name = 'FOO'
           )
    

    HTH

    -- addendum:

    If your user is granted access to the DBA_ views (e.g. if your user has been granted SELECT_CATALOG_ROLE), you can substitute 'DBA_' in place of 'ALL_' in the preceding SQL examples. The ALL_x views only show objects which you have been granted privileges. The DBA_x views will show all database objects, whether you have privileges on them or not.

    How to convert a NumPy array to PIL image applying matplotlib colormap

    The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:

    import matplotlib.pyplot as plt
    plt.imsave(filename, np_array, cmap='Greys')
    

    np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.

    Difference between Divide and Conquer Algo and Dynamic Programming

    • Divide and Conquer
      • They broke into non-overlapping sub-problems
      • Example: factorial numbers i.e. fact(n) = n*fact(n-1)
    fact(5) = 5* fact(4) = 5 * (4 * fact(3))= 5 * 4 * (3 *fact(2))= 5 * 4 * 3 * 2 * (fact(1))
    

    As we can see above, no fact(x) is repeated so factorial has non overlapping problems.

    • Dynamic Programming
      • They Broke into overlapping sub-problems
      • Example: Fibonacci numbers i.e. fib(n) = fib(n-1) + fib(n-2)
    fib(5) = fib(4) + fib(3) = (fib(3)+fib(2)) + (fib(2)+fib(1))
    

    As we can see above, fib(4) and fib(3) both use fib(2). similarly so many fib(x) gets repeated. that's why Fibonacci has overlapping sub-problems.

    • As a result of the repetition of sub-problem in DP, we can keep such results in a table and save computation effort. this is called as memoization

    Should I use Python 32bit or Python 64bit

    Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.

    iframe refuses to display

    The reason for the error is that the host server for https://cw.na1.hgncloud.com has provided some HTTP headers to protect the document. One of which is that the frame ancestors must be from the same domain as the original content. It seems you are attempting to put the iframe at a domain location that is not the same as the content of the iframe - thus violating the Content Security Policy that the host has set.

    Check out this link on Content Security Policy for more details.

    Truncate (not round off) decimal numbers in javascript

    You can work with strings. It Checks if '.' exists, and then removes part of string.

    truncate (7.88, 1) --> 7.8

    truncate (7.889, 2) --> 7.89

    truncate (-7.88, 1 ) --> -7.88

    function  truncate(number, decimals) {
        const tmp = number + '';
        if (tmp.indexOf('.') > -1) {
            return +tmp.substr(0 , tmp.indexOf('.') + decimals+1 );
        } else {
            return +number
        }
     }
    

    Where are static variables stored in C and C++?

    I tried it with objdump and gdb, here is the result what I get:

    (gdb) disas fooTest
    Dump of assembler code for function fooTest:
       0x000000000040052d <+0>: push   %rbp
       0x000000000040052e <+1>: mov    %rsp,%rbp
       0x0000000000400531 <+4>: mov    0x200b09(%rip),%eax        # 0x601040 <foo>
       0x0000000000400537 <+10>:    add    $0x1,%eax
       0x000000000040053a <+13>:    mov    %eax,0x200b00(%rip)        # 0x601040 <foo>
       0x0000000000400540 <+19>:    mov    0x200afe(%rip),%eax        # 0x601044 <bar.2180>
       0x0000000000400546 <+25>:    add    $0x1,%eax
       0x0000000000400549 <+28>:    mov    %eax,0x200af5(%rip)        # 0x601044 <bar.2180>
       0x000000000040054f <+34>:    mov    0x200aef(%rip),%edx        # 0x601044 <bar.2180>
       0x0000000000400555 <+40>:    mov    0x200ae5(%rip),%eax        # 0x601040 <foo>
       0x000000000040055b <+46>:    mov    %eax,%esi
       0x000000000040055d <+48>:    mov    $0x400654,%edi
       0x0000000000400562 <+53>:    mov    $0x0,%eax
       0x0000000000400567 <+58>:    callq  0x400410 <printf@plt>
       0x000000000040056c <+63>:    pop    %rbp
       0x000000000040056d <+64>:    retq   
    End of assembler dump.
    
    (gdb) disas barTest
    Dump of assembler code for function barTest:
       0x000000000040056e <+0>: push   %rbp
       0x000000000040056f <+1>: mov    %rsp,%rbp
       0x0000000000400572 <+4>: mov    0x200ad0(%rip),%eax        # 0x601048 <foo>
       0x0000000000400578 <+10>:    add    $0x1,%eax
       0x000000000040057b <+13>:    mov    %eax,0x200ac7(%rip)        # 0x601048 <foo>
       0x0000000000400581 <+19>:    mov    0x200ac5(%rip),%eax        # 0x60104c <bar.2180>
       0x0000000000400587 <+25>:    add    $0x1,%eax
       0x000000000040058a <+28>:    mov    %eax,0x200abc(%rip)        # 0x60104c <bar.2180>
       0x0000000000400590 <+34>:    mov    0x200ab6(%rip),%edx        # 0x60104c <bar.2180>
       0x0000000000400596 <+40>:    mov    0x200aac(%rip),%eax        # 0x601048 <foo>
       0x000000000040059c <+46>:    mov    %eax,%esi
       0x000000000040059e <+48>:    mov    $0x40065c,%edi
       0x00000000004005a3 <+53>:    mov    $0x0,%eax
       0x00000000004005a8 <+58>:    callq  0x400410 <printf@plt>
       0x00000000004005ad <+63>:    pop    %rbp
       0x00000000004005ae <+64>:    retq   
    End of assembler dump.
    

    here is the objdump result

    Disassembly of section .data:
    
    0000000000601030 <__data_start>:
        ...
    
    0000000000601038 <__dso_handle>:
        ...
    
    0000000000601040 <foo>:
      601040:   01 00                   add    %eax,(%rax)
        ...
    
    0000000000601044 <bar.2180>:
      601044:   02 00                   add    (%rax),%al
        ...
    
    0000000000601048 <foo>:
      601048:   0a 00                   or     (%rax),%al
        ...
    
    000000000060104c <bar.2180>:
      60104c:   14 00                   adc    $0x0,%al
    

    So, that's to say, your four variables are located in data section event the the same name, but with different offset.

    Right pad a string with variable number of spaces

    This is based on Jim's answer,

    SELECT
        @field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
       ,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad
    

    Advantages

    • More Straight Forward
    • Slightly Cleaner (IMO)
    • Faster (Maybe?)
    • Easily Modified to either double pad for displaying in non-fixed width fonts or split padding left and right to center

    Disadvantages

    • Doesn't handle LEN(@field_text) > @pad_length

    Task continuation on UI thread

    With async you just do:

    await Task.Run(() => do some stuff);
    // continue doing stuff on the same context as before.
    // while it is the default it is nice to be explicit about it with:
    await Task.Run(() => do some stuff).ConfigureAwait(true);
    

    However:

    await Task.Run(() => do some stuff).ConfigureAwait(false);
    // continue doing stuff on the same thread as the task finished on.
    

    Undo git pull, how to bring repos to old state

    Running git pull performs the following tasks, in order:

    1. git fetch
    2. git merge

    The merge step combines branches that have been setup to be merged in your config. You want to undo the merge step, but probably not the fetch (doesn't make a lot of sense and shouldn't be necessary).

    To undo the merge, use git reset --hard to reset the local repository to a previous state; use git-reflog to find the SHA-1 of the previous state and then reset to it.

    Warning

    The commands listed in this section remove all uncommitted changes, potentially leading to a loss of work:

    git reset --hard
    

    Alternatively, reset to a particular point in time, such as:

    git reset --hard master@{"10 minutes ago"}
    

    PHP PDO returning single row

    Just fetch. only gets one row. So no foreach loop needed :D

    $row  = $STH -> fetch();
    

    example (ty northkildonan):

    $dbh = new PDO(" --- connection string --- "); 
    $stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 
    $stmt->execute(); 
    $row = $stmt->fetch();
    

    NULL vs nullptr (Why was it replaced?)

    nullptr is always a pointer type. 0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

    f(int);
    f(foo *);
    

    Writing sqlplus output to a file

    just to save my own deductions from all this is (for saving DBMS_OUTPUT output on the client, using sqlplus):

    • no matter if i use Toad/with polling or sqlplus, for a long running script with occasional dbms_output.put_line commands, i will get the output in the end of the script execution
    • set serveroutput on; and dbms_output.enable(); should be present in the script
    • to save the output SPOOL command was not enough to get the DBMS_OUTPUT lines printed to a file - had to use the usual > windows CMD redirection. the passwords etc. can be given to the empty prompt, after invoking sqlplus. also the "/" directives and the "exit;" command should be put either inside the script, or given interactively as the password above (unless it is specified during the invocation of sqlplus)

    Regular Expression for password validation

    There seems to be a lot of confusion here. The answers I see so far don't correctly enforce the 1+ number/1+ lowercase/1+ uppercase rule, meaning that passwords like abc123, 123XYZ, or AB*&^# would still be accepted. Preventing all-lowercase, all-caps, or all-digits is not enough; you have to enforce the presence of at least one of each.

    Try the following:

    ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$
    

    If you also want to require at least one special character (which is probably a good idea), try this:

    ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$
    

    The .{8,15} can be made more restrictive if you wish (for example, you could change it to \S{8,15} to disallow whitespace), but remember that doing so will reduce the strength of your password scheme.

    I've tested this pattern and it works as expected. Tested on ReFiddle here: http://refiddle.com/110


    Edit: One small note, the easiest way to do this is with 3 separate regexes and the string's Length property. It's also easier to read and maintain, so do it that way if you have the option. If this is for validation rules in markup, though, you're probably stuck with a single regex.

    How to rotate x-axis tick labels in Pandas barplot

    Pass param rot=0 to rotate the xticks:

    import matplotlib
    matplotlib.style.use('ggplot')
    import matplotlib.pyplot as plt
    import pandas as pd
    
    df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
    df = df[["celltype","s1","s2"]]
    df.set_index(["celltype"],inplace=True)
    df.plot(kind='bar',alpha=0.75, rot=0)
    plt.xlabel("")
    plt.show()
    

    yields plot:

    enter image description here

    C# how to wait for a webpage to finish loading before continuing

    Assuming the "commit" element represents a standard Form submit button then you can attach an event handler to the WebBrowsers Navigated event.

    MS Access VBA: Sending an email through Outlook

    Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

    Public Function SendEmail2()
    
    Dim varName As Variant          
    Dim varCC As Variant            
    Dim varSubject As Variant      
    Dim varBody As Variant          
    
    varName = "[email protected]"
    varCC = "[email protected], [email protected]"
    'separate each email by a ','
    
    varSubject = "Hello"
    'Email subject
    
    varBody = "Let's get ice cream this week"
    
    'Body of the email
    DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
    'Send email command. The True after "varBody" allows user to edit email before sending.
    'The False at the end will not send it as a Template File
    
    End Function
    

    How to install pandas from pip on windows cmd?

    Reply to abccd and Question to anyone:

    The command: C:\Python34\Scripts>py -3 -m pip install pandas executed just fine. Unfortunately, I can't import Pandas.

    Directory path: C:\users\myname\downloads\miniconda3\lib\site-packages

    My Question: How is it that Pandas' dependency packages(numpy, python-dateutil, pytz, six) also having the same above directory path are able to import just fine but Pandas does not?

    import pandas
    
    Traceback (most recent call last):
      File "<pyshell#9>", line 1, in <module>
        import pandas
    ImportError: No module named 'pandas'
    

    I finally got Pandas reinstalled and imported with the help of the following web pages: *http://pandas.pydata.org/pandas-docs/stable/pandas.pdf (Pages 403 and 404 of 2215 ... 2.2.2 Installing Pandas with Miniconda) *https://conda.io/docs/user-guide/install/download.html *https://conda.io/docs/user-guide/getting-started.html

    After installing Miniconda, I created a new environment area to get Pandas reinstalled and imported. This new environment included the current Python version 3.6.3. I could not import Pandas using Python 3.4.4.

    how to get the selected index of a drop down

    You can also use :checked for <select> elements

    e.g.,

    document.querySelector('select option:checked')
    document.querySelector('select option:checked').getAttribute('value')
    

    You don't even have to get the index and then reference the element by its sibling index.

    How to Set the Background Color of a JButton on the Mac OS

    Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose

    jQuery get html of container including the container itself

    $.fn.outerHtml = function(){
        if (this.length) {
            var div = $('<div style="display:none"></div>');
            var clone =
            $(this[0].cloneNode(false)).html(this.html()).appendTo(div);
            var outer = div.html();
            div.remove();
            return outer;
        }
        else {
            return null;
        }
    };
    

    from http://forum.jquery.com/topic/jquery-getting-html-and-the-container-element-12-1-2010

    The import com.google.android.gms cannot be resolved

    Note that once you have imported the google-play-services_lib project into your IDE, you will also need to add google-play-services.jar to: Project=>Properties=>Java build path=>Libraries=>Add JARs

    Onclick CSS button effect

    This is a press down button example I've made:

    <div>
        <form id="forminput" action="action" method="POST">
           ...
        </form>
        <div style="right: 0px;bottom: 0px;position: fixed;" class="thumbnail">
            <div class="image">
                <a onclick="document.getElementById('forminput').submit();">
                    <img src="images/button.png" alt="Some awesome text">
                </a>
            </div>
        </div>
    </div>
    

    the CSS file:

    .thumbnail {
        width: 128px;
        height: 128px;
    }
    
    .image {
        width: 100%;
        height: 100%;    
    }
    
    .image img {
        -webkit-transition: all .25s ease; /* Safari and Chrome */
        -moz-transition: all .25s ease; /* Firefox */
        -ms-transition: all .25s ease; /* IE 9 */
        -o-transition: all .25s ease; /* Opera */
        transition: all .25s ease;
        max-width: 100%;
        max-height: 100%;
    }
    
    .image:hover img {
        -webkit-transform:scale(1.05); /* Safari and Chrome */
        -moz-transform:scale(1.05); /* Firefox */
        -ms-transform:scale(1.05); /* IE 9 */
        -o-transform:scale(1.05); /* Opera */
         transform:scale(1.05);
    }
    
    .image:active img {
        -webkit-transform:scale(.95); /* Safari and Chrome */
        -moz-transform:scale(.95); /* Firefox */
        -ms-transform:scale(.95); /* IE 9 */
        -o-transform:scale(.95); /* Opera */
         transform:scale(.95);
    }
    

    Enjoy it!

    How do I set the focus to the first input element in an HTML form independent from the id?

    document.forms[0].elements[0].focus();
    

    This can be refined using a loop to eg. not focus certain types of field, disabled fields and so on. Better may be to add a class="autofocus" to the field you actually do want focused, and loop over forms[i].elements[j] looking for that className.

    Anyhow: it's not normally a good idea to do this on every page. When you focus an input the user loses the ability to eg. scroll the page from the keyboard. If unexpected, this can be annoying, so only auto-focus when you're pretty sure that using the form field is going to be what the user wants to do. ie. if you're Google.

    How to attach a file using mail command on Linux?

    mail on every version of modern Linux that I've tried can do it. No need for other software:

    matiu@matiu-laptop:~$ mail -a doc.jpg [email protected]
    Subject: testing
    
    This is a test
    EOT
    

    ctrl+d when you're done typing.

    Generating a random password in php

    I created a more comprehensive and secure password script. This will create a combination of two uppercase, two lowercase, two numbers and two special characters. Total 8 characters.

    $char = [range('A','Z'),range('a','z'),range(0,9),['*','%','$','#','@','!','+','?','.']];
    $pw = '';
    for($a = 0; $a < count($char); $a++)
    {
        $randomkeys = array_rand($char[$a], 2);
        $pw .= $char[$a][$randomkeys[0]].$char[$a][$randomkeys[1]];
    }
    $userPassword = str_shuffle($pw);
    

    Latex - Change margins of only a few pages

    I could not find a easy way to set the margin for a single page.

    My solution was to use vspace with the number of centimeters of empty space I wanted:

     \vspace*{5cm}                                                             
    

    I put this command at the beginning of the pages that I wanted to have +5cm of margin.

    What does $1 mean in Perl?

    Since you asked about the capture groups, you might want to know about $+ too... Pretty useful...

    use Data::Dumper;
    $text = "hiabc ihabc ads byexx eybxx";
    while ($text =~ /(hi|ih)abc|(bye|eyb)xx/igs)
    {
        print Dumper $+;
    }
    

    OUTPUT:
    $VAR1 = 'hi';
    $VAR1 = 'ih';
    $VAR1 = 'bye';
    $VAR1 = 'eyb';

    Setting and getting localStorage with jQuery

    Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

    Sample using .text()

    // get the text
    var text = $('#test').text();
    
    // set the item in localStorage
    localStorage.setItem('test', text);
    
    // alert the value to check if we got it
    alert(localStorage.getItem('test'));
    

    JSFiddle: https://jsfiddle.net/f3zLa3zc/


    Storing the HTML itself

    // get html
    var html = $('#test')[0].outerHTML;
    
    // set localstorage
    localStorage.setItem('htmltest', html);
    
    // test if it works
    alert(localStorage.getItem('htmltest'));
    

    JSFiddle:
    https://jsfiddle.net/psfL82q3/1/


    Update on user comment

    A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

    // get the text
    var text = $('#test').text();
    
    // set the item in localStorage
    localStorage.setItem('test', text);
    
    // bind text to 'blur' event for div
    $('#test').on('blur', function() {
    
        // check the new text
        var newText = $(this).text();
    
        // overwrite the old text
        localStorage.setItem('test', newText);
    
        // test if it works
        alert(localStorage.getItem('test'));
    
    });
    

    If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

    JSFiddle:
    https://jsfiddle.net/g1b8m1fc/

    Pretty Printing JSON with React

    const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")
    
    const JSONDisplayer = ({children}) => (
        <div>
            <pre>{getJsonIndented(children)}</pre>
        </div>
    )
    

    Then you can easily use it:

    const Demo = (props) => {
       ....
       return <JSONDisplayer>{someObj}<JSONDisplayer>
    }
    

    PHP float with 2 decimal places: .00

    A float isn't have 0 or 0.00 : those are different string representations of the internal (IEEE754) binary format but the float is the same.

    If you want to express your float as "0.00", you need to format it in a string, using number_format :

    $numberAsString = number_format($numberAsFloat, 2);
    

    How do you change the character encoding of a postgres database?

    First off, Daniel's answer is the correct, safe option.

    For the specific case of changing from SQL_ASCII to something else, you can cheat and simply poke the pg_database catalogue to reassign the database encoding. This assumes you've already stored any non-ASCII characters in the expected encoding (or that you simply haven't used any non-ASCII characters).

    Then you can do:

    update pg_database set encoding = pg_char_to_encoding('UTF8') where datname = 'thedb'
    

    This will not change the collation of the database, just how the encoded bytes are converted into characters (so now length('£123') will return 4 instead of 5). If the database uses 'C' collation, there should be no change to ordering for ASCII strings. You'll likely need to rebuild any indices containing non-ASCII characters though.

    Caveat emptor. Dumping and reloading provides a way to check your database content is actually in the encoding you expect, and this doesn't. And if it turns out you did have some wrongly-encoded data in the database, rescuing is going to be difficult. So if you possibly can, dump and reinitialise.

    iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

    It is a runtime error that is caused by Dynamic Linker

    dyld: Library not loaded: @rpath/...
    ...
    Reason: image not found
    

    The error Library not loaded with @rpath indicates that Dynamic Linker cannot find the binary.

    1. Check if the dynamic framework was added to General -> Embedded Binaries

    2. Check the @rpath setup between consumer(application) and producer(dynamic framework):

      • Dynamic framework:
        • Build Settings -> Dynamic Library Install Name
      • Application:
        • Build Settings -> Runpath Search Paths
        • Build Phases -> Embed Frameworks -> Destination, Subpath

    Dynamic linker

    Dynamic Library Install Name(LD_DYLIB_INSTALL_NAME) which is used by loadable bundle(Dynamic framework as a derivative) where dyld come into play
    Dynamic Library Install Name - path to binary file(not .framework). Yes, they have the same name, but MyFramework.framework is a packaged bundle with MyFramework binary file and resources inside.
    This path to directory can be absolute or relative(e.g. @executable_path, @loader_path, @rpath). Relative path is more preferable because it is changed together with an anchor that is useful when you distribute your bundle as a single directory

    absolute path - Framework1 example

    //Framework1 Dynamic Library Install Name
    /some_path/Framework1.framework/subfolder1
    

    @executable_path

    @executable_path - relative to entry binary - Framework2 example
    use case: embed a Dynamic framework into an application

    //Application bundle(`.app` package) absolute path
    /some_path/Application.?pp
    
    //Application binary absolute path 
    /some_path/Application.?pp/subfolder1
    
    //Framework2 binary absolute path
    /some_path/Application.?pp/Frameworks/Framework2.framework/subfolder1
    
    //Framework2 @executable_path == Application binary absolute path
    /some_path/Application.?pp/subfolder1
    
    //Framework2 Dynamic Library Install Name 
    @executable_path/../Frameworks/Framework2.framework/subfolder1
    
    //Framework2 binary resolved absolute path by dyld
    /some_path/Application.?pp/subfolder1/../Frameworks/Framework2.framework/subfolder1
    /some_path/Application.?pp/Frameworks/Framework2.framework/subfolder1
    

    @loader_path

    @loader_path - relative to bundle which is an owner of this binary
    use case: framework with embedded framework - Framework3_1 with Framework3_2 inside

    //Framework3_1 binary absolute path
    /some_path/Application.?pp/Frameworks/Framework3_1.framework/subfolder1
    
    //Framework3_2 binary absolute path
    /some_path/Application.?pp/Frameworks/Framework3_1.framework/Frameworks/Framework3_2.framework/subfolder1
    
    //Framework3_1 @executable_path == Application binary absolute path
    /some_path/Application.?pp/subfolder1
    
    //Framework3_1 @loader_path == Framework3_1 @executable_path
    /some_path/Application.?pp/subfolder1
    
    //Framework3_2 @executable_path == Application binary absolute path
    /some_path/Application.?pp/subfolder1
    
    //Framework3_2 @loader_path == Framework3_1 binary absolute path
    /some_path/Application.?pp/Frameworks/Framework3_1.framework/subfolder1
    
    //Framework3_2 Dynamic Library Install Name 
    @loader_path/../Frameworks/Framework3_2.framework/subfolder1
    
    //Framework3_2 binary resolved absolute path by dyld
    /some_path/Application.?pp/Frameworks/Framework3_1.framework/subfolder1/../Frameworks/Framework3_2.framework/subfolder1
    /some_path/Application.?pp/Frameworks/Framework3_1.framework/Frameworks/Framework3_2.framework/subfolder1
    

    @rpath - Runpath Search Path

    Framework2 example

    Previously we had to setup a Framework to work with dyld. It is not convenient because the same Framework can not be used with a different configurations

    @rpath is a compound concept that relies on outer(Application) and nested(Dynamic framework) parts:

    • Application:

      • Runpath Search Paths(LD_RUNPATH_SEARCH_PATHS) - defines a list of templates which be substituted with @rpath.
         @executable_path/../Frameworks
        
      • Review Build Phases -> Embed Frameworks -> Destination, Subpath to be shire where exactly the embed framework is located
    • Dynamic Framework:

      • Dynamic Library Install Name(LD_DYLIB_INSTALL_NAME) - point that @rpath is used together with local bundle path to a binary
        @rpath/Framework2.framework/subfolder1
        
    //Application Runpath Search Paths
    @executable_path/../Frameworks
    
    //Framework2 Dynamic Library Install Name
    @rpath/Framework2.framework/subfolder1
    
    //Framework2 binary resolved absolute path by dyld
    //Framework2 @rpath is replaced by each element of Application Runpath Search Paths
    @executable_path/../Frameworks/Framework2.framework/subfolder1
    /some_path/Application.?pp/Frameworks/Framework2.framework/subfolder1
    

    *../ - go to the parent of the current directory

    otool - object file displaying tool

    //-L print shared libraries used
    //Application otool -L
    @rpath/Framework2.framework/subfolder1/Framework2
    
    //Framework2 otool -L
    @rpath/Framework2.framework/subfolder1/Framework2
    
    //-l print the load commands
    //Application otool -l
    LC_LOAD_DYLIB
    @rpath/Framework2.framework/subfolder1/Framework2
    
    LC_RPATH
    @executable_path/../Frameworks
    
    //Framework2 otool -l
    LC_ID_DYLIB
    @rpath/Framework2.framework/subfolder1/Framework2
    

    install_name_tool change dynamic shared library install names using -rpath

    CocoaPods uses use_frameworks![About] to regulate a Dynamic Linker

    [Vocabulary]

    Declare a variable as Decimal

    You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

    Check for a substring in a string in Oracle without LIKE

    I'm guessing the reason you're asking is performance? There's the instr function. But that's likely to work pretty much the same behind the scenes.

    Maybe you could look into full text search.

    As last resorts you'd be looking at caching or precomputed columns/an indexed view.

    Angular2 equivalent of $document.ready()

    You can fire an event yourself in ngOnInit() of your Angular root component and then listen for this event outside of Angular.

    This is Dart code (I don't know TypeScript) but should't be to hard to translate

    @Component(selector: 'app-element')
    @View(
        templateUrl: 'app_element.html',
    )
    class AppElement implements OnInit {
      ElementRef elementRef;
      AppElement(this.elementRef);
    
      void ngOnInit() {
        DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
      }
    }
    

    What __init__ and self do in Python?

    __init__ does act like a constructor. You'll need to pass "self" to any class functions as the first argument if you want them to behave as non-static methods. "self" are instance variables for your class.

    Split column at delimiter in data frame

    Just came across this question as it was linked in a recent question on SO.

    Shameless plug of an answer: Use cSplit from my "splitstackshape" package:

    df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
    library(splitstackshape)
    cSplit(df, "FOO", "|")
    #   ID FOO_1 FOO_2
    # 1 11     a     b
    # 2 12     b     c
    # 3 13     x     y
    

    This particular function also handles splitting multiple columns, even if each column has a different delimiter:

    df <- data.frame(ID=11:13, 
                     FOO=c('a|b','b|c','x|y'), 
                     BAR = c("A*B", "B*C", "C*D"))
    cSplit(df, c("FOO", "BAR"), c("|", "*"))
    #   ID FOO_1 FOO_2 BAR_1 BAR_2
    # 1 11     a     b     A     B
    # 2 12     b     c     B     C
    # 3 13     x     y     C     D
    

    Essentially, it's a fancy convenience wrapper for using read.table(text = some_character_vector, sep = some_sep) and binding that output to the original data.frame. In other words, another A base R approach could be:

    df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
    cbind(df, read.table(text = as.character(df$FOO), sep = "|"))
      ID FOO V1 V2
    1 11 a|b  a  b
    2 12 b|c  b  c
    3 13 x|y  x  y
    

    Sorting a vector in descending order

    According to my machine, sorting a long long vector of [1..3000000] using the first method takes around 4 seconds, while using the second takes about twice the time. That says something, obviously, but I don't understand why either. Just think this would be helpful.

    Same thing reported here.

    As said by Xeo, with -O3 they use about the same time to finish.

    How to convert a datetime to string in T-SQL

    There are many different ways to convert a datetime to a string. Here is one way:

    SELECT convert(varchar(25), getdate(), 121)  – yyyy-mm-dd hh:mm:ss.mmm
    

    See Demo

    Here is a website that has a list of all of the conversions:

    How to Format datetime & date in SQL Server

    Why does the JFrame setSize() method not set the size correctly?

    On OS X, you need to take into account existing window decorations. They add 22 pixels to the height. So on a JFrame, you need to tell the program this:

    frame.setSize(width, height + 22);
    

    What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

    try this:

    $names = array('Jesse', 'joey', 'jelnny', 'justine');
    $names = new ArrayObject($names);
    
    echo '<pre>';
    print_r($names);
    

    vs this:

    $names = array('Jesse', 'joey', 'jelnny', 'justine');
    $names = new ArrayObject($names);
    
    //echo '<pre>';
    print_r($names);
    

    and it shows what the PRE does very neatly

    Get yesterday's date using Date

    There is no direct function to get yesterday's date.

    To get yesterday's date, you need to use Calendar by subtracting -1.

    Export to xls using angularjs

    I had this problem and I made a tool to export an HTML table to CSV file. The problem I had with FileSaver.js is that this tool grabs the table with html format, this is why some people can't open the file in excel or google. All you have to do is export the js file and then call the function. This is the github url https://github.com/snake404/tableToCSV if someone has the same problem.

    What is the difference between Nexus and Maven?

    Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

    Details

    Stylesheet not updating

    In my case, since I could not append a cache busting timestamp to the css url it turned out that I had to manually refresh the application pool in IIS 7.5.7600.

    Every other avenue was pursued, right down to disabling the caching entirely for the site and also for the local browser (like ENTIRELY disabled for both), still didn't do the trick. Also "restarting" the website did nothing.

    Same position as me? [Site Name] > "Application Pool" > "Recycle" is your last resort...

    get the value of DisplayName attribute

    Assuming property as PropertyInfo type, you can do this in one single line:

    property.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().Single().DisplayName
    

    "Post Image data using POSTMAN"

    Now you can hover the key input and select "file", which will give you a file selector in the value column:

    enter image description here

    Remove icon/logo from action bar on android

    getActionBar().setIcon(android.R.color.transparent);
    

    This worked for me.

    What version of JBoss I am running?

    In your JBoss lib Directory:

    • Open the file jboss-system.jar by example
    • Extract the file MANIFEST.MF from the META-INF directory
    • Open MANIFEST.MF with a text editor and then look at the property Specification-Version and Implementation-Version

    How to import jquery using ES6 syntax?

    You can import like this

    import("jquery").then((jQuery) => {
      window.$ = jQuery;
      window.jQuery = jQuery;
      import("bootstrap").then((_bs)=>{
        $(function() {});
      })
    });
    

    JSON and XML comparison

    The important thing about JSON is to keep data transfer encrypted for security reasons. No doubt that JSON is much much faster then XML. I have seen XML take 100ms where as JSON only took 60ms. JSON data is easy to manipulate.

    C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

    You need to fix the source of the string in the first place.

    A string in .NET is actually just an array of 16-bit unicode code-points, characters, so a string isn't in any particular encoding.

    It's when you take that string and convert it to a set of bytes that encoding comes into play.

    In any case, the way you did it, encoded a string to a byte array with one character set, and then decoding it with another, will not work, as you see.

    Can you tell us more about where that original string comes from, and why you think it has been encoded wrong?

    How do I prevent Eclipse from hanging on startup?

    This one works for me:

    Another, and a bit better workaround which apparently works:

    1. Close Eclipse.
    2. Temporary move offending project somewhere out of the workspace.
    3. Start Eclipse, wait for workspace to load (it should).
    4. Close Eclipse again.
    5. Move the project back to workspace.

    Source: Eclipse hangs while opening workspace after upgrading to GWT 2.0/Google app engine 1.2.8

    Taking pictures with camera on Android programmatically

    The following is a simple way to open the camera:

    private void startCamera() {
    
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
        startActivityForResult(intent, 1);
    }
    

    How to find Control in TemplateField of GridView?

    I have done it accessing the controls inside the cell control. Find in all control collections.

     ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;
    
     Label lbCod = (Label)cc[1];
    

    iPhone is not available. Please reconnect the device

    Restarting my Mac was the only thing that resolved the problem.

    Other things I tried before restarting which didn't work:

    • Restarting Xcode.
    • Re-attaching the iPhone.
    • Restarting the iPhone.

    I am also now using wireless debugging after reading DanielSmurts' answer.

    How do I create/edit a Manifest file?

    The simplest way to create a manifest is:

    Project Properties -> Security -> Click "enable ClickOnce security settings" 
    (it will generate default manifest in your project Properties) -> then Click 
    it again in order to uncheck that Checkbox -> open your app.maifest and edit 
    it as you wish.
    

    Manifest location preview

    How to overlay image with color in CSS?

    #header.overlay {
        background-color: SlateGray;
        position:relative;
        width: 100%;
        height: 100%;
        opacity: 0.20;
        -moz-opacity: 20%;
        -webkit-opacity: 20%;
        z-index: 2;
    }
    

    Something like this. Just add the overlay class to the header, obviously.

    Toggle Class in React

    Ori Drori's comment is correct, you aren't doing this the "React Way". In React, you should ideally not be changing classes and event handlers using the DOM. Do it in the render() method of your React components; in this case that would be the sideNav and your Header. A rough example of how this would be done in your code is as follows.

    HEADER

    class Header extends React.Component {
    constructor(props){
        super(props);
    }
    
    render() {
        return (
            <div className="header">
                <i className="border hide-on-small-and-down"></i>
                <div className="container">
                    <a ref="btn" href="#" className="btn-menu show-on-small"
                    onClick=this.showNav><i></i></a>
                    <Menu className="menu hide-on-small-and-down"/>
                    <Sidenav ref="sideNav"/>
                </div>
            </div>
        )
    }
    
    showNav() {
      this.refs.sideNav.show();
    }
    }
    

    SIDENAV

     class SideNav extends React.Component {
       constructor(props) {
         super(props);
         this.state = {
           open: false
         }
       }
    
       render() {
         if (this.state.open) {
           return ( 
             <div className = "sideNav">
                This is a sidenav 
             </div>
           )
         } else {
           return null;
         }
    
       }
    
       show() {
         this.setState({
           open: true
         })
       }
     }
    

    You can see here that we are not toggling classes but using the state of the components to render the SideNav. This way, or similar is the whole premise of using react. If you are using bootstrap, there is a library which integrates bootstrap elements with the react way of doing things, allowing you to use the same elements but set state on them instead of directly manipulating the DOM. It can be found here - https://react-bootstrap.github.io/

    Hope this helps, and enjoy using React!

    CSS scale down image to fit in containing div, without specifing original size

    I believe this is the best way of doing it, I've tried it and it works very well.

    #img {
      object-fit: cover;
    }
    

    This is where I found it. Good luck!

    Decimal number regular expression, where digit after decimal is optional

    ^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$
    

    should reflect what people usually think of as a well formed decimal number.

    The digits before the decimal point can be either a single digit, in which case it can be from 0 to 9, or more than one digits, in which case it cannot start with a 0.

    If there are any digits present before the decimal sign, then the decimal and the digits following it are optional. Otherwise, a decimal has to be present followed by at least one digit. Note that multiple trailing 0's are allowed after the decimal point.

    grep -E '^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$'
    

    correctly matches the following:

    9
    0
    10
    10.
    0.
    0.0
    0.100
    0.10
    0.01
    10.0
    10.10
    .0
    .1
    .00
    .100
    .001
    

    as well as their signed equivalents, whereas it rejects the following:

    .
    00
    01
    00.0
    01.3
    

    and their signed equivalents, as well as the empty string.

    How do I install ASP.NET MVC 5 in Visual Studio 2012?

    You should be able to install from NuGet (http://www.nuget.org/packages/Microsoft.AspNet.Mvc) into VS2012. Change the Target Framework to .NET 4.5.

    Not sure the new project templates are ready for VS2012. But if you have an ASP.NET MVC 4 app you can upgrade using the link below.

    http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

    C++ convert from 1 char to string?

    All of

    std::string s(1, c); std::cout << s << std::endl;
    

    and

    std::cout << std::string(1, c) << std::endl;
    

    and

    std::string s; s.push_back(c); std::cout << s << std::endl;
    

    worked for me.

    Uncaught ReferenceError: $ is not defined error in jQuery

    Include the jQuery file first:

     <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
     <script type="text/javascript" src="./javascript.js"></script>
        <script
            src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
        </script>
    

    Saving excel worksheet to CSV files with filename+worksheet name using VB

    Best way to find out is to record the macro and perform the exact steps and see what VBA code it generates. you can then go and replace the bits you want to make generic (i.e. file names and stuff)

    How do I escape a reserved word in Oracle?

    Oracle normally requires double-quotes to delimit the name of identifiers in SQL statements, e.g.

    SELECT "MyColumn" AS "MyColAlias"
    FROM "MyTable" "Alias"
    WHERE "ThisCol" = 'That Value';
    

    However, it graciously allows omitting the double-quotes, in which case it quietly converts the identifier to uppercase:

    SELECT MyColumn AS MyColAlias
    FROM MyTable Alias
    WHERE ThisCol = 'That Value';
    

    gets internally converted to something like:

    SELECT "ALIAS" . "MYCOLUMN" AS "MYCOLALIAS"
    FROM "THEUSER" . "MYTABLE" "ALIAS"
    WHERE "ALIAS" . "THISCOL" = 'That Value';
    

    CSS Grid Layout not working in IE11 even with prefixes

    Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.

    The repeat functionality is supported

    You can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr), you have to write (1fr)[4]. That's it. See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/

    Supporting grid-gap

    Grid gaps are supported in all browsers except IE. So you can use the @supports at-rule to set the grid-gaps conditionally for all new browsers:

    Example:

    .grid {
      display: grid;
    }
    .item {
      margin-right: 1rem;
      margin-bottom: 1rem;
    }
    @supports (grid-gap: 1rem) {
      .grid {
        grid-gap: 1rem;
      }
      .item {
        margin-right: 0;
        margin-bottom: 0;
      }
    }
    

    It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.

    Use Autoprefixer

    I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.

    How to switch between frames in Selenium WebDriver using Java

    First you have to locate the frame id and define it in a WebElement

    For ex:- WebElement fr = driver.findElementById("id");

    Then switch to the frame using this code:- driver.switchTo().frame("Frame_ID");

    An example script:-

    WebElement fr = driver.findElementById("theIframe");
    
    driver.switchTo().frame(fr);
    
    Then to move out of frame use:- driver.switchTo().defaultContent();
    

    How to correctly set Http Request Header in Angular 2

    Angular 4 >

    You can either choose to set the headers manually, or make an HTTP interceptor that automatically sets header(s) every time a request is being made.


    Manually

    Setting a header:

    http
      .post('/api/items/add', body, {
        headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
      })
      .subscribe();
    

    Setting headers:

    this.http
    .post('api/items/add', body, {
      headers: new HttpHeaders({
        'Authorization': 'my-auth-token',
        'x-header': 'x-value'
      })
    }).subscribe()
    

    Local variable (immutable instantiate again)

    let headers = new HttpHeaders().set('header-name', 'header-value');
    headers = headers.set('header-name-2', 'header-value-2');
    
    this.http
      .post('api/items/add', body, { headers: headers })
      .subscribe()
    

    The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

    From the Angular docs.


    HTTP interceptor

    A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.

    From the Angular docs.

    Make sure you use @angular/common/http throughout your application. That way your requests will be catched by the interceptor.

    Step 1, create the service:

    import * as lskeys from './../localstorage.items';
    import { Observable } from 'rxjs/Observable';
    import { Injectable } from '@angular/core';
    import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
    
    @Injectable()
    export class HeaderInterceptor implements HttpInterceptor {
    
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            if (true) { // e.g. if token exists, otherwise use incomming request.
                return next.handle(req.clone({
                    setHeaders: {
                        'AuthenticationToken': localStorage.getItem('TOKEN'),
                        'Tenant': localStorage.getItem('TENANT')
                    }
                }));
            }
            else {
                return next.handle(req);
            }
        }
    }
    

    Step 2, add it to your module:

    providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HeaderInterceptor,
          multi: true // Add this line when using multiple interceptors.
        },
        // ...
      ]
    

    Useful links:

    Remove shadow below actionbar

    add app:elevation="0dp" in AppBarLayout for hiding shadow in appbar

    Run a mySQL query as a cron job?

    Try creating a shell script like the one below:

    #!/bin/bash
    
    mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"
    

    You can then add this to the cron

    jQuery $.ajax request of dataType json will not retrieve data from PHP script

    Try this...  
      <script type="text/javascript">
    
        $(document).ready(function(){
    
        $("#find").click(function(){
            var username  = $("#username").val();
                $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'includes/find.php',
                data: 'username='+username,
                success: function( data ) {
                //in data you result will be available...
                response = jQuery.parseJSON(data);
    //further code..
                },
    
        error: function(xhr, status, error) {
            alert(status);
            },
        dataType: 'text'
    
        });
            });
    
        });
    
    
    
        </script>
    
        <form name="Find User" id="userform" class="invoform" method="post" />
    
        <div id ="userdiv">
          <p>Name (Lastname, firstname):</p>
          </label>
          <input type="text" name="username" id="username" class="inputfield" />
          <input type="button" name="find" id="find" class="passwordsubmit" value="find" />
        </div>
        </form>
        <div id="userinfo"><b>info will be listed here.</b></div>
    

    MVC Calling a view from a different controller

    You can move you read.aspx view to Shared folder. It is standard way in such circumstances

    How to pass text in a textbox to JavaScript function?

    You can get textbox value and Id by the following simple example in dotNet programming

    <html>
            <head>
             <script type="text/javascript">
                 function GetTextboxId_Value(textBox) 
                     {
                     alert(textBox.value);    // To get Text Box Value(Text)
                     alert(textBox.id);      // To get Text Box Id like txtSearch
                 }
             </script>     
            </head>
     <body>
     <input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" />  </body>
     </html>
    

    How to configure heroku application DNS to Godaddy Domain?

    I used this videocast to set up my GoDaddy domain with Heroku, and it worked perfectly. Very clear and well explained.

    Note: Skip the part about CNAME yourdomain.com. (note the .) and the heroku addons:add "custom domains"

    http://blog.heroku.com/archives/2009/10/7/heroku_casts_setting_up_custom_domains/


    To summarize the video:

    1) on GoDaddy and create a CNAME with

    Alias Name: www
    Host Name: proxy.heroku.com
    

    2) check that your domain has propagated by typing host www.yourdomain.com on the command line

    3) run heroku domains:add www.yourdomain.com

    4) run heroku domains:add yourdomain.com

    It worked for me after these steps. Hope it works for you too!

    UPDATE: things have changed, check out this post Heroku/GoDaddy: send naked domain to www

    Mocking methods of local scope objects with Mockito

    No way. You'll need some dependency injection, i.e. instead of having the obj1 instantiated it should be provided by some factory.

    MyObjectFactory factory;
    
    public void setMyObjectFactory(MyObjectFactory factory)
    {
      this.factory = factory;
    }
    
    void method1()
    {
      MyObject obj1 = factory.get();
      obj1.method();
    }
    

    Then your test would look like:

    @Test
    public void testMethod1() throws Exception
    {
      MyObjectFactory factory = Mockito.mock(MyObjectFactory.class);
      MyObject obj1 = Mockito.mock(MyObject.class);
      Mockito.when(factory.get()).thenReturn(obj1);
      
      // mock the method()
      Mockito.when(obj1.method()).thenReturn(Boolean.FALSE);
    
      SomeObject someObject = new SomeObject();
      someObject.setMyObjectFactory(factory);
      someObject.method1();
    
      // do some assertions
    }
    

    How can I specify a branch/tag when adding a Git submodule?

    Git submodules are a little bit strange - they're always in "detached head" mode - they don't update to the latest commit on a branch like you might expect.

    This does make some sense when you think about it, though. Let's say I create repository foo with submodule bar. I push my changes and tell you to check out commit a7402be from repository foo.

    Then imagine that someone commits a change to repository bar before you can make your clone.

    When you check out commit a7402be from repository foo, you expect to get the same code I pushed. That's why submodules don't update until you tell them to explicitly and then make a new commit.

    Personally I think submodules are the most confusing part of Git. There are lots of places that can explain submodules better than I can. I recommend Pro Git by Scott Chacon.

    Oracle Convert Seconds to Hours:Minutes:Seconds

    You should check out this site. The TO_TIMESTAMP section could be useful for you!

    Syntax:

    TO_TIMESTAMP ( string , [ format_mask ] [ 'nlsparam' ] )

    Declaring variable workbook / Worksheet vba

    I had the same issue. I used Worksheet instead of Worksheets and it was resolved. Not sure what the difference is between them.

    Object Library Not Registered When Adding Windows Common Controls 6.0

    You can run the tool from Microsoft in this KB http://support.microsoft.com/default.aspx?scid=kb;en-us;Q195353 to fix the licensing issues for earlier ActiveX controls. This worked for me.

    Adding placeholder text to textbox

    This is a extension method for the texbox. Simply Add the Placeholder Text programmatically:

    myTextBox.AddPlaceholderText("Hello World!");
    

    The extension method:

    public static void AddPlaceholderText(this TextBox textBox, string placeholderText)
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                    textBox.Text = placeholderText;
                textBox.SetResourceReference(Control.ForegroundProperty,
                    textBox.Text != placeholderText
                        ? "SystemControlForegroundBaseHighBrush"
                        : "SystemControlForegroundBaseMediumBrush");
                var ignoreSelectionChanged = false;
                textBox.SelectionChanged += (sender, args) =>
                {
                    if (ignoreSelectionChanged) { ignoreSelectionChanged = false; return; }
                    if (textBox.Text != placeholderText) return;
                    ignoreSelectionChanged = true;
                    textBox.Select(0, 0);
                };
                var lastText = textBox.Text;
                var ignoreTextChanged = false;
                textBox.TextChanged += (sender, args) =>
                {
                    if (ignoreTextChanged) { ignoreTextChanged = false; return; }
                    if (string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        ignoreTextChanged = true;
                        textBox.Text = placeholderText;
                        textBox.Select(0, 0);
                    }
                    else if (lastText == placeholderText)
                    {
                        ignoreTextChanged = true;
                        textBox.Text = textBox.Text.Substring(0, 1);
                        textBox.Select(1, 0);
                    }
    
                    textBox.SetResourceReference(Control.ForegroundProperty,
                        textBox.Text != placeholderText
                            ? "SystemControlForegroundBaseHighBrush"
                            : "SystemControlForegroundBaseMediumBrush");
                    lastText = textBox.Text;
                };
            }
    

    Happy coding, BierDav

    Permutations between two lists of unequal length

    Without itertools as a flattened list:

    [(list1[i], list2[j]) for i in range(len(list1)) for j in range(len(list2))]
    

    or in Python 2:

    [(list1[i], list2[j]) for i in xrange(len(list1)) for j in xrange(len(list2))]
    

    "Least Astonishment" and the Mutable Default Argument

    It's a performance optimization. As a result of this functionality, which of these two function calls do you think is faster?

    def print_tuple(some_tuple=(1,2,3)):
        print some_tuple
    
    print_tuple()        #1
    print_tuple((1,2,3)) #2
    

    I'll give you a hint. Here's the disassembly (see http://docs.python.org/library/dis.html):

    #1

    0 LOAD_GLOBAL              0 (print_tuple)
    3 CALL_FUNCTION            0
    6 POP_TOP
    7 LOAD_CONST               0 (None)
    10 RETURN_VALUE
    

    #2

     0 LOAD_GLOBAL              0 (print_tuple)
     3 LOAD_CONST               4 ((1, 2, 3))
     6 CALL_FUNCTION            1
     9 POP_TOP
    10 LOAD_CONST               0 (None)
    13 RETURN_VALUE
    

    I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs ?)

    As you can see, there is a performance benefit when using immutable default arguments. This can make a difference if it's a frequently called function or the default argument takes a long time to construct. Also, bear in mind that Python isn't C. In C you have constants that are pretty much free. In Python you don't have this benefit.

    How to save RecyclerView's scroll position using RecyclerView.State?

    Beginning from version 1.2.0-alpha02 of androidx recyclerView library, it is now automatically managed. Just add it with:

    implementation "androidx.recyclerview:recyclerview:1.2.0-alpha02"
    

    And use:

    adapter.stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY
    

    The StateRestorationPolicy enum has 3 options:

    • ALLOW — the default state, that restores the RecyclerView state immediately, in the next layout pass
    • PREVENT_WHEN_EMPTY — restores the RecyclerView state only when the adapter is not empty (adapter.getItemCount() > 0). If your data is loaded async, the RecyclerView waits until data is loaded and only then the state is restored. If you have default items, like headers or load progress indicators as part of your Adapter, then you should use the PREVENT option, unless the default items are added using MergeAdapter. MergeAdapter waits for all of its adapters to be ready and only then it restores the state.
    • PREVENT — all state restoration is deferred until you set ALLOW or PREVENT_WHEN_EMPTY.

    Note that at the time of this answer, recyclerView library is still in alpha03, but alpha phase is not suitable for production purposes.

    Check if Variable is Empty - Angular 2

    if( myVariable ) 
    { 
        //mayVariable is not : 
        //null 
        //undefined 
        //NaN 
        //empty string ("") 
        //0 
        //false 
    }
    

    Moment.js with ReactJS (ES6)

    I know, question is a bit old, but since am here looks like people are still looking for solutions.

    I'll suggest you to use react-moment link,

    react-moment comes with handy JSXtags which reduce a lot of work. Like in your case :-

    import React  from 'react';
    import Moment from 'react-moment';
    
    exports default class MyComponent extends React.Component {
        render() {
            <Moment format="YYYY/MM/DD">{this.props.dateToFormat}</Moment>
        }
    }
    

    Android Studio - How to increase Allocated Heap Size

    On Ubuntu, it's straight forward, clicking Help > Edit Custom VM Options . The IDE asks whether to create for you a file, click OK.

    An empty studio64.vmoptions file is create and paste the following variables:

    -Xms128m
    -Xmx4096m
    -XX:MaxPermSize=1024m
    -XX:ReservedCodeCacheSize=200m
    -XX:+UseCompressedOops
    

    Restart the IDE, the Max Heap Size is increased to: 4,062M

    Pass Multiple Parameters to jQuery ajax call

    data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}',
    

    Detect if a page has a vertical scrollbar?

    This one did works for me:

    function hasVerticalScroll(node){
        if(node == undefined){
            if(window.innerHeight){
                return document.body.offsetHeight> window.innerHeight;
            }
            else {
                return  document.documentElement.scrollHeight > 
                    document.documentElement.offsetHeight ||
                    document.body.scrollHeight>document.body.offsetHeight;
            }
        }
        else {
            return node.scrollHeight> node.offsetHeight;
        }
    }
    

    For the body, just use hasVerticalScroll().

    Is there a "do ... while" loop in Ruby?

    This works correctly now:

    begin
        # statment
    end until <condition>
    

    But, it may be remove in the future, because the begin statement is counterintuitive. See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745

    Matz (Ruby’s Creator) recommended doing it this way:

    loop do
        # ...
        break if <condition>
    end
    

    MySQL: how to get the difference between two timestamps in seconds

    UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)
    

    If you want an unsigned difference, add an ABS() around the expression.

    Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

    How to get Device Information in Android

    You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).

    For instance :

    System.getProperty("os.version"); // OS version
    android.os.Build.VERSION.SDK      // API Level
    android.os.Build.DEVICE           // Device
    android.os.Build.MODEL            // Model 
    android.os.Build.PRODUCT          // Product
    

    Etc...

    How do I mount a remote Linux folder in Windows through SSH?

    Apparently the free NetDrive software from Novell can access SFTP file servers.

    jQuery: Get the cursor position of text in input without browser specific code?

    Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

    Use it as follows:

    <input type=text id=t1 value=abcd>
    <button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>
    

    I'm giving you the fiddle_demo

    Adding an image to a project in Visual Studio

    • You just need to have an existing file, open the context menu on your folder , and then choose Add => Existing item...

      enter image description here

    • If you have the file already placed within your project structure, but it is not yet included, you can do so by making them visible in the solution explorer

      enter image description here

    and then include them via the file context menu enter image description here

    jQuery UI Accordion Expand/Collapse All

    A lot of these seem to be overcomplicated. I achieved what I wanted with just the following:

    $(".ui-accordion-content").show();
    

    JSFiddle

    sudo echo "something" >> /etc/privilegedFile doesn't work

    Using Yoo's answer, put this in your ~/.bashrc:

    sudoe() {
        [[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1
        echo "$1" | sudo tee --append "$2" > /dev/null
    }
    

    Now you can run sudoe 'deb blah # blah' /etc/apt/sources.list


    Edit:

    A more complete version which allows you to pipe input in or redirect from a file and includes a -a switch to turn off appending (which is on by default):

    sudoe() {
      if ([[ "$1" == "-a" ]] || [[ "$1" == "--no-append" ]]); then
        shift &>/dev/null || local failed=1
      else
        local append="--append"
      fi
    
      while [[ $failed -ne 1 ]]; do
        if [[ -t 0 ]]; then
          text="$1"; shift &>/dev/null || break
        else
          text="$(cat <&0)"
        fi
    
        [[ -z "$1" ]] && break
        echo "$text" | sudo tee $append "$1" >/dev/null; return $?
      done
    
      echo "Usage: $0 [-a|--no-append] [text] <file>"; return 1
    }
    

    Eclipse interface icons very small on high resolution screen in Windows 8.1

    Had same problem, to resolve it, create a shortcut of the launcher, right click > properties > compatibility > tick on 'Override high DPI scaling behaviour' and select System Enhanced from the dropdown as shown on pic below. Relaunch eclipse after changes.

    enter image description here

    How to select a CRAN mirror in R

    If you need to set the mirror in a non-interactive way (for example doing an rbundler install in a deploy script) you can do it in this way:

    First manually run:

    chooseCRANmirror()
    

    Pick the mirror number that is best for you and remember it. Then to automate the selection:

    R -e 'chooseCRANmirror(graphics=FALSE, ind=87);library(rbundler);bundle()'
    

    Where 87 is the number of the mirror you would like to use. This snippet also installs the rbundle for you. You can omit that if you like.

    How to dynamically create generic C# object using reflection?

    Indeed you would not be able to write the last line.

    But you probably don't want to create the object, just for the sake or creating it. You probably want to call some method on your newly created instance.

    You'll then need something like an interface :

    public interface ITask 
    {
        void Process(object o);
    }
    
    public class Task<T> : ITask
    { 
       void ITask.Process(object o) 
       {
          if(o is T) // Just to be sure, and maybe throw an exception
            Process(o as T);
       }
    
       public void Process(T o) { }
    }
    

    and call it with :

    Type d1 = Type.GetType("TaskA"); //or "TaskB"
    Type[] typeArgs = { typeof(Item) };
    Type makeme = d1.MakeGenericType(typeArgs);
    ITask task = Activator.CreateInstance(makeme) as ITask;
    
    // This can be Item, or any type derived from Item
    task.Process(new Item());
    

    In any case, you won't be statically cast to a type you don't know beforehand ("makeme" in this case). ITask allows you to get to your target type.

    If this is not what you want, you'll probably need to be a bit more specific in what you are trying to achieve with this.

    How do I count a JavaScript object's attributes?

    This function makes use of Mozilla's __count__ property if it is available as it is faster than iterating over every property.

    function countProperties(obj) {
      var count = "__count__",
      hasOwnProp = Object.prototype.hasOwnProperty;
    
      if (typeof obj[count] === "number" && !hasOwnProp.call(obj, count)) {
        return obj[count];
      }
      count = 0;
      for (var prop in obj) {
        if (hasOwnProp.call(obj, prop)) {
          count++;
        }
      }
      return count;
    };
    
    countProperties({
      "1": 2,
      "3": 4,
      "5": 6
    }) === 3;
    

    MySQL Incorrect datetime value: '0000-00-00 00:00:00'

    Make the sql mode non strict

    if using laravel go to config->database, the go to mysql settings and make the strict mode false

    What is the perfect counterpart in Python for "while not EOF"

    You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

    line = obj.readlines()
    

    Converting HTML string into DOM elements?

    Okay, I realized the answer myself, after I had to think about other people's answers. :P

    var htmlContent = ... // a response via AJAX containing HTML
    var e = document.createElement('div');
    e.setAttribute('style', 'display: none;');
    e.innerHTML = htmlContent;
    document.body.appendChild(e);
    var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
    document.body.removeChild(e);
    

    How can I generate random number in specific range in Android?

    int min = 65;
    int max = 80;
    
    Random r = new Random();
    int i1 = r.nextInt(max - min + 1) + min;
    

    Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

    Deploy a project using Git push

    I found this script on this site and it seems to work quite well.

    1. Copy over your .git directory to your web server
    2. On your local copy, modify your .git/config file and add your web server as a remote:

      [remote "production"]
          url = username@webserver:/path/to/htdocs/.git
      
    3. On the server, replace .git/hooks/post-update with this file (in the answer below)

    4. Add execute access to the file (again, on the server):

      chmod +x .git/hooks/post-update
      
    5. Now, just locally push to your web server and it should automatically update the working copy:

      git push production
      

    int to unsigned int conversion

    This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

    The actual language in the standard is

    If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

    How to add data into ManyToMany field?

    There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

    As that page states, you need to do:

    my_obj.categories.add(fragmentCategory.objects.get(id=1))
    

    or

    my_obj.categories.create(name='val1')
    

    Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

    See if you can recreate the issue in an Incognito tab. If you find that the problem no longer occurs then I would recommend you go through your extensions, perhaps disabling them one at a time. This is commonly the cause as touched on by Nikola

    Creating an index on a table variable

    The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.

    SQL Server 2014

    In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.

    Example syntax for that is below.

    /*SQL Server 2014+ compatible inline index syntax*/
    DECLARE @T TABLE (
    C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
    C2 INT INDEX IX2 NONCLUSTERED,
           INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
    );
    

    Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"

    /*SQL Server 2016 allows filtered indexes*/
    DECLARE @T TABLE
    (
    c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
    )
    

    SQL Server 2000 - 2012

    Can I create a index on Name?

    Short answer: Yes.

    DECLARE @TEMPTABLE TABLE (
      [ID]   [INT] NOT NULL PRIMARY KEY,
      [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
      UNIQUE NONCLUSTERED ([Name], [ID]) 
      ) 
    

    A more detailed answer is below.

    Traditional tables in SQL Server can either have a clustered index or are structured as heaps.

    Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.

    Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.

    In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE or PRIMARY KEY constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULLs is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.

    Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED or NONCLUSTERED explicitly with the constraint declaration (Example syntax)

    DECLARE @T TABLE
    (
    A INT NULL UNIQUE CLUSTERED,
    B INT NOT NULL PRIMARY KEY NONCLUSTERED
    )
    

    As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.

    +-------------------------------------+-------------------------------------+
    |             Index Type              | Can be created on a table variable? |
    +-------------------------------------+-------------------------------------+
    | Unique Clustered Index              | Yes                                 |
    | Nonunique Clustered Index           |                                     |
    | Unique NCI on a heap                | Yes                                 |
    | Non Unique NCI on a heap            |                                     |
    | Unique NCI on a clustered index     | Yes                                 |
    | Non Unique NCI on a clustered index | Yes                                 |
    +-------------------------------------+-------------------------------------+
    

    The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name is simulated by a unique index on Name,Id (recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).

    A non unique clustered index can also be achieved by manually adding an IDENTITY column to act as a uniqueifier.

    DECLARE @T TABLE
    (
    A INT NULL,
    B INT NULL,
    C INT NULL,
    Uniqueifier INT NOT NULL IDENTITY(1,1),
    UNIQUE CLUSTERED (A,Uniqueifier)
    )
    

    But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.

    How to access a dictionary element in a Django template?

    Could find nothing simpler and better than this solution. Also see the doc.

    @register.filter
    def dictitem(dictionary, key):
        return dictionary.get(key)
    

    But there's a problem (also discussed here) that the returned item is an object and I need to reference a field of this object. Expressions like {{ (schema_dict|dictitem:schema_code).name }} are not supported, so the only solution I found was:

    {% with schema=schema_dict|dictitem:schema_code %}
        <p>Selected schema: {{ schema.name }}</p>
    {% endwith %}
    

    UPDATE:

    @register.filter
    def member(obj, name):
        return getattr(obj, name, None)
    

    So no need for a with tag:

    {{ schema_dict|dictitem:schema_code|member:'name' }}
    

    release Selenium chromedriver.exe from memory

    You should apply close before than quit

    driver.close()
    driver.quit()
    

    How to convert ZonedDateTime to Date?

    I use this.

    public class TimeTools {
    
        public static Date getTaipeiNowDate() {
            Instant now = Instant.now();
            ZoneId zoneId = ZoneId.of("Asia/Taipei");
            ZonedDateTime dateAndTimeInTai = ZonedDateTime.ofInstant(now, zoneId);
            try {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInTai.toString().substring(0, 19).replace("T", " "));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    }
    

    Because Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant()); It's not work!!! If u run your application in your computer, it's not problem. But if you run in any region of AWS or Docker or GCP, it will generate problem. Because computer is not your timezone on Cloud. You should set your correctly timezone in Code. For example, Asia/Taipei. Then it will correct in AWS or Docker or GCP.

    public class App {
        public static void main(String[] args) {
            Instant now = Instant.now();
            ZoneId zoneId = ZoneId.of("Australia/Sydney");
            ZonedDateTime dateAndTimeInLA = ZonedDateTime.ofInstant(now, zoneId);
            try {
                Date ans = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInLA.toString().substring(0, 19).replace("T", " "));
                System.out.println("ans="+ans);
            } catch (ParseException e) {
            }
            Date wrongAns = Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant());
            System.out.println("wrongAns="+wrongAns);
        }
    }
    

    Take a screenshot via a Python script on Linux

    You can use this

    import os
    os.system("import -window root screen_shot.png")
    

    Remove #N/A in vlookup result

    To avoid errors in any excel function, use the Error Handling functions that start with IS* in Excel. Embed your function with these error handing functions and avoid the undesirable text in your results. More info in OfficeTricks Page

    Is there a way to detect if a browser window is not currently active?

    I would use jQuery because then all you have to do is this:

    $(window).blur(function(){
      //your code here
    });
    $(window).focus(function(){
      //your code
    });
    

    Or at least it worked for me.

    Automatically size JPanel inside JFrame

    From my experience, I used GridLayout.

        thePanel.setLayout(new GridLayout(a,b,c,d));
    

    a = row number, b = column number, c = horizontal gap, d = vertical gap.


    For example, if I want to create panel with:

    • unlimited row (set a = 0)
    • 1 column (set b = 1)
    • vertical gap= 3 (set d = 3)

    The code is below:

        thePanel.setLayout(new GridLayout(0,1,0,3));
    

    This method is useful when you want to add JScrollPane to your JPanel. Size of the JPanel inside JScrollPane will automatically changes when you add some components on it, so the JScrollPane will automatically reset the scroll bar.

    Moment Js UTC to Local Time

    To convert UTC to local time

    let UTC = moment.utc()
    let local = moment(UTC).local()
    

    Or you want directly get the local time

    let local = moment()
    

    _x000D_
    _x000D_
    var UTC = moment.utc()_x000D_
    console.log(UTC.format()); // UTC time_x000D_
    _x000D_
    var cLocal = UTC.local()_x000D_
    console.log(cLocal.format()); // Convert UTC time_x000D_
    _x000D_
    var local = moment();_x000D_
    console.log(local.format()); // Local time
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    HTML input time in 24 format

    _x000D_
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
        <body>_x000D_
            Time: <input type="time" id="myTime" value="16:32:55">_x000D_
    _x000D_
     <p>Click the button to get the time of the time field.</p>_x000D_
    _x000D_
     <button onclick="myFunction()">Try it</button>_x000D_
    _x000D_
     <p id="demo"></p>_x000D_
    _x000D_
     <script>_x000D_
         function myFunction() {_x000D_
             var x = document.getElementById("myTime").value;_x000D_
             document.getElementById("demo").innerHTML = x;_x000D_
         }_x000D_
     </script>_x000D_
        </body>_x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    I found that by setting value field (not just what is given below) time input will be internally converted into the 24hr format.

    matplotlib has no attribute 'pyplot'

    pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

    >>> import matplotlib
    >>> print matplotlib.pyplot
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'module' object has no attribute 'pyplot'
    >>> import matplotlib.pyplot
    >>> 
    

    It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

    p = plt.plot(...)
    

    jquery function setInterval

    You can use it like this:

    $(document).ready(function(){
    
        setTimeout("swapImages()",1000);
    
        function swapImages(){
    
            var active = $('.active'); 
            var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');
    
            active.removeClass('active');
            next.addClass('active');
            setTimeout("swapImages()",1000);
    }
    

    });

    Read file from line 2 or skip header row

    To generalize the task of reading multiple header lines and to improve readability I'd use method extraction. Suppose you wanted to tokenize the first three lines of coordinates.txt to use as header information.

    Example

    coordinates.txt
    ---------------
    Name,Longitude,Latitude,Elevation, Comments
    String, Decimal Deg., Decimal Deg., Meters, String
    Euler's Town,7.58857,47.559537,0, "Blah"
    Faneuil Hall,-71.054773,42.360217,0
    Yellowstone National Park,-110.588455,44.427963,0
    

    Then method extraction allows you to specify what you want to do with the header information (in this example we simply tokenize the header lines based on the comma and return it as a list but there's room to do much more).

    def __readheader(filehandle, numberheaderlines=1):
        """Reads the specified number of lines and returns the comma-delimited 
        strings on each line as a list"""
        for _ in range(numberheaderlines):
            yield map(str.strip, filehandle.readline().strip().split(','))
    
    with open('coordinates.txt', 'r') as rh:
        # Single header line
        #print next(__readheader(rh))
    
        # Multiple header lines
        for headerline in __readheader(rh, numberheaderlines=2):
            print headerline  # Or do other stuff with headerline tokens
    

    Output

    ['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
    ['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']
    

    If coordinates.txt contains another headerline, simply change numberheaderlines. Best of all, it's clear what __readheader(rh, numberheaderlines=2) is doing and we avoid the ambiguity of having to figure out or comment on why author of the the accepted answer uses next() in his code.

    How to copy a dictionary and only edit the copy

    Python never implicitly copies objects. When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.

    If you want to copy the dict (which is rare), you have to do so explicitly with

    dict2 = dict(dict1)
    

    or

    dict2 = dict1.copy()
    

    What are .dex files in Android?

    .dex file
    

    Compiled Android application code file.

    Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

    MultipartException: Current request is not a multipart request

    That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.

    I ended up solving it by going to the Body tab, change the param type from File to Text, then back to File and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?

    Android check permission for LocationManager

    Use my custome class to check or request permisson

    public class Permissons {
    
            //Request Permisson
            public static void Request_STORAGE(Activity act,int code)
            {
    
                ActivityCompat.requestPermissions(act, new
                        String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},code);
            }
            public static void Request_CAMERA(Activity act,int code)
            {
                ActivityCompat.requestPermissions(act, new
                        String[]{Manifest.permission.CAMERA},code);
            }
            public static void Request_FINE_LOCATION(Activity act,int code)
            {
                ActivityCompat.requestPermissions(act, new
                        String[]{Manifest.permission.ACCESS_FINE_LOCATION},code);
            }
            public static void Request_READ_SMS(Activity act,int code)
            {
                ActivityCompat.requestPermissions(act, new
                        String[]{Manifest.permission.READ_SMS},code);
            }
            public static void Request_READ_CONTACTS(Activity act,int code)
            {
                ActivityCompat.requestPermissions(act, new
                        String[]{Manifest.permission.READ_CONTACTS},code);
            }
            public static void Request_READ_CALENDAR(Activity act,int code)
            {
                ActivityCompat.requestPermissions(act, new
                        String[]{Manifest.permission.READ_CALENDAR},code);
            }
            public static void Request_RECORD_AUDIO(Activity act,int code)
            {
                ActivityCompat.requestPermissions(act, new
                        String[]{Manifest.permission.RECORD_AUDIO},code);
            }
    
            //Check Permisson
            public static boolean Check_STORAGE(Activity act)
            {
                int result = ContextCompat.checkSelfPermission(act,android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                return result == PackageManager.PERMISSION_GRANTED;
            }
            public static boolean Check_CAMERA(Activity act)
            {
                int result = ContextCompat.checkSelfPermission(act, Manifest.permission.CAMERA);
                return result == PackageManager.PERMISSION_GRANTED;
            }
            public static boolean Check_FINE_LOCATION(Activity act)
            {
                int result = ContextCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION);
                return result == PackageManager.PERMISSION_GRANTED;
            }
            public static boolean Check_READ_SMS(Activity act)
            {
                int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_SMS);
                return result == PackageManager.PERMISSION_GRANTED;
            }
            public static boolean Check_READ_CONTACTS(Activity act)
            {
                int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CONTACTS);
                return result == PackageManager.PERMISSION_GRANTED;
            }
            public static boolean Check_READ_CALENDAR(Activity act)
            {
                int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CALENDAR);
                return result == PackageManager.PERMISSION_GRANTED;
            }
            public static boolean Check_RECORD_AUDIO(Activity act)
            {
                int result = ContextCompat.checkSelfPermission(act, Manifest.permission.RECORD_AUDIO);
                return result == PackageManager.PERMISSION_GRANTED;
            }
        }
    

    Example

    if(!Permissons.Check_STORAGE(MainActivity.this))
    {
       //if not permisson granted so request permisson with request code
       Permissons.Request_STORAGE(MainActivity.this,22);
    }
    

    Using CSS for a fade-in effect on page load

    You can use the onload="" HTML attribute and use JavaScript to adjust the opacity style of your element.

    Leave your CSS as you proposed. Edit your HTML code to:

    <body onload="document.getElementById(test).style.opacity='1'">
        <div id="test">
            <p>?This is a test</p>
        </div>
    </body>
    

    This also works to fade-in the complete page when finished loading:

    HTML:

    <body onload="document.body.style.opacity='1'">
    </body>
    

    CSS:

    body{ 
        opacity: 0;
        transition: opacity 2s;
        -webkit-transition: opacity 2s; /* Safari */
    }
    

    Check the W3Schools website: transitions and an article for changing styles with JavaScript.

    unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

    To bring more confusion in this already rich thread, I happened to bump in the same unresolved external on fprintf

    main.obj : error LNK2019: unresolved external symbol __imp__fprintf referenced in function _GenerateInfoFile
    

    Even if in my case it was in a rather different context : under Visual Studio 2005 (Visual Studio 8.0) and the error was happening in my own code (the very same I was compiling), not a third party.

    It happened that this error was triggered by /MD option in my compiler flags. Switching to /MT removed the issue. This is weird because usually, linking statically (MT) raises more problem than dynamically (MD)... but just in case it serves other, I put it there.

    Angular.js: How does $eval work and why is it different from vanilla eval?

    From the test,

    it('should allow passing locals to the expression', inject(function($rootScope) {
      expect($rootScope.$eval('a+1', {a: 2})).toBe(3);
    
      $rootScope.$eval(function(scope, locals) {
        scope.c = locals.b + 4;
      }, {b: 3});
      expect($rootScope.c).toBe(7);
    }));
    

    We also can pass locals for evaluation expression.

    How to call a .NET Webservice from Android using KSOAP2?

    Typecast the envelope to SoapPrimitive:

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
    String strRes = result.toString();
    

    and it will work.

    Access non-numeric Object properties by index?

    "I'm specifically looking to target the index, just like the first example - if it's possible."

    No, it isn't possible.

    The closest you can get is to get an Array of the object's keys, and use that:

    var keys = Object.keys( obj );
    

    ...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:

    keys[ 0 ];  // 'evenmore'
    keys[ 1 ];  // 'something'
    

    How to handle static content in Spring MVC?

    My way of solving this problem is placing all your actions with a specific prefix like "web" or "service" and configure that all url's with that prefix will be intercepted by the DispatcherServlet.

    Is there a way to crack the password on an Excel VBA Project?

    Yes there is, as long as you are using a .xls format spreadsheet (the default for Excel up to 2003). For Excel 2007 onwards, the default is .xlsx, which is a fairly secure format, and this method will not work.

    As Treb says, it's a simple comparison. One method is to simply swap out the password entry in the file using a hex editor (see Hex editors for Windows). Step by step example:

    1. Create a new simple excel file.
    2. In the VBA part, set a simple password (say - 1234).
    3. Save the file and exit. Then check the file size - see Stewbob's gotcha
    4. Open the file you just created with a hex editor.
    5. Copy the lines starting with the following keys:

      CMG=....
      DPB=...
      GC=...
      
    6. FIRST BACKUP the excel file you don't know the VBA password for, then open it with your hex editor, and paste the above copied lines from the dummy file.

    7. Save the excel file and exit.
    8. Now, open the excel file you need to see the VBA code in. The password for the VBA code will simply be 1234 (as in the example I'm showing here).

    If you need to work with Excel 2007 or 2010, there are some other answers below which might help, particularly these: 1, 2, 3.

    EDIT Feb 2015: for another method that looks very promising, look at this new answer by Ð?c Thanh Nguy?n.

    don't fail jenkins build if execute shell fails

    To stop further execution when command fails:

    command || exit 0

    To continue execution when command fails:

    command || true

    Detect when an HTML5 video finishes

    Here is a full example, I hope it helps =).

    <!DOCTYPE html> 
    <html> 
    <body> 
    
    <video id="myVideo" controls="controls">
      <source src="your_video_file.mp4" type="video/mp4">
      <source src="your_video_file.mp4" type="video/ogg">
      Your browser does not support HTML5 video.
    </video>
    
    <script type='text/javascript'>
        document.getElementById('myVideo').addEventListener('ended',myHandler,false);
        function myHandler(e) {
            if(!e) { e = window.event; }
            alert("Video Finished");
        }
    </script>
    </body> 
    </html>
    

    Swift how to sort array of custom objects by property value

    Nearly everyone gives how directly, let me show the evolvement:

    you can use the instance methods of Array:

    // general form of closure
    images.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
    
    // types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
    images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })
    
    // Single-expression closures can implicitly return the result of their single expression by omitting the "return" keyword
    images.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })
    
    // closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second, third arguments and so on
    images.sortInPlace({ $0.fileID > $1.fileID })
    
    // the simplification of the closure is the same
    images = images.sort({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
    images = images.sort({ image1, image2 in return image1.fileID > image2.fileID })
    images = images.sort({ image1, image2 in image1.fileID > image2.fileID })
    images = images.sort({ $0.fileID > $1.fileID })
    

    For elaborate explanation about the working principle of sort, see The Sorted Function.

    How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

    It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

    The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

       Adobe Reader Preferences dialog

    You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

       Adobe Reader Read Mode toolbar button

    Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

    #toolbar=0&navpanes=0

    So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

    string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
    this._WebBrowser.Navigate(url);
    

    You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

    Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

    To load data via a GET request you don't need any URLRequest (and no semicolons)

    let listUrlString =  "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
    let myUrl = URL(string: listUrlString)!
    let task = URLSession.shared.dataTask(with: myUrl) { ...
    

    Where can I find MySQL logs in phpMyAdmin?

    In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

    Passing an Object from an Activity to a Fragment

    Create a static method in the Fragment and then get it using getArguments().

    Example:

    public class CommentsFragment extends Fragment {
      private static final String DESCRIBABLE_KEY = "describable_key";
      private Describable mDescribable;
    
      public static CommentsFragment newInstance(Describable describable) {
        CommentsFragment fragment = new CommentsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DESCRIBABLE_KEY, describable);
        fragment.setArguments(bundle);
    
        return fragment;
      }
    
      @Override
      public View onCreateView(LayoutInflater inflater,
          ViewGroup container, Bundle savedInstanceState) {
    
        mDescribable = (Describable) getArguments().getSerializable(
            DESCRIBABLE_KEY);
    
        // The rest of your code
    }
    

    You can afterwards call it from the Activity doing something like:

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    Fragment fragment = CommentsFragment.newInstance(mDescribable);
    ft.replace(R.id.comments_fragment, fragment);
    ft.commit();
    

    How to find out which package version is loaded in R?

    Simply use help(package="my_package") and look at the version shown.

    This assumes there are no other package versions in the same .libPaths.

    Switch statement: must default be the last case?

    The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.

    Good Example :-

    switch(5) {
      case 1:
        echo "1";
        break;
      case 2:
      default:
        echo "2, default";
        break;
      case 3;
        echo "3";
        break;
    }
    
    
    Outputs '2,default'
    

    very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default

    missing FROM-clause entry for table

    SELECT 
       AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, 
       BillLimit, Mode, PNotes, gtab82.memno 
    FROM
       VCustomer AS v1
    INNER JOIN   
       gtab82 ON gtab82.memacid = v1.AcId 
    WHERE (AcGrCode = '204' OR CreDebt = 'True') 
    AND Masked = 'false'
    ORDER BY AcName
    

    You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer but only use it in the ON clause for uncertain reasons. You may want to review that aspect of your code.

    How to delete all files from a specific folder?

    Try this:

    foreach (string file in Directory.GetFiles(@"c:\directory\"))
      File.Delete(file);
    

    Check if value exists in the array (AngularJS)

    You can use indexOf(). Like:

    var Color = ["blue", "black", "brown", "gold"];
    var a = Color.indexOf("brown");
    alert(a);
    

    The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.


    If you want to search from end to start, use the lastIndexOf() method:

        var Color = ["blue", "black", "brown", "gold"];
        var a = Color.lastIndexOf("brown");
        alert(a);
    

    The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.

    Returns -1 if the item is not found.

    Angularjs: Get element in controller

    Create custom directive

    masterApp.directive('ngRenderCallback', function() {
        return {
            restrict: "A",
            link: function ($scope, element, attrs) {
                setTimeout(function(){ 
                    $scope[attrs.ngEl] = element[0];
                    $scope.$eval(attrs.ngRenderCallback);               
                }, 30);
            }
        }
    });
    

    code for html template

    <div ng-render-callback="fnRenderCarousel('carouselA')" ng-el="carouselA"></div>
    

    function in controller

    $scope.fnRenderCarousel = function(elName){
        $($scope[elName]).carousel();
    }
    

    Android design support library for API 28 (P) not working

    Google has introduced new AndroidX dependencies. You need to migrate to AndroidX, it's simple.

    I replaced all dependencies to AndroidX dependencies

    Old design dependency

    implementation 'com.android.support:design:28.0.0'
    

    New AndroidX design dependency

    implementation 'com.google.android.material:material:1.0.0-rc01'
    

    you can find AndroidX dependencies here https://developer.android.com/jetpack/androidx/migrate


    Automatic AndroidX migration option (supported on android studio 3.3+)

    Migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.

    Complex nesting of partials and templates

    You may use ng-include to avoid using nested ng-views.

    http://docs.angularjs.org/api/ng/directive/ngInclude
    http://plnkr.co/edit/ngdoc:example-example39@snapshot?p=preview

    My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include. The demo shows a dropdown. I replaced mine with a link ng-click. In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];

    $scope.clickToSomePage= function(){
      $scope.template = $scope.templates[0];
    };
    

    Truncating Text in PHP?

    The obvious thing to do is read the documentation.

    But to help: substr($str, $start, $end);

    $str is your text

    $start is the character index to begin at. In your case, it is likely 0 which means the very beginning.

    $end is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:

    <?php
    
    $text = "long text that should be truncated";
    echo substr($text, 0, 15);
    
    ?>
    

    and you would get this:

    long text that 
    

    makes sense?

    EDIT

    The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:

    function truncate($text, $chars = 25) {
        if (strlen($text) <= $chars) {
            return $text;
        }
        $text = $text." ";
        $text = substr($text,0,$chars);
        $text = substr($text,0,strrpos($text,' '));
        $text = $text."...";
        return $text;
    }
    

    So in your case you would paste this function into the functions.php file and call it like this in your page:

    $post = the_post();
    echo truncate($post, 100);
    

    This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.

    How to determine the screen width in terms of dp or dip at runtime in Android?

    You are missing default density value of 160.

        2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
        1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
        3 px = 2 dip if dpi == 240(hdpi), 840x480 screen
    

    In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)

    Disable keyboard on EditText

    Just put this line inside the activity tag in manifest android:windowSoftInputMode="stateHidden"

    Is it possible to forward-declare a function in Python?

    There is no such thing in python like forward declaration. You just have to make sure that your function is declared before it is needed. Note that the body of a function isn't interpreted until the function is executed.

    Consider the following example:

    def a():
       b() # won't be resolved until a is invoked.
    
    def b(): 
       print "hello"
    
    a() # here b is already defined so this line won't fail.
    

    You can think that a body of a function is just another script that will be interpreted once you call the function.

    sscanf in Python

    Update: The Python documentation for its regex module, re, includes a section on simulating scanf, which I found more useful than any of the answers above.

    https://docs.python.org/2/library/re.html#simulating-scanf

    hash keys / values as array

    var a = {"apples": 3, "oranges": 4, "bananas": 42};    
    
    var array_keys = new Array();
    var array_values = new Array();
    
    for (var key in a) {
        array_keys.push(key);
        array_values.push(a[key]);
    }
    
    alert(array_keys);
    alert(array_values);
    

    Retrieve WordPress root directory path?

    I like @Omry Yadan's solution but I think it can be improved upon to use a loop in case you want to continue traversing up the directory tree until you find where wp-config.php actually lives. Of course, if you don't find it and end up in the server's root then all is lost and we return a sane value (false).

    function wp_get_web_root() {
    
      $base = dirname(__FILE__);
      $path = false;
    
      while(!$path && '/' != $base) {
        if(@file_exists(dirname($base)).'/wp-config.php') {
          $path = dirname($base);
        } else {
          $base = dirname($base);
        }
      }
    
      return $path;
    }
    

    Large Numbers in Java

    Here is an example which gets big numbers very quickly.

    import java.math.BigInteger;
    
    /*
    250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
    Time to compute: 3.5 seconds.
    1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
    Time to compute: 58.1 seconds.
    */
    public class Main {
        public static void main(String... args) {
            int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
            long start = System.nanoTime();
            BigInteger fibNumber = fib(place);
            long time = System.nanoTime() - start;
    
            System.out.println(place + "th fib # is: " + fibNumber);
            System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
        }
    
        private static BigInteger fib(int place) {
            BigInteger a = new BigInteger("0");
            BigInteger b = new BigInteger("1");
            while (place-- > 1) {
                BigInteger t = b;
                b = a.add(b);
                a = t;
            }
            return b;
        }
    }
    

    How do I reference a cell range from one worksheet to another using excel formulas?

    The formula that you have is fine. But, after entering it, you need to hit Control + Shift + Enter in order to apply it to the range of values. Specifically:

    1. Select the range of values in the destination sheet.

    2. Enter into the formula panel your desired formula, e.g. =Sheet2!A1:F1

    3. Hit Control + Shift + Enter to apply the formula to the range.

    How to hash a password

    I use a hash and a salt for my password encryption (it's the same hash that Asp.Net Membership uses):

    private string PasswordSalt
    {
       get
       {
          var rng = new RNGCryptoServiceProvider();
          var buff = new byte[32];
          rng.GetBytes(buff);
          return Convert.ToBase64String(buff);
       }
    }
    
    private string EncodePassword(string password, string salt)
    {
       byte[] bytes = Encoding.Unicode.GetBytes(password);
       byte[] src = Encoding.Unicode.GetBytes(salt);
       byte[] dst = new byte[src.Length + bytes.Length];
       Buffer.BlockCopy(src, 0, dst, 0, src.Length);
       Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
       HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
       byte[] inarray = algorithm.ComputeHash(dst);
       return Convert.ToBase64String(inarray);
    }
    

    How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

    The network results at Browserscope will give you both Connections per Hostname and Max Connections for popular browsers. The data is gathered by running tests on users "in the wild," so it will stay up to date.

    how to get yesterday's date in C#

    Something like this should work

    var yesterday = DateTime.Now.Date.AddDays(-1);
    

    DateTime.Now gives you the current date and time.

    If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.

    Finally .AddDays(-1) removes 1 day to give you yesterday.

    CSS no text wrap

    Additionally to overflow:hidden, use

    white-space:nowrap;
    

    Difference between $(window).load() and $(document).ready() functions

    According to DOM Level 2 Events, the load event is supposed to fire on document, not on window. However, load is implemented on window in all browsers for backwards compatibility.

    Best way to reverse a string

    public string rev(string str)
    {
        if (str.Length <= 0)
            return string.Empty;
        else
            return str[str.Length-1]+ rev(str.Substring(0,str.Length-1));
    }
    

    How to block users from closing a window in Javascript?

    Well you can use the window.onclose event and return false in the event handler.

    function closedWin() {
        confirm("close ?");
        return false; /* which will not allow to close the window */
    }
    if(window.addEventListener) {
         window.addEventListener("close", closedWin, false);
    }
    
    window.onclose = closedWin;
    

    Code was taken from this site.

    In the other hand, if they force the closing (by using task manager or something in those lines) you cannot do anything about it.

    How do I get into a non-password protected Java keystore or change the password?

    which means that cacerts keystore isn't password protected

    That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:

    In order to verify its integrity, you must provide your keystore password.

    Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.

    How do I bind to list of checkbox values with AngularJS?

    Using a string of $index can help to use a hashmap of selected values:

    <ul>
        <li ng-repeat="someItem in someArray">
            <input type="checkbox" ng-model="someObject[$index.toString()]" />
        </li>
    </ul>
    

    This way the ng-model object gets updated with the key representing the index.

    $scope.someObject = {};
    

    After a while $scope.someObject should look something like:

    $scope.someObject = {
         0: true,
         4: false,
         1: true
    };
    

    This method won't work for all situations, but it is easy to implement.

    Write to .txt file?

    FILE *f = fopen("file.txt", "w");
    if (f == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }
    
    /* print some text */
    const char *text = "Write this to the file";
    fprintf(f, "Some text: %s\n", text);
    
    /* print integers and floats */
    int i = 1;
    float py = 3.1415927;
    fprintf(f, "Integer: %d, float: %f\n", i, py);
    
    /* printing single chatacters */
    char c = 'A';
    fprintf(f, "A character: %c\n", c);
    
    fclose(f);
    

    Resolving a Git conflict with binary files

    If the binary is something more than a dll or something that can be edited directly like an image, or a blend file (and you don't need to trash/select one file or the other) a real merge would be some like:

    I suggest searching for a diff tool oriented to what are your binary file, for example, there are some free ones for image files for example

    and compare them.

    If there is no diff tool out there for comparing your files, then if you have the original generator of the bin file (that is, there exist an editor for it... like blender 3d, you can then manually inspect those files, also see the logs, and ask the other person what you should include) and do output of the files with https://git-scm.com/book/es/v2/Git-Tools-Advanced-Merging#_manual_remerge

    $ git show :1:hello.blend > hello.common.blend
    $ git show :2:hello.blend > hello.ours.blend
    $ git show :3:hello.blend > hello.theirs.blend
    

    How do you use the "WITH" clause in MySQL?

    MySQL prior to version 8.0 doesn't support the WITH clause (CTE in SQL Server parlance; Subquery Factoring in Oracle), so you are left with using:

    • TEMPORARY tables
    • DERIVED tables
    • inline views (effectively what the WITH clause represents - they are interchangeable)

    The request for the feature dates back to 2006.

    As mentioned, you provided a poor example - there's no need to perform a subselect if you aren't altering the output of the columns in any way:

      SELECT * 
        FROM ARTICLE t
        JOIN USERINFO ui ON ui.user_userid = t.article_ownerid
        JOIN CATEGORY c ON c.catid =  t.article_categoryid
       WHERE t.published_ind = 0
    ORDER BY t.article_date DESC 
       LIMIT 1, 3
    

    Here's a better example:

    SELECT t.name,
           t.num
      FROM TABLE t
      JOIN (SELECT c.id
                   COUNT(*) 'num'
              FROM TABLE c
             WHERE c.column = 'a'
          GROUP BY c.id) ta ON ta.id = t.id
    

    C#: what is the easiest way to subtract time?

    Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)

    Translating touch events from Javascript to jQuery

    jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

    How to decode a Base64 string?

    Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.

    Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.

    While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.

    I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.

    Base64decode("the answer to life the universe and everything") = 00101010

    How to add scroll bar to the Relative Layout?

    You want to enclose it with a scrollView.

    (HTML) Download a PDF file instead of opening them in browser when clicked

    When you want to direct download any image or pdf file from browser instead on opening it in new tab then in javascript you should set value to download attribute of create dynamic link

        var path= "your file path will be here"; 
        var save = document.createElement('a');  
        save.href = filePath; 
        save.download = "Your file name here"; 
        save.target = '_blank'; 
        var event = document.createEvent('Event');
        event.initEvent('click', true, true); 
        save.dispatchEvent(event);
       (window.URL || window.webkitURL).revokeObjectURL(save.href);
    

    For new Chrome update some time event is not working. for that following code will be use

      var path= "your file path will be here"; 
        var save = document.createElement('a');  
        save.href = filePath; 
        save.download = "Your file name here"; 
        save.target = '_blank'; 
        document.body.appendChild(save);
        save.click();
        document.body.removeChild(save);
    

    Appending child and removing child is useful for Firefox, Internet explorer browser only. On chrome it will work without appending and removing child

    Fatal error: Call to undefined function curl_init()

    For Ubuntu

    Install Curl extension for PHP & restart apache server.

    sudo apt-get install php5-curl
    sudo service apache2 restart
    

    For Windows

    Problem arises because of not including the lib_curl.dll to PHP. also load following extension if not working,so those extension in php.ini or remove comment if already exist in php.ini file then remove comment.

    extension=php_bz2.dll
    extension=php_curl.dll
    extension=php_dba.dll
    

    Now restart apache server. If you get an error "Unable to Load php_curl.dll", copy SSLEAY32.PHP, libEAY32.dll (OpenSSL) Libraries to the System32 folder.