Programs & Examples On #Etcpasswd

Extract Data from PDF and Add to Worksheet

Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext.

Pseudocode to extract the text would include:

  1. Using SHELL VBA statement to extract the text from PDF to a temporary file using XPDF
  2. Using sequential file read statements to read the temporary file contents into a string
  3. Pasting the string into Excel

Simplified example below:

    Sub ReadIntoExcel(PDFName As String)
        'Convert PDF to text
        Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"

        'Read in the text file and write to Excel
        Dim TextLine as String
        Dim RowNumber as Integer
        Dim F1 as Integer
        RowNumber = 1
        F1 = Freefile()
        Open "tempfile.txt" for Input as #F1
            While Not EOF(#F1)
                Line Input #F1, TextLine
                ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
                RowNumber = RowNumber + 1
            Wend
        Close #F1
    End Sub

RS256 vs HS256: What's the difference?

There is a difference in performance.

Simply put HS256 is about 1 order of magnitude faster than RS256 for verification but about 2 orders of magnitude faster than RS256 for issuing (signing).

 640,251  91,464.3 ops/s
  86,123  12,303.3 ops/s (RS256 verify)
   7,046   1,006.5 ops/s (RS256 sign)

Don't get hung up on the actual numbers, just think of them with respect of each other.

[Program.cs]

class Program
{
    static void Main(string[] args)
    {
        foreach (var duration in new[] { 1, 3, 5, 7 })
        {
            var t = TimeSpan.FromSeconds(duration);

            byte[] publicKey, privateKey;

            using (var rsa = new RSACryptoServiceProvider())
            {
                publicKey = rsa.ExportCspBlob(false);
                privateKey = rsa.ExportCspBlob(true);
            }

            byte[] key = new byte[64];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
            }

            var s1 = new Stopwatch();
            var n1 = 0;

            using (var hs256 = new HMACSHA256(key))
            {
                while (s1.Elapsed < t)
                {
                    s1.Start();
                    var hash = hs256.ComputeHash(privateKey);
                    s1.Stop();
                    n1++;
                }
            }

            byte[] sign;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                sign = rsa.SignData(privateKey, "SHA256");
            }

            var s2 = new Stopwatch();
            var n2 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(publicKey);

                while (s2.Elapsed < t)
                {
                    s2.Start();
                    var success = rsa.VerifyData(privateKey, "SHA256", sign);
                    s2.Stop();
                    n2++;
                }
            }

            var s3 = new Stopwatch();
            var n3 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                while (s3.Elapsed < t)
                {
                    s3.Start();
                    rsa.SignData(privateKey, "SHA256");
                    s3.Stop();
                    n3++;
                }
            }

            Console.WriteLine($"{s1.Elapsed.TotalSeconds:0} {n1,7:N0} {n1 / s1.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s2.Elapsed.TotalSeconds:0} {n2,7:N0} {n2 / s2.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s3.Elapsed.TotalSeconds:0} {n3,7:N0} {n3 / s3.Elapsed.TotalSeconds,9:N1} ops/s");

            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n2 / s2.Elapsed.TotalSeconds),9:N1}x slower (verify)");
            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n3 / s3.Elapsed.TotalSeconds),9:N1}x slower (issue)");

            // RS256 is about 7.5x slower, but it can still do over 10K ops per sec.
        }
    }
}

Collapsing Sidebar with Bootstrap

Its not mentioned on doc, but Left sidebar on Bootstrap 3 is possible using "Collapse" method.

As mentioned by bootstrap.js :

Collapse.prototype.dimension = function () {
    var hasWidth = this.$element.hasClass('width')
    return hasWidth ? 'width' : 'height'
  }

This mean, adding class "width" into target, will expand by width instead of height :

http://jsfiddle.net/2316sfbz/2/

Learning to write a compiler

If you are interested in writing a compiler for a functional language (rather than a procedural one) Simon Peyton-Jones and David Lester's "Implementing functional languages: a tutorial" is an excellent guide.

The conceptual basics of how functional evaluation works is guided by examples in a simple but powerful functional language called "Core". Additionally, each part of the Core language compiler is explained with code examples in Miranda (a pure functional language very similar to Haskell).

Several different types of compilers are described but even if you only follow the so-called template compiler for Core you will have an excellent understanding of what makes functional programming tick.

How to create a .gitignore file

You can type new-item .gitignore in Windows Powershell.

Check string for palindrome

Recently I wrote a palindrome program which doesn't use StringBuilder. A late answer but this might come in handy to some people.

public boolean isPalindrome(String value) {
    boolean isPalindrome = true;
    for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
        if (value.charAt(i) != value.charAt(j)) {
            isPalindrome = false;
        }
    }
    return isPalindrome;
}

Microsoft Web API: How do you do a Server.MapPath?

Since Server.MapPath() does not exist within a Web Api (Soap or REST), you'll need to denote the local- relative to the web server's context- home directory. The easiest way to do so is with:

string AppContext.BaseDirectory { get;}

You can then use this to concatenate a path string to map the relative path to any file.
NOTE: string paths are \ and not / like they are in mvc.

Ex:

System.IO.File.Exists($"{**AppContext.BaseDirectory**}\\\\Content\\\\pics\\\\{filename}");

returns true- positing that this is a sound path in your example

How to display loading message when an iFrame is loading?

You can use as below

$('#showFrame').on("load", function () {
        loader.hide();
});

find all unchecked checkbox in jquery

$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
               // enter your code here
            } });

How to get bean using application context in spring boot

actually you want to get the object from the Spring engine, where the engine already maintaining the object of your required class at that starting of the spring application(Initialization of the Spring engine).Now the thing is you just have to get that object to a reference.

in a service class

@Autowired
private ApplicationContext context;

SomeClass sc = (SomeClass)context.getBean(SomeClass.class);

now in the reference of the sc you are having the object. Hope explained well. If any doubt please let me know.

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

Is there a W3C valid way to disable autocomplete in a HTML form?

Using a random 'name' attribute works for me.

I reset the name attribute when sending the form so you can still access it by name when the form is sent. (using the id attribute to store the name)

Failed linking file resources

To be more generic about the answer provided by @P Fuster. There can be error in your xml files.

I encountered the same error and was having error in the drawable where end tag was missing.

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Some systems like Ubuntu, mysql is using by default the UNIX auth_socket plugin.

Basically means that: db_users using it, will be "auth" by the system user credentias. You can see if your root user is set up like this by doing the following:

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql;
mysql> SELECT User, Host, plugin FROM mysql.user;

+------------------+-----------------------+
| User             | plugin                |
+------------------+-----------------------+
| root             | auth_socket           |
| mysql.sys        | mysql_native_password |
| debian-sys-maint | mysql_native_password |
+------------------+-----------------------+

As you can see in the query, the root user is using the auth_socket plugin

There are 2 ways to solve this:

  1. You can set the root user to use the mysql_native_password plugin
  2. You can create a new db_user with you system_user (recommended)

Option 1:

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;

$ sudo service mysql restart

Option 2: (replace YOUR_SYSTEM_USER with the username you have)

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql;
mysql> CREATE USER 'YOUR_SYSTEM_USER'@'localhost' IDENTIFIED BY 'YOUR_PASSWD';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'YOUR_SYSTEM_USER'@'localhost';
mysql> UPDATE user SET plugin='auth_socket' WHERE User='YOUR_SYSTEM_USER';
mysql> FLUSH PRIVILEGES;
mysql> exit;

$ sudo service mysql restart

Remember that if you use option #2 you'll have to connect to mysql as your system username (mysql -u YOUR_SYSTEM_USER)

Note: On some systems (e.g., Debian stretch) 'auth_socket' plugin is called 'unix_socket', so the corresponding SQL command should be: UPDATE user SET plugin='unix_socket' WHERE User='YOUR_SYSTEM_USER';

Update: from @andy's comment seems that mysql 8.x.x updated/replaced the auth_socket for caching_sha2_password I don't have a system setup with mysql 8.x.x to test this, however the steps above should help you to understand the issue. Here's the reply:

One change as of MySQL 8.0.4 is that the new default authentication plugin is 'caching_sha2_password'. The new 'YOUR_SYSTEM_USER' will have this auth plugin and you can login from the bash shell now with "mysql -u YOUR_SYSTEM_USER -p" and provide the password for this user on the prompt. No need for the "UPDATE user SET plugin" step. For the 8.0.4 default auth plugin update see, https://mysqlserverteam.com/mysql-8-0-4-new-default-authentication-plugin-caching_sha2_password/

How do I install package.json dependencies in the current directory using npm

In my case I need to do

sudo npm install  

my project is inside /var/www so I also need to set proper permissions.

How to evaluate a math expression given in string form?

I've written this eval method for arithmetic expressions to answer this question. It does addition, subtraction, multiplication, division, exponentiation (using the ^ symbol), and a few basic functions like sqrt. It supports grouping using (...), and it gets the operator precedence and associativity rules correct.

public static double eval(final String str) {
    return new Object() {
        int pos = -1, ch;

        void nextChar() {
            ch = (++pos < str.length()) ? str.charAt(pos) : -1;
        }

        boolean eat(int charToEat) {
            while (ch == ' ') nextChar();
            if (ch == charToEat) {
                nextChar();
                return true;
            }
            return false;
        }

        double parse() {
            nextChar();
            double x = parseExpression();
            if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
            return x;
        }

        // Grammar:
        // expression = term | expression `+` term | expression `-` term
        // term = factor | term `*` factor | term `/` factor
        // factor = `+` factor | `-` factor | `(` expression `)`
        //        | number | functionName factor | factor `^` factor

        double parseExpression() {
            double x = parseTerm();
            for (;;) {
                if      (eat('+')) x += parseTerm(); // addition
                else if (eat('-')) x -= parseTerm(); // subtraction
                else return x;
            }
        }

        double parseTerm() {
            double x = parseFactor();
            for (;;) {
                if      (eat('*')) x *= parseFactor(); // multiplication
                else if (eat('/')) x /= parseFactor(); // division
                else return x;
            }
        }

        double parseFactor() {
            if (eat('+')) return parseFactor(); // unary plus
            if (eat('-')) return -parseFactor(); // unary minus

            double x;
            int startPos = this.pos;
            if (eat('(')) { // parentheses
                x = parseExpression();
                eat(')');
            } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
                while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                x = Double.parseDouble(str.substring(startPos, this.pos));
            } else if (ch >= 'a' && ch <= 'z') { // functions
                while (ch >= 'a' && ch <= 'z') nextChar();
                String func = str.substring(startPos, this.pos);
                x = parseFactor();
                if (func.equals("sqrt")) x = Math.sqrt(x);
                else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
                else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
                else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
                else throw new RuntimeException("Unknown function: " + func);
            } else {
                throw new RuntimeException("Unexpected: " + (char)ch);
            }

            if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation

            return x;
        }
    }.parse();
}

Example:

System.out.println(eval("((4 - 2^3 + 1) * -sqrt(3*3+4*4)) / 2"));

Output: 7.5 (which is correct)


