Programs & Examples On #Antivirus

Antivirus or anti-virus software is software used to prevent, detect and remove malware.

Multiple Errors Installing Visual Studio 2015 Community Edition

I spent a whole week trying to solve this issue. What finally did it for me was disabling my anti-virus programs. Before I stumbled upon my solution, I went through a lot of other solutions. I thought, I'd post some of the solutions that might prove to be useful for those who are still having trouble with installing Visual Studios 2015 Community Edition.

Solution 1: Minimal Installation

Try installing with minimal extra features. Run the Visual Studios 2015 installation, then click "Custom" and on the following screen, uncheck everything and proceed with the installation.

Solution 2: Delete installation cache

Perhaps the installation failed due to corrupt files in the cache. When installation fails, remove all Visual Studio cache related items and do a full re-installation. To do this, run command prompt (Run as Administrator) and type: "cd /programdata/package cache/" then press enter. Then type "del /f /s *.msi /f /s *.cab" then press enter. Now run the Visual Studios 2015 installation again.

Solution 3: Delete temporary file data stored on your computer

Open up File Explorer and go to "C:\Users\[Your User Account Name]\AppData\Local\Microsoft". Then delete the following folders: VSCommon, VisualStudio, Blend, VsGraphics, ApplicationInsights, vshub, Team Foundation, Web Platform Installer and MsBuild. After this, run the Visual Studios 2015 Installer again.

Solution 4: Enable all four evaluations of Symbolic links

First, check to see if all four evaluations are enabled. Open up command prompt (Run as Administrator) and type "fsutil behavior query SymlinkEvaluation". All 4 evaluations should be enabled. If they aren't then type "fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1". Once those 4 evaluations are set, clear up temporary files and clear installation cache (see Solution 2 and Solution 3) then run the Visual Studios 2015 installation again.

Solution 5: Repair the Redistributables

Perhaps, the problem is that your VC-redistributables are faulty and are in need of repair. To do so, run "Add/Remove programs" and look for all the x86 and x64 versions of Microsoft Visual C++ [Year] Redistributable (Version). Then press Change for each of them and when the uninstallation screen pops up, press Repair. I did it for all the versions I had previously installed: 2012, 2013 and 2015. Therefore, I repaired 6 of them: 2012: x86 and x64, 2013: x86 and x64, 2015: x86 and x64.

Solution 6: Check to see if x86 and x64 sizes are the same

As mentioned by others in this discussion, do a search for vcruntime140.dll and see if the x86 and x64 versions. They should NOT have the same size. If they do, see solution 5 or you can manually delete them (** Be cautious when deleting files from the Windows folder!) and re-install them (from here: https://www.microsoft.com/en-ca/download/details.aspx?id=48145).
Also do the same check for msvcp140.dll. I personally did a search for these files in "C:\Windows\SysWOW64 and C:\Windows\System32" and compared the files from the two folders. Moreover I also checked for differences of vcruntime140.dll and msvcp140.dll in "C:\Program Files\Microsoft Visual Studio 14.0" and "C:\Program Files (x86)\Microsoft Visual Studio 14.0"

Solution 7: Temporarily disable all Anti-Virus Protection and Firewalls

For me, it turned out that the problem stemmed from having ByteFence Anti-Malware and Norton Security with Backup protection. I disabled real-time protection from ByteFence Anti-Malware and I disabled Auto-Protect and Smart Firewall from Norton Security with Backup. Before I ran the installation again, I repeated Solution 2 and Solution 3 (scroll up). And Voila, installation was successful. But how did I find out that the Anti-Virus Program was the culprit? Read Solution 8.

Solution 8: Carefully monitor Visual Studios Installation Process for Intrusions

I resorted to this solution in order to find out the problem. After reading Ezh's article, I decided to download Process Monitor v3.2 and Process Explorer v16.1. I was carefully monitoring 3 programs side-by-side: Process Monitor, Process Explorer and the Visual Studios 2015 Installer, and I watched very closely all the processes that the installer was invoking. Then I noticed that when VSIXInstaller.exe process came on and attempted to install something from a remote server, it kept failing over and over again because my Anti-Virus Program would suddenly appear on screen (as a process) and decide to hog/block some important DLL files that VSIX installation needed. Temporarily disabling the anti-virus program solved my issue!

Solution 9: Complete Windows format and re-installation

If all else fails, and you are really desperate to get Visual Studios 2015 working, I suggest a complete Windows re-installation. At this point, the problem is most likely some type of interference/intrusion with a program which you do not know of.

SQL Developer with JDK (64 bit) cannot find JVM

Depending on the issue, whether it's JAVA home path not correctly set or missing msvcr100.dll file, follow the below methods to rectify the problem:

1. Issue with JAVA home path not correctly set:

Follow these steps:

  • Go to directory where SQL Developer is installed.
  • Open the /bin directory.
  • Open sqldeveloper.conf in any editor to edit.
  • Remove the complete line starting with "SetJavaHome"
  • Save and close the file
  • Start SQL Developer again.
  • Provide the full path for java.exe on prompt.

2. Issue with missing msvcr100.dll file:

OP stated the following in his comments below:

If I first install the jdk and then sql developer without Java, it tells me Unable to launch the Java Virtual Machine Located at path: C:/Program Files/Java/jdk1.8.0_45/bin/msvcr100.dll

So, the error message is clear:

Unable to launch the Java Virtual Machine Located at path: 
C:/Program Files/Java/jdk1.8.0_45/bin/msvcr100.dll

Follow these steps:

copy:

MSVCR100.dll

from:

sqldeveloper\jdk\jre\bin

to:

sqldeveloper\sqldeveloper\bin

And relaunch SQL Developer again.

What is msvcr100.dll file?:

msvcr100.dll is a part of Microsoft Visual C++ and is required to run programs developed with Visual C++. Some applications like SQL Developer in the question, needs the file in the SQL Developer installation folder.

What options are available to fix the issue?:

Copying it from Windows systemfolder to the installation folder of application should fix the problem. Also, you could add the PATH to the msvcr100.dll file based on 32/64 bit requirements. If the local file itself is deleted or corrupt by any chance, then it could be downloaded online or could also be reinstalled via Microsoft visual C++ 2010 Redistributable package. It is important to use the correct version based on the software. Use the 32bit dll file for 32bit software, and 64bit dll file for 64bit software.

wget/curl large file from google drive

Here's a little bash script I wrote that does the job today. It works on large files and can resume partially fetched files too. It takes two arguments, the first is the file_id and the second is the name of the output file. The main improvements over previous answers here are that it works on large files and only needs commonly available tools: bash, curl, tr, grep, du, cut and mv.

#!/usr/bin/env bash
fileid="$1"
destination="$2"

# try to download the file
curl -c /tmp/cookie -L -o /tmp/probe.bin "https://drive.google.com/uc?export=download&id=${fileid}"
probeSize=`du -b /tmp/probe.bin | cut -f1`

# did we get a virus message?
# this will be the first line we get when trying to retrive a large file
bigFileSig='<!DOCTYPE html><html><head><title>Google Drive - Virus scan warning</title><meta http-equiv="content-type" content="text/html; charset=utf-8"/>'
sigSize=${#bigFileSig}

if (( probeSize <= sigSize )); then
  virusMessage=false
else
  firstBytes=$(head -c $sigSize /tmp/probe.bin)
  if [ "$firstBytes" = "$bigFileSig" ]; then
    virusMessage=true
  else
    virusMessage=false
  fi
fi

if [ "$virusMessage" = true ] ; then
  confirm=$(tr ';' '\n' </tmp/probe.bin | grep confirm)
  confirm=${confirm:8:4}
  curl -C - -b /tmp/cookie -L -o "$destination" "https://drive.google.com/uc?export=download&id=${fileid}&confirm=${confirm}"
else
  mv /tmp/probe.bin "$destination"
fi

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.

If you're using GoDaddy Plesk Hosting, use the following SMTP details.

Host = relay-hosting.secureserver.net
Port = 25 

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Go to root folder

Right Click, click on Properties

Choose Tab Security

Click on Edit

Click on Add

Type 'EveryOne'

Click OK

Check Out Full Control

Click OK

The remote server returned an error: (403) Forbidden

In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.

[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
$req.UserAgent = "BlackHole"
$req.UseDefaultCredentials = $true

Good tool for testing socket connections?

I also found a tool called TCP/IP Test Server [Edit: no longer available from the original developer, but still available via Brothersoft] which seems to do what I need too. But I didn't try it because it is not listed on big freeware-sites (like CNET...) and no source code is published so that it won't reassure a paranoid sysadmin.

How to improve Netbeans performance?

Don't invest time in optimizing your NB installation as long as you can scale vertically: get a SSD (and faster hardware in general).

Also:

  • Add an exception for all relevant folders (e.g. project dir, temp dir) to your anti virus software (or better, get rid of it).
  • Don't use network drives for your projects
    • check if your home drive is local
    • check if your IDE uses non-local folders (e.g. %AppData%)

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

How to use the IEqualityComparer

Try This code:

public class GenericCompare<T> : IEqualityComparer<T> where T : class
{
    private Func<T, object> _expr { get; set; }
    public GenericCompare(Func<T, object> expr)
    {
        this._expr = expr;
    }
    public bool Equals(T x, T y)
    {
        var first = _expr.Invoke(x);
        var sec = _expr.Invoke(y);
        if (first != null && first.Equals(sec))
            return true;
        else
            return false;
    }
    public int GetHashCode(T obj)
    {
        return obj.GetHashCode();
    }
}

Example of its use would be

collection = collection
    .Except(ExistedDataEles, new GenericCompare<DataEle>(x=>x.Id))
    .ToList(); 

HTML table sort

Another approach to sort HTML table. (based on W3.JS HTML Sort)

_x000D_
_x000D_
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
  element.addEventListener("click", function() {_x000D_
    w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
  });_x000D_
});
_x000D_
th {_x000D_
  cursor: pointer;_x000D_
  background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
  <!--     _x000D_
  <tr>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
  </tr> _x000D_
  -->_x000D_
  <tr>_x000D_
    <th>Name</th>_x000D_
    <th>Address</th>_x000D_
    <th>Sales Person</th>_x000D_
  </tr>_x000D_
_x000D_
  <tr class="item">_x000D_
    <td>user:2911002</td>_x000D_
    <td>UK</td>_x000D_
    <td>Melissa</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2201002</td>_x000D_
    <td>France</td>_x000D_
    <td>Justin</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901092</td>_x000D_
    <td>San Francisco</td>_x000D_
    <td>Judy</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2801002</td>_x000D_
    <td>Canada</td>_x000D_
    <td>Skipper</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901009</td>_x000D_
    <td>Christchurch</td>_x000D_
    <td>Alex</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

Math.random() versus Random.nextInt(int)

According to this example Random.nextInt(n) has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.

usingRandomClass : time:328 milesecond.

usingMathsRandom : time:187 milesecond.

package javaFuction;
import java.util.Random;
public class RandomFuction 
{
    static int array[] = new int[9999];
    static long sum = 0;
    public static void usingMathsRandom() {
        for (int i = 0; i < 9999; i++) {
         array[i] = (int) (Math.random() * 256);
       }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }
        }
    }

    public static void usingRandomClass() {
        Random random = new Random();
        for (int i = 0; i < 9999; i++) {
            array[i] = random.nextInt(256);
        }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }

        }

    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        usingRandomClass();
        long end = System.currentTimeMillis();
        System.out.println("usingRandomClass " + (end - start));
        start = System.currentTimeMillis();
        usingMathsRandom();
        end = System.currentTimeMillis();
        System.out.println("usingMathsRandom " + (end - start));

    }

}

How to change the minSdkVersion of a project?

In your app/build.gradle file, you can set the minSdkVersion inside defaultConfig.

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.name.app"
        minSdkVersion 19    // This over here
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

ImportError: No module named pythoncom

$ pip3 install pypiwin32

Sometimes using pip3 also works if just pip by itself is not working.

Tricks to manage the available memory in an R session

Unfortunately I did not have time to test it extensively but here is a memory tip that I have not seen before. For me the required memory was reduced with more than 50%. When you read stuff into R with for example read.csv they require a certain amount of memory. After this you can save them with save("Destinationfile",list=ls()) The next time you open R you can use load("Destinationfile") Now the memory usage might have decreased. It would be nice if anyone could confirm whether this produces similar results with a different dataset.

Android Studio 3.0 Execution failed for task: unable to merge dex

I was receiving the same error and in my case, the error was resolved when I fixed a build error which was associated with a different build variant than the one I was currently building.

I was building the build variant I was looking at just fine with no errors, but attempting to debug caused a app:transformDexArchiveWithExternalLibsDexMergerForDebug error. Once I switched to build the other build variant, I caught my error in the build process and fixed it. This seemed to resolve my app:transformDexArchiveWithExternalLibsDexMergerForDebug issue for all build variants.

Note that this error wasn't within the referenced external module but within a distinct source set of a build variant which referenced an external module. Hope that's helpful to someone who may be seeing the same case as me!

Encoding an image file with base64

Borrowing from what Ivo van der Wijk and gnibbler have developed earlier, this is a dynamic solution

import cStringIO
import PIL.Image

image_data = None

def imagetopy(image, output_file):
    with open(image, 'rb') as fin:
        image_data = fin.read()

    with open(output_file, 'w') as fout:
        fout.write('image_data = '+ repr(image_data))

def pytoimage(pyfile):
    pymodule = __import__(pyfile)
    img = PIL.Image.open(cStringIO.StringIO(pymodule.image_data))
    img.show()

if __name__ == '__main__':
    imagetopy('spot.png', 'wishes.py')
    pytoimage('wishes')

You can then decide to compile the output image file with Cython to make it cool. With this method, you can bundle all your graphics into one module.

phpMyAdmin - config.inc.php configuration?

Run This Query:


*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
> 
> -- --------------------------------------------------------
> 
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin`   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> --    'pma'@localhost;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__bookmark`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__bookmark` (   `id` int(10) unsigned
> NOT NULL auto_increment,   `dbase` varchar(255) NOT NULL default '',  
> `user` varchar(255) NOT NULL default '',   `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '',   `query` text NOT NULL, 
> PRIMARY KEY  (`id`) )   COMMENT='Bookmarks'   DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__column_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__column_info` (   `id` int(5) unsigned
> NOT NULL auto_increment,   `db_name` varchar(64) NOT NULL default '', 
> `table_name` varchar(64) NOT NULL default '',   `column_name`
> varchar(64) NOT NULL default '',   `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `transformation` varchar(255)
> NOT NULL default '',   `transformation_options` varchar(255) NOT NULL
> default '',   `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',  
> PRIMARY KEY  (`id`),   UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) )   COMMENT='Column information
> for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__history`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__history` (   `id` bigint(20) unsigned
> NOT NULL auto_increment,   `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '',   `table` varchar(64) NOT NULL
> default '',   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP,   `sqlquery` text NOT NULL,   PRIMARY KEY  (`id`), 
> KEY `username` (`username`,`db`,`table`,`timevalue`) )   COMMENT='SQL
> history for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__pdf_pages`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` (   `db_name` varchar(64)
> NOT NULL default '',   `page_nr` int(10) unsigned NOT NULL
> auto_increment,   `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '',   PRIMARY KEY  (`page_nr`),   KEY `db_name`
> (`db_name`) )   COMMENT='PDF relation pages for phpMyAdmin'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__recent`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__recent` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Recently accessed tables'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__favorite`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__favorite` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Favorite tables'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_uiprefs`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` (   `username`
> varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,   `table_name`
> varchar(64) NOT NULL,   `prefs` text NOT NULL,   `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP,   PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__relation`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__relation` (   `master_db` varchar(64)
> NOT NULL default '',   `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '',   `foreign_db`
> varchar(64) NOT NULL default '',   `foreign_table` varchar(64) NOT
> NULL default '',   `foreign_field` varchar(64) NOT NULL default '',  
> PRIMARY KEY  (`master_db`,`master_table`,`master_field`),   KEY
> `foreign_field` (`foreign_db`,`foreign_table`) )   COMMENT='Relation
> table'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_coords`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_coords` (   `db_name`
> varchar(64) NOT NULL default '',   `table_name` varchar(64) NOT NULL
> default '',   `pdf_page_number` int(11) NOT NULL default '0',   `x`
> float unsigned NOT NULL default '0',   `y` float unsigned NOT NULL
> default '0',   PRIMARY KEY  (`db_name`,`table_name`,`pdf_page_number`)
> )   COMMENT='Table coordinates for phpMyAdmin PDF output'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_info` (   `db_name` varchar(64)
> NOT NULL default '',   `table_name` varchar(64) NOT NULL default '',  
> `display_field` varchar(64) NOT NULL default '',   PRIMARY KEY 
> (`db_name`,`table_name`) )   COMMENT='Table information for
> phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__tracking`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__tracking` (   `db_name` varchar(64)
> NOT NULL,   `table_name` varchar(64) NOT NULL,   `version` int(10)
> unsigned NOT NULL,   `date_created` datetime NOT NULL,  
> `date_updated` datetime NOT NULL,   `schema_snapshot` text NOT NULL,  
> `schema_sql` text,   `data_sql` longtext,   `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL,   `tracking_active`
> int(1) unsigned NOT NULL default '1',   PRIMARY KEY 
> (`db_name`,`table_name`,`version`) )   COMMENT='Database changes
> tracking for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__userconfig`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__userconfig` (   `username`
> varchar(64) NOT NULL,   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,   `config_data` text
> NOT NULL,   PRIMARY KEY  (`username`) )   COMMENT='User preferences
> storage for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__users`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__users` (   `username` varchar(64) NOT
> NULL,   `usergroup` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`usergroup`) )   COMMENT='Users and their assignments to
> user groups'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__usergroups`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__usergroups` (   `usergroup`
> varchar(64) NOT NULL,   `tab` varchar(64) NOT NULL,   `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N',   PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) )   COMMENT='User groups with configured
> menu items'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__navigationhiding`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` (   `username`
> varchar(64) NOT NULL,   `item_name` varchar(64) NOT NULL,  
> `item_type` varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,  
> `table_name` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )  
> COMMENT='Hidden items of navigation tree'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__savedsearches`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` (   `id` int(5)
> unsigned NOT NULL auto_increment,   `username` varchar(64) NOT NULL
> default '',   `db_name` varchar(64) NOT NULL default '',  
> `search_name` varchar(64) NOT NULL default '',   `search_data` text
> NOT NULL,   PRIMARY KEY  (`id`),   UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> )   COMMENT='Saved searches'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__central_columns`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__central_columns` (   `db_name`
> varchar(64) NOT NULL,   `col_name` varchar(64) NOT NULL,   `col_type`
> varchar(64) NOT NULL,   `col_length` text,   `col_collation`
> varchar(64) NOT NULL,   `col_isNull` boolean NOT NULL,   `col_extra`
> varchar(255) default '',   `col_default` text,   PRIMARY KEY
> (`db_name`,`col_name`) )   COMMENT='Central list of columns'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__designer_settings`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` (   `username`
> varchar(64) NOT NULL,   `settings_data` text NOT NULL,   PRIMARY KEY
> (`username`) )   COMMENT='Settings related to Designer'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__export_templates`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__export_templates` (   `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT,   `username` varchar(64) NOT NULL,  
> `export_type` varchar(10) NOT NULL,   `template_name` varchar(64) NOT
> NULL,   `template_data` text NOT NULL,   PRIMARY KEY (`id`),   UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> )   COMMENT='Saved export templates'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*

Open This File :

C:\xampp\phpMyAdmin\config.inc.php

Clear and Past this Code :

> --------------------------------------------------------- <?php /**  * Debian local configuration file  *  * This file overrides the settings
> made by phpMyAdmin interactive setup  * utility.  *  * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz  *  * NOTE:
> do not add security sensitive data to this file (like passwords)  *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still  * want to do this, make sure to properly secure the access to
> this file  * (also on the filesystem level).  */ /**  * Server(s)
> configuration  */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1].  Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
>     /* Authentication type */
>     $cfg['Servers'][$i]['auth_type'] = 'cookie';
>     /* Server parameters */
>     if (empty($dbserver)) $dbserver = 'localhost';
>     $cfg['Servers'][$i]['host'] = $dbserver;
>     if (!empty($dbport)) {
>         $cfg['Servers'][$i]['connect_type'] = 'tcp';
>         $cfg['Servers'][$i]['port'] = $dbport;
>     }
>     //$cfg['Servers'][$i]['compress'] = false;
>     /* Select mysqli if your server has it */
>     $cfg['Servers'][$i]['extension'] = 'mysqli';
>     /* Optional: User for advanced features */
>     $cfg['Servers'][$i]['controluser'] = $dbuser;
>     $cfg['Servers'][$i]['controlpass'] = $dbpass;
>     /* Optional: Advanced phpMyAdmin features */
>     $cfg['Servers'][$i]['pmadb'] = $dbname;
>     $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
>     $cfg['Servers'][$i]['relation'] = 'pma_relation';
>     $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
>     $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
>     $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
>     $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
>     $cfg['Servers'][$i]['history'] = 'pma_history';
>     $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
>     /* Uncomment the following to enable logging in to passwordless accounts,
>      * after taking note of the associated security risks. */
>     // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
>     /* Advance to next server for rest of config */
>     $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';  
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /*  * End of servers
> configuration  */ /*  * Directories for saving/loading files from
> server  */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';

------------------------------------------

i Solve My Problem Through this Method

Excel - Shading entire row based on change of value

If you are using MS Excel 2007, you could use the conditional formatting on the Home tab as shown in the screenshot below. You could either use the color scales default option as I have done here or you can go ahead and create a new rule based on your data set. Conditional Formatting

Converting SVG to PNG using C#

You can call the command-line version of inkscape to do this:

http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx

Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:

Original Project
http://www.codeplex.com/svg

Fork with fixes and more activity: (added 7/2013)
https://github.com/vvvv/SVG

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Since the only missing example is the ANDROID example, I'll add it. This technique uses a custom AsyncTask that should be declared inside your Activity class.

private class UploadFile extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        // set a status bar or show a dialog to the user here
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // progress[0] is the current status (e.g. 10%)
        // here you can update the user interface with the current status
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    private String uploadFile() {

        String responseString = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://example.com/upload-file");

        try {
            AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
                new ProgressListener() {
                    @Override
                        public void transferred(long num) {
                            // this trigger the progressUpdate event
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
            });

            File myFile = new File("/my/image/path/example.jpg");

            ampEntity.addPart("fileFieldName", new FileBody(myFile));

            totalSize = ampEntity.getContentLength();
            httpPost.setEntity(ampEntity);

            // Making server call
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                responseString = EntityUtils.toString(httpEntity);
            } else {
                responseString = "Error, http status: "
                        + statusCode;
            }

        } catch (Exception e) {
            responseString = e.getMessage();
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        // if you want update the user interface with upload result
        super.onPostExecute(result);
    }

}

So, when you want to upload your file just call:

new UploadFile().execute();

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

Rename Files and Directories (Add Prefix)

To add a prefix to all files and folders in the current directory using util-linux's rename (as opposed to prename, the perl variant from Debian and certain other systems), you can do:

rename '' <prefix> *

This finds the first occurrence of the empty string (which is found immediately) and then replaces that occurrence with your prefix, then glues on the rest of the file name to the end of that. Done.

For suffixes, you need to use the perl version or use find.

How do you create a Spring MVC project in Eclipse?

This is the easiest way :

step 1) install Spring Tool Suite (STS) for eclipse (version 3.7.0RELEASE or above) To do this you can go to Help >> eclipse market place , then type Spring Tool suite in search box.

step 2) now go to file >> new >> spring project as shown in the image below enter image description here

step 3)now choose the template as "spring MVC Project" and give a name to your project on the top as shown below ( I named it 'SpringProject') enter image description here

step 4)now give a base package name like this enter image description here

and that is . The project will be created in a few minutes and Now you can right click on it and run on server.

Pass values of checkBox to controller action in asp.net mvc4

 public ActionResult Save(Director director)
        {
          // IsActive my model property same name give in cshtml
//IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive" 
            if(ModelState.IsValid)
            {
                DirectorVM ODirectorVM = new DirectorVM();
                ODirectorVM.SaveData(director);
                return RedirectToAction("Display");
            }
            return RedirectToAction("Add");
        }

How to retrieve the LoaderException property?

Another Alternative for those who are probing around and/or in interactive mode:

$Error[0].Exception.LoaderExceptions

Note: [0] grabs the most recent Error from the stack

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

Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.

AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.

AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.

AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.

AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.

AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.

AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.

How to change date format in JavaScript

Use your mydate object and call getMonth() and getFullYear()

See this for more info: http://www.w3schools.com/jsref/jsref_obj_date.asp

Multiline strings in VB.NET

in Visual studio 2010 (VB NET)i try the following and works fine

Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>

dim Test1 as string =<a>onother multiline example</a>

Convert array of integers to comma-separated string

.NET 4

string.Join(",", arr)

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))

TabLayout tab selection

A combined solution from different answers is:

new Handler().postDelayed(() -> {

  myViewPager.setCurrentItem(position, true);

  myTabLayout.setScrollPosition(position, 0f, true);
},
100);

What is the first character in the sort order used by Windows Explorer?

Although the answer with "!" was chosen as the correct answer, this is NOT true. I´m not sure about Windows Explorer in Windows 10/8.1/8, but I am certain concerning Windows 7 and XP.

The character that moves your filename to the very top is "'" (alt+39), and second best is "-" (the minus sign).

But sorting order in Windows Explorer is more complicated - it depends on the filename-lenght also, and numbers are treated very special.

The second character (and the following) is treated different. Here you often go best with a " " (spacebar), followed by the characters mentioned above, but you´ll have to try out, because it´s not so easy to find out the exact algorithm:

Here is an example for the correct sorting order for your understanding:

  1. file: "'"
  2. file: "''" (longer filename)
  3. file: "'''" (and so on)
  4. file: "-"
  5. file: "--"
  6. file: "---" (and so on)
  7. file: "- -" (spacebar used)
  8. file: "' '" (spacebar two times, therefore longer filename)
  9. file: "' ' '" (most top character, but longer filename!)
  10. file: "'' 0" (shorter filename, but chars like numbers came in)

Another example:

  1. "'' aaaa" ("'" is better than spacebar and spacebar is better than "a")
  2. "'' aaaaa"
  3. "' aaaaaa"

Same filelenght:

  1. "-- aa" (spacebar comes before "-" in this case!)
  2. "---aa"
  3. "--aaa"

Finally the very special logic when it comes to numbers:

  1. "0000000"
  2. "0"
  3. "00001"

But nevertheless: Renaming folders or files this way, you can quickly find what you are searching for.

The differences between initialize, define, declare a variable

For C, at least, per C11 6.7.5:

A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

  • for an object, causes storage to be reserved for that object;

  • for a function, includes the function body;

  • for an enumeration constant, is the (only) declaration of the identifier;

  • for a typedef name, is the first (or only) declaration of the identifier.

Per C11 6.7.9.8-10:

An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.

So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.

Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).

So, if you define an automatic variable without specifying an initial value for it, such as:

int myfunc(void) {
    int myvar;
    ...

You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.

Pure JavaScript: a function like jQuery's isNumeric()

This should help:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Very good link: Validate decimal numbers in JavaScript - IsNumeric()

How to bring an activity to foreground (top of stack)?

Here is a code-example of how you can do it:

Intent intent = getIntent(getApplicationContext(), A.class)

This will make sure that you only have one instance of an activity on the stack.

private static Intent getIntent(Context context, Class<?> cls) {
    Intent intent = new Intent(context, cls);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    return intent;
}

How to dismiss a Twitter Bootstrap popover by clicking outside?

$("body").find('.popover').removeClass('in');

PHP - iterate on string characters

Hmm... There's no need to complicate things. The basics work great always.

    $string = 'abcdef';
    $len = strlen( $string );
    $x = 0;

Forward Direction:

while ( $len > $x ) echo $string[ $x++ ];

Outputs: abcdef

Reverse Direction:

while ( $len ) echo $string[ --$len ];

Outputs: fedcba

How to include a sub-view in Blade templates?

You can use the blade template engine:

@include('view.name') 

'view.name' would live in your main views folder:

// for laravel 4.X
app/views/view/name.blade.php  

// for laravel 5.X
resources/views/view/name.blade.php

Another example

@include('hello.world');

would display the following view

// for laravel 4.X
app/views/hello/world.blade.php

// for laravel 5.X
resources/views/hello/world.blade.php

Another example

@include('some.directory.structure.foo');

would display the following view

// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php

// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x

ADDITIONAL

If you want to pass parameters: @include('view.name', array('paramName' => 'value'))

You can then use the value in your views like so <p>{{$paramName}}</p>

What is the point of "final class" in Java?

Final classes cannot be extended. So if you want a class to behave a certain way and don't someone to override the methods (with possibly less efficient and more malicious code), you can declare the whole class as final or specific methods which you don't want to be changed.

Since declaring a class does not prevent a class from being instantiated, it does not mean it will stop the class from having the characteristics of an object. It's just that you will have to stick to the methods just the way they are declared in the class.

How can I check for Python version in a program that uses new language features?

I'm expanding on akhan's excellent answer, which prints a helpful message before the Python script is even compiled.

If you want to ensure that the script is being run with Python 3.6 or newer, add these two lines to the top of your Python script:

#!/bin/sh
''''python3 -c 'import sys; sys.exit(sys.version_info < (3, 6))' && exec python3 -u -- "$0" ${1+"$@"}; echo 'This script requires Python 3.6 or newer.'; exit 1 # '''

(Note: The second line starts with four single-quotes and ends with three single-quotes. This may look strange, but it is not a typo.)

The advantage of this solution is that code like print(f'Hello, {name}!') won't cause a SyntaxError if a Python version older than 3.6 is used. You'll see this helpful message instead:

This script requires Python 3.6 or newer.

Of course, this solution only works on Unix-like shells, and only when the script is invoked directly (such as: ./script.py), and with the proper eXecute permission bits set.

Error 1022 - Can't write; duplicate key in table

You are probably trying to create a foreign key in some table which exists with the same name in previously existing tables. Use the following format to name your foreign key

tablename_columnname_fk

How can I add the new "Floating Action Button" between two widgets/layouts

Add this to your gradle file

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.android.support:design:23.0.1'
}

This to your activity_main.xml

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/viewOne"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="0.6"
                android:background="@android:color/holo_blue_light"
                android:orientation="horizontal"/>

            <LinearLayout
                android:id="@+id/viewTwo"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="0.4"
                android:background="@android:color/holo_orange_light"
                android:orientation="horizontal"/>

        </LinearLayout>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/floatingButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_done"
            app:layout_anchor="@id/viewOne"
            app:layout_anchorGravity="bottom|right|end"
            app:backgroundTint="#FF0000"
            app:rippleColor="#FFF" />

    </android.support.design.widget.CoordinatorLayout>

You can find the full example with android studio project to download at http://www.ahotbrew.com/android-floating-action-button/

Twitter Bootstrap dropdown menu

<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js"></script>

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

How do I check if a list is empty?

Method 1 (Preferred):

if not a : 
   print ("Empty") 

Method 2 :

if len(a) == 0 :
   print( "Empty" )

Method 3:

if a == [] :
  print ("Empty")

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Use shell=True if you're passing a string to subprocess.call.

From docs:

If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.

subprocess.call(crop, shell=True)

or:

import shlex
subprocess.call(shlex.split(crop))

Tainted canvases may not be exported

I also solved this error by adding useCORS : true, in my code like -

html2canvas($("#chart-section")[0], {
        useCORS : true,
        allowTaint : true,
        scale : 0.98,
        dpi : 500,
        width: 1400, height: 900
    }).then();

powershell - extract file name and extension

If the file is coming off the disk and as others have stated, use the BaseName and Extension properties:

PS C:\> dir *.xlsx | select BaseName,Extension

BaseName                                Extension
--------                                ---------
StackOverflow.com Test Config           .xlsx  

If you are given the file name as part of string (say coming from a text file), I would use the GetFileNameWithoutExtension and GetExtension static methods from the System.IO.Path class:

PS C:\> [System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
Test Config
PS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx")
.xlsx

How to clean old dependencies from maven repositories?

Short answer - Deleted .m2 folder in {user.home}. E.g. in windows 10 user home is C:\Users\user1. Re-build your project using mvn clean package. Only those dependencies would remain, which are required by the projects.

Long Answer - .m2 folder is just like a normal folder and the content of the folder is built from different projects. I think there is no way to figure out automatically that which library is "old". In fact old is a vague word. There could be so many reasons when a previous version of a library is used in a project, hence determining which one is unused is not possible.

All you could do, is to delete the .m2 folder and re-build all of your projects and then the folder would automatically build with all the required library.

If you are concern about only a particular version of a library to be used in all the projects; it is important that the project's pom should also update to latest version. i.e. if different POMs refer different versions of the library, all will get downloaded in .m2.

application/x-www-form-urlencoded or multipart/form-data?

I agree with much that Manuel has said. In fact, his comments refer to this url...

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4

... which states:

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

However, for me it would come down to tool/framework support.

  • What tools and frameworks do you expect your API users to be building their apps with?
  • Do they have frameworks or components they can use that favour one method over the other?

If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.

Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.

Compare objects in Angular

I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

Example:

var obj1 = {
  $key0: "A",
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  $key0: "B"
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)

Calculating the SUM of (Quantity*Price) from 2 different tables

I had the same problem as Marko and come across a solution like this:

/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)

/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS

/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal

/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)

/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
    SELECT oi.Quantity * p.Price AS columnGrandTotal
        FROM OrderItem oi
        JOIN Product p ON oi.Id = p.Id

/*And return the sum of columnGrandTotal from the newly created table*/    
SELECT SUM(columnGrandTotal) as [Grand Total]
    FROM tableGrandTotal

And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)

EXEC GetGrandTotal

How to change the interval time on bootstrap carousel?

You can simply use the data-interval attribute of the carousel class.

It's default value is set to data-interval="3000" i.e 3seconds.

All you need to do is set it to your desired requirements.

How do I determine the current operating system with Node.js

This Works fine for me

var osvar = process.platform;

if (osvar == 'darwin') {
    console.log("you are on a mac os");
}else if(osvar == 'win32'){
    console.log("you are on a windows os")
}else{
    console.log("unknown os")
}

Cannot make a static reference to the non-static method fxn(int) from the type Two

You cannot refer non-static members from a static method.

Non-Static members (like your fxn(int y)) can be called only from an instance of your class.

Example:

You can do this:

       public class A
       {
           public   int fxn(int y) {
              y = 5;
              return y;
          }
       }


  class Two {
public static void main(String[] args) {
    int x = 0;
    A a = new A();
    System.out.println("x = " + x);
    x = a.fxn(x);
    System.out.println("x = " + x);
}

or you can declare you method as static.

Git - How to use .netrc file on Windows to save user and password

This will let Git authenticate on HTTPS using .netrc:

  • The file should be named _netrc and located in c:\Users\<username>.
  • You will need to set an environment variable called HOME=%USERPROFILE% (set system-wide environment variables using the System option in the control panel. Depending on the version of Windows, you may need to select "Advanced Options".).
  • The password stored in the _netrc file cannot contain spaces (quoting the password will not work).

Linux c++ error: undefined reference to 'dlopen'

I was using CMake to compile my project and I've found the same problem.

The solution described here works like a charm, simply add ${CMAKE_DL_LIBS} to the target_link_libraries() call

Detect iPhone/iPad purely by css

iPhone & iPod touch:

<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="../iphone.css" type="text/css" />

iPhone 4 & iPod touch 4G:

<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="../iphone4.css" />

iPad:

<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="../ipad.css" type="text/css" />

How to remove all non-alpha numeric characters from a string in MySQL?

None of these answers worked for me. I had to create my own function called alphanum which stripped the chars for me:

DROP FUNCTION IF EXISTS alphanum; 
DELIMITER | 
CREATE FUNCTION alphanum( str CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC
BEGIN 
  DECLARE i, len SMALLINT DEFAULT 1; 
  DECLARE ret CHAR(255) DEFAULT ''; 
  DECLARE c CHAR(1);
  IF str IS NOT NULL THEN 
    SET len = CHAR_LENGTH( str ); 
    REPEAT 
      BEGIN 
        SET c = MID( str, i, 1 ); 
        IF c REGEXP '[[:alnum:]]' THEN 
          SET ret=CONCAT(ret,c); 
        END IF; 
        SET i = i + 1; 
      END; 
    UNTIL i > len END REPEAT; 
  ELSE
    SET ret='';
  END IF;
  RETURN ret; 
END | 
DELIMITER ; 

Now I can do:

select 'This works finally!', alphanum('This works finally!');

and I get:

+---------------------+---------------------------------+
| This works finally! | alphanum('This works finally!') |
+---------------------+---------------------------------+
| This works finally! | Thisworksfinally                |
+---------------------+---------------------------------+
1 row in set (0.00 sec)

Hurray!

In PowerShell, how can I test if a variable holds a numeric value?

Testing if a value is numeric or a string representation of a numeric value.

function Test-Number 
{
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [ValidatePattern("^[\d\.]+$")]
        $Number
    )

    $Number -is [ValueType] -or [Double]::TryParse($Number,[ref]$null)
}

Testing if a value is numeric.

function Test-Number 
{
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [ValidatePattern("^[\d\.]+$")]
        $Number
    )

    $Number -is [ValueType]
}

Add Insecure Registry to Docker

If you already have a config.json file then the final file should look something like this... Here registry.myprivate.com is the one which was giving me problems.

{ "auths": { "https://index.docker.io/v1/": { "auth": "xxxxxxxxxxxxxxxxxxxx==" }, "registry.myprivate.com": { "auth": "xxxxxxxxxxxxxxxxxxxx=" } }, "HttpHeaders": { "User-Agent": "Docker-Client/19.03.8 (linux)" }, "insecure-registries" : ["registry.myprivate.com"] }

Is there a better jQuery solution to this.form.submit();?

I think what you are looking for is something like this:

$(field).closest("form").submit();

For example, to handle the onchange event, you would have this:

$(select your fields here).change(function() {
    $(this).closest("form").submit();
});

If, for some reason you aren't using jQuery 1.3 or above, you can call parents instead of closest.

How to add hamburger menu in bootstrap

All you have to do is read the code on getbootstrap.com:

Codepen

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
  <div class="container">_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
      <ul class="nav navbar-nav">_x000D_
        <li><a href="index.php">Home</a></li>_x000D_
        <li><a href="about.php">About</a></li>_x000D_
        <li><a href="#portfolio">Portfolio</a></li>_x000D_
        <li><a href="#">Blog</a></li>_x000D_
        <li><a href="contact.php">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Where does Jenkins store configuration files for the jobs it runs?

The best approach would be to keep your job configurations in a Jenkinsfile that live in source control.

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

Why split the <script> tag when writing it with document.write()?

Here's another variation I've used when wanting to generate a script tag inline (so it executes immediately) without needing any form of escapes:

<script>
    var script = document.createElement('script');
    script.src = '/path/to/script.js';
    document.write(script.outerHTML);
</script>

(Note: contrary to most examples on the net, I'm not setting type="text/javascript" on neither the enclosing tag, nor the generated one: there is no browser not having that as the default, and so it is redundant, but will not hurt either, if you disagree).

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

I was able to fix the issue using the following in mac.

sudo npm install -g @aws-amplify/cli --unsafe-perm=true

Execute another jar in a Java program

Hope this helps:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}

Capture key press without placing an input element on the page?

For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.

Attaching a keydown event to document works in all the major browsers:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.ctrlKey && evt.keyCode == 90) {
        alert("Ctrl-Z");
    }
};

For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.

When is JavaScript synchronous?

To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don't necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.

JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete etc...

The main point of confusion arises from the fact that your browser is able to tell JS to execute more code at anytime (similar to how you can execute more JS code on a page from the console). As an example JS has Callback functions who's purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.

Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)

I hope this is clear enough to be helpful to somebody.

How to select all columns, except one column in pandas?

df[df.columns.difference(['b'])]

Out: 
          a         c         d
0  0.427809  0.459807  0.333869
1  0.678031  0.668346  0.645951
2  0.996573  0.673730  0.314911
3  0.786942  0.719665  0.330833

How to load assemblies in PowerShell?

Most people know by now that System.Reflection.Assembly.LoadWithPartialName is deprecated, but it turns out that Add-Type -AssemblyName Microsoft.VisualBasic does not behave much better than LoadWithPartialName:

Rather than make any attempt to parse your request in the context of your system, [Add-Type] looks at a static, internal table to translate the "partial name" to a "full name".

If your "partial name" doesn't appear in their table, your script will fail.

If you have multiple versions of the assembly installed on your computer, there is no intelligent algorithm to choose between them. You are going to get whichever one appears in their table, probably the older, outdated one.

If the versions you have installed are all newer than the obsolete one in the table, your script will fail.

Add-Type has no intelligent parser of "partial names" like .LoadWithPartialNames.

What Microsoft's .Net teams says you're actually supposed to do is something like this:

Add-Type -AssemblyName 'Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

Or, if you know the path, something like this:

Add-Type -Path 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualBasic\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualBasic.dll'

That long name given for the assembly is known as the strong name, which is both unique to the version and the assembly, and is also sometimes known as the full name.

But this leaves a couple questions unanswered:

  1. How do I determine the strong name of what's actually being loaded on my system with a given partial name?

    [System.Reflection.Assembly]::LoadWithPartialName($TypeName).Location; [System.Reflection.Assembly]::LoadWithPartialName($TypeName).FullName;

These should also work:

Add-Type -AssemblyName $TypeName -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
  1. If I want my script to always use a specific version of a .dll but I can't be certain of where it's installed, how do I determine what the strong name is from the .dll?

    [System.Reflection.AssemblyName]::GetAssemblyName($Path).FullName;

Or:

Add-Type $Path -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
  1. If I know the strong name, how do I determine the .dll path?

    [Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a').Location;

  2. And, on a similar vein, if I know the type name of what I'm using, how do I know what assembly it's coming from?

    [Reflection.Assembly]::GetAssembly([Type]).Location [Reflection.Assembly]::GetAssembly([Type]).FullName

  3. How do I see what assemblies are available?

I suggest the GAC PowerShell module. Get-GacAssembly -Name 'Microsoft.SqlServer.Smo*' | Select Name, Version, FullName works pretty well.

  1. How can I see the list that Add-Type uses?

This is a bit more complex. I can describe how to access it for any version of PowerShell with a .Net reflector (see the update below for PowerShell Core 6.0).

First, figure out which library Add-Type comes from:

Get-Command -Name Add-Type | Select-Object -Property DLL

Open the resulting DLL with your reflector. I've used ILSpy for this because it's FLOSS, but any C# reflector should work. Open that library, and look in Microsoft.Powershell.Commands.Utility. Under Microsoft.Powershell.Commands, there should be AddTypeCommand.

In the code listing for that, there is a private class, InitializeStrongNameDictionary(). That lists the dictionary that maps the short names to the strong names. There's almost 750 entries in the library I've looked at.

Update: Now that PowerShell Core 6.0 is open source. For that version, you can skip the above steps and see the code directly online in their GitHub repository. I can't guarantee that that code matches any other version of PowerShell, however.

Update 2: Powershell 7+ does not appear to have the hash table lookup any longer. Instead they use a LoadAssemblyHelper() method which the comments call "the closest approximation possible" to LoadWithPartialName. Basically, they do this:

loadedAssembly = Assembly.Load(new AssemblyName(assemblyName));

Now, the comments also say "users can just say Add-Type -AssemblyName Forms (instead of System.Windows.Forms)". However, that's not what I see in Powershell v7.0.3 on Windows 10 2004.

# Returns an error
Add-Type -AssemblyName Forms

# Returns an error
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('Forms'))

# Works fine
Add-Type -AssemblyName System.Windows.Forms

# Works fine
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('System.Windows.Forms'))

So the comments appear to be a bit of a mystery.

I don't know exactly what the logic is in Assembly.Load(AssemblyName) when there is no version or public key token specified. I would expect that this has many of the same problems that LoadWithPartialName does like potentially loading the wrong version of the assembly if you have multiple installed.

Get all messages from Whatsapp

Working Android Code: (No root required)

Once you have access to the dbcrypt5 file , here is the android code to decrypt it:

private byte[] key = { (byte) 141, 75, 21, 92, (byte) 201, (byte) 255,
        (byte) 129, (byte) 229, (byte) 203, (byte) 246, (byte) 250, 120,
        25, 54, 106, 62, (byte) 198, 33, (byte) 166, 86, 65, 108,
        (byte) 215, (byte) 147 };

private final byte[] iv = { 0x1E, 0x39, (byte) 0xF3, 0x69, (byte) 0xE9, 0xD,
        (byte) 0xB3, 0x3A, (byte) 0xA7, 0x3B, 0x44, 0x2B, (byte) 0xBB,
        (byte) 0xB6, (byte) 0xB0, (byte) 0xB9 };
   long start = System.currentTimeMillis();

    // create paths
    backupPath = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/WhatsApp/Databases/msgstore.db.crypt5";
    outputPath = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/WhatsApp/Databases/msgstore.db.decrypt";

    File backup = new File(backupPath);

    // check if file exists / is accessible
    if (!backup.isFile()) {
        Log.e(TAG, "Backup file not found! Path: " + backupPath);
        return;
    }

    // acquire account name
    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("com.google");

    if (accounts.length == 0) {
        Log.e(TAG, "Unable to fetch account!");
        return;
    }

    String account = accounts[0].name;

    try {
        // calculate md5 hash over account name
        MessageDigest message = MessageDigest.getInstance("MD5");
        message.update(account.getBytes());
        byte[] md5 = message.digest();

        // generate key for decryption
        for (int i = 0; i < 24; i++)
            key[i] ^= md5[i & 0xF];

        // read encrypted byte stream
        byte[] data = new byte[(int) backup.length()];
        DataInputStream reader = new DataInputStream(new FileInputStream(
                backup));
        reader.readFully(data);
        reader.close();

        // create output writer
        File output = new File(outputPath);
        DataOutputStream writer = new DataOutputStream(
                new FileOutputStream(output));

        // decrypt file
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secret = new SecretKeySpec(key, "AES");
        IvParameterSpec vector = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, secret, vector);
        writer.write(cipher.update(data));
        writer.write(cipher.doFinal());
        writer.close();
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Could not acquire hash algorithm!", e);
        return;
    } catch (IOException e) {
        Log.e(TAG, "Error accessing file!", e);
        return;
    } catch (Exception e) {
        Log.e(TAG, "Something went wrong during the encryption!", e);
        return;
    }

    long end = System.currentTimeMillis();

    Log.i(TAG, "Success! It took " + (end - start) + "ms");

What's the best way to join on the same table twice?

SELECT
    T1.ID
    T1.PhoneNumber1,
    T1.PhoneNumber2
    T2A.SomeOtherField AS "SomeOtherField of PhoneNumber1",
    T2B.SomeOtherField AS "SomeOtherField of PhoneNumber2"  
FROM
    Table1 T1
    LEFT JOIN Table2 T2A ON T1.PhoneNumber1 = T2A.PhoneNumber
    LEFT JOIN Table2 T2B ON T1.PhoneNumber2 = T2B.PhoneNumber
WHERE
    T1.ID = 'FOO';

LEFT JOIN or JOIN also return same result. Tested success with PostgreSQL 13.1.1 .

enter image description here

HashMaps and Null values?

Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?

I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :

if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");

Got this error:

Struts Problem Report

Struts has detected an unhandled exception:

Messages:   
File:   aoc/psisclient/samples/PDFValidation.java
Line number:    155
Stacktraces

java.lang.NullPointerException
    aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
    aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    ...

Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.

Python Requests library redirect new url

You are looking for the request history.

The response.history attribute is a list of responses that led to the final URL, which can be found in response.url.

response = requests.get(someurl)
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

Demo:

>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
... 
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get

Function or sub to add new row and data to table

I needed this same solution, but if you use the native ListObject.Add() method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:

Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        For col = 1 To lastRow.Columns.Count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design tab of the ribbon, in Excel 2013 at least: enter image description here

Example code for a table with three columns:

Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x

How to format an inline code in Confluence?

I found formatting with colors a bit trickier as Confluence (5.6.3) is very fussy about spaces around the {{monospace}} blocks.

Creating Colored Monospace with Wiki Markup

As rendered by Confluence

How to unload a package without restarting R

Just go to OUTPUT window, then click on Packages icon (it is located between Plot and Help icons). Remove "tick / check mark" from the package you wanted be unload.

For again using the package just put a "tick or Check mark" in front of package or use :

library (lme4)

How to start working with GTest and CMake

The simplest CMakeLists.txt I distilled from answers in this thread and some trial and error is:

project(test CXX C)
cmake_minimum_required(VERSION 2.6.2)

#include folder contains current project's header filed
include_directories("include")

#test folder contains test files
set (PROJECT_SOURCE_DIR test) 
add_executable(hex2base64 ${PROJECT_SOURCE_DIR}/hex2base64.cpp)

# Link test executable against gtest nothing else required
target_link_libraries(hex2base64 gtest pthread)

Gtest should already be installed on your system.

Ant is using wrong java version

If you are not using eclipse. Then you can change the ant java property directly on the file as mentioned here.

http://pissedoff-techie.blogspot.in/2014/09/ant-picks-up-incorrect-java-version.html

What's the difference between KeyDown and KeyPress in .NET?

From Blogging Developer:

In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

Note: You can also try out the Key Event Tester (available on the above-mentioned site) to understand this concept.

How do I prevent a form from being resized by the user?

There is an option in vb.net that lets you do all this.

Set <code>lock = false</code> to <code>locked = true</code>

The user wont be able to re-size the form or move it around, although there are other ways, this I think is the best.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Convert double to float in Java

To answer your query on "How to convert 2.3423424666767E13 to 23423424666767"

You can use a decimal formatter for formatting decimal numbers.

     double d = 2.3423424666767E13;
     DecimalFormat decimalFormat = new DecimalFormat("#");
     System.out.println(decimalFormat.format(d));

Output : 23423424666767

How can I uninstall Ruby on ubuntu?

Here is what sudo apt-get purge ruby* removed relating to GRUB for me:

grub-pc 
grub-gfxpayload-lists
grub2-common
grub-pc-bin 
grub-common 

Trim whitespace from a String

In addition to answer of @gjha:

inline std::string ltrim_copy(const std::string& str)
{
    auto it = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return std::string(it, str.cend());
}

inline std::string rtrim_copy(const std::string& str)
{
    auto it = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
}

inline std::string trim_copy(const std::string& str)
{
    auto it1 = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    if (it1 == str.cend()) {
        return std::string();
    }
    auto it2 = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
}

View the change history of a file using Git versioning

If you use TortoiseGit you should be able to right click on the file and do TortoiseGit --> Show Log. In the window that pops up, make sure:

  • 'Show Whole Project' option is not checked.

  • 'All Branches' option is checked.

How to remove leading and trailing whitespace in a MySQL field?

This statement will remove and update the field content of your database

To remove whitespaces in the left side of the field value

UPDATE table SET field1 = LTRIM(field1);

ex. UPDATE member SET firstName = LTRIM(firstName);

To remove whitespaces in the right side of the field value

UPDATE table SETfield1 = RTRIM(field1);

ex. UPDATE member SET firstName = RTRIM(firstName);

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

For complete the accepted answer, Had the same issue. First specified the remote

git remote add origin https://github.com/XXXX/YYY.git

git fetch 

Then get the code

git pull origin master

Parse error: Syntax error, unexpected end of file in my PHP code

You can't divide IF/ELSE instructions into two separate blocks. If you need HTML code to be printed, use echo.

<html>
    <?php
        function login()
        {
            // Login function code
        }
        if (login())
        {
            echo "<h2>Welcome Administrator</h2>
            <a href=\"upload.php\">Upload Files</a>
            <br />
            <a href=\"points.php\">Edit Points Tally</a>";
        }
        else
        {
            echo "Incorrect login details. Please login";
        }
    ?>
    Some more HTML code
</html>

Read Variable from Web.Config

I am siteConfiguration class for calling all my appSetting like this way. I share it if it will help anyone.

add the following code at the "web.config"

<configuration>
   <configSections>
     <!-- some stuff omitted here -->
   </configSections>
   <appSettings>
      <add key="appKeyString" value="abc" />
      <add key="appKeyInt" value="123" />  
   </appSettings>
</configuration>

Now you can define a class for getting all your appSetting value. like this

using System; 
using System.Configuration;
namespace Configuration
{
   public static class SiteConfigurationReader
   {
      public static String appKeyString  //for string type value
      {
         get
         {
            return ConfigurationManager.AppSettings.Get("appKeyString");
         }
      }

      public static Int32 appKeyInt  //to get integer value
      {
         get
         {
            return ConfigurationManager.AppSettings.Get("appKeyInt").ToInteger(true);
         }
      }

      // you can also get the app setting by passing the key
      public static Int32 GetAppSettingsInteger(string keyName)
      {
          try
          {
            return Convert.ToInt32(ConfigurationManager.AppSettings.Get(keyName));
        }
        catch
        {
            return 0;
        }
      }
   }
}

Now add the reference of previous class and to access a key call like bellow

string appKeyStringVal= SiteConfigurationReader.appKeyString;
int appKeyIntVal= SiteConfigurationReader.appKeyInt;
int appKeyStringByPassingKey = SiteConfigurationReader.GetAppSettingsInteger("appKeyInt");

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

Code below (taken from my blog article - http://todayguesswhat.blogspot.com/2021/01/manually-verifying-rsa-sha-signature-in.html ) is hopefully helpful in understanding what is present in a standard SHA with RSA signature. This should work in standard Oracle JDK and does not require Bouncy Castle libraries. It is using the sun.security classes to process the decrypted signature contents - you could just as easily manually parse.

In the example below, the message digest algorithm is SHA-512 which produces a 64 byte (512-bit) checksum.

SHA-1 would be pretty similar - but producing a 20-byte (160-bit) checksum.

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

import java.util.Arrays;

import javax.crypto.Cipher;

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

public class RSASignatureVerification
{
    public static void main(String[] args) throws Exception
    {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);

        KeyPair keyPair = generator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        String data = "hello oracle";
        byte[] dataBytes = data.getBytes("UTF8");

        Signature signer = Signature.getInstance("SHA512withRSA");
        signer.initSign(privateKey);

        signer.update(dataBytes);

        byte[] signature = signer.sign(); // signature bytes of the signing operation's result.

        Signature verifier = Signature.getInstance("SHA512withRSA");
        verifier.initVerify(publicKey);
        verifier.update(dataBytes);

        boolean verified = verifier.verify(signature);
        if (verified)
        {
            System.out.println("Signature verified!");
        }

/*
    The statement that describes signing to be equivalent to RSA encrypting the
    hash of the message using the private key is a greatly simplified view
    The decrypted signatures bytes likely convey a structure (ASN.1) encoded
    using DER with the hash just one component of the structure.
*/

        // lets try decrypt signature and see what is in it ...
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] decryptedSignatureBytes = cipher.doFinal(signature);

/*
    sample value of decrypted signature which was 83 bytes long

    30 51 30 0D 06 09 60 86 48 01 65 03 04 02 03 05
    00 04 40 51 00 41 75 CA 3B 2B 6B C0 0A 3F 99 E3
    6B 7A 01 DC F2 9B 36 E6 0D D4 31 89 53 A3 D9 80
    6D AE DD 45 7E 55 45 01 FC C8 73 D2 DD 8D E5 B9
    E0 71 57 13 41 D0 CD FF CA 58 01 03 A3 DD 95 A1
    C1 EE C8

    Taking above sample bytes ...
    0x30 means A SEQUENCE - which contains an ordered field of one or more types.
    It is encoded into a TLV triplet that begins with a Tag byte of 0x30.
    DER uses T,L,V (tag bytes, length bytes, value bytes) format

    0x51 is the length = 81 decimal (13 bytes)

    the 0x30 (48 decimal) that follows begins a second sequence

    https://tools.ietf.org/html/rfc3447#page-43
    the DER encoding T of the DigestInfo value is equal to the following for SHA-512
    0D 06 09 60 86 48 01 65 03 04 02 03 05 00 04 40 || H
    where || is concatenation and H is the hash value.

    0x0D is the length = 13 decimal (13 bytes)

    0x06 means an OBJECT_ID tag
    0x09 means the object id is 9 bytes ...

    https://docs.microsoft.com/en-au/windows/win32/seccertenroll/about-object-identifier?redirectedfrom=MSDN

    taking 2.16.840.1.101.3.4.2.3 (object id for SHA512 Hash Algorithm)

    The first two nodes of the OID are encoded onto a single byte.
    The first node is multiplied by the decimal 40 and the result is added to the value of the second node
    2 * 40 + 16 = 96 decimal = 60 hex
    Node values less than or equal to 127 are encoded on one byte.
    1 101 3 4 2 3 corresponds to in hex 01 65 03 04 02 03
    Node values greater than or equal to 128 are encoded on multiple bytes.
    Bit 7 of the leftmost byte is set to one. Bits 0 through 6 of each byte contains the encoded value.
    840 decimal = 348 hex
    -> 0000 0011 0100 1000
    set bit 7 of the left most byte to 1, ignore bit 7 of the right most byte,
    shifting right nibble of leftmost byte to the left by 1 bit
    -> 1000 0110 X100 1000 in hex 86 48

    05 00          ; NULL (0 Bytes)

    04 40          ; OCTET STRING (0x40 Bytes = 64 bytes
    SHA512 produces a 512-bit (64-byte) hash value

    51 00 41 ... C1 EE C8 is the 64 byte hash value
*/

        // parse DER encoded data
        DerInputStream derReader = new DerInputStream(decryptedSignatureBytes);

        byte[] hashValueFromSignature = null;

        // obtain sequence of entities
        DerValue[] seq = derReader.getSequence(0);
        for (DerValue v : seq)
        {
            if (v.getTag() == 4)
            {
                hashValueFromSignature = v.getOctetString(); // SHA-512 checksum extracted from decrypted signature bytes
            }
        }

        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update(dataBytes);

        byte[] hashValueCalculated = md.digest();

        boolean manuallyVerified = Arrays.equals(hashValueFromSignature, hashValueCalculated);
        if (manuallyVerified)
        {
            System.out.println("Signature manually verified!");
        }
        else
        {
            System.out.println("Signature could NOT be manually verified!");
        }
    }
}

How to type ":" ("colon") in regexp?

use \\: instead of \:.. the \ has special meaning in java strings.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I had the same issue but the password was good and "Log on as batch job" alone was not sufficient.

Check that the IIS application pool identity account or group has both the "Log on as Batch Job" permission AND that it can "impersonate a client after authentication".

To change these settings perform the following steps on the web front end server:

  • Start>Run type "secpol.msc"
    • Find: Security Settings>Local Policies>User Rights assignment
    • Add user or group to "Log on as Batch Job"
    • Check group membership of service account (in Active Directory) if a particular group is being used for this purpose.
    • Find "impersonate a client after authentication" and add the application pool identity
    • Reboot the server

You should be able to access the site!

ng if with angular for string contains

ng-if="select.name.indexOf('?') !== -1" 

How to compile multiple java source files in command line

or you can use the following to compile the all java source files in current directory..

javac *.java

Conversion from List<T> to array T[]

Try using

MyClass[] myArray = list.ToArray();

How to filter multiple values (OR operation) in angularJS

I wrote this for strings AND functionality (I know it's not the question but I searched for it and got here), maybe it can be expanded.

String.prototype.contains = function(str) {
  return this.indexOf(str) != -1;
};

String.prototype.containsAll = function(strArray) {
  for (var i = 0; i < strArray.length; i++) {
    if (!this.contains(strArray[i])) {
      return false;
    }
  }
  return true;
}

app.filter('filterMultiple', function() {
  return function(items, filterDict) {
    return items.filter(function(item) {
      for (filterKey in filterDict) {
        if (filterDict[filterKey] instanceof Array) {
          if (!item[filterKey].containsAll(filterDict[filterKey])) {
            return false;
          }
        } else {
          if (!item[filterKey].contains(filterDict[filterKey])) {
            return false;
          }
        }
      }
      return true;
    });  
  };
});

Usage:

<li ng-repeat="x in array | filterMultiple:{key1: value1, key2:[value21, value22]}">{{x.name}}</li>

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

How to implement DrawerArrowToggle from Android appcompat v7 21 library

To answer the updated part of your question: to style the drawer icon/arrow, you have two options:

Style the arrow itself

To do this, override drawerArrowStyle in your theme like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/MyTheme.DrawerArrowToggle</item>
</style>
<style name="MyTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/holo_purple</item>
    <!-- ^ this will make the icon purple -->
</style>

This is probably not what you want, because the ActionBar itself should have consistent styling with the arrow, so, most probably, you want the option two:

Theme the ActionBar/Toolbar

Override the android:actionBarTheme (actionBarTheme for appcompat) attribute of the global application theme with your own theme (which you probably should derive from ThemeOverlay.Material.ActionBar/ThemeOverlay.AppCompat.ActionBar) like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarTheme">@style/MyTheme.ActionBar</item>
</style>
<style name="MyTheme.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:textColorPrimary">@android:color/white</item>
    <!-- ^ this will make text and arrow white -->
    <!-- you can also override drawerArrowStyle here -->
</style>

An important note here is that when using a custom layout with a Toolbar instead of stock ActionBar implementation (e.g. if you're using the DrawerLayout-NavigationView-Toolbar combo to achieve the Material-style drawer effect where it's visible under translucent statusbar), the actionBarTheme attribute is obviosly not picked up automatically (because it's meant to be taken care of by the AppCompatActivity for the default ActionBar), so for your custom Toolbar don't forget to apply your theme manually:

<!--inside your custom layout with DrawerLayout
and NavigationView or whatever -->
<android.support.v7.widget.Toolbar
        ...
        app:theme="?actionBarTheme">

-- this will resolve to either AppCompat's default ThemeOverlay.AppCompat.ActionBar or your override if you set the attribute in your derived theme.

PS a little comment about the drawerArrowStyle override and the spinBars attribute -- which a lot of sources suggest should be set to true to get the drawer/arrow animation. Thing is, spinBars it is true by default in AppCompat (check out the Base.Widget.AppCompat.DrawerArrowToggle.Common style), you don't have to override actionBarTheme at all to get the animation working. You get the animation even if you do override it and set the attribute to false, it's just a different, less twirly animation. The important thing here is to use ActionBarDrawerToggle, it's what pulls in the fancy animated drawable.

How to save a Seaborn plot into a file

Fewer lines for 2019 searchers:

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
plt.savefig('output.png')

UPDATE NOTE: size was changed to height.

Is there a way to check for both `null` and `undefined`?

Late to join this thread but I find this JavaScript hack very handy in checking whether a value is undefined

 if(typeof(something) === 'undefined'){
   // Yes this is undefined
 }

delete_all vs destroy_all?

To avoid the fact that destroy_all instantiates all the records and destroys them one at a time, you can use it directly from the model class.

So instead of :

u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all

You can do :

u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"

The result is one query to destroy all the associated records

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

Uncaught TypeError: .indexOf is not a function

Convert timeofday to string to use indexOf

var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
console.log(typeof(timeofday)) // for testing will log number
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
    var pos = time.indexOf('.');
    var hrs = time.substr(1, pos - 1);
    var min = (time.substr(pos, 2)) * 60;

    if (hrs > 11) {
        hrs = (hrs - 12) + ":" + min + " PM";
    } else {
        hrs += ":" + min + " AM";
    }
    return hrs;
}
 // "" for typecasting to string
 document.getElementById("oset").innerHTML = timeD2C(""+timeofday);

Test Here

Solution 2

use toString() to convert to string

document.getElementById("oset").innerHTML = timeD2C(timeofday.toString());

jsfiddle with toString()

Change GridView row color based on condition

\\loop throgh all rows of the grid view  

if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value1")
{
   GridView1.Rows[i - 1].ForeColor = Color.Black;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value2")
{
   GridView1.Rows[i - 1].ForeColor = Color.Blue;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value3")
{
   GridView1.Rows[i - 1].ForeColor = Color.Red;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value4")
{
   GridView1.Rows[i - 1].ForeColor = Color.Green;
}

jquery datatables hide column

Note: the accepted solution is now outdated and part of legacy code. http://legacy.datatables.net/ref The solutions might not be appropriate for those working with the newer versions of DataTables (its legacy now) For the newer solution: you could use: https://datatables.net/reference/api/columns().visible()

alternatives you could implement a button: https://datatables.net/extensions/buttons/built-in look at the last option under the link provided that allows having a button that could toggle column visibility.

How to show x and y axes in a MATLAB graph?

Inspired by @Luisa's answer, I made a function, axes0

x = linspace(-2,2,101);
plot(x,2*x.^3-3*x+1);
axes0

Example output for axes0

You can follow the link above to download the function and get more details on usage

Efficient way to return a std::vector in c++

You should return by value.

The standard has a specific feature to improve the efficiency of returning by value. It's called "copy elision", and more specifically in this case the "named return value optimization (NRVO)".

Compilers don't have to implement it, but then again compilers don't have to implement function inlining (or perform any optimization at all). But the performance of the standard libraries can be pretty poor if compilers don't optimize, and all serious compilers implement inlining and NRVO (and other optimizations).

When NRVO is applied, there will be no copying in the following code:

std::vector<int> f() {
    std::vector<int> result;
    ... populate the vector ...
    return result;
}

std::vector<int> myvec = f();

But the user might want to do this:

std::vector<int> myvec;
... some time later ...
myvec = f();

Copy elision does not prevent a copy here because it's an assignment rather than an initialization. However, you should still return by value. In C++11, the assignment is optimized by something different, called "move semantics". In C++03, the above code does cause a copy, and although in theory an optimizer might be able to avoid it, in practice its too difficult. So instead of myvec = f(), in C++03 you should write this:

std::vector<int> myvec;
... some time later ...
f().swap(myvec);

There is another option, which is to offer a more flexible interface to the user:

template <typename OutputIterator> void f(OutputIterator it) {
    ... write elements to the iterator like this ...
    *it++ = 0;
    *it++ = 1;
}

You can then also support the existing vector-based interface on top of that:

std::vector<int> f() {
    std::vector<int> result;
    f(std::back_inserter(result));
    return result;
}

This might be less efficient than your existing code, if your existing code uses reserve() in a way more complex than just a fixed amount up front. But if your existing code basically calls push_back on the vector repeatedly, then this template-based code ought to be as good.

Key hash for Android-Facebook app

I've created a small tool for Windows and Mac OS X. Just throw in the key-store file, and get the hash key.

If you want the default debug.keystore file, use the default alias and password. Else, use your own keystore file and values.

Check it out, download the Windows version or download the Mac OS X version (Dev-Host might be down sometimes... so if the link is broken, PM me and I'll fix it).

I hope that help you guys...

Dec 31, 2014 - EDIT: Changed host to AFH. Please let me know if the links are broken

Nov 21, 2013 - EDIT:

As users requested, I added a default keystore location and a DONATE button. Feel free to use it if I've helped you. :)

Screen shot Screen shot 2

How to make CSS3 rounded corners hide overflow in Chrome/Opera

Here look at how I done it; Jsfiddle

With the Code I put in, I managed to get it working on Webkit (Chrome/Safari) and Firefox. I don't know if it works with the latest version of Opera. Yes it does work under the latest version of Opera.

#wrapper {
  width: 300px; height: 300px;
  border-radius: 100px;
  overflow: hidden;
  position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */
}

#box {
  width: 300px; height: 300px;
  background-color: #cde;
  border-radius: 100px;
  -webkit-border-radius: 100px;
  -moz-border-radius: 100px;
  -o-border-radius: 100px;
}

How do I get a HttpServletRequest in my spring beans?

Better way is to autowire with a constructor:

private final HttpServletRequest httpServletRequest;

public ClassConstructor(HttpServletRequest httpServletRequest){
      this.httpServletRequest = httpServletRequest;
}

lvalue required as left operand of assignment

You are trying to assign a value to a function, which is not possible in C. Try the comparison operator instead:

if (strcmp("hello", "hello") == 0)

What is newline character -- '\n'

NewLine (\n) is 10 (0xA) and CarriageReturn (\r) is 13 (0xD).

Different operating systems picked different end of line representations for files. Windows uses CRLF (\r\n). Unix uses LF (\n). Older Mac OS versions use CR (\r), but OS X switched to the Unix character.

Here is a relatively useful FAQ.

How do I associate file types with an iPhone application?

To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:

    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>IPA</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>public.item</string>
                <string>public.content</string>
                <string>public.data</string>
                <string>public.database</string>
                <string>public.composite-content</string>
                <string>public.contact</string>
                <string>public.archive</string>
                <string>public.url-name</string>
                <string>public.text</string>
                <string>public.plain-text</string>
                <string>public.source-code</string>
                <string>public.executable</string>
                <string>public.script</string>
                <string>public.shell-script</string>
                <string>public.xml</string>
                <string>public.symlink</string>
                <string>org.gnu.gnu-zip-archve</string>
                <string>org.gnu.gnu-tar-archive</string>
                <string>public.image</string>
                <string>public.movie</string>
                <string>public.audiovisual-?content</string>
                <string>public.audio</string>
                <string>public.directory</string>
                <string>public.folder</string>
                <string>com.apple.bundle</string>
                <string>com.apple.package</string>
                <string>com.apple.plugin</string>
                <string>com.apple.application-?bundle</string>
                <string>com.pkware.zip-archive</string>
                <string>public.filename-extension</string>
                <string>public.mime-type</string>
                <string>com.apple.ostype</string>
                <string>com.apple.nspboard-typ</string>
                <string>com.adobe.pdf</string>
                <string>com.adobe.postscript</string>
                <string>com.adobe.encapsulated-?postscript</string>
                <string>com.adobe.photoshop-?image</string>
                <string>com.adobe.illustrator.ai-?image</string>
                <string>com.compuserve.gif</string>
                <string>com.microsoft.word.doc</string>
                <string>com.microsoft.excel.xls</string>
                <string>com.microsoft.powerpoint.?ppt</string>
                <string>com.microsoft.waveform-?audio</string>
                <string>com.microsoft.advanced-?systems-format</string>
                <string>com.microsoft.advanced-?stream-redirector</string>
                <string>com.microsoft.windows-?media-wmv</string>
                <string>com.microsoft.windows-?media-wmp</string>
                <string>com.microsoft.windows-?media-wma</string>
                <string>com.apple.keynote.key</string>
                <string>com.apple.keynote.kth</string>
                <string>com.truevision.tga-image</string>
            </array>
            <key>CFBundleTypeIconFiles</key>
            <array>
                <string>Icon-76@2x</string>
            </array>
        </dict>
    </array>

A warning - comparison between signed and unsigned integer expressions

It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).

Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:

unsigned u = GetSomeUnsignedValue();
int i = GetSomeSignedValue();

if (i >= 0)
{
    // i is nonnegative, so it is safe to cast to unsigned value
    if ((unsigned)i >= u)
        iIsGreaterThanOrEqualToU();
    else
        iIsLessThanU();
}
else
{
    iIsNegative();
}

How to hide code from cells in ipython notebook visualized with nbviewer?

I would use hide_input_all from nbextensions (https://github.com/ipython-contrib/IPython-notebook-extensions). Here's how:

  1. Find out where your IPython directory is:

    from IPython.utils.path import get_ipython_dir
    print get_ipython_dir()
    
  2. Download nbextensions and move it to the IPython directory.

  3. Edit your custom.js file somewhere in the IPython directory (mine was in profile_default/static/custom) to be similar to the custom.example.js in the nbextensions directory.

  4. Add this line to custom.js:

    IPython.load_extensions('usability/hide_input_all')
    

IPython Notebook will now have a button to toggle code cells, no matter the workbook.

Google Chromecast sender error if Chromecast extension is not installed or using incognito

i know it is not the best solution, but the only one supposed solution that i have read for all the web is to install chrome cast extension, so, i've decide, not to put the iframe into the website, i just insert the thumnail of my video from youtube like in this post explain.

and here we have two options:
1) Target the video to the channel and play it there
2) Call the video via ajax, like explain here (i've decided for this one) in a colorbox or any another plugin.

and like this, i prevent the google cast sender error make my site slow

Import an existing git project into GitLab?

Here are the steps provided by the Gitlab:

cd existing_repo
git remote rename origin old-origin
git remote add origin https://gitlab.example.com/rmishra/demoapp.git
git push -u origin --all
git push -u origin --tags

How to insert strings containing slashes with sed?

The easiest way would be to use a different delimiter in your search/replace lines, e.g.:

s:?page=one&:pageone:g

You can use any character as a delimiter that's not part of either string. Or, you could escape it with a backslash:

s/\//foo/

Which would replace / with foo. You'd want to use the escaped backslash in cases where you don't know what characters might occur in the replacement strings (if they are shell variables, for example).

Why are the Level.FINE logging messages not showing?

WHY

As mentioned by @Sheepy, the reason why it doesn't work is that java.util.logging.Logger has a root logger that defaults to Level.INFO, and the ConsoleHandler attached to that root logger also defaults to Level.INFO. Therefore, in order to see the FINE (, FINER or FINEST) output, you need to set the default value of the root logger and its ConsoleHandler to Level.FINE as follows:

Logger.getLogger("").setLevel(Level.FINE);
Logger.getLogger("").getHandlers()[0].setLevel(Level.FINE);


The problem of your Update (solution)

As mentioned by @mins, you will have the messages printed twice on the console for INFO and above: first by the anonymous logger, then by its parent, the root logger which also has a ConsoleHandler set to INFO by default. To disable the root logger, you need to add this line of code: logger.setUseParentHandlers(false);

There are other ways to prevent logs from being processed by default Console handler of the root logger mentioned by @Sheepy, e.g.:

Logger.getLogger("").getHandlers()[0].setLevel( Level.OFF );

But Logger.getLogger("").setLevel( Level.OFF ); won't work because it only blocks the message passed directly to the root logger, not the message comes from a child logger. To illustrate how the Logger Hierarchy works, I draw the following diagram:

enter image description here

public void setLevel(Level newLevel) set the log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded. The level value Level.OFF can be used to turn off logging. If the new level is null, it means that this node should inherit its level from its nearest ancestor with a specific (non-null) level value.

How to auto adjust the div size for all mobile / tablet display formats?

This is called Responsive Web Development(RWD). To make page responsive to all device we need to use some basic fundamental such as:-

1. Set the viewport meta tag in head:

<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0"/>

2.Use media queries.

Example:-

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

3. Or we can directly use RWD framework:-

Some of good Article

Media Queries for Standard Devices - BY CHRIS COYIER

CSS Media Dimensions

4. Larger Device, Medium Devices & Small Devices media queries. (Work in my Scenarios.)

Below media queries for generic Device type: - Larger Device, Medium Devices & Small Devices. This is just basic media types which work for all of scenario & easy to handle code instead of using various media queries just need to care of three media type.

/*###Desktops, big landscape tablets and laptops(Large, Extra large)####*/
@media screen and (min-width: 1024px){
/*Style*/
}

/*###Tablet(medium)###*/
@media screen and (min-width : 768px) and (max-width : 1023px){
/*Style*/
}

/*### Smartphones (portrait and landscape)(small)### */
@media screen and (min-width : 0px) and (max-width : 767px){
/*Style*/
}

Return rows in random order

Here's an example (source):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);

.prop() vs .attr()

I think Tim said it quite well, but let's step back:

A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values from attributes with the same or similar names (value gets its initial value from the "value" attribute; href gets its initial value from the "href" attribute, but it's not exactly the same value; className from the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNode property gets its value based on what its parent element is; an element always has a style property, whether it has a "style" attribute or not.

Let's consider this anchor in a page at http://example.com/testing.html:

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>

Some gratuitous ASCII art (and leaving out a lot of stuff):

+-------------------------------------------+
|             HTMLAnchorElement             |
+-------------------------------------------+
| href:       "http://example.com/foo.html" |
| name:       "fooAnchor"                   |
| id:         "fooAnchor"                   |
| className:  "test one"                    |
| attributes:                               |
|    href:  "foo.html"                      |
|    name:  "fooAnchor"                     |
|    id:    "fooAnchor"                     |
|    class: "test one"                      |
+-------------------------------------------+

Note that the properties and attributes are distinct.

Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if you set them. But not all do, and as you can see from href above, the mapping is not always a straight "pass the value on", sometimes there's interpretation involved.

When I talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:

var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"

(Those values are as per most browsers; there's some variation.)

The link object is a real thing, and you can see there's a real distinction between accessing a property on it, and accessing an attribute.

As Tim said, the vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with href and "href" above).

The standard properties are laid out in the various DOM specs:

These specs have excellent indexes and I recommend keeping links to them handy; I use them all the time.

Custom attributes would include, for instance, any data-xyz attributes you might put on elements to provide meta-data to your code (now that that's valid as of HTML5, as long as you stick to the data- prefix). (Recent versions of jQuery give you access to data-xyz elements via the data function, but that function is not just an accessor for data-xyz attributes [it does both more and less than that]; unless you actually need its features, I'd use the attr function to interact with data-xyz attribute.)

The attr function used to have some convoluted logic around getting what they thought you wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop and attr was meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added back to attr to handle the common situations where people use attr when technically they should use prop.

Excel formula to get ranking position

The way I've done this, which is a bit convoluted, is as follows:

  1. Sort rows by the points in descending order
  2. Create an additional column (D) starting at D2 with numbers 1,2,3,... total number of positions
  3. In the cell for the actual positions (D2) use the formula if(C2=C1), D2, C1). This checks if the points in this row are the same as the points in the previous row. If it is it gives you the position of the previous row, otherwise it uses the value from column D and thus handle people with equal positions.
  4. Copy this formula down the entire column
  5. Copy the positions column(C), then paste special >> values to overwrite the formula with positions
  6. Resort the rows to their original order

That's worked for me! If there's a better way I'd love to know it!

Run command on the Ansible host

I've found a couple other ways you can write these which are a bit more readable IMHO.

- name: check out a git repository
  local_action: 
    module: git
    repo: git://foosball.example.org/path/to/repo.git
    dest: /local/path

OR

- name: check out a git repository
  local_action: git
  args:
    repo: git://foosball.example.org/path/to/repo.git
    dest: /local/path

How To Save Canvas As An Image With canvas.toDataURL()?

You cannot use the methods previously mentioned to download an image when running in Cordova. You will need to use the Cordova File Plugin. This will allow you to pick where to save it and leverage different persistence settings. Details here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Alternatively, you can convert the image to base64 then store the string in localStorage but this will fill your quota pretty quickly if you have many images or high-res.

How to get all groups that a user is a member of?

If you cannot get Get-ADPrincipalGroupMembership to work for you could try logging in as that user then use.

$id = [Security.Principal.WindowsIdentity]::GetCurrent()
$groups = $id.Groups | foreach-object {$_.Translate([Security.Principal.NTAccount])}
$groups | select *

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I had a similar problem when I had installed the 12c database as per Oracle's tutorial . The instruction instructs reader to create a PLUGGABLE DATABASE (pdb).

The problem

sqlplus hr/hr@pdborcl would result in ORACLE initialization or shutdown in progress.

The solution

    1. Login as SYSDBA to the dabase :

      sqlplus SYS/Oracle_1@pdborcl AS SYSDBA
      
    1. Alter database:

      alter pluggable database pdborcl open read write;
      
    1. Login again:

      sqlplus hr/hr@pdborcl
      

That worked for me

Some documentation here

Resizable table columns with jQuery

I tried to add to @user686605's work:

1) changed the cursor to col-resize at the th border

2) fixed the highlight text issue when resizing

I partially succeeded at both. Maybe someone who is better at CSS can help move this forward?

http://jsfiddle.net/telefonica/L2f7F/4/

HTML

<!--Click on th and drag...-->
<table>
    <thead>
        <tr>
            <th><div class="noCrsr">th 1</div></th>
            <th><div class="noCrsr">th 2</div></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>td 1</td>
            <td>td 2</td>
        </tr>
    </tbody>
</table>

JS

$(function() {
    var pressed = false;
    var start = undefined;
    var startX, startWidth;

    $("table th").mousedown(function(e) {
        start = $(this);
        pressed = true;
        startX = e.pageX;
        startWidth = $(this).width();
        $(start).addClass("resizing");
        $(start).addClass("noSelect");
    });

    $(document).mousemove(function(e) {
        if(pressed) {
            $(start).width(startWidth+(e.pageX-startX));
        }
    });

    $(document).mouseup(function() {
        if(pressed) {
            $(start).removeClass("resizing");
            $(start).removeClass("noSelect");
            pressed = false;
        }
    });
});

CSS

table {
    border-width: 1px;
    border-style: solid;
    border-color: black;
    border-collapse: collapse;
}

table td {
    border-width: 1px;
    border-style: solid;
    border-color: black;
}

table th {
    border: 1px;
    border-style: solid;
    border-color: black;
    background-color: green;
    cursor: col-resize;
}

table th.resizing {
    cursor: col-resize;
}

.noCrsr {
    cursor: default;
    margin-right: +5px;
}

.noSelect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

How to pass a form input value into a JavaScript function

Give your inputs names it will make it easier

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>

UPDATE:

If you give your button an id things can be even easier:

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>

Javascript:

var button = document.getElementById("theButton"),
value =  button.form.valueId.value;
button.onclick = function() {
    foo(value);
}

Convert PDF to PNG using ImageMagick

when you set the density to 96, doesn't it look good?

when i tried it i saw that saving as jpg resulted with better quality, but larger file size

C# how to create a Guid value?

There's also ShortGuid - A shorter and url friendly GUID class in C#. It's available as a Nuget. More information here.

PM> Install-Package CSharpVitamins.ShortGuid

Usage:

Guid guid = Guid.NewGuid();
ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid
Console.WriteLine(sguid1);
Console.WriteLine(sguid1.Guid);

This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:

ShortGuid: FEx1sZbSD0ugmgMAF_RGHw 
Guid:      b1754c14-d296-4b0f-a09a-030017f4461f

Finding current executable's path without /proc/self/exe

The whereami library by Gregory Pakosz implements this for a variety of platforms, using the APIs mentioned in mark4o's post. This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms.

At the time of writing, supported platforms are:

  • Windows
  • Linux
  • Mac
  • iOS
  • Android
  • QNX Neutrino
  • FreeBSD
  • NetBSD
  • DragonFly BSD
  • SunOS

The library consists of whereami.c and whereami.h and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it:

#include "whereami.h"

int main() {
  int length = wai_getExecutablePath(NULL, 0, NULL);
  char* path = (char*)malloc(length + 1);
  wai_getExecutablePath(path, length, &dirname_length);
  path[length] = '\0';

  printf("My path: %s", path);

  free(path);
  return 0;
}

How to make a simple image upload using Javascript/HTML

<li class="list-group-item active"><h5>Feaured Image</h5></li>
            <li class="list-group-item">
                <div class="input-group mb-3">
                    <div class="custom-file ">
                        <input type="file"  class="custom-file-input" name="thumbnail" id="thumbnail">
                        <label class="custom-file-label" for="thumbnail">Choose file</label>
                    </div>
                </div>
                <div class="img-thumbnail  text-center">
                    <img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
                </div>
            </li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
    var file = $(this).get(0).files;
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.addEventListener("load", function(e) {
    var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>

MySQL Query GROUP BY day / month / year

If you want to filter records for a particular year (e.g. 2000) then optimize the WHERE clause like this:

SELECT MONTH(date_column), COUNT(*)
FROM date_table
WHERE date_column >= '2000-01-01' AND date_column < '2001-01-01'
GROUP BY MONTH(date_column)
-- average 0.016 sec.

Instead of:

WHERE YEAR(date_column) = 2000
-- average 0.132 sec.

The results were generated against a table containing 300k rows and index on date column.

As for the GROUP BY clause, I tested the three variants against the above mentioned table; here are the results:

SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
FROM date_table
GROUP BY YEAR(date_column), MONTH(date_column)
-- codelogic
-- average 0.250 sec.

SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
FROM date_table
GROUP BY DATE_FORMAT(date_column, '%Y%m')
-- Andriy M
-- average 0.468 sec.

SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
FROM date_table
GROUP BY EXTRACT(YEAR_MONTH FROM date_column)
-- fu-chi
-- average 0.203 sec.

The last one is the winner.

Can I force a UITableView to hide the separator between empty cells?

You can achieve what you want by defining a footer for the tableview. See this answer for more details:Eliminate Extra separators below UITableView

Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);

Rails: How to list database tables/objects using the Rails console?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db. Both commands will direct you the command line interface and will allow you to use that database query syntax.

How do I import a Swift file from another Swift file?

So, you need to

  1. Import external modules you want to use
  2. And make sure you have the right access modifiers on the class and methods you want to use.

In my case I had a swift file I wanted to unit test, and the unit test file was also a swift class. I made sure the access modifiers were correct, but the statement

import stMobile

(let's say that stMobile is our target name)

still did not work (I was still getting the 'No such module' error), I checked my target, and its name was indeed stMobile. So, I went to Build Settings, under packaging, and found the Product Module Name, and for some reason this was called St_Mobile, so I changed my import statement

import St_Mobile

(which is the Product Module Name), and everything worked.

So, to sum up:

  1. Check your Product Module Name and use the import statement below in you unit test class

    import myProductModuleName
    
  2. Make sure your access modifiers are correct (class level and your methods).

Calculating Pearson correlation and significance in Python

Here's a variant on mkh's answer that runs much faster than it, and scipy.stats.pearsonr, using numba.

import numba

@numba.jit
def corr(data1, data2):
    M = data1.size

    sum1 = 0.
    sum2 = 0.
    for i in range(M):
        sum1 += data1[i]
        sum2 += data2[i]
    mean1 = sum1 / M
    mean2 = sum2 / M

    var_sum1 = 0.
    var_sum2 = 0.
    cross_sum = 0.
    for i in range(M):
        var_sum1 += (data1[i] - mean1) ** 2
        var_sum2 += (data2[i] - mean2) ** 2
        cross_sum += (data1[i] * data2[i])

    std1 = (var_sum1 / M) ** .5
    std2 = (var_sum2 / M) ** .5
    cross_mean = cross_sum / M

    return (cross_mean - mean1 * mean2) / (std1 * std2)

Laravel Eloquent limit and offset

Laravel 8 (This is worked for the version 7.16)

$art->products->skip($offset*$limit)->take($limit)->all();

https://laravel.com/docs/8.x/collections#method-take

Android Studio AVD - Emulator: Process finished with exit code 1

Check android studio event log as it could be low storage issue.

emulator: ERROR: Not enough disk space to run AVD 'Nexus_5_API_21'. Exiting...

How do I purge a linux mail box with huge number of emails?

You can simply delete the /var/mail/username file to delete all emails for a specific user. Also, emails that are outgoing but have not yet been sent will be stored in /var/spool/mqueue.

How to pass a JSON array as a parameter in URL

I encountered the same need and make a universal solution (node+browser) that works with the Next.js framework, for instance.

It even works with circular dependencies (thanks to json-stringify-safe).

Although, I also built a serializer on top of it to remove unnecessary data (because it's not recommended to use a url longer than 2k chars, see What is the maximum length of a URL in different browsers?)

import StringifySafe from 'json-stringify-safe';

export const encodeQueryParameter = (data: object): string => {
  return encodeURIComponent(StringifySafe(data)); // Use StringifySafe to avoid crash on circular dependencies
};

export const decodeQueryParameter = (query: string): object => {
  return JSON.parse(decodeURIComponent(query));
};

And the unit tests (jest):

import { decodeQueryParameter, encodeQueryParameter } from './url';

export const data = {
  'organisation': {
    'logo': {
      'id': 'ck2xjm2oj9lr60b32c6l465vx',
      'linkUrl': null,
      'linkTarget': '_blank',
      'classes': null,
      'style': null,
      'defaultTransformations': { 'width': 200, 'height': 200, '__typename': 'AssetTransformations' },
      'mimeType': 'image/png',
      '__typename': 'Asset',
    },
    'theme': {
      'primaryColor': '#1134e6',
      'primaryAltColor': '#203a51',
      'secondaryColor': 'white',
      'font': 'neuzeit-grotesk',
      '__typename': 'Theme',
      'primaryColorG1': '#ffffff',
    },
  },
};
export const encodedData = '%7B%22organisation%22%3A%7B%22logo%22%3A%7B%22id%22%3A%22ck2xjm2oj9lr60b32c6l465vx%22%2C%22linkUrl%22%3Anull%2C%22linkTarget%22%3A%22_blank%22%2C%22classes%22%3Anull%2C%22style%22%3Anull%2C%22defaultTransformations%22%3A%7B%22width%22%3A200%2C%22height%22%3A200%2C%22__typename%22%3A%22AssetTransformations%22%7D%2C%22mimeType%22%3A%22image%2Fpng%22%2C%22__typename%22%3A%22Asset%22%7D%2C%22theme%22%3A%7B%22primaryColor%22%3A%22%231134e6%22%2C%22primaryAltColor%22%3A%22%23203a51%22%2C%22secondaryColor%22%3A%22white%22%2C%22font%22%3A%22neuzeit-grotesk%22%2C%22__typename%22%3A%22Theme%22%2C%22primaryColorG1%22%3A%22%23ffffff%22%7D%7D%7D';

describe(`utils/url.ts`, () => {
  describe(`encodeQueryParameter`, () => {
    test(`should encode a JS object into a url-compatible string`, async () => {
      expect(encodeQueryParameter(data)).toEqual(encodedData);
    });
  });

  describe(`decodeQueryParameter`, () => {
    test(`should decode a url-compatible string into a JS object`, async () => {
      expect(decodeQueryParameter(encodedData)).toEqual(data);
    });
  });

  describe(`encodeQueryParameter <> decodeQueryParameter <> encodeQueryParameter`, () => {
    test(`should encode and decode multiple times without altering data`, async () => {
      const _decodedData: object = decodeQueryParameter(encodedData);
      expect(_decodedData).toEqual(data);

      const _encodedData: string = encodeQueryParameter(_decodedData);
      expect(_encodedData).toEqual(encodedData);

      const _decodedDataAgain: object = decodeQueryParameter(_encodedData);
      expect(_decodedDataAgain).toEqual(data);
    });
  });
});

Detect rotation of Android phone in the browser with JavaScript

two-bit-fool's excellent answer provides all the background, but let me attempt a concise, pragmatic summary of how to handle orientation changes across iOS and Android:

  • If you only care about window dimensions (the typical scenario) - and not about the specific orientation:
    • Handle the resize event only.
    • In your handler, act on window.innerWidth and window.InnerHeight only.
    • Do NOT use window.orientation - it won't be current on iOS.
  • If you DO care about the specific orientation:
    • Handle only the resize event on Android, and only the orientationchange event on iOS.
    • In your handler, act on window.orientation (and window.innerWidth and window.InnerHeight)

These approaches offer slight benefits over remembering the previous orientation and comparing:

  • the dimensions-only approach also works while developing on desktop browsers that can otherwise simulate mobile devices, e.g., Chrome 23. (window.orientation is not available on desktop browsers).
  • no need for a global/anonymous-file-level-function-wrapper-level variable.

Java: Calling a super method which calls an overridden method

Further more extended the output of the raised question, this will give more insight on the access specifier and override behavior.

            package overridefunction;
            public class SuperClass 
                {
                public void method1()
                {
                    System.out.println("superclass method1");
                    this.method2();
                    this.method3();
                    this.method4();
                    this.method5();
                }
                public void method2()
                {
                    System.out.println("superclass method2");
                }
                private void method3()
                {
                    System.out.println("superclass method3");
                }
                protected void method4()
                {
                    System.out.println("superclass method4");
                }
                void method5()
                {
                    System.out.println("superclass method5");
                }
            }

            package overridefunction;
            public class SubClass extends SuperClass
            {
                @Override
                public void method1()
                {
                    System.out.println("subclass method1");
                    super.method1();
                }
                @Override
                public void method2()
                {
                    System.out.println("subclass method2");
                }
                // @Override
                private void method3()
                {
                    System.out.println("subclass method3");
                }
                @Override
                protected void method4()
                {
                    System.out.println("subclass method4");
                }
                @Override
                void method5()
                {
                    System.out.println("subclass method5");
                }
            }

            package overridefunction;
            public class Demo 
            {
                public static void main(String[] args) 
                {
                    SubClass mSubClass = new SubClass();
                    mSubClass.method1();
                }
            }

            subclass method1
            superclass method1
            subclass method2
            superclass method3
            subclass method4
            subclass method5

Retrieve last 100 lines logs

You can simply use the following command:-

tail -NUMBER_OF_LINES FILE_NAME

e.g tail -100 test.log

  • will fetch the last 100 lines from test.log

In case, if you want the output of the above in a separate file then you can pipes as follows:-

tail -NUMBER_OF_LINES FILE_NAME > OUTPUT_FILE_NAME

e.g tail -100 test.log > output.log

  • will fetch the last 100 lines from test.log and store them into a new file output.log)

Vertically center text in a 100% height div?

This answer is no longer the best answer ... see the flexbox answer below instead!


To get it perfectly centered (as mentioned in david's answer) you need to add a negative top margin. If you know (or force) there to only be a single line of text, you can use:

margin-top: -0.5em;

for example:

http://jsfiddle.net/45MHk/623/

//CSS:
html, body, div {
    height: 100%;
}

#parent
{
    position:relative;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
    /* adjust top up half the height of a single line */
    margin-top: -0.5em;
    /* force content to always be a single line */
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
    text-overflow: ellipsis;
}

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>?

The originally accepted answer will not vertically center on the middle of the text (it centers based on the top of the text). So, if you parent is not very tall, it will not look centered at all, for example:

http://jsfiddle.net/45MHk/

//CSS:
#parent
{
    position:relative;
    height: 3em;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
}? 

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>?

"inconsistent use of tabs and spaces in indentation"

Using the autopep8 command below fixed it for me:

 autopep8 -i my_file.py

Documentation for autopep8 linked here.

Trying to add adb to PATH variable OSX

Add to PATH for every login

Total control version:

in your terminal, navigate to home directory

cd

create file .bash_profile

touch .bash_profile

open file with TextEdit

open -e .bash_profile

insert line into TextEdit

export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/

save file and reload file

source ~/.bash_profile

check if adb was set into path

adb version


One liner version

Echo your export command and redirect the output to be appended to .bash_profile file and restart terminal. (have not verified this but should work)

echo "export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/ sdk/platform-tools/" >> ~/.bash_profile

Do I really need to encode '&' as '&amp;'?

if & is used in html then you should escape it

If & is used in javascript strings e.g. an alert('This & that'); or document.href you don't need to use it.

If you're using document.write then you should use it e.g. document.write(<p>this &amp; that</p>)

Getting only response header from HTTP POST using curl

For long response bodies (and various other similar situations), the solution I use is always to pipe to less, so

curl -i https://api.github.com/users | less

or

curl -s -D - https://api.github.com/users | less

will do the job.

C# switch statement limitations - why?

C# 8 allows you to solve this problem elegantly and compactly using an switch expression:

public string GetTypeName(object obj)
{
    return obj switch
    {
        int i => "Int32",
        string s => "String",
        { } => "Unknown",
        _ => throw new ArgumentNullException(nameof(obj))
    };
}

As a result, you get:

Console.WriteLine(GetTypeName(obj: 1));           // Int32
Console.WriteLine(GetTypeName(obj: "string"));    // String
Console.WriteLine(GetTypeName(obj: 1.2));         // Unknown
Console.WriteLine(GetTypeName(obj: null));        // System.ArgumentNullException

You can read more about the new feature here.

how do you increase the height of an html textbox

Note that if you want a multi line text box you have to use a <textarea> instead of an <input type="text">.

Get data from JSON file with PHP

Get the content of the JSON file using file_get_contents():

$str = file_get_contents('http://example.com/example.json/');

Now decode the JSON using json_decode():

$json = json_decode($str, true); // decode the JSON into an associative array

You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:

echo '<pre>' . print_r($json, true) . '</pre>';

This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

Or loop through the array however you wish:

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

Demo!

Xcode 4: create IPA file instead of .xcarchive

For Xcode 4.6 (and Xcode 5) archives

  • In Organizer, right-click an archive, select Show in Finder
  • In Finder, right-click an archive, select Show Package Contents
  • Open the folder Products > Applications
  • The application is there
  • Drag the application into iTunes Apps folder

    enter image description here

  • Right-click on the application in iTunes Apps, select Show in Finder

  • The .ipa is there!

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

Unable to merge dex

./gradlew :app:assembleStubLiveDebug -debug -stacktrace

Or similar (get the task name (:app:assembleStubLiveDebug) from Android Studio).

How to make a background 20% transparent on Android

Use the below code for black:

<color name="black">#000000</color>

Now if I want to use opacity then you can use the below code:

 <color name="black">#99000000</color> <!-- 99 is for alpha and others pairs zero's are for R G B -->

And below for opacity code: and all opacity level here

Hex Opacity Values

100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

If you always to forget what code for transparency then you must have to see below link and no worry about to remember anything regarding transparent code :-

https://github.com/duggu-hcd/TransparentColorCode

textviewHeader.setTextColor(Color.parseColor(ColorTransparentUtils.transparentColor(R.color.border_color,10)));

Basic http file downloading and saving to disk in python?

Another clean way to save the file is this:

import csv
import urllib

urllib.retrieve("your url goes here" , "output.csv")

Remove carriage return from string

You can also try:

string res = string.Join("", sample.Split(Environment.NewLine.ToCharArray())

Environment.NewLine should make it independent of platform.

Recommended Read:

Environment.NewLine Property

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

RestTemplate: How to send URL and query parameters together

One-liner using TestRestTemplate.exchange function with parameters map.

restTemplate.exchange("/someUrl?id={id}", HttpMethod.GET, reqEntity, respType, ["id": id])

The params map initialized like this is a groovy initializer*

What is this Javascript "require"?

I noticed that whilst the other answers explained what require is and that it is used to load modules in Node they did not give a full reply on how to load node modules when working in the Browser.

It is quite simple to do. Install your module using npm as you describe, and the module itself will be located in a folder usually called node_modules.

Now the simplest way to load it into your app is to reference it from your html with a script tag which points at this directory. i.e if your node_modules directory is in the root of the project at the same level as your index.html you would write this in your index.html:

<script src="node_modules/ng"></script>

That whole script will now be loaded into the page - so you can access its variables and methods directly.

There are other approaches which are more widely used in larger projects, such as a module loader like require.js. Of the two, I have not used Require myself, but I think it is considered by many people the way to go.

Interface type check with Typescript

Based on Fenton's answer, here's my implementation of a function to verify if a given object has the keys an interface has, both fully or partially.

Depending on your use case, you may also need to check the types of each of the interface's properties. The code below doesn't do that.

function implementsTKeys<T>(obj: any, keys: (keyof T)[]): obj is T {
    if (!obj || !Array.isArray(keys)) {
        return false;
    }

    const implementKeys = keys.reduce((impl, key) => impl && key in obj, true);

    return implementKeys;
}

Example of usage:

interface A {
    propOfA: string;
    methodOfA: Function;
}

let objectA: any = { propOfA: '' };

// Check if objectA partially implements A
let implementsA = implementsTKeys<A>(objectA, ['propOfA']);

console.log(implementsA); // true

objectA.methodOfA = () => true;

// Check if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // true

objectA = {};

// Check again if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // false, as objectA now is an empty object

accessing a variable from another class

I hope I'm understanding the problem correctly, but it looks like you don't have a reference back to your DrawFrame object from DrawCircle.

Try this:

Change your constructor signature for DrawCircle to take in a DrawFrame object. Within the constructor, set the class variable "d" to the DrawFrame object you just took in. Now add the getWidth/getHeight methods to DrawFrame as mentioned in previous answers. See if that allows you to get what you're looking for.

Your DrawCircle constructor should be changed to something like:

public DrawCircle(DrawFrame frame)
{
    d = frame;
    w = 400;
    h = 400;
    diBig = 300;
    diSmall = 10;
    maxRad = (diBig/2) - diSmall;
    xSq = 50;
    ySq = 50;
    xPoint = 200;
    yPoint = 200;
}

The last line of code in DrawFrame should look something like:

contentPane.add(new DrawCircle(this));

Then, try using d.getheight(), d.getWidth() and so on within DrawCircle. This assumes you still have those methods available on DrawFrame to access them, of course.

Transfer data from one HTML file to another

<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>

<body>

<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>

</body>

client side scripting

function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}

jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.

jquery load function http://api.jquery.com/load/

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Try this :

    driver.findElement(By.id("email")).clear(); 
driver.findElement(By.id("email")).sendKeys("[email protected]");

How to get href value using jQuery?

**Replacing  href attribut value to other** 
 
 <div class="cpt">
   <a href="/ref/ref/testone.html">testoneLink</a>
 </div>

  <div class="test" >
      <a href="/ref/ref/testtwo.html">testtwoLInk</a>
  </div>

 <!--Remove first default Link from href attribut -->
<script>
     Remove first default Link from href attribut
    $(".cpt a").removeAttr("href");
    
    Add  Link to same href attribut
    var testurl= $(".test").find("a").attr("href");
    $(".test a").attr('href', testurl);
</script>

How to get the day name from a selected date?

What about if we use String.Format here

_x000D_
_x000D_
DateTime today = DateTime.Today;_x000D_
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format_x000D_
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
_x000D_
_x000D_
_x000D_

How to remove a package from Laravel using composer?

Normally composer remove used like this is enough:

$ composer remove vendor/package

but if composer package is removed and config cache is not cleaned you cannot clean it, when you try like so

php artisan config:clear

you can get an error In ProviderRepository.php line 208:

Class 'Laracasts\Flash\FlashServiceProvider' not found

this is a dead end, unless you go deleting files

$rm bootstrap/cache/config.php

And this is Laravel 5.6 I'm talking about, not some kind of very old stuff.

It happens usually on automated deployment, when you copy files of a new release on top of old cache. Even if you cleared cache before copying. You end up with old cache and a new composer.json.

add a temporary column with a value

select field1, field2, 'example' as TempField
from table1

This should work across different SQL implementations.

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

Fail module works great! Thanks.

I had to define my fact before checking it, otherwise I'd get an undefined variable error.

And I had issues when doing setting the fact with quotes and without spaces.

This worked:

set_fact: flag="failed"

This threw errors:

set_fact: flag = failed 

How to remove all listeners in an element?

I think that the fastest way to do this is to just clone the node, which will remove all event listeners:

var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.

How do I shut down a python simpleHTTPserver?

You are simply sending signals to the processes. kill is a command to send those signals.

The keyboard command Ctrl+C sends a SIGINT, kill -9 sends a SIGKILL, and kill -15 sends a SIGTERM.

What signal do you want to send to your server to end it?

How to connect wireless network adapter to VMWare workstation?

I also encountered a similar problem. I run Ubuntu 11.04 on VMware on a Windows 7 host OS. Virtual machines can't expose the physical wireless cards. All of that is using a virtualization layer.

Outline effect to text

I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn't involve extra mark-up, js and works in IE7-9 (I haven't tested 6), and doesn't cause aliasing problems.

This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE. CSS3 text-stroke support is poor at the moment.

IE Filters

The glow filter (http://www.impressivewebs.com/css3-text-shadow-ie/) looks terrible, so I didn't use that.

David Hewitt's answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.

I then combined some of the elements suggested on useragentman with the dropshadow filters.

Putting it together

This example would be black text with a white stroke. I'm using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).

#myelement {
    color: #000000;
    text-shadow:
    -1px -1px 0 #ffffff,  
    1px -1px 0 #ffffff,
    -1px 1px 0 #ffffff,
    1px 1px 0 #ffffff;
}

html.ie7 #myelement,
html.ie8 #myelement,
html.ie9 #myelement {
    background-color: white;
    filter: progid:DXImageTransform.Microsoft.Chroma(color='white') progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=-1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=-1);
    zoom: 1;
}

Converting Array to List

where stateb is List'' bucket is a two dimensional array

statesb= IntStream.of(bucket[j-1]).boxed().collect(Collectors.toList());

with import java.util.stream.IntStream;

see https://examples.javacodegeeks.com/core-java/java8-convert-array-list-example/

Remove Elements from a HashSet while Iterating

An other possible solution:

for(Object it : set.toArray()) { /* Create a copy */
    Integer element = (Integer)it;
    if(element % 2 == 0)
        set.remove(element);
}

Or:

Integer[] copy = new Integer[set.size()];
set.toArray(copy);

for(Integer element : copy) {
    if(element % 2 == 0)
        set.remove(element);
}

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

creating a new list with subset of list using index in python

Suppose

a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]

and the list of indexes is stored in

b= [0, 1, 2, 4, 6, 7, 8]

then a simple one-line solution will be

c = [a[i] for i in b]

How to check if AlarmManager already has an alarm set?

I have 2 alarms. I am using intent with extras instead of action to identify the events:

Intent i = new Intent(context, AppReciever.class);
i.putExtra("timer", "timer1");

the thing is that with diff extras the intent (and the alarm) wont be unique. So to able to identify which alarm is active or not, I had to define diff requestCode-s:

boolean alarmUp = (PendingIntent.getBroadcast(context, MyApp.TIMER_1, i, 
                    PendingIntent.FLAG_NO_CREATE) != null);

and here is how alarm was created:

public static final int TIMER_1 = 1;
public static final int TIMER_2 = 2;

PendingIntent pending = PendingIntent.getBroadcast(context, TIMER_1, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);
pending = PendingIntent.getBroadcast(context, TIMER_2, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);

How do I turn a C# object into a JSON string in .NET?

Use these tools for generating a C# class, and then use this code to serialize your object:

 var json = new JavaScriptSerializer().Serialize(obj);

How to embed a SWF file in an HTML page?

<object width="100" height="100">
    <param name="movie" value="file.swf">
    <embed src="file.swf" width="100" height="100">
    </embed>
</object>

Delete specific line number(s) from a text file using sed?

$ cat foo
1
2
3
4
5
$ sed -e '2d;4d' foo
1
3
5
$ 

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

How to select specific columns in laravel eloquent

You can use the below query:

Table('table')->select('name','surname')->where('id',1)->get();

array filter in python?

If the order is not important, you should use set.difference. However, if you want to retain order, a simple list comprehension is all it takes.

result = [a for a in A if a not in subset_of_A]

EDIT: As delnan says, performance will be substantially improved if subset_of_A is an actual set, since checking for membership in a set is O(1) as compared to O(n) for a list.

A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A

result = [a for a in A if a not in subset_of_A]

Easier way to create circle div than using an image?

Setting the border-radius of each side of an element to 50% will create the circle display at any size:

.circle {
  border-radius: 50%;
  width: 200px;
  height: 200px; 
  /* width and height can be anything, as long as they're equal */
}

How to reenable event.preventDefault?

You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding. There is no magical event.cancelled=false;

As requested

 $('form').submit( function(ev){

         ev.preventDefault();

         //later you decide you want to submit
         $(this).unbind('submit').submit()

  });

How to get the first line of a file in a bash script?

This suffices and stores the first line of filename in the variable $line:

read -r line < filename

I also like awk for this:

awk 'NR==1 {print; exit}' file

To store the line itself, use the var=$(command) syntax. In this case, line=$(awk 'NR==1 {print; exit}' file).

Or even sed:

sed -n '1p' file

With the equivalent line=$(sed -n '1p' file).


See a sample when we feed the read with seq 10, that is, a sequence of numbers from 1 to 10:

$ read -r line < <(seq 10) 
$ echo "$line"
1

$ line=$(awk 'NR==1 {print; exit}' <(seq 10))
$ echo "$line"
1

How to find out the location of currently used MySQL configuration file in linux

If you are using terminal just type the following:

locate my.cnf

Is it possible to have placeholders in strings.xml for runtime values?

Supplemental Answer

When I first saw %1$s and %2$d in the accepted answer, it made no sense. Here is a little more explanation.

They are called format specifiers. In the xml string they are in the form of

%[parameter_index$][format_type] 
  • %: The percent sign marks the beginning of the format specifier.
  • parameter index: This is a number followed by a dollar sign. If you had three parameters that you wanted to insert into the string, then they would be called 1$, 2$, and 3$. The order you place them in the resource string doesn't matter, only the order that you supply the parameters.
  • format type: There are a lot of ways that you can format things (see the documentation). Here are some common ones:

    • s string
    • d decimal integer
    • f floating point number

Example

We will create the following formatted string where the gray parts are inserted programmatically.

My sister Mary is 12 years old.

string.xml

<string name="my_xml_string">My sister %1$s is %2$d years old.</string>

MyActivity.java

String myString = "Mary";
int myInt = 12;
String formatted = getString(R.string.my_xml_string, myString, myInt);

Notes

  • I could use getString because I was in an Activity. You can use context.getResources().getString(...) if it is not available.
  • String.format() will also format a String.
  • The 1$ and 2$ terms don't need to be used in that order. That is, 2$ can come before 1$. This is useful when internationalizing an app for languages that use a different word order.
  • You can use a format specifier like %1$s multiple times in the xml if you want to repeat it.
  • Use %% to get the actual % character.
  • For more details read the following helpful tutorial: Android SDK Quick Tip: Formatting Resource Strings

Android studio, gradle and NDK

Now that Android Studio is in the stable channel, it is pretty straightforward to get the android-ndk samples running. These samples use the ndk experimental plugin and are newer than the ones linked to from the Android NDK online documentation. Once you know they work you can study the build.gradle, local.properties and gradle-wrapper.properties files and modify your project accordingly. Following are the steps to get them working.

  1. Go to settings, Appearance & Behavior, System Settings, Android SDK, selected the SDK Tools tab, and check Android NDK version 1.0.0 at the bottom of the list. This will download the NDK.

  2. Point to the location of the newly downloaded NDK. Note that it will be placed in the sdk/ndk-bundle directory. Do this by selecting File, Project Structure, SDK Location (on left), and supplying a path under Android NDK location. This will add an ndk entry to local.properties similar to this:

    Mac/Linux: ndk.dir=/Android/sdk/ndk-bundle
    Windows: ndk.dir=C:\Android\sdk\ndk-bundle

I have successfully built and deployed all projects in the repository this way, except gles3gni, native-codec and builder. I'm using the following:

Android Studio 1.3 build AI-141.2117773
android-ndk samples published July 28, 2015 (link above)
SDK Tools 24.3.3
NDK r10e extracted to C:\Android\sdk\ndk-bundle
Gradle 2.5
Gradle plugin 0.2.0
Windows 8.1 64 bit

Maven project.build.directory

It points to your top level output directory (which by default is target):

https://web.archive.org/web/20150527103929/http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:

http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html#resource-filtering-sect-project-properties

If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.

    project.build.sourceDirectory
    project.build.scriptSourceDirectory
    project.build.testSourceDirectory
    project.build.outputDirectory
    project.build.testOutputDirectory
    project.build.directory

sourceDirectory, scriptSourceDirectory, and testSourceDirectory provide access to the source directories for the project. outputDirectory and testOutputDirectory provide access to the directories where Maven is going to put bytecode or other build output. directory refers to the directory which contains all of these output directories.

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

How to execute an .SQL script file using c#

I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.

But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.

public partial class Form1 : MetroForm
{
    SqlConnection cn;
    SqlCommand cm;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (!CheckDatabaseExist())
        {
            GenerateDatabase();
        }
    }

    private bool CheckDatabaseExist()
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
        try
        {
            con.Open();
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void GenerateDatabase()
    {

        try
        {
            cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
            cm = new SqlCommand(sb.ToString() , cn);
            cn.Open();
            cm.ExecuteNonQuery();
            cn.Close();
        }
        catch
        {

        }
        try
        {
            //Application.StartupPath is the location where the application is Installed
            //Here File Path Can Be Provided Via OpenFileDialog
            if (File.Exists(Application.StartupPath + "\\script.sql"))
            {
                string script = null;
                script = File.ReadAllText(Application.StartupPath + "\\script.sql");
                string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
                using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
                {
                    cn.Open();
                    foreach (string str in ScriptSplitter)
                    {
                        using (cm = cn.CreateCommand())
                        {
                            cm.CommandText = str;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
        catch
        {

        }

    }

}

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}