The parser is a recursive descent parser, so internally uses separate parse methods for each level of operator precedence in its grammar. I kept it short so it's easy to modify, but here are some ideas you might want to expand it with:

  • Variables:

    The bit of the parser that reads the names for functions can easily be changed to handle custom variables too, by looking up names in a variable table passed to the eval method, such as a Map<String,Double> variables.

  • Separate compilation and evaluation:

    What if, having added support for variables, you wanted to evaluate the same expression millions of times with changed variables, without parsing it every time? It's possible. First define an interface to use to evaluate the precompiled expression:

    @FunctionalInterface
    interface Expression {
        double eval();
    }
    

    Now change all the methods that return doubles, so instead they return an instance of that interface. Java 8's lambda syntax works great for this. Example of one of the changed methods:

    Expression parseExpression() {
        Expression x = parseTerm();
        for (;;) {
            if (eat('+')) { // addition
                Expression a = x, b = parseTerm();
                x = (() -> a.eval() + b.eval());
            } else if (eat('-')) { // subtraction
                Expression a = x, b = parseTerm();
                x = (() -> a.eval() - b.eval());
            } else {
                return x;
            }
        }
    }
    

    That builds a recursive tree of Expression objects representing the compiled expression (an abstract syntax tree). Then you can compile it once and evaluate it repeatedly with different values:

    public static void main(String[] args) {
        Map<String,Double> variables = new HashMap<>();
        Expression exp = parse("x^2 - x + 2", variables);
        for (double x = -20; x <= +20; x++) {
            variables.put("x", x);
            System.out.println(x + " => " + exp.eval());
        }
    }
    
  • Different datatypes:

    Instead of double, you could change the evaluator to use something more powerful like BigDecimal, or a class that implements complex numbers, or rational numbers (fractions). You could even use Object, allowing some mix of datatypes in expressions, just like a real programming language. :)


All code in this answer released to the public domain. Have fun!

Check mySQL version on Mac 10.8.5

You should be able to open terminal and just type

mysql -v

JavaScript Object Id

Actually, you don't need to modify the object prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

How to convert minutes to Hours and minutes (hh:mm) in java

Given input in seconds you can transform to format hh:mm:ss like this :

int hours;
int minutes;
int seconds;
int formatHelper;

int input;


//formatHelper maximum value is 24 hours represented in seconds

formatHelper = input % (24*60*60);

//for example let's say format helper is 7500 seconds

hours = formatHelper/60*60;
minutes = formatHelper/60%60;
seconds = formatHelper%60;

//now operations above will give you result = 2hours : 5 minutes : 0 seconds;

I have used formatHelper since the input can be more then 86 400 seconds, which is 24 hours.

If you want total time of your input represented by hh:mm:ss, you can just avoid formatHelper.

I hope it helps.

How to print binary tree diagram?

This is an interesting question, and I also wrote a project for it.

binary-tree-printer

Here are some examples:

Print random BST.

BTPrinter.printRandomBST(100, 100);
                              38                                  
                              / \                                 
                             /   \                                
                            /     \                               
                           /       \                              
                          /         \                             
                         /           \                            
                        /             \                           
                       /               \                          
                      /                 \                         
                     /                   \                        
                    /                     \                       
                   /                       \                      
                  /                         \                     
                 /                           \                    
                /                             \                   
               /                               \                  
              28                               82                 
             / \                               / \                
            /   \                             /   \               
           /     \                           /     \              
          /       \                         /       \             
         5        31                       /         \            
        / \       / \                     /           \           
       /   \     30 36                   /             \          
      /     \   /   / \                 /               \         
     /       \ 29  33 37               /                 \        
    /         \   / \                 /                   \       
   /           \ 32 35               65                   95      
  1            14   /               / \                   / \     
 / \           / \ 34              /   \                 94 97    
0   2         /   \               /     \               /   / \   
     \       12   24             /       \             93  96 98  
      3     / \   / \           /         \           /         \ 
       \   9  13 16 25         /           \         84         99
        4 / \   / \   \       /             \       / \           
         7  10 15 23  26     59             74     83 86          
        / \   \   /     \   / \             / \       / \         
       6   8  11 22     27 56 60           73 76     85 91        
                /         / \   \         /   / \       / \       
               20        /   \  61       67  75 79     88 92      
              / \       40   58   \     / \     / \   / \         
             18 21     / \   /    62   66 72   78 80 87 89        
            / \       39 54 57      \     /   /     \     \       
           17 19         / \        64   69  77     81    90      
                        50 55       /   / \                       
                       / \         63  68 70                      
                      /   \                 \                     
                     /     \                71                    
                    47     53                                     
                   / \     /                                      
                  /   \   52                                      
                 42   49 /                                        
                / \   / 51                                        
               41 43 48                                           
                    \                                             
                    46                                            
                    /                                             
                   45                                             
                  /                                               
                 44     

Print tree from leetcode-style level order array, '#' means a path terminator where no node exists below.

BTPrinter.printTree("1,2,3,4,5,#,#,6,7,8,1,#,#,#,#,#,#,2,3,4,5,6,7,8,9,10,11,12,13,14,15");
        1              
       / \             
      2   3            
     / \               
    /   \              
   4     5             
  / \   / \            
 6   7 8   1           
          / \          
         /   \         
        /     \        
       /       \       
      /         \      
     2           3     
    / \         / \    
   /   \       /   \   
  4     5     6     7  
 / \   / \   / \   / \ 
8   9 10 11 12 13 14 15

The cause of "bad magic number" error when loading a workspace and how to avoid it?

I got that error when I accidentally used load() instead of source() or readRDS().

How to display a JSON representation and not [Object Object] on the screen

if you have array of object and you would like to deserialize them in compoent

get example() { this.arrayOfObject.map(i => JSON.stringify (i) ) };

then in template

<ul>
   <li *ngFor="obj of example">{{obj}}</li>
</ul>

window.onunload is not working properly in Chrome browser. Can any one help me?

There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.

But what is possible (AFAIK):

  1. Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
  2. Return a simple string (in beforeunload event), which triggers a confirm box, which asks the user if s/he want to leave the page.

Example for #2:

$(window).on('beforeunload', function() {
    return 'Your own message goes here...';
});

Demo: http://jsfiddle.net/PQz5k/

"Find next" in Vim

If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.

Python: How to use RegEx in an if statement?

Regex's shouldn't really be used in this fashion - unless you want something more complicated than what you're trying to do - for instance, you could just normalise your content string and comparision string to be:

if 'facebook.com' in content.lower():
    shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")

Can we convert a byte array into an InputStream in Java?

If you use Robert Harder's Base64 utility, then you can do:

InputStream is = new Base64.InputStream(cph);

Or with sun's JRE, you can do:

InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)

However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

There are other Stack Overflow questions about Base64 decoding, such as this one.

PHP7 : install ext-dom issue

I faced this exact same issue with Laravel 8.x on Ubuntu 20. I run: sudo apt install php7.4-xml and composer update within the project directory. This fixed the issue.

Disable pasting text into HTML form

from

Some may suggest using Javascript to capture the users' actions, like right-clicking the mouse or the Ctrl+C / Ctrl+V key combinations and then stopping the operation. But this is obviously not the best or simplest solution. The solution is integrated in the input field properties itself together with some event capturing using Javascript.

In order to disabled the browsers' autocomplete, simply add the attribute to the input field. It should look something like this:

<input type="text" autocomplete="off">

And if you want to deny Copy and Paste for that field, simply add the Javascript event capturing calls oncopy, onpaste, and oncut and make them return false, like so:

<input type="text" oncopy="return false;" onpaste="return false;" oncut="return false;">

The next step is using onselectstart to deny the input field's content selection from the user, but be warned: this only works for Internet Explorer. The rest of the above work great on all the major browsers: Internet Explorer, Mozilla Firefox, Apple Safari (on Windows OS, at least) and Google Chrome.

Convert bytes to int?

Assuming you're on at least 3.2, there's a built in for this:

int.from_bytes( bytes, byteorder, *, signed=False )

...

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

The signed argument indicates whether two’s complement is used to represent the integer.


## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024

Where is debug.keystore in Android Studio

Another way of finding out your key information is to go to your java folder, for me it was at

C:\Program Files\Java\jdk1.8.0_60\bin

and run the following command

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

from the command you can easily see that keystore address is "c:\users/<%mylogin%>.android\debug.keystore" , alias is "androiddebugkey" store password is "android" key password is "android"

This is the default configuration from the Android 'Get API Key' documentation. https://developers.google.com/maps/documentation/android-api/signup

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

Is it possible to use raw SQL within a Spring Repository

YES, You can do this on bellow ways:

1. By CrudRepository (Projection)

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons.

Suppose your entity is like this :

    import javax.persistence.*;
    import java.math.BigDecimal;

    @Entity
    @Table(name = "USER_INFO_TEST")
    public class UserInfoTest {
        private int id;
        private String name;
        private String rollNo;

        public UserInfoTest() {
        }

        public UserInfoTest(int id, String name) {
        this.id = id;
        this.name = name;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "ID", nullable = false, precision = 0)
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Basic
        @Column(name = "name", nullable = true)
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Basic
        @Column(name = "roll_no", nullable = true)
        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

Now your Projection class is like bellow. It can those fields that you needed.

public interface IUserProjection {
     int getId();
     String getName();
     String getRollNo();
}

And Your Data Access Object(Dao) is like bellow :

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;

public interface UserInfoTestDao extends CrudRepository<UserInfoTest,Integer> {
    @Query(value = "select id,name,roll_no from USER_INFO_TEST where rollNo = ?1", nativeQuery = true)
    ArrayList<IUserProjection> findUserUsingRollNo(String rollNo);
}

Now ArrayList<IUserProjection> findUserUsingRollNo(String rollNo) will give you the list of user.

2. Using EntityManager

Suppose your query is "select id,name from users where roll_no = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

Your Response class is like:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where roll_no = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

Here is the Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

get EntityManager from this way:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Note:

query.getSingleResult() return a object array. You have to maintain the column position and data type with query column position.

select id,name from users where roll_no = 1001 

query return a array and it's [0] --> id and [1] -> name.

More info visit this thread and this Thread

Thanks :)

How to open a file / browse dialog using javascript?

Use this.

<script>
  function openFileOption()
{
  document.getElementById("file1").click();
}
</script>
     <input type="file" id="file1" style="display:none">
     <a href="#" onclick="openFileOption();return;">open File Dialog</a>

Twitter bootstrap remote modal shows same content every time

I wrote a simple snippet handling the refreshing of the modal. Basically it stores the clicked link in the modal's data and check if it's the same link that has been clicked, removing or not the modal data.

var handleModal = function()
{
    $('.triggeringLink').click(function(event) {
        var $logsModal = $('#logsModal');
        var $triggeringLink = $logsModal.data('triggeringLink');

        event.preventDefault();

        if ($logsModal.data('modal') != undefined
            && $triggeringLink != undefined
            && !$triggeringLink.is($(this))
        ) {
            $logsModal.removeData('modal');
        }

        $logsModal.data('triggeringLink', $(this));

        $logsModal.modal({ remote: $(this).attr('href') });
        $logsModal.modal('show');
    });
};

'Connect-MsolService' is not recognized as the name of a cmdlet

This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.

To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell

2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.

Import-Module MSOnline 

After it complete, we can use this command to check it.

PS C:\Users> Get-Module -ListAvailable -Name MSOnline*


    Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.1.166.0  MSOnline                            {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest   1.1.166.0  MSOnlineExtended                    {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}

More information about this issue, please refer to it.


Update:

We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.

enter image description here

Visual Studio Code: Auto-refresh file changes

VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.

There is currently no way to disable this behaviour.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

By default, JNDI is disabled in embedded Tomcat which is causing the NoInitialContextException. You need to call Tomcat.enableNaming() to enable it. The easiest way to do that is with a TomcatEmbeddedServletContainer subclass:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
    };
}

If you take this approach, you can also register the DataSource in JNDI by overriding the postProcessContext method in your TomcatEmbeddedServletContainerFactory subclass.

context.getNamingResources().addResource adds the resource to the java:comp/env context so the resource's name should be jdbc/mydatasource not java:comp/env/mydatasource.

Tomcat uses the thread context class loader to determine which JNDI context a lookup should be performed against. You're binding the resource into the web app's JNDI context so you need to ensure that the lookup is performed when the web app's class loader is the thread context class loader. You should be able to achieve this by setting lookupOnStartup to false on the jndiObjectFactoryBean. You'll also need to set expectedType to javax.sql.DataSource:

<bean class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/mydatasource"/>
    <property name="expectedType" value="javax.sql.DataSource"/>
    <property name="lookupOnStartup" value="false"/>
</bean>

This will create a proxy for the DataSource with the actual JNDI lookup being performed on first use rather than during application context startup.

The approach described above is illustrated in this Spring Boot sample.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

One can also receive this error if using the new (so far webkit only) notification feature before getting permission.

First run:

<!-- Get permission -->
<button onclick="webkitNotifications.requestPermission();">Enable Notifications</button>

Later run:

// Display Notification:
window.webkitNotifications.createNotification('image', 'Title', 'Body').show();

The request permission functions needs to be triggered from an event caused by the user, otherwise it won't be displayed.

Twitter Bootstrap onclick event on buttons-radio

If your html is similar to the example, so the click event is produced over the label, not in the input, so I use the next code: Html example:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>      
</div>

Javascript code for the event:

$('#option1').parent().on("click", function () {
   alert("click fired"); 
});

Remove all whitespace in a string

try this.. instead of using re i think using split with strip is much better

def my_handle(self):
    sentence = ' hello  apple  '
    ' '.join(x.strip() for x in sentence.split())
#hello apple
    ''.join(x.strip() for x in sentence.split())
#helloapple

Difference between HashMap and Map in Java..?

Map is an interface in Java. And HashMap is an implementation of that interface (i.e. provides all of the methods specified in the interface).

EventListener Enter Key

Are you trying to submit a form?

Listen to the submit event instead.

This will handle click and enter.

If you must use enter key...

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

How do I iterate through each element in an n-dimensional matrix in MATLAB?

The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,

A = magic(3)
A =
     8     1     6
     3     5     7
     4     9     2

A(2,3)
ans =
     7

A(8)
ans =
     7

We can see the order the elements are stored in memory by unrolling the array into a vector.

A(:)
ans =
     8
     3
     4
     1
     5
     9
     6
     7
     2

As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.

find(A>6)
ans =
     1
     6
     8

The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:

B = zeros(size(A));
for i = 1:numel(A)
  B(i) = A(i).^2;
end

B
B =
    64     1    36
     9    25    49
    16    81     4

There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.

The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)

Center a button in a Linear layout

Set to true android:layout_alignParentTop="true" and android:layout_centerHorizontal="true" in the Button, like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
     <Button
        android:id="@+id/switch_flashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/turn_on_flashlight"
        android:textColor="@android:color/black"
        android:onClick="action_trn"
        android:background="@android:color/holo_green_light"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:padding="5dp" />
</RelativeLayout>

enter image description here

How to install grunt and how to build script with it

Some time we need to set PATH variable for WINDOWS

%USERPROFILE%\AppData\Roaming\npm

After that test with where grunt

Note: Do not forget to close the command prompt window and reopen it.

Detect if page has finished loading

Is this what you had in mind?

$("document").ready( function() {
    // do your stuff
}

How to make a DIV not wrap?

Try using white-space: nowrap; in the container style (instead of overflow: hidden;)

`export const` vs. `export default` in ES6

Minor note: Please consider that when you import from a default export, the naming is completely independent. This actually has an impact on refactorings.

Let's say you have a class Foo like this with a corresponding import:

export default class Foo { }

// The name 'Foo' could be anything, since it's just an
// Identifier for the default export
import Foo from './Foo'

Now if you refactor your Foo class to be Bar and also rename the file, most IDEs will NOT touch your import. So you will end up with this:

export default class Bar { }

// The name 'Foo' could be anything, since it's just an
// Identifier for the default export.
import Foo from './Bar'

Especially in TypeScript, I really appreciate named exports and the more reliable refactoring. The difference is just the lack of the default keyword and the curly braces. This btw also prevents you from making a typo in your import since you have type checking now.

export class Foo { }

//'Foo' needs to be the class name. The import will be refactored
//in case of a rename!
import { Foo } from './Foo'

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

bad operand types for binary operator "&" java

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

Search and get a line in Python

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

items=re.findall("^.*token.*$",s,re.MULTILINE)

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty

In Python script, how do I set PYTHONPATH?

PYTHONPATH ends up in sys.path, which you can modify at runtime.

import sys
sys.path += ["whatever"]

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

How to Inspect Element using Safari Browser

Press CMD + , than click in show develop menu in menu bar. After that click Option + CMD + i to open and close the inspector

enter image description here

C++ code file extension? .cc vs .cpp

Several people saying .cc doesn't stand for anything? It might. C++ started life as "C with Classes".

True that .cc and .cpp are also command names on most Unix systems (c compiler and c preprocessor respectively).

I use .cpp exclusively, but I started on Windows. .cc is more a Unix convention, although I see it less and less even there. GNU make has rules for .cpp so that's probably preferred, it will work by default on both Windows and everything else. On the other hand modern C++ uses no extension at all for headers, I really don't like that. All my projects use .h for header files, and they support both C and C++ as much as possible via extern "C" and testing __cplusplus.

Change input text border color without changing its height

Is this what you are looking for.

$("input.address_field").on('click', function(){  
     $(this).css('border', '2px solid red');
});

How do you manually execute SQL commands in Ruby On Rails using NuoDB

The working command I'm using to execute custom SQL statements is:

results = ActiveRecord::Base.connection.execute("foo")

with "foo" being the sql statement( i.e. "SELECT * FROM table").

This command will return a set of values as a hash and put them into the results variable.

So on my rails application_controller.rb I added this:

def execute_statement(sql)
  results = ActiveRecord::Base.connection.execute(sql)

  if results.present?
    return results
  else
    return nil
  end
end

Using execute_statement will return the records found and if there is none, it will return nil.

This way I can just call it anywhere on the rails application like for example:

records = execute_statement("select * from table")

"execute_statement" can also call NuoDB procedures, functions, and also Database Views.

How to center HTML5 Videos?

I was having the same problem. This worked for me:

.center {
    margin: 0 auto; 
    width: 400px;
    **display:block**
 }

Error CS1705: "which has a higher version than referenced assembly"

In my scenario, I edited the .csproj file for my dotnetCore app. I noticed that the TargetFramework tag had a value of netcoreapp2.1 and the RuntimeFrameworkVersion tag a value of 2.0.0. So I changed the RuntimeFrameworkVersion to 2.1.0, saved, restarted VS and rebuilt and then it resolved the errors.

Hope this will help you ...

Good Luck,

Sugeshan

@Media min-width & max-width

The underlying issue is using max-device-width vs plain old max-width.

Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.

For example:

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}

Versus

@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}

Add an image in a WPF button

In the case of a 'missing' image there are several things to consider:

  1. When XAML can't locate a resource it might ignore it (when it won't throw a XamlParseException)

  2. The resource must be properly added and defined:

    • Make sure it exists in your project where expected.

    • Make sure it is built with your project as a resource.

      (Right click ? Properties ? BuildAction='Resource')

Snippet

Another thing to try in similar cases, which is also useful for reusing of the image (or any other resource):

Define your image as a resource in your XAML:

<UserControl.Resources>
     <Image x:Key="MyImage" Source.../>
</UserControl.Resources>

And later use it in your desired control(s):

<Button Content="{StaticResource MyImage}" />

anaconda/conda - install a specific package version

There is no version 1.3.0 for rope. 1.3.0 refers to the package cached-property. The highest available version of rope is 0.9.4.

You can install different versions with conda install package=version. But in this case there is only one version of rope so you don't need that.

The reason you see the cached-property in this listing is because it contains the string "rope": "cached-p rope erty"

py35_0 means that you need python version 3.5 for this specific version. If you only have python3.4 and the package is only for version 3.5 you cannot install it with conda.

I am not quite sure on the defaults either. It should be an indication that this package is inside the default conda channel.

PHP DOMDocument loadHTML not encoding UTF-8 correctly

Works finde for me:

$dom = new \DOMDocument;
$dom->loadHTML(utf8_decode($html));
...
return  utf8_encode( $dom->saveHTML());

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

The best solution would be to go to http://projects.eclipse.org/projects/tools.pdt/downloads where you will find the URL to the most updated PDT, as most of the URLS listed above are hitting a 404. Then pasting the URL to eclipse.

Where is NuGet.Config file located in Visual Studio project?

If you use proxy, you will have to edit the Nuget.config file.

In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.

Include the setting:

<config>
  <add key = "http_proxy" value = "http://Youproxy:8080" />
  <add key = "http_proxy.user" value = "YouProxyUser" />
</config>

Custom HTTP Authorization Header

Old question I know, but for the curious:

Believe it or not, this issue was solved ~2 decades ago with HTTP BASIC, which passes the value as base64 encoded username:password. (See http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side)

You could do the same, so that the example above would become:

Authorization: FIRE-TOKEN MFBONUoxN0hCR1pIVDdKSjNYODI6ZnJKSVVOOERZcEtEdE9MQ3dvLy95bGxxRHpnPQ==

Generate a UUID on iOS from Swift

You could also just use the NSUUID API:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

Note that NSUUID is available from iOS 6 and up.

Timestamp with a millisecond precision: How to save them in MySQL

CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );

INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');

Rails - How to use a Helper Inside a Controller

In rails 6, simply add this to your controller:

class UsersController < ApplicationController
  include UsersHelper
  
  # Your actions

end

Now the user_helpers.rb will be available in the controller.

How to add one day to a date?

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.

Important hint: That is not correct in all cases. Read the WARNING comment, below.

The cast to value type 'Int32' failed because the materialized value is null

To allow a nullable Amount field, just use the null coalescing operator to convert nulls to 0.

var creditsSum = (from u in context.User
              join ch in context.CreditHistory on u.ID equals ch.UserID                                        
              where u.ID == userID
              select ch.Amount ?? 0).Sum();

How to change my Git username in terminal?

usually the user name resides under git config

git config --global user.name "first last"

although if you still see above doesn't work you could edit .gitconfig under your user directory of mac and update

[user]
        name = gitusername
        email = [email protected]

How do I get my Maven Integration tests to run

You should use maven surefire plugin to run unit tests and maven failsafe plugin to run integration tests.

Please follow below if you wish to toggle the execution of these tests using flags.

Maven Configuration

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <skipTests>${skipUnitTests}</skipTests>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <configuration>
                <includes>
                    <include>**/*IT.java</include>
                </includes>
                <skipTests>${skipIntegrationTests}</skipTests>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <properties>
            <skipTests>false</skipTests>
            <skipUnitTests>${skipTests}</skipUnitTests>
            <skipIntegrationTests>${skipTests}</skipIntegrationTests>
        </properties>

So, tests will be skipped or switched according to below flag rules:

Tests can be skipped by below flags:

  • -DskipTests skips both unit and integration tests
  • -DskipUnitTests skips unit tests but executes integration tests
  • -DskipIntegrationTests skips integration tests but executes unit tests

Running Tests

Run below to execute only Unit Tests

mvn clean test

You can execute below command to run the tests (both unit and integration)

mvn clean verify

In order to run only Integration Tests, follow

mvn failsafe:integration-test

Or skip unit tests

mvn clean install -DskipUnitTests

Also, in order to skip integration tests during mvn install, follow

mvn clean install -DskipIntegrationTests

You can skip all tests using

mvn clean install -DskipTests

Django REST Framework: adding additional field to ModelSerializer

class Demo(models.Model):
    ...
    @property
    def property_name(self):
        ...

If you want to use the same property name:

class DemoSerializer(serializers.ModelSerializer):
    property_name = serializers.ReadOnlyField()
    class Meta:
        model = Product
        fields = '__all__' # or you can choose your own fields

If you want to use different property name, just change this:

new_property_name = serializers.ReadOnlyField(source='property_name')

Bootstrap-select - how to fire event on change

Simplest solution would be -

$('.selectpicker').trigger('change');

Cannot connect to local SQL Server with Management Studio

Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Make <body> fill entire screen?

I think the largely correct way, is to set css to this:

html
{
    overflow: hidden;
}

body
{
    margin: 0;
    box-sizing: border-box;
}

html, body
{
    height: 100%;
}

How to style a select tag's option element?

Unfortunately, WebKit browsers do not support styling of <option> tags yet, except for color and background-color.

The most widely used cross browser solution is to use <ul> / <li> and style them using CSS. Frameworks like Bootstrap do this well.

Finding three elements in an array whose sum is closest to a given number

Here is the C++ code:

bool FindSumZero(int a[], int n, int& x, int& y, int& z)
{
    if (n < 3)
        return false;

    sort(a, a+n);

    for (int i = 0; i < n-2; ++i)
    {
        int j = i+1;
        int k = n-1;

        while (k >= j)
        {
            int s = a[i]+a[j]+a[k];

            if (s == 0 && i != j && j != k && k != i)
            {
                x = a[i], y = a[j], z = a[k];
                return true;
            }

            if (s > 0)
                --k;
            else
                ++j;
        }
    }

    return false;
}

How to upload & Save Files with Desired name

i know what went wrong you see you used "" instead of '' in this

$target_Path = $target_Path.basename( 

   "myFile.png"

);

How do I format date and time on ssrs report?

=Replace(Format(CDate(Now()),"MM.dd.yyyy"), ".", "/")

Deleting Objects in JavaScript

The delete command has no effect on regular variables, only properties. After the delete command the property doesn't have the value null, it doesn't exist at all.

If the property is an object reference, the delete command deletes the property but not the object. The garbage collector will take care of the object if it has no other references to it.

Example:

var x = new Object();
x.y = 42;

alert(x.y); // shows '42'

delete x; // no effect
alert(x.y); // still shows '42'

delete x.y; // deletes the property
alert(x.y); // shows 'undefined'

(Tested in Firefox.)

How do I pass named parameters with Invoke-Command?

I suspect its a new feature since this post was created - pass parameters to the script block using $Using:var. Then its a simple mater to pass parameters provided the script is already on the machine or in a known network location relative to the machine

Taking the main example it would be:

icm -cn $Env:ComputerName { 
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -one "uno" -two "dos" -Debug -Clear $Using:Clear
}

How to format current time using a yyyyMMddHHmmss format?

Use

fmt.Println(t.Format("20060102150405"))

as Go uses following constants to format date,refer here

const (
    stdLongMonth      = "January"
    stdMonth          = "Jan"
    stdNumMonth       = "1"
    stdZeroMonth      = "01"
    stdLongWeekDay    = "Monday"
    stdWeekDay        = "Mon"
    stdDay            = "2"
    stdUnderDay       = "_2"
    stdZeroDay        = "02"
    stdHour           = "15"
    stdHour12         = "3"
    stdZeroHour12     = "03"
    stdMinute         = "4"
    stdZeroMinute     = "04"
    stdSecond         = "5"
    stdZeroSecond     = "05"
    stdLongYear       = "2006"
    stdYear           = "06"
    stdPM             = "PM"
    stdpm             = "pm"
    stdTZ             = "MST"
    stdISO8601TZ      = "Z0700"  // prints Z for UTC
    stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
    stdNumTZ          = "-0700"  // always numeric
    stdNumShortTZ     = "-07"    // always numeric
    stdNumColonTZ     = "-07:00" // always numeric
)

How do I render a shadow?

I'm using Styled Components and created a helper function for myself.

It takes the given Android elevation and creates a fairly equivalent iOS shadow.

stylingTools.js

import { css } from 'styled-components/native';

/*
 REMINDER!!!!!!!!!!!!!
 Shadows do not show up on iOS if `overflow: hidden` is used.
 https://react-native.canny.io/feature-requests/p/shadow-does-not-appear-if-overflow-hidden-is-set-on-ios
*/

// eslint-disable-next-line import/prefer-default-export
export const crossPlatformElevation = (elevation: number = 0) => css`
  /* Android - native default is 4, we're setting to 0 to match iOS. */
  elevation: ${elevation};

  /* iOS - default is no shadow. Only add if above zero */
  ${elevation > 0
    && css`
      shadow-color: black;
      shadow-offset: 0px ${0.5 * elevation}px;
      shadow-opacity: 0.3;
      shadow-radius: ${0.8 * elevation}px;
    `}
`;

To use

import styled from 'styled-components/native';
import { crossPlatformElevation } from "../../lib/stylingTools";

export const ContentContainer = styled.View`
  background: white;
  ${crossPlatformElevation(10)};
`;

babel-loader jsx SyntaxError: Unexpected token

The following way has helped me (includes react-hot, babel loaders and es2015, react presets):

loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
      }
]

How to get http headers in flask?

from flask import request
request.headers.get('your-header-name')

request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:

request.headers['your-header-name']

Relative paths based on file location instead of current working directory

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:


Linux / GNU readlink solution:

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

 scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")

Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.


Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):

If your script must run on any platform that:

  • has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

    • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
  • does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

The following solution, inspired by https://stackoverflow.com/a/1116890/45375, defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

  • If readlink is available, it is used (without options) - true on most modern platforms.

  • Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
    Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
    (Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)

  • An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")

How to change the docker image installation directory?

For Those looking in 2020. The following is for Windows 10 Machine:

  1. In the global Actions pane of Hyper-V Manager click Hyper-V Settings…
  2. Under Virtual Hard Disks change the location from the default to your desired location.
  3. Under Virtual Machines change the location from the default to your desired location, and click apply.

enter image description here

  1. Click OK to close the Hyper-V Settings page.

Ruby: Easiest Way to Filter Hash Keys?

params.select{ |k,v| k =~ /choice\d/ }.map{ |k,v| v}.join("\t")

What does mvn install in maven exactly do

Short answer

mvn install

  • adds all artifact (dependencies) specified in pom, to the local repository (from remote sources).

The thread has exited with code 0 (0x0) with no unhandled exception

I have also faced this problem and the solution is:

  1. open Solution Explore
  2. double click on Program.cs file

I added this code again and my program ran accurately:

Application.Run(new PayrollSystem()); 
//File name this code removed by me accidentally.

Install specific version using laravel installer

Using composer you can specify the version you want easily by running

composer create-project laravel/laravel="5.1.*" myProject

Using the 5.1.* will ensure that you get all the latest patches in the 5.1 branch.

Plotting 4 curves in a single plot, with 3 y-axes

This is a great chance to introduce you to the File Exchange. Though the organization of late has suffered from some very unfortunately interface design choices, it is still a great resource for pre-packaged solutions to common problems. Though many here have given you the gory details of how to achieve this (@prm!), I had a similar need a few years ago and found that addaxis worked very well. (It was a File Exchange pick of the week at one point!) It has inspired later, probably better mods. Here is some example output:

addaxis example http://www.mathworks.com/matlabcentral/fx_files/9016/1/addaxis_screenshot.jpg

I just searched for "plotyy" at File Exchange.

Though understanding what's going on in important, sometimes you just need to get things done, not do them yourself. Matlab Central is great for that.

python: create list of tuples from lists

Use the builtin function zip():

In Python 3:

z = list(zip(x,y))

In Python 2:

z = zip(x,y)

How to find distinct rows with field in list using JPA and Spring?

@Query("SELECT distinct new com.model.referential.Asset(firefCode,firefDescription) FROM AssetClass ")
List<AssetClass> findDistinctAsset();

Text overflow ellipsis on two lines

Css below should do the trick.

After the second line the, text will contain ...

line-height: 1em;
max-height: 2em;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;

Is it possible to make input fields read-only through CSS?

Hope this will help.

    input[readonly="readonly"]
{
    background-color:blue;
}

reference:

http://jsfiddle.net/uzyH5/1/

Disable vertical sync for glxgears

I found a solution that works in the intel card and in the nvidia card using Bumblebee.

> export vblank_mode=0
glxgears
...
optirun glxgears
...
export vblank_mode=1

Finding smallest value in an array most efficiently

If you're developing some kind of your own array abstraction, you can get O(1) if you store smallest added value in additional attribute and compare it every time a new item is put into array.

It should look something like this:

class MyArray
{
public:
    MyArray() : m_minValue(INT_MAX) {}

    void add(int newValue)
    {
        if (newValue < m_minValue) m_minValue = newValue;
        list.push_back( newValue );
    }

    int min()
    {
        return m_minValue;
    }

private:
    int m_minValue;
    std::list m_list;
}

OpenCV - Apply mask to a color image

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here

When do you use map vs flatMap in RxJava?

I just wanted to add that with flatMap, you don't really need to use your own custom Observable inside the function and you can rely on standard factory methods/operators:

Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
    @Override public Observable<String> call(final File file) {
        try {
            String json = new Gson().toJson(new FileReader(file), Object.class);
            return Observable.just(json);
        } catch (FileNotFoundException ex) {
            return Observable.<String>error(ex);
        }
    }
});

Generally, you should avoid throwing (Runtime-) exceptions from onXXX methods and callbacks if possible, even though we placed as many safeguards as we could in RxJava.

BOOLEAN or TINYINT confusion

Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.

A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).

It's a nit, but enough to cause unit tests to fail.

What is the best way to implement constants in Java?

That's the right way to go.

Generally constants are not kept in separate "Constants" classes because they're not discoverable. If the constant is relevant to the current class, keeping them there helps the next developer.

Best practice for partial updates in a RESTful service

For modifying the status I think a RESTful approach is to use a logical sub-resource which describes the status of the resources. This IMO is pretty useful and clean when you have a reduced set of statuses. It makes your API more expressive without forcing the existing operations for your customer resource.

Example:

POST /customer/active  <-- Providing entity in the body a new customer
{
  ...  // attributes here except status
}

The POST service should return the newly created customer with the id:

{
    id:123,
    ...  // the other fields here
}

The GET for the created resource would use the resource location:

GET /customer/123/active

A GET /customer/123/inactive should return 404

For the PUT operation, without providing a Json entity it will just update the status

PUT /customer/123/inactive  <-- Deactivating an existing customer

Providing an entity will allow you to update the contents of the customer and update the status at the same time.

PUT /customer/123/inactive
{
    ...  // entity fields here except id and status
}

You are creating a conceptual sub-resource for your customer resource. It is also consistent with Roy Fielding's definition of a resource: "...A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time..." In this case the conceptual mapping is active-customer to customer with status=ACTIVE.

Read operation:

GET /customer/123/active 
GET /customer/123/inactive

If you make those calls one right after the other one of them must return status 404, the successful output may not include the status as it is implicit. Of course you can still use GET /customer/123?status=ACTIVE|INACTIVE to query the customer resource directly.

The DELETE operation is interesting as the semantics can be confusing. But you have the option of not publishing that operation for this conceptual resource, or use it in accordance with your business logic.

DELETE /customer/123/active

That one can take your customer to a DELETED/DISABLED status or to the opposite status (ACTIVE/INACTIVE).

Datetime current year and month in Python

You can always use a sub-string method:

import datetime;

today = str(datetime.date.today());
curr_year = int(today[:4]);
curr_month = int(today[5:7]);

This will get you the current month and year in integer format. If you want them to be strings you simply have to remove the " int " precedence while assigning values to the variables curr_year and curr_month.

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

How to iterate a loop with index and element in Swift

Using .enumerate() works, but it does not provide the true index of the element; it only provides an Int beginning with 0 and incrementing by 1 for each successive element. This is usually irrelevant, but there is the potential for unexpected behavior when used with the ArraySlice type. Take the following code:

let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5

let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4

var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
    test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds

It's a somewhat contrived example, and it's not a common issue in practice but still I think it's worth knowing this can happen.

SQL keys, MUL vs PRI vs UNI

Walkthough on what is MUL, PRI and UNI in MySQL?

From the MySQL 5.7 documentation:

  • If Key is PRI, the column is a PRIMARY KEY or is one of the columns in a multiple-column PRIMARY KEY.
  • If Key is UNI, the column is the first column of a UNIQUE index. (A UNIQUE index permits multiple NULL values, but you can tell whether the column permits NULL by checking the Null field.)
  • If Key is MUL, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.

Live Examples

Control group, this example has neither PRI, MUL, nor UNI:

mysql> create table penguins (foo INT);
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with one column and an index on the one column has a MUL:

mysql> create table penguins (foo INT, index(foo));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with a column that is a primary key has PRI

mysql> create table penguins (foo INT primary key);
Query OK, 0 rows affected (0.02 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with a column that is a unique key has UNI:

mysql> create table penguins (foo INT unique);
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | UNI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with an index covering foo and bar has MUL only on foo:

mysql> create table penguins (foo INT, bar INT, index(foo, bar));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

A table with two separate indexes on two columns has MUL for each one

mysql> create table penguins (foo INT, bar int, index(foo), index(bar));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

A table with an Index spanning three columns has MUL on the first:

mysql> create table penguins (foo INT, 
       bar INT, 
       baz INT, 
       INDEX name (foo, bar, baz));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  |     | NULL    |       |
| baz   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

A table with a foreign key that references another table's primary key is MUL

mysql> create table penguins(id int primary key);
Query OK, 0 rows affected (0.01 sec)

mysql> create table skipper(id int, foreign key(id) references penguins(id));
Query OK, 0 rows affected (0.01 sec)

mysql> desc skipper;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

Stick that in your neocortex and set the dial to "frappe".

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How do I subscribe to all topics of a MQTT broker

Subscribing to # gives you a subscription to everything except for topics that start with a $ (these are normally control topics anyway).

It is better to know what you are subscribing to first though, of course, and note that some broker configurations may disallow subscribing to # explicitly.

In Python, how do I split a string and keep the separators?

If one wants to split string while keeping separators by regex without capturing group:

def finditer_with_separators(regex, s):
    matches = []
    prev_end = 0
    for match in regex.finditer(s):
        match_start = match.start()
        if (prev_end != 0 or match_start > 0) and match_start != prev_end:
            matches.append(s[prev_end:match.start()])
        matches.append(match.group())
        prev_end = match.end()
    if prev_end < len(s):
        matches.append(s[prev_end:])
    return matches

regex = re.compile(r"[\(\)]")
matches = finditer_with_separators(regex, s)

If one assumes that regex is wrapped up into capturing group:

def split_with_separators(regex, s):
    matches = list(filter(None, regex.split(s)))
    return matches

regex = re.compile(r"([\(\)])")
matches = split_with_separators(regex, s)

Both ways also will remove empty groups which are useless and annoying in most of the cases.

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

The same error here. I fixed this, using "module": "ES6" in tsconfig.

move_uploaded_file gives "failed to open stream: Permission denied" error

Try this:

  1. open /etc/apache2/envvars

    sudo gedit /etc/apache2/envvars
    
  2. replace www-data with your your_username

    "export APACHE_RUN_USER=www-data" 
    

    replace with

    export APACHE_RUN_USER='your_username' 
    

How to change a DIV padding without affecting the width/height ?

try this trick

div{
 -webkit-box-sizing: border-box; 
 -moz-box-sizing: border-box;    
 box-sizing: border-box;      
}

this will force the browser to calculate the width acording to the "outer"-width of the div, it means the padding will be substracted from the width.

makefiles - compile all c files at once

You need to take out your suffix rule (%.o: %.c) in favour of a big-bang rule. Something like this:

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

OBJ = 64bitmath.o    \
      monotone.o     \
      node_sort.o    \
      planesweep.o   \
      triangulate.o  \
      prim_combine.o \
      welding.o      \
      test.o         \
      main.o

SRCS = $(OBJ:%.o=%.c)

test: $(SRCS)
    gcc -o $@  $(CFLAGS) $(LIBS) $(SRCS)

If you're going to experiment with GCC's whole-program optimization, make sure that you add the appropriate flag to CFLAGS, above.

On reading through the docs for those flags, I see notes about link-time optimization as well; you should investigate those too.

jQuery count child elements

You can use .length with just a descendant selector, like this:

var count = $("#selected li").length;

If you have to use .children(), then it's like this:

var count = $("#selected ul").children().length;

You can test both versions here.

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

Maven Java EE Configuration Marker with Java Server Faces 1.2

The below steps should be the simple fix to your problem

  1. Project->Properties->ProjectFacet-->Uncheck jsf apply and OK.
  2. Project->Maven->UpdateProject-->This will solve the issue.

Here while on Updating Project Maven will automatically chooses the Dynamic web module

Bootstrap modal not displaying

I had my modal < div > inside my < li >.... not good.

Outside works fine :-)

<div class="modal fade" id="confirm-logout" tabindex="-1" role="dialog" aria-labelledby="logoutLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">....</h4>
            </div>

            <div class="modal-body">
                <p>....</p>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger btn-ok">OK</a>
            </div>
        </div>
    </div>
</div>
<li>
    .....
</li>

Install sbt on ubuntu

My guess is that the directory ~/bin/sbt/bin is not in your PATH.

To execute programs or scripts that are in the current directory you need to prefix the command with ./, as in:

./sbt

This is a security feature in linux, so to prevent overriding of system commands (and other programs) by a malicious party dropping a file in your home directory (for example). Imagine a script called 'ls' that emails your /etc/passwd file to 3rd party before executing the ls command... Or one that executes 'rm -rf .'...

That said, unless you need something specific from the latest source code, you're best off doing what paradigmatic said in his post, and install it from the Typesafe repository.

Could not find a part of the path ... bin\roslyn\csc.exe

Upgrading Microsoft.CodeDom.Providers.DotNetCompilerPlatform from 1.0.0 to 1.0.1 fixed this for me.

Save Dataframe to csv directly to s3 Python

This is a more up to date answer:

import s3fs

s3 = s3fs.S3FileSystem(anon=False)

# Use 'w' for py3, 'wb' for py2
with s3.open('<bucket-name>/<filename>.csv','w') as f:
    df.to_csv(f)

The problem with StringIO is that it will eat away at your memory. With this method, you are streaming the file to s3, rather than converting it to string, then writing it into s3. Holding the pandas dataframe and its string copy in memory seems very inefficient.

If you are working in an ec2 instant, you can give it an IAM role to enable writing it to s3, thus you dont need to pass in credentials directly. However, you can also connect to a bucket by passing credentials to the S3FileSystem() function. See documention:https://s3fs.readthedocs.io/en/latest/

Change Select List Option background colour on hover

The problem is that even JavaScript does not see the option element being hovered. This is just to put emphasis on how it's not going to be solved (any time soon at least) by using just CSS:

window.onmouseover = function(e)
{
 console.log(e.target.nodeName);
}

The only way to resolve this issue (besides waiting a millennia for browser vendors to fix bugs, let alone one that afflicts what you're trying to do) is to replace the drop-down menu with your own HTML/XML using JavaScript. This would likely involve the use of replacing the select element with a ul element and the use of a radio input element per li element.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

I had a similar issue when using AD on CAS , i.e. 52e error, In my case application accepts the Full Name when in the form of CN= instead of the actual username.

For example, if you had a user who's full name is Ross Butler and their login username is rbutler --you would normally put something like, cn=rbutler,ou=Users,dc=domain,dc=com but ours failed everytime. By changing this to cn=Ross Butler,ou=Users,dc=domain,dc=com it passed!!

What does the ??!??! operator do in C?

As already stated ??!??! is essentially two trigraphs (??! and ??! again) mushed together that get replaced-translated to ||, i.e the logical OR, by the preprocessor.

The following table containing every trigraph should help disambiguate alternate trigraph combinations:

Trigraph   Replaces

??(        [
??)        ]
??<        {
??>        }
??/        \
??'        ^
??=        #
??!        |
??-        ~

Source: C: A Reference Manual 5th Edition

So a trigraph that looks like ??(??) will eventually map to [], ??(??)??(??) will get replaced by [][] and so on, you get the idea.

Since trigraphs are substituted during preprocessing you could use cpp to get a view of the output yourself, using a silly trigr.c program:

void main(){ const char *s = "??!??!"; } 

and processing it with:

cpp -trigraphs trigr.c 

You'll get a console output of

void main(){ const char *s = "||"; }

As you can notice, the option -trigraphs must be specified or else cpp will issue a warning; this indicates how trigraphs are a thing of the past and of no modern value other than confusing people who might bump into them.


As for the rationale behind the introduction of trigraphs, it is better understood when looking at the history section of ISO/IEC 646:

ISO/IEC 646 and its predecessor ASCII (ANSI X3.4) largely endorsed existing practice regarding character encodings in the telecommunications industry.

As ASCII did not provide a number of characters needed for languages other than English, a number of national variants were made that substituted some less-used characters with needed ones.

(emphasis mine)

So, in essence, some needed characters (those for which a trigraph exists) were replaced in certain national variants. This leads to the alternate representation using trigraphs comprised of characters that other variants still had around.

Is the ternary operator faster than an "if" condition in Java

It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.

In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.

Batch file script to zip files

This is link by Tomas has a well written script to zip contents of a folder.

To make it work just copy the script into a batch file and execute it by specifying the folder to be zipped(source).

No need to mention destination directory as it is defaulted in the script to Desktop ("%USERPROFILE%\Desktop")

Copying the script here, just incase the web-link is down:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET sourceDirPath=%1
IF [%2] EQU [] (
  SET destinationDirPath="%USERPROFILE%\Desktop"
) ELSE (
  SET destinationDirPath="%2"
)
IF [%3] EQU [] (
  SET destinationFileName="%~n1%.zip"
) ELSE (
  SET destinationFileName="%3"
)
SET tempFilePath=%TEMP%\FilesToZip.txt
TYPE NUL > %tempFilePath%

FOR /F "DELIMS=*" %%i IN ('DIR /B /S /A-D "%sourceDirPath%"') DO (
  SET filePath=%%i
  SET dirPath=%%~dpi
  SET dirPath=!dirPath:~0,-1!
  SET dirPath=!dirPath:%sourceDirPath%=!
  SET dirPath=!dirPath:%sourceDirPath%=!
  ECHO .SET DestinationDir=!dirPath! >> %tempFilePath%
  ECHO "!filePath!" >> %tempFilePath%
)

MAKECAB /D MaxDiskSize=0 /D CompressionType=MSZIP /D Cabinet=ON /D Compress=ON /D UniqueFiles=OFF /D DiskDirectoryTemplate=%destinationDirPath% /D CabinetNameTemplate=%destinationFileName%  /F %tempFilePath% > NUL 2>&1

DEL setup.inf > NUL 2>&1
DEL setup.rpt > NUL 2>&1
DEL %tempFilePath% > NUL 2>&1

syntax error, unexpected T_VARIABLE

If that is the entire line, it very well might be because you are missing a ; at the end of the line.

How to get the currently logged in user's user id in Django?

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>

Are there benefits of passing by pointer over passing by reference in C++?

Clarifications to the preceding posts:


References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)

While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)

bool test( int & a)
{
  return (&a) == (int *) NULL;
}

int
main()
{
  int * i = (int *)NULL;
  cout << ( test(*i) ) << endl;
};

The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().

Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)

Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...


More practically:

  • References hide that you are changing data stored someplace else.
  • It's easy to confuse a Reference with a Copied object.
  • Pointers make it obvious!

Link to all Visual Studio $ variables

To add to the other answers, note that property sheets can be configured for the project, creating custom project-specific parameters.

To access or create them navigate to(at least in Visual Studio 2013) View -> Other Windows -> Property Manager. You can also find them in the source folder as .prop files

Set Locale programmatically

simple and easy

Locale locale = new Locale("en", "US");
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = locale;
res.updateConfiguration(conf, dm);

where "en" is language code and "US" is country code.

Determine installed PowerShell version

Microsoft's recommended forward compatible method for checking if PowerShell is installed and determining the installed version is to look at two specific registry keys. I've reproduced the details here in case the link breaks.

According to the linked page:

Depending on any other registry key(s), or version of PowerShell.exe or the location of PowerShell.exe is not guaranteed to work in the long term.

To check if any version of PowerShell is installed, check for the following value in the registry:

  • Key Location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1
  • Value Name: Install
  • Value Type: REG_DWORD
  • Value Data: 0x00000001 (1

To check whether version 1.0 or 2.0 of PowerShell is installed, check for the following value in the registry:

  • Key Location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine
  • Value Name: PowerShellVersion
  • Value Type: REG_SZ
  • Value Data: <1.0 | 2.0>

Avoiding "resource is out of sync with the filesystem"

A little hint. The message often appears during rename operation. The quick workaround for me is pressing Ctrl-Y (redo shortcut) after message confirmation. It works only if the renaming affects a single file.

Adding a tooltip to an input box

If you are using bootstrap (I am using version 4.0), feel free to try the following code.

<input data-toggle="tooltip" data-placement="top" title="This is the text of the tooltip" value="44"/>

data-placement can be top, right, bottom or left

Find elements inside forms and iframe using Java and Selenium WebDriver

By using https://github.com/nick318/FindElementInFrames You can find webElement across all frames:

SearchByFramesFactory searchFactory = new SearchByFramesFactory(driver);
SearchByFrames searchInFrame = searchFactory.search(() -> driver.findElement(By.tagName("body")));
Optional<WebElement> elem = searchInFrame.getElem();

Removing all unused references from a project in Visual Studio projects

You can try the free VS2010 extension: Reference Assistant by Lardite group. It works perfectly for me. This tool helps to find unused references and allows you to choose which references should be removed.

How can I inspect element in an Android browser?

You can inspect elements of a website in your Android device using Chrome browser.

Open your Chrome browser and go to the website you want to inspect.

Go to the address bar and type "view-source:" before the "HTTP" and reload the page.

The whole elements of the page will be shown.

How to secure phpMyAdmin

Most likely, somewhere on your webserver will be an Alias directive like this;

Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"

In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.

Just change the alias directive and you should be good to go.

How to change default JRE for all Eclipse workspaces?

Open the Java > Installed JREs preference page. Check the box on the line for the JRE that you want to assign as the default JRE in your workbench. If the JRE you want to assign as the default does not appear in the list, you must add it. Click OK.

Source-http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-assign_default_jre.htm

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

How to add an empty column to a dataframe?

The reason I was looking for such a solution is simply to add spaces between multiple DFs which have been joined column-wise using the pd.concat function and then written to excel using xlsxwriter.

df[' ']=df.apply(lambda _: '', axis=1)
df_2 = pd.concat([df,df1],axis=1)                #worked but only once. 
# Note: df & df1 have the same rows which is my index. 
#
df_2[' ']=df_2.apply(lambda _: '', axis=1)       #didn't work this time !!?     
df_4 = pd.concat([df_2,df_3],axis=1)

I then replaced the second lambda call with

df_2['']=''                                 #which appears to add a blank column
df_4 = pd.concat([df_2,df_3],axis=1)

The output I tested it on was using xlsxwriter to excel. Jupyter blank columns look the same as in excel although doesnt have xlsx formatting. Not sure why the second Lambda call didnt work.

Opposite of %in%: exclude rows with values specified in a vector

Using negate from purrr also does the trick quickly and neatly:

`%not_in%` <- purrr::negate(`%in%`)

Then usage is, for example,

c("cat", "dog") %not_in% c("dog", "mouse")

How long will my session last?

In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called!). But PHP’s session handling is a little bit more complicated.

Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.

Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.

Detect if a jQuery UI dialog box is open

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

Retrieve list of tasks in a queue in Celery

I've come to the conclusion the best way to get the number of jobs on a queue is to use rabbitmqctl as has been suggested several times here. To allow any chosen user to run the command with sudo I followed the instructions here (I did skip editing the profile part as I don't mind typing in sudo before the command.)

I also grabbed jamesc's grep and cut snippet and wrapped it up in subprocess calls.

from subprocess import Popen, PIPE
p1 = Popen(["sudo", "rabbitmqctl", "list_queues", "-p", "[name of your virtula host"], stdout=PIPE)
p2 = Popen(["grep", "-e", "^celery\s"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["cut", "-f2"], stdin=p2.stdout, stdout=PIPE)
p1.stdout.close()
p2.stdout.close()
print("number of jobs on queue: %i" % int(p3.communicate()[0]))

How to count the number of rows in excel with data?

Safest option is

Lastrow =  Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
Lastcol =  Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column

Don't use UsedRange or SpecialCells(xlLastCell) or End(xlUp). All these methods may give wrong results if you previously deleted some rows. Excel still counts these invisible cells.

These methods will work again if you delete your cells, save the workbook, close and re-open it.

How to escape double quotes in JSON

It's showing the backslash because you're also escaping the backslash.

Aside from double quotes, you must also escape backslashes if you want to include one in your JSON quoted string. However if you intend to use a backslash in an escape sequence, obviously you shouldn't escape it.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

How do I get my page title to have an icon?

Apparently you can use this trick.

<title> My title</title>

That icon-alike is actually a text.

Write a formula in an Excel Cell using VBA

You can try using FormulaLocal property instead of Formula. Then the semicolon should work.

How to Create a circular progressbar in Android which rotates on it?

package com.example.ankitrajpoot.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;


public class MainActivity extends Activity {

    private ProgressBar spinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner=(ProgressBar)findViewById(R.id.progressBar);
        spinner.setVisibility(View.VISIBLE);
    }
}

xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<ProgressBar
    android:id="@+id/progressBar"

    android:layout_width="48dp"
    style="?android:attr/progressBarStyleLarge"
    android:layout_height="48dp"
    android:indeterminateDrawable="@drawable/circular_progress_bar"
    android:indeterminate="true" />
</RelativeLayout>





<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%"
    android:pivotY="50%"
    android:fromDegrees="0"
    android:toDegrees="1080">
    <shape
        android:shape="ring"
        android:innerRadiusRatio="3"
        android:thicknessRatio="8"
        android:useLevel="false">

        <size
            android:width="56dip"
            android:height="56dip" />

        <gradient
            android:type="sweep"
            android:useLevel="false"
            android:startColor="@android:color/transparent"
            android:endColor="#1e9dff"
            android:angle="0"
            />

    </shape>
</rotate>

SQL Server : Columns to Rows

You can use the UNPIVOT function to convert the columns into rows:

select id, entityId,
  indicatorname,
  indicatorvalue
from yourtable
unpivot
(
  indicatorvalue
  for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;

Note, the datatypes of the columns you are unpivoting must be the same so you might have to convert the datatypes prior to applying the unpivot.

You could also use CROSS APPLY with UNION ALL to convert the columns:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  select 'Indicator1', Indicator1 union all
  select 'Indicator2', Indicator2 union all
  select 'Indicator3', Indicator3 union all
  select 'Indicator4', Indicator4 
) c (indicatorname, indicatorvalue);

Depending on your version of SQL Server you could even use CROSS APPLY with the VALUES clause:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  values
  ('Indicator1', Indicator1),
  ('Indicator2', Indicator2),
  ('Indicator3', Indicator3),
  ('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);

Finally, if you have 150 columns to unpivot and you don't want to hard-code the entire query, then you could generate the sql statement using dynamic SQL:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot 
  = stuff((select ','+quotename(C.column_name)
           from information_schema.columns as C
           where C.table_name = 'yourtable' and
                 C.column_name like 'Indicator%'
           for xml path('')), 1, 1, '')

set @query 
  = 'select id, entityId,
        indicatorname,
        indicatorvalue
     from yourtable
     unpivot
     (
        indicatorvalue
        for indicatorname in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

How to add font-awesome to Angular 2 + CLI project

Now there is few ways to install fontAwesome on Angular CLI:

ng add @fortawesome/angular-fontawesome

OR using yarn

yarn add @fortawesome/fontawesome-svg-core
yarn add @fortawesome/free-solid-svg-icons
yarn add @fortawesome/angular-fontawesome

OR Using NPM

npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/angular-fontawesome

Reference here: https://github.com/FortAwesome/angular-fontawesome

how to dynamically add options to an existing select in vanilla javascript

The simplest way is:

selectElement.add(new Option('Text', 'value'));

Yes, that simple. And it works even in IE8. And has other optional parameters.

See docs:

Change color of PNG image via CSS?

When changing a picture from black to white, or white to black the hue rotate filter does not work, because black and white are not technically colors. Instead, black and white color changes (from black to white or vice-versa) must be done with the invert filter property.

.img1 { filter: invert(100%); }

how to change any data type into a string in python

str(object) will do the trick.

If you want to alter the way object is stringified, define __str__(self) method for object's class. Such method has to return str or unicode object.

Angular: Cannot find a differ supporting object '[object Object]'

If this is an Observable being return in the HTML simply add the async pipe

    observable | async

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

How can I change the current URL?

If you just want to update the relative path you can also do

window.location.pathname = '/relative-link'

"http://domain.com" -> "http://domain.com/relative-link"

How to put the legend out of the plot

It's worth refreshing this question, as newer versions of Matplotlib have made it much easier to position the legend outside the plot. I produced this example with Matplotlib version 3.1.1.

Users can pass a 2-tuple of coordinates to the loc parameter to position the legend anywhere in the bounding box. The only gotcha is you need to run plt.tight_layout() to get matplotlib to recompute the plot dimensions so the legend is visible:

import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1], label="Label 1")
plt.plot([0, 1], [0, 2], label='Label 2')

plt.legend(loc=(1.05, 0.5))
plt.tight_layout()

This leads to the following plot:

plot with legend outside

References:

What is the difference between json.dump() and json.dumps() in python?

There isn't much else to add other than what the docs say. If you want to dump the JSON into a file/socket or whatever, then you should go with dump(). If you only need it as a string (for printing, parsing or whatever) then use dumps() (dump string)

As mentioned by Antti Haapala in this answer, there are some minor differences on the ensure_ascii behaviour. This is mostly due to how the underlying write() function works, being that it operates on chunks rather than the whole string. Check his answer for more details on that.

json.dump()

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object

If ensure_ascii is False, some chunks written to fp may be unicode instances

json.dumps()

Serialize obj to a JSON formatted str

If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance

Android Fastboot devices not returning device

TLDR - In addition to the previous responses. There might be a problem with the version of the fastboot command. Try to download the newest one via Android SDK Manager instead of default one available in the OS repository.

There is one more thing you can do to fix this issue. I had the similar problem when trying to flash Nexus Player. All the adb commands we working fine while in normal boot mode. However, after switching to fastboot mode I wasn't able to execute fastboot commands. My device was not visible in the output of the fastboot devices command. I've set the right rules in /etc/udev/rules.d/11-android.rules file. The lsusb command showed that the device has been pluged in.

The soultion was quite simple. I've downloaded the the fastboot via Android Studio's SDK Manager instead of using the default one available in Ubuntu packages.

All you need is sdkmanager. Download the Android SDK Platform Tools and replace the default /usr/bin/fastboot with the new one.

Swipe ListView item From right to left show delete button

I have gone through tons of third party libraries to try to achieve this. But none of them exhibits smoothness and usability experience which i wanted. Then i decided to write it myself. And the result was , well, i loved it. I will share the code here. Maybe i will write it as a library which can be embedded in any recycler view in future. But for now here is the code.

Note: i have uses recycler view and ViewHolder. Some values are hardcoded so change them according to your requirement.

  • row_layout.xml

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:orientation="horizontal">
        <Button
            android:id="@+id/slide_button_2"
            android:text="Button2"
            android:layout_width="80dp"
            android:layout_height="80dp" />
        <Button
            android:id="@+id/slide_button_1"
            android:text="Button1"
            android:layout_width="80dp"
            android:layout_height="80dp" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/chat_row_cell"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:orientation="horizontal"
        android:background="@color/white">
        <ImageView
            android:id="@+id/chat_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_gravity="center"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <TextView
                    android:id="@+id/chat_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/md_grey_800"
                    android:textSize="18sp"/>
                <TextView
                    android:id="@+id/chat_subtitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/md_grey_600"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    

  • ChatAdaptor.java

    public class ChatAdaptor extends RecyclerView.Adapter {

    List<MXGroupChatSession> sessions;
    Context context;
    ChatAdaptorInterface listener;
    
    public interface ChatAdaptorInterface{
        void cellClicked(MXGroupChatSession session);
        void utilityButton1Clicked(MXGroupChatSession session);
        void utilityButton2Clicked(MXGroupChatSession session);
    }
    
    public ChatAdaptor(List<MXGroupChatSession> sessions, ChatAdaptorInterface listener, Context context){
        this.sessions=sessions;
        this.context=context;
        this.listener=listener;
    }
    
    @Override
    public ChatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=(View)LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_row,null);
        ChatViewHolder chatViewHolder=new ChatViewHolder(view);
        return chatViewHolder;
    }
    
    @Override
    public void onBindViewHolder(ChatViewHolder holder, final int position) {
        MXGroupChatSession session=this.sessions.get(position);
        holder.selectedSession=session;
        holder.titleView.setText(session.getTopic());
        holder.subtitleView.setText(session.getLastFeedContent());
        Picasso.with(context).load(new File(session.getCoverImagePath())).transform(new CircleTransformPicasso()).into(holder.imageView);
    }
    
    @Override
    public int getItemCount() {
        return sessions.size();
    }
    
    public class ChatViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView titleView;
        TextView subtitleView;
        ViewGroup cell;
        ViewGroup cellContainer;
        Button button1;
        Button button2;
    
        MXGroupChatSession selectedSession;
        private GestureDetectorCompat gestureDetector;
    
        float totalx;
        float buttonTotalWidth;
    
        Boolean open=false;
        Boolean isScrolling=false;
    
    
        public ChatViewHolder(View itemView) {
            super(itemView);
            cell=(ViewGroup) itemView.findViewById(R.id.chat_row_cell);
            cellContainer=(ViewGroup) itemView.findViewById(R.id.chat_row_container);
            button1=(Button) itemView.findViewById(R.id.slide_button_1);
            button2=(Button) itemView.findViewById(R.id.slide_button_2);
    
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.utilityButton1Clicked(selectedSession);
                }
            });
    
            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.utilityButton2Clicked(selectedSession);
                }
            });
    
            ViewTreeObserver vto = cellContainer.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    buttonTotalWidth = button1.getWidth()+button2.getWidth();
                }
            });
    
            this.titleView=(TextView)itemView.findViewById(R.id.chat_title);
            subtitleView=(TextView)itemView.findViewById(R.id.chat_subtitle);
            imageView=(ImageView)itemView.findViewById(R.id.chat_image);
            gestureDetector=new GestureDetectorCompat(context,new ChatRowGesture());
    
            cell.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(gestureDetector.onTouchEvent(event)){
                        return true;
                    }
    
                    if(event.getAction() == MotionEvent.ACTION_UP) {
                        if(isScrolling ) {
                            isScrolling  = false;
                            handleScrollFinished();
                        };
                    }
                    else if(event.getAction() == MotionEvent.ACTION_CANCEL){
                        if(isScrolling ) {
                            isScrolling  = false;
                            handleScrollFinished();
                        };
                    }
                    return false;
                }
            });
        }
    
    
        public class ChatRowGesture extends GestureDetector.SimpleOnGestureListener {
    
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (!open){
                    listener.cellClicked(selectedSession);
                }
                return true;
            }
    
            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
    
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    isScrolling=true;
                    totalx=totalx+distanceX;
                    freescroll(totalx);
    
                return true;
            }
        }
    
        void handleScrollFinished(){
            if (open){
                if (totalx>2*buttonTotalWidth/3){
                    slideLeft();
                    totalx=buttonTotalWidth;
                }else{
                    slideRight();
                    totalx=0;
                }
            }else{
                if (totalx>buttonTotalWidth/3){
                    slideLeft();
                    totalx=buttonTotalWidth;
                }else{
                    slideRight();
                    totalx=0;
                }
            }
    
        }
    
        void slideRight(){
            TransitionManager.beginDelayedTransition(cellContainer);
            ViewGroup.MarginLayoutParams params;
            params=(ViewGroup.MarginLayoutParams) cell.getLayoutParams();
            params.setMargins(0,0,0,0);
            cell.setLayoutParams(params);
            open=false;
        }
    
        void slideLeft(){
            TransitionManager.beginDelayedTransition(cellContainer);
            ViewGroup.MarginLayoutParams params;
            params=(ViewGroup.MarginLayoutParams) cell.getLayoutParams();
            params.setMargins(((int)buttonTotalWidth*-1),0,(int)buttonTotalWidth,0);
            cell.setLayoutParams(params);
            open=true;
        }
        void freescroll(float x){
            if (x<buttonTotalWidth && x>0){
                int xint=(int)x;
                ViewGroup.MarginLayoutParams params;
                params=(ViewGroup.MarginLayoutParams) cell.getLayoutParams();
                params.setMargins(params.leftMargin,0,xint,0);
                cell.setLayoutParams(params);
            }
        }
    }
    

Hope this helps someone!!

javax.net.ssl.SSLException: Received fatal alert: protocol_version

Not sure if you found an answer but I had this problem and needed to upgrade TLS version to 1.2

private HttpsURLConnection getSSlConnection(String url, String username, String password){
    SSLContext sc = SSLContext.getInstance("TLSv1.2")
    // Create a trust manager that accepts all SSL sites
    TrustManager[] trustAllCerts = new TrustManager[1]
    def tm = new X509TrustManager(){
        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0]
        }
    }
    trustAllCerts[0] = tm

    sc.init(null, trustAllCerts, new SecureRandom())
    HttpsURLConnection connection = (HttpsURLConnection) getConnection(url, username, password)
    connection.setSSLSocketFactory(sc.getSocketFactory())
    return connection
}

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How to convert dd/mm/yyyy string into JavaScript Date object?

You can use toLocaleString(). This is a javascript method.

_x000D_
_x000D_
var event = new Date("01/02/1993");_x000D_
_x000D_
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };_x000D_
_x000D_
console.log(event.toLocaleString('en', options));_x000D_
_x000D_
// expected output: "Saturday, January 2, 1993"
_x000D_
_x000D_
_x000D_

Almost all formats supported. Have look on this link for more details.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Vector erase iterator

if(allPlayers.empty() == false) {
    for(int i = allPlayers.size() - 1; i >= 0; i--)
    {
        if(allPlayers.at(i).getpMoney() <= 0) 
            allPlayers.erase(allPlayers.at(i));
    }
}

This works for me. And Don't need to think about indexes have already erased.

jQuery event for images loaded

As per this answer, you can use the jQuery load event on the window object instead of the document:

jQuery(window).load(function() {
    console.log("page finished loading now.");
});

This will be triggered after all content on the page has been loaded. This differs from jQuery(document).load(...) which is triggered after the DOM has finished loading.

Parenthesis/Brackets Matching using Stack algorithm

import java.util.*;

class StackDemo {

    public static void main(String[] argh) {
        boolean flag = true;
        String str = "(()){}()";
        int l = str.length();
        flag = true;
        Stack<String> st = new Stack<String>();
        for (int i = 0; i < l; i++) {
            String test = str.substring(i, i + 1);
            if (test.equals("(")) {
                st.push(test);
            } else if (test.equals("{")) {
                st.push(test);
            } else if (test.equals("[")) {
                st.push(test);
            } else if (test.equals(")")) {
                if (st.empty()) {
                    flag = false;
                    break;
                }
                if (st.peek().equals("(")) {
                    st.pop();
                } else {
                    flag = false;
                    break;
                }
            } else if (test.equals("}")) {
                if (st.empty()) {
                    flag = false;
                    break;
                }
                if (st.peek().equals("{")) {
                    st.pop();
                } else {
                    flag = false;
                    break;
                }
            } else if (test.equals("]")) {
                if (st.empty()) {
                    flag = false;
                    break;
                }
                if (st.peek().equals("[")) {
                    st.pop();
                } else {
                    flag = false;
                    break;
                }
            }
        }
        if (flag && st.empty())
            System.out.println("true");
        else
            System.out.println("false");
    }
}

Revert to a commit by a SHA hash in Git?

If you want to commit on top of the current HEAD with the exact state at a different commit, undoing all the intermediate commits, then you can use reset to create the correct state of the index to make the commit.

# Reset the index and working tree to the desired tree
# Ensure you have no uncommitted changes that you want to keep
git reset --hard 56e05fced

# Move the branch pointer back to the previous HEAD
git reset --soft HEAD@{1}

git commit -m "Revert to 56e05fced"

Loop and get key/value pair for JSON array using jQuery

You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

Live demo.

AngularJS. How to call controller function from outside of controller component

I use to work with $http, when a want to get some information from a resource I do the following:

angular.module('services.value', [])

.service('Value', function($http, $q) {

var URL = "http://localhost:8080/myWeb/rest/";

var valid = false;

return {
    isValid: valid,
    getIsValid: function(callback){
        return $http.get(URL + email+'/'+password, {cache: false})
                    .success(function(data){
            if(data === 'true'){ valid = true; }
        }).then(callback);
    }}
    });

And the code in the controller:

angular.module('controllers.value', ['services.value'])

.controller('ValueController', function($scope, Value) {
    $scope.obtainValue = function(){
        Value.getIsValid(function(){$scope.printValue();});
    }

    $scope.printValue = function(){
        console.log("Do it, and value is " Value.isValid);
    }
}

I send to the service what function have to call in the controller

How to amend older Git commit?

git rebase -i HEAD^^^

Now mark the ones you want to amend with edit or e (replace pick). Now save and exit.

Now make your changes, then

git add .
git rebase --continue

If you want to add an extra delete remove the options from the commit command. If you want to adjust the message, omit just the --no-edit option.

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

Uncaught Typeerror: cannot read property 'innerHTML' of null

While you should ideally highlight the code which is causing an error and post that within your question, the error is because you are trying to get the inner HTML of the 'status' element:

var idPost=document.getElementById("status").innerHTML;

However the 'status' element does not exist within your HTML - either add the necessary element or change the ID you are trying to locate to point to a valid element.

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Android set bitmap to Imageview

There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.

Examples:

  1. Load URL into ImageView without generating a bitmap:

    Picasso.with(context) // Context
           .load("http://abc.imgur.com/gxsg.png") // URL or file
           .into(imageView); // An ImageView object to show the loaded image
    
  2. Load URL into ImageView by generating a bitmap:

    Picasso.with(this)
           .load(artistImageUrl)
           .into(new Target() {
               @Override
               public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                   /* Save the bitmap or do something with it here */
    
                   // Set it in the ImageView
                   theView.setImageBitmap(bitmap)
               }
    
               @Override
               public void onBitmapFailed(Drawable errorDrawable) {
    
               }
    
               @Override
               public void onPrepareLoad(Drawable placeHolderDrawable) {
    
               }
           });
    

There are many more options available in Picasso. Here is the documentation.

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

Locate config.inc.php file under C:\xampp\phpMyAdmin and open it in any editor. Find the following line:

$cfg['Servers'][$i]['password'] = '  ';

Enter the chosen password inside the quotes. Also, in order to make localhost/phpmyadmin ask for a username and password, find the following line:

$cfg['Servers'][$i]['auth_type'] = 'config';

Change the above line to:

$cfg['Servers'][$i]['auth_type'] = 'cookie';

How to get current value of RxJS Subject or Observable?

A subscription can be created and after taking the first emitted item destroyed. Pipe is a function that uses an Observable as its input and returns another Observable as output, while not modifying the first observable. Angular 8.1.0. Packages: "rxjs": "6.5.3", "rxjs-observable": "0.0.7"

  ngOnInit() {

    ...

    // If loading with previously saved value
    if (this.controlValue) {

      // Take says once you have 1, then close the subscription
      this.selectList.pipe(take(1)).subscribe(x => {
        let opt = x.find(y => y.value === this.controlValue);
        this.updateValue(opt);
      });

    }
  }

MySQL error 1449: The user specified as a definer does not exist

The problem is clear - MySQL cannot find user specified as the definer.

I encountered this problem after synchronizing database model from development server, applying it to localhost, making changes to the model and then reapplying it to localhost. Apparently there was a view (I modified) defined and so I couldn't update my local version.

How to fix (easily):

Note: it involves deleting so it works just fine for views but make sure you have data backed-up if you try this on tables.

  1. Login to database as root (or whatever has enough power to make changes).
  2. Delete view, table or whatever you are having trouble with.
  3. Synchronize your new model - it will not complain about something that does not exist now. You may want to remove SQL SECURITY DEFINER part from the item definition you had problems with.

P.S. This is neither a proper nor best-all-around fix. I just posted it as a possible (and very simple) solution.

What's the difference between “mod” and “remainder”?

In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.

 7 modulo  3 -->  1  
 7 modulo -3 --> -2 
-7 modulo  3 -->  2  
-7 modulo -3 --> -1 

Remove useless zero digits from decimals in PHP

$str = 15.00;
$str2 = 14.70;
echo rtrim(rtrim(strval($str), "0"), "."); //15
echo rtrim(rtrim(strval($str2), "0"), "."); //14.7

How can I reorder a list?

You can provide your own sort function to list.sort():

The sort() method takes optional arguments for controlling the comparisons.

  • cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

  • key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.

  • reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

C# - Winforms - Global Variables

One way,

Solution Explorer > Your Project > Properties > Settings.Settings. Click on this file and add define your settings from the IDE.

Access them by

Properties.Settings.Default.MySetting = "hello world";

How to store(bitmap image) and retrieve image from sqlite database in android?

Setting Up the database

public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "database_name";

    // Table Names
    private static final String DB_TABLE = "table_image";

    // column names
    private static final String KEY_NAME = "image_name";
    private static final String KEY_IMAGE = "image_data";

    // Table create statement
    private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+ 
                       KEY_NAME + " TEXT," + 
                       KEY_IMAGE + " BLOB);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating table
        db.execSQL(CREATE_TABLE_IMAGE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);

        // create new table
        onCreate(db);
    }
}

Insert in the Database:

public void addEntry( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_NAME,    name);
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Retrieving data:

 byte[] image = cursor.getBlob(1);

Note:

  1. Before inserting into database, you need to convert your Bitmap image into byte array first then apply it using database query.
  2. When retrieving from database, you certainly have a byte array of image, what you need to do is to convert byte array back to original image. So, you have to make use of BitmapFactory to decode.

Below is an Utility class which I hope could help you:

public class DbBitmapUtility {

    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}


Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.

Count the number of all words in a string

You can remove double spaces and count the number of " " in the string to get the count of words. Use stringr and rm_white {qdapRegex}

str_count(rm_white(s), " ") +1

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

Submit two forms with one button

If you have a regular submit button, you could add an onclick event to it that does the follow:

document.getElementById('otherForm').submit();

How do I setup the InternetExplorerDriver so it works

public class NavigateUsingAllBrowsers {


public static void main(String[] args) {

WebDriver driverFF= new FirefoxDriver();
driverFF.navigate().to("http://www.firefox.com");


File file =new File("C:/Users/mkv/workspace/ServerDrivers/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driverIE=new InternetExplorerDriver();
driverIE.navigate().to("http://www.msn.com");

// Download Chrome Driver from http://code.google.com/p/chromedriver/downloads/list

file =new File("C:/Users/mkv/workspace/ServerDrivers/ChromeDriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driverChrome=new ChromeDriver();
driverChrome.navigate().to("http://www.chrome.com");

}

}

Using .NET, how can you find the mime type of a file based on the file signature not the extension

I use an hybrid solution:

    using System.Runtime.InteropServices;

    [DllImport (@"urlmon.dll", CharSet = CharSet.Auto)]
    private extern static System.UInt32 FindMimeFromData(
        System.UInt32 pBC, 
        [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
        [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
        System.UInt32 cbSize,
        [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
        System.UInt32 dwMimeFlags,
        out System.UInt32 ppwzMimeOut,
        System.UInt32 dwReserverd
    );

    private string GetMimeFromRegistry (string Filename)
    {
        string mime = "application/octetstream";
        string ext = System.IO.Path.GetExtension(Filename).ToLower();
        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (rk != null && rk.GetValue("Content Type") != null)
            mime = rk.GetValue("Content Type").ToString();
        return mime;
    }

    public string GetMimeTypeFromFileAndRegistry (string filename)
    {
        if (!File.Exists(filename))
        {
           return GetMimeFromRegistry (filename);
        }

        byte[] buffer = new byte[256];

        using (FileStream fs = new FileStream(filename, FileMode.Open))
        {
            if (fs.Length >= 256)
                fs.Read(buffer, 0, 256);
            else
                fs.Read(buffer, 0, (int)fs.Length);
        }

        try
        {            
            System.UInt32 mimetype;

            FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);

            System.IntPtr mimeTypePtr = new IntPtr(mimetype);

            string mime = Marshal.PtrToStringUni(mimeTypePtr);

            Marshal.FreeCoTaskMem(mimeTypePtr);

            if (string.IsNullOrWhiteSpace (mime) || 
                mime =="text/plain" || mime == "application/octet-stream")                    
            {
                return GetMimeFromRegistry (filename);
            }

            return mime;
        }
        catch (Exception e)
        {
            return GetMimeFromRegistry (filename);
        }
    }

How do I increase the capacity of the Eclipse output console?

For C++ users, to increase the Build console output size see here

ie Windows > Preference > C/C++ > Build > Console

Different ways of clearing lists

There is a very simple way to clear a python list. Use del list_name[:].

For example:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]
>>> print a, b
[] []